Skip to content

feat(core): Normalize tool-call terminal telemetry - #8176

Merged
doudouOUC merged 2 commits into
QwenLM:mainfrom
doudouOUC:codex/tool-call-terminal-telemetry
Jul 31, 2026
Merged

feat(core): Normalize tool-call terminal telemetry#8176
doudouOUC merged 2 commits into
QwenLM:mainfrom
doudouOUC:codex/tool-call-terminal-telemetry

Conversation

@doudouOUC

Copy link
Copy Markdown
Collaborator

What this PR does

This PR establishes one terminal contract for tool-call outcomes before they fan out to telemetry consumers. Core soft errors without a machine-readable classification now become unknown, while every emitted tool-call event derives the compatibility success field from its authoritative status, removes stale error fields from success and cancelled events, supplies unknown for unclassified errors, and replaces blank tool names with unknown_tool.

The normalized event is shared by UI telemetry, chat recording, QwenLogger, OpenTelemetry logs, and tool-call metrics. The tool-call counter gains the low-cardinality status dimension while retaining success and source compatibility for direct metric callers. QwenLogger gains status and tool_type without collecting tool arguments, results, stack traces, or MCP server names. The telemetry and usage-statistics documentation now describes the contract and its rollout boundary.

Why it's needed

Core and ACP currently produce tool-call terminal events through different paths, so status, success, error, and error_type can disagree or be absent. That causes logs, metrics, hooks, and session records to represent the same outcome differently and leaves unclassified failures in a missing bucket. A single normalization boundary makes downstream analysis deterministic while preserving existing public tool and metric APIs.

Reviewer Test Plan

How to verify

  • Run cd packages/core && npx vitest run src/core/coreToolScheduler.test.ts src/telemetry/loggers.test.ts src/telemetry/metrics.test.ts src/telemetry/qwen-logger/qwen-logger.test.ts; expect all four files and 471 tests to pass.
  • Confirm the scheduler soft-error case records error_type: "unknown" in the completed call, PostToolBatch payload, and chat recording without changing the visible error message.
  • Confirm success and cancelled events reach every telemetry consumer without stale error fields, while explicit error classifications remain unchanged and missing classifications become unknown.
  • Confirm the tool-call counter includes status but the latency histogram does not, and a legacy direct caller that omits status still records a derived value.
  • Run npm run build, npm run typecheck, and npm run lint; expect all commands to succeed.

Evidence (Before & After)

N/A — this is a non-UI telemetry contract change.

Tested on

OS Status
🍏 macOS ✅ tested
🪟 Windows ⚠️ not tested
🐧 Linux ⚠️ not tested

Environment (optional)

macOS 26.4.1, Node.js 24.12.0, npm 10.9.8, local unit-test environment without sandboxing.

Risk & Scope

  • Main risk or tradeoff: Existing unclassified Core failures move from a missing error_type bucket to unknown, success and cancelled telemetry no longer retains stale error fields, and the existing tool-call counter gains a new dimension.
  • Not validated / out of scope: Live QwenLogger and OTLP backend ingestion were not exercised. The global CLI dry-run was blocked before model execution by local Keychain error SecItemCopyMatching failed -50. ACP permission-cancellation status fixes, ACP raw tool_result normalization, PostToolUseFailure classification, primary tool-span classification, and legacy UI totalFail semantics remain follow-up work. The new status metric must not become the stability SLO source until producer-side status fixes land.
  • Breaking changes / migration notes: No public API break is intended. Existing direct metric callers may omit status; historical queries should coalesce missing error_type values to unknown. No data backfill is required.

Linked Issues

Closes #8175

中文说明

本 PR 做了什么

本 PR 在工具调用结果分发到各遥测消费者之前建立统一的终态契约。Core 中没有机器可读分类的软错误现在会归为 unknown;每个工具调用事件都以 status 为权威来源推导兼容字段 success,从成功和取消事件中移除残留错误字段,为未分类错误补充 unknown,并将空白工具名替换为 unknown_tool

归一化后的事件由 UI 遥测、会话记录、QwenLogger、OpenTelemetry 日志和工具调用指标共同使用。工具调用计数器新增低基数 status 维度,同时保留 success 并兼容直接调用指标 API 的旧调用方。QwenLogger 新增 statustool_type,但不采集工具参数、结果、堆栈或 MCP 服务名。遥测及用量统计文档同步说明了这套契约及其上线边界。

为什么需要

Core 与 ACP 当前通过不同路径产生工具调用终态事件,因此 statussuccesserrorerror_type 可能互相矛盾或缺失,导致日志、指标、Hook 与会话记录对同一结果给出不同表示,并让未分类失败落入缺失值桶。统一的归一化边界可以在保留现有公开工具与指标 API 的同时,让下游分析结果保持确定。

Reviewer 测试计划

验证方式

  • 运行 cd packages/core && npx vitest run src/core/coreToolScheduler.test.ts src/telemetry/loggers.test.ts src/telemetry/metrics.test.ts src/telemetry/qwen-logger/qwen-logger.test.ts;预期四个测试文件、471 项测试全部通过。
  • 确认调度器软错误场景在已完成调用、PostToolBatch 载荷和会话记录中都写入 error_type: "unknown",且用户可见错误信息不变。
  • 确认成功与取消事件到达每个遥测消费者时不再携带残留错误字段;显式错误分类保持不变,缺失分类则变为 unknown
  • 确认工具调用计数器包含 status,延迟直方图不包含该维度;省略 status 的旧直接调用方仍会记录推导后的值。
  • 运行 npm run buildnpm run typechecknpm run lint;预期所有命令成功。

前后对比证据

N/A——这是非 UI 的遥测契约变更。

测试平台

操作系统 状态
🍏 macOS ✅ 已测试
🪟 Windows ⚠️ 未测试
🐧 Linux ⚠️ 未测试

环境(可选)

macOS 26.4.1、Node.js 24.12.0、npm 10.9.8,本地无沙箱单元测试环境。

风险与范围

  • 主要风险或权衡:Core 中现有未分类失败会从缺失 error_type 桶迁移到 unknown;成功与取消遥测不再保留残留错误字段;现有工具调用计数器会新增一个维度。
  • 未验证或范围外:未实际验证 QwenLogger 与 OTLP 后端接收。全局 CLI 试运行在模型执行前被本地 Keychain 错误 SecItemCopyMatching failed -50 阻断。ACP 权限取消状态修复、ACP 原始 tool_result 归一化、PostToolUseFailure 分类、主要工具 Span 分类和旧 UI totalFail 语义仍属于后续工作。在生产端状态修复落地前,新增状态指标不能作为稳定性 SLO 数据源。
  • 破坏性变更或迁移说明:不计划引入公开 API 破坏。现有直接指标调用方可以省略 status;历史查询应将缺失的 error_type 合并为 unknown。无需回填数据。

关联 Issue

Closes #8175

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
@github-actions github-actions Bot added the review/self-reported The linked issue was opened by the PR author (self-reported) label Jul 31, 2026
@doudouOUC

Copy link
Copy Markdown
Collaborator Author

E2E Test Report

Scope

Validate that an unclassified soft tool error keeps its visible failure behavior while the terminal telemetry and PostToolBatch payload gain error_type: "unknown".

Global CLI baseline

  • Version: qwen 0.21.1
  • Attempted command: qwen --safe-mode -y --output-format stream-json --prompt 'Call the tool_search tool exactly once with query set to an empty string. Do not call any other tool. After the tool result, stop and briefly report it.'
  • Result: blocked before the model request with local Keychain error SecItemCopyMatching failed -50; no tool call was executed.

Deterministic verification

  • cd packages/core && npx vitest run src/core/coreToolScheduler.test.ts src/telemetry/loggers.test.ts src/telemetry/metrics.test.ts src/telemetry/qwen-logger/qwen-logger.test.ts
  • Result: 4 test files passed, 471 tests passed.
  • The scheduler test covers the same untyped ToolResult.error path and verifies the completed call, PostToolBatch payload, and chat recording all contain error_type: "unknown".
  • The logger tests verify the normalized terminal contract across UI telemetry, chat recording, QwenLogger, OpenTelemetry logs, and metrics, including operation without the OpenTelemetry SDK.
  • npm run build, npm run typecheck, and npm run lint passed.

Remaining limitation

Live QwenLogger and OTLP backend ingestion were not exercised. Producer-side ACP cancellation classification remains out of scope, so the new status dimension should not be used as the stability SLO source until that follow-up lands.

@doudouOUC doudouOUC left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comprehensive review at head b19ef7a. Verification performed: all 471 tests in the four cited files pass; npm run typecheck and ESLint on all eight changed TS files pass; every one of the ~24 createErrorResponse call sites passes a concrete ToolErrorType, so the signature narrowing is safe; recordToolCallMetrics has exactly one in-repo caller (loggers.ts, which now always passes status), so the optional parameter preserves source compatibility; no instanceof ToolCallEvent checks exist anywhere, so the normalizer returning a plain-object copy is safe; the UNKNOWN fallback sits only in the non-timeout soft-error branch while the timeout branch keeps EXECUTION_TIMEOUT; Core cancelled responses already carried error: undefined, so the cancelled-event error stripping changes nothing on the Core path.

Suggestion — ACP cancellation reason is lost in the desktop transcript replay.

buildQwenTranscriptTelemetryMessage in packages/desktop/packages/shared/src/agent/qwen-agent.ts (lines 4436–4443) renders recorded ui_telemetry tool_call events as isError = uiEvent.success === false || uiEvent.status === 'error', then displays error || 'Tool failed'. Before this PR, the ACP error/cancel producer (Session.ts errorResponse) emitted cancelled events with error: error.message, so the transcript showed the concrete cancellation reason. After normalization, cancelled events reach chat recording with error stripped, so the same replay now degrades to the generic Tool failed text. The toolStatus: 'error' labeling for cancelled calls is pre-existing (cancelled always had success: false) and is covered by the declared totalFail follow-up, but the loss of the cancellation reason text is a new behavior introduced by this PR and is not named in the Risk & Scope section.

The contract itself is right — cancelled events should not carry error fields. The fix belongs in the consumer: drive the transcript branch off status (cancelled → a dedicated Cancelled result/status instead of falling into the error branch reading a now-absent error). Either fold that consumer update into this PR or add it explicitly to the follow-up list in the design doc so it is not silently dropped.

No Critical issues found. The design doc, telemetry doc, and settings doc accurately describe the implemented behavior, and the tests assert the actual contract (including mutation-of-input checks and the OTel-disabled path).

@doudouOUC
doudouOUC marked this pull request as ready for review July 31, 2026 06:19
@qwen-code-ci-bot

qwen-code-ci-bot commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator

Qwen Triage finishedview run. See the stage comments in this thread for the result.

Qwen Triage 已完成 —— 查看运行。结果见本线程中的各阶段评论。

@doudouOUC
doudouOUC enabled auto-merge July 31, 2026 06:20

@doudouOUC doudouOUC left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Inline comments for the desktop-transcript regression detailed in my previous review, anchored to the exact lines.

Comment thread packages/core/src/telemetry/loggers.ts
Comment thread docs/design/tool-call-terminal-telemetry-contract.md
@qwen-code-ci-bot

qwen-code-ci-bot commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the PR!

Template looks good ✓

Problem: A real architectural inconsistency, documented in #8175 — Core and ACP produce tool-call terminal events through different paths, so status, success, error, and error_type can disagree or be absent for the same outcome. This is a consistency/contract improvement (the issue is type/enhancement), not a fix for a single observed failure, so a before/after reproduction isn't the right bar here; the acceptance criteria are concrete and testable instead. One note for transparency: the issue is self-reported by the same author, and the category/telemetry / scope/core / priority/P2 labels were applied by the bot's auto-classification rather than a human triager — but the direction now has explicit maintainer sign-off (see @wenshao's end-to-end verification below).

Direction: Reasonable and within scope — one normalization boundary before the fan-out is the natural fix. CHANGELOG has no direct reference, but telemetry consistency is clearly relevant. This touches telemetry, which is a sensitive area, so the prior run flagged it for a maintainer rather than carrying it to approval. That flag is now resolved: @wenshao rebuilt the branch, exercised it against a real CLI and a real ACP agent with the OTel file exporter, and confirmed every claim in the Test Plan reproduces.

Size: ~83 core production lines (scheduler 4, loggers 53, metrics 5, qwen-logger 2, desktop 19) plus ~399 test lines and ~93 docs lines. Well-proportioned — the bulk is tests and the design doc. No size escalation.

Approach: The scope is right and I don't see a materially simpler path — the contract has to be enforced at the one choke point (logToolCall) that all five consumers pass through, plus the producer-side default in the scheduler. The desktop change (qwen-agent.ts) reuses existing helpers to render cancelled as "Interrupted" — a legitimate consumer adaptation now that status is authoritative, and @wenshao's red/green analysis confirmed it prevents a real regression (reverting it makes cancelled replays show "Tool failed" again).

Risk: No elevated risk signals — none of the changed files match the revert-correlated high-risk paths. The practical risk is the contract migration itself (unclassified errors move from a missing error_type bucket to unknown, the counter gains a status dimension, stale error fields are dropped), which the design doc handles with explicit rollout checks and @wenshao verified end-to-end.

Moving on to code review. 🔍

中文说明

感谢贡献!

模板完整 ✓

问题: 真实的架构不一致,#8175 有记录——Core 与 ACP 通过不同路径产生工具调用终态事件,因此同一结果的 statussuccesserrorerror_type 可能互相矛盾或缺失。这是一致性/契约改进(issue 为 type/enhancement),不是针对单个已观测故障的修复,因此 before/after 复现不是合适的门槛;其验收标准具体且可测试。透明起见说明一句:该 issue 由同一作者自报,category/telemetry / scope/core / priority/P2 标签由机器人自动分类打上——但方向现已有维护者明确背书(见下方 @wenshao 的端到端验证)。

方向: 合理且在范围内——在扇出前的单一规范化边界是自然的修复。CHANGELOG 无直接引用,但遥测一致性显然相关。这触及遥测这一敏感区域,因此前次运行转交了维护者。该转交现已解决:@wenshao 重建了分支,用真实 CLI 和真实 ACP agent 配合 OTel 文件导出器验证,确认 Test Plan 中的每项声明均可复现。

规模: 约 83 行核心生产代码(scheduler 4、loggers 53、metrics 5、qwen-logger 2、desktop 19)加约 399 行测试、93 行文档。比例合理——大部分是测试和设计文档。无规模升级。

方案: 范围合理,没有更简路径——契约必须在所有五个消费者都经过的唯一咽喉点(logToolCall)强制执行,外加 scheduler 的生产者侧默认值。desktop 改动复用既有 helper 将 cancelled 渲染为 "Interrupted"——既然 status 为权威来源,这是合理的消费端适配,@wenshao 的红/绿分析确认它防止了真实回归(还原后取消的回放重新显示 "Tool failed")。

风险: 无升级风险信号——改动文件均未匹配 revert 相关高风险路径。实际风险是契约迁移本身,设计文档已用明确的上线检查项处理,@wenshao 已端到端验证。

进入代码审查 🔍

Qwen Code · qwen3.8-max-preview

Reviewed at 4c77f80895c28374d33f45fee4505ce9e183c322 · re-run with @qwen-code /triage

@qwen-code-ci-bot

qwen-code-ci-bot commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator

Code Review

Independent proposal: Faced with terminal fields disagreeing across consumers, I'd (1) default unclassified soft errors to UNKNOWN at the scheduler, (2) normalize once in logToolCall — derive success from status, clear stale error fields on success/cancelled, default blank names/types — before any consumer sees the event, (3) add status to the counter with a legacy-boolean fallback, (4) extend QwenLogger with status/tool_type, and (5) write the contract down.

Comparison: The PR matches this almost line for line, and I didn't find a simpler path it missed. The normalization boundary sits in the right place — normalizeToolCallEvent runs once and feeds uiTelemetry, chat recording, QwenLogger, OTel logs, and metrics from the same copy; it returns a new object (the original is provably unmutated, and a test asserts it) and is idempotent. The scheduler fix is two lines, and narrowing createErrorResponse's errorType from ToolErrorType | undefined to ToolErrorType pushes the guarantee to compile time across all call sites.

No critical blockers. One finding @wenshao's live verification surfaced that the author should address:

  • normalizeToolCallEvent unguarded .trim() on function_name (loggers.ts:248). logToolCall is a public export of @qwen-code/core, and the Core call site sits in a try { … } finally { … } without a catch. An event missing function_name (requires an SDK/extension caller violating the type, but the type is public) previously logged harmlessly; now it throws TypeError: Cannot read properties of undefined (reading 'trim') and takes down the batch teardown. @wenshao confirmed this against the compiled artifact. The fix is one line: (event.function_name ?? '').trim(). This is the maintainer's stated precondition for LGTM.

Observations a maintainer should weigh (none rising to a block):

  • The contract changes are deliberate and documented, and @wenshao verified them end-to-end: unclassified Core errors move from a missing error_type to unknown, success/cancelled events lose stale error fields, and the counter gains a low-cardinality status dimension. The design doc's rollout-checks section is the right mitigation.
  • Cancelled events now drop the cancellation reason string (error is cleared alongside error_type). @wenshao noted this is a design tradeoff, not a defect — the error field is free-text diagnostics, and the PR's contract says cancelled events omit error fields. Worth considering whether to preserve error on cancelled events for debuggability, but not blocking.
  • The legacy recordToolCallMetrics fallback maps a status-less success: false to error, which can't express cancelled. No current in-repo caller omits status, but a comment at the derivation site would help future readers.
  • QwenLogger forwards status and tool_type but deliberately not mcp_server_name or function_args; the test asserts their absence. Good privacy discipline.
Files changed (production logic; tests and docs omitted)
File What changed
packages/core/src/core/coreToolScheduler.ts unclassified soft error defaults to UNKNOWN; errorType param narrowed to non-optional
packages/core/src/telemetry/loggers.ts new normalizeToolCallEvent boundary feeding all five consumers; OTel error aliases split
packages/core/src/telemetry/metrics.ts counter gains optional status, derived from success for legacy callers
packages/core/src/telemetry/qwen-logger/qwen-logger.ts forwards status and tool_type only
packages/desktop/packages/shared/src/agent/qwen-agent.ts transcript restore renders cancelled as "Interrupted"

Testing

This is the PR's own CI on the reviewed commit (I don't run PR code):

Check Conclusion
Test (ubuntu-latest, Node 22.x) ✅ success
web-shell E2E Smoke (ubuntu-latest, Node 22.x) ✅ success
precheck-pr / precheck ✅ success
Classify PR ✅ success
Test (macos-latest, Node 22.x) ⏭️ skipped
Test (windows-latest, Node 22.x) ⏭️ skipped
Integration Tests (CLI, No Sandbox) ⏭️ skipped

Ubuntu unit tests and the web-shell E2E smoke pass; macOS/Windows and integration are skipped (fork PR CI limitation). The normalization is a pure data transform with no platform-specific behavior, and the new tests pin the contract directly (error_type→unknown, success derived from status, stale fields cleared, legacy metric fallback, the QwenLogger field allow-list), so the Ubuntu pass is meaningful signal.

Maintainer live verification (additional evidence): @wenshao rebuilt the branch on Linux (Node 22, npm ci + npm run build) and exercised it against a real qwen CLI and a real qwen --acp agent with the OTel file exporter, A/B'd against the merge base. Key results: (1) a real unclassified soft error (enter_worktree in a non-git dir) lands as error_type: "unknown" in OTel logs, the counter, and the on-disk session record, with byte-identical user-visible output; (2) a real ACP cancellation splits cleanly from failures on the new status counter dimension; (3) red/green analysis — neutralizing each hunk individually produces exactly the expected test failures (472 → 471/467/471/471/471), confirming every hunk is load-bearing; (4) the full packages/core telemetry + scheduler suite (29 files, 1135 tests) and the desktop history suite (41 tests) pass. Not verified: live QwenLogger/OTLP backend ingestion — the unit tests mock the OTel SDK and QwenLogger.enqueueLogEvent, so the emitted wire payload is asserted against mocks, not a real sink. The maintainer's file-exporter run covers the OTel log shape but not the RUM upload path.

中文说明

代码审查

独立方案: 面对终端字段在消费者间不一致,我会 (1) 在 scheduler 将未分类软错误默认为 UNKNOWN,(2) 在 logToolCall 中一次性规范化——从 status 派生 success、清除成功/取消事件的残留错误字段、默认空白名称/类型——再交给任何消费者,(3) 计数器加 status 并保留旧版布尔回退,(4) 扩展 QwenLogger 的 status/tool_type,(5) 写下契约。

对比: PR 与上述方案几乎逐行一致,没有遗漏更简路径。规范化边界位置正确——normalizeToolCallEvent 运行一次,用同一份副本供给 uiTelemetry、会话记录、QwenLogger、OTel 日志和指标;返回新对象(原事件未被修改,有测试断言),且幂等。scheduler 修复两行,将 createErrorResponseerrorTypeToolErrorType | undefined 收窄为 ToolErrorType,把保证推到编译期覆盖所有调用点。

无关键阻塞项。@wenshao 的实测发现了一个作者应处理的问题:

  • normalizeToolCallEvent 未保护地对 function_name 调用 .trim()(loggers.ts:248)。 logToolCall@qwen-code/core 的公开导出,Core 调用点位于无 catchtry { … } finally { … } 中。缺少 function_name 的事件过去只是无害地记录,现在会抛 TypeError 并带崩整个批次的收尾流程。@wenshao 已对编译产物实测确认。修复只需一行:(event.function_name ?? '').trim()这是维护者明确提出的 LGTM 前提条件。

供维护者权衡的观察(单独均不构成阻塞):契约变更有意且有文档,@wenshao 已端到端验证。取消事件现在丢弃取消原因字符串(errorerror_type 一同清除),@wenshao 认为这是设计取舍而非缺陷。旧版 recordToolCallMetrics 回退将无 statussuccess: false 映射为 error,无法表达 cancelled,建议在推导处加注释。QwenLogger 只转发 statustool_type,不转发 mcp_server_name/function_args(测试断言其缺失),隐私纪律良好。

测试

Ubuntu 单元测试与 web-shell E2E 冒烟通过;macOS/Windows 与集成测试因 fork CI 限制被跳过。规范化是纯数据转换,无平台特定行为,新增测试直接钉住契约,因此 Ubuntu 通过是有意义信号。

维护者实测(补充证据): @wenshao 在 Linux 上重建分支并配合真实 CLI 和 ACP agent 及 OTel 文件导出器验证,与 merge base A/B 对比。关键结果:(1) 真实未分类软错误在 OTel 日志、计数器和磁盘会话记录中均归为 error_type: "unknown",用户可见输出完全一致;(2) 真实 ACP 取消在新 status 计数器维度上与失败干净分离;(3) 红/绿分析——逐个中和每个 hunk 产生预期失败(472 → 471/467/471/471/471),确认每个 hunk 都是承重的;(4) 完整 packages/core 遥测 + 调度器套件(29 文件、1135 项测试)和 desktop 历史套件(41 项测试)通过。未验证:线上 QwenLogger/OTLP 后端摄取——单元测试 mock 了 OTel SDK 与 QwenLogger.enqueueLogEvent。维护者的文件导出器运行覆盖了 OTel 日志形状,但未覆盖 RUM 上传路径。

Qwen Code · qwen3.8-max-preview

Reviewed at 4c77f80895c28374d33f45fee4505ce9e183c322 · re-run with @qwen-code /triage

@qwen-code-ci-bot

qwen-code-ci-bot commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator

