Skip to content
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,16 @@ 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
- apps/api/tests/**
- 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
Expand Down
Original file line number Diff line number Diff line change
@@ -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
5 changes: 3 additions & 2 deletions .agents/flow/issues/bugfix-edit-insert-anchor-multiline.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,16 @@ 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
- apps/api/tests/**
- 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
Expand Down
Original file line number Diff line number Diff line change
@@ -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) — 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

- **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.
Original file line number Diff line number Diff line change
@@ -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: 9fb87b7d6842093b5ca0e1e74f8c4f81138b3777
2026-11-25-edit-insert-anchor-multiline.en.md: ac433e70271a20722b091a4363ca993c2c59fce1
Original file line number Diff line number Diff line change
@@ -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`);无终止符的末行即文件末尾,插入点是文件末尾,匹配点与 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

- **给 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` 不再有单行特例;模型拒绝的多行锚由「非法」变为「合法锚点」,坏计划在落盘前失败、应用结果确定可重放的性质不变。
4 changes: 3 additions & 1 deletion apps/api/app/service/evolution/patch_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -541,7 +541,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}]}。",
Expand Down
75 changes: 49 additions & 26 deletions apps/api/app/third_party_api/ai_agent/edits.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -465,18 +463,52 @@ 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 (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``. 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)
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:
# 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}{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:
Expand All @@ -494,15 +526,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(
Expand Down
2 changes: 2 additions & 0 deletions apps/api/tests/test_ai_agent_claude_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -1766,6 +1766,7 @@ def test_from_settings_resolves_generic_and_legacy_entries(tmp_path: Path) -> No
assert both._settings_file() == tmp_path / "generic-settings.json"


@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,
Expand Down Expand Up @@ -1803,6 +1804,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,
Expand Down
Loading
Loading