Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .agents/flow/issues/bugfix-edit-patch-member-scope.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ priority: P2
status: ready
scope:
- apps/api/app/**
- apps/api/alembic/**
- apps/api/tests/**
- apps/web/src/**
- packages/contracts/**
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-patch-member-scope.md
bugfix-edit-patch-member-scope.md: 85b253475f76b5b5197c400bfc424cf6ac6a7ed9
bugfix-edit-patch-member-scope.en.md: 90fe69098f540927f68161702db6a59bf5f4030e
bugfix-edit-patch-member-scope.md: fc8156c82c2435fafec01a75c36a2a8cd5776d3f
bugfix-edit-patch-member-scope.en.md: f39bd5c20aea347519a74c00eee6f56b1055e559
1 change: 1 addition & 0 deletions .agents/flow/issues/bugfix-edit-patch-member-scope.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ priority: P2
status: ready
scope:
- apps/api/app/**
- apps/api/alembic/**
- apps/api/tests/**
- apps/web/src/**
- packages/contracts/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Agent Note: Member-level attribution reports, member clusters and member patches

Status: implemented

English | [中文](2026-12-05-member-scope-attribution-clustering-patch.md)

## Problem

Production run `01M9004SE7E4ZNS1SA1RV5K6M2` exposed three inconsistent identities across a multi-member evolution object: step 4 produced one attribution report per bad case and bound it to one member or object level; a step-5 cluster could contain source reports from both `code-generator` and `codespec-subagent-driven-development`; the step-6 patch took the union of every member directory and the commit was named after the first member. The reporter expected one bad case to attribute to several members with one report each, different members never to share a cluster, and the patch to modify only that cluster's member.

The old model was not data corruption: `probe_reports.member_id` and the execution manifest already carried a member, but the attribution runner built one input per case, the candidate had one `probe_id` pointer, the cluster key had no member, and the patch had no cluster member.

## Decision

- Attribution fans out over candidate members: a self case belongs only to the member that filed it; a discovery case gets one independent report per member observed in its Session (`member_id`/`probe_object`/category/conclusion/confidence/cache key). An object-level report is only the fallback when the candidate set is empty; single-member runs keep the sole-member compatibility path.
- A new run-scoped `evolution_run_candidate_probes` junction records every report; `evolution_run_candidates.probe_id` keeps only the first report and is no longer overwritten. Step 4 reads all reports through the junction and groups them by case.
- The cluster key includes the member: drafts and clusters carry `member_id`; the LLM review rejects cross-member merges and batches oversized inputs by `(type, member)`; degradation buckets also split by member. `probe_clusters.member_id` is persisted (migration 0044).
- The patch inherits the cluster member: `CandidateTrace.member` comes from the cluster, `allowed_paths` contains only that member's `sub_dir`, and the prompt/commit name that member; object-level rounds keep the union fallback; a cross-member change must be split into another member cluster/turn.
- The frontend follows the prototype: step 4 groups reports under a case with rowspan, step 5 groups clusters by member, and step 6 shows the member scope and change range.
- Historical `member_id=null` data is not rewritten; historical mixed clusters still render with the object-level union.

## Alternatives considered

- **Keep object-level patches and only relabel the UI**: it would not fix a patch changing two members, the wrong commit ownership, or the inability to explain evaluation per member; rejected.
- **Do member clusters and member patches without attribution fan-out**: clusters would still see only the first report per case and could not express “one case belongs to several members”; rejected.
- **Change the executor to return several member conclusions in one call**: it needs an executor request/response contract change, Skill prompt changes and report schema changes; this change uses one single-conclusion call per member and keeps the contract stable at the cost of N calls; deferred as a follow-up optimization.
- **Migrate `evolution_attribution_inputs` to a per-report primary key**: it would let the review freeze each report, but touches review UI and history; this change keeps review inputs case-level, lets secondary reports reach clustering through the run junction, and still shows every report in step 4; per-report review is a follow-up.
- **Add a separate member column to turns**: clusters already get migration 0044; turns inherit from the cluster instead of duplicating storage.

## Consequences

New runs produce several reports for a discovery case according to the Session's hit members, so step 4 has more rows; one case may enter several member clusters, increasing cluster and turn counts in steps 5/6. Attribution calls grow with the candidate member count, while single-member and historical cache keys and paths stay unchanged.

Two limits remain explicit: the frozen review input stays case-level (a secondary report cannot be excluded separately; it follows its case), and historical mixed clusters have no member and keep the object-level union patch without automatic splitting. Evaluation still produces one score for the whole run and does not score members separately.

Implementation: `apps/api/app/service/evolution/{attribution,cluster,cluster_llm,prepare,patch_source,git_candidate,stages}.py`, `apps/api/alembic/versions/0044_run_candidate_probes_member.py`, `apps/web/src/pages/evolution/components/{StepAttribution,StepClusters,StepIterations}.vue`; tests in `apps/api/tests/attribution/test_object_level_attribution.py`, `tests/evolution/test_cluster_attribution_drafts.py`, `apps/api/tests/test_agent_edit_source.py`.
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/feature/2026-12-05-member-scope-attribution-clustering-patch.md
2026-12-05-member-scope-attribution-clustering-patch.md: 35d59882d40f2ec114ad250aa1f21808a34db749
2026-12-05-member-scope-attribution-clustering-patch.en.md: 2c9ae948526123b37b0f8aaf15be01a627f33773
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Agent Note: 成员级归因报告、成员簇与成员 patch

Status: implemented

[English](2026-12-05-member-scope-attribution-clustering-patch.en.md) | 中文

## Problem

多成员进化对象的生产 run `01M9004SE7E4ZNS1SA1RV5K6M2` 暴露出三段身份不一致:第 4 步每个 bad case 只有一份归因报告、只落到一个成员或对象级;第 5 步的簇可以同时含 `code-generator` 与 `codespec-subagent-driven-development` 的来源报告;第 6 步 patch 取全部成员目录的并集,commit 以首成员命名。提出人预期的是:一个 bad case 可以同时归因到多个成员、每个成员各有一份报告;不同成员的问题不聚成一类;patch 只修改该簇的成员。

旧模型不是数据损坏:`probe_reports.member_id` 与 manifest 已能表达成员,但归因 runner 只构造一个 input、候选只有一个 `probe_id` 指针,聚类键不含成员,patch 也不知道簇成员。

## Decision

- 归因按候选成员 fan-out:self case 只归上报成员;发现型 case 按该 Session 命中的成员逐成员生成独立报告(`member_id`/`probe_object`/分类/结论/置信度/缓存键)。对象级报告只在候选集合为空时兜底;单成员 run 保持唯一成员兼容路径。
- 新增 run 级 `evolution_run_candidate_probes` 关联记录全部报告;`evolution_run_candidates.probe_id` 只写首个报告,不再被后续成员覆盖。第 4 步从关联读取全部报告并按 case 分组。
- 聚类键加入成员:draft/簇带 `member_id`;LLM 审查校验禁止跨成员合并,超限分批也按 `(type, member)`;降级桶同样按成员。`probe_clusters.member_id` 持久化(migration 0044)。
- patch 继承簇成员:`CandidateTrace.member` 由簇成员解析,`allowed_paths` 只含该成员 `sub_dir`,prompt 与 commit 写该成员;对象级保留并集兜底;跨成员修改拆成不同成员簇/轮次。
- 前端按原型:第 4 步 case rowspan 多报告、第 5 步成员分组单成员簇、第 6 步成员作用域与改动范围。
- 历史 `member_id=null` 不重写;历史混合簇仍按对象级并集渲染。

## Alternatives considered

- **保持对象级 patch,只改 UI 标签**:不能解决 patch 同时改两个成员、commit 归属错误与评测无法按成员解释的问题;否决。
- **只做成员簇与成员 patch,不做归因 fan-out**:簇仍只能看到每个 case 的第一份报告,无法表达“一个 case 属于多个成员”;否决。
- **改 executor 一次返回多成员结论**:需要改 executor 请求/响应契约、Skill 提示词与报告 schema;本轮用逐成员单结论调用,保持契约稳定,成本是 N 次调用;留作后续优化。
- **迁移 `evolution_attribution_inputs` 主键到每报告**:能让 review 逐报告冻结,但涉及 review UI 与历史兼容;本轮 review 输入保持 case 级,二次成员报告通过 run 关联进入聚类,step 4 仍展示全部报告;逐报告 review 留作后续。
- **给簇/轮次增加独立 `member_id` 列**:簇已有 migration 0044;round 通过簇继承,不重复存储。

## Consequences

新 run 的发现型 case 会按 Session 命中成员产出多份报告,step 4 行数增加;同一 case 可进入多个成员簇,step 5/6 的簇数与轮次数可能增加。归因调用数随候选成员数增长,单成员/历史缓存键与路径保持不变。

本轮如实保留两个限制:review 冻结输入仍是 case 级(二次报告不能单独排除,只能随 case 一起纳入/移出);历史混合簇没有成员,仍走对象级并集 patch,不会自动拆分。评测仍是整个 run 一个分数,不按成员单独出分。

实现:`apps/api/app/service/evolution/{attribution,cluster,cluster_llm,prepare,patch_source,git_candidate,stages}.py`、`apps/api/alembic/versions/0044_run_candidate_probes_member.py`、`apps/web/src/pages/evolution/components/{StepAttribution,StepClusters,StepIterations}.vue`;测试见 `apps/api/tests/attribution/test_object_level_attribution.py`、`tests/evolution/test_cluster_attribution_drafts.py`、`apps/api/tests/test_agent_edit_source.py`。
143 changes: 143 additions & 0 deletions apps/api/alembic/versions/0044_run_candidate_probes_member.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
"""Record the member of a cluster and every report a run candidate consumed.

Issue #814 needs two persisted facts that the v2 schema does not carry:

* ``probe_clusters.member_id`` names the member a cluster belongs to. It stays
nullable because object-level clusters and historical rows have no member.
* ``evolution_run_candidate_probes`` links a run candidate to every report the
run consumed. A candidate can now own one report per member, while the legacy
single ``probe_id`` pointer stays for one compatibility window.

Revision ID: 0044
Revises: 0043
Create Date: 2026-12-05
"""

from __future__ import annotations

import sqlalchemy as sa
from sqlalchemy import inspect

from alembic import op

revision: str = "0044"
down_revision: str | None = "0043"
branch_labels: str | None = None
depends_on: str | None = None

CLUSTERS = "probe_clusters"
RUN_PROBES = "evolution_run_candidate_probes"


def _has_table(bind: object, table: str) -> bool:
"""Return whether the named table exists on the current connection."""
return inspect(bind).has_table(table)


def _columns(bind: object, table: str) -> set[str]:
"""Return the reflected column names of an existing table."""
return {str(column["name"]) for column in inspect(bind).get_columns(table)}


def _indexes(bind: object, table: str) -> set[str]:
"""Return the reflected index names of an existing table."""
return {
str(index["name"])
for index in inspect(bind).get_indexes(table)
if index["name"] is not None
}


def upgrade() -> None:
"""Add the nullable cluster member and the run-report membership table."""
bind = op.get_bind()
if _has_table(bind, CLUSTERS) and "member_id" not in _columns(bind, CLUSTERS):
with op.batch_alter_table(CLUSTERS) as batch_op:
batch_op.add_column(sa.Column("member_id", sa.String(36), nullable=True))
if _has_table(bind, RUN_PROBES):
return
constraints: list[object] = [
sa.ForeignKeyConstraint(
["run_id"],
["evolution_runs.id"],
name="fk_evolution_run_candidate_probes_run",
ondelete="CASCADE",
),
]
# External tables may be created later by their owner; the runtime upgrade
# runs with bootstrap_external_tables=False, so only reference tables that
# actually exist (same convention as migration 0006/0020).
if _has_table(bind, "bad_cases"):
constraints.append(
sa.ForeignKeyConstraint(
["bad_case_id"],
["bad_cases.bad_case_id"],
name="fk_evolution_run_candidate_probes_case",
ondelete="CASCADE",
),
)
if _has_table(bind, "probe_reports"):
constraints.append(
sa.ForeignKeyConstraint(
["probe_id"],
["probe_reports.probe_id"],
name="fk_evolution_run_candidate_probes_probe",
),
)
op.create_table(
RUN_PROBES,
sa.Column(
"id",
sa.BigInteger().with_variant(sa.Integer(), "sqlite"),
primary_key=True,
autoincrement=True,
),
sa.Column("run_id", sa.String(36), nullable=False),
sa.Column("bad_case_id", sa.String(64), nullable=False),
sa.Column("probe_id", sa.String(64), nullable=False),
sa.Column("member_id", sa.String(36), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
*constraints,
sa.UniqueConstraint(
"run_id",
"bad_case_id",
"probe_id",
name="uq_evolution_run_candidate_probes_triple",
),
sa.UniqueConstraint(
"run_id",
"bad_case_id",
"member_id",
name="uq_evolution_run_candidate_probes_case_member",
),
)
op.create_index(
"ix_evolution_run_candidate_probes_run_case",
RUN_PROBES,
["run_id", "bad_case_id"],
unique=False,
)
op.create_index(
"ix_evolution_run_candidate_probes_probe",
RUN_PROBES,
["probe_id"],
unique=False,
)


def downgrade() -> None:
"""Drop the run-report membership table and the cluster member column."""
bind = op.get_bind()
if _has_table(bind, RUN_PROBES):
for name in (
"ix_evolution_run_candidate_probes_probe",
"ix_evolution_run_candidate_probes_run_case",
):
if name in _indexes(bind, RUN_PROBES):
op.drop_index(name, table_name=RUN_PROBES)
op.drop_table(RUN_PROBES)
if _has_table(bind, CLUSTERS) and "member_id" in _columns(bind, CLUSTERS):
if bind.dialect.name == "mysql": # type: ignore[attr-defined]
op.drop_column(CLUSTERS, "member_id")
else:
op.execute(sa.text(f'ALTER TABLE "{CLUSTERS}" DROP COLUMN "member_id"'))
1 change: 1 addition & 0 deletions apps/api/app/db/crud/attribution_reviews.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@ async def cluster_inputs(self, run_id: str) -> tuple[ClusterableProbe, ...]:
row["record"]["attribute_type"] or "error",
row["bad_case_id"],
row["record"]["probe_description"],
row["record"].get("member_id"),
)
for row in await self.inputs(run_id)
if not row["excluded"] and row["record"]["conclusion"] == "attributed"
Expand Down
Loading
Loading