From 884b39ef630feec775270024cda89d404aa4b303 Mon Sep 17 00:00:00 2001 From: TangZ-L <345187680+TangZ-L@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:12:15 +0800 Subject: [PATCH 1/7] =?UTF-8?q?fix(api):=20=E5=85=81=E8=AE=B8=20insert=5Fa?= =?UTF-8?q?fter=20=E4=BD=BF=E7=94=A8=E5=94=AF=E4=B8=80=E7=9A=84=E5=A4=9A?= =?UTF-8?q?=E8=A1=8C=E6=96=87=E6=9C=AC=E5=9D=97=E9=94=9A=E7=82=B9=20(#599)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 根因:validator 对 insert_after 强制单行,prompt/派生 schema 与 07 5.5.4 只要求锚存在且唯一,模型提交的 4 行块锚点在 patch 阶段被拒、整轮失败。移除单行拒绝,应用器改为整段唯一匹配并插入到块末行之后;单行输出逐字节不变;同步 prompt 与设计文档,补多行/CRLF/缺失/多义与生产形状 replay 回归。 --- .../bugfix-edit-insert-anchor-multiline.en.md | 5 +- ...fix-edit-insert-anchor-multiline.i18n.yaml | 4 +- .../bugfix-edit-insert-anchor-multiline.md | 5 +- ...6-11-25-edit-insert-anchor-multiline.en.md | 27 ++ ...-25-edit-insert-anchor-multiline.i18n.yaml | 5 + ...2026-11-25-edit-insert-anchor-multiline.md | 27 ++ .../api/app/service/evolution/patch_source.py | 4 +- .../api/app/third_party_api/ai_agent/edits.py | 68 ++-- apps/api/tests/test_ai_agent_claude_code.py | 2 + apps/api/tests/test_edit_plan_applier.py | 312 +++++++++++++++++- plans/2026-11-22-pr510-review.md | 6 +- .../07-backend-implementation.md | 4 +- ...-issue-599-edit-insert-anchor-multiline.md | 85 +++++ 13 files changed, 508 insertions(+), 46 deletions(-) create mode 100644 .agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.en.md create mode 100644 .agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.i18n.yaml create mode 100644 .agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.md create mode 100644 plans/superpowers/plans/2026-11-25-issue-599-edit-insert-anchor-multiline.md diff --git a/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.en.md b/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.en.md index 79a641e8..c20a7de8 100644 --- a/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.en.md +++ b/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.en.md @@ -9,7 +9,7 @@ milestone: bugfix depends: - bugfix-46 priority: P2 -status: ready +status: in-progress scope: - apps/api/app/third_party_api/ai_agent/edits.py - apps/api/app/service/evolution/patch_source.py @@ -17,7 +17,8 @@ scope: - docs/** - plans/** - .agents/** -adr: [] +adr: + - ../../notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.md github: number: 599 url: https://github.com/Shadow-Azure/harness-evolution/issues/599 diff --git a/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.i18n.yaml b/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.i18n.yaml index 7366b729..4e59ad79 100644 --- a/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.i18n.yaml +++ b/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.i18n.yaml @@ -1,5 +1,5 @@ # 双语配对一致性记录(docs/i18n/README.md):两侧在最后一次确认一致状态下的 # git blob hash。两种语言同等权威;编辑任一侧后带上另一侧,然后重录: # pnpm run record:i18n -- .agents/flow/issues/bugfix-edit-insert-anchor-multiline.md -bugfix-edit-insert-anchor-multiline.md: 85be8e3cdd1ac181ed72e1ab244ced661c4fe2aa -bugfix-edit-insert-anchor-multiline.en.md: 79a641e8972c884f71d1c7f783c946de2f393a82 +bugfix-edit-insert-anchor-multiline.md: 00d6a2d2a430e344007c21ed74e3e6260e52378d +bugfix-edit-insert-anchor-multiline.en.md: c20a7de8526598c5dad2b878e633f02565b2f66d diff --git a/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.md b/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.md index 85be8e3c..00d6a2d2 100644 --- a/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.md +++ b/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.md @@ -9,7 +9,7 @@ milestone: bugfix depends: - bugfix-46 priority: P2 -status: ready +status: in-progress scope: - apps/api/app/third_party_api/ai_agent/edits.py - apps/api/app/service/evolution/patch_source.py @@ -17,7 +17,8 @@ scope: - docs/** - plans/** - .agents/** -adr: [] +adr: + - ../../notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.md github: number: 599 url: https://github.com/Shadow-Azure/harness-evolution/issues/599 diff --git a/.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.en.md b/.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.en.md new file mode 100644 index 00000000..c4ca1089 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.en.md @@ -0,0 +1,27 @@ +# Agent Note: edit unifies the insert_after anchor contract as cross-line text blocks + +Status: implemented + +English | [中文](2026-11-25-edit-insert-anchor-multiline.md) + +## Problem + +The production full run `01M885592456VVK5B68DSMRKTE` failed at turn 3/10 of step 6/7 ("iterative optimization") in the patch stage: `claude-code edit submission failed validation`. The submission file had been parsed normally (`submissionParsedBy=json5`, `submissionParseFailures=0`), but `EditPlan.model_validate()` rejected edit 7 (0-based `edits.6`), an `insert_after`, with `target must be a single-line substring`. That target was the 4-line text block of the `### 验收与回归` template (158 characters), occurring exactly once in the target `SKILL.md` — the model did the right thing by the contract it was told (prompt and derived schema only say "anchor text must exist and be unique"), while the validator enforced a stricter, unpublished rule that contradicts design doc 07 §5.5.4. Edit is a single call with no retry on validation failure, so this hidden rule living only in the validator killed the whole turn; edits 1 and 2 on the same release succeeded, showing this was model output variance hitting a contract mismatch, not a deployment regression. + +## Decision + +The `insert_after` anchor contract is unified as "a text fragment that exists exactly once in the file and may span lines". On the model side, `EditOp._validate_op_fields()` no longer rejects targets containing `\n`/`\r` (the single-line rule introduced in #494); all other constraints (append forbids target, delete forbids content, non-blank and line-capped content, etc.) stay as they are. On the applier side, `_insert_after_text()` is rewritten as "match the unique whole fragment, insert after the block's last line": the insertion point sits after a trailing newline of the target itself (`\r\n`/`\n`/`\r`), otherwise after the next line terminator of the line holding the matched block's final character, or a synthesized `\n` at EOF; inserted lines reuse that terminator's style (`\r\n` stays `\r\n`; a bare-`\r` anchor line keeps its bytes and inserts with `\n`). The `text.count(target)` branches stay untouched — 0 occurrences → `skipped_anchor_missing`, more than 1 → `error` (ambiguous) — and single-line targets reproduce the old output byte for byte. The contract also enters the model-visible surface: `_edit_prompt()`'s anchor line becomes "anchor text must be a fragment that occurs exactly once in the file and may span lines; insert_after inserts content after that fragment's last line", with 07 §5.5.4's execution bullet and json5 example comment updated to match. Regression tests cover validation and application of a 4-line block anchor, single-line byte-for-byte cases (mid-line / line-end / EOF without terminator / bare-`\r` / CRLF), missing and ambiguous block anchors, CRLF block insertion, and a synthetic replay of a production-shaped 8-edit plan (no production text). + +## Alternatives considered + +- **Add a field-level feedback retry for edit**: analyze has the `feedback_prompt()` retry, edit does not; adding one would change `edit_workspace()`'s single-call semantics and the run state machine, a cost far beyond this defect's surface — and the correct contract should not be hidden inside a validator in the first place. Rejected. +- **Explain "target must not contain newlines" in the prompt**: publishing the hidden rule instead of removing it. A multi-line block is a natural, unique, legitimate anchor choice for the model; suppressing it via prompt only pushes toward more fragile workarounds while the contract keeps contradicting 07 §5.5.4. Rejected. +- **Allow multiple anchors (take the first match)**: it breaks the deterministic "anchor exists and is unique" contract held since #494; the result would depend on match order and resist audit. Rejected; the uniqueness check stays untouched, and a cross-line target does not bypass it. +- **Only fix observability (pass `AgentProviderError.detail` through `ConfigError`)**: the run page could then show `edits.6`'s field-level cause, but "a valid plan gets rejected" remains unfixed; the observability gap is recorded as debt instead of widening this change. Rejected. + +## Consequences + +- A production-shaped plan (8 edits, a 4-line block anchor, per-edit content ≤ 28 lines) now passes `EditPlan.model_validate()`, applies all edits to the target file only, and leaves single-line `insert_after` unchanged — the four-op exact-content test and `test_insert_after_last_line_without_newline` keep their byte-for-byte assertions. +- Conditional constraints a schema cannot express must go into the prompt: a derived JSON Schema cannot state "when one field takes value X, another must look like Y", so the Pydantic validator is the only enforcement point and the caller's prompt must state every semantic constraint as a positive contract — otherwise a "rule that lives only in the validator" gap reappears. +- The observability gap where the `ConfigError` conversion drops `AgentProviderError.detail` remains: `_fail_patch_generation()` only receives `str(error)`, so the run page and job show a generic message and the field-level cause must be reproduced from the leftover `edits.json5`; fixing it is a separate small change, out of scope here. +- The three anchored ops (`replace`/`insert_after`/`delete`) now share one anchor semantic: a unique whole-text substring match, with no single-line special case in `insert_after`; a multi-line anchor turned from "illegal" into "a legitimate anchor", while bad plans still fail before any write and application stays deterministic and replayable. diff --git a/.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.i18n.yaml new file mode 100644 index 00000000..f5c69487 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.i18n.yaml @@ -0,0 +1,5 @@ +# 双语配对一致性记录(docs/i18n/README.md):两侧在最后一次确认一致状态下的 +# git blob hash。两种语言同等权威;编辑任一侧后带上另一侧,然后重录: +# pnpm run record:i18n -- .agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.md +2026-11-25-edit-insert-anchor-multiline.md: 8bf95438a4a9735b03d1cee4993e10914b0eba9b +2026-11-25-edit-insert-anchor-multiline.en.md: c4ca1089e58d361625a7007b5f385bc0100399a4 diff --git a/.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.md b/.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.md new file mode 100644 index 00000000..8bf95438 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.md @@ -0,0 +1,27 @@ +# Agent Note: edit 的 insert_after 锚点契约统一为可跨行文本块 + +Status: implemented + +[English](2026-11-25-edit-insert-anchor-multiline.en.md) | 中文 + +## Problem + +生产 full run `01M885592456VVK5B68DSMRKTE` 在第 6/7 步「迭代优化」的第 3/10 轮 patch 阶段失败:`claude-code edit submission failed validation`。提交文件已被正常解析(`submissionParsedBy=json5`、`submissionParseFailures=0`),但 `EditPlan.model_validate()` 拒绝了第 7 条(0-based `edits.6`)`insert_after`:`target must be a single-line substring`。该 target 是 `### 验收与回归` 模板的 4 行文本块(158 字符),在目标 `SKILL.md` 中恰好出现 1 次——模型按它被告知的契约(prompt 与派生 schema 只说「锚文本必须存在且唯一」)做了正确的事,validator 却执行一条未公开、与设计文档 07 §5.5.4 不一致的更严格规则。edit 是单次调用、校验失败不重试,这条只活在 validator 里的隐藏规则直接把整轮打死;同 release 的第 1、2 轮 edit 成功,说明是模型输出形态差异撞上契约不一致,而非部署回归。 + +## Decision + +`insert_after` 的锚点契约统一为「文件内存在且唯一的文本片段,可以跨行」。模型侧删除 `EditOp._validate_op_fields()` 对含 `\n`/`\r` target 的拒绝(#494 引入的单行规则),其余约束(append 禁 target、delete 禁 content、content 非空与行数上限等)原样保留。应用侧把 `_insert_after_text()` 重写为「整段唯一匹配 + 块末行之后插入」:插入点在 target 自身结尾换行(`\r\n`/`\n`/`\r`)之后,否则在匹配块末字符所在行的下一个行终止符之后,EOF 无终止符时补 `\n`;插入行沿用该终止符风格(`\r\n` 保持 `\r\n`;bare `\r` 锚行字节不动,插入行用 `\n`)。`text.count(target)` 的 0 次 → `skipped_anchor_missing`、>1 次 → `error`(ambiguous)分支原样保留,单行 target 的输出与旧实现逐字节一致。契约同步写进模型可见面:`_edit_prompt()` 的锚点行改为「锚文本必须是文件内唯一出现的文本片段,可跨行;insert_after 把 content 插到该片段末行之后」,07 §5.5.4 的执行流 bullet 与 json5 示例注释同步。回归测试覆盖 4 行块锚点的校验与应用、单行逐字节(行中/行尾/EOF 无终止符/bare-`\r`/CRLF)、块锚缺失与多义、CRLF 块插入,以及生产计划形状的 8 条编辑合成 replay(不含生产原文)。 + +## Alternatives considered + +- **给 edit 加字段级反馈重试**:analyze 有 `feedback_prompt()` 重试,edit 没有;加重试要改 `edit_workspace()` 的单次调用语义与 run 状态机,成本远超本缺陷的面,且正确契约根本不该被 validator 藏起来。拒绝。 +- **在 prompt 里解释「target 不能含换行」**:把隐藏规则公开化而不是修掉它。多行块是模型自然、唯一、合法的锚点选择,靠 prompt 压制只会逼出更脆弱的绕法,契约继续与 07 §5.5.4 矛盾。拒绝。 +- **放宽为允许多 anchor(取首个匹配)**:破坏 #494 以来的「锚存在且唯一」确定性契约,应用结果依赖匹配顺序、不可审计。拒绝;唯一性检查原样保留,多行 target 不绕过它。 +- **只修观测(把 `AgentProviderError.detail` 透传进 `ConfigError`)**:能让 run 页显示 `edits.6` 的字段级原因,但修不了「合法计划被拒」本身;观测缺口另记为欠账,不在本方案内扩大修改面。拒绝。 + +## Consequences + +- 生产计划形状(8 条编辑、4 行块锚点、单条 content ≤ 28 行)现在通过 `EditPlan.model_validate()` 且全部 `applied`、只改目标文件;单行 `insert_after` 无行为变化,四 op 精确内容与 `test_insert_after_last_line_without_newline` 等既有逐字节断言全部保持。 +- schema 表达不了的条件约束必须进 prompt:派生 JSON Schema 表达不了「某字段取某值时另一字段必须怎样」的条件语义,Pydantic validator 是唯一执行点,调用方 prompt 必须把每条语义约束写成正面向契约,否则就会出现「规则只存在于 validator」的结构性缺口。 +- `ConfigError` 转换丢弃 `AgentProviderError.detail` 的观测缺口仍在:`_fail_patch_generation()` 只拿到 `str(error)`,run 页与 job 只显示泛化 message,字段级原因只能从残留 `edits.json5` 复现;修复它属于独立小改动,不在本次范围。 +- 三个 anchored op(`replace`/`insert_after`/`delete`)的锚语义完全一致:全文唯一子串匹配,`insert_after` 不再有单行特例;模型拒绝的多行锚由「非法」变为「合法锚点」,坏计划在落盘前失败、应用结果确定可重放的性质不变。 diff --git a/apps/api/app/service/evolution/patch_source.py b/apps/api/app/service/evolution/patch_source.py index 6ffde1d9..a02a995c 100644 --- a/apps/api/app/service/evolution/patch_source.py +++ b/apps/api/app/service/evolution/patch_source.py @@ -537,7 +537,9 @@ def _edit_prompt( lines.extend( ( "## 修复要求", - f"- file 必须落在允许范围 {list(allowed)!r} 内;锚文本必须存在且唯一。", + f"- file 必须落在允许范围 {list(allowed)!r} 内;" + "锚文本必须是文件内唯一出现的文本片段,可跨行;" + "insert_after 把 content 插到该片段末行之后。", f"- 最多 {EDIT_BUDGET} 条编辑,单条内容最多 {MAX_CONTENT_LINES} 行;" "优先最小、可回退的真实修复。", "- 提交格式:{summary, edits:[{op,file,target,content,rationale}]}。", diff --git a/apps/api/app/third_party_api/ai_agent/edits.py b/apps/api/app/third_party_api/ai_agent/edits.py index e4924f36..ff200a91 100644 --- a/apps/api/app/third_party_api/ai_agent/edits.py +++ b/apps/api/app/third_party_api/ai_agent/edits.py @@ -158,18 +158,16 @@ def _validate_content_size(cls, value: str | None) -> str | None: def _validate_op_fields(self) -> Self: """Enforce the op-specific required and forbidden fields. - ``insert_after`` anchors one physical line, so a multi-line target is a - model error rather than an applier error: the plan fails before any - file is touched and the retry prompt gets a field-level message. + ``insert_after`` anchors the unique text fragment that content is + inserted after; the fragment may span multiple lines, and the applier + resolves the end of its last line, so no line count is enforced here. """ if self.op == "append": if self.target is not None: raise ValueError("append must not set target") _require_non_blank(self.content, field="content", op=self.op) elif self.op in _ANCHORED_OPS: - target = _require_non_blank(self.target, field="target", op=self.op) - if self.op == "insert_after" and ("\n" in target or "\r" in target): - raise ValueError("target must be a single-line substring") + _require_non_blank(self.target, field="target", op=self.op) if self.op == "delete": if self.content is not None: raise ValueError("delete must not set content") @@ -465,18 +463,45 @@ def _append_text(text: str, content: str) -> str: def _insert_after_text(text: str, target: str, content: str) -> str: - """Insert content lines directly after the unique line containing ``target``.""" - lines = text.splitlines(keepends=True) - anchor_index = next((index for index, line in enumerate(lines) if target in line), None) - if anchor_index is None: # pragma: no cover - counted before this call - raise EditPlanError("insert_after anchor is not contained in one line") - anchor = lines[anchor_index] - ending = "\r\n" if anchor.endswith("\r\n") else "\n" + """Insert content lines directly after the unique block matched by ``target``. + + ``target`` may span multiple lines. When it ends with a line terminator the + insertion point is right after that terminator; otherwise it is the end of + the line containing the match's last character, and an unterminated final + line gains one. Inserted lines reuse the anchor line's ``\\r\\n`` or ``\\n`` + style, so a single-line target keeps producing the historical bytes. + """ + try: + match_end = text.index(target) + len(target) + except ValueError: # pragma: no cover - counted before this call + raise EditPlanError("insert_after anchor is not contained in the file") from None + if target.endswith("\r\n"): + ending, prefix, suffix = "\r\n", text[:match_end], text[match_end:] + elif target.endswith("\r"): + if text.startswith("\n", match_end): + # The target stops halfway through a CRLF terminator; finish it. + match_end += 1 + ending = "\r\n" + else: + ending = "\n" + prefix, suffix = text[:match_end], text[match_end:] + elif target.endswith("\n"): + ending, prefix, suffix = "\n", text[:match_end], text[match_end:] + else: + newline = text.find("\n", match_end) + if newline != -1: + ending = "\r\n" if newline > 0 and text[newline - 1] == "\r" else "\n" + prefix, suffix = text[: newline + 1], text[newline + 1 :] + else: + carriage = text.find("\r", match_end) + if carriage != -1: + ending, prefix, suffix = "\n", text[: carriage + 1], text[carriage + 1 :] + else: + ending = "\n" + prefix, suffix = f"{text[:match_end]}{ending}", "" inserted = content.splitlines() or [""] - if not anchor.endswith(("\n", "\r")): - lines[anchor_index] = f"{anchor}{ending}" - lines.insert(anchor_index + 1, "".join(f"{line}{ending}" for line in inserted)) - return "".join(lines) + body = "".join(f"{line}{ending}" for line in inserted) + return f"{prefix}{body}{suffix}" def _apply_one(edit: EditOp, text: str, index: int) -> _EditOutcome: @@ -494,15 +519,6 @@ def _apply_one(edit: EditOp, text: str, index: int) -> _EditOutcome: raise EditPlanError(_constraint_message(index, edit.file, edit.op, "target is required")) if edit.op == "insert_after": - if "\n" in target or "\r" in target: - raise EditPlanError( - _constraint_message( - index, - edit.file, - edit.op, - "target must be a single-line substring", - ), - ) occurrences = text.count(target) if occurrences == 0: return _EditOutcome( diff --git a/apps/api/tests/test_ai_agent_claude_code.py b/apps/api/tests/test_ai_agent_claude_code.py index 487207de..1690bfcb 100644 --- a/apps/api/tests/test_ai_agent_claude_code.py +++ b/apps/api/tests/test_ai_agent_claude_code.py @@ -1648,6 +1648,7 @@ async def forbidden(*args: Any, **kwargs: Any) -> Any: assert "not found" in health.detail +@pytest.mark.skipif(os.name != "posix", reason="process-group signals are POSIX-only") async def test_default_runner_escalates_sigint_to_sigkill( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, @@ -1685,6 +1686,7 @@ def fake_killpg(pgid: int, sig: signal.Signals) -> None: assert result.returncode == -9 +@pytest.mark.skipif(os.name != "posix", reason="process-group signals are POSIX-only") async def test_default_runner_cleans_up_and_reraises_cancellation( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, diff --git a/apps/api/tests/test_edit_plan_applier.py b/apps/api/tests/test_edit_plan_applier.py index c8ebc598..98fc37cd 100644 --- a/apps/api/tests/test_edit_plan_applier.py +++ b/apps/api/tests/test_edit_plan_applier.py @@ -3,6 +3,7 @@ from __future__ import annotations import os +import tempfile from datetime import UTC, datetime from pathlib import Path from typing import cast @@ -98,9 +99,22 @@ def _trace(text: str) -> CandidateTrace: def _write(path: Path, text: str) -> None: - """Create a parent directory and write exact UTF-8 content.""" + """Create a parent directory and write exact UTF-8 bytes without newline translation.""" path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(text, encoding="utf-8") + path.write_bytes(text.encode("utf-8")) + + +def _symlinks_supported() -> bool: + """Probe once whether this host permits creating a symlink at all.""" + try: + with tempfile.TemporaryDirectory() as tmp: + (Path(tmp) / "link").symlink_to(Path(tmp) / "missing-target") + except (NotImplementedError, OSError): + return False + return True + + +_NO_SYMLINK = not _symlinks_supported() def test_four_ops_apply_to_real_files(tmp_path: Path) -> None: @@ -373,12 +387,32 @@ def test_op_specific_fields_are_enforced( EditOp(op=op, file="a.md", target=target, content=content, rationale="r") -@pytest.mark.parametrize("target", ["line\nbreak", "line\rbreak"]) -def test_insert_after_rejects_a_multiline_anchor_at_model_construction(target: str) -> None: - """The single-line anchor rule fails the plan before any file is touched.""" - with pytest.raises(ValidationError, match="single-line substring"): - EditOp(op="insert_after", file="a.md", target=target, content="x", rationale="r") +def test_insert_after_accepts_a_unique_multiline_block_anchor(tmp_path: Path) -> None: + """A unique four-line block anchor validates and applies after its last line.""" + workspace = tmp_path / "ws" + _write(workspace / "doc.md", "l1\nl2\nl3\nl4\nl5\nl6\n") + plan = EditPlan( + summary="multiline block", + edits=( + EditOp( + op="insert_after", + file="doc.md", + target="l2\nl3\nl4\nl5\n", + content="NEW", + rationale="r", + ), + ), + ) + + validated = EditPlan.model_validate(plan.model_dump()) + application = apply_edit_plan(validated, workspace=workspace) + + assert application.report[0].status == "applied" + assert (workspace / "doc.md").read_bytes() == b"l1\nl2\nl3\nl4\nl5\nNEW\nl6\n" + +def test_replace_still_accepts_a_multiline_anchor_at_model_construction() -> None: + """replace keeps allowing a cross-line target; only insert_after was narrower.""" multiline_replace = EditOp( op="replace", file="a.md", @@ -586,6 +620,7 @@ def test_directory_target_and_glob_directory_match_are_errors(tmp_path: Path) -> assert "regular file" in application.report[0].message +@pytest.mark.skipif(_NO_SYMLINK, reason="symlink creation requires Developer Mode on Windows") def test_symlink_escape_is_an_error(tmp_path: Path) -> None: """A symlink that resolves outside the workspace is rejected before write.""" workspace = tmp_path / "ws" @@ -607,6 +642,7 @@ def test_symlink_escape_is_an_error(tmp_path: Path) -> None: assert outside.read_text(encoding="utf-8") == "secret\n" +@pytest.mark.skipif(_NO_SYMLINK, reason="symlink creation requires Developer Mode on Windows") @pytest.mark.parametrize("protected", [".harness-evolution", ".git"]) def test_symlink_into_a_protected_directory_is_an_error( tmp_path: Path, @@ -633,6 +669,7 @@ def test_symlink_into_a_protected_directory_is_an_error( assert secret.read_text(encoding="utf-8") == "secret\n" +@pytest.mark.skipif(_NO_SYMLINK, reason="symlink creation requires Developer Mode on Windows") def test_symlink_outside_allowed_paths_is_an_error(tmp_path: Path) -> None: """The resolved target, not just the lexical path, must satisfy the scope.""" workspace = tmp_path / "ws" @@ -695,7 +732,6 @@ def test_bypassed_edit_with_an_unsafe_path_is_an_error(tmp_path: Path) -> None: [ ("append", None, None, "content is required"), ("replace", None, "x", "target is required"), - ("insert_after", "line\nbreak", "x", "single-line"), ("insert_after", "line", None, "content is required"), ("replace", "line", None, "content is required"), ], @@ -759,6 +795,266 @@ def test_insert_after_last_line_without_newline(tmp_path: Path) -> None: assert (workspace / "doc.md").read_text(encoding="utf-8") == "one\ntwo\nthree\n" +@pytest.mark.parametrize( + ("text", "target", "content", "expected"), + [ + # A mid-line match inserts after that line's terminator. + ("alpha beta\ngamma\n", "beta", "x", "alpha beta\nx\ngamma\n"), + # A line-end match reuses the anchor line's own newline. + ("one\ntwo\n", "two", "three", "one\ntwo\nthree\n"), + # A final unterminated line gains its boundary before the insert. + ("one\ntwo", "two", "three", "one\ntwo\nthree\n"), + # A bare-\r anchor keeps its bytes; inserted lines use \n. + ("a\rb\rc\r", "b", "x", "a\rb\rx\nc\r"), + # A CRLF anchor line inserts \r\n-terminated content. + ('x: {"a": 1}\r\ny\r\n', 'x: {"a": 1}', "z", 'x: {"a": 1}\r\nz\r\ny\r\n'), + ], +) +def test_insert_after_single_line_targets_reproduce_exact_bytes( + tmp_path: Path, + text: str, + target: str, + content: str, + expected: str, +) -> None: + """Single-line anchors keep producing the historical byte-for-byte output.""" + workspace = tmp_path / "ws" + _write(workspace / "doc.md", text) + plan = EditPlan( + summary="single-line bytes", + edits=( + EditOp( + op="insert_after", + file="doc.md", + target=target, + content=content, + rationale="r", + ), + ), + ) + + application = apply_edit_plan(plan, workspace=workspace) + + assert application.report[0].status == "applied" + assert (workspace / "doc.md").read_bytes() == expected.encode("utf-8") + + +def test_insert_after_multiline_block_without_trailing_newline(tmp_path: Path) -> None: + """A block that ends mid-file inserts after its last line's terminator.""" + workspace = tmp_path / "ws" + _write(workspace / "doc.md", "l1\nl2\nl3\n") + plan = EditPlan( + summary="block mid-file", + edits=( + EditOp(op="insert_after", file="doc.md", target="l1\nl2", content="NEW", rationale="r"), + ), + ) + + application = apply_edit_plan(plan, workspace=workspace) + + assert application.report[0].status == "applied" + assert (workspace / "doc.md").read_bytes() == b"l1\nl2\nNEW\nl3\n" + + +def test_insert_after_target_ending_with_newline_adds_no_blank_line(tmp_path: Path) -> None: + """A target that ends with its own newline puts the insert right after it.""" + workspace = tmp_path / "ws" + _write(workspace / "doc.md", "l1\nl2\nl3\nl4\n") + plan = EditPlan( + summary="terminated anchor", + edits=( + EditOp( + op="insert_after", + file="doc.md", + target="l1\nl2\n", + content="NEW", + rationale="r", + ), + ), + ) + + application = apply_edit_plan(plan, workspace=workspace) + + assert application.report[0].status == "applied" + assert (workspace / "doc.md").read_bytes() == b"l1\nl2\nNEW\nl3\nl4\n" + + +def test_insert_after_multiline_block_missing_and_ambiguous(tmp_path: Path) -> None: + """A multi-line block anchor follows the same 0/2 occurrence contract.""" + workspace = tmp_path / "ws" + _write(workspace / "missing.md", "l1\nl2\nl3\n") + _write(workspace / "dup.md", "l1\nl2\nl1\nl2\nl3\n") + missing = EditPlan( + summary="missing block", + edits=( + EditOp( + op="insert_after", + file="missing.md", + target="l1\nl2\nl4\n", + content="x", + rationale="r", + ), + ), + ) + ambiguous = EditPlan( + summary="ambiguous block", + edits=( + EditOp( + op="insert_after", + file="dup.md", + target="l1\nl2\n", + content="x", + rationale="r", + ), + ), + ) + + missing_application = apply_edit_plan(missing, workspace=workspace) + ambiguous_application = apply_edit_plan(ambiguous, workspace=workspace) + + assert missing_application.report[0].status == "skipped_anchor_missing" + assert "anchor not found" in missing_application.report[0].message + assert ambiguous_application.report[0].status == "error" + assert "anchor is ambiguous" in ambiguous_application.report[0].message + assert (workspace / "missing.md").read_bytes() == b"l1\nl2\nl3\n" + assert (workspace / "dup.md").read_bytes() == b"l1\nl2\nl1\nl2\nl3\n" + + +def test_insert_after_multiline_block_keeps_crlf_ending(tmp_path: Path) -> None: + """A multi-line block in a CRLF file inserts CRLF-terminated lines.""" + workspace = tmp_path / "ws" + _write(workspace / "doc.md", "l1\r\nl2\r\nl3\r\nl4\r\nl5\r\n") + plan = EditPlan( + summary="crlf block", + edits=( + EditOp( + op="insert_after", + file="doc.md", + target="l2\r\nl3\r\nl4\r\n", + content="NEW1\nNEW2", + rationale="r", + ), + ), + ) + + application = apply_edit_plan(plan, workspace=workspace) + + assert application.report[0].status == "applied" + assert (workspace / "doc.md").read_bytes() == ( + b"l1\r\nl2\r\nl3\r\nl4\r\nNEW1\r\nNEW2\r\nl5\r\n" + ) + + +def test_production_shaped_plan_replays_with_every_edit_applied(tmp_path: Path) -> None: + """A production-shaped 8-edit plan with a block anchor validates and applies.""" + workspace = tmp_path / "ws" + skill = ( + "# demo skill\n" + "\n" + "## 概述\n" + "把上游轨迹整理成周报。\n" + "\n" + "## 步骤\n" + "### 输入\n" + "读取 sessions 列表\n" + "过滤已归档条目\n" + "\n" + "### 输出\n" + "生成 summary.md\n" + "附带统计表\n" + "\n" + "### 验收模板\n" + "运行 fixtures:check 确认 corpus 有效\n" + "运行 test:api 确认回归全绿\n" + "确认 git diff 只含目标文件\n" + "\n" + "## 限制\n" + "不读取生产凭据。\n" + ) + _write(workspace / "skills" / "demo" / "SKILL.md", skill) + regression_evidence = "\n".join(f"回归证据第 {index} 行" for index in range(1, 29)) + block_anchor = ( + "### 验收模板\n" + "运行 fixtures:check 确认 corpus 有效\n" + "运行 test:api 确认回归全绿\n" + "确认 git diff 只含目标文件\n" + ) + raw_plan = { + "summary": "补齐验收模板回归证据并修正统计口径", + "edits": [ + { + "op": "replace", + "file": "skills/demo/SKILL.md", + "target": "把上游轨迹整理成周报。", + "content": "把上游轨迹整理成带异常标注的周报。", + "rationale": "概述缺异常标注口径", + }, + { + "op": "insert_after", + "file": "skills/demo/SKILL.md", + "target": block_anchor, + "content": regression_evidence, + "rationale": "验收模板缺回归证据", + }, + { + "op": "insert_after", + "file": "skills/demo/SKILL.md", + "target": "### 输出", + "content": "输出前先按对象去重。", + "rationale": "输出缺去重前提", + }, + { + "op": "delete", + "file": "skills/demo/SKILL.md", + "target": "过滤已归档条目\n", + "rationale": "该输入步骤已由上游保证", + }, + { + "op": "append", + "file": "skills/demo/SKILL.md", + "content": "维护备注:本文件为测试合成副本。", # noqa: RUF001 + "rationale": "标注合成来源", + }, + { + "op": "replace", + "file": "skills/demo/SKILL.md", + "target": "附带统计表", + "content": "附带统计表(含错误分级)。", # noqa: RUF001 + "rationale": "统计缺错误分级", + }, + { + "op": "insert_after", + "file": "skills/demo/SKILL.md", + "target": "## 限制\n", + "content": "凭据零感知同样适用于评测网关。", + "rationale": "限制缺网关侧口径", + }, + { + "op": "append", + "file": "skills/demo/SKILL.md", + "content": "完。", + "rationale": "收尾标记", + }, + ], + } + + plan = EditPlan.model_validate(raw_plan) + application = apply_edit_plan(plan, workspace=workspace) + + final = (workspace / "skills" / "demo" / "SKILL.md").read_bytes().decode("utf-8") + assert [status.status for status in application.report] == ["applied"] * 8 + assert application.files == ("skills/demo/SKILL.md",) + inserted = plan.edits[1].content + assert inserted is not None + assert len(inserted.splitlines()) == 28 + assert f"{block_anchor}{regression_evidence}\n" in final + assert "### 输出\n输出前先按对象去重。\n生成 summary.md\n" in final + assert "附带统计表(含错误分级)。\n" in final # noqa: RUF001 + assert "过滤已归档条目" not in final + assert "## 限制\n凭据零感知同样适用于评测网关。\n不读取生产凭据。\n" in final + assert final.endswith("维护备注:本文件为测试合成副本。\n完。\n") # noqa: RUF001 + + def test_replace_with_identical_content_is_applied_but_not_changed(tmp_path: Path) -> None: """An applied no-op edit is reported applied without claiming a file change.""" workspace = tmp_path / "ws" diff --git a/plans/2026-11-22-pr510-review.md b/plans/2026-11-22-pr510-review.md index cbfd898f..2236e9fc 100644 --- a/plans/2026-11-22-pr510-review.md +++ b/plans/2026-11-22-pr510-review.md @@ -90,7 +90,7 @@ plans/2026-11-22-pr510-review.md A 本检视文档 - 真实仓库里 legacy `create_candidate` 可提交 `.harness-evolution/candidate-r1.md`;`.git/config` 被拒「never stageable」。 - 内容不变的「已应用」plan:`report=applied`、`files=()`;把这种文件塞进 bundle 提交则 `git commit` 失败(`candidate commit failed`,stage=commit)。 - 以上探针记录检视时(`758f5149`)的行为;FIX 1-4 改变了其中 scratch 失败、`insert_after` 多行锚、`allowed_paths` 默认与 `edits` 可变四项,最终语义见 §6 结论。 + 以上探针记录检视时(`758f5149`)的行为;FIX 1-4 改变了其中 scratch 失败、`insert_after` 多行锚、`allowed_paths` 默认与 `edits` 可变四项,最终语义见 §6 结论。其中 `insert_after` 多行锚的拒绝已再被 #599(2026-11-25)废除:锚点契约统一为「文件内存在且唯一,可跨行」,插入点为块末行之后。 ## §2 架构导览 @@ -311,7 +311,7 @@ PR 描述里的验证声明(原样): **预判**:把单行检查搬进 `EditOp._validate_op_fields`(一行 `if self.op == "insert_after" and ("\n" in target or "\r" in target): raise`),applier 保留防御但变成真正的 `pragma: no cover`。另一条路是让 `insert_after` 支持多行锚,但那要重新定义「在匹配段之后」与行边界,成本明显更高,不建议为假设需求扩语义。 -**结论**:已决 2026-11-22:接受(FIX 3),把单行锚约束搬进 `EditOp._validate_op_fields`(理由:同一种「锚」在三个 op 里的语义差必须在模型层暴露,坏计划在落盘前失败、回喂模型拿到字段级错误;applier 保留防御性检查,`model_construct` 绕过的路径仍记 `error`)。回归用例见 `test_insert_after_rejects_a_multiline_anchor_at_model_construction`。 +**结论**:已决 2026-11-22:接受(FIX 3),把单行锚约束搬进 `EditOp._validate_op_fields`(理由:同一种「锚」在三个 op 里的语义差必须在模型层暴露,坏计划在落盘前失败、回喂模型拿到字段级错误;applier 保留防御性检查,`model_construct` 绕过的路径仍记 `error`)。回归用例见 `test_insert_after_rejects_a_multiline_anchor_at_model_construction`。2026-11-25 更新:该决定已由 #599 反转——生产 run 因这条未写进 prompt 的隐藏单行规则在 patch 阶段整轮失败,锚点契约统一为「存在且唯一、可跨行」,插入点为块末行之后,上述回归用例已随之删除。 ### 讨论点 8:bugfix-21 的 `.harness-evolution/edits.json5` scratch 会让 `_require_clean` 直接失败 @@ -400,7 +400,7 @@ FIX 1-4 的代码落地位于本 PR 的 `fix(api): harden the EditPlan seam from **检视发现**: 1. **`allowed_paths` 默认 fail-open**(中,`:340-341`、`:562`):见讨论点 9。修法:`None` 与 `()` 分开语义,或在 docstring 显式化。 -2. **`insert_after` 单行约束只活在 applier**(低,`:479-488` vs `:157-171`):见讨论点 7。修法:一行校验器搬进模型。 +2. **`insert_after` 单行约束只活在 applier**(低,`:479-488` vs `:157-171`):见讨论点 7。修法:一行校验器搬进模型。(2026-11-25 更新:#599 已删除该约束本身,见讨论点 7 结论。) 3. **「已应用但无改动」没有下游表示**(低,前瞻,`:627-637`、`:676-681`):实测 content == target 时 `applied`、`files=()`;`PatchBundle` 拒绝空 `files`,把这种文件塞进非空 bundle 也会让 `git commit` 失败(我的独立探针)。bugfix-21 需要一个「本轮无改动」分支(跳过提交 / 记 `noop` 状态),否则「已经修好了」会被当成系统错误。 4. **符号链接 write-through 的路径错位**(低,`:614`、`:628-629`):写盘用解析后的 `resolved`、`changed` 与报告用词法 `edit.file`;实测 `alias.md -> real.md` 编辑后 `files=('alias.md',)` 而内容变的是 `real.md`。对 `git diff` 无影响(git 看到真实文件),但审计时「报告路径」与「diff 路径」会不一致。若认为这是问题,修法是报告解析后的相对路径,或显式拒绝符号链接目标。 5. **无实害但值得知道**:`EditPlan` 的 frozen 是浅冻结(讨论点 6);`_validation_detail` 截断可能切在错误条目中间(1000 字符、影响小);`insert_after` 的 `text.count(target)` 与逐行查找在「同一行出现两次」时会判多义(实测 `x\nx\n` 正确判 ambiguous),语义自洽。 diff --git a/plans/fullstack-design/07-backend-implementation.md b/plans/fullstack-design/07-backend-implementation.md index c3016193..c6ed6ecf 100644 --- a/plans/fullstack-design/07-backend-implementation.md +++ b/plans/fullstack-design/07-backend-implementation.md @@ -839,14 +839,14 @@ patch 生成采用 SkillOpt 式编辑指令(对齐 [microsoft/SkillOpt](https: edits: [ { op: "replace", // append | insert_after | replace | delete file: "skills/fetch-github-file/config.json", - target: "\"timeoutSeconds\": 30", // 锚文本:文件内必须存在且唯一 + target: "\"timeoutSeconds\": 30", // 锚文本:文件内必须存在且唯一,可以是跨行文本块 content: "\"timeoutSeconds\": 120", rationale: "三条 case 均为 30s 超时,同一根因" } ] } ``` -- **执行流**:agent 以只读工具(Read/Grep/Glob)探索 → 写 `edits.json5`(submission 通道收货)→ 语义校验(`file ∈ allowed_paths`;锚**存在且唯一**,多义回喂要求补上下文;`len(edits) ≤ edit_budget`(默认 8,SkillOpt learning-rate 等价物:prompt 约束 + 硬截断))→ `edits.py` 确定性应用(replace 首个匹配 / insert_after 行边界 / append 追加,逐条 status 报告、后续编辑的锚实时复查)→ `git diff` 收真实改动 → `PatchBundle{files, unified_diff, note=intent.summary, intent=EditPlan, report=逐条状态}` → candidate 提交(`Harness-Patch-Hash` trailer)→ push → eval。 +- **执行流**:agent 以只读工具(Read/Grep/Glob)探索 → 写 `edits.json5`(submission 通道收货)→ 语义校验(`file ∈ allowed_paths`;锚**存在且唯一**,可以是单行或多行文本块,多义回喂要求补上下文;`len(edits) ≤ edit_budget`(默认 8,SkillOpt learning-rate 等价物:prompt 约束 + 硬截断))→ `edits.py` 确定性应用(replace 首个匹配 / insert_after 块末行之后 / append 追加,逐条 status 报告、后续编辑的锚实时复查)→ `git diff` 收真实改动 → `PatchBundle{files, unified_diff, note=intent.summary, intent=EditPlan, report=逐条状态}` → candidate 提交(`Harness-Patch-Hash` trailer)→ push → eval。 - **拒绝处理**:评测 reject 沿用既有状态机结束该轮并清理候选,不自动开启下一轮,也不注入 `--resume` 反馈或 rejected-edit buffer(2026-11-23 决定:失败即拒绝,避免 round 生命周期改造);accept → 并入 run 分支。 - **安全闸**:agent 工具面 = 只读 + 写一个 json5 文件(`dontAsk` 模式,无文件编辑权限);`.harness-evolution/` 排除在 diff scope 外;应用器只在临时镜像上写入,越界/失败编辑不会触达仓库,因此无需 `git checkout -- .` 回滚;diff + intent + report 落 run events(diff 为候选 commit 的真实 git diff,超长时按事件载荷上限截断)。声明(intent)与实际(diff)的对照本身是审计信号。 - **patch source 接入**:新增第三种模式 `agent-edit` 注册进 `PATCH_SOURCE_MODES` 与工厂,沿用「run 冻结配置优先、env 兜底」的选择语义;`PatchSource` 增加 `build_bundle()`(默认实现包装旧 `build()` 为单文件 bundle,旧实现零改动)。 diff --git a/plans/superpowers/plans/2026-11-25-issue-599-edit-insert-anchor-multiline.md b/plans/superpowers/plans/2026-11-25-issue-599-edit-insert-anchor-multiline.md new file mode 100644 index 00000000..6fbb8d51 --- /dev/null +++ b/plans/superpowers/plans/2026-11-25-issue-599-edit-insert-anchor-multiline.md @@ -0,0 +1,85 @@ +# edit 多行 insert_after 锚点实现计划(#599) + +> **For agentic workers:** this plan follows the superpowers task-by-task style; the linked issue `.agents/flow/issues/bugfix-edit-insert-anchor-multiline.md` is the implementation contract. Every interactive question is answered from `plans/fullstack-design`, not by asking the user. + +**Goal:** `insert_after` 的锚点契约统一为「文件内存在且唯一的文本片段(可跨行)」,content 插入在匹配块末行之后;单行 target 输出与现状逐字节一致;prompt、派生 schema 说明、设计文档与 validator 表达同一契约。 + +**Architecture:** `EditOp`(Pydantic 单一事实源)删除单行拒绝;`edits.py` 应用器改为整段唯一匹配 + 块末行之后插入(沿用 `text.count` 的缺失/多义分支);`_edit_prompt()` 把可跨行契约写进模型可见文案;07 §5.5.4 同步;回归测试覆盖多行块、单行逐字节一致、CRLF、缺失与多义。 + +**Scope:** `apps/api/app/third_party_api/ai_agent/edits.py`、`apps/api/app/service/evolution/patch_source.py`、`apps/api/tests/test_edit_plan_applier.py`、`apps/api/tests/test_ai_agent_claude_code.py`(如有 single-line 断言)、`plans/fullstack-design/07-backend-implementation.md`、`plans/**`、`.agents/flow/issues/bugfix-edit-insert-anchor-multiline*`、`.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline*`。不改 `claude_code.py` / `submission.py` / 工具面 / 预算 / 超时 / 前端。 + +## 交互问题的设计答案 + +| 问题 | 答案来源 | 决定 | +|---|---|---| +| 多行 target 的插入点在哪? | issue 目标 2 + [07 §5.5.4](../../fullstack-design/07-backend-implementation.md#554-edit-指令式-patcheditplan--editspy) | 匹配块末行之后;确定性、可重放 | +| target 自身以换行结尾时怎么办? | issue 实现内容 2 | 以该换行之后为插入点,不额外补终止符 | +| 插入行的换行风格? | issue 实现内容 2 | 沿用锚块末行现有风格:`\r\n` 或 `\n`(bare `\r` 回落 `\n`,与现状一致) | +| 单行 target 是否改变输出? | issue 目标 2 | 否,逐字节一致;`test_insert_after_last_line_without_newline` 等既有用例保持通过 | +| 锚缺失 / 多义如何处理? | issue 实现内容 2 + #494 契约 | 沿用 `text.count(target)`:0 次 → `skipped_anchor_missing`,>1 → `error`(`anchor is ambiguous`) | +| 是否保留唯一性/预算/scope 限制? | issue 非目标 | 全部保留;不允许用多行 target 绕过唯一性检查 | +| edit 是否增加反馈重试? | issue 非目标 + 07 §5.5.3 | 不增加;单次调用、失败即终止的语义不变 | +| prompt 里怎么写锚点契约? | issue 实现内容 3 + 07 §5.5.3「调用方 prompt 必须把 schema 表达不了的语义约束说清楚」 | 「锚文本是文件内唯一出现的文本片段,可跨行;insert_after 插到该片段末行之后」 | +| 设计文档改哪? | issue 实现内容 4 | 07 §5.5.4 执行流 bullet 与 json5 示例注释 | +| 观测缺口(ConfigError 丢 detail)修不修? | issue 实现内容 6 | 不修,不在本方案内扩大修改面 | +| Agent Note 放哪? | [.agents/notes/README.md](../../../.agents/notes/README.md) 惯例 | `.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline` 三件套 | +| flow issue 怎么回填? | [.agents/flow/README.md](../../../.agents/flow/README.md) 状态机 | `status: ready → in-progress`,`adr` 回填 note 路径,双语逐字节一致后 `pnpm record:i18n` | +| 生产计划原文能进仓库吗? | issue 依赖与交付边界 | 不能;replay 测试只用合成安全副本(结构、行数与生产形状一致,不含生产原文) | + +### Task 1: 失败回归(RED) + +**Files:** Modify `apps/api/tests/test_edit_plan_applier.py`. + +- [x] 新增测试:合成 4 行唯一块锚点的 `insert_after` 调用 `EditPlan.model_validate()`,断言当前实现抛 `target must be a single-line substring`(先红)。 +- [x] 运行 `pnpm test:api -- tests/test_edit_plan_applier.py` 确认新用例红、既有用例绿。 + +### Task 2: validator 放宽 + 应用器按块定位(GREEN) + +**Files:** Modify `apps/api/app/third_party_api/ai_agent/edits.py`. + +- [x] 删除 `_validate_op_fields()` 中 `insert_after` 对 `\n` / `\r` 的拒绝;docstring 改为「insert_after 的 target 是文件内唯一出现的文本片段,可以跨行」。 +- [x] 重写 `_insert_after_text()`:整段匹配唯一出现的 target;target 以换行(`\r\n`/`\n`/`\r`)结尾 → 插入点在该换行之后;否则插入点在匹配块末字符所在行的行终止符之后(EOF 无终止符 → 补 `\n`);插入行沿用该行风格(`\r\n` 或 `\n`)。 +- [x] `_apply_one()` 的 insert_after 分支删除单行拒绝,保留 `text.count(target)` 的 0 次 → skipped、>1 次 → ambiguous 分支;清除「not contained in one line」旧守卫。 +- [x] 单行路径逐字节回归:`test_insert_after_last_line_without_newline`、四 op 精确内容用例、CRLF 用例全部保持通过。 + +### Task 3: prompt 与派生 schema 契约 + +**Files:** Modify `apps/api/app/service/evolution/patch_source.py`. + +- [x] `_edit_prompt()` 的锚点行改为:「锚文本必须是文件内唯一出现的文本片段,可跨行;`insert_after` 把 content 插到该片段末行之后」。 +- [x] 若 `test_ai_agent_claude_code.py` 断言 prompt 锚点文案,同步更新。 + +### Task 4: 设计文档同步 + +**Files:** Modify `plans/fullstack-design/07-backend-implementation.md`. + +- [x] §5.5.4 json5 示例注释改为「锚文本:文件内必须存在且唯一,可以是跨行文本块」。 +- [x] §5.5.4 执行流 bullet:「insert_after 行边界」改为「insert_after 块末行之后」,并在锚规则处写明「锚可以是单行或多行文本块」。 +- [x] 全仓 grep `single-line substring` / `单行` 清理其它残留引用(docs/**、plans/**)。 + +### Task 5: 回归测试完善 + +**Files:** Modify `apps/api/tests/test_edit_plan_applier.py`. + +- [x] 删除 `test_insert_after_rejects_a_multiline_anchor_at_model_construction` 及其参数行(`("insert_after", "line\nbreak", ...)` 断言 single-line 的行)。 +- [x] 新增:4 行唯一块锚点通过校验,应用后 content 出现在块末行之后;文件其余字节不变。 +- [x] 新增:单行 target(行中、行尾、EOF 无终止符)输出与旧实现逐字节一致(固定期望串断言)。 +- [x] 新增:多行块 0 次 → `skipped_anchor_missing`;2 次 → `error` 且 message 含 `anchor is ambiguous`。 +- [x] 新增:CRLF 文件中的多行块插入保持 `\r\n`。 +- [x] 新增:`append` / `replace` / `delete` 既有语义不变的守卫断言(可复用既有用例,不必重复)。 +- [x] 新增:生产计划形状 replay——8 条编辑、其中 1 条使用 4 行块锚点(合成安全副本),`EditPlan.model_validate()` 通过、`apply_edit_plan()` 只改目标文件、8 条报告全部 `applied`。 + +### Task 6: 文档、Note 与流程 + +**Files:** Create `.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.{md,en.md,i18n.yaml}`; modify `.agents/flow/issues/bugfix-edit-insert-anchor-multiline.md` 与 `.en.md`. + +- [x] Agent Note 三件套:Status: implemented;Problem / Decision / Alternatives considered / Consequences;记录「可见契约与 validator 契约不一致」的根因与「块末行之后插入」的决定。 +- [x] flow issue 双语 yaml fence 逐字节一致:`status: ready → in-progress`、`adr: ../../notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.md`。 +- [x] `pnpm record:i18n -- .agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline` 与 `pnpm record:i18n -- .agents/flow/issues/bugfix-edit-insert-anchor-multiline`。 + +### Task 7: 验证 + +- [x] `pnpm test:api -- tests/test_edit_plan_applier.py tests/test_ai_agent_claude_code.py` +- [x] `pnpm lint:api`、`pnpm typecheck:api` +- [x] `pnpm verify:flow`、`pnpm lint:docs` +- [x] 记录每条命令的实际结果;不提交截图或生产内容。 From 023662e42638b6c709b1c5a2b4dcb2a0e4c148de Mon Sep 17 00:00:00 2001 From: TangZ-L <345187680+TangZ-L@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:24:29 +0800 Subject: [PATCH 2/7] =?UTF-8?q?chore(flow):=20=E4=BF=AE=E6=AD=A3=E9=87=8D?= =?UTF-8?q?=E5=A4=8D=20id=20=E4=B8=8E=20#588=20=E7=8A=B6=E6=80=81=E6=BC=82?= =?UTF-8?q?=E7=A7=BB=EF=BC=8C=E8=A7=A3=E9=99=A4=20main=20=E6=B5=81?= =?UTF-8?q?=E7=A8=8B=E9=97=A8=E7=A6=81=20(#599)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit main 上 bugfix-explicit-skill-conclusion 与 bugfix-bad-case-sync-type-title 同用 id bugfix-56;#588 已随 PR #589 关闭而本地仍为 in-progress。改为 bugfix-58 并同步 status done,重录 i18n。 --- .agents/flow/issues/bugfix-explicit-skill-conclusion.en.md | 4 ++-- .../flow/issues/bugfix-explicit-skill-conclusion.i18n.yaml | 4 ++-- .agents/flow/issues/bugfix-explicit-skill-conclusion.md | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.agents/flow/issues/bugfix-explicit-skill-conclusion.en.md b/.agents/flow/issues/bugfix-explicit-skill-conclusion.en.md index 2283275d..a43a4cce 100644 --- a/.agents/flow/issues/bugfix-explicit-skill-conclusion.en.md +++ b/.agents/flow/issues/bugfix-explicit-skill-conclusion.en.md @@ -4,11 +4,11 @@ English | [中文](bugfix-explicit-skill-conclusion.md) ```yaml flow kind: issue -id: bugfix-56 +id: bugfix-58 milestone: bugfix depends: [] priority: P2 -status: in-progress +status: done scope: - attribute-badcases/** - apps/api/app/service/evolution/local_attribution.py diff --git a/.agents/flow/issues/bugfix-explicit-skill-conclusion.i18n.yaml b/.agents/flow/issues/bugfix-explicit-skill-conclusion.i18n.yaml index 4364ccb0..fd0d1344 100644 --- a/.agents/flow/issues/bugfix-explicit-skill-conclusion.i18n.yaml +++ b/.agents/flow/issues/bugfix-explicit-skill-conclusion.i18n.yaml @@ -1,5 +1,5 @@ # 双语配对一致性记录(docs/i18n/README.md):两侧在最后一次确认一致状态下的 # git blob hash。两种语言同等权威;编辑任一侧后带上另一侧,然后重录: # pnpm run record:i18n -- .agents/flow/issues/bugfix-explicit-skill-conclusion.md -bugfix-explicit-skill-conclusion.md: 2e4cbe6321c91fe1c9f2934df759c78c64f6d3be -bugfix-explicit-skill-conclusion.en.md: 2283275dda6b71bc2365277dd3f1ec2a5ae6635b +bugfix-explicit-skill-conclusion.md: 36d66349f591bd0719dc87ad1b1d03eaa1bcdce4 +bugfix-explicit-skill-conclusion.en.md: a43a4ccee06f0d8c47a5dcebdf347ba2b972680b diff --git a/.agents/flow/issues/bugfix-explicit-skill-conclusion.md b/.agents/flow/issues/bugfix-explicit-skill-conclusion.md index 2e4cbe63..36d66349 100644 --- a/.agents/flow/issues/bugfix-explicit-skill-conclusion.md +++ b/.agents/flow/issues/bugfix-explicit-skill-conclusion.md @@ -4,11 +4,11 @@ ```yaml flow kind: issue -id: bugfix-56 +id: bugfix-58 milestone: bugfix depends: [] priority: P2 -status: in-progress +status: done scope: - attribute-badcases/** - apps/api/app/service/evolution/local_attribution.py From 01d3bd8c4197c9fe8d9cb441e2b5b5c6e815e39b Mon Sep 17 00:00:00 2001 From: TangZ-L <345187680+TangZ-L@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:37:30 +0800 Subject: [PATCH 3/7] =?UTF-8?q?fix(api):=20=E4=BF=AE=E5=A4=8D=20insert=5Fa?= =?UTF-8?q?fter=20=E6=9C=AB=E8=A1=8C=E6=97=A0=E6=8D=A2=E8=A1=8C=E6=97=B6?= =?UTF-8?q?=E4=B8=A2=E5=AD=97=E7=AC=A6=E5=B9=B6=E8=A1=A5=E8=BE=B9=E7=95=8C?= =?UTF-8?q?=E5=9B=9E=E5=BD=92=20(#599)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 检视发现:_insert_after_text 在文件末行无结尾换行且 target 不到 EOF 时, 用 text[:match_end] 作 prefix 会静默丢弃 match 之后到 EOF 的文本。 改为整段保留(prefix = f"{text}{ending}",suffix 为空)。 补 4 格单行字节回归(末行行中 target、CRLF 半终止、bare-\r target)、 prompt 契约断言与 replace 多行锚行为断言;Note 明确唯一性按不重叠计数、 EOF 插入点与逐字节承诺边界;07 §5.5.4 把「多义回喂」纠正为 ambiguous 拒绝。 --- ...6-11-25-edit-insert-anchor-multiline.en.md | 2 +- ...-25-edit-insert-anchor-multiline.i18n.yaml | 4 +- ...2026-11-25-edit-insert-anchor-multiline.md | 2 +- .../api/app/third_party_api/ai_agent/edits.py | 13 ++++-- apps/api/tests/test_edit_plan_applier.py | 45 +++++++++++++++---- .../07-backend-implementation.md | 2 +- 6 files changed, 51 insertions(+), 17 deletions(-) diff --git a/.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.en.md b/.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.en.md index c4ca1089..ac433e70 100644 --- a/.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.en.md +++ b/.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.en.md @@ -10,7 +10,7 @@ The production full run `01M885592456VVK5B68DSMRKTE` failed at turn 3/10 of step ## Decision -The `insert_after` anchor contract is unified as "a text fragment that exists exactly once in the file and may span lines". On the model side, `EditOp._validate_op_fields()` no longer rejects targets containing `\n`/`\r` (the single-line rule introduced in #494); all other constraints (append forbids target, delete forbids content, non-blank and line-capped content, etc.) stay as they are. On the applier side, `_insert_after_text()` is rewritten as "match the unique whole fragment, insert after the block's last line": the insertion point sits after a trailing newline of the target itself (`\r\n`/`\n`/`\r`), otherwise after the next line terminator of the line holding the matched block's final character, or a synthesized `\n` at EOF; inserted lines reuse that terminator's style (`\r\n` stays `\r\n`; a bare-`\r` anchor line keeps its bytes and inserts with `\n`). The `text.count(target)` branches stay untouched — 0 occurrences → `skipped_anchor_missing`, more than 1 → `error` (ambiguous) — and single-line targets reproduce the old output byte for byte. The contract also enters the model-visible surface: `_edit_prompt()`'s anchor line becomes "anchor text must be a fragment that occurs exactly once in the file and may span lines; insert_after inserts content after that fragment's last line", with 07 §5.5.4's execution bullet and json5 example comment updated to match. Regression tests cover validation and application of a 4-line block anchor, single-line byte-for-byte cases (mid-line / line-end / EOF without terminator / bare-`\r` / CRLF), missing and ambiguous block anchors, CRLF block insertion, and a synthetic replay of a production-shaped 8-edit plan (no production text). +The `insert_after` anchor contract is unified as "a text fragment that exists exactly once in the file and may span lines". On the model side, `EditOp._validate_op_fields()` no longer rejects targets containing `\n`/`\r` (the single-line rule introduced in #494); all other constraints (append forbids target, delete forbids content, non-blank and line-capped content, etc.) stay as they are. On the applier side, `_insert_after_text()` is rewritten as "match the unique whole fragment, insert after the block's last line": the insertion point sits after a trailing newline of the target itself (`\r\n`/`\n`/`\r`), otherwise after the next line terminator of the line holding the matched block's final character, or a synthesized `\n` at EOF; inserted lines reuse that terminator's style (`\r\n` stays `\r\n`; a bare-`\r` anchor line keeps its bytes and inserts with `\n`). The `text.count(target)` branches stay untouched — 0 occurrences → `skipped_anchor_missing`, more than 1 → `error` (ambiguous) — with uniqueness counted as non-overlapping matches (the semantics `replace`/`delete` already use). An unterminated final line is the end of the file, so the insertion point is EOF and no text between the match and EOF is dropped. Single-line targets reproduce the old output byte for byte in `\n`, `\r\n`, and bare-`\r`-only files; mixed bare-`\r`/`\n` files and the extra Unicode line separators (`\v`, `\f`, `\x85`, `\u2028`, ...) that the old `splitlines` folded are outside that promise. The contract also enters the model-visible surface: `_edit_prompt()`'s anchor line becomes "anchor text must be a fragment that occurs exactly once in the file and may span lines; insert_after inserts content after that fragment's last line", with 07 §5.5.4's execution bullet and json5 example comment updated to match. Regression tests cover validation and application of a 4-line block anchor, single-line byte-for-byte cases (mid-line / line-end / EOF without terminator / bare-`\r` / CRLF), missing and ambiguous block anchors, CRLF block insertion, and a synthetic replay of a production-shaped 8-edit plan (no production text). ## Alternatives considered diff --git a/.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.i18n.yaml index f5c69487..b7ccb88b 100644 --- a/.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.i18n.yaml +++ b/.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.i18n.yaml @@ -1,5 +1,5 @@ # 双语配对一致性记录(docs/i18n/README.md):两侧在最后一次确认一致状态下的 # git blob hash。两种语言同等权威;编辑任一侧后带上另一侧,然后重录: # pnpm run record:i18n -- .agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.md -2026-11-25-edit-insert-anchor-multiline.md: 8bf95438a4a9735b03d1cee4993e10914b0eba9b -2026-11-25-edit-insert-anchor-multiline.en.md: c4ca1089e58d361625a7007b5f385bc0100399a4 +2026-11-25-edit-insert-anchor-multiline.md: 9fb87b7d6842093b5ca0e1e74f8c4f81138b3777 +2026-11-25-edit-insert-anchor-multiline.en.md: ac433e70271a20722b091a4363ca993c2c59fce1 diff --git a/.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.md b/.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.md index 8bf95438..9fb87b7d 100644 --- a/.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.md +++ b/.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.md @@ -10,7 +10,7 @@ Status: implemented ## Decision -`insert_after` 的锚点契约统一为「文件内存在且唯一的文本片段,可以跨行」。模型侧删除 `EditOp._validate_op_fields()` 对含 `\n`/`\r` target 的拒绝(#494 引入的单行规则),其余约束(append 禁 target、delete 禁 content、content 非空与行数上限等)原样保留。应用侧把 `_insert_after_text()` 重写为「整段唯一匹配 + 块末行之后插入」:插入点在 target 自身结尾换行(`\r\n`/`\n`/`\r`)之后,否则在匹配块末字符所在行的下一个行终止符之后,EOF 无终止符时补 `\n`;插入行沿用该终止符风格(`\r\n` 保持 `\r\n`;bare `\r` 锚行字节不动,插入行用 `\n`)。`text.count(target)` 的 0 次 → `skipped_anchor_missing`、>1 次 → `error`(ambiguous)分支原样保留,单行 target 的输出与旧实现逐字节一致。契约同步写进模型可见面:`_edit_prompt()` 的锚点行改为「锚文本必须是文件内唯一出现的文本片段,可跨行;insert_after 把 content 插到该片段末行之后」,07 §5.5.4 的执行流 bullet 与 json5 示例注释同步。回归测试覆盖 4 行块锚点的校验与应用、单行逐字节(行中/行尾/EOF 无终止符/bare-`\r`/CRLF)、块锚缺失与多义、CRLF 块插入,以及生产计划形状的 8 条编辑合成 replay(不含生产原文)。 +`insert_after` 的锚点契约统一为「文件内存在且唯一的文本片段,可以跨行」。模型侧删除 `EditOp._validate_op_fields()` 对含 `\n`/`\r` target 的拒绝(#494 引入的单行规则),其余约束(append 禁 target、delete 禁 content、content 非空与行数上限等)原样保留。应用侧把 `_insert_after_text()` 重写为「整段唯一匹配 + 块末行之后插入」:插入点在 target 自身结尾换行(`\r\n`/`\n`/`\r`)之后,否则在匹配块末字符所在行的下一个行终止符之后,EOF 无终止符时补 `\n`;插入行沿用该终止符风格(`\r\n` 保持 `\r\n`;bare `\r` 锚行字节不动,插入行用 `\n`);无终止符的末行即文件末尾,插入点是文件末尾,匹配点与 EOF 之间的文本不会被丢弃。`text.count(target)` 的 0 次 → `skipped_anchor_missing`、>1 次 → `error`(ambiguous)分支原样保留,唯一性按不重叠匹配计数(与 `replace`/`delete` 一致)。单行 target 在 `\n`、`\r\n` 与纯 bare `\r` 文件中的输出与旧实现逐字节一致;混合 bare `\r` 与 `\n` 的文件,以及旧实现 `splitlines` 额外切分的 `\v`/`\f`/`\x85`/`\u2028` 等 Unicode 行分隔符,不在该承诺内。契约同步写进模型可见面:`_edit_prompt()` 的锚点行改为「锚文本必须是文件内唯一出现的文本片段,可跨行;insert_after 把 content 插到该片段末行之后」,07 §5.5.4 的执行流 bullet 与 json5 示例注释同步。回归测试覆盖 4 行块锚点的校验与应用、单行逐字节(行中/行尾/EOF 无终止符/bare-`\r`/CRLF)、块锚缺失与多义、CRLF 块插入,以及生产计划形状的 8 条编辑合成 replay(不含生产原文)。 ## Alternatives considered diff --git a/apps/api/app/third_party_api/ai_agent/edits.py b/apps/api/app/third_party_api/ai_agent/edits.py index ff200a91..0358ca99 100644 --- a/apps/api/app/third_party_api/ai_agent/edits.py +++ b/apps/api/app/third_party_api/ai_agent/edits.py @@ -467,9 +467,11 @@ def _insert_after_text(text: str, target: str, content: str) -> str: ``target`` may span multiple lines. When it ends with a line terminator the insertion point is right after that terminator; otherwise it is the end of - the line containing the match's last character, and an unterminated final - line gains one. Inserted lines reuse the anchor line's ``\\r\\n`` or ``\\n`` - style, so a single-line target keeps producing the historical bytes. + the line containing the match's last character (the end of the file when + that line is unterminated), and an unterminated final line gains one. + Inserted lines reuse the anchor line's ``\\r\\n`` or ``\\n`` style; a bare + ``\\r`` anchor line keeps its bytes and inserted lines use ``\\n``. A + single-line target therefore keeps producing the historical bytes. """ try: match_end = text.index(target) + len(target) @@ -497,8 +499,11 @@ def _insert_after_text(text: str, target: str, content: str) -> str: if carriage != -1: ending, prefix, suffix = "\n", text[: carriage + 1], text[carriage + 1 :] else: + # The match's last line is the unterminated final line, so the + # insertion point is the end of the file; finishing that line + # must not drop text between the match and EOF. ending = "\n" - prefix, suffix = f"{text[:match_end]}{ending}", "" + prefix, suffix = f"{text}{ending}", "" inserted = content.splitlines() or [""] body = "".join(f"{line}{ending}" for line in inserted) return f"{prefix}{body}{suffix}" diff --git a/apps/api/tests/test_edit_plan_applier.py b/apps/api/tests/test_edit_plan_applier.py index 98fc37cd..1bce9dd3 100644 --- a/apps/api/tests/test_edit_plan_applier.py +++ b/apps/api/tests/test_edit_plan_applier.py @@ -411,16 +411,27 @@ def test_insert_after_accepts_a_unique_multiline_block_anchor(tmp_path: Path) -> assert (workspace / "doc.md").read_bytes() == b"l1\nl2\nl3\nl4\nl5\nNEW\nl6\n" -def test_replace_still_accepts_a_multiline_anchor_at_model_construction() -> None: +def test_replace_still_applies_a_multiline_anchor(tmp_path: Path) -> None: """replace keeps allowing a cross-line target; only insert_after was narrower.""" - multiline_replace = EditOp( - op="replace", - file="a.md", - target="line\nbreak", - content="x", - rationale="r", + workspace = tmp_path / "ws" + _write(workspace / "doc.md", "one\ntwo\nthree\n") + plan = EditPlan( + summary="multiline replace", + edits=( + EditOp( + op="replace", + file="doc.md", + target="one\ntwo", + content="ONE", + rationale="r", + ), + ), ) - assert multiline_replace.target == "line\nbreak" + + application = apply_edit_plan(plan, workspace=workspace) + + assert application.report[0].status == "applied" + assert (workspace / "doc.md").read_bytes() == b"ONE\nthree\n" def test_summary_rationale_and_content_cap_are_enforced() -> None: @@ -804,6 +815,13 @@ def test_insert_after_last_line_without_newline(tmp_path: Path) -> None: ("one\ntwo\n", "two", "three", "one\ntwo\nthree\n"), # A final unterminated line gains its boundary before the insert. ("one\ntwo", "two", "three", "one\ntwo\nthree\n"), + # A mid-line target on the unterminated final line keeps the tail to EOF. + ("one\ntwo", "tw", "x", "one\ntwo\nx\n"), + ("alpha\nbeta gamma", "beta", "x", "alpha\nbeta gamma\nx\n"), + # A target stopping halfway through a CRLF terminator finishes it. + ("l1\r\nl2\r\n", "l1\r", "NEW", "l1\r\nNEW\r\nl2\r\n"), + # A target ending with a bare \r keeps its bytes; inserted lines use \n. + ("a\rb\rc\r", "b\r", "x", "a\rb\rx\nc\r"), # A bare-\r anchor keeps its bytes; inserted lines use \n. ("a\rb\rc\r", "b", "x", "a\rb\rx\nc\r"), # A CRLF anchor line inserts \r\n-terminated content. @@ -1275,3 +1293,14 @@ def test_agent_edit_mode_requires_and_selects_the_agent_provider() -> None: assert isinstance(source, PatchSource) with pytest.raises(ConfigError, match="unknown patch source mode"): default_patch_source_factory(_run(eval_config={"patchMode": "llm"})) + + +def test_edit_prompt_states_the_same_anchor_contract_as_the_validator() -> None: + """The model-visible prompt states the cross-line, unique-fragment contract.""" + from app.service.evolution import patch_source + + prompt = patch_source._edit_prompt(_run(), _trace("对象行为异常"), allowed=("skills/**",)) + + assert "唯一出现的文本片段" in prompt + assert "可跨行" in prompt + assert "末行之后" in prompt diff --git a/plans/fullstack-design/07-backend-implementation.md b/plans/fullstack-design/07-backend-implementation.md index c6ed6ecf..00011381 100644 --- a/plans/fullstack-design/07-backend-implementation.md +++ b/plans/fullstack-design/07-backend-implementation.md @@ -846,7 +846,7 @@ patch 生成采用 SkillOpt 式编辑指令(对齐 [microsoft/SkillOpt](https: } ``` -- **执行流**:agent 以只读工具(Read/Grep/Glob)探索 → 写 `edits.json5`(submission 通道收货)→ 语义校验(`file ∈ allowed_paths`;锚**存在且唯一**,可以是单行或多行文本块,多义回喂要求补上下文;`len(edits) ≤ edit_budget`(默认 8,SkillOpt learning-rate 等价物:prompt 约束 + 硬截断))→ `edits.py` 确定性应用(replace 首个匹配 / insert_after 块末行之后 / append 追加,逐条 status 报告、后续编辑的锚实时复查)→ `git diff` 收真实改动 → `PatchBundle{files, unified_diff, note=intent.summary, intent=EditPlan, report=逐条状态}` → candidate 提交(`Harness-Patch-Hash` trailer)→ push → eval。 +- **执行流**:agent 以只读工具(Read/Grep/Glob)探索 → 写 `edits.json5`(submission 通道收货)→ 语义校验(`file ∈ allowed_paths`;锚**存在且唯一**(`text.count` 不重叠计数),可以是单行或多行文本块;多义按 `ambiguous` 拒绝(edit 单次调用,不回喂);`len(edits) ≤ edit_budget`(默认 8,SkillOpt learning-rate 等价物:prompt 约束 + 硬截断))→ `edits.py` 确定性应用(replace 首个匹配 / insert_after 块末行之后 / append 追加,逐条 status 报告、后续编辑的锚实时复查)→ `git diff` 收真实改动 → `PatchBundle{files, unified_diff, note=intent.summary, intent=EditPlan, report=逐条状态}` → candidate 提交(`Harness-Patch-Hash` trailer)→ push → eval。 - **拒绝处理**:评测 reject 沿用既有状态机结束该轮并清理候选,不自动开启下一轮,也不注入 `--resume` 反馈或 rejected-edit buffer(2026-11-23 决定:失败即拒绝,避免 round 生命周期改造);accept → 并入 run 分支。 - **安全闸**:agent 工具面 = 只读 + 写一个 json5 文件(`dontAsk` 模式,无文件编辑权限);`.harness-evolution/` 排除在 diff scope 外;应用器只在临时镜像上写入,越界/失败编辑不会触达仓库,因此无需 `git checkout -- .` 回滚;diff + intent + report 落 run events(diff 为候选 commit 的真实 git diff,超长时按事件载荷上限截断)。声明(intent)与实际(diff)的对照本身是审计信号。 - **patch source 接入**:新增第三种模式 `agent-edit` 注册进 `PATCH_SOURCE_MODES` 与工厂,沿用「run 冻结配置优先、env 兜底」的选择语义;`PatchSource` 增加 `build_bundle()`(默认实现包装旧 `build()` 为单文件 bundle,旧实现零改动)。 From 4210e6dad5771e8ea9ebccd549806577c9f3d0db Mon Sep 17 00:00:00 2001 From: TangZ-L <345187680+TangZ-L@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:38:04 +0800 Subject: [PATCH 4/7] =?UTF-8?q?docs(review):=20=E5=9B=9E=E5=A1=AB=20PR=20#?= =?UTF-8?q?607=20=E6=A3=80=E8=A7=86=E7=BB=93=E8=AE=BA=E4=B8=8E=E5=A4=84?= =?UTF-8?q?=E7=BD=AE=E8=AE=B0=E5=BD=95=20(#599)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plans/2026-11-25-pr607-review.md | 535 +++++++++++++++++++++++++++++++ 1 file changed, 535 insertions(+) create mode 100644 plans/2026-11-25-pr607-review.md diff --git a/plans/2026-11-25-pr607-review.md b/plans/2026-11-25-pr607-review.md new file mode 100644 index 00000000..3b7f4138 --- /dev/null +++ b/plans/2026-11-25-pr607-review.md @@ -0,0 +1,535 @@ +# PR #607 检视:`insert_after` 锚点契约统一为可跨行文本块(#599) + +## 元信息 + +| 项 | 值 | +|---|---| +| 检视对象 | GitHub PR **#607** `fix(api): 允许 insert_after 使用唯一的多行文本块锚点 (#599)`(Shadow-Azure/harness-evolution) | +| 分支 | `agent/develop-issue-599-edit-insert-anchor-multiline` → `main` | +| 提交 | 2 个:`884b39ef`(功能)、`023662e4`(flow 门禁修复)。检视时 HEAD = **`023662e4`** | +| 规模 | +514 / −52,**16 文件 = 新增 A 4 + 修改 M 12**(`gh pr view 607`,2026-11-25 15:13 抓取;15:24 作者追加第二个提交后重新抓取) | +| 检视时点 | 2026-11-25 15:13–15:45 CST(Asia/Shanghai) | +| owning Agent Note | [.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.md](../.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.md) | +| 实现计划 | [plans/superpowers/plans/2026-11-25-issue-599-edit-insert-anchor-multiline.md](superpowers/plans/2026-11-25-issue-599-edit-insert-anchor-multiline.md) | +| flow issue | [.agents/flow/issues/bugfix-edit-insert-anchor-multiline.md](../.agents/flow/issues/bugfix-edit-insert-anchor-multiline.md)(#599,`bugfix-57`) | +| 设计依据 | [07 §5.5.4](fullstack-design/07-backend-implementation.md)(`plans/fullstack-design/07-backend-implementation.md:831-852`) | +| 检视方式 | 通读 diff 与最终源码 + 复跑门禁 + **旧实现等价物 vs 新实现的字节级差分探针**(临时脚本放系统 TEMP,未入库) | + +> **检视过程中 HEAD 前移**:15:13 抓取时 HEAD=`884b39ef`(13 文件);15:24 作者追加 `023662e4`(flow 重复 id 修复,+3 文件)。两个提交之间 **`git diff 884b39ef..HEAD -- apps` 为空**,代码与测试逐字节相同,因此先在 `884b39ef` 跑出的测试结论对 `023662e4` 同样成立;`verify:flow` / `lint:docs` 在 `884b39ef` 红、在 `023662e4` 绿(见 §1 与讨论点 5)。下文行号以 `023662e4` 为准。 + +--- + +## §0 变更文件树与职责 + +``` +16 文件 = 新增 A 4 + 修改 M 12 + +契约与应用器(M 2) + apps/api/app/third_party_api/ai_agent/edits.py M +42 −26 EditOp 校验、_insert_after_text、_apply_one + apps/api/app/service/evolution/patch_source.py M +3 −1 _edit_prompt 的锚点文案 + +回归测试(M 2) + apps/api/tests/test_edit_plan_applier.py M +304 −8 删除单行拒绝用例;新增块锚/字节/CRLF/replay;symlink skipif + apps/api/tests/test_ai_agent_claude_code.py M +2 −0 2 个 POSIX 用例加平台跳过 + +设计与过程文档(M 2 + A 1) + plans/fullstack-design/07-backend-implementation.md M +2 −2 §5.5.4 json5 注释 + 执行流 bullet + plans/2026-11-22-pr510-review.md M +3 −3 历史检视文档的日期化追注 + plans/superpowers/plans/2026-11-25-issue-599-….md A +85 −0 实现计划(任务勾选表) + +Agent Note 三件套(A 3) + .agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.md A +27 + .agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.en.md A +27 + .agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.i18n.yaml A +5 + +flow 流程树(M 6,两组三件套) + .agents/flow/issues/bugfix-edit-insert-anchor-multiline.{md,en.md,i18n.yaml} M status ready→in-progress;adr 回填 + .agents/flow/issues/bugfix-explicit-skill-conclusion.{md,en.md,i18n.yaml} M id bugfix-56→58;status in-progress→done +``` + +按架构故事排序:契约层(`EditOp`)→ 应用层(`_insert_after_text` / `_apply_one`)→ 模型可见面(`_edit_prompt` / 07 设计)→ 证据(测试 / Note / flow)。 + +--- + +## §1 一页速览 + +**一句话**:把 `insert_after` 的锚点从「文件里包含这段文字的**那一行**」改成「文件里**唯一出现的一整段文字**,插在这段文字**末行**之后」,并让 prompt、设计文档、validator 说的是同一句话——起因是生产 run 因为一条**只活在 validator 里、没写进 prompt** 的「锚必须单行」规则整轮失败。 + +**一个比喻**:旧实现像「拿一句话当书签,夹在含这句话的那一页的页脚下面」;新实现像「拿整段引用当书签,贴在引用所指段落的末尾」。而这次事故的根因,是门口保安(validator)额外要求「书签只能是一个词」,说明书(prompt / 派生 schema / 设计文档)却只写了「书签要在书里独一无二」——模型交了合法书签,被保安当场撕票,而 edit 只有一次机会。 + +### 交付块表 + +| 交付块 | 做了什么 | 为什么 | 锚点 | +|---|---|---|---| +| 契约放宽 | 删掉 `insert_after` 对含 `\n`/`\r` target 的拒绝,只保留「target 非空」 | 让 validator 与 prompt/07 说同一件事;多行块是合法且唯一的锚 | `edits.py:157-176` | +| 应用器重写 | `text.index` 整段唯一匹配;按 target 结尾形态分 5 支决定插入点;插入行沿用锚行的 `\r\n`/`\n` | 「块末行之后」需要新的行边界定义;单行 target 必须与旧输出一致 | `edits.py:465-504` | +| 分支守卫 | 删掉 `_apply_one` 里同一份单行检查,保留 `text.count` 的 0 次/多义分支 | 同一规则不应写两遍;唯一性契约不变 | `edits.py:521-542` | +| 模型可见面 | prompt 写明「锚文本是文件内唯一出现的文本片段,可跨行;insert_after 插到该片段末行之后」 | 事故根因是「规则只在 validator」,必须写进模型看得到的地方 | `patch_source.py:537-547` | +| 设计文档 | 07 §5.5.4 的 json5 注释与执行流 bullet 同步同一契约 | 设计文档是契约的 home,避免第三次口径分叉 | `07-backend-implementation.md:842`、`:849` | +| 回归证据 | 4 行块校验+应用、单行字节矩阵、块锚缺失/多义、CRLF 块、生产形状 8 条编辑 replay | 覆盖 issue 验收项;replay 用合成副本,不引生产原文 | `test_edit_plan_applier.py:390-1056` | +| 流程与决策 | Agent Note 三件套 + flow issue `in-progress`/`adr` 回填 + (第二提交)修 main 上的重复 id | 决策留痕;解锁 `verify:flow` | `.agents/notes/implemented/bug-fix/2026-11-25-…`、`.agents/flow/issues/…` | + +### 验证基线(我自己复跑的结果) + +| 命令 | 结果 | 与 PR 描述对照 | +|---|---|---| +| `pnpm test:api -- tests/test_edit_plan_applier.py` | **86 passed, 4 skipped**(29.3s) | 一致(4 skipped = symlink,无 Developer Mode) | +| `pnpm test:api -- tests/test_ai_agent_claude_code.py` | **45 passed, 6 skipped**(28.3s) | 一致(2 POSIX + 4 真实 CLI opt-in) | +| `pnpm lint:api` | `530 files already formatted` / `All checks passed!` | 一致 | +| `pnpm verify:flow` @`884b39ef` | **FAIL**:`.agents\flow\issues\bugfix-explicit-skill-conclusion.md: id bugfix-56 重复` | ❌ 描述写 ok;原因是 main 既有(见讨论点 5) | +| `pnpm verify:flow` @`023662e4` | **ok** | 第二提交修复后成立 | +| `pnpm lint:docs` @`884b39ef` | **10/11**,`verify-flow` ✗(同因) | ❌ 描述写「全绿(11 叶)」 | +| `pnpm lint:docs` @`023662e4` | **doc-quick 全绿(11 叶)** | 成立 | +| `node scripts/verify-flow.mjs --diff origin/main`(带 `PR_TITLE`,模拟 CI) | **ok** | 额外实跑:CI 的 flow lane 会过 | +| `pnpm typecheck:api` | **13 errors**(`O_NOFOLLOW`/`SIGKILL`/`killpg` 等平台属性 + `probe_query.py` 既有 redundant-cast) | 一致;13 条均与本改动无关(其中 4 条落在本 PR 新跳过的两条 POSIX 用例内、1 条在同文件的 `_FakeProcess`,跳过不改变 mypy 结果) | +| 覆盖率探针 `pytest --cov=app.third_party_api.ai_agent.edits` | 行覆盖 **94%**;未覆盖 `481-487`(target 以 bare `\r` 结尾的分支)等 | 新增探针,见讨论点 3 | +| 字节级差分探针(旧实现等价物 vs 新实现) | 单行 target 且旧实现不报错的 **602** 组里,**154 组输出不同**:**120 组丢字符**(数据丢失)、14 组插入点偏移、20 组 `splitlines` 分隔符差异 | 新增探针,证伪「单行逐字节不变」,见讨论点 1/2 | + +--- + +## §2 架构导览 + +### 2.1 契约层:Pydantic 是唯一事实源,但只能表达「字段级」约束 + +`edits.py` 的 `EditOp` 用一个 `mode="after"` 的模型级校验器把「哪个 op 允许/禁止哪个字段」收在一处(`edits.py:157-176`)。这次改动只做减法:不再检查 target 里有没有换行。 + +```python +# 旧(main) +elif self.op in _ANCHORED_OPS: + target = _require_non_blank(self.target, field="target", op=self.op) + if self.op == "insert_after" and ("\n" in target or "\r" in target): + raise ValueError("target must be a single-line substring") +# 新(HEAD) +elif self.op in _ANCHORED_OPS: + _require_non_blank(self.target, field="target", op=self.op) +``` + +理解这段的关键是:**Pydantic 只校验「形状与字面量」,不校验「与文件内容的关系」**。「锚是否存在、是否唯一」永远是应用器的事(它要读文件),所以这次事故的本质不是「校验太严」,而是「一条**依赖文件内容**的规则被写成了**形态规则**,而且没写进 prompt」。 + +### 2.2 应用层:`_apply_one` 只做计数,`_insert_after_text` 只做定位 + +- `_apply_one`(`edits.py:507-542`):`text.count(target)` 为 0 → `skipped_anchor_missing`(`526`),>1 → 抛 `EditPlanError`「anchor is ambiguous」(`528-536`),==1 → 调 `_insert_after_text`(`542`)。删掉的是旧实现 `_apply_one` 里的同一段单行拒绝(diff 的 `-` 侧),计数与多义逻辑原样保留。 +- `_insert_after_text`(`edits.py:465-504`)是纯函数:输入文件全文 + 唯一出现的 target + content,输出新全文。它按 **target 的结尾形态**分支: + +| target 结尾 | 插入点 | 插入行换行 | 代码 | +|---|---|---|---| +| `\r\n` | 该 `\r\n` 之后 | `\r\n` | `478-479` | +| `\r` 且下一个字符是 `\n`(停在 CRLF 中间) | 补完这个 `\r\n` 之后 | `\r\n` | `480-484` | +| 其他 bare `\r` | 该 `\r` 之后 | `\n` | `485-487` | +| `\n` | 该 `\n` 之后 | `\n` | `488-489` | +| 无结尾换行 | 匹配末字符所在行的**下一个行终止符**之后;无终止符则 EOF 并补 `\n` | 该终止符风格(`\r\n`/`\n`) | `490-501` | + +### 2.3 让「绕过模型」依然安全的第二道门:`_coerce_edit` + +`apply_edit_plan` 对每一条编辑先调 `_coerce_edit`(`edits.py:650`),后者**不管传进来的是不是 `EditOp` 实例,都 `model_dump()` 后重新 `model_validate`**(`edits.py:300-320`)。这是讨论点里「删除 `_apply_one` 守卫后 `model_construct` 是否还安全」的答案:安全——空 target 会在这次重校验里被 `_require_non_blank` 拒掉,到不了 `_insert_after_text`。代价是 `_apply_one` 里 `target is required` / `content is required` 两处(`:518-519`、`:538-541`)变成纯防御分支。 + +### 2.4 模型可见面:prompt 与设计文档 + +- `_edit_prompt()`(`patch_source.py:511-548`)产出 edit 会话的唯一 goal prompt,`build_bundle()` 在 `patch_source.py:411-417` 调用它;锚点契约就在 `537-547` 的三行里,改动是第二行的一句: + ``` + 「锚文本必须存在且唯一。」→「锚文本必须是文件内唯一出现的文本片段,可跨行;insert_after 把 content 插到该片段末行之后。」 + ``` +- 07 §5.5.4 是这条契约的设计 home:json5 示例注释(`07:842`)与执行流 bullet(`07:849`)各改一处,且 bullet 里「insert_after 行边界」改成「insert_after 块末行之后」。 + +### 2.5 支撑性基础件(无改动,但决定字节保真) + +`_load_target` 用 `newline=""` 读(`edits.py:436-437`)、`_atomic_write` 用 `newline=""` 写(`:578`),`_apply_on_scratch`(`patch_source.py:458-473`)用 `shutil.copyfile` 镜像(`494`)+ `_read_text` 的 `newline=""`(`497-500`)——整条链路不做换行翻译,所以 `\r\n` 能一路保到 `PatchBundle`。**这是 PR 描述里「插入行沿用锚行风格」能成立的前提**,也被这次 `_write` 改成 `write_bytes` 的测试基建改动呼应(`test_edit_plan_applier.py:101-104`)。 + +--- + +## §3 数据流走查 + +剧本:生产 run 第 3/10 轮,计划第 7 条是 4 行块锚点的 `insert_after`。 + +1. **prompt 生成**(`patch_source.py:411-417`):`_edit_prompt()` 把「锚文本必须是文件内唯一出现的文本片段,可跨行;insert_after 把 content 插到该片段末行之后」交给 CLI。 +2. **agent 写提交文件**:`.harness-evolution/edits.json5`(json5,注释/尾逗号容错)。生产那次 `submissionParsedBy=json5`,说明这一步成功。 +3. **提交校验**(`claude_code.py` 侧 `submission.collect(prep, EditPlan.model_validate)`):`EditPlan.model_validate` → 每个 `EditOp._validate_op_fields`(`edits.py:157-176`)。**旧实现**在这里抛 `edits.6: target must be a single-line substring`,整轮失败;**新实现**放行。 +4. **镜像与逐条应用**(`patch_source.py:427` → `458-473`): + - `_mirror_plan_files` 用 `shutil.copyfile` 把 plan 涉及的每个文件复制到临时目录(`476-494`); + - `apply_edit_plan` 在 scratch 上跑(`edits.py:591-718`):每条先 `_coerce_edit` 重校验(`650`)→ `_load_target` 做 scope/符号链接/UTF-8 校验并 `newline=""` 读全文(`368-451`)→ `_apply_one` 计数(`507-542`)→ `_insert_after_text` 定位(`465-504`)→ 内容真变了才 `_atomic_write`(`664-665`)。 +5. **字节结果示例**(合成样例,与新增用例同形):文件 `l1\nl2\nl3\nl4\nl5\nl6\n`,target `l2\nl3\nl4\nl5\n`,content `NEW` → 输出 `l1\nl2\nl3\nl4\nl5\nNEW\nl6\n`(`test_edit_plan_applier.py:390-411`)。块末行的 `\n` 之后插入,不产生空行。 +6. **回到 bundle**:`_read_text`(`newline=""`)取回改动文件全文 → `_patch_from_content` 按 `\n` 切行(`503-508`)→ `PatchBundle{files, unified_diff, note=summary, intent=plan, report}`(`432-437`)。 +7. **下游**:candidate 提交 → push → eval;`report` 逐条 status 落 run events,`git diff` 是唯一真值。 + +**这次走查暴露的关键事实**:第 4 步 `_insert_after_text` 的「无结尾换行」分支(`edits.py:495-501`)在**文件末行没有换行符**时,会把 target 之后、末行结尾之前的内容**整段丢掉**(`prefix = f"{text[:match_end]}{ending}"`,`suffix` 置空)。走查见讨论点 1。 + +--- + +## §4 导读地图 + +| 层 | 文件 | 状态 | 说明 | +|---|---|---|---| +| 契约 | `apps/api/app/third_party_api/ai_agent/edits.py` | ✅ 通读 | 732 行;`EditOp`、`EditPlan`、`_coerce_edit`、`_load_target`、4 个 op 的纯函数、`apply_edit_plan` 全部读过 | +| 契约 | `apps/api/app/service/evolution/patch_source.py` | ◻ 部分 | 只通读变更区段 `380-548`(`build_bundle`、`_apply_on_scratch`、镜像、`_edit_prompt`);其余 250 行(analyze 侧)未读 | +| 测试 | `apps/api/tests/test_edit_plan_applier.py` | ✅ 通读 | 重点 90-130、380-430、615-760、795-1056 | +| 测试 | `apps/api/tests/test_ai_agent_claude_code.py` | ◻ 部分 | 只读 `1640-1770`(2 个 POSIX 用例与 `_FakeProcess`);其余未读 | +| 设计 | `plans/fullstack-design/07-backend-implementation.md` | ◻ 部分 | 只读 §5.5.4(`826-855`);§5.5.3 六层可靠性未逐行读 | +| 设计 | `plans/fullstack-design/…` 其余 | ◻ 未读 | 与本次契约无关 | +| 过程 | `.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.{md,en.md,i18n.yaml}` | ✅ 通读 | 双语对照读;i18n blob hash 已实测匹配 | +| 过程 | `.agents/flow/issues/bugfix-edit-insert-anchor-multiline.{md,en.md,i18n.yaml}` | ✅ 通读 | yaml 围栏中英逐字节一致(445 字符,实测) | +| 过程 | `.agents/flow/issues/bugfix-explicit-skill-conclusion.*` | ✅ 通读 | 第二提交的重编号;`bugfix-58` 全树唯一、无残留 `bugfix-56` 引用 | +| 过程 | `plans/2026-11-22-pr510-review.md` | ◻ 部分 | 只读三处改动(`90-93`、`304-314`、`400-404`)与上下文 | +| 计划 | `plans/superpowers/plans/2026-11-25-issue-599-edit-insert-anchor-multiline.md` | ✅ 通读 | 85 行 | + +--- + +## §5 人工验收清单 + +PR 描述没有 checkbox 形式的清单,以下是**从 PR 描述的验证声明 + issue #599 的「验收标准」**(`.agents/flow/issues/bugfix-edit-insert-anchor-multiline.md:160-167`)合并出的可勾选项,`[x]` 表示我在本次检视中实测通过。 + +- [x] 4 行唯一块锚点通过 `EditPlan.model_validate()`,应用后 content 出现在块末行之后 —— `test_insert_after_accepts_a_unique_multiline_block_anchor` 实测 86 passed +- [x] 生产形状的 8 条编辑(含 1 条 4 行块锚点、单条 content 28 行)全部 `applied`,只改 `skills/demo/SKILL.md` —— `test_production_shaped_plan_replays_with_every_edit_applied` 实测通过 +- [x] 块锚 0 次 → `skipped_anchor_missing`;2 次 → `error`(`anchor is ambiguous`),文件不被改动 —— 实测通过 +- [x] CRLF 文件中的块插入保持 `\r\n`;单行 CRLF 锚点同样保持 —— 实测通过 +- [x] 锚缺失、多义、scope 越界、content 超限、budget 超限仍按原规则拒绝/跳过 —— 既有用例全绿 +- [x] `replace` / `append` / `delete` 语义不变 —— 既有四 op 精确内容用例全绿 +- [ ] **单行 `insert_after` 输出与旧实现逐字节一致** —— ❌ **实测不成立**:末行无换行符时丢字符(讨论点 1);混合 bare `\r`/`\n` 文件插入点偏移(讨论点 2);含 `\v`/`\f`/`\x1c`/`\x85`/`\u2028` 等字符的文件分歧(讨论点 2) +- [x] prompt、07 §5.5.4、Agent Note 三处措辞一致(人工比对;**无测试守护**,见讨论点 3) +- [x] 仓库不含生产计划原文 / Session 内容 / 凭据;replay 用合成 demo skill —— 已核对测试文本 +- [x] `verify:flow`、`lint:docs` 在当前 HEAD 全绿(`023662e4` 实测);CI 的 `verify-flow --diff` 也 ok +- [ ] **一次真实 full run 能完成此前失败的第 3 轮** —— PR 描述「冒烟与证据」仍是占位(讨论点 4) + +--- + +## §6 讨论点 + +### 讨论点 1:末行没有换行符时,`insert_after` 会静默吞掉锚点之后的字符 + +**位置**:`apps/api/app/third_party_api/ai_agent/edits.py:495-501`(新 `_insert_after_text` 的「无行终止符」分支) + +**现象**:文件末行没有结尾换行、target 落在末行中间(不触到 EOF)时,插入结果会丢掉 target 之后到 EOF 的内容。公开入口实测(`apply_edit_plan`,报告都是 `applied`): + +| 文件 | target | content | 旧实现输出 | 新实现输出 | +|---|---|---|---|---| +| `one\ntwo` | `tw` | `x` | `one\ntwo\nx\n` | `one\ntw\nx\n`(丢了 `o`) | +| `{\n "version": "1.0"}` | `"version"` | `"build": 7` | `{\n "version": "1.0"}\n"build": 7\n` | `{\n "version"\n"build": 7\n`(丢了 `"1.0"}`) | +| `alpha\nbeta gamma` | `beta` | `NEW` | `alpha\nbeta gamma\nNEW\n` | `alpha\nbeta\nNEW\n`(丢了 ` gamma`) | +| `# title\n\nlast line` | `last` | `NEW` | `# title\n\nlast line\nNEW\n` | `# title\n\nlast\nNEW\n` | + +根因是一行 `prefix, suffix = f"{text[:match_end]}{ending}", ""`:既然 `match_end` 之后没有任何 `\r`/`\n`,那么「这一行的结尾」就等于 EOF,`prefix` 应当是 `text`(整段保留)而不是 `text[:match_end]`。旧实现用 `splitlines(keepends=True)` + 整行拼接,天然保留了尾巴,所以这是**本 PR 引入的行为回归**,而不是既有限制。 + +**问题**:这是静默数据丢失——`report` 是 `applied`、`git diff` 会把删掉的字符如实呈现,但 plan 与模型都不知道自己写坏了文件;如果被删的是 `SKILL.md` 结尾的半个句子或 JSON 的收尾括号,候选 patch 会变成语法错误文件,而失败会以「评测 reject」而不是「应用器 bug」的形式出现,归因成本很高。仓库里不带末尾换行的文件并不罕见(外部工具生成的 JSON、`.gitignore`、部分 fixture)。 + +**预判**:必修(bug,建议阻断合并)。修法很小:该分支改成 `prefix, suffix = f"{text}{ending}", ""`;同时补一条「末行无换行 + target 在行中/行首」的用例(这正是现有单行字节矩阵漏掉的那一格)。顺带把 docstring `edits.py:468-472`「否则插入点是匹配末字符所在行的结尾」与实现对不齐的地方一起对齐。 + +**结论**:已决 2026-11-25:成立且已修复(`01d3bd8c`)。该分支改为整段保留 `prefix=f"{text}{ending}"`,并新增「末行无换行 + target 在行中/行首」的字节回归(`test_insert_after_single_line_targets_reproduce_exact_bytes` 扩到 9 格)。 + +### 讨论点 2:多行 target 可以绕过「唯一」契约,而且单行等价只在 LF/CRLF/纯 CR 文件成立 + +**位置**:`apps/api/app/third_party_api/ai_agent/edits.py:522`(`text.count(target)`)、`Agent Note:19`(「多行 target 不绕过它」)、`edits.py:490-501`(`find("\n")` 定位) + +**现象**: + +1. **自重叠多行块漏判多义**:`text.count` 数的是**不重叠**出现次数。文件 `L\nL\nL\n`、target `L\nL` 实际出现 2 次(下标 0 与 2),`count` 得 1,于是按「唯一」放行、插在第一个块之后;`ab\nab\nab` 同理。单行 target 时代这个洞就存在(文件 `aaa` + target `aa`:`count` 得 1,实际重叠出现 2 次),但那时多行 target 在 validator 就被拒,所以**多行契约把这条洞从「不可达」变成「可达」,而 Note 明确写了「多行 target 不绕过它」**。结果仍然确定(总是第一个),但「唯一」这个审计承诺不再成立。 +2. **单行等价的前提被夸大**:用旧实现等价物对 602 组「旧实现不报错」的单行 target 做差分,**154 组输出不同**: + - **120 组**是讨论点 1 的丢字符; + - **14 组**来自混合 bare `\r` 与 `\n` 的文件:`a\rb\n` + target `a`,旧实现插在 `a\r` 之后(`a\rx\nb\n`),新实现一路找到后面的 `\n`、插到 `b\n` 之后(`a\rb\nx\n`);`a\rb\r\nc\n` 同理; + - **20 组**来自 `str.splitlines()` 与 `find("\n")` 的分隔符集合不同:`str.splitlines()` 还切 `\v`、`\f`、`\x1c`–`\x1e`、`\x85`、`\u2028`、`\u2029`,`a\vb\n` + target `a` 在旧实现里 `a\v` 自成一「行」、新实现把它和 `b` 当同一行。仓库 `11-bad-case-session-sync.md:92` 恰好记过同类坑(「按 `\n` 分帧而不是 `splitlines`」),说明这是团队已知的语义分界。 + +**问题**:契约文字(prompt / 07 / Note)说的是「唯一出现的文本片段」,实现说的是「不重叠出现次数为 1」;两者在多行自重叠块上不等价。另外「单行输出逐字节不变」被写进了 Note 与实现计划,作为回归安全网的核心承诺,而它只在「文件只用 LF、CRLF 或纯 CR 一种换行风格」时成立。 + +**预判**:唯一性问题建议定为**正确性**(中低):修法是把计数改成逐位推进的 `find` 循环(`count` 换成 `while (i := text.find(target, i)) != -1: i += 1`),或在 Note/07 里把「唯一」显式降级为「不重叠唯一」并说明理由——二选一,不要文字说一套代码做一套。混合换行与 `splitlines` 分隔符差异建议如实标注为已知边界(低,无实害:仓库内文本文件基本是 LF/CRLF),但 Note 与实现计划里的「逐字节一致」必须加上限定语。 + +**结论**:已决 2026-11-25:按 issue 契约保留 `text.count` 的不重叠计数,并在 Agent Note 与 07 §5.5.4 显式标注「不重叠唯一」;「逐字节一致」限定为 `\n` / `\r\n` / 纯 bare `\r` 文件,混合换行与 `splitlines` 的 Unicode 分隔符记为已知边界(无实害,不另开 issue)。 + +### 讨论点 3:新增测试的矩阵漏掉了最危险的那一格,prompt 文案零测试 + +**位置**:`apps/api/tests/test_edit_plan_applier.py:798-839`(单行字节矩阵)、`edits.py:480-487`(bare `\r` target 分支)、`patch_source.py:537-547`(prompt) + +**现象**: + +1. 单行矩阵的 5 个样例是:行中匹配(`beta`)、行尾匹配(`two`)、**EOF 且 target 正好到文件尾**(`one\ntwo` + `two`)、纯 CR 文件(`a\rb\rc\r`)、CRLF。**没有**「末行无换行且 target 不到 EOF」这一格——也就是讨论点 1 的 bug 恰好落在覆盖空档里;测试 docstring 却写着「keep producing the historical byte-for-byte output」(`:820`),给出的是比实际更强的保证。 +2. 覆盖率实测:`edits.py` 行覆盖 94%,未覆盖行里包含 **`481-487`**——整个「target 以 bare `\r` 结尾」分支(含「停在 CRLF 中间要补完」的注释块)没有任何用例;`test_edit_plan_applier.py` 里所有 target 要么以 `\n` 结尾、要么以普通字符结尾。这个分支恰恰是新增代码里最容易算错偏移量的地方。 +3. `_edit_prompt()` 在 `apps/api/tests/` 下**没有任何测试**(`git grep -n "锚文本\|修复要求\|_edit_prompt" -- apps/api/tests` 为空)。而这次事故的根因就是「prompt 没写、validator 却执行」,也就是说:**本 PR 最重要的一处修复(把契约写进模型可见面)没有任何回归守护**,将来改 prompt 时把这句话删掉,测试全绿。 +4. `test_replace_still_accepts_a_multiline_anchor_at_model_construction`(`:414-423`)只构造一个 `EditOp` 并断言 `target` 字段,没有断言任何行为变化——它守护的是「replace 一直允许的事」,价值接近 0。 + +**问题**:测试在「形状覆盖」上很足(4 行块、CRLF、缺失/多义、replay),但在「边界与契约文本」上留了口子;而口子正好开在本 PR 唯一会写坏文件的分支上。这不是过度拟合实现细节的问题(replay 用例用的是合成 demo skill,没有引生产原文,这点做得对),而是**边界取样不足**。 + +**预判**:建议补三条:(a) 末行无换行 + target 在行中/行首的字节断言;(b) bare `\r` target(含 CRLF 中间截断)的插入点断言;(c) 一条 prompt 断言(例如 `assert "可跨行" in _edit_prompt(...)`),把「契约必须出现在 prompt 里」变成可红的门禁。另建议删掉或加强第 4 条弱用例。 + +**结论**:已决 2026-11-25:已补 (a) 末行行中 target、(b) bare `\r` target 与 CRLF 半终止、(c) `_edit_prompt` 契约断言;`replace` 弱用例改为实际应用断言(`01d3bd8c`)。 + +### 讨论点 4:「冒烟与证据」是占位,issue 的第 5 条验收没有证据;PR 描述也停在第一个提交 + +**位置**:PR 描述「## 冒烟与证据」节;`.agents/flow/issues/bugfix-edit-insert-anchor-multiline.md:160-167`(验收标准第 5 条「一次真实 full run 能完成此前失败的第 3 轮」) + +**现象**:PR 描述的最后一节只写「集成冒烟与截图对比将在 PR 描述中补充(截图不入库)」;本次检视没有任何可复跑的冒烟脚本、命令或 run 链接。同时 PR 描述仍是 13 文件 / 1 提交时代的文本(现为 16 文件 / 2 提交),「改动」清单里也没有第二提交(`bugfix-explicit-skill-conclusion` 重编号 + #588 置 done)和 `_write`/symlink skipif 这些测试基建改动。 + +**问题**:issue 的验收标准明确要求「一次真实 full run 能完成此前失败的第 3 轮」,且 PR 描述自称会补——这是本 PR 唯一无法靠单测替代的验收项(生产 run 的 `agent.edit` 是否 `outcome=ok`、`submissionValidationFailures=0`、是否进入 candidate/push/eval)。在证据补齐之前,issue 不能置 `done`,`status: in-progress` 是正确状态。 + +**预判**:合并前补齐即可(流程项,中):(a) 贴一次新 full run 的关键事件(step/round、`agent.edit outcome`、`submissionValidationFailures`、是否进入 eval),不留截图也可,字段即可;(b) 更新 PR 描述的「改动」与「验证」两节到 2 提交 / 16 文件。若短期无法跑生产 run,至少给一条本地端到端命令(用 fake provider 走 `agent.edit` 全链路)作为可复跑替代,并在描述里说明证据层级。 + +**结论**:已决 2026-11-25:PR 描述补齐本地端到端冒烟(真实 `ClaudeCodeProvider` 提交通道 + fake CLI + 真实 `apply_edit_plan`)、截图与可复跑脚本说明;「真实 full run」属部署后验收,issue 在部署验证前保持 `in-progress`。 + +### 讨论点 5:第二个提交把「main 流程门禁修复」塞进了本 PR,且改的是另一个 issue 的身份 + +**位置**:提交 `023662e4`;`.agents/flow/issues/bugfix-explicit-skill-conclusion.md:7`(`id: bugfix-56 → bugfix-58`)、`:12`(`status: in-progress → done`) + +**现象**:我在 15:13 复跑 `pnpm verify:flow` 时它是 **FAIL**:`bugfix-explicit-skill-conclusion` 与 `bugfix-bad-case-sync-type-title` 同用 `id: bugfix-56`,两者都在 `origin/main` 上,与本 PR 的 13 个文件无关(`git grep -l "^id: bugfix-56$" origin/main` 可复现)。15:24 作者追加 `023662e4`:把 #588 那份 issue 改成 `bugfix-58` 并置 `done`,随后 `verify:flow` / `lint:docs` / `verify-flow --diff` 全绿。我核过:`bugfix-58` 全树唯一、无其它地方引用 `bugfix-56`、`.i18n.yaml` 的两个 blob hash 与实际文件一致、`gh issue view 588` 确为 `CLOSED`(置 `done` 自洽)、#599 issue 的 scope 含 `.agents/**`(不越界)。 + +**问题**:两件事:(a) 这是一次**跨 issue 的身份变更**(别人的 id 与状态),却挂在 #599 的 bugfix PR 里,PR 标题、描述都不体现;(b) main 本身是红的,意味着在它修好之前**所有 PR 的 flow 门禁都红**,这类「解除 main 门禁」的改动更适合独立 chore PR,或至少在 PR 描述里单列一节说明。另一方面也要承认:不并进来,本 PR 的 CI 就是红的,作者的选择是务实的。 + +**预判**:功能上没问题(已实测三道 flow 门禁全绿),属于**流程取舍**(低—中):建议保留代码,但在 PR 描述里加一节「顺带修复 main 重复 id(#588, bugfix-56→58, done)」并说明为何不另开 PR;若维护者坚持单一职责,可拆成独立 PR 先行合并,本 PR rebase 后再跑门禁。 + +**结论**:已决 2026-11-25:保留实现,PR 描述单列「顺带修复 main 重复 id」一节说明动机与范围(`023662e4`)。 + +### 讨论点 6:回头修订 2026-11-22 的检视文档,是否越过了「检视语料」的边界 + +**位置**:`plans/2026-11-22-pr510-review.md:93`(§3 探针汇总追加一句)、`:314`(讨论点 7 结论追加「2026-11-25 更新」)、`:403`(§9 检视发现 #2 追加同义注) + +**现象**:三处都是「保留原文 + 追加日期化说明」,措辞明确(「其中……已再被 #599(2026-11-25)废除」「2026-11-25 更新:该决定已由 #599 反转」),并且正确记录了「上述回归用例已随之删除」。flow issue 的 scope 含 `plans/**`,门禁与词数预算也都过。风险点只有一个:`:93` 改的是 §3「探针记录」的汇总句,而那一节自称是「检视时(`758f5149`)的行为」快照——在快照里插一句后加的结论,会让「当时观测到什么」与「后来变成什么」混在同一段。 + +**问题**:检视文档是**过程记录**(SKILL 明确说它不进 Agent Note 的封闭决策系统),其价值在于「当时的事实可追溯」。就地改写历史记录(哪怕加了日期)会削弱这个属性;而「某决定被后来的 issue 反转」这件事,Note 与 flow issue 已经是更合适的 home。 + +**预判**:可接受的边界做法(低)。建议的规范是:历史检视文档只允许在**结论栏**追加带日期的状态变更(`:314` 这种),§3 的探针快照与 §9 的发现正文保持冻结,反转写进 owning Note 或新检视文档的「关联」节。若维护者认可现状,至少把这条规则写进 `docs/review.md`,避免下次各自发挥。 + +**结论**:已决 2026-11-25:接受现状,不再改动 2026-11-22 检视文档;「历史检视只追加结论栏」的规则建议留给维护者在 `docs/review.md` 决定。 + +### 讨论点 7:三处契约文字已经一致,但 07 §5.5.4 仍留着「多义回喂」这句与实现不符的话 + +**位置**:`plans/fullstack-design/07-backend-implementation.md:849`(「多义回喂要求补上下文」);对照 `Agent Note:26`(「edit 是单次调用、校验失败不重试」) + +**现象**:prompt(`patch_source.py:540-542`)、07(`:842`、`:849`)、Note(`:13`)对锚点契约的表述已经同口径(唯一、可跨行、块末行之后),这是本 PR 做得最干净的一处。但 07 同一句里还写着「多义回喂要求补上下文」——edit 路径根本没有回喂(`claude_code.py` 单次 `collect`,失败即 `retryable=False`),这次事故报告里也专门点了这一点。这句是既有文字,本 PR 只改了相邻的「行边界→块末行之后」,没有顺手纠正。 + +**问题**:设计文档是契约 home。「validator 执行什么」已经对齐了,「失败之后会发生什么」仍写着不存在的重试,下一个读文档的人(或模型)会误以为「多义会被回喂修正」。这与本 PR 想消除的「文档与实际不一致」是同一类问题,只是方向相反。 + +**预判**:低,但建议在本 PR 顺手改(一行):把「多义回喂要求补上下文」改成「多义即 `error`(edit 无回喂重试)」或类似表述;若担心扩大面,就在 Note 的「Consequences」里显式记这条文档欠账,别让它继续漂。 + +**结论**:已决 2026-11-25:已修复(`01d3bd8c`):07 §5.5.4 改为「多义按 `ambiguous` 拒绝(edit 单次调用,不回喂)」。 + +### 讨论点 8:`insert_after` 的「块末行」定义在 target 停在 CRLF 中间时的取舍 + +**位置**:`apps/api/app/third_party_api/ai_agent/edits.py:480-487` + +**现象**:target 以 bare `\r` 结尾、而文件里紧跟 `\n` 时,实现选择「补完这个 `\r\n` 再插」,实测 `a\r\nb\r\n` + target `a\r` → `a\r\nNEW\r\nb\r\n`;target 是 bare `\r` 且后面不是 `\n` 时,插入行用 `\n`(保留旧实现行为)。两种都合理,但这条分支**零测试覆盖**(见讨论点 3),且 docstring 只写「插入行沿用锚行 `\r\n` / `\n` 风格」,没写「bare `\r` 锚行的插入行是 `\n`」这一特例(Note 里写了)。 + +**问题**:语义本身没有对错,问题是「没有测试 + 文档少一句」,一旦未来有人把 `\r` 分支的 `ending` 从 `\n` 改成 `\r`,行为会变而测试不会红。 + +**预判**:低(无实害,纯健壮性)。建议补一条 bare `\r` target 用例(顺带把 `481-487` 覆盖上),并把 docstring 补成 Note 里的三句式(`\r\n` 保持、`\n` 保持、bare `\r` 的插入行用 `\n`)。 + +**结论**:已决 2026-11-25:已修复(`01d3bd8c`):补两格 bare `\r` target 用例覆盖该分支,docstring 写明 bare `\r` 锚行的插入行用 `\n`。 + +--- + +## §7 分流表 + +| # | 发现 | 定性 | 去处 | 状态 | +|---|---|---|---|---| +| 1 | 末行无换行时 `_insert_after_text` 丢字符(`edits.py:495-501`,公开入口可复现,`applied` 静默) | **bug(高)** | 修复 PR(本 PR 内改一行 + 补用例),合入后按需 postmortem 记录「为何单测没兜住」 | ✅ 2026-11-25 已修复(`01d3bd8c`) | +| 2 | `text.count` 对自重叠多行 target 漏判「多义」(`edits.py:522`),与 Note「多行不绕过唯一性」冲突 | 正确性(中低) | 修复 PR(改计数)或 Note/07 明确「不重叠唯一」并说明 | ✅ 2026-11-25 已处理:保留 `text.count`,Note/07 标注不重叠 | +| 3 | 「单行逐字节一致」只在 LF/CRLF/纯 CR 成立;混合换行 14 组、`splitlines` 分隔符 20 组分歧(`edits.py:490-501`) | 正确性/文档(低) | 文档:Note:24 与实现计划:18 加限定语;如需兼容,另开 issue 讨论 `splitlines` 语义 | ✅ 2026-11-25 已处理:Note 限定逐字节承诺边界 | +| 4 | 单行字节矩阵缺「末行无换行 + target 不到 EOF」;`481-487` 零覆盖;`_edit_prompt` 零测试;`replace` 守卫用例空心(`test_edit_plan_applier.py:414-423`、`:798-839`) | 测试缺口(中) | 本 PR 补测试(至少 bug 修复的回归 + prompt 断言) | ✅ 2026-11-25 已修复:补边界/分支/prompt 测试 | +| 5 | 「冒烟与证据」占位,issue 验收第 5 条(真实 full run)无证据;PR 描述未更新到 2 提交 / 16 文件 | process(中) | PR 描述与 issue 状态;证据补进 PR,不写进仓库 | ✅ 2026-11-25 已处理:PR 描述补冒烟证据;真实 run 留部署后 | +| 6 | 第二提交把 #588 的 id/status 修复并入本 PR(`bugfix-56→58`、`done`) | process(低—中) | 保留实现 + PR 描述单列说明;或拆独立 chore PR | ✅ 2026-11-25 已处理:PR 描述单列说明 | +| 7 | 就地修订 2026-11-22 检视文档的探针快照(`plans/2026-11-22-pr510-review.md:93`) | process/语料(低) | `docs/review.md` 补「历史检视只可追加结论栏」规则;本次可接受 | ✅ 2026-11-25 已决:接受现状;规则建议另议 | +| 8 | 07 §5.5.4「多义回喂要求补上下文」与实际无重试不符(`07:849`) | 文档(低) | 本 PR 顺手改一行,或在 Note 记欠账 | ✅ 2026-11-25 已修复:07 改为 ambiguous 拒绝 | +| 9 | bare `\r` target 分支无测试、docstring 少一句特例(`edits.py:480-487`、`:466-473`) | 测试/文档(低) | 随 #4 一起补 | ✅ 2026-11-25 已修复:补 bare-`\r` 用例与 docstring | +| 10 | 删除 `_apply_one` 单行守卫后,`model_construct` 绕过路径**仍安全**(`_coerce_edit` 重校验,`edits.py:300-320`、`:650`) | 无实害(结论) | 无需动作;写入本检视 §2.3 留档 | ✅ 已核实 | +| 11 | 2 个 POSIX skipif(`test_ai_agent_claude_code.py:1651`、`:1689`)合理,不削弱 Linux CI(`os.name == "posix"` 时照跑) | 无实害(结论) | 无需动作;Windows 本机失去 2 条进程组用例覆盖,属平台限制 | ✅ 已核实 | +| 12 | `pnpm typecheck:api` 13 条 Windows 平台误报(`O_NOFOLLOW`/`SIGKILL`/`killpg`/既有 redundant-cast),与本改动无关 | 无实害(结论) | 既有欠账,不在本 PR 处理 | ✅ 已核实 | +| 13 | 测试基建改动(`_write` 改 `write_bytes`、`_NO_SYMLINK` 探针、重录 i18n)方向正确,但未写进 PR 描述 | 文档/process(低) | 随 #5 一起补描述 | ✅ 2026-11-25 已处理:PR 描述补测试基建说明 | + +--- + +## §8 链接 + +- PR:#607 — https://github.com/Shadow-Azure/harness-evolution/pull/607 +- issue:#599 — https://github.com/Shadow-Azure/harness-evolution/issues/599 +- owning Agent Note:[2026-11-25-edit-insert-anchor-multiline.md](../.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.md)(双语 + i18n) +- 实现计划:[2026-11-25-issue-599-edit-insert-anchor-multiline.md](superpowers/plans/2026-11-25-issue-599-edit-insert-anchor-multiline.md) +- 设计依据:[07 §5.5.4](fullstack-design/07-backend-implementation.md)(`plans/fullstack-design/07-backend-implementation.md:831-852`) +- 前序检视:[2026-11-22-pr510-review.md](2026-11-22-pr510-review.md)(讨论点 7 记录了单行规则的引入与本次反转) +- 相邻事故/契约:[#494](https://github.com/Shadow-Azure/harness-evolution/issues/494)(单行规则来源)、[#566](https://github.com/Shadow-Azure/harness-evolution/issues/566)(edit 工具面修复)、[#588](https://github.com/Shadow-Azure/harness-evolution/issues/588)(第二提交重编号的 issue) +- 后续建议 PR(未创建):修复讨论点 1 + 补 §7 #4/#9 的测试;07 措辞(讨论点 7) + +--- + +## §9 文件级代码分析 + +### 9.1 `apps/api/app/third_party_api/ai_agent/edits.py`(M,+42 −26) + +**职责**:EditPlan 的 Pydantic 契约(`EditOp` / `EditPlan`)+ 四个 op 的纯文本应用器 + 逐条 report。**变更形态**:M,改了三处函数体 + 两段 docstring,无新增依赖。 + +**关键依赖**:Pydantic v2(第三方、运行时、无版本变动)——它像报关单:字段形状、必填、互斥都在这张单子上核;`model_construct()` 可以伪造单子,所以 `_coerce_edit`(`300-320`)在应用前**再核一遍**。另一个隐性依赖是 Python 的 `str.splitlines()`:它按「通用换行集合」切分(含 `\v`/`\f`/`\x1c`–`\x1e`/`\x85`/`\u2028`/`\u2029`),旧实现用它、新实现用 `find("\n")`/`find("\r")`——这正是讨论点 2 中 20 组分歧的来源,属于「同一段代码换了一个 stdlib 语义」的典型陷阱。 + +**变更代码块 1:validator 删掉单行拒绝**(`edits.py:157-176`) + +```python +# 旧 +target = _require_non_blank(self.target, field="target", op=self.op) +if self.op == "insert_after" and ("\n" in target or "\r" in target): + raise ValueError("target must be a single-line substring") +# 新 +_require_non_blank(self.target, field="target", op=self.op) +``` + +这在做什么:把「锚不能跨行」从模型层移除;`append` 禁 target、`delete` 禁 content、content 非空等约束全部保留。为什么这么写:这条规则与 prompt/07 冲突,且模型无法从派生 schema 里看到它——留在这里只会继续制造「合法计划被拒」。**实现思路**:契约只保留「形状」类约束;「与文件内容的唯一性」交给应用器,这是本仓库一贯的分工(`_ANCHORED_OPS` 的 docstring 也是这么写的,`edits.py:68-69`)。 + +**变更代码块 2:`_insert_after_text` 重写**(`edits.py:465-504`) + +```python +# 旧(整行定位) +lines = text.splitlines(keepends=True) +anchor_index = next((i for i, line in enumerate(lines) if target in line), None) +anchor = lines[anchor_index] +ending = "\r\n" if anchor.endswith("\r\n") else "\n" +if not anchor.endswith(("\n", "\r")): + lines[anchor_index] = f"{anchor}{ending}" +lines.insert(anchor_index + 1, "".join(f"{line}{ending}" for line in inserted)) +return "".join(lines) + +# 新(整段定位;节选无换行结尾分支) +match_end = text.index(target) + len(target) +... +newline = text.find("\n", match_end) +if newline != -1: + ending = "\r\n" if newline > 0 and text[newline - 1] == "\r" else "\n" + prefix, suffix = text[: newline + 1], text[newline + 1 :] +else: + carriage = text.find("\r", match_end) + if carriage != -1: + ending, prefix, suffix = "\n", text[: carriage + 1], text[carriage + 1 :] + else: + ending = "\n" + prefix, suffix = f"{text[:match_end]}{ending}", "" # ← 讨论点 1 +``` + +这在做什么:先按整段找到唯一匹配的末尾(`match_end`),再根据 target 自己是否带换行决定插入点;不带换行时,向后找「这一行的终止符」,插在终止符之后。为什么这么写:旧实现「第一个包含 target 的行」在多行 target 下无法定义;用 `index` + 五个结尾分支能把「块末行之后」写成显式规则,也顺手兼容了 CRLF。**实现思路**:把「插入点」抽象成 `(prefix, suffix, ending)` 三元组,最后一段 `f"{prefix}{body}{suffix}"` 统一拼装——比旧实现「改列表元素再 insert」更容易验证字节不变。 + +这是本文件里唯一有实质风险的重写,风险点就是讨论点 1 的 `text[:match_end]`、讨论点 2 的换行语义、以及 `481-487` 的零覆盖。 + +**变更代码块 3:`_apply_one` 删守卫**(`edits.py:521-542`) + +```python +# 旧:先 `if "\n" in target or "\r" in target: raise EditPlanError(...single-line...)`,再 count +# 新:直接 count → 0 次 skipped / >1 次 ambiguous / ==1 次调 _insert_after_text +``` + +这在做什么:去掉与模型层重复的检查,保留唯一性分支。为什么安全:`_coerce_edit` 已经重校验(§2.3),所以 bypass 路径的 target 不可能是 None/空白;`:518-519`、`:538-541` 变成防御性代码。 + +**检视发现**: +1. **(高)末行无换行时丢字符**(`:495-501`)——见讨论点 1,公开入口实测 `applied` 且静默改坏文件,旧实现无此问题。 +2. **(中低)唯一性靠不重叠 `count`**(`:522`)——见讨论点 2。 +3. **(中)新增分支 `481-487` 零测试覆盖**、单行字节矩阵缺最关键一格——见讨论点 3/9。 +4. **(低)docstring 与实现不符**:`:468-472` 说「插入点是匹配末字符所在行的结尾」,实际在无终止符时截断;也没写 bare `\r` 锚行的插入行用 `\n`(Note:13 写了)——见讨论点 8。 +5. 无新增依赖,无需过 dep-allowlist;`text.count` 语义、`index` 与 count 的一致性(count==1 时 `index` 命中同一处)成立。 + +### 9.2 `apps/api/app/service/evolution/patch_source.py`(M,+3 −1) + +**职责**:`agent-edit` patch source——组装 edit prompt、调 provider、在临时镜像上应用 plan、产出 `PatchBundle`。**变更形态**:M,只改 `_edit_prompt()` 的一句文案(`537-547`),调用链、镜像、bundle 都没动。 + +**关键依赖**:CLI provider(`edit_workspace`,`patch_source.py:411-417`)与 `apply_edit_plan`;本文件在中间只做「prompt 组装 + 镜像 + 取回文本」,不新增依赖。 + +**变更代码块**: + +```python +# 旧 +f"- file 必须落在允许范围 {list(allowed)!r} 内;锚文本必须存在且唯一。", +# 新 +f"- file 必须落在允许范围 {list(allowed)!r} 内;" +"锚文本必须是文件内唯一出现的文本片段,可跨行;" +"insert_after 把 content 插到该片段末行之后。", +``` + +这在做什么:把「可跨行」「插到末行之后」两条模型看不见的语义写进正向契约。为什么这么写:事故根因是 validator 比 prompt 严;把规则写进 prompt 是唯一能让模型在下一次调用里做对的办法(edit 不重试,`Agent Note:26`)。**实现思路**:不新增 prompt 段落,只在既有锚点行内补全,避免 prompt 预算膨胀。 + +**检视发现**:文案与 07 §5.5.4、Note 三处一致(人工比对);但**没有测试断言 prompt 文案**(讨论点 3),且「唯一出现」与实现的「不重叠唯一」有语义差(讨论点 2)。另:07 里「多义回喂」的旧话仍与「edit 无重试」冲突(讨论点 7,位于 07 而非本文件)。 + +### 9.3 `apps/api/tests/test_edit_plan_applier.py`(M,+304 −8) + +**职责**:应用器契约的全部单测。**变更形态**:M——删 1 个测试函数(单行拒绝,2 组参数)+ `_apply_one` 参数化 1 行、改 3 处基建(`_write`、symlink 探针、3 个 `skipif` 标记)、加 8 条新用例(其中单行字节矩阵 1 条含 5 组参数)。 + +- 基建 1:`_write` 从 `write_text` 改为 `write_bytes`(`101-104`)。这在做什么:绕开 Windows 的 `\n`→`\r\n` 翻译,让字节断言在任何平台都成立。为什么必要:本 PR 开始用 `read_bytes()` 断言精确换行,旧写法在 Windows 上会让「期望 LF」的用例永远红。**这是正确的修复**,但属于跨用例的行为改动(全文件 40+ 处 `_write` 受影响),PR 描述没提。 +- 基建 2:`_symlinks_supported()` 探针 + `_NO_SYMLINK`(`107-117`),给 3 个 symlink 用例加 `skipif`(`623`、`645`、`672`)。为什么合理:Windows 非 Developer Mode 建不了符号链接;用探针而不是 `os.name == "nt"`,让开了 Developer Mode 的 Windows 也能跑。Linux CI 不受影响。 +- 删除:`test_insert_after_rejects_a_multiline_anchor_at_model_construction`(旧文件 `377-383`)及 `_apply_one` 参数化里的 `("insert_after", "line\nbreak", "x", "single-line")` 一行(`test_edit_plan_applier.py:730-760` 区域)。删除是正确的——它守护的规则已被 #599 废除。 +- 新增: + - `:390-411` 4 行块锚点校验+应用(`l2\nl3\nl4\nl5\n` → 插在 `l5` 行之后),并额外做了一次 `EditPlan.model_validate(plan.model_dump())` 往返; + - `:414-423` `replace` 仍接受多行锚(只断言构造,价值低,见讨论点 3); + - `:798-839` 单行字节矩阵(行中/行尾/EOF-到文件尾/纯 CR/CRLF); + - `:842-856` 块锚无结尾换行(target `l1\nl2` 在 `l3` 前插入); + - `:859-879` 块锚自带结尾换行不产生空行; + - `:882-920` 块锚 0 次/2 次; + - `:923-946` CRLF 块插入; + - `:948-1056` 生产形状 8 条编辑 replay(合成 demo skill、28 行 content、四种 op 混用、逐条 `applied`、只改一个文件、用子串断言核对插入位置)。 + +**检视发现**:覆盖「形状」与「端到端」很到位,replay 用合成数据、未引生产原文(符合 issue 边界);缺「末行无换行 + target 不到 EOF」这一格(讨论点 1 的 bug 正好落在空档)、bare `\r` target 分支零覆盖(`481-487`)、`replace` 守卫用例空心。矩阵里的期望串是**正确的旧行为**,所以它们全过——问题不在断言写错,而在取样没取到会挂的那一格。 + +### 9.4 `apps/api/tests/test_ai_agent_claude_code.py`(M,+2 −0) + +**职责**:CLI provider 的单测。**变更形态**:M,只加两行 `@pytest.mark.skipif(os.name != "posix", reason="process-group signals are POSIX-only")`(`1651`、`1689`)。 + +**变更分析**:两条用例用 `os.getpgid`/`os.killpg` 与 `signal.SIGKILL`,Windows 没有进程组语义,`AsyncioClaudeCliRunner` 的 POSIX 分支在 Windows 上本就不可执行。加跳过是**如实标注平台能力**,不是掩盖失败:`os.name == "posix"`(Linux/macOS CI)照跑,`45 passed, 6 skipped` 里 6 = 2 POSIX + 4 真实 CLI opt-in。**唯一的代价**是 Windows 本机失去这两条覆盖,属平台限制。注意:跳过不影响 `pnpm typecheck:api`——mypy 仍会检查这两条用例及相关 `_FakeProcess` 里的 `signal.SIGKILL`,该文件在 Windows 上仍有 5 条 SIGKILL 报错(PR 描述已如实说明,且与本次改动无关)。 + +**检视发现**:合理,无实害。位置与 reason 文案准确。 + +### 9.5 `plans/fullstack-design/07-backend-implementation.md`(M,+2 −2) + +**职责**:后端实现设计,§5.5.4 是 EditPlan 契约与执行流的设计 home。**变更形态**:M,两行。 + +- `:842` json5 示例注释:「锚文本:文件内必须存在且唯一」→「……且唯一,可以是跨行文本块」; +- `:849` 执行流 bullet:「insert_after 行边界」→「insert_after 块末行之后」,并在锚规则处加「可以是单行或多行文本块」。 + +**变更分析**:设计文档与实现对齐,是这次「三处一致」的第三处。措辞与 prompt 略有差异(07 用「可以是单行或多行文本块」,prompt 用「唯一出现的文本片段,可跨行」),但语义相同,不算分叉。**检视发现**:同一句里「多义回喂要求补上下文」与 edit 无重试冲突(讨论点 7,低);`plans/` 不参与双语/预算门禁,无额外义务。 + +### 9.6 `plans/2026-11-22-pr510-review.md`(M,+3 −3) + +**职责**:前一次 PR #510 的结构化检视(历史过程记录)。**变更形态**:M,三处**追加式**追注。 + +- `:93` §3 探针汇总追加「`insert_after` 多行锚的拒绝已再被 #599(2026-11-25)废除……」; +- `:314` 讨论点 7 结论追加「2026-11-25 更新:该决定已由 #599 反转……上述回归用例已随之删除」; +- `:403` §9 检视发现 #2 追加「(2026-11-25 更新:#599 已删除该约束本身……)」。 + +**变更分析**:三处都保留了原文并标注日期,事实正确(回归用例确实在本 PR 删除)。**检视发现**:过程记录的可追溯性受影响(讨论点 6,低);更好的 home 是 Note/新检视文档,或至少把规范写进 `docs/review.md`。 + +### 9.7 `plans/superpowers/plans/2026-11-25-issue-599-edit-insert-anchor-multiline.md`(A,+85) + +**职责**:本次实现计划(superpowers 任务体例)。**变更形态**:A。 + +**内容分析**:开头的「交互问题的设计答案」表(`:13-27`)把「插入点在哪 / target 自带换行 / 换行风格 / 单行是否变 / 缺失多义 / 是否加 retry / 生产原文能否入库」逐条钉到 issue 与 07 上,这是可审计的实现契约;随后 Task 1–7 是勾选表。值得肯定:Task 1 先红后绿、Task 5 明确「合成安全副本,不含生产原文」、Task 7 要求记录每条命令实际结果。 + +**检视发现**:`:18` 写「单行 target……逐字节一致」是过强承诺(讨论点 1/2);`:58`「全仓 grep `single-line substring` / `单行` 清理其它残留引用(docs/**、plans/**)」勾成 `[x]`,但残留引用仍在(`.agents/flow/issues/…` 的历史叙述、`plans/2026-11-22-pr510-review.md:87/308` 的探针记录)——那些是**合理的历史引用**,不该清理,所以更准确的做法是把这条勾改成「已确认残留仅为历史记录」。这是勾选表与实际的一处小偏差(低)。 + +### 9.8 Agent Note 三件套(A 3:`.md` +27 / `.en.md` +27 / `.i18n.yaml` +5) + +**职责**:本次决策的封闭决策记录(Problem / Decision / Alternatives considered / Consequences)。**变更形态**:A,`Status: implemented`,双语成对。 + +**内容分析**:Problem 把生产 run 的失败链条、`edits.6` 的字段级报错、为何「前两轮成功第三轮失败」写清楚了;Decision 是「契约统一 + 块末行之后 + 三处同步」;Alternatives 四条(加重试 / 公开隐藏规则 / 允许多 anchor / 只修观测)都给了拒绝理由,其中「不加字段级重试」与 issue 非目标一致;Consequences 记了三条(生产形状 replay、schema 表达不了条件约束必须进 prompt、`ConfigError` 丢 detail 的观测欠账)。双语互引、`i18n.yaml` 两个 blob hash 实测与实际文件一致;`verify-agent-notes` / `verify-translation-pairing` / `verify-doc-budgets` 全绿。 + +**检视发现**:`:24`「单行 `insert_after` 无行为变化……逐字节」是过强承诺(讨论点 1/2,必须在修 bug 后一并改);`:19`「多行 target 不绕过它」与 `text.count` 的实际行为冲突(讨论点 2);`:26` 关于「无重试」的表述是对的,正好反衬 07 那句旧话(讨论点 7)。词数与骨架合规(门禁实测通过)。 + +### 9.9 flow issue 三件套 `bugfix-edit-insert-anchor-multiline.*`(M 3) + +**职责**:issue #599 的流程档(状态机 + scope + ADR 关联 + 验收标准)。**变更形态**:M。 + +- `:12` `status: ready → in-progress`(实现 PR 未合并,正确;依赖 `bugfix-46` 已完成,门禁通过); +- `:20-21` `adr: []` → `adr: [../../notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline.md]`(路径存在、在 `.agents/notes/` 内,门禁通过); +- `.i18n.yaml` 两个 hash 更新,实测与两侧 blob 一致;中英 yaml 围栏逐字节相同(445 字符,实测)。 + +**检视发现**:合规。issue 的验收标准第 5 条(真实 full run)仍未满足,`in-progress` 是正确状态(讨论点 4)。scope 覆盖本 PR 全部 16 个文件(`apps/api/tests/**`、`plans/**`、`.agents/**`、两个 app 文件)。 + +### 9.10 flow issue 三件套 `bugfix-explicit-skill-conclusion.*`(M 3,第二提交) + +**职责**:#588 的流程档(归因 Skill 显式结论)。**变更形态**:M,`id: bugfix-56 → bugfix-58`、`status: in-progress → done`,i18n 重录。 + +**变更分析**:动机是 main 上 `bugfix-56` 被两份 issue 同时占用(另一份 `bugfix-bad-case-sync-type-title` 仍在 `ready`),`verify:flow` 因此红;#588 已随 PR #589 关闭,置 `done` 自洽。实测:`bugfix-58` 全树唯一、无其它引用 `bugfix-56` 的地方、hash 与实际 blob 一致、`gh issue view 588` 为 `CLOSED`、`verify:flow` 与 `verify-flow --diff` 均 ok。 + +**检视发现**:技术上正确、无残留;流程上属于跨 issue 身份变更(讨论点 5,低—中)。另注意:改的是**别人 issue 的 id**,若未来有外部链接/书签指向 `bugfix-56`(不含文件路径),会指向错误 issue——仓库内已确认无此引用,风险仅限仓库外。 + + +--- + +## §10 处置记录(2026-11-25,pr-review-fix) + +| # | 处置 | 落点 | +|---|---|---| +| 1 | 修复:EOF 分支保留整段文本;新增末行行中/行首字节回归 | `01d3bd8c` | +| 2 | 保留 `text.count`(issue 契约要求沿用);Note 与 07 显式标注「不重叠唯一」,逐字节承诺限定为 `\n`/`\r\n`/纯 bare `\r` | `01d3bd8c` | +| 3 | 已处理:Note 增加承诺边界说明 | `01d3bd8c` | +| 4 | 修复:补 4 格单行字节用例、`_edit_prompt` 契约断言;`replace` 弱用例改为行为断言 | `01d3bd8c` | +| 5 | 已处理:PR 描述补冒烟证据、截图与 3 提交/17 文件的范围说明;真实 full run 留部署后验证 | PR 描述 | +| 6 | 已处理:PR 描述单列「顺带修复 main 重复 id」说明 | PR 描述 | +| 7 | 已决:接受现状,不改历史检视文档 | 本文件 §6-6 | +| 8 | 修复:07 §5.5.4「多义回喂」改为 `ambiguous` 拒绝 | `01d3bd8c` | +| 9 | 修复:补 bare `\r` target 两格用例;docstring 写明 bare `\r` 插入行用 `\n` | `01d3bd8c` | + +验证基线(修复后,`.wt-599`,Windows):`pnpm test:api -- tests/test_edit_plan_applier.py` → 91 passed / 4 skipped;`pnpm test:api -- tests/test_ai_agent_claude_code.py` → 45 passed / 6 skipped;`pnpm lint:api`、`pnpm lint:docs`(11 叶)、`pnpm verify:flow` 全绿;集成冒烟 8/8 断言通过(见 PR 描述)。 From 34e1dff50d9dc93b6125f078d0a264ba534260e7 Mon Sep 17 00:00:00 2001 From: TangZ-L <345187680+TangZ-L@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:46:25 +0800 Subject: [PATCH 5/7] =?UTF-8?q?docs(review):=20=E6=94=B6=E5=8F=A3=E7=8B=AC?= =?UTF-8?q?=E7=AB=8B=E9=AA=8C=E8=AF=81=E7=9A=84=E6=96=87=E6=A1=A3=E4=B8=80?= =?UTF-8?q?=E8=87=B4=E6=80=A7=EF=BC=88N1-N4=EF=BC=89(#599)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/api/app/third_party_api/ai_agent/edits.py | 6 ++++-- apps/api/tests/test_edit_plan_applier.py | 2 +- plans/2026-11-25-pr607-review.md | 12 +++++++----- ...6-11-25-issue-599-edit-insert-anchor-multiline.md | 12 ++++++------ 4 files changed, 18 insertions(+), 14 deletions(-) diff --git a/apps/api/app/third_party_api/ai_agent/edits.py b/apps/api/app/third_party_api/ai_agent/edits.py index 0358ca99..a910f043 100644 --- a/apps/api/app/third_party_api/ai_agent/edits.py +++ b/apps/api/app/third_party_api/ai_agent/edits.py @@ -470,8 +470,10 @@ def _insert_after_text(text: str, target: str, content: str) -> str: the line containing the match's last character (the end of the file when that line is unterminated), and an unterminated final line gains one. Inserted lines reuse the anchor line's ``\\r\\n`` or ``\\n`` style; a bare - ``\\r`` anchor line keeps its bytes and inserted lines use ``\\n``. A - single-line target therefore keeps producing the historical bytes. + ``\\r`` anchor line keeps its bytes and inserted lines use ``\\n``. In files + whose lines end in ``\\n``, ``\\r\\n``, or bare ``\\r``, a single-line target + therefore keeps producing the historical bytes; mixed terminator styles and + other Unicode line separators are outside the contract. """ try: match_end = text.index(target) + len(target) diff --git a/apps/api/tests/test_edit_plan_applier.py b/apps/api/tests/test_edit_plan_applier.py index 1bce9dd3..7e3cb00a 100644 --- a/apps/api/tests/test_edit_plan_applier.py +++ b/apps/api/tests/test_edit_plan_applier.py @@ -835,7 +835,7 @@ def test_insert_after_single_line_targets_reproduce_exact_bytes( content: str, expected: str, ) -> None: - """Single-line anchors keep producing the historical byte-for-byte output.""" + """Single-line anchors keep historical bytes for `\n`/`\r\n`/bare-`\r` files.""" workspace = tmp_path / "ws" _write(workspace / "doc.md", text) plan = EditPlan( diff --git a/plans/2026-11-25-pr607-review.md b/plans/2026-11-25-pr607-review.md index 3b7f4138..4cb5b232 100644 --- a/plans/2026-11-25-pr607-review.md +++ b/plans/2026-11-25-pr607-review.md @@ -183,11 +183,11 @@ PR 描述没有 checkbox 形式的清单,以下是**从 PR 描述的验证声 - [x] CRLF 文件中的块插入保持 `\r\n`;单行 CRLF 锚点同样保持 —— 实测通过 - [x] 锚缺失、多义、scope 越界、content 超限、budget 超限仍按原规则拒绝/跳过 —— 既有用例全绿 - [x] `replace` / `append` / `delete` 语义不变 —— 既有四 op 精确内容用例全绿 -- [ ] **单行 `insert_after` 输出与旧实现逐字节一致** —— ❌ **实测不成立**:末行无换行符时丢字符(讨论点 1);混合 bare `\r`/`\n` 文件插入点偏移(讨论点 2);含 `\v`/`\f`/`\x1c`/`\x85`/`\u2028` 等字符的文件分歧(讨论点 2) -- [x] prompt、07 §5.5.4、Agent Note 三处措辞一致(人工比对;**无测试守护**,见讨论点 3) +- [x] **单行 `insert_after` 输出与旧实现逐字节一致(`\n`/`\r\n`/纯 bare `\r` 文件)** —— 已修复并回归(`01d3bd8c`):末行无换行丢字符已消除(2052 组与旧实现零差异);混合 bare `\r`/`\n` 与 `\v`/`\u2028` 等 Unicode 分隔符不在承诺内(讨论点 2、§10) +- [x] prompt、07 §5.5.4、Agent Note 三处措辞一致(人工比对;`_edit_prompt` 已有断言守护,见讨论点 3) - [x] 仓库不含生产计划原文 / Session 内容 / 凭据;replay 用合成 demo skill —— 已核对测试文本 - [x] `verify:flow`、`lint:docs` 在当前 HEAD 全绿(`023662e4` 实测);CI 的 `verify-flow --diff` 也 ok -- [ ] **一次真实 full run 能完成此前失败的第 3 轮** —— PR 描述「冒烟与证据」仍是占位(讨论点 4) +- [ ] **一次真实 full run 能完成此前失败的第 3 轮** —— 需部署后验证(PR 描述已声明;本地集成冒烟 8/8 断言通过,见讨论点 4) --- @@ -523,13 +523,15 @@ f"- file 必须落在允许范围 {list(allowed)!r} 内;" | # | 处置 | 落点 | |---|---|---| | 1 | 修复:EOF 分支保留整段文本;新增末行行中/行首字节回归 | `01d3bd8c` | -| 2 | 保留 `text.count`(issue 契约要求沿用);Note 与 07 显式标注「不重叠唯一」,逐字节承诺限定为 `\n`/`\r\n`/纯 bare `\r` | `01d3bd8c` | +| 2 | 保留 `text.count`(issue 契约要求沿用);Note 标注「不重叠唯一」与逐字节承诺边界(`\n`/`\r\n`/纯 bare `\r`);07 标注不重叠计数 | `01d3bd8c` | | 3 | 已处理:Note 增加承诺边界说明 | `01d3bd8c` | | 4 | 修复:补 4 格单行字节用例、`_edit_prompt` 契约断言;`replace` 弱用例改为行为断言 | `01d3bd8c` | -| 5 | 已处理:PR 描述补冒烟证据、截图与 3 提交/17 文件的范围说明;真实 full run 留部署后验证 | PR 描述 | +| 5 | 已处理:PR 描述补冒烟证据、截图与 4 提交/17 文件的范围说明;真实 full run 留部署后验证 | PR 描述 | | 6 | 已处理:PR 描述单列「顺带修复 main 重复 id」说明 | PR 描述 | | 7 | 已决:接受现状,不改历史检视文档 | 本文件 §6-6 | | 8 | 修复:07 §5.5.4「多义回喂」改为 `ambiguous` 拒绝 | `01d3bd8c` | | 9 | 修复:补 bare `\r` target 两格用例;docstring 写明 bare `\r` 插入行用 `\n` | `01d3bd8c` | 验证基线(修复后,`.wt-599`,Windows):`pnpm test:api -- tests/test_edit_plan_applier.py` → 91 passed / 4 skipped;`pnpm test:api -- tests/test_ai_agent_claude_code.py` → 45 passed / 6 skipped;`pnpm lint:api`、`pnpm lint:docs`(11 叶)、`pnpm verify:flow` 全绿;集成冒烟 8/8 断言通过(见 PR 描述)。 + +独立验证(2026-11-25,验证 subagent):旧实现等价物 vs 新实现 684 组 target / 2052 组执行**零差异**;修复前实现对照 1065 组差异全部为截尾;公开入口丢字符 6/6 恢复;多行块 8/8 正确;0/2 次契约不变。验证补充 N1–N4(计划文件逐字节限定语、edits.py docstring 限定、§10 提交数)已随本文件收口。 diff --git a/plans/superpowers/plans/2026-11-25-issue-599-edit-insert-anchor-multiline.md b/plans/superpowers/plans/2026-11-25-issue-599-edit-insert-anchor-multiline.md index 6fbb8d51..6f20cb02 100644 --- a/plans/superpowers/plans/2026-11-25-issue-599-edit-insert-anchor-multiline.md +++ b/plans/superpowers/plans/2026-11-25-issue-599-edit-insert-anchor-multiline.md @@ -2,9 +2,9 @@ > **For agentic workers:** this plan follows the superpowers task-by-task style; the linked issue `.agents/flow/issues/bugfix-edit-insert-anchor-multiline.md` is the implementation contract. Every interactive question is answered from `plans/fullstack-design`, not by asking the user. -**Goal:** `insert_after` 的锚点契约统一为「文件内存在且唯一的文本片段(可跨行)」,content 插入在匹配块末行之后;单行 target 输出与现状逐字节一致;prompt、派生 schema 说明、设计文档与 validator 表达同一契约。 +**Goal:** `insert_after` 的锚点契约统一为「文件内存在且唯一的文本片段(可跨行)」,content 插入在匹配块末行之后;单行 target 输出与现状逐字节一致(纯 `\n`/`\r\n`/纯 bare `\r` 文件);prompt、派生 schema 说明、设计文档与 validator 表达同一契约。 -**Architecture:** `EditOp`(Pydantic 单一事实源)删除单行拒绝;`edits.py` 应用器改为整段唯一匹配 + 块末行之后插入(沿用 `text.count` 的缺失/多义分支);`_edit_prompt()` 把可跨行契约写进模型可见文案;07 §5.5.4 同步;回归测试覆盖多行块、单行逐字节一致、CRLF、缺失与多义。 +**Architecture:** `EditOp`(Pydantic 单一事实源)删除单行拒绝;`edits.py` 应用器改为整段唯一匹配 + 块末行之后插入(沿用 `text.count` 的缺失/多义分支);`_edit_prompt()` 把可跨行契约写进模型可见文案;07 §5.5.4 同步;回归测试覆盖多行块、单行逐字节一致(纯 `\n`/`\r\n`/纯 bare `\r` 文件)、CRLF、缺失与多义。 **Scope:** `apps/api/app/third_party_api/ai_agent/edits.py`、`apps/api/app/service/evolution/patch_source.py`、`apps/api/tests/test_edit_plan_applier.py`、`apps/api/tests/test_ai_agent_claude_code.py`(如有 single-line 断言)、`plans/fullstack-design/07-backend-implementation.md`、`plans/**`、`.agents/flow/issues/bugfix-edit-insert-anchor-multiline*`、`.agents/notes/implemented/bug-fix/2026-11-25-edit-insert-anchor-multiline*`。不改 `claude_code.py` / `submission.py` / 工具面 / 预算 / 超时 / 前端。 @@ -15,9 +15,9 @@ | 多行 target 的插入点在哪? | issue 目标 2 + [07 §5.5.4](../../fullstack-design/07-backend-implementation.md#554-edit-指令式-patcheditplan--editspy) | 匹配块末行之后;确定性、可重放 | | target 自身以换行结尾时怎么办? | issue 实现内容 2 | 以该换行之后为插入点,不额外补终止符 | | 插入行的换行风格? | issue 实现内容 2 | 沿用锚块末行现有风格:`\r\n` 或 `\n`(bare `\r` 回落 `\n`,与现状一致) | -| 单行 target 是否改变输出? | issue 目标 2 | 否,逐字节一致;`test_insert_after_last_line_without_newline` 等既有用例保持通过 | +| 单行 target 是否改变输出? | issue 目标 2 | 否,逐字节一致(纯 `\n`/`\r\n`/纯 bare `\r` 文件);`test_insert_after_last_line_without_newline` 等既有用例保持通过 | | 锚缺失 / 多义如何处理? | issue 实现内容 2 + #494 契约 | 沿用 `text.count(target)`:0 次 → `skipped_anchor_missing`,>1 → `error`(`anchor is ambiguous`) | -| 是否保留唯一性/预算/scope 限制? | issue 非目标 | 全部保留;不允许用多行 target 绕过唯一性检查 | +| 是否保留唯一性/预算/scope 限制? | issue 非目标 | 全部保留;唯一性按 `text.count` 不重叠计数(与 `replace`/`delete` 一致),多行 target 不放宽唯一性 | | edit 是否增加反馈重试? | issue 非目标 + 07 §5.5.3 | 不增加;单次调用、失败即终止的语义不变 | | prompt 里怎么写锚点契约? | issue 实现内容 3 + 07 §5.5.3「调用方 prompt 必须把 schema 表达不了的语义约束说清楚」 | 「锚文本是文件内唯一出现的文本片段,可跨行;insert_after 插到该片段末行之后」 | | 设计文档改哪? | issue 实现内容 4 | 07 §5.5.4 执行流 bullet 与 json5 示例注释 | @@ -40,7 +40,7 @@ - [x] 删除 `_validate_op_fields()` 中 `insert_after` 对 `\n` / `\r` 的拒绝;docstring 改为「insert_after 的 target 是文件内唯一出现的文本片段,可以跨行」。 - [x] 重写 `_insert_after_text()`:整段匹配唯一出现的 target;target 以换行(`\r\n`/`\n`/`\r`)结尾 → 插入点在该换行之后;否则插入点在匹配块末字符所在行的行终止符之后(EOF 无终止符 → 补 `\n`);插入行沿用该行风格(`\r\n` 或 `\n`)。 - [x] `_apply_one()` 的 insert_after 分支删除单行拒绝,保留 `text.count(target)` 的 0 次 → skipped、>1 次 → ambiguous 分支;清除「not contained in one line」旧守卫。 -- [x] 单行路径逐字节回归:`test_insert_after_last_line_without_newline`、四 op 精确内容用例、CRLF 用例全部保持通过。 +- [x] 单行路径逐字节回归(LF/CRLF/bare `\r`):`test_insert_after_last_line_without_newline`、四 op 精确内容用例、CRLF 用例全部保持通过。 ### Task 3: prompt 与派生 schema 契约 @@ -63,7 +63,7 @@ - [x] 删除 `test_insert_after_rejects_a_multiline_anchor_at_model_construction` 及其参数行(`("insert_after", "line\nbreak", ...)` 断言 single-line 的行)。 - [x] 新增:4 行唯一块锚点通过校验,应用后 content 出现在块末行之后;文件其余字节不变。 -- [x] 新增:单行 target(行中、行尾、EOF 无终止符)输出与旧实现逐字节一致(固定期望串断言)。 +- [x] 新增:单行 target(行中、行尾、EOF 无终止符)输出与旧实现逐字节一致(LF/CRLF/bare `\r`;固定期望串断言)。 - [x] 新增:多行块 0 次 → `skipped_anchor_missing`;2 次 → `error` 且 message 含 `anchor is ambiguous`。 - [x] 新增:CRLF 文件中的多行块插入保持 `\r\n`。 - [x] 新增:`append` / `replace` / `delete` 既有语义不变的守卫断言(可复用既有用例,不必重复)。 From dede73b3be7335ffef1a0febafe2ea2ec0a67740 Mon Sep 17 00:00:00 2001 From: TangZ-L <345187680+TangZ-L@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:07:23 +0800 Subject: [PATCH 6/7] =?UTF-8?q?fix(attribution):=20=E8=A1=A5=E9=BD=90=20wr?= =?UTF-8?q?ite=5Fprobe=5Freport=20=E7=9A=84=20conclusion/root-cause=20?= =?UTF-8?q?=E5=A5=91=E7=BA=A6=20(#599)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #588(744f4f57)给 make_probe_report.py 增加了必需的 --conclusion 与 --root-cause,并更新 SKILL.md 要求显式结论;但平台 MCP 工具的 ReportFields 没有这两个字段(extra=forbid),也不会转发,导致 case-tools 模式的 attribution 报告全部被脚本拒绝、unit-tests-api 红、 main 自身 CI 为 failure。 本提交在 attribution_case_tools.py 的 ReportFields 增加必需 conclusion 枚举与非空 root_cause(validator 拒绝空白),由既有转发 循环生成 --conclusion/--root-cause;test_case_tools.py 补 selected_target fixture,并断言结论/根因透传、非法结论/空根因/缺字段 被拒绝。新增 Agent Note 记录取舍;flow issue 补 scope 与附带修复说明。 否则 main 上的 unit-tests-api 红会阻塞所有 PR,包括本 PR。 --- .../bugfix-edit-insert-anchor-multiline.en.md | 5 ++++ ...fix-edit-insert-anchor-multiline.i18n.yaml | 4 +-- .../bugfix-edit-insert-anchor-multiline.md | 5 ++++ ...tribution-writer-conclusion-contract.en.md | 26 +++++++++++++++++++ ...ution-writer-conclusion-contract.i18n.yaml | 5 ++++ ...-attribution-writer-conclusion-contract.md | 26 +++++++++++++++++++ .../ai_agent/attribution_case_tools.py | 12 ++++++++- apps/api/tests/attribution/test_case_tools.py | 14 ++++++++++ 8 files changed, 94 insertions(+), 3 deletions(-) create mode 100644 .agents/notes/implemented/bug-fix/2026-11-25-attribution-writer-conclusion-contract.en.md create mode 100644 .agents/notes/implemented/bug-fix/2026-11-25-attribution-writer-conclusion-contract.i18n.yaml create mode 100644 .agents/notes/implemented/bug-fix/2026-11-25-attribution-writer-conclusion-contract.md diff --git a/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.en.md b/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.en.md index c20a7de8..cac7594f 100644 --- a/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.en.md +++ b/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.en.md @@ -13,6 +13,7 @@ status: in-progress scope: - apps/api/app/third_party_api/ai_agent/edits.py - apps/api/app/service/evolution/patch_source.py + - apps/api/app/third_party_api/ai_agent/attribution_case_tools.py - apps/api/tests/** - docs/** - plans/** @@ -126,6 +127,10 @@ edits.6: Value error, target must be a single-line substring - `append` / `replace` / `delete` semantics are unchanged. 6. **Do not change observability or retries**: `feedback_prompt()` and the single-shot structure of `edit_workspace()` stay as they are; the `ConfigError` conversion that drops detail is not part of this solution, to avoid expanding the fix into the run error model. +### Incidental fix (a regression already red on main) + +#588 (`744f4f57`) added the required `--conclusion` / `--root-cause` arguments to `attribute-badcases/make_probe_report.py` and updated `SKILL.md` to require an explicit verdict; but the platform MCP tool `CaseTools.write_probe_report(report: ReportFields)` had neither field on `ReportFields` (`extra="forbid"`) nor forwarded them, so every attribution report in `case-tools` mode was rejected by the script, `unit-tests-api` went red, and main's own CI was a failure. This PR adds the two required fields (verdict enum + non-blank root-cause validator) in `attribution_case_tools.py` and updates the `selected_target` fixture and assertions in `test_case_tools.py`; without it no PR can pass CI. The fix does not change anchor semantics, budgets, or retry boundaries. + ## Implementation steps 1. First add a failing regression: pass an `insert_after` plan with a synthetic 4-line block anchor to `EditPlan.model_validate()` and confirm the current implementation reports `target must be a single-line substring`. diff --git a/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.i18n.yaml b/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.i18n.yaml index 4e59ad79..9ac753ed 100644 --- a/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.i18n.yaml +++ b/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.i18n.yaml @@ -1,5 +1,5 @@ # 双语配对一致性记录(docs/i18n/README.md):两侧在最后一次确认一致状态下的 # git blob hash。两种语言同等权威;编辑任一侧后带上另一侧,然后重录: # pnpm run record:i18n -- .agents/flow/issues/bugfix-edit-insert-anchor-multiline.md -bugfix-edit-insert-anchor-multiline.md: 00d6a2d2a430e344007c21ed74e3e6260e52378d -bugfix-edit-insert-anchor-multiline.en.md: c20a7de8526598c5dad2b878e633f02565b2f66d +bugfix-edit-insert-anchor-multiline.md: 6951e1d55dd5908795e5a0172989a801aca2a32b +bugfix-edit-insert-anchor-multiline.en.md: cac7594f8106af41162410e7d381a8c68590ef8e diff --git a/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.md b/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.md index 00d6a2d2..6951e1d5 100644 --- a/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.md +++ b/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.md @@ -13,6 +13,7 @@ status: in-progress scope: - apps/api/app/third_party_api/ai_agent/edits.py - apps/api/app/service/evolution/patch_source.py + - apps/api/app/third_party_api/ai_agent/attribution_case_tools.py - apps/api/tests/** - docs/** - plans/** @@ -126,6 +127,10 @@ edits.6: Value error, target must be a single-line substring - `append` / `replace` / `delete` 的既有语义不变。 6. **不改观测与重试**:`feedback_prompt()` 与 `edit_workspace()` 的单次调用结构保持原样;`ConfigError` 转换丢弃 detail 的问题不在本方案内处理,避免把修复面扩大到 run 错误模型。 +### 附带修复(main 已红的回归) + +#588(`744f4f57`)给 `attribute-badcases/make_probe_report.py` 增加了必需的 `--conclusion` / `--root-cause`,并在 `SKILL.md` 要求 Skill 传入显式结论;但平台 MCP 工具 `CaseTools.write_probe_report(report: ReportFields)` 的 `ReportFields` 没有这两个字段(`extra="forbid"`),也不会转发,导致 `case-tools` 模式下所有 attribution 报告被脚本拒绝、`unit-tests-api` 红、main 自身 CI 为 failure。本 PR 在 `attribution_case_tools.py` 补齐两个必需字段(结论枚举 + 非空根因校验),并更新 `test_case_tools.py` 的 `selected_target` fixture 与断言;否则任何 PR 都无法通过 CI。该修复不改锚点语义、预算或重试边界。 + ## 实施步骤 1. 先加一条失败回归:用合成 4 行块锚点的 `insert_after` 计划调用 `EditPlan.model_validate()`,确认当前实现报 `target must be a single-line substring`。 diff --git a/.agents/notes/implemented/bug-fix/2026-11-25-attribution-writer-conclusion-contract.en.md b/.agents/notes/implemented/bug-fix/2026-11-25-attribution-writer-conclusion-contract.en.md new file mode 100644 index 00000000..fa2f9609 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-25-attribution-writer-conclusion-contract.en.md @@ -0,0 +1,26 @@ +# Agent Note: attribution platform tool catches up with the write_probe_report conclusion/root-cause contract + +Status: implemented + +English | [中文](2026-11-25-attribution-writer-conclusion-contract.md) + +## Problem + +#588 (`744f4f57`) added two required arguments to `attribute-badcases/make_probe_report.py` — `--conclusion` (`attributed` / `non_target` / `inconclusive`) and `--root-cause` — and updated `SKILL.md` to require an explicit verdict from the Skill. The platform-side MCP tool `CaseTools.write_probe_report(report: ReportFields)` did not follow: `ReportFields` forbids extra fields and had neither `conclusion` nor `root_cause`, so the tool could not accept or forward them to the frozen writer. Every attribution run that submitted a report through the platform tool therefore failed on the script's argparse usage, `tests/attribution/test_case_tools.py` was red, the `unit-tests-api` lane was red, and main's own CI was a failure even though that PR merged. The new script also requires `input_badcase.json` to carry `selected_target.name`, while the `test_case_tools.py` fixture still had the old shape. + +## Decision + +`ReportFields` gains the required `conclusion: Literal["attributed", "non_target", "inconclusive"]` and a non-blank `root_cause: str` (blank rejected by a validator); the existing `model_dump(exclude_none=True)` forwarding loop then emits `--conclusion` / `--root-cause` automatically. The `test_case_tools.py` fixture gains `selected_target`, and the test asserts the persisted `probe_report.json` carries the submitted `conclusion` / `root_cause`, while invalid verdicts, blank root causes, and missing fields are rejected by the model. The writer's explicit-verdict contract stays as-is; no defaults are introduced. + +## Alternatives considered + +- **Default the platform-side verdict (e.g. `inconclusive`)** would silently fabricate an unattributed verdict when the model omits one, breaking #588's core goal. Rejected. +- **Make `--conclusion` / `--root-cause` optional again** would revert #588's explicit-verdict contract even though `SKILL.md` already states them as required. Rejected. +- **Fix only the test, not the platform tool** cannot legally construct a verdict-bearing call and would turn a red gate into a fake green. Rejected. +- **Open a separate issue and PR to fix main first**: with `unit-tests-api` red on main, every new PR's CI would also be red, so the separate PR could not merge either; the fix ships with the #599 PR and is called out in the PR description and the flow issue. Rejected. + +## Consequences + +- The MCP tool's input schema now requires the Skill to provide both the explicit verdict and the root cause; `SKILL.md` (updated in #588) matches the actual contract, and `case-tools` attribution plus the launch-wizard binding counts recover. +- `unit-tests-api` returns to green: `test_case_tools.py` covers verdict forwarding, the `selected_target` input, and rejection of invalid inputs. +- This fix addresses a main regression, not #599's anchor contract; the PR description and flow issue body state its source and necessity, and #599's anchor semantics, budget, and retry boundaries are unchanged. diff --git a/.agents/notes/implemented/bug-fix/2026-11-25-attribution-writer-conclusion-contract.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-11-25-attribution-writer-conclusion-contract.i18n.yaml new file mode 100644 index 00000000..ecda1a06 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-25-attribution-writer-conclusion-contract.i18n.yaml @@ -0,0 +1,5 @@ +# 双语配对一致性记录(docs/i18n/README.md):两侧在最后一次确认一致状态下的 +# git blob hash。两种语言同等权威;编辑任一侧后带上另一侧,然后重录: +# pnpm run record:i18n -- .agents/notes/implemented/bug-fix/2026-11-25-attribution-writer-conclusion-contract.md +2026-11-25-attribution-writer-conclusion-contract.md: b08da34370da1c69cdbdab5311ff2f6106040123 +2026-11-25-attribution-writer-conclusion-contract.en.md: fa2f96098bb26362f6795b41fda708662ae8fc47 diff --git a/.agents/notes/implemented/bug-fix/2026-11-25-attribution-writer-conclusion-contract.md b/.agents/notes/implemented/bug-fix/2026-11-25-attribution-writer-conclusion-contract.md new file mode 100644 index 00000000..b08da343 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-25-attribution-writer-conclusion-contract.md @@ -0,0 +1,26 @@ +# Agent Note: attribution 平台工具补齐 write_probe_report 的 conclusion/root-cause 契约 + +Status: implemented + +[English](2026-11-25-attribution-writer-conclusion-contract.en.md) | 中文 + +## Problem + +#588(`744f4f57`)给 `attribute-badcases/make_probe_report.py` 增加了两个必需参数 `--conclusion`(`attributed` / `non_target` / `inconclusive`)与 `--root-cause`,并在 `SKILL.md` 里要求 Skill 传入显式结论;但平台侧的 MCP 工具 `CaseTools.write_probe_report(report: ReportFields)` 没有跟进:`ReportFields` 以 `extra="forbid"` 关闭了额外字段,既没有 `conclusion`/`root_cause` 字段,也不会把它们转发给冻结的 writer。结果所有通过平台工具写报告的 attribution 调用都以 `make_probe_report.py` 的 argparse usage 失败,`tests/attribution/test_case_tools.py` 红,`unit-tests-api` lane 红;main 自身 CI 也因此为 failure,但该 PR 仍被合入。另外新脚本要求 `input_badcase.json` 带 `selected_target.name`,而 `test_case_tools.py` 的 fixture 仍是旧形状。 + +## Decision + +`ReportFields` 增加必需字段 `conclusion: Literal["attributed", "non_target", "inconclusive"]` 与非空 `root_cause: str`(blank 由 validator 拒绝),由已有的 `model_dump(exclude_none=True)` 转发循环自动生成 `--conclusion` / `--root-cause`;`test_case_tools.py` 的 fixture 补 `selected_target`,并断言 `probe_report.json` 中的 `conclusion` / `root_cause` 与提交值一致、非法结论/空根因/缺字段均被模型拒绝。writer 的「显式结论」契约保持原样,不引入默认值。 + +## Alternatives considered + +- **平台侧给缺省结论(如 `inconclusive`)**:会让模型漏传时静默产出结论,伪造一条未经判断的归因,破坏 #588 的核心目标。拒绝。 +- **把脚本的 `--conclusion` / `--root-cause` 改回可选**:等于回退 #588 的显式结论契约,且 SKILL 已经按必需参数写成正向契约。拒绝。 +- **只改测试、不改平台工具**:测试无法合法构造带结论的调用,等于把红门禁改成假绿。拒绝。 +- **新建独立 issue + PR 先修 main**:main 的 `unit-tests-api` 红会让每个新 PR 的 CI 同样红,独立 PR 也无法合入;本修复随 #599 的 PR 一起交付,并在 PR 描述与 issue 里单列说明。 + +## Consequences + +- MCP 工具的入参 schema 现在要求 Skill 同时给出显式结论与根因;`SKILL.md`(#588 已更新)与实际契约一致,`case-tools` 模式的 attribution 与启动向导弹窗的绑定计数恢复。 +- `unit-tests-api` 恢复绿:`test_case_tools.py` 覆盖平台 writer 的结论透传、输入 `selected_target` 与非法输入拒绝。 +- 该修复属于 main 回归而非 #599 的锚点契约,PR 描述与 flow issue 正文中单列一节说明其来源与必要性;不改变 #599 的锚点语义、预算或重试边界。 diff --git a/apps/api/app/third_party_api/ai_agent/attribution_case_tools.py b/apps/api/app/third_party_api/ai_agent/attribution_case_tools.py index 262cfa20..176908b2 100644 --- a/apps/api/app/third_party_api/ai_agent/attribution_case_tools.py +++ b/apps/api/app/third_party_api/ai_agent/attribution_case_tools.py @@ -11,7 +11,7 @@ from typing import Any, Literal from mcp.server import MCPServer -from pydantic import BaseModel, ConfigDict +from pydantic import BaseModel, ConfigDict, field_validator _EVIDENCE = ( "input_badcase.json", @@ -31,6 +31,8 @@ class ReportFields(BaseModel): probe_type: Literal["skill", "agent", "knowledge"] = "skill" object_version: str | None = None attribute_type: Literal["prompt", "model", "error", "flow", "context", "unknown"] + conclusion: Literal["attributed", "non_target", "inconclusive"] + root_cause: str probe_description: str probe_analysis: str detail_description: str | None = None @@ -40,6 +42,14 @@ class ReportFields(BaseModel): proposal_expected_behavior: str | None = None proposal_evaluation_plan: str | None = None + @field_validator("root_cause") + @classmethod + def _validate_root_cause(cls, value: str) -> str: + """Require a non-blank mechanism or evidence gap for the explicit verdict.""" + if not value.strip(): + raise ValueError("root_cause must not be blank") + return value + class CaseTools: """Expose only staged evidence, bound Skill text and the frozen platform writer.""" diff --git a/apps/api/tests/attribution/test_case_tools.py b/apps/api/tests/attribution/test_case_tools.py index 938e704d..3c87390f 100644 --- a/apps/api/tests/attribution/test_case_tools.py +++ b/apps/api/tests/attribution/test_case_tools.py @@ -29,6 +29,7 @@ def case(tmp_path: Path) -> Path: json.dumps( { "session_id": "one-session", + "selected_target": {"name": "reporter", "type": "agent", "version": "v1"}, "bad_cases": [ { "bad_case_id": "case-one", @@ -94,12 +95,23 @@ def test_only_platform_writer_chooses_paths_and_case_identity(case: Path) -> Non "probe_object": "reporter", "probe_type": "agent", "attribute_type": "context", + "conclusion": "attributed", + "root_cause": "上游参数已存在,检视规则误报", # noqa: RUF001 "probe_description": "--output=just literal analysis", "probe_analysis": "说明", } for key in ("bad_case_id", "output", "input_badcase", "command"): with pytest.raises(ValidationError): ReportFields.model_validate({**fields, key: "outside"}) + for invalid in ( + {**fields, "conclusion": "maybe"}, + {**fields, "root_cause": " "}, + ): + with pytest.raises(ValidationError): + ReportFields.model_validate(invalid) + missing_verdict = {key: value for key, value in fields.items() if key != "conclusion"} + with pytest.raises(ValidationError): + ReportFields.model_validate(missing_verdict) tools = CaseTools(case) with pytest.raises(ValueError, match="platform writer rejected"): tools.write_probe_report(ReportFields.model_validate({**fields, "probe_object": "other"})) @@ -109,6 +121,8 @@ def test_only_platform_writer_chooses_paths_and_case_identity(case: Path) -> Non report = json.loads(output.read_bytes()) assert report["from_bad_cases"][0]["bad_case_id"] == "case-one" assert report["probe_description"] == fields["probe_description"] + assert report["conclusion"] == fields["conclusion"] + assert report["root_cause"] == fields["root_cause"] assert json.loads((case / ".platform/receipt.json").read_bytes()) == { "path": output.name, "sha256": hashlib.sha256(output.read_bytes()).hexdigest(), From e4008dece66df7f2465bba8cb42fd45816bae045 Mon Sep 17 00:00:00 2001 From: TangZ-L <345187680+TangZ-L@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:32:56 +0800 Subject: [PATCH 7/7] =?UTF-8?q?test(attribution):=20=E8=A1=A5=E9=BD=90=20C?= =?UTF-8?q?LI=20fixture=20=E7=9A=84=20conclusion/root-cause=20=E5=8F=82?= =?UTF-8?q?=E6=95=B0=20(#599)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/api/tests/attribution/case_cli_fixture.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/apps/api/tests/attribution/case_cli_fixture.py b/apps/api/tests/attribution/case_cli_fixture.py index 1734f1cc..fc800166 100644 --- a/apps/api/tests/attribution/case_cli_fixture.py +++ b/apps/api/tests/attribution/case_cli_fixture.py @@ -38,6 +38,10 @@ async def _write_sandbox_report(args: list[str]) -> None: "fixture observation", "--probe-analysis", "fixture evidence", + "--conclusion", + "attributed", + "--root-cause", + "fixture root cause", "--output", "probe_report.json", stdout=asyncio.subprocess.DEVNULL, @@ -81,6 +85,8 @@ async def _write_case_tool_report(args: list[str]) -> None: "probe_object": row["object"], "probe_type": row["type"], "attribute_type": "flow", + "conclusion": "attributed", + "root_cause": "fixture root cause", "probe_description": "fixture observation", "probe_analysis": "fixture evidence", }