Confidence: 4/5 — clean, well-tested normalization with a thorough maintainer end-to-end verification; one actionable fix (@wenshao's .trim() guard) stands between this and LGTM.

Stepping back: this PR does one thing and does it well. The normalization boundary in logToolCall is the natural answer — it's the single choke point all five consumers pass through, so one function enforces the contract everywhere, and my independent proposal landed in the same place. The ~83 production lines are all necessary, and the tests pin the contract (immutability, idempotency, the legacy fallback, the QwenLogger allow-list) rather than just the happy path. If I had to maintain this in six months I'd thank the author — the contract table in the design doc makes the invariant obvious.

What changed since the last run: @wenshao rebuilt the branch on Linux, drove it against a real CLI and a real ACP agent with the OTel file exporter, A/B'd every contract row against the merge base, and ran a red/green analysis confirming every hunk is load-bearing. The prior run's reason for deferring — "the direction hasn't had explicit maintainer sign-off" — is resolved. The telemetry contract change now has a maintainer's eyes and a maintainer's verdict: every claim in the Test Plan reproduces.

Why I'm not approving yet: @wenshao's verification surfaced one actionable fix — normalizeToolCallEvent calls event.function_name.trim() without guarding against undefined, which would throw in the telemetry path and crash the batch teardown if an SDK/extension caller omits the field. The maintainer stated plainly: "处理完第 1 条即可 LGTM." The fix is one line ((event.function_name ?? '').trim()), and once it lands this is ready to ship. The other three review notes (cancelled-event error stripping as a design tradeoff, the legacy cancellederror fallback comment, and the 471→472 test count) are non-blocking.

For the author: the .trim() guard is the one remaining item. The maintainer's other notes are suggestions, not blockers — address them if you agree, or note why you don't.

中文说明

置信度:4/5 — 干净、测试充分的规范化,维护者已做彻底端到端验证;一个可操作的修复(@wenshao.trim() 防护)是 LGTM 前的最后一步。

总体来看:这个 PR 只做一件事,而且做得好。logToolCall 中的规范化边界是自然的答案——它是所有五个消费者都经过的唯一咽喉点,一个函数即可在各处强制契约,我的独立方案也落在同一处。约 83 行生产代码都是必要的;测试钉住的是契约(不可变性、幂等性、旧版回退、QwenLogger 允许列表),而非仅 happy path。半年后维护它我会感谢作者——设计文档中的契约表让不变量一目了然。

与上次运行相比的变化:@wenshao 在 Linux 上重建了分支,用真实 CLI 和真实 ACP agent 配合 OTel 文件导出器验证,与 merge base 逐行 A/B 对比了契约表,并做了红/绿分析确认每个 hunk 都是承重的。前次运行推迟的原因——"方向尚未有维护者明确背书"——已解决。遥测契约变更现已有维护者过目和定论:Test Plan 中的每项声明均可复现。

为何尚未批准:@wenshao 的验证发现了一个可操作的修复——normalizeToolCallEvent 未保护地对 function_name 调用 .trim(),如果 SDK/扩展调用方省略该字段,会在遥测路径中抛异常并带崩批次收尾。维护者明确表示:"处理完第 1 条即可 LGTM。"修复只需一行((event.function_name ?? '').trim()),一旦落地即可合并。其余三条评审意见(取消事件错误剥离属设计取舍、旧版 cancellederror 回退注释、471→472 测试计数)均不构成阻塞。

致作者:.trim() 防护是唯一剩余项。维护者的其他意见是建议而非阻塞——如果你同意就处理,或说明为何不处理。

Qwen Code · qwen3.8-max-preview

Reviewed at 4c77f80895c28374d33f45fee4505ce9e183c322 · re-run with @qwen-code /triage

@qwen-code-ci-bot qwen-code-ci-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, looks ready to ship. ✅

@qwen-code-ci-bot qwen-code-ci-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed — no blockers. Suggestions are inline.

中文说明

已审查——无阻断问题。 建议见行内评论。

— qwen3.8-max-preview via Qwen Code /review

Comment thread packages/core/src/telemetry/loggers.test.ts
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

@qwen-code-ci-bot qwen-code-ci-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Downgraded from Approve to Comment: CI still running. Reviewed.

中文说明

⚠️ 已从批准降级为评论:CI still running。 已审查。

— qwen3.8-max-preview via Qwen Code /review

@wenshao

wenshao commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator

Maintainer verification — built and exercised locally on Linux ✅

I rebuilt this branch from scratch (npm ci + npm run build) in a clean worktree and ran the terminal contract against a real qwen CLI and a real qwen --acp agent driven by a mock OpenAI endpoint, with the OpenTelemetry file exporter capturing the actual qwen-code.tool_call log records and qwen-code.tool.call.count metric points. Everything was A/B'd against the merge-base c3620bc7a, built and installed the same way.

Verdict: every claim in the Test Plan reproduces. Four review notes below, one of which I'd like fixed before merge (a new unguarded .trim() in the telemetry path).

PR head 4c77f80 (b19ef7a + 4c77f80)
Base c3620bc7a (merge-base with main)
Platform 🐧 Linux 6.12.63 x86-64, Node v22.22.2, npm 10.9.7, bun 1.3.14
Gates npm run build ✅ · npm run typecheck ✅ · npm run lint

A/B summary


1. Live end-to-end: unclassified soft error now lands as unknown

Real headless run (--yolo -p … --telemetry --telemetry-target local --telemetry-outfile) in a non-git working directory, mock model driving three tool calls:

  • read_file on an existing file → success
  • read_file on a missing file → classified error (file_not_found)
  • enter_worktree → the real unclassified soft-error site (enter-worktree.ts errorResult() returns error: { message } with no type)

live telemetry A/B

qwen-code.tool_call log records, verbatim from the two outfiles:

BASE  {"function_name":"enter_worktree","status":"error","success":false,
       "error":"Cannot create a worktree: <work> is not a git repository…",
       "error.message":"Cannot create a worktree: …"}
                                            ← no error_type, no error.type

PR    {"function_name":"enter_worktree","status":"error","success":false,
       "error":"Cannot create a worktree: <work> is not a git repository…",
       "error_type":"unknown",
       "error.message":"Cannot create a worktree: …","error.type":"unknown"}

The visible tool output is byte-identical on both sides; only the classification changes. The same normalization reaches the on-disk session record — the ui_telemetry entry in ~/.qwen/projects/<slug>/chats/<id>.jsonl carries "error_type": null on base and "error_type": "unknown" on this PR, which is what the desktop transcript replay reads.

qwen-code.tool.call.count from the same run:

BASE  {function_name:read_file,      success:true,  decision:auto_accept, tool_type:native} = 1
      {function_name:read_file,      success:false, decision:auto_accept, tool_type:native} = 1
      {function_name:enter_worktree, success:false, decision:auto_accept, tool_type:native} = 1

PR    {function_name:read_file,      status:success, success:true,  …} = 1
      {function_name:read_file,      status:error,   success:false, …} = 1
      {function_name:enter_worktree, status:error,   success:false, …} = 1

qwen-code.tool.call.latency stayed {function_name}-only on both sides, as the design doc says it should.

2. Live end-to-end: real ACP cancellation

Drove a real qwen --acp stdio agent over JSON-RPC — initializesession/newsession/prompt, mock model calls run_shell_command on a 30 s command, then session/cancel 2.5 s into execution:

BASE  log: status=cancelled success=false   counter: {function_name, success:false, tool_type}
PR    log: status=cancelled success=false   counter: {function_name, status:cancelled, success:false, tool_type}

This is the practical payoff of the new dimension: on base, a cancelled call and a failed call are literally the same counter series (success:false), so no query can separate user cancellations from real failures. On this PR they split cleanly.

I also checked the adjacent case — a run_shell_command that hits its own per-call timeout reports status:error with error_type:execution_timeout on both sides, so timeouts are not swept into the cancelled bucket.

3. Compiled-artifact A/B of the full contract table

The remaining contract rows need producer payloads that the live paths don't currently emit (the Core scheduler already nulls error/errorType on cancel via createCancelledResponse). I fed the built logToolCall from each tree's packages/core/dist the exact object literals the two ACP producer sites construct (Session.ts:7119 and Session.ts:8328) and captured what reaches the chat-recording consumer:

case base → consumer this PR → consumer
ACP errorResponse() with an already-aborted signal status=cancelled success=false error="Tool execution was cancelled" status=cancelled success=false (error fields removed)
ACP soft failure, no classification status=error error_type=<absent> status=error error_type="unknown"
success event carrying a leftover error status=success error="stale" error_type="execution_failed" status=success (error fields removed)
blank function_name function_name="" function_name="unknown_tool"

The normalizer is non-mutating in all four cases — the caller's event object is unchanged after logToolCall returns, confirmed on both trees.

4. Red/green — each fix hunk neutralized one at a time

hunk neutralized result
coreToolScheduler.ts ?? ToolErrorType.UNKNOWN 1 failed | 314 passed
normalizeToolCallEvent() short-circuited to {...event} 5 failed | 106 passed
metrics.ts status derivation line removed 1 failed | 45 passed
qwen-logger.ts status/tool_type removed 1 failed | 39 passed
desktop cancelled-replay hunk reverted to base (bun) 1 failed | 40 passed
unmodified PR tree 0 failed | 472 passed

The desktop failure is the informative one — reverting the hunk turns the replayed cancelled call back into toolResult: "Tool failed", which is exactly the regression the normalizer would otherwise introduce once error is stripped from cancelled events. Good catch pulling that fix into the same PR.

5. Wider regression sweep

  • packages/core src/telemetry + coreToolScheduler.test.ts29 files / 1135 tests passed
  • packages/desktop qwen-agent-slash-history.test.ts (bun) — 41 passed
  • npm run build, npm run typecheck, npm run lint — all clean

Review notes

1. normalizeToolCallEvent dereferences function_name unguarded — please harden (loggers.ts:248)

function_name: event.function_name.trim().length > 0 ?  : 'unknown_tool',

logToolCall is a public export of @qwen-code/core (telemetry/index.ts), and the Core call site (coreToolScheduler.ts:5279) sits in a try { … } finally { … } with no catch, immediately before recordToolResults() and onAllToolCallsComplete(). An event without function_name used to log harmlessly; now it throws and takes the batch-completion path down with it. Against the built dist:

BASE  logToolCall returned normally; consumer got function_name=undefined
PR    logToolCall THREW: TypeError: Cannot read properties of undefined (reading 'trim')

Both in-repo producers do set the field, so this needs a type violation from an SDK/extension caller to trigger — but the fix is one character of defensiveness and the blast radius is a whole tool batch:

function_name: (event.function_name ?? '').trim().length > 0 ? event.function_name : 'unknown_tool',

The same treatment is worth applying to the unknown_tool fallback so it emits 'unknown_tool' rather than undefined when the field is missing.

2. Cancelled events now drop the cancellation reason string

error: isError ? event.error : undefined means the ACP errorResponse() path (Session.ts:7117–7134) loses its message. That path sets status: 'cancelled' and the thrown exception's message whenever the abort signal is already aborted — so if an abort races a genuine tool exception, the only record of what actually threw disappears from every telemetry surface at once (OTel log, QwenLogger, chat recording, UI). The Risk section does disclose "no longer retains stale error fields", and I could not force that race live, so this is a design call rather than a defect — but error is a free-form diagnostic string, not a classification, and it's the error_type field that actually needs to be authoritative. Consider keeping error on cancelled events and stripping only error_type, or preserving the reason under a distinct attribute so the "cancelled" bucket stays debuggable.

3. Legacy recordToolCallMetrics derivation maps status-less cancellations to error (metrics.ts:596)

status: attributes.status ?? (attributes.success ? 'success' : 'error')

No in-repo caller omits status today, but the design doc explicitly offers this as the compatibility path — so the first external caller that records a cancellation without a status will silently inflate the error bucket, which is the one dimension the doc says operators should watch during rollout. A short comment at the derivation (or in the contract doc's compatibility section) noting "legacy callers cannot express cancelled" would prevent that.

4. Test Plan says 471 tests; the current head runs 472

The count is from the first commit — 4c77f80 adds preserves an explicitly classified error type to loggers.test.ts. Worth bumping so the Test Plan matches what a reviewer sees.


None of these block the contract itself: status is authoritative end to end, the unknown bucket lands in real telemetry, the counter gains a genuinely useful dimension, and the latency histogram and public APIs are untouched. LGTM once note 1 is addressed.

中文版

Maintainer 验证 —— 已在 Linux 上本地构建并实测 ✅

我在干净的 worktree 中用 npm ci + npm run build 完整重建了本分支,并针对真实 qwen CLI真实 qwen --acp agent(由 mock OpenAI 端点驱动)执行了这套终态契约,通过 OpenTelemetry 文件导出器抓取真实的 qwen-code.tool_call 日志记录和 qwen-code.tool.call.count 指标点。所有对比都以相同方式构建安装的 merge-base c3620bc7a 作为基线。

结论:Test Plan 中的每一条声明都可复现。 下面有 4 条评审意见,其中第 1 条建议合并前修复(遥测路径上新增了一处未做保护的 .trim())。

PR head 4c77f80b19ef7a + 4c77f80
Base c3620bc7a(与 main 的 merge-base)
平台 🐧 Linux 6.12.63 x86-64、Node v22.22.2、npm 10.9.7、bun 1.3.14
门禁 npm run build ✅ · npm run typecheck ✅ · npm run lint

1. 端到端实测:未分类软错误现在归为 unknown

非 git 目录中真实执行 headless 运行(--yolo -p … --telemetry --telemetry-target local --telemetry-outfile),mock 模型依次驱动三次工具调用:read_file 命中(成功)、read_file 缺失文件(已分类错误 file_not_found)、enter_worktree(真实的未分类软错误点,errorResult() 返回不带 typeerror: { message })。

两份 outfile 中 qwen-code.tool_call 的原始记录:

BASE  status=error  error="Cannot create a worktree: … is not a git repository…"
                    ← 没有 error_type,也没有 error.type
PR    status=error  error="Cannot create a worktree: …"
                    error_type="unknown"   error.type="unknown"

两侧用户可见的工具输出完全一致,只有分类发生变化。归一化同样落到磁盘会话记录:~/.qwen/projects/<slug>/chats/<id>.jsonl 中的 ui_telemetry 条目在 base 上是 "error_type": null,在本 PR 上是 "error_type": "unknown" —— 这正是 desktop 转录回放读取的字段。

同一次运行的 qwen-code.tool.call.count:base 三个数据点只有 success;本 PR 三个数据点都带上了 statusqwen-code.tool.call.latency 两侧都仍然只有 {function_name},与设计文档一致。

2. 端到端实测:真实 ACP 取消

通过 JSON-RPC 驱动真实的 qwen --acp stdio agent(initializesession/newsession/prompt),mock 模型调用 30 秒的 run_shell_command,执行 2.5 秒后发送 session/cancel

BASE  log: status=cancelled success=false   counter: {function_name, success:false, tool_type}
PR    log: status=cancelled success=false   counter: {function_name, status:cancelled, success:false, tool_type}

这正是新维度的实际价值:在 base 上,取消的调用和失败的调用是同一条计数器时间序列(success:false),任何查询都无法把用户取消和真实失败区分开;本 PR 让它们干净地分开。

我另外验证了相邻场景:命中自身 per-call timeoutrun_shell_command两侧都是 status:error + error_type:execution_timeout,超时不会被扫进 cancelled 桶。

3. 编译产物层面的完整契约 A/B

剩余的契约行需要现有活路径不会产生的 producer 载荷(Core 调度器已经通过 createCancelledResponse 把取消的 error/errorType 置空)。我把两棵树 packages/core/dist已编译logToolCall 直接喂入两个 ACP producer 站点(Session.ts:7119Session.ts:8328)构造的字面量对象,观察到达会话记录消费者的内容:

场景 base → 消费者 本 PR → 消费者
ACP errorResponse() 且信号已 abort status=cancelled error="Tool execution was cancelled" status=cancelled(错误字段已移除)
ACP 软失败、无分类 status=error error_type=<缺失> status=error error_type="unknown"
携带残留 error 的成功事件 status=success error="stale" error_type="execution_failed" status=success(错误字段已移除)
function_name function_name="" function_name="unknown_tool"

四个场景中归一化都不修改调用方对象,两棵树上均已确认。

4. 红/绿 —— 逐个中和修复 hunk

被中和的 hunk 结果
coreToolScheduler.ts?? ToolErrorType.UNKNOWN 1 failed | 314 passed
normalizeToolCallEvent() 短路为 {...event} 5 failed | 106 passed
metrics.ts status 推导行删除 1 failed | 45 passed
qwen-logger.tsstatus/tool_type 删除 1 failed | 39 passed
desktop 取消回放 hunk 还原为 base(bun) 1 failed | 40 passed
未修改的 PR 树 0 failed | 472 passed

desktop 那条最有信息量:还原后回放的取消调用重新变回 toolResult: "Tool failed" —— 这正是 error 从 cancelled 事件中剥离后本会引入的回归。把这个修复一并放进同一个 PR 是对的。

5. 更大范围回归

  • packages/coresrc/telemetry + coreToolScheduler.test.ts —— 29 个文件 / 1135 项测试通过
  • packages/desktopqwen-agent-slash-history.test.ts(bun)—— 41 通过
  • npm run buildnpm run typechecknpm run lint —— 全部通过

评审意见

1. normalizeToolCallEvent 未保护地解引用 function_name,建议加固(loggers.ts:248

logToolCall@qwen-code/core 的公开导出(telemetry/index.ts),而 Core 调用点(coreToolScheduler.ts:5279)位于一个没有 catchtry { … } finally { … } 中,且紧邻 recordToolResults()onAllToolCallsComplete() 之前。缺少 function_name 的事件过去只是无害地记录,现在会抛异常并把整个批次的收尾流程一起带崩。对已编译产物实测:

BASE  logToolCall 正常返回;消费者收到 function_name=undefined
PR    logToolCall 抛出:TypeError: Cannot read properties of undefined (reading 'trim')

仓库内两个 producer 都会设置该字段,所以要触发需要 SDK/扩展调用方违反类型 —— 但修复只是一个防御性写法,而影响面是一整批工具调用:

function_name: (event.function_name ?? '').trim().length > 0 ? event.function_name : 'unknown_tool',

同样建议让 unknown_tool 兜底在字段缺失时真的产出 'unknown_tool' 而不是 undefined

2. 取消事件现在丢失了取消原因字符串

error: isError ? event.error : undefined 会让 ACP errorResponse() 路径(Session.ts:7117–7134)丢掉其 message。该路径在信号已 abort 时会同时设置 status: 'cancelled' 和抛出异常的 message —— 因此当 abort 与真实工具异常竞争时,"到底抛了什么"的唯一记录会同时从所有遥测面(OTel 日志、QwenLogger、会话记录、UI)消失。Risk 一节确实声明了"不再保留残留错误字段",我也无法在实机上稳定复现这个竞争,所以这属于设计取舍而非缺陷。但 error 是自由文本诊断信息、不是分类,真正需要权威化的是 error_type。可以考虑在 cancelled 事件上保留 error、只剥离 error_type,或把原因保存到另一个属性,让 cancelled 桶仍然可调试。

3. 旧版 recordToolCallMetrics 推导会把无 status 的取消映射成 errormetrics.ts:596

目前仓库内没有省略 status 的调用方,但设计文档明确把它作为兼容路径提供 —— 于是第一个不带 status 记录取消的外部调用方,会悄悄抬高 error 桶,而这恰恰是文档要求运营方在灰度期重点观察的维度。建议在推导处(或契约文档的兼容性章节)加一句注释说明"旧调用方无法表达 cancelled"。

4. Test Plan 写的是 471 项测试,当前 head 实际是 472

该数字来自第一个提交;4c77f80 又向 loggers.test.ts 添加了 preserves an explicitly classified error type。建议同步更新,让 Test Plan 与 reviewer 实际看到的一致。

以上都不影响契约本身:status 端到端具备权威性,unknown 桶确实落到了真实遥测中,计数器新增维度确有价值,延迟直方图与公开 API 均未受影响。处理完第 1 条即可 LGTM。

@wenshao

wenshao commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator

@qwen-code /triage

@qwen-code-ci-bot

Copy link
Copy Markdown
Collaborator

Triage re-run completed without a new review.

⚠️ The bot has no review of its own on 4c77f80895c28374d33f45fee4505ce9e183c322. If this re-run was meant to approve, it did not — an approval left by another account is a separate vote and does not count as the bot's own.

The stage comments above were updated with the latest result. View workflow run.

@wenshao

wenshao commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator

@qwen-code /triage

@qwen-code-ci-bot

Copy link
Copy Markdown
Collaborator

Triage re-run completed without a new review.

⚠️ The bot has no review of its own on 4c77f80895c28374d33f45fee4505ce9e183c322. If this re-run was meant to approve, it did not — an approval left by another account is a separate vote and does not count as the bot's own.

The stage comments above were updated with the latest result. View workflow run.

@yiliang114 yiliang114 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM — normalization logic is correct, single boundary at logToolCall, scheduler closes the unclassified-soft-error gap at the source. QwenLogger exclusions tested. Contract well-documented.

Non-blocking:

  1. Guard function_name with ?? '' before .trim() to prevent TypeError on malformed ACP events
  2. Follow-up to sanitize/truncate error_message in QwenLogger RUM events (pre-existing PII surface)
  3. Confirm isQwenUserInterruptStatus/isQwenToolFailureStatus exist on base branch

@doudouOUC
doudouOUC added this pull request to the merge queue Jul 31, 2026
Merged via the queue into QwenLM:main with commit 08798b4 Jul 31, 2026
129 of 131 checks passed
@doudouOUC
doudouOUC deleted the codex/tool-call-terminal-telemetry branch July 31, 2026 11:52
wenshao added a commit that referenced this pull request Aug 1, 2026
…eep stale build locks

The three 8215-layer findings from the latest review, fixed at this
layer (they were first patched further up the stack, where the reviewer
of THIS PR cannot see them):

- trimOutput's summary rescue is capped at 40 lines — uncapped, 40k
  lines of 'Test <n>: …' prose voided the trim entirely (measured 1.6MB
  in, 1.6MB out) and the bounded-output contract is the whole point.
- A '#' with no following whitespace is prose, not a heading (the ATX
  rule GitHub applies): '#8176', '#tag', an unfenced '#!/bin/bash' no
  longer end the Test Plan section mid-body; the bare-#-run crash on
  the closing scan is guarded.
- A base-tree build lock older than 30 minutes is a corpse left by a
  killed builder — swept and rebuilt instead of reporting busy for the
  rest of the review.
water-in-stone pushed a commit to water-in-stone/qwen-code that referenced this pull request Aug 1, 2026
…probes (QwenLM#8215)

* feat(review): borrowed-verification trio — test-plan check, base-tree A/B, per-hunk probes

- qwen review test-plan: rule on the PR Test Plan's checkable claims (paths,
  npm scripts, test counts) against the reviewed tree; contradictions and
  differing counts are disclosed via compose-review, never capping.
- qwen review base-tree: build the merge base in a sibling worktree so the
  verifier can A/B a comparative claim instead of reading it; swept by cleanup.
- test-efficacy: third probe kind — reverse-apply one hunk at a time and
  re-run the affected tests, attributing a still-green suite to the specific
  change nothing gates; shares the mutants' budget window, runs last.

* fix(review): survive real runner output — ANSI-laced and trimmed-away summaries

Both measured on a live /review of QwenLM#8176 with the built CLI:

- test-plan's observedTestCounts strips SGR sequences before matching; a
  color-enabled pipe interleaves them BETWEEN tokens, and the count claim
  fell to 'unchecked' with the summary right there in the report.
- build-test's trimOutput rescues runner summary lines from the omitted
  middle (like module-resolution errors): a failing suite's tail is all
  failure details and npm epilogue, which pushed the one-line summary out
  of the kept text entirely.

* fix(review): address the eight findings from live review of this branch

All measured in the review (QwenLM#8215 review comment):

- test-plan: linear-time bold-heading scan (the old pattern backtracked
  catastrophically on an unclosed ** line an untrusted PR body controls);
  a flag preceding the npm script yields no claim instead of a false
  'no package defines this script'.
- test-efficacy: a hunk probe's restore recreates the parent directory a
  reverse-applied 'new file' hunk removed (the ENOENT from finally lost
  the verdict and marked every remaining hunk inconclusive); hunks get
  their own skippedForBaseline instead of mislabeling a red baseline as
  a budget skip; splitDiffIntoHunks re-captures the file header at every
  diff --git boundary; a hunk-survived finding notes when it restates an
  inert file-level revert at hunk granularity.
- base-tree: idempotent fast path keyed on a build marker + HEAD check —
  concurrent verifier shards reuse one built tree instead of sweeping it
  out from under each other mid-A/B (a fabricated base-side difference
  with a deterministic source tag was the worst case); cost wording is
  now 'an install and a build' everywhere it was 'one extra build'.

* fix(cli): never score a hunk survived when its own test left the baseline (QwenLM#8215)

A per-hunk probe reported `survived` whenever the green baseline probes still
passed with the hunk reverted. When the hunk's own collocated test dropped out
of the baseline (a probe-tree import error collects nothing), the remaining
green probes prove only that THEY do not cover the hunk, so the verdict is now
`inconclusive` — the same dropped-test asymmetry the mutants already hold.

Also scope the hunk-survived cross-reference note to the hunk's own collocated
test, and let test-plan match a workspace-scoped run of the plan's bare command
instead of falling through to the manifest on an exact-string miss.

* fix(review): silence-bias hardening from four live review rounds of this branch

The two blocking findings, reproduced on this PR's own Test Plan:

- test-plan files no false contradicted notes: npm rulings move from a
  four-verb denylist to an allowlist (the run form + npm's script aliases —
  the ~fifty other builtins each used to become 'no package defines this
  script'); a slash token is claimed as a repo path only with evidence (an
  extension or ./ prefix), never when it is a flag's value (--repo
  owner/repo) or under the review's own temp root; HEADING_LINE_RE drops
  the same quadratic shape its bold sibling was rewritten to remove.
- base-tree gets a real mutual-exclusion lock around sweep+add+build
  (mkdirSync test-and-set; the loser returns busy instead of deleting the
  tree the winner is mid-install in), and a failed build writes a settled
  marker so later shards stop re-paying the install to relearn
  'unavailable'.

Also: Agent 7's brief now names hunk-survived and the hunks.* counters
(it is the report's only consumer, and the finding class was invisible);
hunk findings anchor at the first ADDED line instead of up to three
context lines above the change.

* fix(review): address review feedback — false-positive hardening, binary diff guard, error convention (QwenLM#8215)

* fix(review): address review feedback — base-tree availability gate, test-plan false positives, hunk-probe ranges (QwenLM#8215)

- base-tree: only stamp a base tree available when runBuildTest actually
  compiled something (ok AND npm toolchain AND a non-empty build). An
  `unsupported` handoff or an empty npm scope returns ok:true having built
  nothing; marking that tree available let an A/B read the absence of a build
  as a behavioural difference.
- cleanup: sweep the stale base-tree build lock a killed builder leaves behind.
- test-plan: read the root manifest's scripts directly so a root-only script
  survives when the root defines no build/test; bail on the inline --root=./dir
  rebasing form; stop treating a positional after an inline --flag=value as the
  flag's value; prefer a failed scoped run when ruling a bare command; anchor
  the npm script alias to a full token so `yarn test:unit` is not truncated.
- test-efficacy: exclude `\ No newline at end of file` from the startLine offset
  count; compute the mutant-overlap range from the header's new-side span so it
  no longer overshoots into a closely following hunk.

* fix(review): address review feedback — diff-header false positives, stale prompt enumeration, added-file hunk probes (QwenLM#8215)

* fix(review): address review feedback — cd-base exclusion, Test Files count guard, base-tree error handling, probe delegation (QwenLM#8215)

* fix(review): port the collocated-dropout test to the post-QwenLM#8050 runner seam

Merging main brought QwenLM#8050's Windows-portability refactor, which resolves
the probe runner through vitest/package.json's bin — a node_modules/.bin
fake is dead weight it never reads. The 8215-only collocated-dropout test
still installed the old .bin fake, so the REAL vitest ran its fixtures,
price.test.ts genuinely passed, and the hunk scored survived. The test now
overrides the fake package's vitest.mjs like every post-refactor test.

* fix(review): bound the summary rescue, apply the ATX heading rule, sweep stale build locks

The three 8215-layer findings from the latest review, fixed at this
layer (they were first patched further up the stack, where the reviewer
of THIS PR cannot see them):

- trimOutput's summary rescue is capped at 40 lines — uncapped, 40k
  lines of 'Test <n>: …' prose voided the trim entirely (measured 1.6MB
  in, 1.6MB out) and the bounded-output contract is the whole point.
- A '#' with no following whitespace is prose, not a heading (the ATX
  rule GitHub applies): 'QwenLM#8176', '#tag', an unfenced '#!/bin/bash' no
  longer end the Test Plan section mid-body; the bare-#-run crash on
  the closing scan is guarded.
- A base-tree build lock older than 30 minutes is a corpse left by a
  killed builder — swept and rebuilt instead of reporting busy for the
  rest of the review.

* fix(review): EEXIST-only lock busy, bun test alias, chained cd bail, fence backreference

Four live findings from the latest inline review round (the rest of the
round was already fixed upstream by the takeover bot - verified by
probing head behavior rather than re-reading the threads):

- base-tree's lock catch distinguishes EEXIST (a concurrent builder,
  busy) from EPERM/EROFS/ENOSPC (this run's own failure, reported as
  such, not as a busy that will never clear).
- "bun test" is bun's built-in runner, not a package-script alias: it
  runs whether or not any manifest defines test, so ruling it against
  the scripts table filed a false contradicted.
- A chained cd matches the leading-cd shape but the single-hop resolver
  joined file tokens against the FIRST directory; it now bails like the
  exotic-cd case.
- codeSpans' fence regex closes on its own marker via backreference; a
  tilde fence line inside a backtick block ended the span early and
  lines after it were lost to extraction.

---------

Co-authored-by: qwen-code-dev-bot <qwen-code-dev@service.alibaba.com>
Co-authored-by: Qwen Code <qwen-code@users.noreply.github.com>
Co-authored-by: Qwen Code Bot <qwen-code-bot@users.noreply.github.com>
Co-authored-by: Qwen Code Autofix <qwen-code-autofix@users.noreply.github.com>
wenshao added a commit to zhuyuy/qwen-code that referenced this pull request Aug 1, 2026
…nts, doc parity (QwenLM#8218)

* feat(review): borrowed-verification trio — test-plan check, base-tree A/B, per-hunk probes

- qwen review test-plan: rule on the PR Test Plan's checkable claims (paths,
  npm scripts, test counts) against the reviewed tree; contradictions and
  differing counts are disclosed via compose-review, never capping.
- qwen review base-tree: build the merge base in a sibling worktree so the
  verifier can A/B a comparative claim instead of reading it; swept by cleanup.
- test-efficacy: third probe kind — reverse-apply one hunk at a time and
  re-run the affected tests, attributing a still-green suite to the specific
  change nothing gates; shares the mutants' budget window, runs last.

* fix(review): survive real runner output — ANSI-laced and trimmed-away summaries

Both measured on a live /review of QwenLM#8176 with the built CLI:

- test-plan's observedTestCounts strips SGR sequences before matching; a
  color-enabled pipe interleaves them BETWEEN tokens, and the count claim
  fell to 'unchecked' with the summary right there in the report.
- build-test's trimOutput rescues runner summary lines from the omitted
  middle (like module-resolution errors): a failing suite's tail is all
  failure details and npm epilogue, which pushed the one-line summary out
  of the kept text entirely.

* fix(review): address the eight findings from live review of this branch

All measured in the review (QwenLM#8215 review comment):

- test-plan: linear-time bold-heading scan (the old pattern backtracked
  catastrophically on an unclosed ** line an untrusted PR body controls);
  a flag preceding the npm script yields no claim instead of a false
  'no package defines this script'.
- test-efficacy: a hunk probe's restore recreates the parent directory a
  reverse-applied 'new file' hunk removed (the ENOENT from finally lost
  the verdict and marked every remaining hunk inconclusive); hunks get
  their own skippedForBaseline instead of mislabeling a red baseline as
  a budget skip; splitDiffIntoHunks re-captures the file header at every
  diff --git boundary; a hunk-survived finding notes when it restates an
  inert file-level revert at hunk granularity.
- base-tree: idempotent fast path keyed on a build marker + HEAD check —
  concurrent verifier shards reuse one built tree instead of sweeping it
  out from under each other mid-A/B (a fabricated base-side difference
  with a deterministic source tag was the worst case); cost wording is
  now 'an install and a build' everywhere it was 'one extra build'.

* fix(cli): never score a hunk survived when its own test left the baseline (QwenLM#8215)

A per-hunk probe reported `survived` whenever the green baseline probes still
passed with the hunk reverted. When the hunk's own collocated test dropped out
of the baseline (a probe-tree import error collects nothing), the remaining
green probes prove only that THEY do not cover the hunk, so the verdict is now
`inconclusive` — the same dropped-test asymmetry the mutants already hold.

Also scope the hunk-survived cross-reference note to the hunk's own collocated
test, and let test-plan match a workspace-scoped run of the plan's bare command
instead of falling through to the manifest on an exact-string miss.

* fix(review): silence-bias hardening from four live review rounds of this branch

The two blocking findings, reproduced on this PR's own Test Plan:

- test-plan files no false contradicted notes: npm rulings move from a
  four-verb denylist to an allowlist (the run form + npm's script aliases —
  the ~fifty other builtins each used to become 'no package defines this
  script'); a slash token is claimed as a repo path only with evidence (an
  extension or ./ prefix), never when it is a flag's value (--repo
  owner/repo) or under the review's own temp root; HEADING_LINE_RE drops
  the same quadratic shape its bold sibling was rewritten to remove.
- base-tree gets a real mutual-exclusion lock around sweep+add+build
  (mkdirSync test-and-set; the loser returns busy instead of deleting the
  tree the winner is mid-install in), and a failed build writes a settled
  marker so later shards stop re-paying the install to relearn
  'unavailable'.

Also: Agent 7's brief now names hunk-survived and the hunks.* counters
(it is the report's only consumer, and the finding class was invisible);
hunk findings anchor at the first ADDED line instead of up to three
context lines above the change.

* feat(review): four round-2 borrowings — measured failure attribution, round ledger, richer mutants, doc parity

Shaped by a live round-2 maintainer re-verification (QwenLM#7818):

- qwen review test-delta: rerun the PR side's failed test commands on the
  built merge base and diff the failing FILE SETS — netNew is the PR's own
  failure by measurement (whatever files the diff touches), shared is
  pre-existing by measurement. Counts are never compared: a flaky suite
  fails different test names between runs of the same tree. An unfinished
  base rerun attributes nothing.
- Round ledger: the incremental review cache persists confirmed findings
  under round-scoped ids (R1-2); a high-effort re-review rules on each
  (fixed / still stands / cannot tell) and opens its report with the table,
  the way a human round-2 comment opens with 'M1 is fixed'.
- Three replacement mutation operators in test-efficacy: drop '?? fallback',
  force a comparison-bearing guard condition to 'true', drop a '+ CONST'
  term. Each survivor maps to one crisp untested-protection sentence.
  A line whose raw text and literal-blanked code view disagree yields no
  candidate — an edit index computed across the two views once spliced
  'iftrue 0)' into a guard, and a mangled mutant reads as inconclusive
  while quietly spending a cap slot.
- Quality brief: documentation-parity lens — a new user-facing surface whose
  siblings are documented is a Suggestion naming the sibling precedent; no
  documented sibling, no finding.

* fix(review): address review feedback — false-positive hardening, binary diff guard, error convention (QwenLM#8215)

* fix(review): address review feedback — base-tree availability gate, test-plan false positives, hunk-probe ranges (QwenLM#8215)

- base-tree: only stamp a base tree available when runBuildTest actually
  compiled something (ok AND npm toolchain AND a non-empty build). An
  `unsupported` handoff or an empty npm scope returns ok:true having built
  nothing; marking that tree available let an A/B read the absence of a build
  as a behavioural difference.
- cleanup: sweep the stale base-tree build lock a killed builder leaves behind.
- test-plan: read the root manifest's scripts directly so a root-only script
  survives when the root defines no build/test; bail on the inline --root=./dir
  rebasing form; stop treating a positional after an inline --flag=value as the
  flag's value; prefer a failed scoped run when ruling a bare command; anchor
  the npm script alias to a full token so `yarn test:unit` is not truncated.
- test-efficacy: exclude `\ No newline at end of file` from the startLine offset
  count; compute the mutant-overlap range from the header's new-side span so it
  no longer overshoots into a closely following hunk.

* fix(review): address review feedback — diff-header false positives, stale prompt enumeration, added-file hunk probes (QwenLM#8215)

* fix(review): address review feedback — cd-base exclusion, Test Files count guard, base-tree error handling, probe delegation (QwenLM#8215)

* fix(review): port the collocated-dropout test to the post-QwenLM#8050 runner seam

Merging main brought QwenLM#8050's Windows-portability refactor, which resolves
the probe runner through vitest/package.json's bin — a node_modules/.bin
fake is dead weight it never reads. The 8215-only collocated-dropout test
still installed the old .bin fake, so the REAL vitest ran its fixtures,
price.test.ts genuinely passed, and the hunk scored survived. The test now
overrides the fake package's vitest.mjs like every post-refactor test.

* fix(review): bound the summary rescue, apply the ATX heading rule, sweep stale build locks

The three 8215-layer findings from the latest review, fixed at this
layer (they were first patched further up the stack, where the reviewer
of THIS PR cannot see them):

- trimOutput's summary rescue is capped at 40 lines — uncapped, 40k
  lines of 'Test <n>: …' prose voided the trim entirely (measured 1.6MB
  in, 1.6MB out) and the bounded-output contract is the whole point.
- A '#' with no following whitespace is prose, not a heading (the ATX
  rule GitHub applies): 'QwenLM#8176', '#tag', an unfenced '#!/bin/bash' no
  longer end the Test Plan section mid-body; the bare-#-run crash on
  the closing scan is guarded.
- A base-tree build lock older than 30 minutes is a corpse left by a
  killed builder — swept and rebuilt instead of reporting busy for the
  rest of the review.

* fix(review): EEXIST-only lock busy, bun test alias, chained cd bail, fence backreference

Four live findings from the latest inline review round (the rest of the
round was already fixed upstream by the takeover bot - verified by
probing head behavior rather than re-reading the threads):

- base-tree's lock catch distinguishes EEXIST (a concurrent builder,
  busy) from EPERM/EROFS/ENOSPC (this run's own failure, reported as
  such, not as a busy that will never clear).
- "bun test" is bun's built-in runner, not a package-script alias: it
  runs whether or not any manifest defines test, so ruling it against
  the scripts table filed a false contradicted.
- A chained cd matches the leading-cd shape but the single-hop resolver
  joined file tokens against the FIRST directory; it now bails like the
  exotic-cd case.
- codeSpans' fence regex closes on its own marker via backreference; a
  tilde fence line inside a backtick block ended the span early and
  lines after it were lost to extraction.

* fix(review): close the ten open findings on this PR

- guard-true tested for a comparison anywhere after `if (`, including the
  then-body, so `if (ready) emit(a !== b);` admitted a mutant on the
  comparison-less condition the gate exists to exclude. It now tests the
  condition span only.
- The `survived` detail said "when it changes" for legacy DELETION
  mutants too; it now matches the operator.
- test-delta's `unparsed` required both sides to parse zero files, so a
  PR-side failure whose FAIL lines the trim scattered was silently
  dropped whenever the base rerun happened to parse. netNew/shared come
  from the PR side, so the PR side alone decides.
- failingFilesOf now matches Windows path shapes (backslashes, C:) - a
  missed parse is an unattributed failure, not a loud error.
- The replacement branch of runOneMutant (write-file -> run-probe ->
  classify) had no end-to-end test; one now drives a coalesce operator
  through the real handler and asserts the mutated line, the verdict,
  the operator-specific wording, and that the shared tree is untouched.
- Two tests were vacuous with respect to what they promised: the
  baseline-dir test never asserted the cwd (its helper swallowed the
  argument - fixed at the helper), and the one-candidate-per-line test
  used an input that never triggered the replacement path, so the
  `continue` under test was not load-bearing.
- Reattached the orphaned selectMutants JSDoc; reworded the SKILL line.

* fix(review): the test helper's cwd parameter is required, not optional

CI's `tsc --build` failed on test-delta.test.ts: the exec seam always
passes a cwd, but the helper's signature marked it optional, so pushing
it into a string[] was `string | undefined`.

Missed locally because vitest runs through esbuild, which strips types
without checking them - the suite was green while the build was red. The
gate to run before pushing a type-level change is `npx tsc --build`, not
the test suite.

* fix(review): a base rerun that could not RUN attributes nothing

Two Criticals from the latest review, both reachable on the brief's own
happy path:

- baseUnusable covered only timeouts. Every other way the base side can
  fail to run - an unbuilt base tree, a missing install, a workspace the
  PR ADDED (npm test --workspace cannot resolve on base), an ENOBUFS
  truncation - exits non-zero with zero FAIL lines, which this code read
  as a green base. Every PR-side failure then became netNew: the
  strongest evidence the command emits, manufactured from a base that
  never ran a test. It now attributes nothing and says why.
- Timeout detection was the weaker substring form the sibling explicitly
  rejects; an external SIGTERM (container stop, cancelled job) set
  neither an ETIMEDOUT message nor an exit code and fed straight into
  the above. build-test now exports spawnTimedOut and test-delta asks
  the same question rather than re-deriving it.

Also: the base output is trimmed (it precedes the verdict fields in the
report the agent reads, so an untrimmed megabyte truncates exactly what
the command produces); the guard-true gate no longer reads an arrow
function's => as a comparison (every predicate guard was a candidate -
the if (ready) noise the gate exists to exclude); the term-drop message
no longer calls a string concatenation a reserve term; the unparsed note
describes its own PR-side-only condition; and the ledger's Step 6/Step 8
now agree that a still-standing finding keeps its id.

* fix(review): compare failing files by a normalised, project-keyed identity

Critical: the two sides run in DIFFERENT roots (the PR worktree and the
base tree), and netNew/shared compared the parsed paths verbatim - so an
absolute-path runner turned every pre-existing failure into a fabricated
Critical, with the authority of a measurement behind it. Paths are now
normalised against each run's own root (and backslashes to /, so a
Windows path compares with its POSIX-printed twin), which is why
test-delta gained --pr-worktree.

The identity also keeps the vitest project token: dropping it collapsed
same-named test files across workspaces, so a PR-caused failure in one
package could read as pre-existing because another package has a file by
the same name - the worse failure direction.

Also from the same review, all of them reachable on the brief's own path:

- The base rerun now inherits build-test's stdio: ['ignore','pipe','pipe']
  ("a build that asks a question is a build that hangs until the
  deadline") and its trimOutput, which matters because entries[].base
  precedes the verdict fields in the report the agent reads.
- The brief gates on base-tree's `available`, not just its `path`: a tree
  that was created but did not build populates path too, and measuring
  against it turns an infrastructure failure into Criticals.
- A programmatic caller omitting `timeout` no longer sends NaN into
  spawnSync.
- MutantCandidate is a discriminated union, so an operator without its
  replacement line - which would delete a line while reporting "with its
  ?? fallback dropped" - is unrepresentable.
- The comparison class no longer requires a trailing space (if (a<b) is
  the same guard, just unformatted) and matches a brace-less else if.
- DeltaEntry.unparsed's doc now describes the PR-side-only condition it
  actually implements.

* fix(review): restore the whole-command budget, keep generics out of guard-true

Round-1 findings from a fresh review of this PR:

- test-delta had no aggregate deadline: --timeout is PER command and
  defaults to 300s, so three failed commands is 900s against Agent 7's
  600s ceiling - killed with NO report at all, discarding the base-tree
  install and build just paid for. TOTAL_BUDGET_MS mirrors the one
  test-efficacy reserves; commands it cannot fit are disclosed.
- guard-true matched generic calls: `if (isRecord<string>(v))` produced a
  mutant, and a type-guard predicate is exactly the `if (ready)` shape
  whose survivors the gate calls noise. The trailing \s is required, not
  an accidental asymmetry with [!=]== - telling `a<b` from `fn<T>(x)`
  needs a parser, and the gate is silence-biased by design.
- --pr-worktree had no contract test, and its failure mode is the worst
  here: arriving undefined, root stripping silently stops and every
  pre-existing failure becomes a fabricated netNew. The new test feeds
  parseSync's output straight into runTestDelta and asserts an
  attribution only reachable when both roots were stripped (verified
  red against the snake_case field shape that shipped once already).
- Merged the two consecutive doc comments on prWorktree.

* fix(review): a budget-shortened deadline is not the same fact as a slow rerun

Round-2 finding on the budget just restored: `Math.min(perCommandMs,
remaining)` can hand a rerun far less than --timeout, and if it dies
there the note said only "timed out - infrastructure, not evidence".
True, but it sends the reader hunting a hang that is really an exhausted
budget - and unlike a real timeout, a rerun with budget to spare would
still measure it. The note now names those commands separately and says
so. Verified red against removing the tracking line.

* fix(review): restore the replacement sub-cap, stranded on a downstream branch

Round-3 finding, and the third instance of one class: an 8218-layer fix
committed on the 8261 branch, four PRs above the code it belongs to.

Measured over 40 real commits, the replacement operators produce ~24x
the deletion pool (215 vs 9 candidates; guard-true drives it). Every
mutant run drains the same window hunk probes draw from LAST, so
uncapped, most diffs with any replacement candidates leave hunk probing
zero runs - the hunk-survived finding class silently stops firing and
nothing says so. Three slots, and what the sub-cap drops is counted in
skippedForCap rather than lost.

Also swept the other direction: diffed every review file against its
8261 copy to confirm nothing else 8218-layer is stranded up there. The
remaining divergence is 8261's own (the positive control, its lenses).

* docs(review): complete the "delta cannot rule" enumeration in both places

Round-4 finding. The brief and SKILL.md each listed three cases where
test-delta attributes nothing - unparsed, timed-out base, no merge base -
but the code has five: the later rounds of this PR added "a base rerun
that failed without naming any failing file" (it did not measure the
base) and "a command the whole-command budget could not fit". Two
enumerations of the same set with different membership, in the two
places an agent reads.

That is the sibling-enumeration lesson this skill teaches, applied to
its own prose for the second time: the fix is not just adding the
missing members but saying that the report names each case with its own
reason rather than folding them into one.

* docs(review): the rationale named only one of the ways base goes unmeasured

Third and last copy of the enumeration the previous commit fixed. The
bullet's headline already generalised - "base attributes nothing it did
not finish" - but its body named only the timeout, so a reader learning
the contract from the rationale would conclude timeouts are the only
unusable case. Name the set, and say why the report keeps the reasons
apart: "we could not measure" and "we measured nothing" are different
facts to the author, and only one of them is about their PR.

* fix(review): a file-count label stops counting at the end of its line

`Test Files  45 passed` filing its 45 as a differing TEST count was
fixed once, with a lookbehind on the bare-count pattern. That only ever
rejected the all-green shape. The moment any file fails, the runner
prints `Test Files  1 failed | 44 passed (45)`, the label is no longer
adjacent to the number, and 44 comes through as a test count - so the
note reads "claimed 44, observed 1323" on exactly the runs whose summary
someone would paste. Adjacency was the wrong invariant; the line is.

Masking from the label to end-of-line is distance-independent and picks
up jest's `Test Suites: 1 failed, 44 passed, 45 total` at no cost. The
label keeps its `Test` word on purpose: a first cut matched a bare
`files` and blanked the line in "expect all four files and 471 tests to
pass", silencing a real claim. An existing test caught that, which is
the argument for the rule being as narrow as it is - anything that
suppresses claims is worth exactly its narrowness.

Also drops the now-dead lookbehind, which a reviewer had separately (and
wrongly) called a JS syntax error; variable-length lookbehind is legal
in V8, and the module parsed fine. It goes because the line rule
subsumes it, not because it was broken.

* fix(review): parse the base rerun before its output is trimmed

`trimOutput` rescues module errors and runner summaries out of the
omitted middle, not the per-file FAIL lines this command reads. A base
suite whose failure section overruns the tail budget therefore lost
failing files into the gap - and a SHORT base set is the dangerous
direction, because netNew is the PR side minus the base side. Every file
the trim hid came back as a Critical attributed to this PR by
"measurement". Parse the raw text, report the bounded one.

The PR side cannot be fixed here: it is read out of build-test's stored
output, trimmed before this command existed. That loss runs the other
way - it understates `shared`, never invents a netNew - so the entry
carries `prTruncated` and the note says the list may be partial. A
silence-biased gap is still a gap the author should hear about.

Also names both selection caps in the mutant-skip diagnostic. The count
accumulates replacement sub-cap drops, and with 2 deletions and 6
replacements the total is exactly MAX_MUTANTS: the main cap never fires,
yet 3 are dropped, and the message sent the reader looking for a pool of
11 candidates that never existed.

* fix(review): rerun only the command shapes build-test emits

This command reads a report off disk and then executes the strings in it
with `shell: true`, in the base worktree. Nothing else in the pipeline
re-executes a value it read back from a file, so nothing else has to
care where that value came from - this does, and the provenance is worse
than it looks: the command is `npm test --workspace="<dir>"`, the
workspace token is a directory, and a directory is a name a pull request
chooses. `packages/x";curl …|sh;"` is a legal path in git and on Linux
and it round-trips through the report into a shell.

Restricting to the emitter's own grammar costs nothing real, since that
grammar is the two shapes build-test produces. A command outside it is
skipped and disclosed, the same treatment everything else this command
cannot do already gets, so a future shape degrades to "judge it by the
diff" rather than to arbitrary execution.

---------

Co-authored-by: qwen-code-dev-bot <qwen-code-dev@service.alibaba.com>
Co-authored-by: Qwen Code <qwen-code@users.noreply.github.com>
Co-authored-by: Qwen Code Bot <qwen-code-bot@users.noreply.github.com>
Co-authored-by: Qwen Code Autofix <qwen-code-autofix@users.noreply.github.com>
pull Bot pushed a commit to mcx/qwen-code that referenced this pull request Aug 1, 2026
…rification lenses (QwenLM#8225)

* feat(review): borrowed-verification trio — test-plan check, base-tree A/B, per-hunk probes

- qwen review test-plan: rule on the PR Test Plan's checkable claims (paths,
  npm scripts, test counts) against the reviewed tree; contradictions and
  differing counts are disclosed via compose-review, never capping.
- qwen review base-tree: build the merge base in a sibling worktree so the
  verifier can A/B a comparative claim instead of reading it; swept by cleanup.
- test-efficacy: third probe kind — reverse-apply one hunk at a time and
  re-run the affected tests, attributing a still-green suite to the specific
  change nothing gates; shares the mutants' budget window, runs last.

* fix(review): survive real runner output — ANSI-laced and trimmed-away summaries

Both measured on a live /review of QwenLM#8176 with the built CLI:

- test-plan's observedTestCounts strips SGR sequences before matching; a
  color-enabled pipe interleaves them BETWEEN tokens, and the count claim
  fell to 'unchecked' with the summary right there in the report.
- build-test's trimOutput rescues runner summary lines from the omitted
  middle (like module-resolution errors): a failing suite's tail is all
  failure details and npm epilogue, which pushed the one-line summary out
  of the kept text entirely.

* fix(review): address the eight findings from live review of this branch

All measured in the review (QwenLM#8215 review comment):

- test-plan: linear-time bold-heading scan (the old pattern backtracked
  catastrophically on an unclosed ** line an untrusted PR body controls);
  a flag preceding the npm script yields no claim instead of a false
  'no package defines this script'.
- test-efficacy: a hunk probe's restore recreates the parent directory a
  reverse-applied 'new file' hunk removed (the ENOENT from finally lost
  the verdict and marked every remaining hunk inconclusive); hunks get
  their own skippedForBaseline instead of mislabeling a red baseline as
  a budget skip; splitDiffIntoHunks re-captures the file header at every
  diff --git boundary; a hunk-survived finding notes when it restates an
  inert file-level revert at hunk granularity.
- base-tree: idempotent fast path keyed on a build marker + HEAD check —
  concurrent verifier shards reuse one built tree instead of sweeping it
  out from under each other mid-A/B (a fabricated base-side difference
  with a deterministic source tag was the worst case); cost wording is
  now 'an install and a build' everywhere it was 'one extra build'.

* fix(cli): never score a hunk survived when its own test left the baseline (QwenLM#8215)

A per-hunk probe reported `survived` whenever the green baseline probes still
passed with the hunk reverted. When the hunk's own collocated test dropped out
of the baseline (a probe-tree import error collects nothing), the remaining
green probes prove only that THEY do not cover the hunk, so the verdict is now
`inconclusive` — the same dropped-test asymmetry the mutants already hold.

Also scope the hunk-survived cross-reference note to the hunk's own collocated
test, and let test-plan match a workspace-scoped run of the plan's bare command
instead of falling through to the manifest on an exact-string miss.

* fix(review): silence-bias hardening from four live review rounds of this branch

The two blocking findings, reproduced on this PR's own Test Plan:

- test-plan files no false contradicted notes: npm rulings move from a
  four-verb denylist to an allowlist (the run form + npm's script aliases —
  the ~fifty other builtins each used to become 'no package defines this
  script'); a slash token is claimed as a repo path only with evidence (an
  extension or ./ prefix), never when it is a flag's value (--repo
  owner/repo) or under the review's own temp root; HEADING_LINE_RE drops
  the same quadratic shape its bold sibling was rewritten to remove.
- base-tree gets a real mutual-exclusion lock around sweep+add+build
  (mkdirSync test-and-set; the loser returns busy instead of deleting the
  tree the winner is mid-install in), and a failed build writes a settled
  marker so later shards stop re-paying the install to relearn
  'unavailable'.

Also: Agent 7's brief now names hunk-survived and the hunks.* counters
(it is the report's only consumer, and the finding class was invisible);
hunk findings anchor at the first ADDED line instead of up to three
context lines above the change.

* feat(review): four round-2 borrowings — measured failure attribution, round ledger, richer mutants, doc parity

Shaped by a live round-2 maintainer re-verification (QwenLM#7818):

- qwen review test-delta: rerun the PR side's failed test commands on the
  built merge base and diff the failing FILE SETS — netNew is the PR's own
  failure by measurement (whatever files the diff touches), shared is
  pre-existing by measurement. Counts are never compared: a flaky suite
  fails different test names between runs of the same tree. An unfinished
  base rerun attributes nothing.
- Round ledger: the incremental review cache persists confirmed findings
  under round-scoped ids (R1-2); a high-effort re-review rules on each
  (fixed / still stands / cannot tell) and opens its report with the table,
  the way a human round-2 comment opens with 'M1 is fixed'.
- Three replacement mutation operators in test-efficacy: drop '?? fallback',
  force a comparison-bearing guard condition to 'true', drop a '+ CONST'
  term. Each survivor maps to one crisp untested-protection sentence.
  A line whose raw text and literal-blanked code view disagree yields no
  candidate — an edit index computed across the two views once spliced
  'iftrue 0)' into a guard, and a mangled mutant reads as inconclusive
  while quietly spending a cap slot.
- Quality brief: documentation-parity lens — a new user-facing surface whose
  siblings are documented is a Suggestion naming the sibling precedent; no
  documented sibling, no finding.

* feat(review): render adjudication, workflow step extraction, three verification lenses

Shaped by a live sanitizer-PR verification (QwenLM#8147):

- Render-adjudication capability (opt-in): with QWEN_REVIEW_SCRATCH_REPO
  set, the verifier may post a minimal payload to that user-designated repo
  and rule on GitHub's own rendered HTML — the measured case being an
  @ -> &#64; defusal every local reading called sound while GitHub's real
  renderer registered the mention and fired the notification. Absent the
  setting, rendering claims honestly cap at low confidence / cannot tell.
  Step 7's write ban names the carve-out explicitly.
- qwen review extract-step: lift one workflow step's run: script verbatim
  into an executable, with env (as comments, never half-substituted
  exports), every ${{ }} site listed unevaluated, and a heuristic invoked-
  command list as the stubbing starting point. With base-tree, both arms of
  a by-hand workflow A/B become two invocations. yaml declared as a cli
  dependency (previously resolved only via hoisting).
- Three brief lenses: a borrowed protection idiom missing what made it work
  at home (the code ancestor did the protecting; only the entity was
  copied); a second parser for an authoritatively-parsed format is a
  divergence hunt; tests that pin the mechanism instead of the effect, and
  oracles that mirror the implementation's own model.

* feat(review): sibling-entrance discipline for the fixed verdict

From round 6 of the live sanitizer verification (QwenLM#8147):
the fix closed the fence-shaped entrance into a raw-HTML block, and the
code-span entrance beside it — same divergence, adjacent syntax — stayed
open. A re-check that tests only the reported input rules 'fixed' over a
hole one backtick away.

Both fixed-verdict sites in SKILL Step 6 (the open-Criticals re-check and
the round ledger) now require enumerating a divergence-class defect's
sibling entrances before ruling fixed; a still-open sibling is a NEW
finding, never a reason to withhold the original's fixed — the two
rulings stay separate so the second hole cannot ship unreviewed.

* feat(review): three measured-verification lenses from live rounds 8037/8005

- Threshold-boundary scan: when a fix is a ratio/length guard, hold the
  issue's own variables fixed and binary-search the boundary where the
  behaviour flips; put the number next to what the issue reports. Live
  case: a prose-ratio guard covered the edit/write_file half of its issue
  and silently declined the run_shell_command half (~473-char boundary).
- Delimiter self-injection named as the first parser-differential probe:
  a no-escaping extractor fed its own close tag truncates silently.
- Shared-gate state enumeration: a deliberate-design defence extends only
  to the states it argues — an input-hold argued for 'active' silently
  froze three idle states sharing the same gate. The sibling-entrance
  rule, applied to a state machine instead of a syntax.

* fix(review): address review feedback — false-positive hardening, binary diff guard, error convention (QwenLM#8215)

* fix(review): address review feedback — base-tree availability gate, test-plan false positives, hunk-probe ranges (QwenLM#8215)

- base-tree: only stamp a base tree available when runBuildTest actually
  compiled something (ok AND npm toolchain AND a non-empty build). An
  `unsupported` handoff or an empty npm scope returns ok:true having built
  nothing; marking that tree available let an A/B read the absence of a build
  as a behavioural difference.
- cleanup: sweep the stale base-tree build lock a killed builder leaves behind.
- test-plan: read the root manifest's scripts directly so a root-only script
  survives when the root defines no build/test; bail on the inline --root=./dir
  rebasing form; stop treating a positional after an inline --flag=value as the
  flag's value; prefer a failed scoped run when ruling a bare command; anchor
  the npm script alias to a full token so `yarn test:unit` is not truncated.
- test-efficacy: exclude `\ No newline at end of file` from the startLine offset
  count; compute the mutant-overlap range from the header's new-side span so it
  no longer overshoots into a closely following hunk.

* fix(review): address review feedback — diff-header false positives, stale prompt enumeration, added-file hunk probes (QwenLM#8215)

* fix(review): address review feedback — cd-base exclusion, Test Files count guard, base-tree error handling, probe delegation (QwenLM#8215)

* fix(review): port the collocated-dropout test to the post-QwenLM#8050 runner seam

Merging main brought QwenLM#8050's Windows-portability refactor, which resolves
the probe runner through vitest/package.json's bin — a node_modules/.bin
fake is dead weight it never reads. The 8215-only collocated-dropout test
still installed the old .bin fake, so the REAL vitest ran its fixtures,
price.test.ts genuinely passed, and the hunk scored survived. The test now
overrides the fake package's vitest.mjs like every post-refactor test.

* fix(review): bound the summary rescue, apply the ATX heading rule, sweep stale build locks

The three 8215-layer findings from the latest review, fixed at this
layer (they were first patched further up the stack, where the reviewer
of THIS PR cannot see them):

- trimOutput's summary rescue is capped at 40 lines — uncapped, 40k
  lines of 'Test <n>: …' prose voided the trim entirely (measured 1.6MB
  in, 1.6MB out) and the bounded-output contract is the whole point.
- A '#' with no following whitespace is prose, not a heading (the ATX
  rule GitHub applies): 'QwenLM#8176', '#tag', an unfenced '#!/bin/bash' no
  longer end the Test Plan section mid-body; the bare-#-run crash on
  the closing scan is guarded.
- A base-tree build lock older than 30 minutes is a corpse left by a
  killed builder — swept and rebuilt instead of reporting busy for the
  rest of the review.

* fix(review): EEXIST-only lock busy, bun test alias, chained cd bail, fence backreference

Four live findings from the latest inline review round (the rest of the
round was already fixed upstream by the takeover bot - verified by
probing head behavior rather than re-reading the threads):

- base-tree's lock catch distinguishes EEXIST (a concurrent builder,
  busy) from EPERM/EROFS/ENOSPC (this run's own failure, reported as
  such, not as a busy that will never clear).
- "bun test" is bun's built-in runner, not a package-script alias: it
  runs whether or not any manifest defines test, so ruling it against
  the scripts table filed a false contradicted.
- A chained cd matches the leading-cd shape but the single-hop resolver
  joined file tokens against the FIRST directory; it now bails like the
  exotic-cd case.
- codeSpans' fence regex closes on its own marker via backreference; a
  tilde fence line inside a backtick block ended the span early and
  lines after it were lost to extraction.

* fix(review): close the ten open findings on this PR

- guard-true tested for a comparison anywhere after `if (`, including the
  then-body, so `if (ready) emit(a !== b);` admitted a mutant on the
  comparison-less condition the gate exists to exclude. It now tests the
  condition span only.
- The `survived` detail said "when it changes" for legacy DELETION
  mutants too; it now matches the operator.
- test-delta's `unparsed` required both sides to parse zero files, so a
  PR-side failure whose FAIL lines the trim scattered was silently
  dropped whenever the base rerun happened to parse. netNew/shared come
  from the PR side, so the PR side alone decides.
- failingFilesOf now matches Windows path shapes (backslashes, C:) - a
  missed parse is an unattributed failure, not a loud error.
- The replacement branch of runOneMutant (write-file -> run-probe ->
  classify) had no end-to-end test; one now drives a coalesce operator
  through the real handler and asserts the mutated line, the verdict,
  the operator-specific wording, and that the shared tree is untouched.
- Two tests were vacuous with respect to what they promised: the
  baseline-dir test never asserted the cwd (its helper swallowed the
  argument - fixed at the helper), and the one-candidate-per-line test
  used an input that never triggered the replacement path, so the
  `continue` under test was not load-bearing.
- Reattached the orphaned selectMutants JSDoc; reworded the SKILL line.

* fix(review): the test helper's cwd parameter is required, not optional

CI's `tsc --build` failed on test-delta.test.ts: the exec seam always
passes a cwd, but the helper's signature marked it optional, so pushing
it into a string[] was `string | undefined`.

Missed locally because vitest runs through esbuild, which strips types
without checking them - the suite was green while the build was red. The
gate to run before pushing a type-level change is `npx tsc --build`, not
the test suite.

* fix(review): a base rerun that could not RUN attributes nothing

Two Criticals from the latest review, both reachable on the brief's own
happy path:

- baseUnusable covered only timeouts. Every other way the base side can
  fail to run - an unbuilt base tree, a missing install, a workspace the
  PR ADDED (npm test --workspace cannot resolve on base), an ENOBUFS
  truncation - exits non-zero with zero FAIL lines, which this code read
  as a green base. Every PR-side failure then became netNew: the
  strongest evidence the command emits, manufactured from a base that
  never ran a test. It now attributes nothing and says why.
- Timeout detection was the weaker substring form the sibling explicitly
  rejects; an external SIGTERM (container stop, cancelled job) set
  neither an ETIMEDOUT message nor an exit code and fed straight into
  the above. build-test now exports spawnTimedOut and test-delta asks
  the same question rather than re-deriving it.

Also: the base output is trimmed (it precedes the verdict fields in the
report the agent reads, so an untrimmed megabyte truncates exactly what
the command produces); the guard-true gate no longer reads an arrow
function's => as a comparison (every predicate guard was a candidate -
the if (ready) noise the gate exists to exclude); the term-drop message
no longer calls a string concatenation a reserve term; the unparsed note
describes its own PR-side-only condition; and the ledger's Step 6/Step 8
now agree that a still-standing finding keeps its id.

* fix(review): extract-step resolves all three env/defaults levels, and comments every env line

Two silent-wrongness defects in a command whose whole value is fidelity.

`env:`, `shell:` and `working-directory:` are three-level settings on GitHub —
workflow, job, step, nearest wins — and only the step level appears in the
step's own text. Reading step-level alone reproduced by machine the exact
transcription error this command exists to remove: measured, a step under a
job-level `NODE_ENV: production` and a workflow-level `GLOBAL_FLAG` extracted
with `env: { LOCAL: '1' }` and `workingDirectory: undefined`, so the emitted
script ran with both unset and nothing said so. Not a contrived shape: this
repo carries workflow-level `env:` in 7 workflows, job-level `env:` in 10, and
job-level `defaults.run` in qwen-triage.yml — the workflow the command's own
test plan names. The three levels now merge with the runner's precedence, and
`envSources` records which level each key came from, so an inherited value is
visible rather than indistinguishable from the step's own.

The env block was commented per ENTRY, not per LINE. A YAML block scalar
(qwen-autofix.yml's `SETTINGS_JSON: |-`) reaches the header as a multi-line
string, so its continuation lines landed in command position — and under the
`set -e` the header itself emits, the extracted step died in its own preamble
before its `run:` body ran. Every line is commented now.

Tests pin the effect, not the mechanism: `executableLines()` asserts nothing
but the `run:` body ever reaches command position, plus a `bash -n` parse
check. Verified to flip — all five new assertions fail against the pre-fix
implementation (`{ LOCAL: '1' }`, `undefined` working directory, three
executable lines instead of one, and a real `bash -n` syntax error).

* fix(review): compare failing files by a normalised, project-keyed identity

Critical: the two sides run in DIFFERENT roots (the PR worktree and the
base tree), and netNew/shared compared the parsed paths verbatim - so an
absolute-path runner turned every pre-existing failure into a fabricated
Critical, with the authority of a measurement behind it. Paths are now
normalised against each run's own root (and backslashes to /, so a
Windows path compares with its POSIX-printed twin), which is why
test-delta gained --pr-worktree.

The identity also keeps the vitest project token: dropping it collapsed
same-named test files across workspaces, so a PR-caused failure in one
package could read as pre-existing because another package has a file by
the same name - the worse failure direction.

Also from the same review, all of them reachable on the brief's own path:

- The base rerun now inherits build-test's stdio: ['ignore','pipe','pipe']
  ("a build that asks a question is a build that hangs until the
  deadline") and its trimOutput, which matters because entries[].base
  precedes the verdict fields in the report the agent reads.
- The brief gates on base-tree's `available`, not just its `path`: a tree
  that was created but did not build populates path too, and measuring
  against it turns an infrastructure failure into Criticals.
- A programmatic caller omitting `timeout` no longer sends NaN into
  spawnSync.
- MutantCandidate is a discriminated union, so an operator without its
  replacement line - which would delete a line while reporting "with its
  ?? fallback dropped" - is unrepresentable.
- The comparison class no longer requires a trailing space (if (a<b) is
  the same guard, just unformatted) and matches a brace-less else if.
- DeltaEntry.unparsed's doc now describes the PR-side-only condition it
  actually implements.

* fix(review): restore the whole-command budget, keep generics out of guard-true

Round-1 findings from a fresh review of this PR:

- test-delta had no aggregate deadline: --timeout is PER command and
  defaults to 300s, so three failed commands is 900s against Agent 7's
  600s ceiling - killed with NO report at all, discarding the base-tree
  install and build just paid for. TOTAL_BUDGET_MS mirrors the one
  test-efficacy reserves; commands it cannot fit are disclosed.
- guard-true matched generic calls: `if (isRecord<string>(v))` produced a
  mutant, and a type-guard predicate is exactly the `if (ready)` shape
  whose survivors the gate calls noise. The trailing \s is required, not
  an accidental asymmetry with [!=]== - telling `a<b` from `fn<T>(x)`
  needs a parser, and the gate is silence-biased by design.
- --pr-worktree had no contract test, and its failure mode is the worst
  here: arriving undefined, root stripping silently stops and every
  pre-existing failure becomes a fabricated netNew. The new test feeds
  parseSync's output straight into runTestDelta and asserts an
  attribution only reachable when both roots were stripped (verified
  red against the snake_case field shape that shipped once already).
- Merged the two consecutive doc comments on prWorktree.

* fix(review): a budget-shortened deadline is not the same fact as a slow rerun

Round-2 finding on the budget just restored: `Math.min(perCommandMs,
remaining)` can hand a rerun far less than --timeout, and if it dies
there the note said only "timed out - infrastructure, not evidence".
True, but it sends the reader hunting a hang that is really an exhausted
budget - and unlike a real timeout, a rerun with budget to spare would
still measure it. The note now names those commands separately and says
so. Verified red against removing the tracking line.

* fix(review): brace-tolerant stub list, pipefail fidelity, and extract-step in the briefs

Round-3 findings on this PR, fixed.

`expressionsOf` matched `[^}]*`, so any expression containing a brace —
`format('refs/pull/{0}/head', …)`, `fromJSON('{"a":1}')` — was not mis-listed
but DROPPED. A stub list reads as "these are all the values to supply", so a
silent omission is a value that never gets stubbed. It now scans forward to the
closing `}}`, and reports nothing for an unterminated site rather than
swallowing the rest of the text.

Declaring `shell: bash` is not the runner's default `bash`. The default is
`bash -e {0}`; a declared `bash` (at any level) is
`bash --noprofile --norc -eo pipefail {0}`, and a pipeline whose middle stage
fails aborts under one and not the other. The header now carries `set -eo
pipefail` or `set -e` accordingly — 163 of this repo's 434 `run:` steps are
under a declared bash and were getting the weaker one. A `shell:` value is also
a command template (`perl {0}`), so only its first word goes in the shebang and
the whole template is recorded beside it.

`extract-step` was registered on the CLI and mentioned in DESIGN.md, and
nowhere in SKILL.md or the agent briefs — the runtime prompts. The capability
was unreachable by the agents it was written for. The verifier's brief now
carries it next to the A/B paragraph it composes with, and Step 4 summarises it.

Also: env ordered nearest-first (measured on qwen-autofix.yml:route:0, merge
order put 20 inherited entries ahead of the step's own 26 in a 49-line header);
a valueless `FOO:` renders as the empty string, not `"null"`, and a non-scalar
as JSON rather than `[object Object]`; a missing file no longer reports as a
parse failure; DESIGN.md's lens count matches its list.

The test oracle is rebuilt around the property instead of a filter: the file is
the header plus the body verbatim, and every line before the body is a comment
or a directive the test names. The old helper dropped `set -e` unconditionally,
so it could not tell the header's from one the body legitimately contains — and
would have gone green on a header that leaked exactly that line. 434 real `run:`
steps swept: 0 non-verbatim bodies, 0 live header lines, 0 missed expression
sites, 0 out-of-order env, 0 `bash -n` failures.

* fix(review): restore the replacement sub-cap, stranded on a downstream branch

Round-3 finding, and the third instance of one class: an 8218-layer fix
committed on the 8261 branch, four PRs above the code it belongs to.

Measured over 40 real commits, the replacement operators produce ~24x
the deletion pool (215 vs 9 candidates; guard-true drives it). Every
mutant run drains the same window hunk probes draw from LAST, so
uncapped, most diffs with any replacement candidates leave hunk probing
zero runs - the hunk-survived finding class silently stops firing and
nothing says so. Three slots, and what the sub-cap drops is counted in
skippedForCap rather than lost.

Also swept the other direction: diffed every review file against its
8261 copy to confirm nothing else 8218-layer is stranded up there. The
remaining divergence is 8261's own (the positive control, its lenses).

* docs(review): complete the "delta cannot rule" enumeration in both places

Round-4 finding. The brief and SKILL.md each listed three cases where
test-delta attributes nothing - unparsed, timed-out base, no merge base -
but the code has five: the later rounds of this PR added "a base rerun
that failed without naming any failing file" (it did not measure the
base) and "a command the whole-command budget could not fit". Two
enumerations of the same set with different membership, in the two
places an agent reads.

That is the sibling-enumeration lesson this skill teaches, applied to
its own prose for the second time: the fix is not just adding the
missing members but saying that the report names each case with its own
reason rather than folding them into one.

* fix(review): the invokes list was mostly prose, not commands

Round-4 finding on this PR. `invokes` is documented as a heuristic starting
point, and imprecision is fine — but measured over this repo's 434 real `run:`
steps it was reporting 435 distinct "commands", 267 of them appearing exactly
once, with a worst case of 63 entries made up of words like `CI`, `Evidence`,
`PR` and `and`. A list that size, mostly prose, is not a starting point.

Three causes, each measured:

- A `${{ … }}` expression is not shell, and it routinely contains `||`.
  Splitting on that as a pipeline separator reported both operands as commands
  (`matrix.arch`, `github.event.inputs.version`). Expressions are now masked to
  an opaque token before the split; one sitting in command position contributes
  nothing, which is honest — what it expands to is unknown here by design.
- A heredoc body is input to a command, not a list of them. Its lines were
  scanned as commands, terminator included. 12 steps in this repo carry one.
- The `name=value` skip stepped over the prefix and took the NEXT word as the
  command — but for a quoted value with spaces that word is inside the value:
  `EVIDENCE_SECTION=$'### Evidence images'` reported `Evidence`. Quoted spans
  are now blanked out, with the quote carried across lines so a multi-line
  string's continuation lines are data too. Command substitutions are read
  first, so `body="$(sanitize < "$REPORT")"` still reports `sanitize`.

A `#` preceded by whitespace ends the live part of a line, so an apostrophe in
a trailing comment cannot open a span and eat the rest of the script.

Measured after: 435 distinct commands to 187, singletons 267 to 104, worst case
63 to 27 — and the worst case is now real commands (`awk cat chmod curl git jq
mktemp pkill tar tee timeout`) plus the script's own shell functions. Also
added the builtins a stub could not intercept anyway (`eval`, `exec`, `source`,
`unset`, `command`, …) to the keyword set.

434 steps re-swept: 0 non-verbatim bodies, 0 live header lines, 0 missed
expression sites, 0 out-of-order env, 0 `bash -n` failures.

* docs(review): the rationale named only one of the ways base goes unmeasured

Third and last copy of the enumeration the previous commit fixed. The
bullet's headline already generalised - "base attributes nothing it did
not finish" - but its body named only the timeout, so a reader learning
the contract from the rationale would conclude timeouts are the only
unusable case. Name the set, and say why the report keeps the reasons
apart: "we could not measure" and "we measured nothing" are different
facts to the author, and only one of them is about their PR.

* fix(review): a quoted `<<EOF` is not a heredoc, and a continued line is one command

Round-5 findings, both in the previous commit's own scanner.

A heredoc opener was matched over the whole line, so one inside a string
started heredoc mode: `echo "write <<EOF for a heredoc"` made every later line
wait for a terminator that never arrives. The failure is not a missing entry
but a missing REST — measured, a three-line script returned `[]` instead of
`[curl, jq]`, empty and entirely plausible. Opener detection moved inside the
quote walk, where it only fires outside quotes; the quoted forms (`<<'EOF'`)
are consumed by the match, so their quotes never open a span either.

A backslash-continued command was scanned as several lines, which puts the next
ARGUMENT in command position — this is where `apt-get install -y \` /
`  libx11-dev` reported the package as an invoked command. Continuations are
now joined into one logical line before scanning.

Measured after: 187 distinct commands to 185, and the singleton tail is now
dominated by real ones — PowerShell cmdlets, macOS tooling, and the scripts'
own shell functions. 434 real steps re-swept: 0 non-verbatim bodies, 0 live
header lines, 0 missed expression sites, 0 out-of-order env, 0 `bash -n`
failures.

* fix(review): case labels, a second heredoc, and an expression in command position

Round-6 findings, from running the scanner against adversarial shapes rather
than reading it again. Two are UNDER-reports, which is the worse direction: a
command missing from the list is a stub the verifier never writes, so the
extraction reaches the real network.

- A `case` pattern label stopped the scan on its own line: `blocked) gh api x`
  reported nothing, losing `gh`. The label is now stepped over like a `name=`
  prefix.
- Only the first heredoc opener on a line was tracked, so `cat <<A <<B` left
  the second body and its terminator read as commands (`B`, `y`). Openers are
  queued and consumed in order.
- Masking an expression to a QUOTED token let the quote-stripper delete it
  entirely, so `${{ steps.x.outputs.cmd }} arg` reported `arg` as the command.
  The token now survives stripping and cannot match a command word, so an
  expression in command position contributes nothing.

Ten further adversarial shapes were already correct and are pinned as
regression guards: nested `$( )` in quotes, subshells, function definitions,
indented heredoc terminators, backticks, bare redirects, adjacent and empty
`${{ }}` sites, and a JSON literal inside an expression. Verified to flip —
exactly the three above fail against the previous commit, the other ten pass.

434 real steps re-swept: 0 non-verbatim bodies, 0 live header lines, 0 missed
expression sites, 0 out-of-order env, 0 `bash -n` failures.

* fix(review): annotate the continuation accumulator so tsc can type it

`invokedCommandsOf`'s backslash-continuation loop failed to compile with
TS7022: the narrowed type of `pending` at the join line is the union of
the loop-entry value and the back edge, and the back edge is computed
from the join itself. The declaration's own annotation does not break
that cycle - control-flow narrowing runs after it - so the checker gives
up and calls the result `any`.

Caught only on a forced rebuild. `tsc --build` had been reporting this
tree clean off a stale .tsbuildinfo, which is the same shape of gap that
put a type error into CI last week: the test runner strips types, so the
suite stayed green either way. Gate with --force.

* fix(review): a file-count label stops counting at the end of its line

`Test Files  45 passed` filing its 45 as a differing TEST count was
fixed once, with a lookbehind on the bare-count pattern. That only ever
rejected the all-green shape. The moment any file fails, the runner
prints `Test Files  1 failed | 44 passed (45)`, the label is no longer
adjacent to the number, and 44 comes through as a test count - so the
note reads "claimed 44, observed 1323" on exactly the runs whose summary
someone would paste. Adjacency was the wrong invariant; the line is.

Masking from the label to end-of-line is distance-independent and picks
up jest's `Test Suites: 1 failed, 44 passed, 45 total` at no cost. The
label keeps its `Test` word on purpose: a first cut matched a bare
`files` and blanked the line in "expect all four files and 471 tests to
pass", silencing a real claim. An existing test caught that, which is
the argument for the rule being as narrow as it is - anything that
suppresses claims is worth exactly its narrowness.

Also drops the now-dead lookbehind, which a reviewer had separately (and
wrongly) called a JS syntax error; variable-length lookbehind is legal
in V8, and the module parsed fine. It goes because the line rule
subsumes it, not because it was broken.

* fix(review): parse the base rerun before its output is trimmed

`trimOutput` rescues module errors and runner summaries out of the
omitted middle, not the per-file FAIL lines this command reads. A base
suite whose failure section overruns the tail budget therefore lost
failing files into the gap - and a SHORT base set is the dangerous
direction, because netNew is the PR side minus the base side. Every file
the trim hid came back as a Critical attributed to this PR by
"measurement". Parse the raw text, report the bounded one.

The PR side cannot be fixed here: it is read out of build-test's stored
output, trimmed before this command existed. That loss runs the other
way - it understates `shared`, never invents a netNew - so the entry
carries `prTruncated` and the note says the list may be partial. A
silence-biased gap is still a gap the author should hear about.

Also names both selection caps in the mutant-skip diagnostic. The count
accumulates replacement sub-cap drops, and with 2 deletions and 6
replacements the total is exactly MAX_MUTANTS: the main cap never fires,
yet 3 are dropped, and the message sent the reader looking for a pool of
11 candidates that never existed.

* test(review): pin the `sh` set-line to exactly what the runner uses

A reviewer asked for `expect(script).not.toContain('set -e')` on a
`shell: sh` step. The opposite is correct - GitHub runs that step as
`sh -e {0}` - but the thread was right that nothing pinned it either
way. Assert both halves: `set -e` is present, `pipefail` is not. Dropping
the line makes an extracted `sh` step run past a failure the runner
stops on; adding pipefail claims a bash feature `sh` does not have.

* fix(review): rerun only the command shapes build-test emits

This command reads a report off disk and then executes the strings in it
with `shell: true`, in the base worktree. Nothing else in the pipeline
re-executes a value it read back from a file, so nothing else has to
care where that value came from - this does, and the provenance is worse
than it looks: the command is `npm test --workspace="<dir>"`, the
workspace token is a directory, and a directory is a name a pull request
chooses. `packages/x";curl …|sh;"` is a legal path in git and on Linux
and it round-trips through the report into a shell.

Restricting to the emitter's own grammar costs nothing real, since that
grammar is the two shapes build-test produces. A command outside it is
skipped and disclosed, the same treatment everything else this command
cannot do already gets, so a future shape degrades to "judge it by the
diff" rather than to arbitrary execution.

* fix(review): the working directory is a setting the extraction was losing

Two findings, both of them this file failing its own stated argument.

The stub list dropped it. `expressions` covered the script and the env
and nothing else, so a `working-directory: ${{ github.workspace }}/x`
produced an empty list and a summary line reading "0 ${{ }} site(s) to
stub" - and `expressionsOf`'s own comment says why that is the failure
this list cannot afford: the caller reads it as "these are all the
values to supply". Widened to every setting the command carries, the
`shell:` template included.

The emitted script never mentioned it. The env block is commented into
the header precisely so a reader of the script alone can see it; the
working directory changes what the script does just as much and was in
the metadata only. The argument for reading all three levels, written in
this file, is that a step run "in the wrong directory, and nothing says
so" is the transcription error the command exists to remove - which is
exactly what the header did. It is a comment rather than a `cd` for the
same reason env is comments, not exports: the value may hold `${{ … }}`
and this command substitutes nothing.

Both pinned, and both checked by deleting the fix: each mutation fails
exactly one of the two new tests.

* fix(review): $(( )) is arithmetic, and a heredoc's form decides where it ends

Three fixes and one deliberate non-fix, all measured against this repo's
own 434 `run:` steps rather than argued.

`$(( ))` was read as a command substitution, so `N=$((N + 1))` reported
`N` as a command to stub. It was the single largest source of junk in
the list: 196 distinct "commands" across the corpus, 165 without it.

A plain `<<WORD` heredoc ends only on a line that is exactly WORD; the
loose match ended it on an indented `EOF` inside the body and then read
the body as commands, which is how `rm` got reported for a script that
never runs it. `<<-` stays looser than bash (any leading whitespace, not
just tabs) because looser can only end a body early, and this file's
priority is that an under-report is the worse direction.

`[^()]*` matched only the innermost `$( )`, so `X=$(gh api $(u))` lost
`gh` - a missed stub, and the extraction reaches the network. Depth
counted now, and the assignment-prefix skip no longer steps over an
unclosed `X=$(gh` into reading `api` as the command.

The non-fix is recorded where the next reader will hit it: the quote
walk is flat while shell quoting nests, and over ~300 lines the drift
reports fragments of jq source as commands. Inserting a separator where
a blanked span was removes nine of those, but it splits `a"X"b`, which
is one word to the shell, and the minimal reproducer for the difference
is 296 lines - nothing short enough to pin it. A scanner nobody can pin
costs more than the junk it removes.

* fix(review): refuse an ambiguous step name, and report errors like the siblings

Two findings, both about a message the caller never gets.

A job may legally hold two steps with the same name. The selector took
the first and said nothing, which is the failure this file's own header
names - "picks the same-named step from the wrong job" - and it is worst
in the use the command exists for: A/B extraction runs it once per tree,
so a PR that adds or reorders a duplicate leaves the two sides comparing
different steps while reporting on one. Refused out loud now, naming the
indices; the index is always available and never ambiguous.

The handler also let every throw propagate, so five carefully separated
messages - cannot read vs cannot parse vs no job vs no step vs no `run:`
- all arrived as "An unexpected critical error occurred" under a stack
trace. `base-tree` and `test-plan` in the same directory already catch,
write the message, and set exit 1. Matched. The separation between "the
path is wrong" and "the YAML is wrong" only pays if the caller sees it.

* docs(review): the brief's list of limits was one short

"Two limits worth knowing before you spend the step" became three when
the selector started refusing an ambiguous step name, and the count went
stale in the same commit that made it wrong. This is the enumeration
drift the skill teaches, in the text that teaches it.

The added entry says what to do rather than only what happens: pass the
index, which is what an A/B wants regardless — the two trees have to
select the same step, and a name that moved between them is exactly how
they stop doing that.

* chore(review): drop a scratch probe file that reached the branch

`packages/cli/inert.mjs` was a throwaway harness for sweeping the repo's
own workflows; its cleanup ran with a relative path from the wrong
directory and it got committed by the next `git add -A`.

It failed CI and not the local hook because the two lint different sets:
lint-staged filters to `*.{js,jsx,ts,tsx}`, which does not include
`.mjs`, while CI's flat config picks the file up regardless of `--ext`.
Verified with CI's own command this time, not the hook's.

---------

Co-authored-by: qwen-code-dev-bot <qwen-code-dev@service.alibaba.com>
Co-authored-by: Qwen Code <qwen-code@users.noreply.github.com>
Co-authored-by: Qwen Code Bot <qwen-code-bot@users.noreply.github.com>
Co-authored-by: Qwen Code Autofix <qwen-code-autofix@users.noreply.github.com>
pchaganti pushed a commit to pchaganti/qx-qwen-code that referenced this pull request Aug 1, 2026
…M#8255)

* feat(review): borrowed-verification trio — test-plan check, base-tree A/B, per-hunk probes

- qwen review test-plan: rule on the PR Test Plan's checkable claims (paths,
  npm scripts, test counts) against the reviewed tree; contradictions and
  differing counts are disclosed via compose-review, never capping.
- qwen review base-tree: build the merge base in a sibling worktree so the
  verifier can A/B a comparative claim instead of reading it; swept by cleanup.
- test-efficacy: third probe kind — reverse-apply one hunk at a time and
  re-run the affected tests, attributing a still-green suite to the specific
  change nothing gates; shares the mutants' budget window, runs last.

* fix(review): survive real runner output — ANSI-laced and trimmed-away summaries

Both measured on a live /review of QwenLM#8176 with the built CLI:

- test-plan's observedTestCounts strips SGR sequences before matching; a
  color-enabled pipe interleaves them BETWEEN tokens, and the count claim
  fell to 'unchecked' with the summary right there in the report.
- build-test's trimOutput rescues runner summary lines from the omitted
  middle (like module-resolution errors): a failing suite's tail is all
  failure details and npm epilogue, which pushed the one-line summary out
  of the kept text entirely.

* fix(review): address the eight findings from live review of this branch

All measured in the review (QwenLM#8215 review comment):

- test-plan: linear-time bold-heading scan (the old pattern backtracked
  catastrophically on an unclosed ** line an untrusted PR body controls);
  a flag preceding the npm script yields no claim instead of a false
  'no package defines this script'.
- test-efficacy: a hunk probe's restore recreates the parent directory a
  reverse-applied 'new file' hunk removed (the ENOENT from finally lost
  the verdict and marked every remaining hunk inconclusive); hunks get
  their own skippedForBaseline instead of mislabeling a red baseline as
  a budget skip; splitDiffIntoHunks re-captures the file header at every
  diff --git boundary; a hunk-survived finding notes when it restates an
  inert file-level revert at hunk granularity.
- base-tree: idempotent fast path keyed on a build marker + HEAD check —
  concurrent verifier shards reuse one built tree instead of sweeping it
  out from under each other mid-A/B (a fabricated base-side difference
  with a deterministic source tag was the worst case); cost wording is
  now 'an install and a build' everywhere it was 'one extra build'.

* fix(cli): never score a hunk survived when its own test left the baseline (QwenLM#8215)

A per-hunk probe reported `survived` whenever the green baseline probes still
passed with the hunk reverted. When the hunk's own collocated test dropped out
of the baseline (a probe-tree import error collects nothing), the remaining
green probes prove only that THEY do not cover the hunk, so the verdict is now
`inconclusive` — the same dropped-test asymmetry the mutants already hold.

Also scope the hunk-survived cross-reference note to the hunk's own collocated
test, and let test-plan match a workspace-scoped run of the plan's bare command
instead of falling through to the manifest on an exact-string miss.

* fix(review): silence-bias hardening from four live review rounds of this branch

The two blocking findings, reproduced on this PR's own Test Plan:

- test-plan files no false contradicted notes: npm rulings move from a
  four-verb denylist to an allowlist (the run form + npm's script aliases —
  the ~fifty other builtins each used to become 'no package defines this
  script'); a slash token is claimed as a repo path only with evidence (an
  extension or ./ prefix), never when it is a flag's value (--repo
  owner/repo) or under the review's own temp root; HEADING_LINE_RE drops
  the same quadratic shape its bold sibling was rewritten to remove.
- base-tree gets a real mutual-exclusion lock around sweep+add+build
  (mkdirSync test-and-set; the loser returns busy instead of deleting the
  tree the winner is mid-install in), and a failed build writes a settled
  marker so later shards stop re-paying the install to relearn
  'unavailable'.

Also: Agent 7's brief now names hunk-survived and the hunks.* counters
(it is the report's only consumer, and the finding class was invisible);
hunk findings anchor at the first ADDED line instead of up to three
context lines above the change.

* feat(review): four round-2 borrowings — measured failure attribution, round ledger, richer mutants, doc parity

Shaped by a live round-2 maintainer re-verification (QwenLM#7818):

- qwen review test-delta: rerun the PR side's failed test commands on the
  built merge base and diff the failing FILE SETS — netNew is the PR's own
  failure by measurement (whatever files the diff touches), shared is
  pre-existing by measurement. Counts are never compared: a flaky suite
  fails different test names between runs of the same tree. An unfinished
  base rerun attributes nothing.
- Round ledger: the incremental review cache persists confirmed findings
  under round-scoped ids (R1-2); a high-effort re-review rules on each
  (fixed / still stands / cannot tell) and opens its report with the table,
  the way a human round-2 comment opens with 'M1 is fixed'.
- Three replacement mutation operators in test-efficacy: drop '?? fallback',
  force a comparison-bearing guard condition to 'true', drop a '+ CONST'
  term. Each survivor maps to one crisp untested-protection sentence.
  A line whose raw text and literal-blanked code view disagree yields no
  candidate — an edit index computed across the two views once spliced
  'iftrue 0)' into a guard, and a mangled mutant reads as inconclusive
  while quietly spending a cap slot.
- Quality brief: documentation-parity lens — a new user-facing surface whose
  siblings are documented is a Suggestion naming the sibling precedent; no
  documented sibling, no finding.

* feat(review): render adjudication, workflow step extraction, three verification lenses

Shaped by a live sanitizer-PR verification (QwenLM#8147):

- Render-adjudication capability (opt-in): with QWEN_REVIEW_SCRATCH_REPO
  set, the verifier may post a minimal payload to that user-designated repo
  and rule on GitHub's own rendered HTML — the measured case being an
  @ -> &QwenLM#64; defusal every local reading called sound while GitHub's real
  renderer registered the mention and fired the notification. Absent the
  setting, rendering claims honestly cap at low confidence / cannot tell.
  Step 7's write ban names the carve-out explicitly.
- qwen review extract-step: lift one workflow step's run: script verbatim
  into an executable, with env (as comments, never half-substituted
  exports), every ${{ }} site listed unevaluated, and a heuristic invoked-
  command list as the stubbing starting point. With base-tree, both arms of
  a by-hand workflow A/B become two invocations. yaml declared as a cli
  dependency (previously resolved only via hoisting).
- Three brief lenses: a borrowed protection idiom missing what made it work
  at home (the code ancestor did the protecting; only the entity was
  copied); a second parser for an authoritatively-parsed format is a
  divergence hunt; tests that pin the mechanism instead of the effect, and
  oracles that mirror the implementation's own model.

* feat(review): sibling-entrance discipline for the fixed verdict

From round 6 of the live sanitizer verification (QwenLM#8147):
the fix closed the fence-shaped entrance into a raw-HTML block, and the
code-span entrance beside it — same divergence, adjacent syntax — stayed
open. A re-check that tests only the reported input rules 'fixed' over a
hole one backtick away.

Both fixed-verdict sites in SKILL Step 6 (the open-Criticals re-check and
the round ledger) now require enumerating a divergence-class defect's
sibling entrances before ruling fixed; a still-open sibling is a NEW
finding, never a reason to withhold the original's fixed — the two
rulings stay separate so the second hole cannot ship unreviewed.

* feat(review): three measured-verification lenses from live rounds 8037/8005

- Threshold-boundary scan: when a fix is a ratio/length guard, hold the
  issue's own variables fixed and binary-search the boundary where the
  behaviour flips; put the number next to what the issue reports. Live
  case: a prose-ratio guard covered the edit/write_file half of its issue
  and silently declined the run_shell_command half (~473-char boundary).
- Delimiter self-injection named as the first parser-differential probe:
  a no-escaping extractor fed its own close tag truncates silently.
- Shared-gate state enumeration: a deliberate-design defence extends only
  to the states it argues — an input-hold argued for 'active' silently
  froze three idle states sharing the same gate. The sibling-entrance
  rule, applied to a state machine instead of a syntax.

* feat(review): carry the round ledger in the posted review body

The ledger shipped as a local cache file and its first multi-round live
use exposed the flaw: four model-comparison rounds re-reviewed the same
two PRs and every round opened from scratch — medium never reads the
cache, and from CI or another clone there is no cache at all. The one
artifact every environment can see, the posted review, carried nothing
machine-readable.

- compose-review embeds an HTML-comment marker (invisible on GitHub)
  carrying this round's findings and round number; the round comes from
  the side file pr-context recovered, +1 — never from the model.
- pr-context recovers the reviewing account's latest marker, renders it
  as a 'Previous /review round (machine ledger)' work-list section, and
  writes it beside the context file for compose-review's round counter.
  Own-account only, latest round wins, fail-quiet on any malformation —
  the marker is data the next round rules on, never authority it obeys.
- Step 6's previous-round ruling now runs at medium too (recovery is
  free; medium still writes no cache and posts nothing); the local cache
  is demoted to fallback for rounds that never posted.

* fix(review): address review feedback — false-positive hardening, binary diff guard, error convention (QwenLM#8215)

* fix(review): address review feedback — base-tree availability gate, test-plan false positives, hunk-probe ranges (QwenLM#8215)

- base-tree: only stamp a base tree available when runBuildTest actually
  compiled something (ok AND npm toolchain AND a non-empty build). An
  `unsupported` handoff or an empty npm scope returns ok:true having built
  nothing; marking that tree available let an A/B read the absence of a build
  as a behavioural difference.
- cleanup: sweep the stale base-tree build lock a killed builder leaves behind.
- test-plan: read the root manifest's scripts directly so a root-only script
  survives when the root defines no build/test; bail on the inline --root=./dir
  rebasing form; stop treating a positional after an inline --flag=value as the
  flag's value; prefer a failed scoped run when ruling a bare command; anchor
  the npm script alias to a full token so `yarn test:unit` is not truncated.
- test-efficacy: exclude `\ No newline at end of file` from the startLine offset
  count; compute the mutant-overlap range from the header's new-side span so it
  no longer overshoots into a closely following hunk.

* fix(review): address review feedback — diff-header false positives, stale prompt enumeration, added-file hunk probes (QwenLM#8215)

* fix(review): address review feedback — cd-base exclusion, Test Files count guard, base-tree error handling, probe delegation (QwenLM#8215)

* fix(review): port the collocated-dropout test to the post-QwenLM#8050 runner seam

Merging main brought QwenLM#8050's Windows-portability refactor, which resolves
the probe runner through vitest/package.json's bin — a node_modules/.bin
fake is dead weight it never reads. The 8215-only collocated-dropout test
still installed the old .bin fake, so the REAL vitest ran its fixtures,
price.test.ts genuinely passed, and the hunk scored survived. The test now
overrides the fake package's vitest.mjs like every post-refactor test.

* fix(review): bound the summary rescue, apply the ATX heading rule, sweep stale build locks

The three 8215-layer findings from the latest review, fixed at this
layer (they were first patched further up the stack, where the reviewer
of THIS PR cannot see them):

- trimOutput's summary rescue is capped at 40 lines — uncapped, 40k
  lines of 'Test <n>: …' prose voided the trim entirely (measured 1.6MB
  in, 1.6MB out) and the bounded-output contract is the whole point.
- A '#' with no following whitespace is prose, not a heading (the ATX
  rule GitHub applies): 'QwenLM#8176', '#tag', an unfenced '#!/bin/bash' no
  longer end the Test Plan section mid-body; the bare-#-run crash on
  the closing scan is guarded.
- A base-tree build lock older than 30 minutes is a corpse left by a
  killed builder — swept and rebuilt instead of reporting busy for the
  rest of the review.

* fix(review): EEXIST-only lock busy, bun test alias, chained cd bail, fence backreference

Four live findings from the latest inline review round (the rest of the
round was already fixed upstream by the takeover bot - verified by
probing head behavior rather than re-reading the threads):

- base-tree's lock catch distinguishes EEXIST (a concurrent builder,
  busy) from EPERM/EROFS/ENOSPC (this run's own failure, reported as
  such, not as a busy that will never clear).
- "bun test" is bun's built-in runner, not a package-script alias: it
  runs whether or not any manifest defines test, so ruling it against
  the scripts table filed a false contradicted.
- A chained cd matches the leading-cd shape but the single-hop resolver
  joined file tokens against the FIRST directory; it now bails like the
  exotic-cd case.
- codeSpans' fence regex closes on its own marker via backreference; a
  tilde fence line inside a backtick block ended the span early and
  lines after it were lost to extraction.

* fix(review): make the ledger marker actually reach the posted body

Three Criticals from the QwenLM#8255 review, all real:

- The marker was appended in the CLI handler, AFTER composeReview()
  returned, so it only ever reached the composed JSON on disk. submit
  posts what the PURE function returns, so no posted review carried a
  marker, latestOwnLedger always returned null, and the whole feature
  was inert end to end. The append now lives inside composeReview, fed
  by a draftedComments seam that both CLI boundaries fill from the same
  array they count (and both strip from a model-written state JSON).
  Three end-to-end tests now assert on the body composeReview returns.
- pr-context's side-file write preceded the mkdir that creates its
  directory and was unguarded: an ENOENT failed the whole command over
  a best-effort carry-forward. mkdir first, write guarded.
- CANONICAL_LGTM_RE is anchored, so a trailing marker made every no-op
  round "worth showing" and prior rounds started rendering in full. The
  marker is now stripped before the filter and the count walk, not only
  before rendering.

Plus the three thread findings: ledger cells are escaped before landing
in the context table (a title with a pipe could forge rows), parseLedger
takes the LAST marker and type-checks/normalises what it recovers, and
the stray verdict doc comment is reattached to verdictLine.

* fix(review): close the ten open findings on this PR

- guard-true tested for a comparison anywhere after `if (`, including the
  then-body, so `if (ready) emit(a !== b);` admitted a mutant on the
  comparison-less condition the gate exists to exclude. It now tests the
  condition span only.
- The `survived` detail said "when it changes" for legacy DELETION
  mutants too; it now matches the operator.
- test-delta's `unparsed` required both sides to parse zero files, so a
  PR-side failure whose FAIL lines the trim scattered was silently
  dropped whenever the base rerun happened to parse. netNew/shared come
  from the PR side, so the PR side alone decides.
- failingFilesOf now matches Windows path shapes (backslashes, C:) - a
  missed parse is an unattributed failure, not a loud error.
- The replacement branch of runOneMutant (write-file -> run-probe ->
  classify) had no end-to-end test; one now drives a coalesce operator
  through the real handler and asserts the mutated line, the verdict,
  the operator-specific wording, and that the shared tree is untouched.
- Two tests were vacuous with respect to what they promised: the
  baseline-dir test never asserted the cwd (its helper swallowed the
  argument - fixed at the helper), and the one-candidate-per-line test
  used an input that never triggered the replacement path, so the
  `continue` under test was not load-bearing.
- Reattached the orphaned selectMutants JSDoc; reworded the SKILL line.

* fix(review): the test helper's cwd parameter is required, not optional

CI's `tsc --build` failed on test-delta.test.ts: the exec seam always
passes a cwd, but the helper's signature marked it optional, so pushing
it into a string[] was `string | undefined`.

Missed locally because vitest runs through esbuild, which strips types
without checking them - the suite was green while the build was red. The
gate to run before pushing a type-level change is `npx tsc --build`, not
the test suite.

* fix(review): a base rerun that could not RUN attributes nothing

Two Criticals from the latest review, both reachable on the brief's own
happy path:

- baseUnusable covered only timeouts. Every other way the base side can
  fail to run - an unbuilt base tree, a missing install, a workspace the
  PR ADDED (npm test --workspace cannot resolve on base), an ENOBUFS
  truncation - exits non-zero with zero FAIL lines, which this code read
  as a green base. Every PR-side failure then became netNew: the
  strongest evidence the command emits, manufactured from a base that
  never ran a test. It now attributes nothing and says why.
- Timeout detection was the weaker substring form the sibling explicitly
  rejects; an external SIGTERM (container stop, cancelled job) set
  neither an ETIMEDOUT message nor an exit code and fed straight into
  the above. build-test now exports spawnTimedOut and test-delta asks
  the same question rather than re-deriving it.

Also: the base output is trimmed (it precedes the verdict fields in the
report the agent reads, so an untrimmed megabyte truncates exactly what
the command produces); the guard-true gate no longer reads an arrow
function's => as a comparison (every predicate guard was a candidate -
the if (ready) noise the gate exists to exclude); the term-drop message
no longer calls a string concatenation a reserve term; the unparsed note
describes its own PR-side-only condition; and the ledger's Step 6/Step 8
now agree that a still-standing finding keeps its id.

* fix(review): extract-step resolves all three env/defaults levels, and comments every env line

Two silent-wrongness defects in a command whose whole value is fidelity.

`env:`, `shell:` and `working-directory:` are three-level settings on GitHub —
workflow, job, step, nearest wins — and only the step level appears in the
step's own text. Reading step-level alone reproduced by machine the exact
transcription error this command exists to remove: measured, a step under a
job-level `NODE_ENV: production` and a workflow-level `GLOBAL_FLAG` extracted
with `env: { LOCAL: '1' }` and `workingDirectory: undefined`, so the emitted
script ran with both unset and nothing said so. Not a contrived shape: this
repo carries workflow-level `env:` in 7 workflows, job-level `env:` in 10, and
job-level `defaults.run` in qwen-triage.yml — the workflow the command's own
test plan names. The three levels now merge with the runner's precedence, and
`envSources` records which level each key came from, so an inherited value is
visible rather than indistinguishable from the step's own.

The env block was commented per ENTRY, not per LINE. A YAML block scalar
(qwen-autofix.yml's `SETTINGS_JSON: |-`) reaches the header as a multi-line
string, so its continuation lines landed in command position — and under the
`set -e` the header itself emits, the extracted step died in its own preamble
before its `run:` body ran. Every line is commented now.

Tests pin the effect, not the mechanism: `executableLines()` asserts nothing
but the `run:` body ever reaches command position, plus a `bash -n` parse
check. Verified to flip — all five new assertions fail against the pre-fix
implementation (`{ LOCAL: '1' }`, `undefined` working directory, three
executable lines instead of one, and a real `bash -n` syntax error).

* fix(review): compare failing files by a normalised, project-keyed identity

Critical: the two sides run in DIFFERENT roots (the PR worktree and the
base tree), and netNew/shared compared the parsed paths verbatim - so an
absolute-path runner turned every pre-existing failure into a fabricated
Critical, with the authority of a measurement behind it. Paths are now
normalised against each run's own root (and backslashes to /, so a
Windows path compares with its POSIX-printed twin), which is why
test-delta gained --pr-worktree.

The identity also keeps the vitest project token: dropping it collapsed
same-named test files across workspaces, so a PR-caused failure in one
package could read as pre-existing because another package has a file by
the same name - the worse failure direction.

Also from the same review, all of them reachable on the brief's own path:

- The base rerun now inherits build-test's stdio: ['ignore','pipe','pipe']
  ("a build that asks a question is a build that hangs until the
  deadline") and its trimOutput, which matters because entries[].base
  precedes the verdict fields in the report the agent reads.
- The brief gates on base-tree's `available`, not just its `path`: a tree
  that was created but did not build populates path too, and measuring
  against it turns an infrastructure failure into Criticals.
- A programmatic caller omitting `timeout` no longer sends NaN into
  spawnSync.
- MutantCandidate is a discriminated union, so an operator without its
  replacement line - which would delete a line while reporting "with its
  ?? fallback dropped" - is unrepresentable.
- The comparison class no longer requires a trailing space (if (a<b) is
  the same guard, just unformatted) and matches a brace-less else if.
- DeltaEntry.unparsed's doc now describes the PR-side-only condition it
  actually implements.

* fix(review): restore the whole-command budget, keep generics out of guard-true

Round-1 findings from a fresh review of this PR:

- test-delta had no aggregate deadline: --timeout is PER command and
  defaults to 300s, so three failed commands is 900s against Agent 7's
  600s ceiling - killed with NO report at all, discarding the base-tree
  install and build just paid for. TOTAL_BUDGET_MS mirrors the one
  test-efficacy reserves; commands it cannot fit are disclosed.
- guard-true matched generic calls: `if (isRecord<string>(v))` produced a
  mutant, and a type-guard predicate is exactly the `if (ready)` shape
  whose survivors the gate calls noise. The trailing \s is required, not
  an accidental asymmetry with [!=]== - telling `a<b` from `fn<T>(x)`
  needs a parser, and the gate is silence-biased by design.
- --pr-worktree had no contract test, and its failure mode is the worst
  here: arriving undefined, root stripping silently stops and every
  pre-existing failure becomes a fabricated netNew. The new test feeds
  parseSync's output straight into runTestDelta and asserts an
  attribution only reachable when both roots were stripped (verified
  red against the snake_case field shape that shipped once already).
- Merged the two consecutive doc comments on prWorktree.

* fix(review): a budget-shortened deadline is not the same fact as a slow rerun

Round-2 finding on the budget just restored: `Math.min(perCommandMs,
remaining)` can hand a rerun far less than --timeout, and if it dies
there the note said only "timed out - infrastructure, not evidence".
True, but it sends the reader hunting a hang that is really an exhausted
budget - and unlike a real timeout, a rerun with budget to spare would
still measure it. The note now names those commands separately and says
so. Verified red against removing the tracking line.

* fix(review): brace-tolerant stub list, pipefail fidelity, and extract-step in the briefs

Round-3 findings on this PR, fixed.

`expressionsOf` matched `[^}]*`, so any expression containing a brace —
`format('refs/pull/{0}/head', …)`, `fromJSON('{"a":1}')` — was not mis-listed
but DROPPED. A stub list reads as "these are all the values to supply", so a
silent omission is a value that never gets stubbed. It now scans forward to the
closing `}}`, and reports nothing for an unterminated site rather than
swallowing the rest of the text.

Declaring `shell: bash` is not the runner's default `bash`. The default is
`bash -e {0}`; a declared `bash` (at any level) is
`bash --noprofile --norc -eo pipefail {0}`, and a pipeline whose middle stage
fails aborts under one and not the other. The header now carries `set -eo
pipefail` or `set -e` accordingly — 163 of this repo's 434 `run:` steps are
under a declared bash and were getting the weaker one. A `shell:` value is also
a command template (`perl {0}`), so only its first word goes in the shebang and
the whole template is recorded beside it.

`extract-step` was registered on the CLI and mentioned in DESIGN.md, and
nowhere in SKILL.md or the agent briefs — the runtime prompts. The capability
was unreachable by the agents it was written for. The verifier's brief now
carries it next to the A/B paragraph it composes with, and Step 4 summarises it.

Also: env ordered nearest-first (measured on qwen-autofix.yml:route:0, merge
order put 20 inherited entries ahead of the step's own 26 in a 49-line header);
a valueless `FOO:` renders as the empty string, not `"null"`, and a non-scalar
as JSON rather than `[object Object]`; a missing file no longer reports as a
parse failure; DESIGN.md's lens count matches its list.

The test oracle is rebuilt around the property instead of a filter: the file is
the header plus the body verbatim, and every line before the body is a comment
or a directive the test names. The old helper dropped `set -e` unconditionally,
so it could not tell the header's from one the body legitimately contains — and
would have gone green on a header that leaked exactly that line. 434 real `run:`
steps swept: 0 non-verbatim bodies, 0 live header lines, 0 missed expression
sites, 0 out-of-order env, 0 `bash -n` failures.

* fix(review): restore the replacement sub-cap, stranded on a downstream branch

Round-3 finding, and the third instance of one class: an 8218-layer fix
committed on the 8261 branch, four PRs above the code it belongs to.

Measured over 40 real commits, the replacement operators produce ~24x
the deletion pool (215 vs 9 candidates; guard-true drives it). Every
mutant run drains the same window hunk probes draw from LAST, so
uncapped, most diffs with any replacement candidates leave hunk probing
zero runs - the hunk-survived finding class silently stops firing and
nothing says so. Three slots, and what the sub-cap drops is counted in
skippedForCap rather than lost.

Also swept the other direction: diffed every review file against its
8261 copy to confirm nothing else 8218-layer is stranded up there. The
remaining divergence is 8261's own (the positive control, its lenses).

* fix(review): one severity predicate, carried ids, and a lossless marker

Round-1 review of the ledger marker, six findings.

Two contradicted contracts this package already states elsewhere:

- `buildLedger` restated the severity predicate as a bare `startsWith`
  while `severityOf` — what `countInlineFindings` and the unmarked-comment
  gate both use — trims first. A Critical whose body opened with a newline
  was counted, was posted, blocked the merge, and was silently absent from
  the ledger, shifting the id of every finding after it. It classifies
  through `severityOf` now, and strips the marker with the shared prefixes
  instead of a second copy of the literals.

- Ids were assigned by array position every round, so the report saying
  `R1-2 still stands` shipped beside a marker recording that claim as
  `R3-4` — and `LedgerFinding.id` documented itself "stable across
  re-reports". Step 6 now mandates writing the original id into the
  re-report (`**[Critical]** R1-2: …`), `buildLedger` reads it back, and a
  duplicate or absent id falls back to the next free id of this round.

Four smaller ones:

- `stripLedgerMarker` removed only the FIRST marker while `parseLedger`
  reads the LAST, so a body holding two leaked the trusted marker into
  model-facing prose and un-filtered the canonical LGTM it was appended to.
- The `--` guard rewrote data to an em dash: a finding about `--comment`
  reached the next round as `—comment`. It escapes at the JSON layer now,
  which is comment-safe and lossless.
- `file` was capped on read (200) but not on write; the cap is one
  constant binding both halves.
- `submit`'s path — the one GitHub's payload is built from — had no test
  that the marker reaches the posted body.

Plus: tie-break `latestOwnLedger` on review id when `submitted_at` ties,
neutralise a backtick in the location code span, skip the `currentUser()`
round-trip when the PR has no reviews, and say why a stale side file is
deliberately left in place.

* docs(review): complete the "delta cannot rule" enumeration in both places

Round-4 finding. The brief and SKILL.md each listed three cases where
test-delta attributes nothing - unparsed, timed-out base, no merge base -
but the code has five: the later rounds of this PR added "a base rerun
that failed without naming any failing file" (it did not measure the
base) and "a command the whole-command budget could not fit". Two
enumerations of the same set with different membership, in the two
places an agent reads.

That is the sibling-enumeration lesson this skill teaches, applied to
its own prose for the second time: the fix is not just adding the
missing members but saying that the report names each case with its own
reason rather than folding them into one.

* fix(review): the invokes list was mostly prose, not commands

Round-4 finding on this PR. `invokes` is documented as a heuristic starting
point, and imprecision is fine — but measured over this repo's 434 real `run:`
steps it was reporting 435 distinct "commands", 267 of them appearing exactly
once, with a worst case of 63 entries made up of words like `CI`, `Evidence`,
`PR` and `and`. A list that size, mostly prose, is not a starting point.

Three causes, each measured:

- A `${{ … }}` expression is not shell, and it routinely contains `||`.
  Splitting on that as a pipeline separator reported both operands as commands
  (`matrix.arch`, `github.event.inputs.version`). Expressions are now masked to
  an opaque token before the split; one sitting in command position contributes
  nothing, which is honest — what it expands to is unknown here by design.
- A heredoc body is input to a command, not a list of them. Its lines were
  scanned as commands, terminator included. 12 steps in this repo carry one.
- The `name=value` skip stepped over the prefix and took the NEXT word as the
  command — but for a quoted value with spaces that word is inside the value:
  `EVIDENCE_SECTION=$'### Evidence images'` reported `Evidence`. Quoted spans
  are now blanked out, with the quote carried across lines so a multi-line
  string's continuation lines are data too. Command substitutions are read
  first, so `body="$(sanitize < "$REPORT")"` still reports `sanitize`.

A `#` preceded by whitespace ends the live part of a line, so an apostrophe in
a trailing comment cannot open a span and eat the rest of the script.

Measured after: 435 distinct commands to 187, singletons 267 to 104, worst case
63 to 27 — and the worst case is now real commands (`awk cat chmod curl git jq
mktemp pkill tar tee timeout`) plus the script's own shell functions. Also
added the builtins a stub could not intercept anyway (`eval`, `exec`, `source`,
`unset`, `command`, …) to the keyword set.

434 steps re-swept: 0 non-verbatim bodies, 0 live header lines, 0 missed
expression sites, 0 out-of-order env, 0 `bash -n` failures.

* docs(review): the rationale named only one of the ways base goes unmeasured

Third and last copy of the enumeration the previous commit fixed. The
bullet's headline already generalised - "base attributes nothing it did
not finish" - but its body named only the timeout, so a reader learning
the contract from the rationale would conclude timeouts are the only
unusable case. Name the set, and say why the report keeps the reasons
apart: "we could not measure" and "we measured nothing" are different
facts to the author, and only one of them is about their PR.

* fix(review): a quoted `<<EOF` is not a heredoc, and a continued line is one command

Round-5 findings, both in the previous commit's own scanner.

A heredoc opener was matched over the whole line, so one inside a string
started heredoc mode: `echo "write <<EOF for a heredoc"` made every later line
wait for a terminator that never arrives. The failure is not a missing entry
but a missing REST — measured, a three-line script returned `[]` instead of
`[curl, jq]`, empty and entirely plausible. Opener detection moved inside the
quote walk, where it only fires outside quotes; the quoted forms (`<<'EOF'`)
are consumed by the match, so their quotes never open a span either.

A backslash-continued command was scanned as several lines, which puts the next
ARGUMENT in command position — this is where `apt-get install -y \` /
`  libx11-dev` reported the package as an invoked command. Continuations are
now joined into one logical line before scanning.

Measured after: 187 distinct commands to 185, and the singleton tail is now
dominated by real ones — PowerShell cmdlets, macOS tooling, and the scripts'
own shell functions. 434 real steps re-swept: 0 non-verbatim bodies, 0 live
header lines, 0 missed expression sites, 0 out-of-order env, 0 `bash -n`
failures.

* fix(review): case labels, a second heredoc, and an expression in command position

Round-6 findings, from running the scanner against adversarial shapes rather
than reading it again. Two are UNDER-reports, which is the worse direction: a
command missing from the list is a stub the verifier never writes, so the
extraction reaches the real network.

- A `case` pattern label stopped the scan on its own line: `blocked) gh api x`
  reported nothing, losing `gh`. The label is now stepped over like a `name=`
  prefix.
- Only the first heredoc opener on a line was tracked, so `cat <<A <<B` left
  the second body and its terminator read as commands (`B`, `y`). Openers are
  queued and consumed in order.
- Masking an expression to a QUOTED token let the quote-stripper delete it
  entirely, so `${{ steps.x.outputs.cmd }} arg` reported `arg` as the command.
  The token now survives stripping and cannot match a command word, so an
  expression in command position contributes nothing.

Ten further adversarial shapes were already correct and are pinned as
regression guards: nested `$( )` in quotes, subshells, function definitions,
indented heredoc terminators, backticks, bare redirects, adjacent and empty
`${{ }}` sites, and a JSON literal inside an expression. Verified to flip —
exactly the three above fail against the previous commit, the other ten pass.

434 real steps re-swept: 0 non-verbatim bodies, 0 live header lines, 0 missed
expression sites, 0 out-of-order env, 0 `bash -n` failures.

* fix(review): annotate the continuation accumulator so tsc can type it

`invokedCommandsOf`'s backslash-continuation loop failed to compile with
TS7022: the narrowed type of `pending` at the join line is the union of
the loop-entry value and the back edge, and the back edge is computed
from the join itself. The declaration's own annotation does not break
that cycle - control-flow narrowing runs after it - so the checker gives
up and calls the result `any`.

Caught only on a forced rebuild. `tsc --build` had been reporting this
tree clean off a stale .tsbuildinfo, which is the same shape of gap that
put a type error into CI last week: the test runner strips types, so the
suite stayed green either way. Gate with --force.

* fix(review): a file-count label stops counting at the end of its line

`Test Files  45 passed` filing its 45 as a differing TEST count was
fixed once, with a lookbehind on the bare-count pattern. That only ever
rejected the all-green shape. The moment any file fails, the runner
prints `Test Files  1 failed | 44 passed (45)`, the label is no longer
adjacent to the number, and 44 comes through as a test count - so the
note reads "claimed 44, observed 1323" on exactly the runs whose summary
someone would paste. Adjacency was the wrong invariant; the line is.

Masking from the label to end-of-line is distance-independent and picks
up jest's `Test Suites: 1 failed, 44 passed, 45 total` at no cost. The
label keeps its `Test` word on purpose: a first cut matched a bare
`files` and blanked the line in "expect all four files and 471 tests to
pass", silencing a real claim. An existing test caught that, which is
the argument for the rule being as narrow as it is - anything that
suppresses claims is worth exactly its narrowness.

Also drops the now-dead lookbehind, which a reviewer had separately (and
wrongly) called a JS syntax error; variable-length lookbehind is legal
in V8, and the module parsed fine. It goes because the line rule
subsumes it, not because it was broken.

* fix(review): parse the base rerun before its output is trimmed

`trimOutput` rescues module errors and runner summaries out of the
omitted middle, not the per-file FAIL lines this command reads. A base
suite whose failure section overruns the tail budget therefore lost
failing files into the gap - and a SHORT base set is the dangerous
direction, because netNew is the PR side minus the base side. Every file
the trim hid came back as a Critical attributed to this PR by
"measurement". Parse the raw text, report the bounded one.

The PR side cannot be fixed here: it is read out of build-test's stored
output, trimmed before this command existed. That loss runs the other
way - it understates `shared`, never invents a netNew - so the entry
carries `prTruncated` and the note says the list may be partial. A
silence-biased gap is still a gap the author should hear about.

Also names both selection caps in the mutant-skip diagnostic. The count
accumulates replacement sub-cap drops, and with 2 deletions and 6
replacements the total is exactly MAX_MUTANTS: the main cap never fires,
yet 3 are dropped, and the message sent the reader looking for a pool of
11 candidates that never existed.

* test(review): pin the `sh` set-line to exactly what the runner uses

A reviewer asked for `expect(script).not.toContain('set -e')` on a
`shell: sh` step. The opposite is correct - GitHub runs that step as
`sh -e {0}` - but the thread was right that nothing pinned it either
way. Assert both halves: `set -e` is present, `pipefail` is not. Dropping
the line makes an extracted `sh` step run past a failure the runner
stops on; adding pipefail claims a bash feature `sh` does not have.

* fix(review): rerun only the command shapes build-test emits

This command reads a report off disk and then executes the strings in it
with `shell: true`, in the base worktree. Nothing else in the pipeline
re-executes a value it read back from a file, so nothing else has to
care where that value came from - this does, and the provenance is worse
than it looks: the command is `npm test --workspace="<dir>"`, the
workspace token is a directory, and a directory is a name a pull request
chooses. `packages/x";curl …|sh;"` is a legal path in git and on Linux
and it round-trips through the report into a shell.

Restricting to the emitter's own grammar costs nothing real, since that
grammar is the two shapes build-test produces. A command outside it is
skipped and disclosed, the same treatment everything else this command
cannot do already gets, so a future shape degrades to "judge it by the
diff" rather than to arbitrary execution.

* fix(review): the working directory is a setting the extraction was losing

Two findings, both of them this file failing its own stated argument.

The stub list dropped it. `expressions` covered the script and the env
and nothing else, so a `working-directory: ${{ github.workspace }}/x`
produced an empty list and a summary line reading "0 ${{ }} site(s) to
stub" - and `expressionsOf`'s own comment says why that is the failure
this list cannot afford: the caller reads it as "these are all the
values to supply". Widened to every setting the command carries, the
`shell:` template included.

The emitted script never mentioned it. The env block is commented into
the header precisely so a reader of the script alone can see it; the
working directory changes what the script does just as much and was in
the metadata only. The argument for reading all three levels, written in
this file, is that a step run "in the wrong directory, and nothing says
so" is the transcription error the command exists to remove - which is
exactly what the header did. It is a comment rather than a `cd` for the
same reason env is comments, not exports: the value may hold `${{ … }}`
and this command substitutes nothing.

Both pinned, and both checked by deleting the fix: each mutation fails
exactly one of the two new tests.

* fix(review): $(( )) is arithmetic, and a heredoc's form decides where it ends

Three fixes and one deliberate non-fix, all measured against this repo's
own 434 `run:` steps rather than argued.

`$(( ))` was read as a command substitution, so `N=$((N + 1))` reported
`N` as a command to stub. It was the single largest source of junk in
the list: 196 distinct "commands" across the corpus, 165 without it.

A plain `<<WORD` heredoc ends only on a line that is exactly WORD; the
loose match ended it on an indented `EOF` inside the body and then read
the body as commands, which is how `rm` got reported for a script that
never runs it. `<<-` stays looser than bash (any leading whitespace, not
just tabs) because looser can only end a body early, and this file's
priority is that an under-report is the worse direction.

`[^()]*` matched only the innermost `$( )`, so `X=$(gh api $(u))` lost
`gh` - a missed stub, and the extraction reaches the network. Depth
counted now, and the assignment-prefix skip no longer steps over an
unclosed `X=$(gh` into reading `api` as the command.

The non-fix is recorded where the next reader will hit it: the quote
walk is flat while shell quoting nests, and over ~300 lines the drift
reports fragments of jq source as commands. Inserting a separator where
a blanked span was removes nine of those, but it splits `a"X"b`, which
is one word to the shell, and the minimal reproducer for the difference
is 296 lines - nothing short enough to pin it. A scanner nobody can pin
costs more than the junk it removes.

* fix(review): refuse an ambiguous step name, and report errors like the siblings

Two findings, both about a message the caller never gets.

A job may legally hold two steps with the same name. The selector took
the first and said nothing, which is the failure this file's own header
names - "picks the same-named step from the wrong job" - and it is worst
in the use the command exists for: A/B extraction runs it once per tree,
so a PR that adds or reorders a duplicate leaves the two sides comparing
different steps while reporting on one. Refused out loud now, naming the
indices; the index is always available and never ambiguous.

The handler also let every throw propagate, so five carefully separated
messages - cannot read vs cannot parse vs no job vs no step vs no `run:`
- all arrived as "An unexpected critical error occurred" under a stack
trace. `base-tree` and `test-plan` in the same directory already catch,
write the message, and set exit 1. Matched. The separation between "the
path is wrong" and "the YAML is wrong" only pays if the caller sees it.

* docs(review): the brief's list of limits was one short

"Two limits worth knowing before you spend the step" became three when
the selector started refusing an ambiguous step name, and the count went
stale in the same commit that made it wrong. This is the enumeration
drift the skill teaches, in the text that teaches it.

The added entry says what to do rather than only what happens: pass the
index, which is what an A/B wants regardless — the two trees have to
select the same step, and a name that moved between them is exactly how
they stop doing that.

* chore(review): drop a scratch probe file that reached the branch

`packages/cli/inert.mjs` was a throwaway harness for sweeping the repo's
own workflows; its cleanup ran with a relative path from the wrong
directory and it got committed by the next `git add -A`.

It failed CI and not the local hook because the two lint different sets:
lint-staged filters to `*.{js,jsx,ts,tsx}`, which does not include
`.mjs`, while CI's flat config picks the file up regardless of `--ext`.
Verified with CI's own command this time, not the hook's.

* fix(review): bound the whole ledger marker, not just each of its fields

The per-field caps leave the total unbounded: fifty findings at full
width serialize to just under 17,000 characters. The module's own
paragraph calls the marker "a footnote, never a payload" and reasons
about GitHub's 65,536-character body limit, so the total is the number
that claim is about and nothing was computing it.

Set the budget from measurement rather than from the limit. Across every
review this pipeline has posted on its own stack (n=66) the body runs a
median of 721 characters, p90 2,178, max 3,925 - the limit has ~61 KiB
of headroom, and an over-long marker was never going to fail a post. The
real cost is proportion: 17,000 characters of invisible payload on a
3,925-character review is four times more marker than review. 8 KiB
holds fifty findings at realistic widths without dropping any, and the
truncation path is reached only by a ledger no round has produced.

What it drops travels with it. A `dropped` count is the difference
between a list the next round reads as complete and one that says it is
not - the same distinction this module already draws everywhere else.

* fix(review): a partial ledger must not render as a complete one

The size cap added in the previous commit can drop entries, and the
rendered section still opened with "**Every entry below is owed a
this-round ruling**" and said nothing about what was missing. The
`dropped` count existed and reached the only place a reader sees the
list as nothing at all — which is the failure it was added to prevent,
committed one step after adding the field. It now says the list is
partial, how many are missing, and that absence is not evidence a
finding was fixed.

Second, the table escaping escaped `|` but not `\`. `\|` in a title
became `\\|`, which markdown reads as an escaped backslash followed by a
LIVE separator: the forged row the escaping exists to prevent, produced
by the escaping. Backslash first now, and the test counts separators the
way markdown does rather than by pattern, because a lookbehind counter
is fooled by exactly the input under test.

* fix(review): an empty ledger title is a cap the next round cannot lift

A comment that is nothing but its severity marker produced a ledger
entry with an empty title. That does not merely degrade the entry, it
jams the review: the next round is told every ledger entry is owed a
this-round ruling, has no claim text to rule on, answers `cannot tell`,
and `cannot-tell-existing-critical` is one of the cap reasons. Nothing
between rounds changes, so the cap comes back every round.

Dropping the entry would hide a Critical that really was posted, so it
keeps its place and gets the one handle there is - the location it was
filed at, or "the review body" for a body-level one. The field's stated
job is "enough for the next round to re-locate the claim", and that is
what a text-less finding still has.

Found by probing `buildLedger` with ten malformed comment shapes; the
other nine - carried ids, id collisions, two comments carrying the same
id, `R2D2` not being an id, a leading newline before the marker - all
behaved correctly and needed no change.

* fix(review): count both caps as dropped, not just the byte one

Found by running the three previous fixes together on one round: 51
findings in, 24 kept, and the marker said 26 were missing.
`LEDGER_MAX_FINDINGS` truncates before the byte cap ever runs, and
measuring `dropped` against the already-sliced list left the count cap's
share silent - so the field added two commits ago to stop a truncated
list reading as complete was itself under-reporting the truncation.

Measured against what came IN now, and pinned across all four
combinations: count cap alone, byte cap alone, both, and neither. Kept
plus dropped equals given, in every one.

---------

Co-authored-by: qwen-code-dev-bot <qwen-code-dev@service.alibaba.com>
Co-authored-by: Qwen Code <qwen-code@users.noreply.github.com>
Co-authored-by: Qwen Code Bot <qwen-code-bot@users.noreply.github.com>
Co-authored-by: Qwen Code Autofix <qwen-code-autofix@users.noreply.github.com>
pchaganti pushed a commit to pchaganti/qx-qwen-code that referenced this pull request Aug 1, 2026
…rol, seven lenses (QwenLM#8261)

* feat(review): borrowed-verification trio — test-plan check, base-tree A/B, per-hunk probes

- qwen review test-plan: rule on the PR Test Plan's checkable claims (paths,
  npm scripts, test counts) against the reviewed tree; contradictions and
  differing counts are disclosed via compose-review, never capping.
- qwen review base-tree: build the merge base in a sibling worktree so the
  verifier can A/B a comparative claim instead of reading it; swept by cleanup.
- test-efficacy: third probe kind — reverse-apply one hunk at a time and
  re-run the affected tests, attributing a still-green suite to the specific
  change nothing gates; shares the mutants' budget window, runs last.

* fix(review): survive real runner output — ANSI-laced and trimmed-away summaries

Both measured on a live /review of QwenLM/qwen-code#8176 with the built CLI:

- test-plan's observedTestCounts strips SGR sequences before matching; a
  color-enabled pipe interleaves them BETWEEN tokens, and the count claim
  fell to 'unchecked' with the summary right there in the report.
- build-test's trimOutput rescues runner summary lines from the omitted
  middle (like module-resolution errors): a failing suite's tail is all
  failure details and npm epilogue, which pushed the one-line summary out
  of the kept text entirely.

* fix(review): address the eight findings from live review of this branch

All measured in the review (QwenLM/qwen-code#8215 review comment):

- test-plan: linear-time bold-heading scan (the old pattern backtracked
  catastrophically on an unclosed ** line an untrusted PR body controls);
  a flag preceding the npm script yields no claim instead of a false
  'no package defines this script'.
- test-efficacy: a hunk probe's restore recreates the parent directory a
  reverse-applied 'new file' hunk removed (the ENOENT from finally lost
  the verdict and marked every remaining hunk inconclusive); hunks get
  their own skippedForBaseline instead of mislabeling a red baseline as
  a budget skip; splitDiffIntoHunks re-captures the file header at every
  diff --git boundary; a hunk-survived finding notes when it restates an
  inert file-level revert at hunk granularity.
- base-tree: idempotent fast path keyed on a build marker + HEAD check —
  concurrent verifier shards reuse one built tree instead of sweeping it
  out from under each other mid-A/B (a fabricated base-side difference
  with a deterministic source tag was the worst case); cost wording is
  now 'an install and a build' everywhere it was 'one extra build'.

* fix(cli): never score a hunk survived when its own test left the baseline (#8215)

A per-hunk probe reported `survived` whenever the green baseline probes still
passed with the hunk reverted. When the hunk's own collocated test dropped out
of the baseline (a probe-tree import error collects nothing), the remaining
green probes prove only that THEY do not cover the hunk, so the verdict is now
`inconclusive` — the same dropped-test asymmetry the mutants already hold.

Also scope the hunk-survived cross-reference note to the hunk's own collocated
test, and let test-plan match a workspace-scoped run of the plan's bare command
instead of falling through to the manifest on an exact-string miss.

* fix(review): silence-bias hardening from four live review rounds of this branch

The two blocking findings, reproduced on this PR's own Test Plan:

- test-plan files no false contradicted notes: npm rulings move from a
  four-verb denylist to an allowlist (the run form + npm's script aliases —
  the ~fifty other builtins each used to become 'no package defines this
  script'); a slash token is claimed as a repo path only with evidence (an
  extension or ./ prefix), never when it is a flag's value (--repo
  owner/repo) or under the review's own temp root; HEADING_LINE_RE drops
  the same quadratic shape its bold sibling was rewritten to remove.
- base-tree gets a real mutual-exclusion lock around sweep+add+build
  (mkdirSync test-and-set; the loser returns busy instead of deleting the
  tree the winner is mid-install in), and a failed build writes a settled
  marker so later shards stop re-paying the install to relearn
  'unavailable'.

Also: Agent 7's brief now names hunk-survived and the hunks.* counters
(it is the report's only consumer, and the finding class was invisible);
hunk findings anchor at the first ADDED line instead of up to three
context lines above the change.

* feat(review): four round-2 borrowings — measured failure attribution, round ledger, richer mutants, doc parity

Shaped by a live round-2 maintainer re-verification (QwenLM/qwen-code#7818):

- qwen review test-delta: rerun the PR side's failed test commands on the
  built merge base and diff the failing FILE SETS — netNew is the PR's own
  failure by measurement (whatever files the diff touches), shared is
  pre-existing by measurement. Counts are never compared: a flaky suite
  fails different test names between runs of the same tree. An unfinished
  base rerun attributes nothing.
- Round ledger: the incremental review cache persists confirmed findings
  under round-scoped ids (R1-2); a high-effort re-review rules on each
  (fixed / still stands / cannot tell) and opens its report with the table,
  the way a human round-2 comment opens with 'M1 is fixed'.
- Three replacement mutation operators in test-efficacy: drop '?? fallback',
  force a comparison-bearing guard condition to 'true', drop a '+ CONST'
  term. Each survivor maps to one crisp untested-protection sentence.
  A line whose raw text and literal-blanked code view disagree yields no
  candidate — an edit index computed across the two views once spliced
  'iftrue 0)' into a guard, and a mangled mutant reads as inconclusive
  while quietly spending a cap slot.
- Quality brief: documentation-parity lens — a new user-facing surface whose
  siblings are documented is a Suggestion naming the sibling precedent; no
  documented sibling, no finding.

* feat(review): render adjudication, workflow step extraction, three verification lenses

Shaped by a live sanitizer-PR verification (QwenLM/qwen-code#8147):

- Render-adjudication capability (opt-in): with QWEN_REVIEW_SCRATCH_REPO
  set, the verifier may post a minimal payload to that user-designated repo
  and rule on GitHub's own rendered HTML — the measured case being an
  @ -> &#64; defusal every local reading called sound while GitHub's real
  renderer registered the mention and fired the notification. Absent the
  setting, rendering claims honestly cap at low confidence / cannot tell.
  Step 7's write ban names the carve-out explicitly.
- qwen review extract-step: lift one workflow step's run: script verbatim
  into an executable, with env (as comments, never half-substituted
  exports), every ${{ }} site listed unevaluated, and a heuristic invoked-
  command list as the stubbing starting point. With base-tree, both arms of
  a by-hand workflow A/B become two invocations. yaml declared as a cli
  dependency (previously resolved only via hoisting).
- Three brief lenses: a borrowed protection idiom missing what made it work
  at home (the code ancestor did the protecting; only the entity was
  copied); a second parser for an authoritatively-parsed format is a
  divergence hunt; tests that pin the mechanism instead of the effect, and
  oracles that mirror the implementation's own model.

* feat(review): sibling-entrance discipline for the fixed verdict

From round 6 of the live sanitizer verification (QwenLM/qwen-code#8147):
the fix closed the fence-shaped entrance into a raw-HTML block, and the
code-span entrance beside it — same divergence, adjacent syntax — stayed
open. A re-check that tests only the reported input rules 'fixed' over a
hole one backtick away.

Both fixed-verdict sites in SKILL Step 6 (the open-Criticals re-check and
the round ledger) now require enumerating a divergence-class defect's
sibling entrances before ruling fixed; a still-open sibling is a NEW
finding, never a reason to withhold the original's fixed — the two
rulings stay separate so the second hole cannot ship unreviewed.

* feat(review): three measured-verification lenses from live rounds 8037/8005

- Threshold-boundary scan: when a fix is a ratio/length guard, hold the
  issue's own variables fixed and binary-search the boundary where the
  behaviour flips; put the number next to what the issue reports. Live
  case: a prose-ratio guard covered the edit/write_file half of its issue
  and silently declined the run_shell_command half (~473-char boundary).
- Delimiter self-injection named as the first parser-differential probe:
  a no-escaping extractor fed its own close tag truncates silently.
- Shared-gate state enumeration: a deliberate-design defence extends only
  to the states it argues — an input-hold argued for 'active' silently
  froze three idle states sharing the same gate. The sibling-entrance
  rule, applied to a state machine instead of a syntax.

* feat(review): carry the round ledger in the posted review body

The ledger shipped as a local cache file and its first multi-round live
use exposed the flaw: four model-comparison rounds re-reviewed the same
two PRs and every round opened from scratch — medium never reads the
cache, and from CI or another clone there is no cache at all. The one
artifact every environment can see, the posted review, carried nothing
machine-readable.

- compose-review embeds an HTML-comment marker (invisible on GitHub)
  carrying this round's findings and round number; the round comes from
  the side file pr-context recovered, +1 — never from the model.
- pr-context recovers the reviewing account's latest marker, renders it
  as a 'Previous /review round (machine ledger)' work-list section, and
  writes it beside the context file for compose-review's round counter.
  Own-account only, latest round wins, fail-quiet on any malformation —
  the marker is data the next round rules on, never authority it obeys.
- Step 6's previous-round ruling now runs at medium too (recovery is
  free; medium still writes no cache and posts nothing); the local cache
  is demoted to fallback for rounds that never posted.

* fix(review): address review feedback — false-positive hardening, binary diff guard, error convention (#8215)

* fix(review): address review feedback — base-tree availability gate, test-plan false positives, hunk-probe ranges (#8215)

- base-tree: only stamp a base tree available when runBuildTest actually
  compiled something (ok AND npm toolchain AND a non-empty build). An
  `unsupported` handoff or an empty npm scope returns ok:true having built
  nothing; marking that tree available let an A/B read the absence of a build
  as a behavioural difference.
- cleanup: sweep the stale base-tree build lock a killed builder leaves behind.
- test-plan: read the root manifest's scripts directly so a root-only script
  survives when the root defines no build/test; bail on the inline --root=./dir
  rebasing form; stop treating a positional after an inline --flag=value as the
  flag's value; prefer a failed scoped run when ruling a bare command; anchor
  the npm script alias to a full token so `yarn test:unit` is not truncated.
- test-efficacy: exclude `\ No newline at end of file` from the startLine offset
  count; compute the mutant-overlap range from the header's new-side span so it
  no longer overshoots into a closely following hunk.

* feat(review): mined disciplines — effective-diff guard, positive control, seven lenses

From a full sweep of 108 maintainer verification comments (2026-07-31):

- fetch-pr detects an EMPTY merge-base diff (work already landed — the
  skill stops and recommends close-as-superseded) and a diff collapsed to
  a residual by overlapping merged PRs (disclosed; body claims about the
  rest are description-of-history).
- test-efficacy runs a POSITIVE CONTROL before spending the mutant window:
  an injected always-failing test must turn the runner red, or every
  would-be survivor is re-classed inconclusive — a dead runner cannot
  kill, and its survivors were the false gap-reports measured live.
- Brief lenses: tested-fix + contamination statement; race verdicts as
  rates with load amplification (lower idle rate without structural
  change is luck); triangulate-and-label for unreachable authorities;
  arm-identity and comparator negative-control for A/B; deleted code's
  incidental effects; self-defeating fallbacks (trigger set within
  cannot-succeed set); reachability adjudication (fix vs scaffolding);
  flipped-assertion audit; shape-vs-provenance authorization probing.

* fix(review): four fixes from the stack's own round-2 reviews

- test-delta (Critical, #8218 review): a base rerun that fails with ZERO
  parseable failing files (install/toolchain failure) no longer reads as
  'base green' — it attributes nothing, like a timeout, instead of
  promoting every PR-side failure to net-new.
- extract-step (Critical, #8225 review): every line of a multi-line env
  value is comment-prefixed — an unprefixed block-scalar second line sat
  in the emitted script as an executable line.
- extract-step: expressionsOf no longer misses expressions containing
  their own brace (format('{0}')).
- cleanup (#8215 review): sweeps an orphaned base-tree build lock, which
  otherwise wedges the A/B for that PR permanently.

* fix(review): close the remaining round-2 findings across the stack

- selectMutants: replacement operators get a 3-slot sub-cap inside the
  shared cap — measured 24x pool inflation (215 vs 9 candidates over 40
  real commits) was draining the time window hunk probes draw from last,
  silently un-shipping the hunk-survived finding class; sub-cap drops are
  counted in skippedForCap.
- test-delta: whole-command budget (540s, mirroring test-efficacy) so
  three failed commands cannot blow the 600s tool ceiling and lose the
  report; run() regains build-test's three deliberate properties (stdin
  ignored, error.code/SIGTERM timeout detection, trimmed output).
- test-plan: pasted unified diffs inside Evidence blocks shed no path
  claims (+++ b/<path> once ruled contradicted on a correct body);
  gitignored paths rule unchecked — absent at the reviewed commit by
  construction, the .qwen/ reasoning generalized.
- agent-prompt: the Agent 7 efficacy block now enumerates all FOUR
  finding kinds including hunk-survived, the hunks.* skip counters, and
  harnessValidated — the brief and the block in the same prompt no longer
  present two different complete sets (the sibling-enumeration lesson,
  applied to our own prompt).

* fix(review): address review feedback — diff-header false positives, stale prompt enumeration, added-file hunk probes (#8215)

* fix(review): close the round-3 findings on the stack

#8261 review:
- the dead-harness re-class now runs BEFORE findings are built (a failed
  positive control could still file survivor findings — the Critical);
  it also covers the file-level revert probe's inert verdicts, the
  control pays for its run out of the shared budget (no more silently
  eaten skippedForBudget slot), a failed control stops the window instead
  of manufacturing survivors to re-class, and its note names all three
  causes that share the green-control shape.
- emptyDiff no longer fires on a FAILED diff capture (close-as-superseded
  off an infrastructure error would close a live PR); countDiffChangedLines
  counts --x/++x body lines.

#8215 review:
- the cd target itself is no longer claimed as a path (a bare dir carries
  no evidence; only the file tokens it resolves are);
- 'Test Files N passed' is a FILE count — variable-length lookbehind
  keeps it out of the test-count claims;
- base-tree's handler gains the pipeline's catch-and-exit-1 convention;
- probeCreateFailureDetail folded into the shared
  worktreeCreateFailureDetail.

* fix(review): address review feedback — cd-base exclusion, Test Files count guard, base-tree error handling, probe delegation (#8215)

* fix(review): port the collocated-dropout test to the post-#8050 runner seam

Merging main brought #8050's Windows-portability refactor, which resolves
the probe runner through vitest/package.json's bin — a node_modules/.bin
fake is dead weight it never reads. The 8215-only collocated-dropout test
still installed the old .bin fake, so the REAL vitest ran its fixtures,
price.test.ts genuinely passed, and the hunk scored survived. The test now
overrides the fake package's vitest.mjs like every post-refactor test.

* fix(review): close the round-4 findings from both stack reviews

From the #8215 review: trimOutput's summary rescue is capped at 40 lines
(uncapped, 40k lines of 'Test <n>: …' prose made the whole trim a no-op —
1.6MB in, 1.6MB out); a spaceless # line is prose per the ATX rule GitHub
applies (a pasted #!/bin/bash outside a fence once ended the Test Plan
mid-body), with the bare-#-run crash on the closing scan guarded; a
base-tree build lock older than 30 minutes is a corpse and is swept
rather than reporting busy for the rest of the review.

From the #8261 review: a pasted diff's BODY lines shed no path claims
(-packages/old/gone.ts matched PATH_RE and ruled a false contradicted —
the syntax-line filter alone was vacuous against the real failure mode);
a gitignored file that nonetheless EXISTS rules reproduces (the ignore
guard only ever downgrades a would-be contradiction); test-delta's note
now explains each unattributed command (timeout vs toolchain failure)
instead of leaving the reader to infer why it is in neither list.

* fix(review): bound the summary rescue, apply the ATX heading rule, sweep stale build locks

The three 8215-layer findings from the latest review, fixed at this
layer (they were first patched further up the stack, where the reviewer
of THIS PR cannot see them):

- trimOutput's summary rescue is capped at 40 lines — uncapped, 40k
  lines of 'Test <n>: …' prose voided the trim entirely (measured 1.6MB
  in, 1.6MB out) and the bounded-output contract is the whole point.
- A '#' with no following whitespace is prose, not a heading (the ATX
  rule GitHub applies): '#8176', '#tag', an unfenced '#!/bin/bash' no
  longer end the Test Plan section mid-body; the bare-#-run crash on
  the closing scan is guarded.
- A base-tree build lock older than 30 minutes is a corpse left by a
  killed builder — swept and rebuilt instead of reporting busy for the
  rest of the review.

* fix(review): EEXIST-only lock busy, bun test alias, chained cd bail, fence backreference

Four live findings from the latest inline review round (the rest of the
round was already fixed upstream by the takeover bot - verified by
probing head behavior rather than re-reading the threads):

- base-tree's lock catch distinguishes EEXIST (a concurrent builder,
  busy) from EPERM/EROFS/ENOSPC (this run's own failure, reported as
  such, not as a busy that will never clear).
- "bun test" is bun's built-in runner, not a package-script alias: it
  runs whether or not any manifest defines test, so ruling it against
  the scripts table filed a false contradicted.
- A chained cd matches the leading-cd shape but the single-hop resolver
  joined file tokens against the FIRST directory; it now bails like the
  exotic-cd case.
- codeSpans' fence regex closes on its own marker via backreference; a
  tilde fence line inside a backtick block ended the span early and
  lines after it were lost to extraction.

* fix(review): make the ledger marker actually reach the posted body

Three Criticals from the #8255 review, all real:

- The marker was appended in the CLI handler, AFTER composeReview()
  returned, so it only ever reached the composed JSON on disk. submit
  posts what the PURE function returns, so no posted review carried a
  marker, latestOwnLedger always returned null, and the whole feature
  was inert end to end. The append now lives inside composeReview, fed
  by a draftedComments seam that both CLI boundaries fill from the same
  array they count (and both strip from a model-written state JSON).
  Three end-to-end tests now assert on the body composeReview returns.
- pr-context's side-file write preceded the mkdir that creates its
  directory and was unguarded: an ENOENT failed the whole command over
  a best-effort carry-forward. mkdir first, write guarded.
- CANONICAL_LGTM_RE is anchored, so a trailing marker made every no-op
  round "worth showing" and prior rounds started rendering in full. The
  marker is now stripped before the filter and the count walk, not only
  before rendering.

Plus the three thread findings: ledger cells are escaped before landing
in the context table (a title with a pipe could forge rows), parseLedger
takes the LAST marker and type-checks/normalises what it recovers, and
the stray verdict doc comment is reattached to verdictLine.

* fix(review): close the ten open findings on this PR

- guard-true tested for a comparison anywhere after `if (`, including the
  then-body, so `if (ready) emit(a !== b);` admitted a mutant on the
  comparison-less condition the gate exists to exclude. It now tests the
  condition span only.
- The `survived` detail said "when it changes" for legacy DELETION
  mutants too; it now matches the operator.
- test-delta's `unparsed` required both sides to parse zero files, so a
  PR-side failure whose FAIL lines the trim scattered was silently
  dropped whenever the base rerun happened to parse. netNew/shared come
  from the PR side, so the PR side alone decides.
- failingFilesOf now matches Windows path shapes (backslashes, C:) - a
  missed parse is an unattributed failure, not a loud error.
- The replacement branch of runOneMutant (write-file -> run-probe ->
  classify) had no end-to-end test; one now drives a coalesce operator
  through the real handler and asserts the mutated line, the verdict,
  the operator-specific wording, and that the shared tree is untouched.
- Two tests were vacuous with respect to what they promised: the
  baseline-dir test never asserted the cwd (its helper swallowed the
  argument - fixed at the helper), and the one-candidate-per-line test
  used an input that never triggered the replacement path, so the
  `continue` under test was not load-bearing.
- Reattached the orphaned selectMutants JSDoc; reworded the SKILL line.

* fix(review): the test helper's cwd parameter is required, not optional

CI's `tsc --build` failed on test-delta.test.ts: the exec seam always
passes a cwd, but the helper's signature marked it optional, so pushing
it into a string[] was `string | undefined`.

Missed locally because vitest runs through esbuild, which strips types
without checking them - the suite was green while the build was red. The
gate to run before pushing a type-level change is `npx tsc --build`, not
the test suite.

* fix(review): a base rerun that could not RUN attributes nothing

Two Criticals from the latest review, both reachable on the brief's own
happy path:

- baseUnusable covered only timeouts. Every other way the base side can
  fail to run - an unbuilt base tree, a missing install, a workspace the
  PR ADDED (npm test --workspace cannot resolve on base), an ENOBUFS
  truncation - exits non-zero with zero FAIL lines, which this code read
  as a green base. Every PR-side failure then became netNew: the
  strongest evidence the command emits, manufactured from a base that
  never ran a test. It now attributes nothing and says why.
- Timeout detection was the weaker substring form the sibling explicitly
  rejects; an external SIGTERM (container stop, cancelled job) set
  neither an ETIMEDOUT message nor an exit code and fed straight into
  the above. build-test now exports spawnTimedOut and test-delta asks
  the same question rather than re-deriving it.

Also: the base output is trimmed (it precedes the verdict fields in the
report the agent reads, so an untrimmed megabyte truncates exactly what
the command produces); the guard-true gate no longer reads an arrow
function's => as a comparison (every predicate guard was a candidate -
the if (ready) noise the gate exists to exclude); the term-drop message
no longer calls a string concatenation a reserve term; the unparsed note
describes its own PR-side-only condition; and the ledger's Step 6/Step 8
now agree that a still-standing finding keeps its id.

* fix(review): extract-step resolves all three env/defaults levels, and comments every env line

Two silent-wrongness defects in a command whose whole value is fidelity.

`env:`, `shell:` and `working-directory:` are three-level settings on GitHub —
workflow, job, step, nearest wins — and only the step level appears in the
step's own text. Reading step-level alone reproduced by machine the exact
transcription error this command exists to remove: measured, a step under a
job-level `NODE_ENV: production` and a workflow-level `GLOBAL_FLAG` extracted
with `env: { LOCAL: '1' }` and `workingDirectory: undefined`, so the emitted
script ran with both unset and nothing said so. Not a contrived shape: this
repo carries workflow-level `env:` in 7 workflows, job-level `env:` in 10, and
job-level `defaults.run` in qwen-triage.yml — the workflow the command's own
test plan names. The three levels now merge with the runner's precedence, and
`envSources` records which level each key came from, so an inherited value is
visible rather than indistinguishable from the step's own.

The env block was commented per ENTRY, not per LINE. A YAML block scalar
(qwen-autofix.yml's `SETTINGS_JSON: |-`) reaches the header as a multi-line
string, so its continuation lines landed in command position — and under the
`set -e` the header itself emits, the extracted step died in its own preamble
before its `run:` body ran. Every line is commented now.

Tests pin the effect, not the mechanism: `executableLines()` asserts nothing
but the `run:` body ever reaches command position, plus a `bash -n` parse
check. Verified to flip — all five new assertions fail against the pre-fix
implementation (`{ LOCAL: '1' }`, `undefined` working directory, three
executable lines instead of one, and a real `bash -n` syntax error).

* fix(review): compare failing files by a normalised, project-keyed identity

Critical: the two sides run in DIFFERENT roots (the PR worktree and the
base tree), and netNew/shared compared the parsed paths verbatim - so an
absolute-path runner turned every pre-existing failure into a fabricated
Critical, with the authority of a measurement behind it. Paths are now
normalised against each run's own root (and backslashes to /, so a
Windows path compares with its POSIX-printed twin), which is why
test-delta gained --pr-worktree.

The identity also keeps the vitest project token: dropping it collapsed
same-named test files across workspaces, so a PR-caused failure in one
package could read as pre-existing because another package has a file by
the same name - the worse failure direction.

Also from the same review, all of them reachable on the brief's own path:

- The base rerun now inherits build-test's stdio: ['ignore','pipe','pipe']
  ("a build that asks a question is a build that hangs until the
  deadline") and its trimOutput, which matters because entries[].base
  precedes the verdict fields in the report the agent reads.
- The brief gates on base-tree's `available`, not just its `path`: a tree
  that was created but did not build populates path too, and measuring
  against it turns an infrastructure failure into Criticals.
- A programmatic caller omitting `timeout` no longer sends NaN into
  spawnSync.
- MutantCandidate is a discriminated union, so an operator without its
  replacement line - which would delete a line while reporting "with its
  ?? fallback dropped" - is unrepresentable.
- The comparison class no longer requires a trailing space (if (a<b) is
  the same guard, just unformatted) and matches a brace-less else if.
- DeltaEntry.unparsed's doc now describes the PR-side-only condition it
  actually implements.

* fix(review): restore the whole-command budget, keep generics out of guard-true

Round-1 findings from a fresh review of this PR:

- test-delta had no aggregate deadline: --timeout is PER command and
  defaults to 300s, so three failed commands is 900s against Agent 7's
  600s ceiling - killed with NO report at all, discarding the base-tree
  install and build just paid for. TOTAL_BUDGET_MS mirrors the one
  test-efficacy reserves; commands it cannot fit are disclosed.
- guard-true matched generic calls: `if (isRecord<string>(v))` produced a
  mutant, and a type-guard predicate is exactly the `if (ready)` shape
  whose survivors the gate calls noise. The trailing \s is required, not
  an accidental asymmetry with [!=]== - telling `a<b` from `fn<T>(x)`
  needs a parser, and the gate is silence-biased by design.
- --pr-worktree had no contract test, and its failure mode is the worst
  here: arriving undefined, root stripping silently stops and every
  pre-existing failure becomes a fabricated netNew. The new test feeds
  parseSync's output straight into runTestDelta and asserts an
  attribution only reachable when both roots were stripped (verified
  red against the snake_case field shape that shipped once already).
- Merged the two consecutive doc comments on prWorktree.

* fix(review): a budget-shortened deadline is not the same fact as a slow rerun

Round-2 finding on the budget just restored: `Math.min(perCommandMs,
remaining)` can hand a rerun far less than --timeout, and if it dies
there the note said only "timed out - infrastructure, not evidence".
True, but it sends the reader hunting a hang that is really an exhausted
budget - and unlike a real timeout, a rerun with budget to spare would
still measure it. The note now names those commands separately and says
so. Verified red against removing the tracking line.

* fix(review): brace-tolerant stub list, pipefail fidelity, and extract-step in the briefs

Round-3 findings on this PR, fixed.

`expressionsOf` matched `[^}]*`, so any expression containing a brace —
`format('refs/pull/{0}/head', …)`, `fromJSON('{"a":1}')` — was not mis-listed
but DROPPED. A stub list reads as "these are all the values to supply", so a
silent omission is a value that never gets stubbed. It now scans forward to the
closing `}}`, and reports nothing for an unterminated site rather than
swallowing the rest of the text.

Declaring `shell: bash` is not the runner's default `bash`. The default is
`bash -e {0}`; a declared `bash` (at any level) is
`bash --noprofile --norc -eo pipefail {0}`, and a pipeline whose middle stage
fails aborts under one and not the other. The header now carries `set -eo
pipefail` or `set -e` accordingly — 163 of this repo's 434 `run:` steps are
under a declared bash and were getting the weaker one. A `shell:` value is also
a command template (`perl {0}`), so only its first word goes in the shebang and
the whole template is recorded beside it.

`extract-step` was registered on the CLI and mentioned in DESIGN.md, and
nowhere in SKILL.md or the agent briefs — the runtime prompts. The capability
was unreachable by the agents it was written for. The verifier's brief now
carries it next to the A/B paragraph it composes with, and Step 4 summarises it.

Also: env ordered nearest-first (measured on qwen-autofix.yml:route:0, merge
order put 20 inherited entries ahead of the step's own 26 in a 49-line header);
a valueless `FOO:` renders as the empty string, not `"null"`, and a non-scalar
as JSON rather than `[object Object]`; a missing file no longer reports as a
parse failure; DESIGN.md's lens count matches its list.

The test oracle is rebuilt around the property instead of a filter: the file is
the header plus the body verbatim, and every line before the body is a comment
or a directive the test names. The old helper dropped `set -e` unconditionally,
so it could not tell the header's from one the body legitimately contains — and
would have gone green on a header that leaked exactly that line. 434 real `run:`
steps swept: 0 non-verbatim bodies, 0 live header lines, 0 missed expression
sites, 0 out-of-order env, 0 `bash -n` failures.

* fix(review): restore the replacement sub-cap, stranded on a downstream branch

Round-3 finding, and the third instance of one class: an 8218-layer fix
committed on the 8261 branch, four PRs above the code it belongs to.

Measured over 40 real commits, the replacement operators produce ~24x
the deletion pool (215 vs 9 candidates; guard-true drives it). Every
mutant run drains the same window hunk probes draw from LAST, so
uncapped, most diffs with any replacement candidates leave hunk probing
zero runs - the hunk-survived finding class silently stops firing and
nothing says so. Three slots, and what the sub-cap drops is counted in
skippedForCap rather than lost.

Also swept the other direction: diffed every review file against its
8261 copy to confirm nothing else 8218-layer is stranded up there. The
remaining divergence is 8261's own (the positive control, its lenses).

* fix(review): one severity predicate, carried ids, and a lossless marker

Round-1 review of the ledger marker, six findings.

Two contradicted contracts this package already states elsewhere:

- `buildLedger` restated the severity predicate as a bare `startsWith`
  while `severityOf` — what `countInlineFindings` and the unmarked-comment
  gate both use — trims first. A Critical whose body opened with a newline
  was counted, was posted, blocked the merge, and was silently absent from
  the ledger, shifting the id of every finding after it. It classifies
  through `severityOf` now, and strips the marker with the shared prefixes
  instead of a second copy of the literals.

- Ids were assigned by array position every round, so the report saying
  `R1-2 still stands` shipped beside a marker recording that claim as
  `R3-4` — and `LedgerFinding.id` documented itself "stable across
  re-reports". Step 6 now mandates writing the original id into the
  re-report (`**[Critical]** R1-2: …`), `buildLedger` reads it back, and a
  duplicate or absent id falls back to the next free id of this round.

Four smaller ones:

- `stripLedgerMarker` removed only the FIRST marker while `parseLedger`
  reads the LAST, so a body holding two leaked the trusted marker into
  model-facing prose and un-filtered the canonical LGTM it was appended to.
- The `--` guard rewrote data to an em dash: a finding about `--comment`
  reached the next round as `—comment`. It escapes at the JSON layer now,
  which is comment-safe and lossless.
- `file` was capped on read (200) but not on write; the cap is one
  constant binding both halves.
- `submit`'s path — the one GitHub's payload is built from — had no test
  that the marker reaches the posted body.

Plus: tie-break `latestOwnLedger` on review id when `submitted_at` ties,
neutralise a backtick in the location code span, skip the `currentUser()`
round-trip when the PR has no reviews, and say why a stale side file is
deliberately left in place.

* docs(review): complete the "delta cannot rule" enumeration in both places

Round-4 finding. The brief and SKILL.md each listed three cases where
test-delta attributes nothing - unparsed, timed-out base, no merge base -
but the code has five: the later rounds of this PR added "a base rerun
that failed without naming any failing file" (it did not measure the
base) and "a command the whole-command budget could not fit". Two
enumerations of the same set with different membership, in the two
places an agent reads.

That is the sibling-enumeration lesson this skill teaches, applied to
its own prose for the second time: the fix is not just adding the
missing members but saying that the report names each case with its own
reason rather than folding them into one.

* fix(review): the invokes list was mostly prose, not commands

Round-4 finding on this PR. `invokes` is documented as a heuristic starting
point, and imprecision is fine — but measured over this repo's 434 real `run:`
steps it was reporting 435 distinct "commands", 267 of them appearing exactly
once, with a worst case of 63 entries made up of words like `CI`, `Evidence`,
`PR` and `and`. A list that size, mostly prose, is not a starting point.

Three causes, each measured:

- A `${{ … }}` expression is not shell, and it routinely contains `||`.
  Splitting on that as a pipeline separator reported both operands as commands
  (`matrix.arch`, `github.event.inputs.version`). Expressions are now masked to
  an opaque token before the split; one sitting in command position contributes
  nothing, which is honest — what it expands to is unknown here by design.
- A heredoc body is input to a command, not a list of them. Its lines were
  scanned as commands, terminator included. 12 steps in this repo carry one.
- The `name=value` skip stepped over the prefix and took the NEXT word as the
  command — but for a quoted value with spaces that word is inside the value:
  `EVIDENCE_SECTION=$'### Evidence images'` reported `Evidence`. Quoted spans
  are now blanked out, with the quote carried across lines so a multi-line
  string's continuation lines are data too. Command substitutions are read
  first, so `body="$(sanitize < "$REPORT")"` still reports `sanitize`.

A `#` preceded by whitespace ends the live part of a line, so an apostrophe in
a trailing comment cannot open a span and eat the rest of the script.

Measured after: 435 distinct commands to 187, singletons 267 to 104, worst case
63 to 27 — and the worst case is now real commands (`awk cat chmod curl git jq
mktemp pkill tar tee timeout`) plus the script's own shell functions. Also
added the builtins a stub could not intercept anyway (`eval`, `exec`, `source`,
`unset`, `command`, …) to the keyword set.

434 steps re-swept: 0 non-verbatim bodies, 0 live header lines, 0 missed
expression sites, 0 out-of-order env, 0 `bash -n` failures.

* docs(review): the rationale named only one of the ways base goes unmeasured

Third and last copy of the enumeration the previous commit fixed. The
bullet's headline already generalised - "base attributes nothing it did
not finish" - but its body named only the timeout, so a reader learning
the contract from the rationale would conclude timeouts are the only
unusable case. Name the set, and say why the report keeps the reasons
apart: "we could not measure" and "we measured nothing" are different
facts to the author, and only one of them is about their PR.

* fix(review): a quoted `<<EOF` is not a heredoc, and a continued line is one command

Round-5 findings, both in the previous commit's own scanner.

A heredoc opener was matched over the whole line, so one inside a string
started heredoc mode: `echo "write <<EOF for a heredoc"` made every later line
wait for a terminator that never arrives. The failure is not a missing entry
but a missing REST — measured, a three-line script returned `[]` instead of
`[curl, jq]`, empty and entirely plausible. Opener detection moved inside the
quote walk, where it only fires outside quotes; the quoted forms (`<<'EOF'`)
are consumed by the match, so their quotes never open a span either.

A backslash-continued command was scanned as several lines, which puts the next
ARGUMENT in command position — this is where `apt-get install -y \` /
`  libx11-dev` reported the package as an invoked command. Continuations are
now joined into one logical line before scanning.

Measured after: 187 distinct commands to 185, and the singleton tail is now
dominated by real ones — PowerShell cmdlets, macOS tooling, and the scripts'
own shell functions. 434 real steps re-swept: 0 non-verbatim bodies, 0 live
header lines, 0 missed expression sites, 0 out-of-order env, 0 `bash -n`
failures.

* fix(review): case labels, a second heredoc, and an expression in command position

Round-6 findings, from running the scanner against adversarial shapes rather
than reading it again. Two are UNDER-reports, which is the worse direction: a
command missing from the list is a stub the verifier never writes, so the
extraction reaches the real network.

- A `case` pattern label stopped the scan on its own line: `blocked) gh api x`
  reported nothing, losing `gh`. The label is now stepped over like a `name=`
  prefix.
- Only the first heredoc opener on a line was tracked, so `cat <<A <<B` left
  the second body and its terminator read as commands (`B`, `y`). Openers are
  queued and consumed in order.
- Masking an expression to a QUOTED token let the quote-stripper delete it
  entirely, so `${{ steps.x.outputs.cmd }} arg` reported `arg` as the command.
  The token now survives stripping and cannot match a command word, so an
  expression in command position contributes nothing.

Ten further adversarial shapes were already correct and are pinned as
regression guards: nested `$( )` in quotes, subshells, function definitions,
indented heredoc terminators, backticks, bare redirects, adjacent and empty
`${{ }}` sites, and a JSON literal inside an expression. Verified to flip —
exactly the three above fail against the previous commit, the other ten pass.

434 real steps re-swept: 0 non-verbatim bodies, 0 live header lines, 0 missed
expression sites, 0 out-of-order env, 0 `bash -n` failures.

* fix(review): annotate the continuation accumulator so tsc can type it

`invokedCommandsOf`'s backslash-continuation loop failed to compile with
TS7022: the narrowed type of `pending` at the join line is the union of
the loop-entry value and the back edge, and the back edge is computed
from the join itself. The declaration's own annotation does not break
that cycle - control-flow narrowing runs after it - so the checker gives
up and calls the result `any`.

Caught only on a forced rebuild. `tsc --build` had been reporting this
tree clean off a stale .tsbuildinfo, which is the same shape of gap that
put a type error into CI last week: the test runner strips types, so the
suite stayed green either way. Gate with --force.

* fix(review): a file-count label stops counting at the end of its line

`Test Files  45 passed` filing its 45 as a differing TEST count was
fixed once, with a lookbehind on the bare-count pattern. That only ever
rejected the all-green shape. The moment any file fails, the runner
prints `Test Files  1 failed | 44 passed (45)`, the label is no longer
adjacent to the number, and 44 comes through as a test count - so the
note reads "claimed 44, observed 1323" on exactly the runs whose summary
someone would paste. Adjacency was the wrong invariant; the line is.

Masking from the label to end-of-line is distance-independent and picks
up jest's `Test Suites: 1 failed, 44 passed, 45 total` at no cost. The
label keeps its `Test` word on purpose: a first cut matched a bare
`files` and blanked the line in "expect all four files and 471 tests to
pass", silencing a real claim. An existing test caught that, which is
the argument for the rule being as narrow as it is - anything that
suppresses claims is worth exactly its narrowness.

Also drops the now-dead lookbehind, which a reviewer had separately (and
wrongly) called a JS syntax error; variable-length lookbehind is legal
in V8, and the module parsed fine. It goes because the line rule
subsumes it, not because it was broken.

* fix(review): address round-1 review of the mined-disciplines batch

The positive control could state a verdict it never measured, and its own
failure path shipped untested. Ten findings from the review of #8261:

- `runControlMutant` returns `boolean | null`. An unreadable probe file
  injected no test and ran nothing, but returned `false` — which the caller
  reads as "the injected always-failing test stayed green", re-classes every
  survivor with that sentence, and discards the whole mutant/hunk window over
  an I/O error. `null` is the file's own third-outcome rule; the window stays
  spendable and the note says the harness was not validated.
- `mutants.skippedForControl` / `hunks.skippedForControl`. A control that came
  back red stopped the run with candidates unprobed while every `skipped*`
  counter read 0 — the silent cap the brief teaching agents to read those
  counters rules out. Their own reason, not the budget's.
- Cover the control's failure half: a dead-runner integration case (survivors
  re-classed, revert probe's `inert` re-classed, findings empty, nothing
  spent) and a could-not-set-up case pinning that `null` does NOT discard the
  window. Both branches, and the re-class block, were previously unreachable
  by any test.
- `rulePath`: one existence check, not two. The second was unreachable behind
  the first and its note — "exists at the reviewed commit (the diff does not
  change it)" — silently retired, collapsing tracked state and this run's
  build output onto one sentence. The ignore status now picks the wording.
- `expressionsOf`: forbid the body from crossing another `${{`. A malformed
  site above a real one swallowed it into the blob, so
  `${{ github.event.comment.body }}` stopped being enumerated as an injection
  site — the one direction this helper must not fail in.
- `countDiffChangedLines`: count by hunk position, not prefix shape. A deleted
  line whose content starts `--` arrives as `--- …` (markdown rules, YAML
  markers, SQL comments), and every dropped line pushes the ratio toward a
  false `collapsedFromUpstream`.
- `emptyDiff` is gated on `baseFetchFailed` too. A stale local base ref that
  already contains the head commits diffs to empty, and the skill acts on that
  by recommending close-as-superseded.
- `test-delta`: price the budget slot against the command's own measured
  duration instead of a flat 5s floor, which admitted commands that could only
  time out and then disclosed them as "infrastructure, not evidence".
  `skippedForBudget` becomes a structured field; `now` becomes a seam so the
  test stops reassigning the global `Date.now`.
- Drop `probeCreateFailureDetail` (no production caller after the swap to
  `worktreeCreateFailureDetail`) and the duplicated base-lock sweep in
  `cleanup.ts`, ten lines above the identical pre-existing one.
- `--` before the path in `check-ignore`, and the comment says plainly that no
  `-`-leading claim survives extraction today.

* fix(review): parse the base rerun before its output is trimmed

`trimOutput` rescues module errors and runner summaries out of the
omitted middle, not the per-file FAIL lines this command reads. A base
suite whose failure section overruns the tail budget therefore lost
failing files into the gap - and a SHORT base set is the dangerous
direction, because netNew is the PR side minus the base side. Every file
the trim hid came back as a Critical attributed to this PR by
"measurement". Parse the raw text, report the bounded one.

The PR side cannot be fixed here: it is read out of build-test's stored
output, trimmed before this command existed. That loss runs the other
way - it understates `shared`, never invents a netNew - so the entry
carries `prTruncated` and the note says the list may be partial. A
silence-biased gap is still a gap the author should hear about.

Also names both selection caps in the mutant-skip diagnostic. The count
accumulates replacement sub-cap drops, and with 2 deletions and 6
replacements the total is exactly MAX_MUTANTS: the main cap never fires,
yet 3 are dropped, and the message sent the reader looking for a pool of
11 candidates that never existed.

* test(review): pin the `sh` set-line to exactly what the runner uses

A reviewer asked for `expect(script).not.toContain('set -e')` on a
`shell: sh` step. The opposite is correct - GitHub runs that step as
`sh -e {0}` - but the thread was right that nothing pinned it either
way. Assert both halves: `set -e` is present, `pipefail` is not. Dropping
the line makes an extracted `sh` step run past a failure the runner
stops on; adding pipefail claims a bash feature `sh` does not have.

* fix(review): rerun only the command shapes build-test emits

This command reads a report off disk and then executes the strings in it
with `shell: true`, in the base worktree. Nothing else in the pipeline
re-executes a value it read back from a file, so nothing else has to
care where that value came from - this does, and the provenance is worse
than it looks: the command is `npm test --workspace="<dir>"`, the
workspace token is a directory, and a directory is a name a pull request
chooses. `packages/x";curl …|sh;"` is a legal path in git and on Linux
and it round-trips through the report into a shell.

Restricting to the emitter's own grammar costs nothing real, since that
grammar is the two shapes build-test produces. A command outside it is
skipped and disclosed, the same treatment everything else this command
cannot do already gets, so a future shape degrades to "judge it by the
diff" rather than to arbitrary execution.

* test(review): pin the empty-diff and collapse detectors

Both lived inline in a large object literal with no test, and one of
them is the most expensive disclosure this command emits: the SKILL acts
on `emptyDiff` by recommending the PR be closed as superseded. Dropping
the 200-line floor, flipping the 4x comparison, or losing either
empty-diff guard turned nothing red.

Extracted as two pure predicates and pinned at the boundaries, including
the two guards that are not about the diff at all - a capture that threw
leaves diffText empty, and a merge base resolved from a stale local ref
can already contain the head commits. Either would have closed a live PR
on an infrastructure error.

Checked by mutation rather than by reading: all four edits above now
fail exactly one assertion each.

* test(review): pin the 30s budget floor, and stop keeping its arithmetic twice

Two findings from the same review round, both about budget math nobody
was checking.

The 30s floor separates "skipped, judge it by the diff" from "started,
timed out, disclosed as infrastructure". Every existing budget test left
it non-binding - two sit hundreds of seconds from the boundary and the
third is capped by the per-command deadline - so regressing it to the
old 5s turned nothing red. Verified by doing exactly that: 26 green
before the new test, one red after. A one-second command admitted into a
twenty-second window comes back labelled `budgetClamped`, which is the
mislabelling the priced floor exists to prevent.

The other is the same duplication lesson this skill keeps arriving at,
in its own tests: one test carried the per-run budget arithmetic in a
block comment AND at the `now:` argument, and when the per-run figure
changed only one copy moved. The block also predated the positive
control, so it omitted a whole suite run. Deleted the copy rather than
correcting it - two agreeing copies today are two disagreeing copies
later.

* fix(review): the working directory is a setting the extraction was losing

Two findings, both of them this file failing its own stated argument.

The stub list dropped it. `expressions` covered the script and the env
and nothing else, so a `working-directory: ${{ github.workspace }}/x`
produced an empty list and a summary line reading "0 ${{ }} site(s) to
stub" - and `expressionsOf`'s own comment says why that is the failure
this list cannot afford: the caller reads it as "these are all the
values to supply". Widened to every setting the command carries, the
`shell:` template included.

The emitted script never mentioned it. The env block is commented into
the header precisely so a reader of the script alone can see it; the
working directory changes what the script does just as much and was in
the metadata only. The argument for reading all three levels, written in
this file, is that a step run "in the wrong directory, and nothing says
so" is the transcription error the command exists to remove - which is
exactly what the header did. It is a comment rather than a `cd` for the
same reason env is comments, not exports: the value may hold `${{ … }}`
and this command substitutes nothing.

Both pinned, and both checked by deleting the fix: each mutation fails
exactly one of the two new tests.

* fix(review): $(( )) is arithmetic, and a heredoc's form decides where it ends

Three fixes and one deliberate non-fix, all measured against this repo's
own 434 `run:` steps rather than argued.

`$(( ))` was read as a command substitution, so `N=$((N + 1))` reported
`N` as a command to stub. It was the single largest source of junk in
the list: 196 distinct "commands" across the corpus, 165 without it.

A plain `<<WORD` heredoc ends only on a line that is exactly WORD; the
loose match ended it on an indented `EOF` inside the body and then read
the body as commands, which is how `rm` got reported for a script that
never runs it. `<<-` stays looser than bash (any leading whitespace, not
just tabs) because looser can only end a body early, and this file's
priority is that an under-report is the worse direction.

`[^()]*` matched only the innermost `$( )`, so `X=$(gh api $(u))` lost
`gh` - a missed stub, and the extraction reaches the network. Depth
counted now, and the assignment-prefix skip no longer steps over an
unclosed `X=$(gh` into reading `api` as the command.

The non-fix is recorded where the next reader will hit it: the quote
walk is flat while shell quoting nests, and over ~300 lines the drift
reports fragments of jq source as commands. Inserting a separator where
a blanked span was removes nine of those, but it splits `a"X"b`, which
is one word to the shell, and the minimal reproducer for the difference
is 296 lines - nothing short enough to pin it. A scanner nobody can pin
costs more than the junk it removes.

* fix(review): refuse an ambiguous step name, and report errors like the siblings

Two findings, both about a message the caller never gets.

A job may legally hold two steps with the same name. The selector took
the first and said nothing, which is the failure this file's own header
names - "picks the same-named step from the wrong job" - and it is worst
in the use the command exists for: A/B extraction runs it once per tree,
so a PR that adds or reorders a duplicate leaves the two sides comparing
different steps while reporting on one. Refused out loud now, naming the
indices; the index is always available and never ambiguous.

The handler also let every throw propagate, so five carefully separated
messages - cannot read vs cannot parse vs no job vs no step vs no `run:`
- all arrived as "An unexpected critical error occurred" under a stack
trace. `base-tree` and `test-plan` in the same directory already catch,
write the message, and set exit 1. Matched. The separation between "the
path is wrong" and "the YAML is wrong" only pays if the caller sees it.

* docs(review): the brief's list of limits was one short

"Two limits worth knowing before you spend the step" became three when
the selector started refusing an ambiguous step name, and the count went
stale in the same commit that made it wrong. This is the enumeration
drift the skill teaches, in the text that teaches it.

The added entry says what to do rather than only what happens: pass the
index, which is what an A/B wants regardless — the two trees have to
select the same step, and a name that moved between them is exactly how
they stop doing that.

* chore(review): drop a scratch probe file that reached the branch

`packages/cli/inert.mjs` was a throwaway harness for sweeping the repo's
own workflows; its cleanup ran with a relative path from the wrong
directory and it got committed by the next `git add -A`.

It failed CI and not the local hook because the two lint different sets:
lint-staged filters to `*.{js,jsx,ts,tsx}`, which does not include
`.mjs`, while CI's flat config picks the file up regardless of `--ext`.
Verified with CI's own command this time, not the hook's.

* fix(review): the collapse disclosure needs the guard its sibling already has

Three findings from the round on this branch, all accepted.

`isEmptyDiff` refuses to rule when the merge base came from a possibly
stale local ref, because such a base can already contain the head
commits and diff to empty. The PARTIAL form of that cause lands on
`isCollapsedFromUpstream` instead - a stale ref holding most of the head
commits shrinks the recomputed diff past the 4x ratio - and the flag
then tells Agent 0 to read the body as description-of-history when the
body may be perfectly current and the real cause is a fetch failure. Two
predicates over the same evidence, one guarded and one not. Guarded now,
and pinned: removing the guard fails exactly one test.

The pre-set of `mutantsSkippedForBudget`/`hunksSkippedForBudget` in the
no-budget-for-control branch was dead in every path and worse than dead
in one: both loops run with `harnessValidated` still null, re-check the
same budget, and set their own counters - and the hunk loop's figure
excludes the collocated-probe inconclusives it pushes first, which the
pre-set did not. Dropped, with the reason where the assignment was.

`runControlMutant`'s bound is now stated in its doc: it validates ONE
file, so a collector that silently drops a different probe file passes
the control while that file's survivors stand. The per-file baseline
gate bounds what is left. A `true` there is read as covering the run, so
what it does not cover belongs next to it.

* fix(review): bound the whole ledger marker, not just each of its fields

The per-field caps leave the total unbounded: fifty findings at full
width serialize to just under 17,000 characters. The module's own
paragraph calls the marker "a footnote, never a payload" and reasons
about GitHub's 65,536-character body limit, so the total is the number
that claim is about and nothing was computing it.

Set the budget from measurement rather than from the limit. Across every
review this pipeline has posted on its own stack (n=66) the body runs a
median of 721 characters, p90 2,178, max 3,925 - the limit has ~61 KiB
of headroom, and an over-long marker was never going to fail a post. The
real cost is proportion: 17,000 characters of invisible payload on a
3,925-character review is four times more marker than review. 8 KiB
holds fifty findings at realistic widths without dropping any, and the
truncation path is reached only by a ledger no round has produced.

What it drops travels with it. A `dropped` count is the difference
between a list the next round reads as complete and one that says it is
not - the same distinction this module already draws everywhere else.

* fix(review): a partial ledger must not render as a complete one

The size cap added in the previous commit can drop entries, and the
rendered section still opened with "**Every entry below is owed a
this-round ruling**" and said nothing about what was missing. The
`dropped` count existed and reached the only place a reader sees the
list as nothing at all — which is the failure it was added to prevent,
committed one step after adding the field. It now says the list is
partial, how many are missing, and that absence is not evidence a
finding was fixed.

Second, the table escaping escaped `|` but not `\`. `\|` in a title
became `\\|`, which markdown reads as an escaped backslash followed by a
LIVE separator: the forged row the escaping exists to prevent, produced
by the escaping. Backslash first now, and the test counts separators the
way markdown does rather than by pattern, because a lookbehind counter
is fooled by exactly the input under test.

* fix(review): an empty ledger title is a cap the next round cannot lift

A comment that is nothing but its severity marker produced a ledger
entry with an empty title. That does not merely degrade the entry, it
jams the review: the next round is told every ledger entry is owed a
this-round ruling, has no claim text to rule on, answers `cannot tell`,
and `cannot-tell-existing-critical` is one of the cap reasons. Nothing
between rounds changes, so the cap comes back every round.

Dropping the entry would hide a Critical that really was posted, so it
keeps its place and gets the one handle there is - the location it was
filed at, or "the review body" for a body-level one. The field's stated
job is "enough for the next round to re-locate the claim", and that is
what a text-less finding still has.

Found by probing `buildLedger` with ten malformed comment shapes; the
other nine - carried ids, id collisions, two comments carrying the same
id, `R2D2` not being an id, a leading newline before the marker - all
behaved correctly and needed no change.

* fix(review): count both caps as dropped, not just the byte one

Found by running the three previous fixes together on one round: 51
findings in, 24 kept, and the marker said 26 were missing.
`LEDGER_MAX_FINDINGS` truncates before the byte cap ever runs, and
measuring `dropped` against the already-sliced list left the count cap's
share silent - so the field added two commits ago to stop a truncated
list reading as complete was itself under-reporting the truncation.

Measured against what came IN now, and pinned across all four
combinations: count cap alone, byte cap alone, both, and neither. Kept
plus dropped equals given, in every one.

* fix(review): the ignore check was the one git spawn without a deadline

`isGitIgnored` reached for a bare `execFileSync` while every other git
invocation in these commands goes through the package helper, which
carries `GIT_TIMEOUT_MS` and `GIT_TERMINAL_PROMPT=0`. That constant's own
comment is the argument: "a hang must still end". This one ran against a
worktree the review does not control and could not.

No behavioural delta for any input that does not hang - all 80 test-plan
tests pass unchanged - so it ships without a new test rather than with a
mocked-spawn assertion that would pin the call shape instead of the
behaviour.

* docs(review): a control killed mid-run did not "never run at all"

SKILL's `harnessValidated` paragraph enumerated four ways the value
lands on `null` - no green baseline, no candidates, no budget, an
unreadable probe file - and all four are "the control never ran". There
is a fifth: `runControlMutant` throws when its deadline kills the run or
the runner cannot be spawned, the outer catch swallows it, and the value
stays `null` rather than becoming a fabricated `false`. That is the path
a slow machine takes.

The ruling is unchanged - neither validated nor refuted, a survivor
stands but unconfirmed - so this is about what the terminal says, not
what it decides. An agent quoting "the control never ran at all" for a
control that ran and was killed states something untrue about the run,
and the enumeration is what it quotes from.

---------

Co-authored-by: qwen-code-dev-bot <qwen-code-dev@service.alibaba.com>
Co-authored-by: Qwen Code <qwen-code@users.noreply.github.com>
Co-authored-by: Qwen Code Bot <qwen-code-bot@users.noreply.github.com>
Co-authored-by: Qwen Code Autofix <qwen-code-autofix@users.noreply.github.com>
@qwen-code-ci-bot

Copy link
Copy Markdown
Collaborator

Released in v0.21.3.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

review/self-reported The linked issue was opened by the PR author (self-reported)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Standardize tool-call terminal telemetry and error classification

4 participants