From 4b9ec5d1db5688f03d2e28223c5f4b8c417bed27 Mon Sep 17 00:00:00 2001 From: haley <710872687@qq.com> Date: Tue, 24 Nov 2026 17:35:38 +0800 Subject: [PATCH 01/17] feat(db): add workspace badcase assignments (#582) --- .../0032_workspace_bad_case_labels.py | 118 +++++++++++++++++ apps/api/app/db/models/domain.py | 33 +++++ .../test_migration.py | 121 +++++++++++++++++- .../workspaces/test_bad_case_assignments.py | 18 +++ 4 files changed, 289 insertions(+), 1 deletion(-) create mode 100644 apps/api/alembic/versions/0032_workspace_bad_case_labels.py create mode 100644 apps/api/tests/workspaces/test_bad_case_assignments.py diff --git a/apps/api/alembic/versions/0032_workspace_bad_case_labels.py b/apps/api/alembic/versions/0032_workspace_bad_case_labels.py new file mode 100644 index 00000000..62792a69 --- /dev/null +++ b/apps/api/alembic/versions/0032_workspace_bad_case_labels.py @@ -0,0 +1,118 @@ +"""Add label rules and explicit workspace badcase assignments.""" + +from __future__ import annotations + +import sqlalchemy as sa +from sqlalchemy import inspect + +from alembic import op + +revision = "0032" +down_revision = "0031" + + +def upgrade() -> None: + """Create routing tables and preserve every legacy workspace owner.""" + bind = op.get_bind() + inspector = inspect(bind) + + if inspector.has_table("bad_cases"): + bad_case_columns = { + str(column["name"]) for column in inspector.get_columns("bad_cases") + } + if "catalog_label" not in bad_case_columns: + with op.batch_alter_table("bad_cases") as batch_op: + batch_op.add_column(sa.Column("catalog_label", sa.String(128))) + batch_op.create_index( + "ix_bad_cases_catalog_label", + ["catalog_label"], + unique=False, + ) + + if not inspector.has_table("workspace_bad_case_labels"): + op.create_table( + "workspace_bad_case_labels", + sa.Column("workspace_id", sa.String(36), nullable=False), + sa.Column("label", sa.String(128), nullable=False), + sa.Column("created_at", sa.DateTime(timezone=True), nullable=False), + sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False), + sa.ForeignKeyConstraint( + ["workspace_id"], + ["workspaces.id"], + ondelete="CASCADE", + ), + sa.PrimaryKeyConstraint("workspace_id", "label"), + ) + op.create_index( + "ix_workspace_bad_case_labels_label", + "workspace_bad_case_labels", + ["label"], + unique=False, + ) + + if not inspector.has_table("workspace_bad_cases"): + op.create_table( + "workspace_bad_cases", + sa.Column("workspace_id", sa.String(36), nullable=False), + sa.Column("bad_case_id", sa.String(64), nullable=False), + sa.Column("assignment_source", sa.String(24), nullable=False), + sa.Column("label", sa.String(128), nullable=True), + sa.Column("assigned_at", sa.DateTime(timezone=True), nullable=False), + sa.ForeignKeyConstraint( + ["workspace_id"], + ["workspaces.id"], + ondelete="CASCADE", + ), + sa.ForeignKeyConstraint( + ["bad_case_id"], + ["bad_cases.bad_case_id"], + ondelete="CASCADE", + ), + sa.PrimaryKeyConstraint( + "workspace_id", + "bad_case_id", + "assignment_source", + ), + ) + op.create_index( + "ix_workspace_bad_cases_bad_case", + "workspace_bad_cases", + ["bad_case_id"], + unique=False, + ) + op.create_index( + "ix_workspace_bad_cases_label", + "workspace_bad_cases", + ["label"], + unique=False, + ) + + inspector = inspect(bind) + if inspector.has_table("bad_cases") and inspector.has_table("workspace_bad_cases"): + op.execute( + sa.text( + """ + INSERT INTO workspace_bad_cases ( + workspace_id, bad_case_id, assignment_source, label, assigned_at + ) + SELECT workspace_id, bad_case_id, 'legacy_owner', NULL, CURRENT_TIMESTAMP + FROM bad_cases + WHERE workspace_id IS NOT NULL + """, + ), + ) + + +def downgrade() -> None: + """Remove routing state without deleting canonical badcase facts.""" + inspector = inspect(op.get_bind()) + if inspector.has_table("workspace_bad_cases"): + op.drop_table("workspace_bad_cases") + if inspector.has_table("workspace_bad_case_labels"): + op.drop_table("workspace_bad_case_labels") + if inspector.has_table("bad_cases"): + columns = {str(column["name"]) for column in inspector.get_columns("bad_cases")} + if "catalog_label" in columns: + with op.batch_alter_table("bad_cases") as batch_op: + batch_op.drop_index("ix_bad_cases_catalog_label") + batch_op.drop_column("catalog_label") diff --git a/apps/api/app/db/models/domain.py b/apps/api/app/db/models/domain.py index c7bd4f57..5d121f35 100644 --- a/apps/api/app/db/models/domain.py +++ b/apps/api/app/db/models/domain.py @@ -311,6 +311,7 @@ Column("title", String(255), nullable=False), Column("bad_case_description", Text, nullable=False), Column("meta_data", JSON, nullable=True), + Column("catalog_label", String(128), nullable=True), Column("source", String(64), nullable=True), Column("session_source", JSON, nullable=True), Column("created_at", DateTime(timezone=True), nullable=False), @@ -326,6 +327,38 @@ ), Index("ix_bad_cases_workspace_object", "workspace_id", "object_name"), Index("ix_bad_cases_workspace_type", "workspace_id", "bad_case_type"), + Index("ix_bad_cases_catalog_label", "catalog_label"), +) + + +workspace_bad_case_labels = Table( + "workspace_bad_case_labels", + DOMAIN_METADATA, + # The migration owns the cross-metadata workspace foreign key. + Column("workspace_id", String(36), primary_key=True), + Column("label", String(128), primary_key=True), + Column("created_at", DateTime(timezone=True), nullable=False), + Column("updated_at", DateTime(timezone=True), nullable=False), + Index("ix_workspace_bad_case_labels_label", "label"), +) + + +workspace_bad_cases = Table( + "workspace_bad_cases", + DOMAIN_METADATA, + # The migration owns the cross-metadata workspace foreign key. + Column("workspace_id", String(36), primary_key=True), + Column( + "bad_case_id", + String(64), + ForeignKey("bad_cases.bad_case_id", ondelete="CASCADE"), + primary_key=True, + ), + Column("assignment_source", String(24), primary_key=True), + Column("label", String(128), nullable=True), + Column("assigned_at", DateTime(timezone=True), nullable=False), + Index("ix_workspace_bad_cases_bad_case", "bad_case_id"), + Index("ix_workspace_bad_cases_label", "label"), ) diff --git a/apps/api/tests/m6-16-bad-case-catalog-sync/test_migration.py b/apps/api/tests/m6-16-bad-case-catalog-sync/test_migration.py index 072428b7..3095e097 100644 --- a/apps/api/tests/m6-16-bad-case-catalog-sync/test_migration.py +++ b/apps/api/tests/m6-16-bad-case-catalog-sync/test_migration.py @@ -2,13 +2,17 @@ from __future__ import annotations +import asyncio from pathlib import Path import pytest +from alembic.config import Config from pydantic import SecretStr from sqlalchemy import inspect, text +from alembic import command from app.config import DatabaseDialect, Settings +from app.db.base import Database from app.db.factory import create_database from app.db.migrate import upgrade_database @@ -64,6 +68,121 @@ async def test_upgrade_creates_catalog_sync_table(tmp_path: Path) -> None: assert exists is True assert columns == EXPECTED_COLUMNS assert primary_key == ["id"] - assert revision == "0031" + assert revision == "0032" + finally: + await database.dispose() + + +def _alembic_config(database: Database) -> Config: + """Build a config for exercising the 0031 → head data migration.""" + config = Config(str(Path(__file__).resolve().parents[2] / "alembic.ini")) + config.set_main_option("sqlalchemy.url", database.url.replace("%", "%%")) + config.attributes["bootstrap_external_tables"] = True + return config + + +@pytest.mark.asyncio +async def test_upgrade_backfills_workspace_bad_case_assignments(tmp_path: Path) -> None: + """A legacy badcase remains visible through an explicit legacy-owner row.""" + settings = Settings( + db_dialect=DatabaseDialect.SQLITE, + data_dir=tmp_path, + jwt_secret=SecretStr("workspace-assignment-migration-secret"), + ) + database = create_database(settings) + await database.start() + try: + await asyncio.to_thread(command.upgrade, _alembic_config(database), "0031") + async with database.session() as session: + await session.execute( + text( + """ + INSERT INTO bad_cases ( + bad_case_id, workspace_id, bad_case_session_id, bad_case_type, + object_name, object_type, title, bad_case_description, + created_at, updated_at + ) VALUES ( + 'legacy-case', 'ws-default', 'session-1', 'skill', + 'review', 'skill', 'Legacy', 'Legacy case', + CURRENT_TIMESTAMP, CURRENT_TIMESTAMP + ) + """, + ), + ) + await session.commit() + + await upgrade_database(database) + + async with database.engine.connect() as connection: + schema = await connection.run_sync( + lambda sync_connection: { + "bad_case_columns": { + str(column["name"]) + for column in inspect(sync_connection).get_columns("bad_cases") + }, + "label_columns": { + str(column["name"]) + for column in inspect(sync_connection).get_columns( + "workspace_bad_case_labels", + ) + }, + "assignment_columns": { + str(column["name"]) + for column in inspect(sync_connection).get_columns( + "workspace_bad_cases", + ) + }, + "assignment_pk": inspect(sync_connection).get_pk_constraint( + "workspace_bad_cases", + )["constrained_columns"], + "assignment_fks": { + tuple(foreign_key["constrained_columns"]) + for foreign_key in inspect(sync_connection).get_foreign_keys( + "workspace_bad_cases", + ) + }, + "bad_case_indexes": { + index["name"] + for index in inspect(sync_connection).get_indexes("bad_cases") + }, + }, + ) + async with database.session() as session: + assignment = ( + await session.execute( + text( + "SELECT workspace_id, bad_case_id, assignment_source, label " + "FROM workspace_bad_cases WHERE bad_case_id = 'legacy-case'", + ), + ) + ).one() + + assert "catalog_label" in schema["bad_case_columns"] + assert schema["label_columns"] == { + "workspace_id", + "label", + "created_at", + "updated_at", + } + assert schema["assignment_columns"] == { + "workspace_id", + "bad_case_id", + "assignment_source", + "label", + "assigned_at", + } + assert schema["assignment_pk"] == [ + "workspace_id", + "bad_case_id", + "assignment_source", + ] + assert schema["assignment_fks"] == {("workspace_id",), ("bad_case_id",)} + assert "ix_bad_cases_catalog_label" in schema["bad_case_indexes"] + assert tuple(assignment) == ( + "ws-default", + "legacy-case", + "legacy_owner", + None, + ) finally: await database.dispose() diff --git a/apps/api/tests/workspaces/test_bad_case_assignments.py b/apps/api/tests/workspaces/test_bad_case_assignments.py new file mode 100644 index 00000000..d956eec7 --- /dev/null +++ b/apps/api/tests/workspaces/test_bad_case_assignments.py @@ -0,0 +1,18 @@ +"""Published SQLAlchemy tables for workspace badcase assignment.""" + +from app.db.models.domain import DOMAIN_METADATA, bad_cases + + +def test_domain_metadata_declares_workspace_assignment_tables() -> None: + """Fixture bootstrap includes both rule and assignment relations.""" + labels = DOMAIN_METADATA.tables["workspace_bad_case_labels"] + assignments = DOMAIN_METADATA.tables["workspace_bad_cases"] + + assert "catalog_label" in bad_cases.c + assert tuple(labels.primary_key.columns.keys()) == ("workspace_id", "label") + assert tuple(assignments.primary_key.columns.keys()) == ( + "workspace_id", + "bad_case_id", + "assignment_source", + ) + assert assignments.c.bad_case_id.references(bad_cases.c.bad_case_id) From 31af0b5254f6274d63a40753e35243aa4287bb30 Mon Sep 17 00:00:00 2001 From: haley <710872687@qq.com> Date: Tue, 24 Nov 2026 20:54:07 +0800 Subject: [PATCH 02/17] feat(api): configure workspace badcase labels (#582) --- .../0032_workspace_bad_case_labels.py | 4 +- apps/api/app/api/workspaces.py | 45 +++++ .../app/db/crud/workspace_bad_case_labels.py | 149 ++++++++++++++ apps/api/app/main.py | 6 + .../app/service/workspaces/bad_case_labels.py | 48 +++++ apps/api/app/service/workspaces/schemas.py | 28 ++- .../test_migration.py | 3 +- .../workspaces/test_bad_case_labels_api.py | 184 ++++++++++++++++++ .../test_bad_case_labels_service.py | 90 +++++++++ 9 files changed, 551 insertions(+), 6 deletions(-) create mode 100644 apps/api/app/db/crud/workspace_bad_case_labels.py create mode 100644 apps/api/app/service/workspaces/bad_case_labels.py create mode 100644 apps/api/tests/workspaces/test_bad_case_labels_api.py create mode 100644 apps/api/tests/workspaces/test_bad_case_labels_service.py diff --git a/apps/api/alembic/versions/0032_workspace_bad_case_labels.py b/apps/api/alembic/versions/0032_workspace_bad_case_labels.py index 62792a69..de829867 100644 --- a/apps/api/alembic/versions/0032_workspace_bad_case_labels.py +++ b/apps/api/alembic/versions/0032_workspace_bad_case_labels.py @@ -17,9 +17,7 @@ def upgrade() -> None: inspector = inspect(bind) if inspector.has_table("bad_cases"): - bad_case_columns = { - str(column["name"]) for column in inspector.get_columns("bad_cases") - } + bad_case_columns = {str(column["name"]) for column in inspector.get_columns("bad_cases")} if "catalog_label" not in bad_case_columns: with op.batch_alter_table("bad_cases") as batch_op: batch_op.add_column(sa.Column("catalog_label", sa.String(128))) diff --git a/apps/api/app/api/workspaces.py b/apps/api/app/api/workspaces.py index 1dddb935..ffcde493 100644 --- a/apps/api/app/api/workspaces.py +++ b/apps/api/app/api/workspaces.py @@ -10,8 +10,11 @@ from app.db.models.users import UserRecord from app.errors import AppError, ErrorCode, ErrorResponse from app.service.identity.principals import Principal +from app.service.workspaces.bad_case_labels import WorkspaceBadCaseLabelService from app.service.workspaces.schemas import ( Workspace, + WorkspaceBadCaseLabelConfiguration, + WorkspaceBadCaseLabelRequest, WorkspaceCreateRequest, WorkspaceCredentialCreated, WorkspaceCredentialListResponse, @@ -38,6 +41,11 @@ def workspaces_from(request: Request) -> WorkspaceService: return cast(WorkspaceService, request.app.state.workspaces) +def bad_case_labels_from(request: Request) -> WorkspaceBadCaseLabelService: + """Return the application-scoped workspace label service.""" + return cast(WorkspaceBadCaseLabelService, request.app.state.bad_case_labels) + + async def current_user(request: Request) -> UserRecord: """Return the authenticated user row for the current principal.""" principal = cast(Principal, request.state.principal) @@ -110,6 +118,43 @@ async def update_workspace( return await workspaces_from(request).update_workspace(access, body) +@router.get( + "/{wid}/bad-case-labels", + dependencies=[Security(BEARER_AUTH)], + responses={ + 401: {"model": ErrorResponse, "description": "Authentication is required"}, + 404: {"model": ErrorResponse, "description": "Workspace does not exist"}, + }, +) +async def get_bad_case_labels( + wid: WorkspaceId, + request: Request, + access: Annotated[WorkspaceAccess, Depends(require_workspace_role("viewer"))], +) -> WorkspaceBadCaseLabelConfiguration: + """Return the public badcase labels accepted by this workspace.""" + return await bad_case_labels_from(request).get(access.workspace_id) + + +@router.put( + "/{wid}/bad-case-labels", + dependencies=[Security(BEARER_AUTH)], + responses={ + 401: {"model": ErrorResponse, "description": "Authentication is required"}, + 403: {"model": ErrorResponse, "description": "Workspace role is insufficient"}, + 404: {"model": ErrorResponse, "description": "Workspace does not exist"}, + 422: {"model": ErrorResponse, "description": "Label set is invalid"}, + }, +) +async def replace_bad_case_labels( + wid: WorkspaceId, + body: WorkspaceBadCaseLabelRequest, + request: Request, + access: Annotated[WorkspaceAccess, Depends(require_workspace_role("space_admin"))], +) -> WorkspaceBadCaseLabelConfiguration: + """Replace label rules and historical catalog assignments atomically.""" + return await bad_case_labels_from(request).replace(access.workspace_id, body.items) + + @router.get( "/{wid}/members", dependencies=[Security(BEARER_AUTH)], diff --git a/apps/api/app/db/crud/workspace_bad_case_labels.py b/apps/api/app/db/crud/workspace_bad_case_labels.py new file mode 100644 index 00000000..962bdfaf --- /dev/null +++ b/apps/api/app/db/crud/workspace_bad_case_labels.py @@ -0,0 +1,149 @@ +"""Persistence for workspace label rules and derived badcase assignments.""" + +from collections.abc import Sequence +from dataclasses import dataclass + +from sqlalchemy import delete, func, insert, literal, select + +from app.db.base import Database +from app.db.models.domain import ( + bad_cases, + workspace_bad_case_labels, + workspace_bad_cases, +) +from app.db.models.workspace import workspaces +from app.utils.time import now_shanghai + +CATALOG_ASSIGNMENT_SOURCE = "catalog_label" + + +@dataclass(frozen=True, slots=True) +class WorkspaceBadCaseLabelRecord: + """One complete label configuration and its distinct visible case count.""" + + items: tuple[str, ...] + assigned_bad_case_count: int + + +class WorkspaceBadCaseLabelRepository: + """Atomically replace label rules and their derived historical assignments.""" + + def __init__(self, database: Database) -> None: + """Bind the repository to the application database boundary.""" + self._database = database + + async def get(self, workspace_id: str) -> WorkspaceBadCaseLabelRecord: + """Return sorted rules and the distinct assigned badcase count.""" + async with self._database.session() as session: + labels: list[str] = ( + ( + await session.execute( + select(workspace_bad_case_labels.c.label) + .where(workspace_bad_case_labels.c.workspace_id == workspace_id) + .order_by(workspace_bad_case_labels.c.label), + ) + ) + .scalars() + .all() + ) + assigned_count = int( + ( + await session.execute( + select(func.count(func.distinct(workspace_bad_cases.c.bad_case_id))).where( + workspace_bad_cases.c.workspace_id == workspace_id, + ), + ) + ).scalar_one(), + ) + return WorkspaceBadCaseLabelRecord( + items=tuple(labels), + assigned_bad_case_count=assigned_count, + ) + + async def replace( + self, + workspace_id: str, + labels: Sequence[str], + ) -> WorkspaceBadCaseLabelRecord | None: + """Replace rules and rebuild catalog assignments in one transaction.""" + now = now_shanghai() + async with self._database.transaction() as session: + workspace_exists = ( + await session.execute( + select(workspaces.c.id) + .where(workspaces.c.id == workspace_id) + .with_for_update(), + ) + ).scalar_one_or_none() + if workspace_exists is None: + return None + + await session.execute( + delete(workspace_bad_case_labels).where( + workspace_bad_case_labels.c.workspace_id == workspace_id, + ), + ) + if labels: + await session.execute( + insert(workspace_bad_case_labels), + [ + { + "workspace_id": workspace_id, + "label": label, + "created_at": now, + "updated_at": now, + } + for label in labels + ], + ) + + await session.execute( + delete(workspace_bad_cases).where( + workspace_bad_cases.c.workspace_id == workspace_id, + workspace_bad_cases.c.assignment_source == CATALOG_ASSIGNMENT_SOURCE, + ), + ) + if labels: + matching_cases = ( + select( + literal(workspace_id), + bad_cases.c.bad_case_id, + literal(CATALOG_ASSIGNMENT_SOURCE), + bad_cases.c.catalog_label, + literal(now), + ) + .select_from( + bad_cases.join( + workspace_bad_case_labels, + workspace_bad_case_labels.c.label == bad_cases.c.catalog_label, + ), + ) + .where(workspace_bad_case_labels.c.workspace_id == workspace_id) + ) + await session.execute( + insert(workspace_bad_cases).from_select( + [ + "workspace_id", + "bad_case_id", + "assignment_source", + "label", + "assigned_at", + ], + matching_cases, + ), + ) + + assigned_count = int( + ( + await session.execute( + select(func.count(func.distinct(workspace_bad_cases.c.bad_case_id))).where( + workspace_bad_cases.c.workspace_id == workspace_id, + ), + ) + ).scalar_one(), + ) + + return WorkspaceBadCaseLabelRecord( + items=tuple(labels), + assigned_bad_case_count=assigned_count, + ) diff --git a/apps/api/app/main.py b/apps/api/app/main.py index d16cf4a3..6561ed8e 100644 --- a/apps/api/app/main.py +++ b/apps/api/app/main.py @@ -53,6 +53,7 @@ from app.db.crud.problems import ProblemRepository from app.db.crud.run_events import SqlRunEventStore from app.db.crud.sessions import SessionRepository +from app.db.crud.workspace_bad_case_labels import WorkspaceBadCaseLabelRepository from app.db.crud.workspaces import WorkspaceRepository from app.db.external_contract import ExternalContractMonitor from app.db.factory import create_database @@ -136,6 +137,7 @@ from app.service.overview.targets import TargetOverviewService from app.service.problems.service import ProblemService from app.service.sessions.service import SessionService +from app.service.workspaces.bad_case_labels import WorkspaceBadCaseLabelService from app.service.workspaces.ingest import BadCaseIngestService from app.service.workspaces.service import WorkspaceService from app.third_party_api.ai_agent.base import AIAgentProvider @@ -349,6 +351,9 @@ def create_app( bad_case_sync.source_available, ) workspaces = WorkspaceService(WorkspaceRepository(resolved_database)) + bad_case_labels = WorkspaceBadCaseLabelService( + WorkspaceBadCaseLabelRepository(resolved_database), + ) bad_case_ingest = BadCaseIngestService( BadCaseIngestRepository(resolved_database), workspaces, @@ -734,6 +739,7 @@ async def lifespan(lifespan_app: FastAPI) -> AsyncIterator[None]: app.state.overview = overview app.state.target_overview = target_overview app.state.workspaces = workspaces + app.state.bad_case_labels = bad_case_labels app.state.bad_case_ingest = bad_case_ingest app.state.problems = problems app.state.attribution_read = attribution_read diff --git a/apps/api/app/service/workspaces/bad_case_labels.py b/apps/api/app/service/workspaces/bad_case_labels.py new file mode 100644 index 00000000..1902f9b6 --- /dev/null +++ b/apps/api/app/service/workspaces/bad_case_labels.py @@ -0,0 +1,48 @@ +"""Workspace badcase label configuration rules.""" + +from collections.abc import Sequence + +from app.db.crud.workspace_bad_case_labels import ( + WorkspaceBadCaseLabelRecord, + WorkspaceBadCaseLabelRepository, +) +from app.errors import AppError, ErrorCode +from app.service.workspaces.schemas import WorkspaceBadCaseLabelConfiguration + + +class WorkspaceBadCaseLabelService: + """Expose sorted label resources over atomic repository operations.""" + + def __init__(self, repository: WorkspaceBadCaseLabelRepository) -> None: + """Bind workspace label behavior to its persistence boundary.""" + self._repository = repository + + async def get(self, workspace_id: str) -> WorkspaceBadCaseLabelConfiguration: + """Return one workspace's complete label configuration.""" + return self._to_configuration(await self._repository.get(workspace_id)) + + async def replace( + self, + workspace_id: str, + labels: Sequence[str], + ) -> WorkspaceBadCaseLabelConfiguration: + """Atomically replace a workspace's rules and historical assignments.""" + normalized = tuple(sorted(labels)) + record = await self._repository.replace(workspace_id, normalized) + if record is None: + raise AppError( + status_code=404, + code=ErrorCode.WORKSPACE_NOT_FOUND, + message="workspace was not found", + ) + return self._to_configuration(record) + + @staticmethod + def _to_configuration( + record: WorkspaceBadCaseLabelRecord, + ) -> WorkspaceBadCaseLabelConfiguration: + """Translate a repository record without leaking persistence types.""" + return WorkspaceBadCaseLabelConfiguration( + items=list(record.items), + assigned_bad_case_count=record.assigned_bad_case_count, + ) diff --git a/apps/api/app/service/workspaces/schemas.py b/apps/api/app/service/workspaces/schemas.py index add3e820..d40766ae 100644 --- a/apps/api/app/service/workspaces/schemas.py +++ b/apps/api/app/service/workspaces/schemas.py @@ -2,7 +2,7 @@ from datetime import datetime -from pydantic import BaseModel, ConfigDict, Field +from pydantic import BaseModel, ConfigDict, Field, field_validator from pydantic.alias_generators import to_camel from app.service.identity.schemas import PublicUser @@ -150,3 +150,29 @@ class WorkspaceCredentialCreated(WorkspaceModel): credential_id: str prefix: str credential: str + + +class WorkspaceBadCaseLabelRequest(WorkspaceModel): + """Complete replacement set for one workspace's accepted public labels.""" + + items: list[str] = Field(default_factory=list) + + @field_validator("items") + @classmethod + def validate_items(cls, items: list[str]) -> list[str]: + """Keep exact matching deterministic and reject ambiguous rule sets.""" + if len(items) != len(set(items)): + raise ValueError("labels must be unique") + for label in items: + if not label or len(label) > 128 or label != label.strip(): + raise ValueError( + "labels must be 1-128 characters without surrounding whitespace", + ) + return sorted(items) + + +class WorkspaceBadCaseLabelConfiguration(WorkspaceModel): + """One label rule set plus its current distinct assignment count.""" + + items: list[str] + assigned_bad_case_count: int = Field(ge=0) diff --git a/apps/api/tests/m6-16-bad-case-catalog-sync/test_migration.py b/apps/api/tests/m6-16-bad-case-catalog-sync/test_migration.py index 3095e097..1a7da120 100644 --- a/apps/api/tests/m6-16-bad-case-catalog-sync/test_migration.py +++ b/apps/api/tests/m6-16-bad-case-catalog-sync/test_migration.py @@ -142,8 +142,7 @@ async def test_upgrade_backfills_workspace_bad_case_assignments(tmp_path: Path) ) }, "bad_case_indexes": { - index["name"] - for index in inspect(sync_connection).get_indexes("bad_cases") + index["name"] for index in inspect(sync_connection).get_indexes("bad_cases") }, }, ) diff --git a/apps/api/tests/workspaces/test_bad_case_labels_api.py b/apps/api/tests/workspaces/test_bad_case_labels_api.py new file mode 100644 index 00000000..bd502ca4 --- /dev/null +++ b/apps/api/tests/workspaces/test_bad_case_labels_api.py @@ -0,0 +1,184 @@ +"""Workspace badcase label configuration HTTP contract.""" + +import httpx +from fastapi import FastAPI +from sqlalchemy import insert + +from app.db.models.domain import bad_cases, workspace_bad_cases +from app.utils.time import now_shanghai +from tests.workspaces.helpers import ( + access_token, + bearer, + create_user, + insert_member, + insert_workspace, +) + + +async def _insert_catalog_case( + app: FastAPI, + *, + case_id: str, + label: str | None, +) -> None: + """Insert one canonical public case with its validated label projection.""" + now = now_shanghai() + async with app.state.database.transaction() as session: + await session.execute( + insert(bad_cases).values( + bad_case_id=case_id, + workspace_id="ws-default", + bad_case_session_id=f"session-{case_id}", + bad_case_type="self", + object_name="example-object", + object_type="skill", + title=f"Case {case_id}", + bad_case_description="Public catalog case.", + meta_data={"label": label} if label is not None else {}, + catalog_label=label, + created_at=now, + updated_at=now, + ), + ) + + +async def test_viewers_read_labels_but_only_space_admins_replace_them( + workspace_client: tuple[FastAPI, httpx.AsyncClient], +) -> None: + """The management resource follows the viewer/read and space-admin/write boundary.""" + app, client = workspace_client + database = app.state.database + workspace_id = await insert_workspace(database, name="Label access") + viewer_id = await create_user(database, username="label-viewer") + member_id = await create_user(database, username="label-member") + admin_id = await create_user(database, username="label-admin") + outsider_id = await create_user(database, username="label-outsider") + await insert_member( + database, + workspace_id=workspace_id, + user_id=viewer_id, + role="viewer", + ) + await insert_member( + database, + workspace_id=workspace_id, + user_id=member_id, + role="member", + ) + await insert_member( + database, + workspace_id=workspace_id, + user_id=admin_id, + role="space_admin", + ) + viewer_header = bearer(access_token(app, user_id=viewer_id)) + member_header = bearer(access_token(app, user_id=member_id)) + admin_header = bearer(access_token(app, user_id=admin_id)) + outsider_header = bearer(access_token(app, user_id=outsider_id)) + + initial = await client.get( + f"/api/workspaces/{workspace_id}/bad-case-labels", + headers=viewer_header, + ) + denied = await client.put( + f"/api/workspaces/{workspace_id}/bad-case-labels", + headers=member_header, + json={"items": ["review"]}, + ) + hidden = await client.get( + f"/api/workspaces/{workspace_id}/bad-case-labels", + headers=outsider_header, + ) + saved = await client.put( + f"/api/workspaces/{workspace_id}/bad-case-labels", + headers=admin_header, + json={"items": ["tool-use", "review"]}, + ) + + assert initial.status_code == 200 + assert initial.json() == {"items": [], "assignedBadCaseCount": 0} + assert denied.status_code == 403 + assert denied.json()["error"]["code"] == "WORKSPACE_FORBIDDEN" + assert hidden.status_code == 404 + assert hidden.json()["error"]["code"] == "WORKSPACE_NOT_FOUND" + assert saved.status_code == 200 + assert saved.json() == { + "items": ["review", "tool-use"], + "assignedBadCaseCount": 0, + } + + +async def test_replacement_reassigns_history_to_every_matching_workspace( + workspace_client: tuple[FastAPI, httpx.AsyncClient], +) -> None: + """Exact replacement fans out shared labels and preserves direct ownership.""" + app, client = workspace_client + database = app.state.database + first_workspace = await insert_workspace(database, name="Label first") + second_workspace = await insert_workspace(database, name="Label second") + admin_id = await create_user(database, username="routing-admin", role="admin") + headers = bearer(access_token(app, user_id=admin_id, role="admin")) + await _insert_catalog_case(app, case_id="case-review", label="review") + await _insert_catalog_case(app, case_id="case-tools", label="tool-use") + now = now_shanghai() + async with database.transaction() as session: + await session.execute( + insert(workspace_bad_cases).values( + workspace_id=first_workspace, + bad_case_id="case-review", + assignment_source="direct_ingest", + label=None, + assigned_at=now, + ), + ) + + first = await client.put( + f"/api/workspaces/{first_workspace}/bad-case-labels", + headers=headers, + json={"items": ["tool-use", "review"]}, + ) + second = await client.put( + f"/api/workspaces/{second_workspace}/bad-case-labels", + headers=headers, + json={"items": ["review"]}, + ) + replaced = await client.put( + f"/api/workspaces/{first_workspace}/bad-case-labels", + headers=headers, + json={"items": ["tool-use"]}, + ) + + assert first.json() == { + "items": ["review", "tool-use"], + "assignedBadCaseCount": 2, + } + assert second.json() == { + "items": ["review"], + "assignedBadCaseCount": 1, + } + assert replaced.json() == { + "items": ["tool-use"], + "assignedBadCaseCount": 2, + } + + +async def test_label_request_rejects_duplicates_whitespace_and_oversize( + workspace_client: tuple[FastAPI, httpx.AsyncClient], +) -> None: + """Ambiguous labels never enter the exact-match rule set.""" + app, client = workspace_client + workspace_id = await insert_workspace(app.state.database, name="Label validation") + admin_id = await create_user( + app.state.database, + username="validation-admin", + role="admin", + ) + headers = bearer(access_token(app, user_id=admin_id, role="admin")) + + for items in (["review", "review"], [" review"], ["x" * 129], [""]): + response = await client.put( + f"/api/workspaces/{workspace_id}/bad-case-labels", + headers=headers, + json={"items": items}, + ) + assert response.status_code == 422 diff --git a/apps/api/tests/workspaces/test_bad_case_labels_service.py b/apps/api/tests/workspaces/test_bad_case_labels_service.py new file mode 100644 index 00000000..b62dba88 --- /dev/null +++ b/apps/api/tests/workspaces/test_bad_case_labels_service.py @@ -0,0 +1,90 @@ +"""Atomic workspace label replacement behavior.""" + +import pytest +from fastapi import FastAPI +from sqlalchemy import insert, select, text +from sqlalchemy.exc import IntegrityError + +from app.db.models.domain import ( + bad_cases, + workspace_bad_case_labels, + workspace_bad_cases, +) +from app.utils.time import now_shanghai +from tests.workspaces.helpers import insert_workspace + + +async def test_reconciliation_rolls_back_rules_and_assignments_together( + workspace_client: tuple[FastAPI, object], +) -> None: + """A failed association rebuild cannot publish the replacement rule set.""" + app, _client = workspace_client + database = app.state.database + workspace_id = await insert_workspace(database, name="Atomic labels") + now = now_shanghai() + async with database.transaction() as session: + await session.execute( + insert(bad_cases).values( + bad_case_id="atomic-case", + workspace_id="ws-default", + bad_case_session_id="session-atomic", + bad_case_type="self", + object_name="review", + object_type="skill", + title="Atomic", + bad_case_description="Atomic replacement fixture.", + catalog_label="new-label", + created_at=now, + updated_at=now, + ), + ) + await session.execute( + insert(workspace_bad_case_labels).values( + workspace_id=workspace_id, + label="old-label", + created_at=now, + updated_at=now, + ), + ) + await session.execute( + text( + """ + CREATE TRIGGER reject_catalog_assignment + BEFORE INSERT ON workspace_bad_cases + WHEN NEW.assignment_source = 'catalog_label' + BEGIN + SELECT RAISE(ABORT, 'reconciliation failed'); + END + """, + ), + ) + + with pytest.raises(IntegrityError): + await app.state.bad_case_labels.replace(workspace_id, ["new-label"]) + + async with database.session() as session: + labels = ( + ( + await session.execute( + select(workspace_bad_case_labels.c.label).where( + workspace_bad_case_labels.c.workspace_id == workspace_id, + ), + ) + ) + .scalars() + .all() + ) + assignments = ( + ( + await session.execute( + select(workspace_bad_cases.c.bad_case_id).where( + workspace_bad_cases.c.workspace_id == workspace_id, + ), + ) + ) + .scalars() + .all() + ) + + assert labels == ["old-label"] + assert assignments == [] From 7e6d4107390cc23f7c5ee81e9580b8b770d9b7be Mon Sep 17 00:00:00 2001 From: haley <710872687@qq.com> Date: Tue, 24 Nov 2026 21:02:41 +0800 Subject: [PATCH 03/17] feat(sync): route public badcases by label (#582) --- .../0032_workspace_bad_case_labels.py | 44 +++++ apps/api/app/api/acquisition.py | 6 + apps/api/app/db/crud/bad_case_catalog_sync.py | 91 +++++++++- apps/api/app/db/models/domain.py | 5 + .../acquisition/bad_case_catalog_sync.py | 13 ++ .../bad_case_catalog_sync_coordinator.py | 12 ++ .../test_catalog_status_api.py | 9 + .../test_catalog_sync_repository.py | 166 +++++++++++++++++- .../test_catalog_sync_service.py | 101 ++++++++++- .../test_migration.py | 5 + 10 files changed, 443 insertions(+), 9 deletions(-) diff --git a/apps/api/alembic/versions/0032_workspace_bad_case_labels.py b/apps/api/alembic/versions/0032_workspace_bad_case_labels.py index de829867..34b520cc 100644 --- a/apps/api/alembic/versions/0032_workspace_bad_case_labels.py +++ b/apps/api/alembic/versions/0032_workspace_bad_case_labels.py @@ -21,11 +21,45 @@ def upgrade() -> None: if "catalog_label" not in bad_case_columns: with op.batch_alter_table("bad_cases") as batch_op: batch_op.add_column(sa.Column("catalog_label", sa.String(128))) + batch_op.add_column( + sa.Column( + "catalog_synced", + sa.Boolean(), + nullable=False, + server_default=sa.text("0"), + ), + ) batch_op.create_index( "ix_bad_cases_catalog_label", ["catalog_label"], unique=False, ) + batch_op.create_index( + "ix_bad_cases_catalog_synced", + ["catalog_synced"], + unique=False, + ) + + if inspector.has_table("bad_case_catalog_sync"): + sync_columns = { + str(column["name"]) for column in inspector.get_columns("bad_case_catalog_sync") + } + missing_sync_columns = [ + name + for name in ("assigned_count", "unassigned_count", "invalid_label_count") + if name not in sync_columns + ] + if missing_sync_columns: + with op.batch_alter_table("bad_case_catalog_sync") as batch_op: + for name in missing_sync_columns: + batch_op.add_column( + sa.Column( + name, + sa.Integer(), + nullable=False, + server_default="0", + ), + ) if not inspector.has_table("workspace_bad_case_labels"): op.create_table( @@ -104,6 +138,14 @@ def upgrade() -> None: def downgrade() -> None: """Remove routing state without deleting canonical badcase facts.""" inspector = inspect(op.get_bind()) + if inspector.has_table("bad_case_catalog_sync"): + sync_columns = { + str(column["name"]) for column in inspector.get_columns("bad_case_catalog_sync") + } + with op.batch_alter_table("bad_case_catalog_sync") as batch_op: + for name in ("invalid_label_count", "unassigned_count", "assigned_count"): + if name in sync_columns: + batch_op.drop_column(name) if inspector.has_table("workspace_bad_cases"): op.drop_table("workspace_bad_cases") if inspector.has_table("workspace_bad_case_labels"): @@ -112,5 +154,7 @@ def downgrade() -> None: columns = {str(column["name"]) for column in inspector.get_columns("bad_cases")} if "catalog_label" in columns: with op.batch_alter_table("bad_cases") as batch_op: + batch_op.drop_index("ix_bad_cases_catalog_synced") batch_op.drop_index("ix_bad_cases_catalog_label") + batch_op.drop_column("catalog_synced") batch_op.drop_column("catalog_label") diff --git a/apps/api/app/api/acquisition.py b/apps/api/app/api/acquisition.py index 85279195..17047e84 100644 --- a/apps/api/app/api/acquisition.py +++ b/apps/api/app/api/acquisition.py @@ -75,6 +75,9 @@ class BadCaseCatalogSyncSummary(IdentityModel): synced: int unsynced: int + assigned: int + unassigned: int + invalid_label: int last_bad_case_id: int status: Literal["unavailable", "idle", "queued", "running", "failed"] last_run_at: datetime | None @@ -199,6 +202,9 @@ def _status_response( bad_case_catalog_sync=BadCaseCatalogSyncSummary( synced=catalog_sync.synced, unsynced=catalog_sync.unsynced, + assigned=catalog_sync.assigned, + unassigned=catalog_sync.unassigned, + invalid_label=catalog_sync.invalid_label, last_bad_case_id=catalog_sync.last_bad_case_id, status=catalog_sync.status, last_run_at=catalog_sync.last_run_at, diff --git a/apps/api/app/db/crud/bad_case_catalog_sync.py b/apps/api/app/db/crud/bad_case_catalog_sync.py index 4aced6f2..601bdd29 100644 --- a/apps/api/app/db/crud/bad_case_catalog_sync.py +++ b/apps/api/app/db/crud/bad_case_catalog_sync.py @@ -8,14 +8,19 @@ from datetime import datetime from typing import Any -from sqlalchemy import func, insert, select, update +from sqlalchemy import delete, func, insert, literal, select, update from sqlalchemy.dialects.mysql import insert as mysql_insert from sqlalchemy.dialects.sqlite import insert as sqlite_insert from sqlalchemy.engine import RowMapping from sqlalchemy.exc import OperationalError, ProgrammingError from app.db.base import Database -from app.db.models.domain import bad_case_catalog_sync, bad_cases +from app.db.models.domain import ( + bad_case_catalog_sync, + bad_cases, + workspace_bad_case_labels, + workspace_bad_cases, +) logger = logging.getLogger(__name__) @@ -32,6 +37,8 @@ "title", "bad_case_description", "meta_data", + "catalog_label", + "catalog_synced", "source", "created_at", "updated_at", @@ -56,6 +63,7 @@ class CatalogCaseRow: created_at: datetime updated_at: datetime trigger_line: int | None = None + catalog_label: str | None = None @dataclass(frozen=True, slots=True) @@ -65,6 +73,9 @@ class CatalogSyncState: last_bad_case_id: int synced_count: int pending_count: int + assigned_count: int + unassigned_count: int + invalid_label_count: int status: str attempts: int last_error: str | None @@ -86,6 +97,9 @@ def _state(row: RowMapping) -> CatalogSyncState: last_bad_case_id=int(row["last_bad_case_id"]), synced_count=int(row["synced_count"]), pending_count=int(row["pending_count"]), + assigned_count=int(row["assigned_count"]), + unassigned_count=int(row["unassigned_count"]), + invalid_label_count=int(row["invalid_label_count"]), status=str(row["status"]), attempts=int(row["attempts"]), last_error=(str(row["last_error"]) if row["last_error"] is not None else None), @@ -108,6 +122,8 @@ def _values(row: CatalogCaseRow) -> dict[str, Any]: "title": row.title, "bad_case_description": row.description, "meta_data": row.meta_data, + "catalog_label": row.catalog_label, + "catalog_synced": True, "source": row.source, "created_at": row.created_at, "updated_at": row.updated_at, @@ -158,6 +174,9 @@ async def initialize(self, now: datetime) -> CatalogSyncState: last_bad_case_id=0, synced_count=0, pending_count=0, + assigned_count=0, + unassigned_count=0, + invalid_label_count=0, status="idle", attempts=0, last_error=None, @@ -250,10 +269,69 @@ async def commit_page( ) if values: await session.execute(self._upsert_statement(values)) + await session.execute( + delete(workspace_bad_cases).where( + workspace_bad_cases.c.bad_case_id.in_(ids), + workspace_bad_cases.c.assignment_source.in_( + ("legacy_owner", "catalog_label"), + ), + ), + ) + matching_assignments = ( + select( + workspace_bad_case_labels.c.workspace_id, + bad_cases.c.bad_case_id, + literal("catalog_label"), + bad_cases.c.catalog_label, + literal(now), + ) + .select_from( + bad_cases.join( + workspace_bad_case_labels, + workspace_bad_case_labels.c.label == bad_cases.c.catalog_label, + ), + ) + .where(bad_cases.c.bad_case_id.in_(ids)) + ) + await session.execute( + insert(workspace_bad_cases).from_select( + [ + "workspace_id", + "bad_case_id", + "assignment_source", + "label", + "assigned_at", + ], + matching_assignments, + ), + ) synced = int( ( await session.execute( - select(func.count()).select_from(bad_cases), + select(func.count()) + .select_from(bad_cases) + .where(bad_cases.c.catalog_synced.is_(True)), + ) + ).scalar_one(), + ) + valid = int( + ( + await session.execute( + select(func.count()) + .select_from(bad_cases) + .where( + bad_cases.c.catalog_synced.is_(True), + bad_cases.c.catalog_label.is_not(None), + ), + ) + ).scalar_one(), + ) + assigned = int( + ( + await session.execute( + select(func.count(func.distinct(workspace_bad_cases.c.bad_case_id))).where( + workspace_bad_cases.c.assignment_source == "catalog_label", + ), ) ).scalar_one(), ) @@ -264,6 +342,9 @@ async def commit_page( last_bad_case_id=last_bad_case_id, synced_count=synced, pending_count=pending_count, + assigned_count=assigned, + unassigned_count=max(valid - assigned, 0), + invalid_label_count=max(synced - valid, 0), status="running", updated_at=now, ), @@ -280,7 +361,9 @@ async def count_bad_cases(self) -> int: return int( ( await session.execute( - select(func.count()).select_from(bad_cases), + select(func.count()) + .select_from(bad_cases) + .where(bad_cases.c.catalog_synced.is_(True)), ) ).scalar_one(), ) diff --git a/apps/api/app/db/models/domain.py b/apps/api/app/db/models/domain.py index 5d121f35..21a419d1 100644 --- a/apps/api/app/db/models/domain.py +++ b/apps/api/app/db/models/domain.py @@ -312,6 +312,7 @@ Column("bad_case_description", Text, nullable=False), Column("meta_data", JSON, nullable=True), Column("catalog_label", String(128), nullable=True), + Column("catalog_synced", Boolean, nullable=False, server_default=text("0")), Column("source", String(64), nullable=True), Column("session_source", JSON, nullable=True), Column("created_at", DateTime(timezone=True), nullable=False), @@ -328,6 +329,7 @@ Index("ix_bad_cases_workspace_object", "workspace_id", "object_name"), Index("ix_bad_cases_workspace_type", "workspace_id", "bad_case_type"), Index("ix_bad_cases_catalog_label", "catalog_label"), + Index("ix_bad_cases_catalog_synced", "catalog_synced"), ) @@ -489,6 +491,9 @@ ), Column("synced_count", Integer, nullable=False), Column("pending_count", Integer, nullable=False), + Column("assigned_count", Integer, nullable=False, server_default="0"), + Column("unassigned_count", Integer, nullable=False, server_default="0"), + Column("invalid_label_count", Integer, nullable=False, server_default="0"), Column("status", String(16), nullable=False), Column("attempts", Integer, nullable=False), Column("last_error", Text, nullable=True), diff --git a/apps/api/app/service/acquisition/bad_case_catalog_sync.py b/apps/api/app/service/acquisition/bad_case_catalog_sync.py index d246d867..ecca8d29 100644 --- a/apps/api/app/service/acquisition/bad_case_catalog_sync.py +++ b/apps/api/app/service/acquisition/bad_case_catalog_sync.py @@ -59,6 +59,18 @@ def _object_name(item: BadCaseItem) -> str: return _SOURCE_OBJECT_NAMES.get(source, source or "unknown") +def _catalog_label(meta_data: object) -> str | None: + """Extract one exact valid public catalog label, or reject it as invalid.""" + if not isinstance(meta_data, Mapping): + return None + label = meta_data.get("label") + if not isinstance(label, str): + return None + if not label or len(label) > 128 or label != label.strip(): + return None + return label + + def _row(item: BadCaseItem, fallback: datetime) -> CatalogCaseRow: """Map one upstream item to local column names, defaulting timestamps.""" return CatalogCaseRow( @@ -73,6 +85,7 @@ def _row(item: BadCaseItem, fallback: datetime) -> CatalogCaseRow: title=item.title, description=item.description, meta_data=item.meta_data, + catalog_label=_catalog_label(item.meta_data), source=item.source, created_at=item.created_at or fallback, updated_at=item.updated_at or fallback, diff --git a/apps/api/app/service/acquisition/bad_case_catalog_sync_coordinator.py b/apps/api/app/service/acquisition/bad_case_catalog_sync_coordinator.py index c4a1cf3f..abc2c0f5 100644 --- a/apps/api/app/service/acquisition/bad_case_catalog_sync_coordinator.py +++ b/apps/api/app/service/acquisition/bad_case_catalog_sync_coordinator.py @@ -40,6 +40,9 @@ class CatalogSyncStatus: synced: int unsynced: int + assigned: int + unassigned: int + invalid_label: int last_bad_case_id: int status: SyncStatus last_run_at: datetime | None @@ -154,10 +157,16 @@ async def status(self) -> CatalogSyncStatus: unsynced = state.pending_count if state is not None else 0 last_run_at = state.last_run_at if state is not None else None last_error = state.last_error if state is not None else None + assigned = state.assigned_count if state is not None else 0 + unassigned = state.unassigned_count if state is not None else 0 + invalid_label = state.invalid_label_count if state is not None else 0 if not self.available: return CatalogSyncStatus( synced=synced, unsynced=unsynced, + assigned=assigned, + unassigned=unassigned, + invalid_label=invalid_label, last_bad_case_id=last_bad_case_id, status="unavailable", last_run_at=last_run_at, @@ -173,6 +182,9 @@ async def status(self) -> CatalogSyncStatus: return CatalogSyncStatus( synced=synced, unsynced=unsynced, + assigned=assigned, + unassigned=unassigned, + invalid_label=invalid_label, last_bad_case_id=last_bad_case_id, status=status, last_run_at=last_run_at, diff --git a/apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_status_api.py b/apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_status_api.py index fba5cfa5..6e49b3e5 100644 --- a/apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_status_api.py +++ b/apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_status_api.py @@ -169,6 +169,9 @@ async def test_status_reports_catalog_and_analysis_progress( assert catalog["lastBadCaseId"] == 2 assert catalog["status"] == "idle" assert catalog["lastError"] is None + assert catalog["assigned"] == 0 + assert catalog["unassigned"] == 0 + assert catalog["invalidLabel"] == 2 assert payload["badCaseAnalysis"] == { "total": 2, "analyzed": 0, @@ -224,6 +227,9 @@ async def test_status_reports_unavailable_without_catalog_source( "status": "unavailable", "lastRunAt": None, "lastError": None, + "assigned": 0, + "unassigned": 0, + "invalidLabel": 0, } assert payload["badCaseAnalysis"] == { "total": 0, @@ -266,4 +272,7 @@ async def test_empty_catalog_finishes_without_error(tmp_path: Path) -> None: assert catalog["unsynced"] == 0 assert catalog["lastBadCaseId"] == 0 assert catalog["lastError"] is None + assert catalog["assigned"] == 0 + assert catalog["unassigned"] == 0 + assert catalog["invalidLabel"] == 0 assert payload["badCaseAnalysis"]["total"] == 0 diff --git a/apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_sync_repository.py b/apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_sync_repository.py index cc003825..e0b48a7b 100644 --- a/apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_sync_repository.py +++ b/apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_sync_repository.py @@ -9,7 +9,8 @@ import pytest import pytest_asyncio from pydantic import SecretStr -from sqlalchemy import select +from sqlalchemy import insert, select, text +from sqlalchemy.exc import IntegrityError from app.config import DatabaseDialect, Settings from app.db.base import Database @@ -20,7 +21,13 @@ from app.db.crud.bad_cases import BadCaseRepository from app.db.factory import create_database from app.db.migrate import upgrade_database -from app.db.models.domain import bad_case_analysis, bad_cases +from app.db.models.domain import ( + bad_case_analysis, + bad_cases, + workspace_bad_case_labels, + workspace_bad_cases, +) +from app.db.models.workspace import workspaces from app.utils.time import now_shanghai @@ -46,6 +53,7 @@ def _case( *, title: str = "case title", meta_data: Any = None, + catalog_label: str | None = None, ) -> CatalogCaseRow: now = now_shanghai() return CatalogCaseRow( @@ -59,6 +67,7 @@ def _case( title=title, description="description", meta_data=meta_data, + catalog_label=catalog_label, source="test", created_at=now, updated_at=now, @@ -243,3 +252,156 @@ async def test_analysis_progress_counts_statuses(database: Database) -> None: assert progress.pending == 2 assert progress.issue == 1 assert progress.non_issue == 1 + + +@pytest.mark.asyncio +async def test_repeated_page_replaces_stale_catalog_assignment_without_duplicates( + database: Database, +) -> None: + """A retried case converges from its previous label to one exact assignment.""" + repository = BadCaseCatalogSyncRepository(database) + now = now_shanghai() + await repository.initialize(now) + async with database.transaction() as session: + await session.execute( + insert(workspaces).values( + id="ws-route", + name="Route", + mark="R", + quota=10, + status="active", + created_at=now, + updated_at=now, + ), + ) + await session.execute( + insert(workspace_bad_case_labels), + [ + { + "workspace_id": "ws-route", + "label": "old", + "created_at": now, + "updated_at": now, + }, + { + "workspace_id": "ws-route", + "label": "new", + "created_at": now, + "updated_at": now, + }, + ], + ) + + await repository.commit_page( + [_case(1, catalog_label="old")], + last_bad_case_id=1, + pending_count=0, + now=now, + ) + await repository.commit_page( + [_case(1, catalog_label="new")], + last_bad_case_id=1, + pending_count=0, + now=now, + ) + + async with database.session() as session: + assignments = ( + await session.execute( + select( + workspace_bad_cases.c.bad_case_id, + workspace_bad_cases.c.label, + ), + ) + ).all() + assert assignments == [("1", "new")] + + +@pytest.mark.asyncio +async def test_assignment_failure_rolls_back_fact_and_cursor(database: Database) -> None: + """Fact, assignment, counters, and cursor form one page transaction.""" + repository = BadCaseCatalogSyncRepository(database) + now = now_shanghai() + await repository.initialize(now) + async with database.transaction() as session: + await session.execute( + insert(workspaces).values( + id="ws-reject", + name="Reject", + mark="R", + quota=10, + status="active", + created_at=now, + updated_at=now, + ), + ) + await session.execute( + insert(workspace_bad_case_labels).values( + workspace_id="ws-reject", + label="review", + created_at=now, + updated_at=now, + ), + ) + await session.execute( + text( + """ + CREATE TRIGGER reject_sync_assignment + BEFORE INSERT ON workspace_bad_cases + WHEN NEW.assignment_source = 'catalog_label' + BEGIN + SELECT RAISE(ABORT, 'assignment failed'); + END + """, + ), + ) + + with pytest.raises(IntegrityError): + await repository.commit_page( + [_case(8, catalog_label="review")], + last_bad_case_id=8, + pending_count=0, + now=now, + ) + + state = await repository.get_state() + async with database.session() as session: + facts = (await session.execute(select(bad_cases.c.bad_case_id))).scalars().all() + assert state is not None + assert state.last_bad_case_id == 0 + assert facts == [] + + +@pytest.mark.asyncio +async def test_catalog_status_counts_exclude_direct_ingest_facts(database: Database) -> None: + """Label health counters describe public catalog facts, not direct uploads.""" + repository = BadCaseCatalogSyncRepository(database) + now = now_shanghai() + await repository.initialize(now) + async with database.transaction() as session: + await session.execute( + insert(bad_cases).values( + bad_case_id="direct-only", + workspace_id="ws-default", + bad_case_session_id="session-direct", + bad_case_type="self", + object_name="direct", + object_type="skill", + title="Direct", + bad_case_description="Direct ingest must not affect catalog health.", + catalog_label=None, + created_at=now, + updated_at=now, + ), + ) + + await repository.commit_page( + [_case(9, catalog_label=None)], + last_bad_case_id=9, + pending_count=0, + now=now, + ) + + state = await repository.get_state() + assert state is not None + assert state.invalid_label_count == 1 diff --git a/apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_sync_service.py b/apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_sync_service.py index a6ded12a..c9700acf 100644 --- a/apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_sync_service.py +++ b/apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_sync_service.py @@ -9,7 +9,7 @@ import pytest import pytest_asyncio from pydantic import SecretStr -from sqlalchemy import select +from sqlalchemy import insert, select from app.config import DatabaseDialect, Settings from app.db.base import Database @@ -17,7 +17,13 @@ from app.db.crud.bad_cases import BadCaseRepository from app.db.factory import create_database from app.db.migrate import upgrade_database -from app.db.models.domain import bad_case_analysis, bad_cases +from app.db.models.domain import ( + bad_case_analysis, + bad_cases, + workspace_bad_case_labels, + workspace_bad_cases, +) +from app.db.models.workspace import workspaces from app.errors import AppError, ErrorCode from app.service.acquisition.bad_case_catalog_sync import ( BadCaseCatalogSyncService, @@ -65,6 +71,7 @@ def _item( object_name: str | None = "deep-research", object_type: str | None = "skill", source: str | None = "test", + meta_data: object | None = None, ) -> BadCaseItem: return BadCaseItem( bad_case_id=case_id, @@ -76,7 +83,7 @@ def _item( bad_case_agent_id=None, bad_case_title=title or f"case {case_id}", bad_case_description="description", - meta_data=None, + meta_data=meta_data, source=source, created_at=datetime.fromisoformat("2026-10-30T10:00:00+08:00"), updated_at=datetime.fromisoformat("2026-10-30T10:00:00+08:00"), @@ -359,3 +366,91 @@ async def test_analysis_rows_survive_upsert(database: Database) -> None: progress = await BadCaseRepository(database).analysis_progress() assert progress.total == 1 assert progress.analyzed == 1 + + +@pytest.mark.asyncio +async def test_labels_fan_out_exactly_and_invalid_values_stay_unassigned( + database: Database, +) -> None: + """Valid exact labels route to every matching workspace and invalid labels do not.""" + now = now_shanghai() + async with database.transaction() as session: + await session.execute( + insert(workspaces), + [ + { + "id": "ws-label-a", + "name": "Label A", + "mark": "A", + "quota": 10, + "status": "active", + "created_at": now, + "updated_at": now, + }, + { + "id": "ws-label-b", + "name": "Label B", + "mark": "B", + "quota": 10, + "status": "active", + "created_at": now, + "updated_at": now, + }, + ], + ) + await session.execute( + insert(workspace_bad_case_labels), + [ + { + "workspace_id": "ws-label-a", + "label": "review", + "created_at": now, + "updated_at": now, + }, + { + "workspace_id": "ws-label-b", + "label": "review", + "created_at": now, + "updated_at": now, + }, + ], + ) + + source = FakeSource( + [ + _item(1, meta_data={"label": "review"}), + _item(2, meta_data={"label": "Review"}), + _item(3, meta_data={"label": " review"}), + _item(4, meta_data=["review"]), + ], + ) + await _service(database, source).run(owner="label-routing") + + async with database.session() as session: + cases = ( + await session.execute( + select(bad_cases.c.bad_case_id, bad_cases.c.catalog_label).order_by( + bad_cases.c.bad_case_id, + ), + ) + ).all() + assignments = ( + await session.execute( + select( + workspace_bad_cases.c.workspace_id, + workspace_bad_cases.c.bad_case_id, + workspace_bad_cases.c.assignment_source, + ).order_by(workspace_bad_cases.c.workspace_id), + ) + ).all() + + state = await BadCaseCatalogSyncRepository(database).get_state() + assert cases == [("1", "review"), ("2", "Review"), ("3", None), ("4", None)] + assert assignments == [ + ("ws-label-a", "1", "catalog_label"), + ("ws-label-b", "1", "catalog_label"), + ] + assert state is not None + assert state.assigned_count == 1 + assert state.unassigned_count == 1 + assert state.invalid_label_count == 2 diff --git a/apps/api/tests/m6-16-bad-case-catalog-sync/test_migration.py b/apps/api/tests/m6-16-bad-case-catalog-sync/test_migration.py index 1a7da120..fa58f15e 100644 --- a/apps/api/tests/m6-16-bad-case-catalog-sync/test_migration.py +++ b/apps/api/tests/m6-16-bad-case-catalog-sync/test_migration.py @@ -21,6 +21,9 @@ "last_bad_case_id", "synced_count", "pending_count", + "assigned_count", + "unassigned_count", + "invalid_label_count", "status", "attempts", "last_error", @@ -157,6 +160,7 @@ async def test_upgrade_backfills_workspace_bad_case_assignments(tmp_path: Path) ).one() assert "catalog_label" in schema["bad_case_columns"] + assert "catalog_synced" in schema["bad_case_columns"] assert schema["label_columns"] == { "workspace_id", "label", @@ -177,6 +181,7 @@ async def test_upgrade_backfills_workspace_bad_case_assignments(tmp_path: Path) ] assert schema["assignment_fks"] == {("workspace_id",), ("bad_case_id",)} assert "ix_bad_cases_catalog_label" in schema["bad_case_indexes"] + assert "ix_bad_cases_catalog_synced" in schema["bad_case_indexes"] assert tuple(assignment) == ( "ws-default", "legacy-case", From 58b6286ab50f9091a7cff82ba086c637606b1485 Mon Sep 17 00:00:00 2001 From: haley <710872687@qq.com> Date: Wed, 25 Nov 2026 00:32:53 +0800 Subject: [PATCH 04/17] fix(ingest): preserve workspace-owned badcases (#582) --- apps/api/app/db/crud/acquisition_replay.py | 6 +- apps/api/app/db/crud/bad_case_ingest.py | 75 +++++++++++++++++-- .../app/db/crud/workspace_bad_case_labels.py | 2 +- apps/api/app/db/crud/workspaces.py | 27 ++++--- apps/api/tests/ingest/helpers.py | 8 +- .../tests/ingest/test_ingest_repository.py | 58 +++++++++++++- .../test_knowledge_replay.py | 10 +++ apps/api/tests/workspaces/helpers.py | 11 ++- apps/api/tests/workspaces/test_admin.py | 11 ++- .../workspaces/test_bad_case_labels_api.py | 4 + 10 files changed, 185 insertions(+), 27 deletions(-) diff --git a/apps/api/app/db/crud/acquisition_replay.py b/apps/api/app/db/crud/acquisition_replay.py index f581baa3..3e43fe83 100644 --- a/apps/api/app/db/crud/acquisition_replay.py +++ b/apps/api/app/db/crud/acquisition_replay.py @@ -24,6 +24,7 @@ sync_runs, trajectory_payloads, user_turns, + workspace_bad_cases, ) from app.db.models.jobs import JobRunRecord, job_runs, record_from_row from app.db.models.workspace import workspaces @@ -328,8 +329,11 @@ async def list_workspace_knowledge_roots( select(workspaces.c.id, workspaces.c.knowledge_roots) .select_from( bad_cases.join( + workspace_bad_cases, + workspace_bad_cases.c.bad_case_id == bad_cases.c.bad_case_id, + ).join( workspaces, - workspaces.c.id == bad_cases.c.workspace_id, + workspaces.c.id == workspace_bad_cases.c.workspace_id, ), ) .where(bad_cases.c.bad_case_session_id == root_session_id) diff --git a/apps/api/app/db/crud/bad_case_ingest.py b/apps/api/app/db/crud/bad_case_ingest.py index ada7c256..f8ffcc56 100644 --- a/apps/api/app/db/crud/bad_case_ingest.py +++ b/apps/api/app/db/crud/bad_case_ingest.py @@ -8,14 +8,14 @@ from datetime import datetime from typing import Any -from sqlalchemy import func, insert, select, update +from sqlalchemy import delete, func, insert, select, update from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncSession from app.db.base import Database from app.db.crud.bad_case_sync import insert_pending_root from app.db.crud.integrity import is_unique_violation -from app.db.models.domain import bad_cases +from app.db.models.domain import bad_cases, workspace_bad_cases from app.db.models.workspace import workspaces from app.utils.time import as_shanghai, now_shanghai @@ -170,14 +170,21 @@ async def ingest(self, workspace_id: str, row: BadCaseIngestRow) -> BadCaseInges existing = await self._existing_owner(session, row.bad_case_id) if existing is not None and existing != workspace_id: raise BadCaseIdConflict(row.bad_case_id) - if existing is None: + already_assigned = await self._workspace_has_case( + session, + workspace_id, + row.bad_case_id, + ) + if not already_assigned: used = await self._used(session, workspace_id) if used >= quota: raise QuotaExceeded(quota=quota, used=used) + if existing is None: created = await self._insert(session, workspace_id, values, now=now) else: created = False await self._update(session, row.bad_case_id, values, now=now) + await self._assign_direct(session, workspace_id, row.bad_case_id, now=now) workspace_used = await self._used(session, workspace_id) await insert_pending_root( session, @@ -298,13 +305,67 @@ async def _update( ) async def _used(self, session: AsyncSession, workspace_id: str) -> int: - """Return the live count of cases owned by the workspace.""" + """Return the distinct live assignment count for one workspace.""" return int( ( await session.execute( - select(func.count()) - .select_from(bad_cases) - .where(bad_cases.c.workspace_id == workspace_id), + select(func.count(func.distinct(workspace_bad_cases.c.bad_case_id))).where( + workspace_bad_cases.c.workspace_id == workspace_id, + ), ) ).scalar_one(), ) + + async def _workspace_has_case( + self, + session: AsyncSession, + workspace_id: str, + bad_case_id: str, + ) -> bool: + """Return whether any assignment source already exposes this case.""" + return ( + await session.execute( + select(workspace_bad_cases.c.bad_case_id) + .where( + workspace_bad_cases.c.workspace_id == workspace_id, + workspace_bad_cases.c.bad_case_id == bad_case_id, + ) + .limit(1), + ) + ).scalar_one_or_none() is not None + + async def _assign_direct( + self, + session: AsyncSession, + workspace_id: str, + bad_case_id: str, + *, + now: datetime, + ) -> None: + """Converge legacy ownership to direct ingest without touching catalog rows.""" + await session.execute( + delete(workspace_bad_cases).where( + workspace_bad_cases.c.workspace_id == workspace_id, + workspace_bad_cases.c.bad_case_id == bad_case_id, + workspace_bad_cases.c.assignment_source == "legacy_owner", + ), + ) + direct_exists = ( + await session.execute( + select(workspace_bad_cases.c.bad_case_id).where( + workspace_bad_cases.c.workspace_id == workspace_id, + workspace_bad_cases.c.bad_case_id == bad_case_id, + workspace_bad_cases.c.assignment_source == "direct_ingest", + ), + ) + ).scalar_one_or_none() + if direct_exists is None: + await session.execute( + insert(workspace_bad_cases).values( + workspace_id=workspace_id, + bad_case_id=bad_case_id, + assignment_source="direct_ingest", + label=None, + assigned_at=now, + ), + ) diff --git a/apps/api/app/db/crud/workspace_bad_case_labels.py b/apps/api/app/db/crud/workspace_bad_case_labels.py index 962bdfaf..5a000a9d 100644 --- a/apps/api/app/db/crud/workspace_bad_case_labels.py +++ b/apps/api/app/db/crud/workspace_bad_case_labels.py @@ -35,7 +35,7 @@ def __init__(self, database: Database) -> None: async def get(self, workspace_id: str) -> WorkspaceBadCaseLabelRecord: """Return sorted rules and the distinct assigned badcase count.""" async with self._database.session() as session: - labels: list[str] = ( + labels: Sequence[str] = ( ( await session.execute( select(workspace_bad_case_labels.c.label) diff --git a/apps/api/app/db/crud/workspaces.py b/apps/api/app/db/crud/workspaces.py index 88f7d994..31a789cc 100644 --- a/apps/api/app/db/crud/workspaces.py +++ b/apps/api/app/db/crud/workspaces.py @@ -12,7 +12,7 @@ from app.db.base import Database from app.db.crud.acquisition_replay import bad_cases_table_present from app.db.crud.integrity import is_unique_violation -from app.db.models.domain import bad_cases, source_records +from app.db.models.domain import bad_cases, source_records, workspace_bad_cases from app.db.models.users import users from app.db.models.workspace import ( workspace_ingest_credentials, @@ -271,11 +271,13 @@ async def used_counts(self, workspace_ids: Sequence[str]) -> dict[str, int]: return {} statement = ( select( - bad_cases.c.workspace_id.label("workspace_id"), - func.count().label("case_count"), + workspace_bad_cases.c.workspace_id, + func.count(func.distinct(workspace_bad_cases.c.bad_case_id)).label( + "case_count", + ), ) - .where(bad_cases.c.workspace_id.in_(workspace_ids)) - .group_by(bad_cases.c.workspace_id) + .where(workspace_bad_cases.c.workspace_id.in_(workspace_ids)) + .group_by(workspace_bad_cases.c.workspace_id) ) async with self._database.session() as session: rows = (await session.execute(statement)).mappings().all() @@ -287,9 +289,9 @@ async def used_count(self, workspace_id: str) -> int: return int( ( await session.execute( - select(func.count()) - .select_from(bad_cases) - .where(bad_cases.c.workspace_id == workspace_id), + select(func.count(func.distinct(workspace_bad_cases.c.bad_case_id))).where( + workspace_bad_cases.c.workspace_id == workspace_id, + ), ) ).scalar_one(), ) @@ -431,8 +433,13 @@ async def invalidate_reported_root_parsers(self, workspace_id: str) -> int: """ if not await bad_cases_table_present(self._database): return 0 - root_ids = select(bad_cases.c.bad_case_session_id).where( - bad_cases.c.workspace_id == workspace_id, + root_ids = ( + select(bad_cases.c.bad_case_session_id) + .join( + workspace_bad_cases, + workspace_bad_cases.c.bad_case_id == bad_cases.c.bad_case_id, + ) + .where(workspace_bad_cases.c.workspace_id == workspace_id) ) async with self._database.transaction() as session: result = await session.execute( diff --git a/apps/api/tests/ingest/helpers.py b/apps/api/tests/ingest/helpers.py index 5a82d823..2a26e757 100644 --- a/apps/api/tests/ingest/helpers.py +++ b/apps/api/tests/ingest/helpers.py @@ -9,7 +9,7 @@ from sqlalchemy import func, select from app.db.base import Database -from app.db.models.domain import bad_cases +from app.db.models.domain import bad_cases, workspace_bad_cases from app.utils.time import as_shanghai from tests.workspaces.helpers import ( access_token, @@ -116,9 +116,9 @@ async def count_cases(database: Database, workspace_id: str) -> int: return int( ( await session.execute( - select(func.count()) - .select_from(bad_cases) - .where(bad_cases.c.workspace_id == workspace_id), + select(func.count(func.distinct(workspace_bad_cases.c.bad_case_id))).where( + workspace_bad_cases.c.workspace_id == workspace_id, + ), ) ).scalar_one(), ) diff --git a/apps/api/tests/ingest/test_ingest_repository.py b/apps/api/tests/ingest/test_ingest_repository.py index f1861d68..5a514f72 100644 --- a/apps/api/tests/ingest/test_ingest_repository.py +++ b/apps/api/tests/ingest/test_ingest_repository.py @@ -5,7 +5,7 @@ import httpx import pytest from fastapi import FastAPI -from sqlalchemy import func, select +from sqlalchemy import func, insert, select from sqlalchemy.ext.asyncio import AsyncSession from app.db.base import Database @@ -20,7 +20,7 @@ BadCaseRootSyncRepository, insert_pending_root, ) -from app.db.models.domain import bad_case_root_sync +from app.db.models.domain import bad_case_root_sync, workspace_bad_cases from app.errors import AppError, ErrorCode from app.service.workspaces.ingest import BadCaseIngest, BadCaseIngestService from app.service.workspaces.service import WorkspaceCredentialAccess @@ -183,6 +183,60 @@ async def test_repository_reports_created_flag_and_live_usage( assert stored.title == "第二版标题" +async def test_direct_ingest_replaces_legacy_and_preserves_catalog_assignment( + ingest_client: tuple[FastAPI, httpx.AsyncClient], +) -> None: + """A repeat report converges ownership without deleting label visibility.""" + app, client = ingest_client + workspace = await create_ingest_workspace(app, client, name="Repo Assignment", quota=4) + repository = BadCaseIngestRepository(app.state.database) + await repository.ingest(workspace.workspace_id, ingest_row()) + now = now_shanghai() + async with app.state.database.transaction() as session: + await session.execute( + insert(workspace_bad_cases), + [ + { + "workspace_id": workspace.workspace_id, + "bad_case_id": "BC-REPO-1", + "assignment_source": "legacy_owner", + "label": None, + "assigned_at": now, + }, + { + "workspace_id": workspace.workspace_id, + "bad_case_id": "BC-REPO-1", + "assignment_source": "catalog_label", + "label": "review", + "assigned_at": now, + }, + ], + ) + + repeated = await repository.ingest( + workspace.workspace_id, + ingest_row(title="direct update"), + ) + + async with app.state.database.session() as session: + sources = ( + ( + await session.execute( + select(workspace_bad_cases.c.assignment_source) + .where( + workspace_bad_cases.c.workspace_id == workspace.workspace_id, + workspace_bad_cases.c.bad_case_id == "BC-REPO-1", + ) + .order_by(workspace_bad_cases.c.assignment_source), + ) + ) + .scalars() + .all() + ) + assert repeated.workspace_used == 1 + assert sources == ["catalog_label", "direct_ingest"] + + async def test_ensure_pending_inserts_once_and_never_resets_state( ingest_client: tuple[FastAPI, httpx.AsyncClient], ) -> None: diff --git a/apps/api/tests/m9-05-knowledge-document-triggers/test_knowledge_replay.py b/apps/api/tests/m9-05-knowledge-document-triggers/test_knowledge_replay.py index ed7ddbfb..73f7ef93 100644 --- a/apps/api/tests/m9-05-knowledge-document-triggers/test_knowledge_replay.py +++ b/apps/api/tests/m9-05-knowledge-document-triggers/test_knowledge_replay.py @@ -20,6 +20,7 @@ bad_cases, source_records, trajectory_payloads, + workspace_bad_cases, ) from app.db.models.workspace import workspaces from app.main import create_app @@ -186,6 +187,15 @@ async def seed_workspace( updated_at=now, ), ) + await session.execute( + workspace_bad_cases.insert().values( + workspace_id=workspace_id, + bad_case_id=bad_case_id, + assignment_source="legacy_owner", + label=None, + assigned_at=now, + ), + ) async def test_replay_persists_knowledge_documents_from_every_reported_root( diff --git a/apps/api/tests/workspaces/helpers.py b/apps/api/tests/workspaces/helpers.py index 007a75ea..f87b9616 100644 --- a/apps/api/tests/workspaces/helpers.py +++ b/apps/api/tests/workspaces/helpers.py @@ -8,7 +8,7 @@ from app.api.deps import require_workspace_role from app.db.base import Database -from app.db.models.domain import bad_cases +from app.db.models.domain import bad_cases, workspace_bad_cases from app.db.models.users import users from app.db.models.workspace import workspace_members, workspaces from app.service.workspaces.service import WorkspaceAccess @@ -113,6 +113,15 @@ async def insert_bad_case( updated_at=now, ), ) + await session.execute( + insert(workspace_bad_cases).values( + workspace_id=workspace_id, + bad_case_id=bad_case_id, + assignment_source="legacy_owner", + label=None, + assigned_at=now, + ), + ) def access_token( diff --git a/apps/api/tests/workspaces/test_admin.py b/apps/api/tests/workspaces/test_admin.py index bb056670..5adb69ba 100644 --- a/apps/api/tests/workspaces/test_admin.py +++ b/apps/api/tests/workspaces/test_admin.py @@ -6,7 +6,7 @@ from sqlalchemy import select, update from app.db.base import Database -from app.db.models.domain import bad_cases, source_records +from app.db.models.domain import bad_cases, source_records, workspace_bad_cases from app.utils.time import now_shanghai from tests.workspaces.helpers import ( access_token, @@ -742,6 +742,15 @@ async def test_knowledge_root_change_marks_reported_roots_for_replay( updated_at=now, ), ) + await session.execute( + workspace_bad_cases.insert().values( + workspace_id=workspace_id, + bad_case_id="bc-root-stale", + assignment_source="legacy_owner", + label=None, + assigned_at=now, + ), + ) await session.execute( source_records.insert().values( runtime_key="claude-code", diff --git a/apps/api/tests/workspaces/test_bad_case_labels_api.py b/apps/api/tests/workspaces/test_bad_case_labels_api.py index bd502ca4..065c20d2 100644 --- a/apps/api/tests/workspaces/test_bad_case_labels_api.py +++ b/apps/api/tests/workspaces/test_bad_case_labels_api.py @@ -160,6 +160,10 @@ async def test_replacement_reassigns_history_to_every_matching_workspace( "items": ["tool-use"], "assignedBadCaseCount": 2, } + listed = await client.get("/api/workspaces", headers=headers) + usage = {item["id"]: item["used"] for item in listed.json()["items"]} + assert usage[first_workspace] == 2 + assert usage[second_workspace] == 1 async def test_label_request_rejects_duplicates_whitespace_and_oversize( From dce73dd290af9fe41cbdf41454ee2d68a2043371 Mon Sep 17 00:00:00 2001 From: haley <710872687@qq.com> Date: Wed, 25 Nov 2026 01:29:18 +0800 Subject: [PATCH 05/17] refactor(api): unify workspace badcase visibility (#582) --- apps/api/app/db/crud/bad_case_sync.py | 7 +- apps/api/app/db/crud/bad_cases.py | 3 +- apps/api/app/db/crud/evolution_targets.py | 3 +- apps/api/app/db/crud/overview.py | 12 +- apps/api/app/db/crud/overview_targets.py | 3 +- apps/api/app/db/crud/potential.py | 3 +- apps/api/app/db/crud/probe_query.py | 5 +- apps/api/app/db/crud/problems.py | 8 +- apps/api/app/db/crud/read_scope.py | 48 ++++++-- apps/api/app/db/crud/sessions.py | 8 +- .../test_session_scope.py | 6 + .../test_latest_ten.py | 3 + .../test_overview_api.py | 7 ++ apps/api/tests/workspaces/helpers.py | 45 +++++++- .../workspaces/test_scope_associations.py | 108 ++++++++++++++++++ 15 files changed, 239 insertions(+), 30 deletions(-) create mode 100644 apps/api/tests/workspaces/test_scope_associations.py diff --git a/apps/api/app/db/crud/bad_case_sync.py b/apps/api/app/db/crud/bad_case_sync.py index be32eaf5..f3111c87 100644 --- a/apps/api/app/db/crud/bad_case_sync.py +++ b/apps/api/app/db/crud/bad_case_sync.py @@ -17,6 +17,7 @@ from app.db.base import Database from app.db.crud.integrity import is_unique_violation +from app.db.crud.read_scope import scoped_case_ids from app.db.models.domain import bad_case_root_sync, bad_cases, session_families from app.utils.time import as_shanghai, now_shanghai @@ -170,7 +171,7 @@ def _distinct_roots(workspace_ids: tuple[str, ...] | None = None) -> Subquery: """Return distinct bad-case root ids as a subquery.""" query = select(bad_cases.c.bad_case_session_id.label("root_session_id")) if workspace_ids is not None: - query = query.where(bad_cases.c.workspace_id.in_(workspace_ids)) + query = query.where(bad_cases.c.bad_case_id.in_(scoped_case_ids(workspace_ids))) return query.distinct().subquery() @@ -406,7 +407,9 @@ async def has_report_source(self, workspace_ids: tuple[str, ...] | None = None) .limit(1) ) if workspace_ids is not None: - statement = statement.where(bad_cases.c.workspace_id.in_(workspace_ids)) + statement = statement.where( + bad_cases.c.bad_case_id.in_(scoped_case_ids(workspace_ids)), + ) try: async with self._database.session() as session: return (await session.execute(statement)).scalar_one_or_none() is not None diff --git a/apps/api/app/db/crud/bad_cases.py b/apps/api/app/db/crud/bad_cases.py index fdc091eb..c48b6991 100644 --- a/apps/api/app/db/crud/bad_cases.py +++ b/apps/api/app/db/crud/bad_cases.py @@ -14,6 +14,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from app.db.base import Database +from app.db.crud.read_scope import scoped_case_ids from app.db.external_contract import ( classify_external_failure, classify_external_read_error, @@ -305,7 +306,7 @@ async def analysis_progress( """Aggregate attribution states without materializing new columns.""" cases = select(bad_cases.c.bad_case_id, bad_cases.c.workspace_id) if workspace_ids is not None: - cases = cases.where(bad_cases.c.workspace_id.in_(workspace_ids)) + cases = cases.where(bad_cases.c.bad_case_id.in_(scoped_case_ids(workspace_ids))) scope = cases.subquery() v2 = probe_reports.c.report_schema_version == "probe-report/v2" legacy = bad_case_analysis.c.analysis_status diff --git a/apps/api/app/db/crud/evolution_targets.py b/apps/api/app/db/crud/evolution_targets.py index d473e7a1..8d2740c8 100644 --- a/apps/api/app/db/crud/evolution_targets.py +++ b/apps/api/app/db/crud/evolution_targets.py @@ -10,6 +10,7 @@ from app.db.base import Database from app.db.crud.integrity import is_unique_violation +from app.db.crud.read_scope import scoped_case_ids from app.db.models.domain import agents, attribution_skill_packages, bad_cases, evolution_targets from app.db.models.evolution import evolution_runs from app.db.models.workspace import DEFAULT_WORKSPACE_ID @@ -487,7 +488,7 @@ async def list_models( ) if workspace_ids is not None: scoped_sessions = select(bad_cases.c.bad_case_session_id).where( - bad_cases.c.workspace_id.in_(workspace_ids), + bad_cases.c.bad_case_id.in_(scoped_case_ids(workspace_ids)), ) statement = statement.where(agents.c.root_session_id.in_(scoped_sessions)) statement = statement.group_by(agents.c.model).order_by( diff --git a/apps/api/app/db/crud/overview.py b/apps/api/app/db/crud/overview.py index f107a3b4..385082c4 100644 --- a/apps/api/app/db/crud/overview.py +++ b/apps/api/app/db/crud/overview.py @@ -19,6 +19,7 @@ from app.db.base import Database from app.db.crud.bad_case_sync import BadCaseRootSyncRow, _to_row +from app.db.crud.read_scope import WorkspaceReadScope from app.db.external_contract import read_only_guard from app.db.models.domain import ( bad_case_analysis, @@ -26,6 +27,7 @@ bad_cases, probe_reports, session_families, + workspace_bad_cases, ) from app.db.models.workspace import workspaces from app.utils.time import SHANGHAI @@ -112,7 +114,7 @@ def _case_conditions( reads always pass both boundaries. """ conditions: list[ColumnElement[bool]] = [ - bad_cases.c.workspace_id == workspace_id, + WorkspaceReadScope.for_workspace(workspace_id).case_condition(), # Legacy catalog sync only enforces the column length, so a row can carry # a type outside the report contract. Excluding it here keeps # badCases == self + discovery and the trend total on every read path. @@ -224,9 +226,11 @@ async def workspace_usage(self, workspace_id: str) -> tuple[int, int]: used = int( ( await session.execute( - select(func.count()) - .select_from(bad_cases) - .where(bad_cases.c.workspace_id == workspace_id), + select( + func.count( + func.distinct(workspace_bad_cases.c.bad_case_id), + ) + ).where(workspace_bad_cases.c.workspace_id == workspace_id), ) ).scalar_one(), ) diff --git a/apps/api/app/db/crud/overview_targets.py b/apps/api/app/db/crud/overview_targets.py index a171ac49..52751bed 100644 --- a/apps/api/app/db/crud/overview_targets.py +++ b/apps/api/app/db/crud/overview_targets.py @@ -16,6 +16,7 @@ from sqlalchemy import select from app.db.base import Database +from app.db.crud.read_scope import WorkspaceReadScope from app.db.models.domain import ( agent_events, agents, @@ -109,7 +110,7 @@ async def list_window_cases( bad_cases.c.created_at, ) .where( - bad_cases.c.workspace_id == workspace_id, + WorkspaceReadScope.for_workspace(workspace_id).case_condition(), bad_cases.c.created_at >= window_start, bad_cases.c.created_at < window_end, bad_cases.c.bad_case_type.in_(("self", "discovery")), diff --git a/apps/api/app/db/crud/potential.py b/apps/api/app/db/crud/potential.py index 00b304f6..3c3ac8fc 100644 --- a/apps/api/app/db/crud/potential.py +++ b/apps/api/app/db/crud/potential.py @@ -14,6 +14,7 @@ from app.db.base import Database from app.db.crud.evolution_targets import EvolutionObjectType +from app.db.crud.read_scope import WorkspaceReadScope from app.db.models.domain import ( agent_events, agents, @@ -132,7 +133,7 @@ async def list_window_cases( bad_cases.c.created_at, ) .where( - bad_cases.c.workspace_id == workspace_id, + WorkspaceReadScope.for_workspace(workspace_id).case_condition(), bad_cases.c.created_at >= window_start, bad_cases.c.created_at < window_end, bad_cases.c.bad_case_type.in_(("self", "discovery")), diff --git a/apps/api/app/db/crud/probe_query.py b/apps/api/app/db/crud/probe_query.py index b5bc7569..be370d0a 100644 --- a/apps/api/app/db/crud/probe_query.py +++ b/apps/api/app/db/crud/probe_query.py @@ -10,6 +10,7 @@ from sqlalchemy import select from app.db.base import Database +from app.db.crud.read_scope import scoped_case_ids from app.db.models.domain import ( agents, bad_case_analysis, @@ -171,7 +172,9 @@ async def list_hit_rows(self, query: ProbeHitQuery) -> tuple[ProbeHitRow, ...]: probe_reports.c.probe_type == query.target_type, ] if query.workspace_ids is not None: - conditions.append(bad_cases.c.workspace_id.in_(query.workspace_ids)) + conditions.append( + bad_cases.c.bad_case_id.in_(scoped_case_ids(query.workspace_ids)), + ) statement = ( self._hit_selection() .where(*conditions) diff --git a/apps/api/app/db/crud/problems.py b/apps/api/app/db/crud/problems.py index 9d637e45..ba994e7a 100644 --- a/apps/api/app/db/crud/problems.py +++ b/apps/api/app/db/crud/problems.py @@ -182,7 +182,7 @@ async def session_probes( ) .where( bad_case_analysis.c.probe_id.is_not(None), - scope.condition(bad_cases.c.workspace_id), + scope.case_condition(), ) ) probes = tuple( @@ -257,7 +257,7 @@ async def probe_visible( ) .where( bad_case_analysis.c.probe_id == probe_id, - scope.condition(bad_cases.c.workspace_id), + scope.case_condition(), ) .limit(1), ) @@ -348,7 +348,7 @@ async def _case( await session.execute( select(bad_cases).where( bad_cases.c.bad_case_id == case_id, - scope.condition(bad_cases.c.workspace_id), + scope.case_condition(), ), ) ) @@ -370,7 +370,7 @@ async def _cases( select(bad_cases) .where( bad_cases.c.bad_case_session_id == session_id, - scope.condition(bad_cases.c.workspace_id), + scope.case_condition(), ) .order_by(bad_cases.c.created_at, bad_cases.c.bad_case_id), ) diff --git a/apps/api/app/db/crud/read_scope.py b/apps/api/app/db/crud/read_scope.py index a2d88de6..57b03dbc 100644 --- a/apps/api/app/db/crud/read_scope.py +++ b/apps/api/app/db/crud/read_scope.py @@ -2,13 +2,15 @@ from __future__ import annotations +from collections.abc import Sequence from dataclasses import dataclass from sqlalchemy import inspect, select, true from sqlalchemy.sql.elements import ColumnElement +from sqlalchemy.sql.selectable import Select from app.db.base import Database -from app.db.models.domain import bad_cases, session_families +from app.db.models.domain import bad_cases, session_families, workspace_bad_cases from app.db.models.workspace import workspace_members @@ -43,14 +45,31 @@ def for_user(cls, *, user_id: str, role: str) -> WorkspaceReadScope: return cls.all_workspaces() return cls(workspace_id=None, user_id=user_id) - def condition(self, column: ColumnElement[str]) -> ColumnElement[bool]: - """Return the SQL predicate selecting rows this scope may read.""" + def case_condition(self) -> ColumnElement[bool]: + """Return the predicate selecting bad cases associated with this scope. + + Visibility comes from the ``workspace_bad_cases`` association, so one + canonical case shared through a label is readable by every matching + workspace while an unrelated space reads nothing. All bad-case and + Session read paths must go through this boundary. + """ if self.workspace_id is not None: - return column == self.workspace_id + return ( + select(workspace_bad_cases.c.bad_case_id) + .where( + workspace_bad_cases.c.workspace_id == self.workspace_id, + workspace_bad_cases.c.bad_case_id == bad_cases.c.bad_case_id, + ) + .exists() + ) if self.user_id is not None: - return column.in_( - select(workspace_members.c.workspace_id).where( - workspace_members.c.user_id == self.user_id, + return bad_cases.c.bad_case_id.in_( + select(workspace_bad_cases.c.bad_case_id).where( + workspace_bad_cases.c.workspace_id.in_( + select(workspace_members.c.workspace_id).where( + workspace_members.c.user_id == self.user_id, + ), + ), ), ) return true() @@ -58,12 +77,21 @@ def condition(self, column: ColumnElement[str]) -> ColumnElement[bool]: def session_condition(self) -> ColumnElement[bool]: """Keep only sessions projected from bad cases inside this scope.""" return session_families.c.id.in_( - select(bad_cases.c.bad_case_session_id).where( - self.condition(bad_cases.c.workspace_id), - ), + select(bad_cases.c.bad_case_session_id).where(self.case_condition()), ) +def scoped_case_ids(workspace_ids: Sequence[str]) -> Select[tuple[str]]: + """Return the case ids associated with any of the explicit workspaces. + + Legacy unscoped compatibility routes resolve a workspace-id list first and + then reuse this subquery instead of filtering ``bad_cases.workspace_id``. + """ + return select(workspace_bad_cases.c.bad_case_id).where( + workspace_bad_cases.c.workspace_id.in_(workspace_ids), + ) + + async def bad_cases_table_present(database: Database) -> bool: """Return whether the external bad-case table exists in this installation. diff --git a/apps/api/app/db/crud/sessions.py b/apps/api/app/db/crud/sessions.py index f309e0b9..9e8a3f41 100644 --- a/apps/api/app/db/crud/sessions.py +++ b/apps/api/app/db/crud/sessions.py @@ -363,7 +363,7 @@ async def count_pending_sessions(self, scope: WorkspaceReadScope) -> int: select(func.count(func.distinct(bad_cases.c.bad_case_session_id))) .select_from(bad_cases) .where( - scope.condition(bad_cases.c.workspace_id), + scope.case_condition(), ~select(session_families.c.id) .where(session_families.c.id == bad_cases.c.bad_case_session_id) .exists(), @@ -457,7 +457,7 @@ async def tree_snapshot( select(bad_cases) .where( bad_cases.c.bad_case_session_id == session_id, - scope.condition(bad_cases.c.workspace_id), + scope.case_condition(), ) .order_by(bad_cases.c.created_at, bad_cases.c.bad_case_id), ) @@ -488,7 +488,7 @@ async def bad_case_counts( ) .where( bad_cases.c.bad_case_session_id.in_(session_ids), - scope.condition(bad_cases.c.workspace_id), + scope.case_condition(), ) .group_by(bad_cases.c.bad_case_session_id) ) @@ -532,7 +532,7 @@ async def list_bad_cases( select(bad_cases) .where( bad_cases.c.bad_case_session_id == session_id, - scope.condition(bad_cases.c.workspace_id), + scope.case_condition(), ) .order_by(bad_cases.c.created_at, bad_cases.c.bad_case_id) ) diff --git a/apps/api/tests/m7-06-session-workspace-scope/test_session_scope.py b/apps/api/tests/m7-06-session-workspace-scope/test_session_scope.py index 48a2480a..4b4986fa 100644 --- a/apps/api/tests/m7-06-session-workspace-scope/test_session_scope.py +++ b/apps/api/tests/m7-06-session-workspace-scope/test_session_scope.py @@ -17,6 +17,7 @@ from app.utils.time import now_shanghai from tests.workspaces.helpers import ( access_token, + associate_case, bearer, create_user, insert_member, @@ -120,6 +121,11 @@ async def scope_environment(tmp_path: Path) -> AsyncIterator[ScopeEnvironment]: ), ) + await associate_case(database, workspace_id=workspace_a, bad_case_id=CASE_S1_A) + await associate_case(database, workspace_id=workspace_a, bad_case_id=CASE_S3_A) + await associate_case(database, workspace_id=workspace_b, bad_case_id=CASE_S2_B) + await associate_case(database, workspace_id=workspace_b, bad_case_id=CASE_S1_B) + yield ScopeEnvironment( client=client, database=database, diff --git a/apps/api/tests/m8-02-session-latest-ten/test_latest_ten.py b/apps/api/tests/m8-02-session-latest-ten/test_latest_ten.py index 351ba1bb..74bb84ec 100644 --- a/apps/api/tests/m8-02-session-latest-ten/test_latest_ten.py +++ b/apps/api/tests/m8-02-session-latest-ten/test_latest_ten.py @@ -17,6 +17,7 @@ from app.main import create_app from tests.workspaces.helpers import ( access_token, + backfill_legacy_associations, bearer, create_user, insert_member, @@ -146,6 +147,8 @@ async def latest_ten(tmp_path: Path) -> AsyncIterator[LatestTenEnvironment]: ), ) + await backfill_legacy_associations(database) + yield LatestTenEnvironment( client=client, database=database, diff --git a/apps/api/tests/m8-03-workspace-overview/test_overview_api.py b/apps/api/tests/m8-03-workspace-overview/test_overview_api.py index 68a187c1..bb402568 100644 --- a/apps/api/tests/m8-03-workspace-overview/test_overview_api.py +++ b/apps/api/tests/m8-03-workspace-overview/test_overview_api.py @@ -26,6 +26,7 @@ from tests.identity.helpers import identity_settings from tests.workspaces.helpers import ( access_token, + backfill_legacy_associations, bearer, create_user, insert_member, @@ -266,6 +267,7 @@ async def _seed_corpus( ] async with database.transaction() as session: await session.execute(insert(bad_cases), rows) + await backfill_legacy_associations(database) @pytest_asyncio.fixture @@ -942,6 +944,7 @@ async def test_list_projects_trigger_line_without_faking_missing_rows( ), ], ) + await backfill_legacy_associations(environment.database) response = await _get( environment, @@ -980,6 +983,7 @@ async def test_list_default_page_size_is_eight_and_pages_do_not_overlap( for index in range(1, 5) ], ) + await backfill_legacy_associations(environment.database) first = await _get( environment, @@ -1067,6 +1071,7 @@ async def test_list_ties_break_by_bad_case_id_ascending( ), ], ) + await backfill_legacy_associations(environment.database) response = await _get( environment, @@ -1591,6 +1596,7 @@ async def test_object_options_are_isolated_per_workspace( ), ], ) + await backfill_legacy_associations(environment.database) own = await _get( environment, @@ -1684,6 +1690,7 @@ async def test_unknown_bad_case_type_rows_are_excluded_consistently( ), ], ) + await backfill_legacy_associations(environment.database) summary = await _get( environment, diff --git a/apps/api/tests/workspaces/helpers.py b/apps/api/tests/workspaces/helpers.py index f87b9616..b4906792 100644 --- a/apps/api/tests/workspaces/helpers.py +++ b/apps/api/tests/workspaces/helpers.py @@ -4,7 +4,7 @@ from typing import Annotated, cast from fastapi import Depends, FastAPI -from sqlalchemy import insert +from sqlalchemy import insert, text from app.api.deps import require_workspace_role from app.db.base import Database @@ -124,6 +124,49 @@ async def insert_bad_case( ) +async def associate_case( + database: Database, + *, + workspace_id: str, + bad_case_id: str, + source: str = "legacy_owner", + label: str | None = None, +) -> None: + """Insert one workspace→bad-case association for scoped read tests.""" + async with database.transaction() as session: + await session.execute( + insert(workspace_bad_cases).values( + workspace_id=workspace_id, + bad_case_id=bad_case_id, + assignment_source=source, + label=label, + assigned_at=now_shanghai(), + ), + ) + + +async def backfill_legacy_associations(database: Database) -> None: + """Mirror migration 0032 for fixtures that seed ownership without associations. + + Workspace-scoped reads derive visibility from ``workspace_bad_cases``, so a + fixture that writes ``bad_cases.workspace_id`` directly must backfill the + matching ``legacy_owner`` rows exactly as the migration would have. + """ + async with database.transaction() as session: + await session.execute( + text( + """ + INSERT INTO workspace_bad_cases ( + workspace_id, bad_case_id, assignment_source, label, assigned_at + ) + SELECT workspace_id, bad_case_id, 'legacy_owner', NULL, CURRENT_TIMESTAMP + FROM bad_cases + WHERE workspace_id IS NOT NULL + """, + ), + ) + + def access_token( app: FastAPI, *, diff --git a/apps/api/tests/workspaces/test_scope_associations.py b/apps/api/tests/workspaces/test_scope_associations.py new file mode 100644 index 00000000..b41a9361 --- /dev/null +++ b/apps/api/tests/workspaces/test_scope_associations.py @@ -0,0 +1,108 @@ +"""Cross-stack contract: one catalog case may be shared by many workspaces. + +These scenarios are impossible under the legacy ``bad_cases.workspace_id`` +visibility model, so they pin the association boundary that every workspace +read path now uses. +""" + +import httpx +from fastapi import FastAPI +from sqlalchemy import insert + +from app.db.models.domain import bad_cases +from app.utils.time import now_shanghai +from tests.workspaces.helpers import ( + access_token, + bearer, + insert_workspace, +) + + +async def _insert_catalog_case( + app: FastAPI, + *, + case_id: str, + label: str, +) -> None: + """Insert one canonical public case whose validated label is already projected.""" + now = now_shanghai() + async with app.state.database.transaction() as session: + await session.execute( + insert(bad_cases).values( + bad_case_id=case_id, + workspace_id="ws-default", + bad_case_session_id=f"session-{case_id}", + bad_case_type="self", + object_name="shared-object", + object_type="skill", + title=f"Case {case_id}", + bad_case_description="Shared catalog case.", + meta_data={"label": label}, + catalog_label=label, + created_at=now, + updated_at=now, + ), + ) + + +async def _configure(app: FastAPI, client: httpx.AsyncClient, wid: str, items: list[str]) -> None: + response = await client.put( + f"/api/workspaces/{wid}/bad-case-labels", + headers=bearer(access_token(app, user_id="admin", role="admin")), + json={"items": items}, + ) + assert response.status_code == 200 + + +async def test_shared_catalog_case_is_readable_by_every_matching_workspace( + workspace_client: tuple[FastAPI, httpx.AsyncClient], +) -> None: + """One canonical row fans out to both configured spaces; a third sees nothing.""" + app, client = workspace_client + database = app.state.database + first = await insert_workspace(database, name="shared-first") + second = await insert_workspace(database, name="shared-second") + outsider = await insert_workspace(database, name="shared-outsider") + admin = bearer(access_token(app, user_id="admin", role="admin")) + + await _insert_catalog_case(app, case_id="case-shared", label="shared") + await _configure(app, client, first, ["shared"]) + await _configure(app, client, second, ["shared"]) + + for wid in (first, second): + case = await client.get(f"/api/workspaces/{wid}/bad-cases/case-shared", headers=admin) + assert case.status_code == 200, wid + summary = await client.get(f"/api/workspaces/{wid}/overview/summary", headers=admin) + assert summary.json()["totals"]["badCases"] == 1, wid + + hidden = await client.get( + f"/api/workspaces/{outsider}/bad-cases/case-shared", + headers=admin, + ) + assert hidden.status_code == 404 + hidden_summary = await client.get( + f"/api/workspaces/{outsider}/overview/summary", + headers=admin, + ) + assert hidden_summary.json()["totals"]["badCases"] == 0 + + +async def test_removing_label_revokes_catalog_visibility_only_for_that_workspace( + workspace_client: tuple[FastAPI, httpx.AsyncClient], +) -> None: + """Clearing one workspace's rule removes its association but not the sibling's.""" + app, client = workspace_client + database = app.state.database + first = await insert_workspace(database, name="revoke-first") + second = await insert_workspace(database, name="revoke-second") + admin = bearer(access_token(app, user_id="admin", role="admin")) + + await _insert_catalog_case(app, case_id="case-revoke", label="shared") + await _configure(app, client, first, ["shared"]) + await _configure(app, client, second, ["shared"]) + await _configure(app, client, second, []) + + kept = await client.get(f"/api/workspaces/{first}/bad-cases/case-revoke", headers=admin) + assert kept.status_code == 200 + revoked = await client.get(f"/api/workspaces/{second}/bad-cases/case-revoke", headers=admin) + assert revoked.status_code == 404 From 05f7cc4629a462f6047b77a166b445f7b0797009 Mon Sep 17 00:00:00 2001 From: haley <710872687@qq.com> Date: Wed, 25 Nov 2026 09:26:36 +0800 Subject: [PATCH 06/17] feat(web): manage workspace badcase labels (#582) --- apps/web/src/api/queryKeys.ts | 2 + apps/web/src/api/workspaces.ts | 31 ++ apps/web/src/composables/useWorkspaces.ts | 64 +++ apps/web/src/pages/workspaces/Admin.test.ts | 20 +- apps/web/src/pages/workspaces/Admin.vue | 15 +- .../components/BadCaseLabelsTab.test.ts | 173 +++++++ .../components/BadCaseLabelsTab.vue | 461 ++++++++++++++++++ packages/contracts/openapi.json | 212 ++++++++ packages/contracts/src/generated/api.d.ts | 159 ++++++ packages/contracts/src/index.ts | 2 + packages/contracts/src/workspaces.ts | 8 + plans/ui-prototype-v2/harness-evolution.html | 67 ++- 12 files changed, 1206 insertions(+), 8 deletions(-) create mode 100644 apps/web/src/pages/workspaces/components/BadCaseLabelsTab.test.ts create mode 100644 apps/web/src/pages/workspaces/components/BadCaseLabelsTab.vue diff --git a/apps/web/src/api/queryKeys.ts b/apps/web/src/api/queryKeys.ts index abaf1b25..61ce4523 100644 --- a/apps/web/src/api/queryKeys.ts +++ b/apps/web/src/api/queryKeys.ts @@ -27,6 +27,8 @@ export const queryKeys = { ["ws", workspaceId, "admin", "member-candidates", query] as const, adminCredentials: (workspaceId: string) => ["ws", workspaceId, "admin", "credentials"] as const, + adminBadCaseLabels: (workspaceId: string) => + ["ws", workspaceId, "admin", "bad-case-labels"] as const, attributionSkillPackages: (workspaceId: string) => ["ws", workspaceId, "admin", "attribution-skill-packages"] as const, users: () => ["users"] as const, diff --git a/apps/web/src/api/workspaces.ts b/apps/web/src/api/workspaces.ts index 6195b7e1..6e4ef2f1 100644 --- a/apps/web/src/api/workspaces.ts +++ b/apps/web/src/api/workspaces.ts @@ -1,5 +1,7 @@ import type { Workspace, + WorkspaceBadCaseLabelConfiguration, + WorkspaceBadCaseLabelRequest, WorkspaceCreateRequest, WorkspaceCredentialCreated, WorkspaceCredentialListResponse, @@ -208,3 +210,32 @@ export function revokeWorkspaceCredential( { method: "DELETE" }, ); } + +/** + * Read the public badcase labels accepted by one workspace. + * @param workspaceId Route workspace identifier. + * @returns Sorted label set with its distinct assigned case count. + */ +export function listWorkspaceBadCaseLabels( + workspaceId: string, +): Promise { + return request( + workspacePath(workspaceId, "/bad-case-labels"), + ); +} + +/** + * Atomically replace one workspace's accepted labels and rebuild assignments. + * @param workspaceId Route workspace identifier. + * @param body Complete replacement label set. + * @returns Sorted label set with its recomputed distinct assignment count. + */ +export function replaceWorkspaceBadCaseLabels( + workspaceId: string, + body: WorkspaceBadCaseLabelRequest, +): Promise { + return request( + workspacePath(workspaceId, "/bad-case-labels"), + { method: "PUT", body: JSON.stringify(body) }, + ); +} diff --git a/apps/web/src/composables/useWorkspaces.ts b/apps/web/src/composables/useWorkspaces.ts index 878975e2..6e781eb8 100644 --- a/apps/web/src/composables/useWorkspaces.ts +++ b/apps/web/src/composables/useWorkspaces.ts @@ -1,6 +1,8 @@ import type { PublicUser, Workspace, + WorkspaceBadCaseLabelConfiguration, + WorkspaceBadCaseLabelRequest, WorkspaceCreateRequest, WorkspaceCredentialCreated, WorkspaceMember, @@ -24,10 +26,12 @@ import { createWorkspace, createWorkspaceCredential, listMemberCandidates, + listWorkspaceBadCaseLabels, listWorkspaceCredentials, listWorkspaceMembers, listWorkspaces, removeWorkspaceMember, + replaceWorkspaceBadCaseLabels, revokeWorkspaceCredential, updateWorkspace, updateWorkspaceMember, @@ -326,6 +330,66 @@ export function useWorkspaceCredentialMutations( }; } +/** + * Read the public badcase labels accepted by one workspace. + * + * Every member can read the label set; it drives the workspace's visible + * badcase boundary, not a secret, so the query stays enabled for viewers too. + * @param workspaceId Workspace route identifier. + * @param enabled Whether the label query should run. + * @returns Label configuration query state. + */ +export function useWorkspaceBadCaseLabels( + workspaceId: MaybeRefOrGetter, + enabled: MaybeRefOrGetter = true, +) { + return useQuery({ + queryKey: computed(() => + queryKeys.adminBadCaseLabels(toValue(workspaceId)), + ), + queryFn: () => listWorkspaceBadCaseLabels(toValue(workspaceId)), + enabled: computed( + () => toValue(enabled) && toValue(workspaceId).length > 0, + ), + }); +} + +/** + * Atomically replace a workspace's accepted labels and historical assignments. + * @param workspaceId Workspace route identifier. + * @returns Label replacement mutation. + */ +export function useReplaceWorkspaceBadCaseLabels( + workspaceId: MaybeRefOrGetter, +) { + const queryClient = useQueryClient(); + const mutation = useMutation({ + mutationFn: (body: WorkspaceBadCaseLabelRequest) => + replaceWorkspaceBadCaseLabels(toValue(workspaceId), body), + onSuccess: async () => { + await Promise.all([ + queryClient.invalidateQueries({ + queryKey: queryKeys.adminBadCaseLabels(toValue(workspaceId)), + }), + queryClient.invalidateQueries({ + queryKey: queryKeys.workspace(toValue(workspaceId)), + }), + queryClient.invalidateQueries({ + queryKey: queryKeys.workspaces(), + }), + queryClient.invalidateQueries({ queryKey: queryKeys.authSession }), + ]); + await refreshAuthSession(); + }, + }); + return { + isPending: mutation.isPending, + replaceLabels: ( + body: WorkspaceBadCaseLabelRequest, + ): Promise => mutation.mutateAsync(body), + }; +} + /** * Build the JSON ingest example shown on the ingest tab. * diff --git a/apps/web/src/pages/workspaces/Admin.test.ts b/apps/web/src/pages/workspaces/Admin.test.ts index 65a11f99..535e0c5a 100644 --- a/apps/web/src/pages/workspaces/Admin.test.ts +++ b/apps/web/src/pages/workspaces/Admin.test.ts @@ -164,6 +164,9 @@ function installWorkspaceAdminHandlers(): void { http.get(`${base}/credentials`, () => HttpResponse.json({ items: credentials }), ), + http.get(`${base}/bad-case-labels`, () => + HttpResponse.json({ items: [], assignedBadCaseCount: 0 }), + ), http.get(`${base}/attribution-skill-packages`, () => HttpResponse.json(skillPackages), ), @@ -222,12 +225,12 @@ afterEach(() => { afterAll(() => server.close()); describe("workspace admin page", () => { - it("renders all five tabs and the global workspace table for the global administrator", async () => { + it("renders all six tabs and the global workspace table for the global administrator", async () => { installWorkspaceAdminHandlers(); const wrapper = await mountPage("global_admin"); expect(wrapper.get("h1").text()).toBe("工作空间管理"); - expect(wrapper.findAll(".admin-nav button")).toHaveLength(5); + expect(wrapper.findAll(".admin-nav button")).toHaveLength(6); expect(wrapper.get("[data-testid='admin-tab-spaces']").classes("active")).toBe( true, ); @@ -426,6 +429,19 @@ describe("workspace admin page", () => { ); }); + it("places the Badcase 类型 tab between 上报接入 and 归因 Skill", async () => { + installWorkspaceAdminHandlers(); + const wrapper = await mountPage("global_admin"); + + const labels = wrapper + .findAll(".admin-nav button") + .map((button) => button.text()); + const index = labels.indexOf("Badcase 类型"); + expect(index).toBeGreaterThan(0); + expect(labels[index - 1]).toBe("上报接入"); + expect(labels[index + 1]).toBe("归因 Skill"); + }); + it("renders the read-only auth contract and switches tabs through the URL", async () => { installWorkspaceAdminHandlers(); const wrapper = await mountPage("space_admin", memberUser, "auth"); diff --git a/apps/web/src/pages/workspaces/Admin.vue b/apps/web/src/pages/workspaces/Admin.vue index a68a5d2b..01c2d444 100644 --- a/apps/web/src/pages/workspaces/Admin.vue +++ b/apps/web/src/pages/workspaces/Admin.vue @@ -24,6 +24,7 @@ import { } from "../../utils/workspaceDisplay"; import AuthTab from "./components/AuthTab.vue"; import AttributionSkillsTab from "./components/AttributionSkillsTab.vue"; +import BadCaseLabelsTab from "./components/BadCaseLabelsTab.vue"; import IngestTab from "./components/IngestTab.vue"; import MembersTab from "./components/MembersTab.vue"; import SpacesTab from "./components/SpacesTab.vue"; @@ -31,12 +32,19 @@ import WorkspaceFormDialog from "./components/WorkspaceFormDialog.vue"; defineOptions({ name: "WorkspaceAdminPage" }); -type AdminTab = "spaces" | "members" | "ingest" | "attribution-skills" | "auth"; +type AdminTab = + | "spaces" + | "members" + | "ingest" + | "bad-case-labels" + | "attribution-skills" + | "auth"; const TABS: ReadonlyArray<{ key: AdminTab; label: string }> = [ { key: "spaces", label: "空间与额度" }, { key: "members", label: "成员与角色" }, { key: "ingest", label: "上报接入" }, + { key: "bad-case-labels", label: "Badcase 类型" }, { key: "attribution-skills", label: "归因 Skill" }, { key: "auth", label: "鉴权接入" }, ]; @@ -292,6 +300,11 @@ function workspaceErrorMessage(error: unknown): string { :workspace="currentWorkspace" :can-manage="canManage" /> + { + const wrapper = mount(BadCaseLabelsTab, { + props: { workspaceId, canManage }, + global: { + components: elementPlusComponents, + plugins: [ + [ + VueQueryPlugin, + { + queryClient: new QueryClient({ + defaultOptions: { queries: { gcTime: 0, retry: false } }, + }), + }, + ], + ], + }, + }); + wrappers.push(wrapper); + await flushPromises(); + return wrapper; +} + +beforeAll(() => server.listen({ onUnhandledRequest: "error" })); +afterEach(() => { + for (const wrapper of wrappers.splice(0)) wrapper.unmount(); + server.resetHandlers(); +}); +afterAll(() => server.close()); + +describe("Badcase 类型 label management tab", () => { + it("renders sorted chips and the assigned case count from the server", async () => { + server.use( + http.get(`${base}/bad-case-labels`, () => + HttpResponse.json(config(["code-review", "tool-use"], 142)), + ), + ); + const wrapper = await mountTab(); + + const chips = wrapper + .findAll("[data-testid='bad-case-label-chips'] .chip") + .map((chip) => chip.text().replace("×", "").trim()); + expect(chips).toEqual(["code-review", "tool-use"]); + expect(wrapper.get("[data-testid='bad-case-label-assigned-count']").text()).toBe( + "已关联 142 条", + ); + }); + + it("adds a label through both the button and Enter, keeping lexical order", async () => { + server.use( + http.get(`${base}/bad-case-labels`, () => HttpResponse.json(config([]))), + ); + const wrapper = await mountTab(); + + await wrapper.get("[data-testid='bad-case-label-input']").setValue("zebra"); + await wrapper.get("[data-testid='bad-case-label-input']").trigger("keyup.enter"); + await flushPromises(); + + await wrapper.get("[data-testid='bad-case-label-input']").setValue("alpha"); + await wrapper.get("[data-testid='add-bad-case-label']").trigger("click"); + await flushPromises(); + + const chips = wrapper + .findAll("[data-testid='bad-case-label-chips'] .chip") + .map((chip) => chip.text().replace("×", "").trim()); + expect(chips).toEqual(["alpha", "zebra"]); + }); + + it("rejects duplicate, whitespace, empty, and oversize labels inline", async () => { + server.use( + http.get(`${base}/bad-case-labels`, () => + HttpResponse.json(config(["review"])), + ), + ); + const wrapper = await mountTab(); + + const input = () => wrapper.get("[data-testid='bad-case-label-input']"); + const add = () => wrapper.get("[data-testid='add-bad-case-label']"); + const error = () => wrapper.get("[data-testid='bad-case-label-input-error']"); + + await input().setValue("review"); + await add().trigger("click"); + expect(error().text()).toContain("已经添加"); + + await input().setValue(" review "); + await add().trigger("click"); + expect(error().text()).toContain("首尾不能有空白"); + + await input().setValue(" "); + await add().trigger("click"); + expect(error().text()).toContain("不能为空"); + + await input().setValue("x".repeat(129)); + await add().trigger("click"); + expect(error().text()).toContain("最多 128 个字符"); + + expect(wrapper.findAll("[data-testid='bad-case-label-chips'] .chip")).toHaveLength(1); + }); + + it("tracks a dirty draft and saves a full replacement atomically", async () => { + let savedBody: unknown = null; + server.use( + http.get(`${base}/bad-case-labels`, () => HttpResponse.json(config([]))), + http.put(`${base}/bad-case-labels`, async ({ request }) => { + savedBody = await request.json(); + return HttpResponse.json(config(["review"], 3)); + }), + ); + const wrapper = await mountTab(); + + expect(wrapper.find("[data-testid='bad-case-label-dirty']").exists()).toBe(false); + + await wrapper.get("[data-testid='bad-case-label-input']").setValue("review"); + await wrapper.get("[data-testid='add-bad-case-label']").trigger("click"); + await flushPromises(); + + expect(wrapper.find("[data-testid='bad-case-label-dirty']").exists()).toBe(true); + + await wrapper.get("[data-testid='save-bad-case-labels']").trigger("click"); + await flushPromises(); + + expect(savedBody).toEqual({ items: ["review"] }); + expect(wrapper.find("[data-testid='bad-case-label-dirty']").exists()).toBe(false); + }); + + it("shows the empty hint when no label is configured", async () => { + server.use( + http.get(`${base}/bad-case-labels`, () => HttpResponse.json(config([]))), + ); + const wrapper = await mountTab(); + + expect(wrapper.get("[data-testid='no-bad-case-labels']").text()).toContain( + "还没有配置 label", + ); + }); + + it("keeps write controls hidden for read-only members while showing chips", async () => { + server.use( + http.get(`${base}/bad-case-labels`, () => + HttpResponse.json(config(["review"], 5)), + ), + ); + const wrapper = await mountTab(false); + + expect(wrapper.find("[data-testid='save-bad-case-labels']").exists()).toBe(false); + expect(wrapper.find("[data-testid='bad-case-label-input']").exists()).toBe(false); + expect(wrapper.find("[data-testid='add-bad-case-label']").exists()).toBe(false); + expect(wrapper.find(".chip-remove").exists()).toBe(false); + expect(wrapper.findAll("[data-testid='bad-case-label-chips'] .chip")).toHaveLength(1); + }); +}); diff --git a/apps/web/src/pages/workspaces/components/BadCaseLabelsTab.vue b/apps/web/src/pages/workspaces/components/BadCaseLabelsTab.vue new file mode 100644 index 00000000..56da7410 --- /dev/null +++ b/apps/web/src/pages/workspaces/components/BadCaseLabelsTab.vue @@ -0,0 +1,461 @@ + + + + + diff --git a/packages/contracts/openapi.json b/packages/contracts/openapi.json index f7205dec..68493088 100644 --- a/packages/contracts/openapi.json +++ b/packages/contracts/openapi.json @@ -1968,6 +1968,14 @@ "additionalProperties": false, "description": "Read-only catalog-sync counters for the top-nav popover.", "properties": { + "assigned": { + "title": "Assigned", + "type": "integer" + }, + "invalidLabel": { + "title": "Invalidlabel", + "type": "integer" + }, "lastBadCaseId": { "title": "Lastbadcaseid", "type": "integer" @@ -2010,6 +2018,10 @@ "title": "Synced", "type": "integer" }, + "unassigned": { + "title": "Unassigned", + "type": "integer" + }, "unsynced": { "title": "Unsynced", "type": "integer" @@ -2018,6 +2030,9 @@ "required": [ "synced", "unsynced", + "assigned", + "unassigned", + "invalidLabel", "lastBadCaseId", "status", "lastRunAt", @@ -10294,6 +10309,45 @@ "title": "WorkspaceAdmin", "type": "object" }, + "WorkspaceBadCaseLabelConfiguration": { + "additionalProperties": false, + "description": "One label rule set plus its current distinct assignment count.", + "properties": { + "assignedBadCaseCount": { + "minimum": 0.0, + "title": "Assignedbadcasecount", + "type": "integer" + }, + "items": { + "items": { + "type": "string" + }, + "title": "Items", + "type": "array" + } + }, + "required": [ + "items", + "assignedBadCaseCount" + ], + "title": "WorkspaceBadCaseLabelConfiguration", + "type": "object" + }, + "WorkspaceBadCaseLabelRequest": { + "additionalProperties": false, + "description": "Complete replacement set for one workspace's accepted public labels.", + "properties": { + "items": { + "items": { + "type": "string" + }, + "title": "Items", + "type": "array" + } + }, + "title": "WorkspaceBadCaseLabelRequest", + "type": "object" + }, "WorkspaceCreateRequest": { "additionalProperties": false, "description": "Administrator-provisioned workspace with at least one initial space admin.", @@ -15318,6 +15372,164 @@ ] } }, + "/api/workspaces/{wid}/bad-case-labels": { + "get": { + "description": "Return the public badcase labels accepted by this workspace.", + "operationId": "get_bad_case_labels_api_workspaces__wid__bad_case_labels_get", + "parameters": [ + { + "in": "path", + "name": "wid", + "required": true, + "schema": { + "maxLength": 36, + "minLength": 1, + "title": "Wid", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WorkspaceBadCaseLabelConfiguration" + } + } + }, + "description": "Successful Response" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Authentication is required" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Workspace does not exist" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "security": [ + { + "BearerAuth": [] + } + ], + "summary": "Get Bad Case Labels", + "tags": [ + "workspaces" + ] + }, + "put": { + "description": "Replace label rules and historical catalog assignments atomically.", + "operationId": "replace_bad_case_labels_api_workspaces__wid__bad_case_labels_put", + "parameters": [ + { + "in": "path", + "name": "wid", + "required": true, + "schema": { + "maxLength": 36, + "minLength": 1, + "title": "Wid", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WorkspaceBadCaseLabelRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WorkspaceBadCaseLabelConfiguration" + } + } + }, + "description": "Successful Response" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Authentication is required" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Workspace role is insufficient" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Workspace does not exist" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Label set is invalid" + } + }, + "security": [ + { + "BearerAuth": [] + } + ], + "summary": "Replace Bad Case Labels", + "tags": [ + "workspaces" + ] + } + }, "/api/workspaces/{wid}/bad-cases": { "get": { "description": "Return one filtered page of this workspace's reported cases.", diff --git a/packages/contracts/src/generated/api.d.ts b/packages/contracts/src/generated/api.d.ts index 2b212cc9..b1a21738 100644 --- a/packages/contracts/src/generated/api.d.ts +++ b/packages/contracts/src/generated/api.d.ts @@ -1014,6 +1014,30 @@ export interface paths { patch?: never; trace?: never; }; + "/api/workspaces/{wid}/bad-case-labels": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Get Bad Case Labels + * @description Return the public badcase labels accepted by this workspace. + */ + get: operations["get_bad_case_labels_api_workspaces__wid__bad_case_labels_get"]; + /** + * Replace Bad Case Labels + * @description Replace label rules and historical catalog assignments atomically. + */ + put: operations["replace_bad_case_labels_api_workspaces__wid__bad_case_labels_put"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/workspaces/{wid}/bad-cases": { parameters: { query?: never; @@ -2877,6 +2901,10 @@ export interface components { * @description Read-only catalog-sync counters for the top-nav popover. */ BadCaseCatalogSyncSummary: { + /** Assigned */ + assigned: number; + /** Invalidlabel */ + invalidLabel: number; /** Lastbadcaseid */ lastBadCaseId: number; /** Lasterror */ @@ -2890,6 +2918,8 @@ export interface components { status: "unavailable" | "idle" | "queued" | "running" | "failed"; /** Synced */ synced: number; + /** Unassigned */ + unassigned: number; /** Unsynced */ unsynced: number; }; @@ -6257,6 +6287,24 @@ export interface components { /** Id */ id: string; }; + /** + * WorkspaceBadCaseLabelConfiguration + * @description One label rule set plus its current distinct assignment count. + */ + WorkspaceBadCaseLabelConfiguration: { + /** Assignedbadcasecount */ + assignedBadCaseCount: number; + /** Items */ + items: string[]; + }; + /** + * WorkspaceBadCaseLabelRequest + * @description Complete replacement set for one workspace's accepted public labels. + */ + WorkspaceBadCaseLabelRequest: { + /** Items */ + items?: string[]; + }; /** * WorkspaceCreateRequest * @description Administrator-provisioned workspace with at least one initial space admin. @@ -9730,6 +9778,117 @@ export interface operations { }; }; }; + get_bad_case_labels_api_workspaces__wid__bad_case_labels_get: { + parameters: { + query?: never; + header?: never; + path: { + wid: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["WorkspaceBadCaseLabelConfiguration"]; + }; + }; + /** @description Authentication is required */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ErrorResponse"]; + }; + }; + /** @description Workspace does not exist */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ErrorResponse"]; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; + replace_bad_case_labels_api_workspaces__wid__bad_case_labels_put: { + parameters: { + query?: never; + header?: never; + path: { + wid: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["WorkspaceBadCaseLabelRequest"]; + }; + }; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["WorkspaceBadCaseLabelConfiguration"]; + }; + }; + /** @description Authentication is required */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ErrorResponse"]; + }; + }; + /** @description Workspace role is insufficient */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ErrorResponse"]; + }; + }; + /** @description Workspace does not exist */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ErrorResponse"]; + }; + }; + /** @description Label set is invalid */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ErrorResponse"]; + }; + }; + }; + }; list_workspace_bad_cases_api_workspaces__wid__bad_cases_get: { parameters: { query?: { diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 25efca50..d96dae6a 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -461,6 +461,8 @@ export type { SessionWorkspace, Workspace, WorkspaceAdmin, + WorkspaceBadCaseLabelConfiguration, + WorkspaceBadCaseLabelRequest, WorkspaceCreateRequest, WorkspaceCredential, WorkspaceCredentialCreated, diff --git a/packages/contracts/src/workspaces.ts b/packages/contracts/src/workspaces.ts index 07d74bf4..10a52731 100644 --- a/packages/contracts/src/workspaces.ts +++ b/packages/contracts/src/workspaces.ts @@ -63,5 +63,13 @@ export type WorkspaceCredentialListResponse = /** One-time credential creation response; `credential` is never persisted. */ export type WorkspaceCredentialCreated = components["schemas"]["WorkspaceCredentialCreated"]; +/** One label rule set plus its current distinct assignment count. */ +export type WorkspaceBadCaseLabelConfiguration = + components["schemas"]["WorkspaceBadCaseLabelConfiguration"]; + +/** Complete replacement set for one workspace's accepted public labels. */ +export type WorkspaceBadCaseLabelRequest = + components["schemas"]["WorkspaceBadCaseLabelRequest"]; + /** Current user plus every workspace they can see for this session. */ export type SessionPayload = components["schemas"]["SessionPayload"]; diff --git a/plans/ui-prototype-v2/harness-evolution.html b/plans/ui-prototype-v2/harness-evolution.html index a8d8b660..61983ee2 100644 --- a/plans/ui-prototype-v2/harness-evolution.html +++ b/plans/ui-prototype-v2/harness-evolution.html @@ -6359,7 +6359,7 @@

${evEsc(run.title)}

${evStatusBadge(run)}${evEsc( listFrom: '', listTo: '', page: 1, targetPage: 1, multiOpen: false, }, targetDetail: { targetId: '', versions: new Set(), from: '', to: '', limit: 5, menuOpen: false }, - admin: { tab: 'spaces', skills: new Map() }, + admin: { tab: 'spaces', skills: new Map(), labels: new Map() }, loginChoice: 'admin', }; window.V2 = V2; @@ -6384,7 +6384,7 @@

${evEsc(run.title)}

${evStatusBadge(run)}${evEsc( function v2IsAdmin(user) { return (user || V2.user)?.globalRole === 'admin'; } function v2CanManage(wsId) { const r = v2Role(wsId); return r === 'admin' || r === 'space_admin'; } function v2CanViewAdmin() { - return v2CanManage(V2.wsId) || (V2.admin.tab === 'attribution-skills' && !!v2Role(V2.wsId)); + return v2CanManage(V2.wsId) || (['attribution-skills', 'bad-case-labels'].includes(V2.admin.tab) && !!v2Role(V2.wsId)); } function v2VisibleWorkspaces() { if (!V2.user) return []; @@ -7251,8 +7251,8 @@

工作空间总览

/* ── 空间管理 ── */ function v2AdminNav() { - const tabs = [['spaces', '空间与额度'], ['members', '成员与角色'], ['ingest', '上报接入'], ['attribution-skills', '归因 Skill'], ['auth', '鉴权接入']]; - const visibleTabs = v2CanManage(V2.wsId) ? tabs : tabs.filter(([key]) => key === 'attribution-skills'); + const tabs = [['spaces', '空间与额度'], ['members', '成员与角色'], ['ingest', '上报接入'], ['bad-case-labels', 'Badcase 类型'], ['attribution-skills', '归因 Skill'], ['auth', '鉴权接入']]; + const visibleTabs = v2CanManage(V2.wsId) ? tabs : tabs.filter(([key]) => key === 'attribution-skills' || key === 'bad-case-labels'); const hint = v2IsAdmin() ? '全局管理员可创建空间、任命空间管理员。' : v2CanManage(V2.wsId) ? '空间管理员只管理当前空间,不能创建空间。' : '当前空间为只读访问。'; return ``; @@ -7276,6 +7276,7 @@

工作空间总览

if (V2.admin.tab === 'spaces') return v2AdminSpaces(); if (V2.admin.tab === 'members') return v2AdminMembers(); if (V2.admin.tab === 'ingest') return v2AdminIngest(); + if (V2.admin.tab === 'bad-case-labels') return v2AdminBadCaseLabels(); if (V2.admin.tab === 'attribution-skills') return v2AdminSkills(); return v2AdminAuth(); } @@ -7519,6 +7520,35 @@

curl 示例

${v2Esc(`curl -X POST '${V2_ORIGIN}${endpoint}' \\\n  -H 'Authorization: Bearer ${token}' \\\n  -H 'Content-Type: application/json' \\\n  -d '${body.replace(/\n/g, ' ')}'`)}
`; } +function v2LabelState() { + if (!V2.admin.labels.has(V2.wsId)) { + const seeded = V2.wsId === 'ws-harness'; + V2.admin.labels.set(V2.wsId, { + items: seeded ? ['code-review', 'tool-use'] : [], + draft: seeded ? ['code-review', 'tool-use'] : [], + assigned: seeded ? 142 : 0, + dirty: false, + }); + } + return V2.admin.labels.get(V2.wsId); +} +function v2AdminBadCaseLabels() { + const state = v2LabelState(); + const canManage = v2CanManage(V2.wsId); + const chips = state.draft.map(label => `${v2Esc(label)}${canManage ? `` : ''}`).join(''); + const empty = state.draft.length === 0 ? '
还没有配置 label。未配置时,公共 badcase 不会进入当前空间。
' : `
${chips}
`; + return `
+

Badcase 类型

选择当前空间从公共仓库接收的 badcase 大类型;未配置时公共 badcase 不会进入当前空间。
+ ${canManage ? '
' : v2Badge('只读', 'viewer')} +
+
+

已配置 label ${state.items.length} 个

+ ${empty} + ${canManage ? `
` : ''} +
当前划分
已关联 ${state.assigned} 条
${state.dirty ? '有未保存更改' : ''}
+
label 区分大小写、精确匹配;同一 label 可配置给多个空间,一条公共 badcase 会同时进入所有匹配空间。
+
`; +} function v2AdminAuth() { return `

鉴权接入(预留)

原型使用内置演示账号;生产登录使用用户名与密码,账号由管理员创建,不提供注册入口。
${v2Badge('注册未开放', 'warn')}
@@ -7699,7 +7729,7 @@

接入契约(替换身份提供方即可)

/* ── 事件 ── */ document.addEventListener('click', e => { - const el = e.target.closest('[data-v2-login-user],[data-v2-switch-ws],[data-v2-manage-ws],[data-v2-preview-login],[data-v2-admin-entry],[data-v2-logout],[data-v2-ov-range],[data-v2-ov-grain],[data-v2-ov-clear],[data-v2-ov-remove],[data-v2-ov-page],[data-v2-ov-reset],[data-v2-ov-tab],[data-v2-tg-add],[data-v2-tg-edit],[data-v2-tg-remove],[data-v2-tg-metric],[data-v2-tg-clear],[data-v2-tg-page],[data-v2-tg-side-page],[data-v2-tg-reset],[data-v2-tg-save],[data-v2-td-limit],[data-v2-td-config],[data-v2-overview-ingest],[data-v2-overview-evo],[data-v2-copy-endpoint],[data-v2-admin-tab],[data-v2-open-ws],[data-v2-members-ws],[data-v2-quota-ws],[data-v2-create-ws],[data-v2-add-member],[data-v2-self-admin],[data-v2-remove-member],[data-v2-copy],[data-v2-rotate-token],[data-v2-close],[data-v2-save-ws],[data-v2-save-member]'); + const el = e.target.closest('[data-v2-login-user],[data-v2-switch-ws],[data-v2-manage-ws],[data-v2-preview-login],[data-v2-admin-entry],[data-v2-logout],[data-v2-ov-range],[data-v2-ov-grain],[data-v2-ov-clear],[data-v2-ov-remove],[data-v2-ov-page],[data-v2-ov-reset],[data-v2-ov-tab],[data-v2-tg-add],[data-v2-tg-edit],[data-v2-tg-remove],[data-v2-tg-metric],[data-v2-tg-clear],[data-v2-tg-page],[data-v2-tg-side-page],[data-v2-tg-reset],[data-v2-tg-save],[data-v2-td-limit],[data-v2-td-config],[data-v2-overview-ingest],[data-v2-overview-evo],[data-v2-copy-endpoint],[data-v2-admin-tab],[data-v2-open-ws],[data-v2-members-ws],[data-v2-quota-ws],[data-v2-create-ws],[data-v2-add-member],[data-v2-self-admin],[data-v2-remove-member],[data-v2-copy],[data-v2-rotate-token],[data-v2-close],[data-v2-save-ws],[data-v2-save-member],[data-v2-label-add],[data-v2-label-remove],[data-v2-label-save]'); if (!el) return; const ds = el.dataset; if (ds.v2LoginUser) { V2.loginChoice = ds.v2LoginUser; v2RenderLogin(); return; } @@ -7754,6 +7784,33 @@

接入契约(替换身份提供方即可)

document.querySelector(`[data-v2-admin-tab="${ds.v2AdminTab}"]`)?.focus(); return; } + if (ds.v2LabelAdd !== undefined) { + const input = document.getElementById('v2LabelInput'); + const value = (input?.value || '').trim(); + const state = v2LabelState(); + if (!value) { v2Toast('label 不能为空'); return; } + if (value.length > 128) { v2Toast('label 最多 128 个字符'); return; } + if (state.draft.includes(value)) { v2Toast('该 label 已经添加'); return; } + state.draft = [...state.draft, value].sort(); + state.dirty = true; + v2RenderAdmin(); + return; + } + if (ds.v2LabelRemove) { + const state = v2LabelState(); + state.draft = state.draft.filter(label => label !== ds.v2LabelRemove); + state.dirty = true; + v2RenderAdmin(); + return; + } + if (ds.v2LabelSave !== undefined) { + const state = v2LabelState(); + state.items = [...state.draft]; + state.dirty = false; + v2RenderAdmin(); + v2Toast('Badcase 类型已保存,历史数据已重新划分'); + return; + } if (ds.v2OpenWs) { v2SwitchWorkspace(ds.v2OpenWs); V2.admin.tab = 'spaces'; v2SetPage('overview'); return; } if (ds.v2MembersWs) { v2SwitchWorkspace(ds.v2MembersWs); V2.admin.tab = 'members'; v2SetPage('admin'); return; } if (ds.v2QuotaWs) { v2WorkspaceModal(ds.v2QuotaWs); return; } From 2d0a46ccff16219179f1fd6c1a2dc9bd2456fce9 Mon Sep 17 00:00:00 2001 From: haley <710872687@qq.com> Date: Wed, 25 Nov 2026 09:34:35 +0800 Subject: [PATCH 07/17] docs: record workspace badcase label routing (#582) --- .../bugfix-evolution-label-allowlist.en.md | 90 ++++++++++ ...bugfix-evolution-label-allowlist.i18n.yaml | 5 + .../bugfix-evolution-label-allowlist.md | 90 ++++++++++ ...-24-workspace-bad-case-label-routing.en.md | 35 ++++ ...workspace-bad-case-label-routing.i18n.yaml | 5 + ...-11-24-workspace-bad-case-label-routing.md | 35 ++++ docs/architecture.en.md | 2 +- docs/architecture.i18n.yaml | 4 +- docs/architecture.md | 2 +- .../17-workspace-bad-case-label-routing.md | 122 +++++++++++++ plans/fullstack-design/README.md | 3 +- ...6-11-24-issue-582-badcase-label-routing.md | 169 ++++++++++++++++++ 12 files changed, 557 insertions(+), 5 deletions(-) create mode 100644 .agents/flow/issues/bugfix-evolution-label-allowlist.en.md create mode 100644 .agents/flow/issues/bugfix-evolution-label-allowlist.i18n.yaml create mode 100644 .agents/flow/issues/bugfix-evolution-label-allowlist.md create mode 100644 .agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.en.md create mode 100644 .agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.md create mode 100644 plans/fullstack-design/17-workspace-bad-case-label-routing.md create mode 100644 plans/superpowers/plans/2026-11-24-issue-582-badcase-label-routing.md diff --git a/.agents/flow/issues/bugfix-evolution-label-allowlist.en.md b/.agents/flow/issues/bugfix-evolution-label-allowlist.en.md new file mode 100644 index 00000000..48457890 --- /dev/null +++ b/.agents/flow/issues/bugfix-evolution-label-allowlist.en.md @@ -0,0 +1,90 @@ +# Assign public bad cases to workspaces by label + +English | [中文](bugfix-evolution-label-allowlist.md) + +```yaml flow +kind: issue +id: bugfix-48 +milestone: bugfix +depends: [] +priority: P2 +status: backlog +scope: + - apps/api/** + - apps/web/** + - packages/contracts/** + - tests/** + - plans/** + - .agents/** + - docs/** +adr: [] +github: + number: 582 + url: https://github.com/Shadow-Azure/harness-evolution/issues/582 +``` + +## Background + +Production bad cases are reported to one public repository. The platform periodically pulls mixed categories from that source, and `items[].meta_data.label` identifies each category. Workspaces configure accepted labels; the same label may be configured by multiple workspaces, so one matching bad case must be available to all of them. + +## Goals + +Add a Badcase types tab to workspace management and use its rules to build a many-to-many assignment between public bad cases and workspaces. Browsing, Sessions, statistics and evolution then share that assignment boundary. + +## Design authority + +Follow the [evolution domain](../../../plans/fullstack-design/02-features.md#22-自进化域) and public catalog sync design. Update the relevant design chapter and an Agent Note during implementation. + +## Problem, investigation and root cause + +1. apps/api/app/third_party_api/bad_case_query/http.py calls GET {HE_BAD_CASE_QUERY_BASE_URL}/bad-cases with bad_case_id, offset and limit, without label parameters. +2. models.py in that directory declares BadCaseItem.meta_data as Any | None without a label contract. This supports carrying labels but does not prove their presence or type in live responses. +3. apps/api/app/service/acquisition/bad_case_catalog_sync.py preserves meta_data but upserts public records directly into bad_cases without parsing labels or assigning workspaces. +4. bad_cases.bad_case_id is a global primary key and each row has one workspace_id. It cannot represent one public bad case assigned to several workspaces, while copying rows conflicts with the global key. +5. Browsing, Sessions, statistics and PotentialMatcher.associated_sessions use bad_cases.workspace_id. Evolution-only filtering would create inconsistent boundaries and still cannot expose one case to several workspaces. +6. apps/web/src/pages/workspaces/Admin.vue has no label-rule UI, while the backend lacks rule persistence, reconciliation and unassigned-data observability. + +The root cause is coupling the public bad-case fact to a single workspace_id, plus the absence of a many-to-many label assignment rule and post-sync allocation process. Findings are static code analysis; production data was not queried. Confirm label shape and completeness with sanitized samples. + +## Implementation + +The sole recommended solution is to keep bad_cases as the public fact table, add workspace label rules and a badcase-workspace relation, and have sync plus reconciliation maintain the relation. Every workspace read path uses that relation. + +- Add workspace_bad_case_labels(workspace_id, label), unique by the pair. One label may map to many workspaces. Add a manually managed Badcase types tab; global and workspace administrators may write, with server-side authorization. +- Add workspace_bad_cases(workspace_id, bad_case_id, assignment_source, label, assigned_at), unique by workspace, case and source, where assignment_source is legacy_owner / direct_ingest / catalog_label and label only appears on catalog_label rows. Keep one public fact in bad_cases and stop using its single workspace_id as ownership. Migrate existing workspace_id values into legacy_owner relations and remove legacy-field dependencies, for SQLite and MySQL. +- Sync validates meta_data.label, upserts the public fact, finds every workspace accepting that label, and idempotently writes all relations. One bad case can belong to many workspaces while its source record remains singular. +- Saving rules starts a controlled reconciliation over local public facts for affected labels. Adding a rule backfills history; removing it deletes only that workspace's live relations. No cursor rewind or upstream refetch is required, and persisted inputs of existing runs remain intact. +- Browsing, Sessions, statistics, quota counts, attribution candidates and evolution all constrain through workspace_bad_cases. Existing target, version, time and evidence filters still intersect with this boundary. +- Recommend nonempty, case-sensitive exact string labels. Reject blank and surrounding whitespace. Preserve records with missing, null, empty or non-string labels but leave them unassigned, with invalid/unassigned sync counters; never put them in a default workspace. +- When upstream changes a historical label, remove relations produced by the old label and rebuild from the new label within a transaction or recoverable job boundary. + +## Implementation steps + +1. Verify sanitized label samples and fix the label contract, migration design and Agent Note. +2. Implement both relation tables, migrate current workspace_id data, add the authorized rule API and generate shared contracts. +3. Update public sync and reconciliation, including invalid/unassigned observability. +4. Move every workspace read path to the relation and complete UI and cross-stack verification. + +## Dependencies and boundary + +No upstream filtering API is required; one public source and one global cursor remain. Actual label type verification is an implementation prerequisite. This issue owns workspace assignment and all consuming read paths, not upstream data production. + +## Verification + +Use public fixtures with A/B, missing, null and numeric labels. Workspace one accepts A; workspace two accepts A/B. Run pnpm test:api:serial, pnpm test:db, pnpm test:db:mysql, pnpm test and pnpm test:e2e. Verify that A is stored once and related to both spaces, B only to space two, and invalid/unconfigured labels remain unassigned. Adding and removing rules reconciles history; browsing, statistics, Sessions and full/cluster_only evolution see identical sets; retries create no duplicates and existing runs still resume. + +## Acceptance + +- One label can serve several workspaces; each source bad case is stored once and related to every matching workspace. +- Rules persist with authorization; additions and removals deterministically reconcile history and unauthorized writes are rejected. +- Missing, invalid and unconfigured labels enter no workspace and have observable counts. +- Browsing, Sessions, statistics, quotas and evolution share the same set; sync and reconciliation are idempotent and existing runs remain recoverable. + +## Gates and CI + +Implementation runs pnpm contract:generate, pnpm contract:check, pnpm typecheck, pnpm typecheck:web, pnpm lint:api, pnpm lint:web, pnpm test:db, pnpm test:db:mysql and the behavior tests above. CI includes new cases and maintains at least 80% coverage. Documentation runs pnpm record:i18n -- .agents/flow/issues/bugfix-evolution-label-allowlist.md, pnpm verify:flow and pnpm lint:docs. Issue creation does not claim product acceptance tests passed. + +## Non-goals + +No upstream changes, public fact deletion, label inference or completion, label dictionary, or retrospective modification of existing run inputs. + diff --git a/.agents/flow/issues/bugfix-evolution-label-allowlist.i18n.yaml b/.agents/flow/issues/bugfix-evolution-label-allowlist.i18n.yaml new file mode 100644 index 00000000..37f20839 --- /dev/null +++ b/.agents/flow/issues/bugfix-evolution-label-allowlist.i18n.yaml @@ -0,0 +1,5 @@ +# 双语配对一致性记录(docs/i18n/README.md):两侧在最后一次确认一致状态下的 +# git blob hash。两种语言同等权威;编辑任一侧后带上另一侧,然后重录: +# pnpm run record:i18n -- .agents/flow/issues/bugfix-evolution-label-allowlist.md +bugfix-evolution-label-allowlist.md: dc3a91ff4f00c1264ea3cc103077d8e2ab1868ab +bugfix-evolution-label-allowlist.en.md: 484578901e9c34b283ae982e662dcee883a8aedb diff --git a/.agents/flow/issues/bugfix-evolution-label-allowlist.md b/.agents/flow/issues/bugfix-evolution-label-allowlist.md new file mode 100644 index 00000000..dc3a91ff --- /dev/null +++ b/.agents/flow/issues/bugfix-evolution-label-allowlist.md @@ -0,0 +1,90 @@ +# 按 label 将公共 badcase 划分到空间 + +[English](bugfix-evolution-label-allowlist.en.md) | 中文 + +```yaml flow +kind: issue +id: bugfix-48 +milestone: bugfix +depends: [] +priority: P2 +status: backlog +scope: + - apps/api/** + - apps/web/** + - packages/contracts/** + - tests/** + - plans/** + - .agents/** + - docs/** +adr: [] +github: + number: 582 + url: https://github.com/Shadow-Azure/harness-evolution/issues/582 +``` + +## 背景 + +生产环境中的 badcase 统一上报到公共仓库,平台定期从同一个仓库拉取多种类型的数据,`items[].meta_data.label` 表示 badcase 大类型。空间需要配置自己接收的 label;同一个 label 可以同时配置给多个空间,匹配的数据应同时对这些空间可见并参与各自后续自进化。 + +## 目标 + +在空间管理增加「Badcase 类型」页签维护当前空间接受的 label。公共仓库同步后,平台按 label 建立 badcase 与空间的多对多分配关系,使列表、Session、统计和自进化统一使用同一空间数据边界。 + +## 设计依据 + +遵循 [自进化域](../../../plans/fullstack-design/02-features.md#22-自进化域) 与公共 badcase 同步设计。本 issue 补充公共目录到空间数据面的划分规则,实施时同步对应设计章节与 Agent Note。 + +## 问题描述、分析过程与根因 + +1. `apps/api/app/third_party_api/bad_case_query/http.py` 调用 GET `{HE_BAD_CASE_QUERY_BASE_URL}/bad-cases`,参数是 bad_case_id、offset、limit,没有 label 筛选参数。 +2. 同目录 `models.py` 中 `BadCaseItem.meta_data` 是 `Any | None`,没有显式 label 契约。代码可承载 label,但尚未核实真实响应中的存在性与类型。 +3. `apps/api/app/service/acquisition/bad_case_catalog_sync.py` 的 `_row` 保留完整 meta_data,但目录同步按递增 ID 将公共记录直接 upsert 到 `bad_cases`,没有解析 label 或执行空间分配。 +4. `bad_cases.bad_case_id` 是全局主键且每行只有一个 `workspace_id`。该模型无法表达“同一公共 badcase 因同一 label 同时属于多个空间”;把记录复制到多行也会与全局主键冲突。 +5. 当前列表、Session、统计和 `PotentialMatcher.associated_sessions` 都通过 `bad_cases.workspace_id` 限定空间。若只在自进化入口过滤,其他空间数据面会与自进化口径不一致,也无法让同一 badcase进入多个空间。 +6. `apps/web/src/pages/workspaces/Admin.vue` 缺少 label 分配规则入口,后端也没有规则存储、重算和未分配观测能力。 + +结论:根因是公共 badcase 事实与空间归属耦合在 `bad_cases.workspace_id` 单值字段中,同时缺少 label 到空间的多对多规则及同步后的统一分配过程。真实 label 类型与完整性仍需脱敏样本确认;上述结论来自静态代码分析,未查询生产数据。 + +## 实现内容 + +唯一推荐方案:把 `bad_cases` 作为公共仓库事实表,新增空间 label 规则表和 badcase—空间关联表,由目录同步与规则重算共同维护关联;所有空间数据查询统一通过关联表限定范围。 + +- 新增 `workspace_bad_case_labels(workspace_id, label)`,联合唯一;同一 label 可对应多个 workspace。空间管理新增「Badcase 类型」页签,V1 手动添加、删除和保存。全局管理员与空间管理员可写,后端强制权限检查。 +- 新增 `workspace_bad_cases(workspace_id, bad_case_id, assignment_source, label, assigned_at)`,以 `(workspace_id, bad_case_id, assignment_source)` 唯一;`assignment_source` 三态 `legacy_owner` / `direct_ingest` / `catalog_label`,`label` 只落在 `catalog_label` 行。`bad_cases` 保存一份公共原始事实,不再以单值 `workspace_id` 表达归属;迁移把现有记录的 workspace_id 回填为 `legacy_owner` 关联,再逐步移除旧字段依赖。SQLite/MySQL 同步迁移。 +- 公共同步验证 `meta_data.label` 后先幂等 upsert 公共事实,再查询接受该 label 的全部空间,为每个空间幂等写入关联。同一 badcase 可因此属于多个空间,但原始记录只保存一次。 +- 保存 label 配置后,在同一受控任务中按本地公共事实重算受影响 label 的关联:新增规则补齐历史数据,删除规则移除该空间的实时关联;不需要回退同步游标或重新请求上游。已创建运行持久化的候选和报告不被删除。 +- 列表、Session、统计、额度计数、归因候选和自进化取数全部由 `workspace_bad_cases` 关联限定;因此自进化无需再实现一套独立 label 过滤,原有对象、版本、时间和证据条件继续取交集。 +- 建议 V1 label 为非空字符串,区分大小写精确匹配;配置去重并拒绝空白和首尾空格。缺失、null、空串和非字符串 label 的公共记录保留但不分配,纳入同步状态中的 invalid/unassigned 计数,不进入默认空间。 +- 上游更新历史 badcase 的 label 时,先删除旧 label 产生的关联,再按新 label 重建;整个重分配具备事务或可恢复任务边界,避免数据同时消失或重复。 + +## 实施步骤 + +1. 核实脱敏 label 样本,固定 label 契约、迁移方案和 Agent Note。 +2. 实现两张关系表、现有 workspace_id 数据迁移、规则 API 与共享协议。 +3. 改造公共目录同步和配置重算任务,补未分配/非法 label 观测。 +4. 将所有空间读路径切到关联表,完成管理页签与跨栈验证。 + +## 依赖与交付边界 + +不依赖上游新增筛选接口,公共仓库仍只配置一个来源且同步游标保持全局。真实 label 类型确认是实施前置条件。本 issue 负责空间划分及其所有读路径;不修改上游仓库的数据生产方式。 + +## 独立验证 + +合成公共数据含 A/B、无 label、null、数字 label;空间一接受 A,空间二接受 A/B。执行 `pnpm test:api:serial`、`pnpm test:db`、`pnpm test:db:mysql`、`pnpm test`、`pnpm test:e2e`。验证 A 记录只存一份但关联两个空间,B 只关联空间二,非法/未配置 label 保留且不分配;新增规则能补齐历史关联,删除规则只移除目标空间关联;列表、统计、Session 和 full/cluster_only 自进化看到一致集合,重试不会产生重复关联,既有运行可继续恢复。 + +## 验收标准 + +- 同一 label 可配置给多个空间,同一 badcase 原始事实只存一份并正确关联所有匹配空间。 +- 配置持久化且权限隔离;新增、删除规则会确定性重算历史关联,非管理员写入被拒绝。 +- 缺失、非法和未配置 label 不进入任何空间,并有可观测计数。 +- 列表、Session、统计、额度和自进化使用相同空间集合;同步及重算重试保持幂等,既有运行不被配置变化破坏。 + +## 门禁与 CI + +实现运行 `pnpm contract:generate`、`pnpm contract:check`、`pnpm typecheck`、`pnpm typecheck:web`、`pnpm lint:api`、`pnpm lint:web`、`pnpm test:db`、`pnpm test:db:mysql` 及上述行为测试,CI 纳入新增用例且覆盖率不少于 80%。文档运行 `pnpm record:i18n -- .agents/flow/issues/bugfix-evolution-label-allowlist.md`、`pnpm verify:flow`、`pnpm lint:docs`。本次创建 issue 不代表这些产品验收已通过。 + +## 非目标 + +不改上游接口、不删除公共原始 badcase、不推断或补全 label、不做标签字典、不追溯修改已经创建的运行输入。 + diff --git a/.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.en.md b/.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.en.md new file mode 100644 index 00000000..6401791f --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.en.md @@ -0,0 +1,35 @@ +# Agent Note: Associative facts and one read boundary for label-routed public bad cases + +Status: implemented + +English | [中文](2026-11-24-workspace-bad-case-label-routing.md) + +## Problem + +Production bad cases land in one public repository, and after the periodic pull the platform must route each case by `items[].meta_data.label` into every matching workspace, with lists, Sessions, statistics, and evolution all sharing one workspace boundary. The legacy `bad_cases.workspace_id` was a single column that doubled as ownership and visibility, so it cannot express "one public case belongs to several workspaces through the same label"; copying the row per workspace collides with the global `bad_case_id` primary key. Upstream `/bad-cases` has no label filter parameter, so assignment can only happen platform-side. + +## Decision + +- `bad_cases` keeps one canonical fact per global `bad_case_id`, while visibility moves to the `workspace_bad_cases` association keyed by `(workspace_id, bad_case_id, assignment_source)`. +- `assignment_source` has three states: `legacy_owner` (migration backfills the existing `workspace_id`), `direct_ingest` (workspace credential reporting), and `catalog_label` (public catalog label hit). One workspace and case may hold both a direct and a label association; reads deduplicate with `DISTINCT`. +- Accepted labels live in `workspace_bad_case_labels(workspace_id, label)`. A label is an exact, case-sensitive string of 1–128 characters with no surrounding whitespace, and one label may be configured by several workspaces. +- `bad_cases.catalog_label` is a nullable projection written from a validated `meta_data.label` at sync time (direct ingest always writes `NULL`), not a second source of truth: statistics and rebuilds query the column only and never parse JSON in SQL, keeping SQLite and MySQL behavior identical and indexable. +- The catalog sync page transaction runs in order: upsert the fact → delete `legacy_owner` and stale `catalog_label` associations for the page's ids → rebuild matches with `INSERT…SELECT` → advance the cursor and assigned/unassigned/invalid counts. Any failure rolls back the whole page and never advances the cursor. +- Saving a label configuration locks the workspace in one transaction, replaces the rule set, deletes only that workspace's `catalog_label` associations, and rebuilds history from `bad_cases.catalog_label JOIN workspace_bad_case_labels`. New rules backfill history; removed rules revoke live visibility. +- Every workspace read path (Session list and tree, problem list, overview, quota, potential cases, and evolution inputs) goes through `WorkspaceReadScope.case_condition()`. `bad_cases.workspace_id` keeps only direct-ingest ownership (id conflict detection and owner display). + +## Alternatives considered + +- **Copy the public case into every matching workspace**: rejected. It collides with the global `bad_case_id` key and loses the single fact; a label change then rewrites many rows. +- **Keep `bad_cases.workspace_id`, or fall back with `workspace_id OR association`**: rejected. After catalog sync removes the `legacy_owner` row for a re-touched id, the fallback would keep showing public data in the old default workspace, breaking the visibility boundary. +- **Parse the `meta_data` JSON in SQL for the label filter**: rejected. JSON functions and indexing differ between SQLite and MySQL, and it cannot serve the missing/invalid label counting consistently. +- **Materialize a label dictionary or write back to the public repository**: rejected. No second source of truth, and no change to how upstream produces data. +- **Rewrite already-created evolution run inputs retroactively**: rejected. Persisted candidates, reports, and run snapshots never re-read live associations; a configuration change only affects later previews and new runs. + +## Consequences + +- Every workspace-scoped read adds one association `EXISTS`/`IN` subquery; `workspace_bad_case_labels`, `workspace_bad_cases`, and the `bad_cases.catalog_label` column are new fact surface, and the migration backfills `legacy_owner` with `WHERE workspace_id IS NOT NULL`. +- `bad_cases.workspace_id` becomes a direct-ingest-only compatibility column whose removal needs its own window. +- Public catalog assignment can push a workspace's `used` above `quota`: direct ingest keeps rejecting on quota while the admin page suggests raising quota or removing a label; `used` counts distinct associations everywhere. +- A configuration save returns only after its transaction commits, so readers never observe a rule set that disagrees with its associations; sync and re-reconciliation retries stay idempotent. +- Test fixtures that write `bad_cases.workspace_id` directly must backfill the matching `legacy_owner` association per migration semantics, or workspace-scoped reads come back empty. diff --git a/.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.i18n.yaml b/.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.i18n.yaml new file mode 100644 index 00000000..f49f879b --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.i18n.yaml @@ -0,0 +1,5 @@ +# 双语配对一致性记录(docs/i18n/README.md):两侧在最后一次确认一致状态下的 +# git blob hash。两种语言同等权威;编辑任一侧后带上另一侧,然后重录: +# pnpm run record:i18n -- .agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.md +2026-11-24-workspace-bad-case-label-routing.md: ee5d11aa9816a786176341b3a9231c1b221e65e6 +2026-11-24-workspace-bad-case-label-routing.en.md: 6401791f0811191376a7504e71eba9708d0f9065 diff --git a/.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.md b/.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.md new file mode 100644 index 00000000..ee5d11aa --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.md @@ -0,0 +1,35 @@ +# Agent Note: 公共 badcase 按 label 划分空间的可关联事实与统一读边界 + +Status: implemented + +[English](2026-11-24-workspace-bad-case-label-routing.en.md) | 中文 + +## Problem + +生产 badcase 统一上报到公共仓库,平台定期拉取后需要按 `items[].meta_data.label` 把同一条公共 badcase 同时提供给多个空间,并让列表、Session、统计和自进化使用同一空间边界。旧的 `bad_cases.workspace_id` 是单值字段:既表达归属又表达可见性,无法表达"一条公共 badcase 因同一 label 属于多个空间";把记录复制成多行又会撞 `bad_case_id` 全局主键。上游 `/bad-cases` 没有 label 筛选参数,分配只能在平台侧做。 + +## Decision + +- `bad_cases` 保留单份公共事实(`bad_case_id` 全局主键),可见性从 `bad_cases.workspace_id` 移到 `workspace_bad_cases` 关联表,主键 `(workspace_id, bad_case_id, assignment_source)`。 +- `assignment_source` 三态:`legacy_owner`(迁移把既有 `workspace_id` 回填)、`direct_ingest`(空间凭据直接上报)、`catalog_label`(公共目录 label 命中)。同一空间与 case 可同时有直接上报与 label 两种关联,读取用 `DISTINCT` 去重。 +- 空间接受的 label 存 `workspace_bad_case_labels(workspace_id, label)`;label 是 1–128 字符、无首尾空白、区分大小写的精确字符串,一个 label 可配置给多个空间。 +- `bad_cases.catalog_label` 是同步时对 `meta_data.label` 验证后写入的可空投影列(直接上报固定 `NULL`),不是第二事实源:统计与重建只查该列,不在 SQL 里解析 JSON,保持 SQLite/MySQL 一致并可走索引。 +- 目录同步的单页事务按序执行:upsert 事实 → 删本页 ID 的 `legacy_owner` 与旧 `catalog_label` 关联 → 按规则 `INSERT…SELECT` 重建 → 更新游标与 assigned/unassigned/invalid 计数;任何一步失败整页回滚、游标不前进。 +- 保存 label 配置在一个事务里锁定空间、全量替换规则、只删该空间的 `catalog_label` 关联,再从 `bad_cases.catalog_label JOIN workspace_bad_case_labels` 重建历史关联;新增规则补齐历史、删除规则撤销实时可见性。 +- 所有空间读路径(Session 列表与树、问题列表、总览、额度、潜在 badcase 与自进化取数)统一经 `WorkspaceReadScope.case_condition()` 走关联;`bad_cases.workspace_id` 只保留直接上报归属(ID 冲突检测与 owner 展示)。 + +## Alternatives considered + +- **把公共 case 复制到每个匹配空间**:拒绝。撞 `bad_case_id` 全局主键,且失去单份事实,label 变更要批量删改多行。 +- **读路径沿用 `bad_cases.workspace_id`,或用 `workspace_id OR 关联` 兜底**:拒绝。目录同步再次触达同 ID 时移除 `legacy_owner` 后,旧默认空间会因兜底继续看到公共数据,可见性收口失效。 +- **label 过滤在 SQL 里解析 `meta_data` JSON**:拒绝。SQLite/MySQL 的 JSON 函数与索引行为不一致,且无法覆盖缺失/非法 label 的计数口径。 +- **物化 label 字典或回写公共仓库**:拒绝。不建立第二事实源,也不改动上游数据生产方式。 +- **追溯修改已创建的自进化运行输入**:拒绝。已持久化候选、报告与运行快照不反查实时关联,配置变化只影响后续预览和新运行。 + +## Consequences + +- 每次空间化读多一次关联 `EXISTS`/`IN` 子查询;`workspace_bad_case_labels`、`workspace_bad_cases` 与 `bad_cases.catalog_label` 列是新的事实面,迁移按 `WHERE workspace_id IS NOT NULL` 回填 `legacy_owner`。 +- `bad_cases.workspace_id` 成为仅属直接上报的兼容字段,移除需要单独的兼容窗口。 +- 公共目录分配可使空间 `used > quota`:直接上报继续按额度拒绝,管理页提示调整额度或移除 label;`used` 统一按关联去重计数。 +- 配置保存只在整个事务提交后返回,读取不会观察到规则与关联不一致的中间态;同步与重算重试幂等。 +- 测试 fixture 直接写 `bad_cases.workspace_id` 的场景须按迁移语义回填 `legacy_owner` 关联,否则空间化读为空。 diff --git a/docs/architecture.en.md b/docs/architecture.en.md index 1ab75295..e683818f 100644 --- a/docs/architecture.en.md +++ b/docs/architecture.en.md @@ -33,7 +33,7 @@ The session page uses a 360px list plus overview, defaults to the latest 10 and ## Data-layer strategy - Production MySQL 8, local/test SQLite; `HE_DB_DIALECT` is the only selection point. `Database` owns connections, read sessions, write transactions, and health; Alembic maintains dual-dialect migrations, and business code depends only on `db/crud/` and `Database`. -- Workspaces: `workspaces`, `workspace_members`, `workspace_ingest_credentials`; bad cases, target configuration, and runs carry `workspace_id`. Traces are global, and workspace Sessions are projected from bad cases. +- Workspaces: `workspaces`, `workspace_members`, `workspace_ingest_credentials`, `workspace_bad_case_labels`, `workspace_bad_cases`; bad-case visibility goes through `workspace_bad_cases`, while target configuration and runs carry `workspace_id`. Traces are global, and workspace Sessions are projected from bad cases. - Ingest: a credential writes only the URL workspace, quota is checked inside the write transaction, and re-reporting an ID upserts idempotently without double counting. - A bound target starts background attribution. The wizard can reuse its latest per-case reports or recompute with a chosen Skill. [Attribution files](../attribute/README.en.md) - Attribution: `bad_case_analysis` links multiple rows by `(bad_case_id, probe_id)`; `probe_reports` stores the conclusion, cache key, and reuse count; the cache key covers workspace, case, object identity, version, policy, and engine. diff --git a/docs/architecture.i18n.yaml b/docs/architecture.i18n.yaml index 15169705..28efdd46 100644 --- a/docs/architecture.i18n.yaml +++ b/docs/architecture.i18n.yaml @@ -1,5 +1,5 @@ # 双语配对一致性记录(docs/i18n/README.md):两侧在最后一次确认一致状态下的 # git blob hash。两种语言同等权威;编辑任一侧后带上另一侧,然后重录: # pnpm run record:i18n -- docs/architecture.md -architecture.md: 271accdeb27be6cb80d5171e2f26ab319b734ee9 -architecture.en.md: 1ab752951cc0dc471bdc1d757db45ad9998ced8c +architecture.md: 0846b56d06e586d051f895f8796f3f18ade60119 +architecture.en.md: e683818fd48daef31298781bc6a573d8f155a14b diff --git a/docs/architecture.md b/docs/architecture.md index 271accde..0846b56d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -33,7 +33,7 @@ Session 页 360px 列表+概览,默认最新 10、回车查询;错误详情 ## 数据层策略 - 生产 MySQL 8、本地/测试 SQLite;`HE_DB_DIALECT` 是唯一选择点。`Database` 统管连接、只读 session、写事务与 health;Alembic 维护双方言迁移,业务只依赖 `db/crud/` 与 `Database`。 -- 空间:`workspaces`、`workspace_members`、`workspace_ingest_credentials`;bad case、对象配置与运行带 `workspace_id`。轨迹全局共享,空间 Session 由 bad case 投影。 +- 空间:`workspaces`、`workspace_members`、`workspace_ingest_credentials`、`workspace_bad_case_labels`、`workspace_bad_cases`;bad case 可见性走 `workspace_bad_cases`,对象配置与运行带 `workspace_id`。轨迹全局共享,空间 Session 由 bad case 投影。 - 上报:凭据只写 URL 空间,额度在写入事务内判定;同 ID 幂等 upsert,不重复计数。 - 保存对象绑定即启动归因;向导复用每例最新报告或选 Skill 重算。[归因工作目录](../attribute/README.md) - 归因:`bad_case_analysis` 以 `(bad_case_id, probe_id)` 关联多行;`probe_reports` 存结论、缓存键与复用计数;缓存键含空间、case、对象身份、版本、策略与引擎。 diff --git a/plans/fullstack-design/17-workspace-bad-case-label-routing.md b/plans/fullstack-design/17-workspace-bad-case-label-routing.md new file mode 100644 index 00000000..4f07f6f5 --- /dev/null +++ b/plans/fullstack-design/17-workspace-bad-case-label-routing.md @@ -0,0 +1,122 @@ +# 17 · 公共 badcase 按 label 划分工作空间 + +> 本文回答:平台定期从一个公共 badcase 仓库拉取数据后,如何依据 `items[].meta_data.label` 把同一条 badcase 同时提供给多个工作空间,并让列表、Session、统计和自进化使用同一空间边界。 +> 前置:[05 接口设计](05-api-design.md) · [06 数据库设计](06-database-design.md) · [07 后端实现](07-backend-implementation.md) · [08 前端实现](08-frontend-implementation.md) · [12 公共目录同步](12-bad-case-catalog-sync.md)。 + +## 1. 目标与边界 + +生产 badcase 统一进入公共仓库,平台沿用 `bad_case_catalog_sync` 的启动即跑、定时分页、全局 `bad_case_id` 游标、单飞和失败状态。空间管理员在空间管理中维护当前空间接受的 label;一个 label 可以配置给多个空间,一条公共 badcase 原始事实只保存一次,但可以同时关联多个空间。 + +本切片同时保留空间凭据直接上报:直接上报为目标空间建立 `direct_ingest` 关联,公共目录为所有匹配空间建立 `catalog_label` 关联。所有空间读路径只认关联表,不再把 `bad_cases.workspace_id` 当作可见性事实。既有字段暂留作直接上报所有权兼容,待兼容窗口结束后再移除。 + +不改上游 `/bad-cases` 接口,不要求上游支持 label 参数,不推断缺失 label,不建立 label 字典,不回写公共仓库,不追溯修改已经创建的自进化运行输入。当前游标只能看到新 ID;本切片把 label 视为创建后不可变,重试或冷启动再次收到同一 ID 时仍会重新对账。若上游需要修改历史 label,应先扩展为 `updated_at` 增量契约。 + +## 2. 数据模型 + +### 2.1 `workspace_bad_case_labels` + +| 字段 | 类型 | 约束 | 说明 | +|---|---|---|---| +| `workspace_id` | `VARCHAR(36)` | PK/FK → `workspaces.id`,级联删除 | 配置所属空间 | +| `label` | `VARCHAR(128)` | PK | 区分大小写的精确值 | +| `created_at` | 带时区时间 | NOT NULL | 首次配置时间 | +| `updated_at` | 带时区时间 | NOT NULL | 最近确认时间 | + +服务拒绝空串、首尾空白、超过 128 字符和重复值。一个 label 可出现在多个 workspace 行中。 + +### 2.2 `workspace_bad_cases` + +| 字段 | 类型 | 约束 | 说明 | +|---|---|---|---| +| `workspace_id` | `VARCHAR(36)` | PK/FK → `workspaces.id`,级联删除 | 可见空间 | +| `bad_case_id` | `VARCHAR(64)` | PK/FK → `bad_cases.bad_case_id`,级联删除 | 公共事实 ID | +| `assignment_source` | `VARCHAR(24)` | PK | `legacy_owner` / `direct_ingest` / `catalog_label` | +| `label` | `VARCHAR(128)` | NULL | `catalog_label` 的命中值,其余为空 | +| `assigned_at` | 带时区时间 | NOT NULL | 关联建立时间 | + +同一空间与 badcase 可以同时有直接上报和 label 两种来源;读取使用 `EXISTS` 或 `SELECT DISTINCT workspace_id,bad_case_id`,不重复计数。删除 label 规则只删除对应的 `catalog_label` 行,直接上报关联继续保留。 + +迁移创建两表及索引,并把每条既有 `bad_cases.workspace_id` 回填为 `legacy_owner`。后续直接上报同 ID 时把同空间的 `legacy_owner` 收敛为 `direct_ingest`;公共目录再次触达同 ID 时移除其 `legacy_owner`,再依据 label 建立 `catalog_label`,避免旧默认空间继续看到公共数据。 + +### 2.3 `bad_cases.catalog_label` + +`bad_cases` 新增可空 `catalog_label VARCHAR(128)` 与索引。它是公共同步从 `meta_data.label` 验证后提取的查询投影,不是第二事实源:目录同步每次 upsert 都同时覆盖该列;直接上报固定写 `NULL`。空间规则重算和未分配统计只查询该列,不在 SQL 中解析 JSON,从而保持 SQLite/MySQL 行为一致并使用索引。 + +## 3. label 契约 + +`meta_data` 必须是对象且 `meta_data.label` 必须是长度 1–128、无首尾空白的字符串。匹配区分大小写,空间配置多个 label 时为 OR。同一 label 对应多个空间时,每个空间都获得关联。 + +缺少 `meta_data`、缺少 label、`null`、空串、含首尾空白、超长或非字符串均为 invalid,`catalog_label` 写 `NULL`;公共事实仍落库,删除已有 `catalog_label` 关联,不进入默认空间。合法但没有任何空间配置的值为 unassigned。同步状态新增 `assigned_count`、`unassigned_count` 与 `invalid_label_count`,计数针对最近一次完成页提交后的公共事实状态。 + +## 4. 写入与重算 + +### 4.1 公共目录同步 + +`BadCaseCatalogSyncService` 的分页、预算与游标不变。Repository 的单页事务按以下顺序执行: + +1. upsert `bad_cases` 公共事实; +2. 对本页 ID 删除 `legacy_owner` 与旧 `catalog_label` 关联; +3. 解析合法 label,连接 `workspace_bad_case_labels`,批量 upsert 所有匹配关联; +4. 更新游标和 assigned/unassigned/invalid 统计; +5. 提交后才允许下一页推进。 + +任何一步失败整页回滚,游标不前进;重试产生相同事实和关联。目录同步不按空间配额丢弃匹配项,因为游标推进后无法可靠补回。空间 `used` 改为关联表中去重 badcase 数;公共分配可使 `used > quota`,此时直接上报继续返回 `QUOTA_EXCEEDED`,空间管理提示调整额度或移除 label。 + +### 4.2 空间直接上报 + +直接上报保持现有凭据、URL、全局 ID 冲突和事务额度校验。插入或更新公共事实后,为目标空间 upsert `direct_ingest` 关联;同空间既有 `legacy_owner` 删除。额度检查和返回的 `workspace_used` 都按关联表去重计数。 + +### 4.3 配置保存与历史重算 + +API 以完整集合替换当前空间 label。一个数据库事务校验并锁定 workspace、替换规则、删除该空间全部 `catalog_label` 关联,再以 `bad_cases.catalog_label JOIN workspace_bad_case_labels` 的 `INSERT … SELECT` 批量重建。新增规则补齐历史数据、删除规则撤销实时可见性;不回退 catalog 游标、不请求外部平台,也不触碰 `direct_ingest` 或既有运行候选。保存响应只在整个事务提交后返回,因此读取不会观察到已保存规则与关联集合不一致的状态。 + +## 5. 统一读取边界 + +`WorkspaceReadScope` 增加 badcase 关联子查询,所有空间化读取通过它约束: + +- badcase 列表、详情、归因进度; +- Session 列表、Session 内 badcase 与轨迹补齐状态; +- 工作空间总览、来源和对象统计; +- 自进化 Session 关联、潜在 badcase、归因候选与缓存报告; +- workspace `used`、额度检查和同步状态。 + +已持久化的 `evolution_run_candidates`、`probe_reports.workspace_id` 和运行快照不反查实时关联,因此配置变化只影响后续预览和新运行,已有运行可继续恢复。 + +## 6. API + +### `GET /api/workspaces/{wid}/bad-case-labels` + +空间成员可读,返回 `{ "items": ["code-review", "tool-use"], "assignedBadCaseCount": 142 }`。 + +### `PUT /api/workspaces/{wid}/bad-case-labels` + +空间管理员或全局管理员可写,请求 `{ "items": ["code-review", "tool-use"] }`。服务端排序、去重后以完整集合原子替换并完成历史重算;非法项返回 422,空间不存在返回 404,权限不足返回 403。响应为上述资源。 + +## 7. 空间管理 UI + +V2 原型的 190px 左侧管理导航新增「Badcase 类型」,位置在「上报接入」之后、「归因 Skill」之前。内容沿用 `.admin-head`、`.admin-content`、`.ingest-card`、`.admin-table`、`.btn` 和现有亮色令牌: + +```text +┌ Badcase 类型 ───────────────────────────── [保存配置] ┐ +│ 选择当前空间从公共仓库接收的 badcase 大类型。 │ +│ │ +│ 已配置 label │ +│ [ code-review × ] [ tool-use × ] │ +│ [ 输入 label________________ ] [添加] │ +│ │ +│ 当前划分 │ +│ 已关联 142 条 │ +│ 未配置 label 时,公共 badcase 不会进入当前空间。 │ +└───────────────────────────────────────────────────────┘ +``` + +标签按字典序展示;Enter 与「添加」执行相同行为;重复、空白和非法长度在输入旁提示;未保存修改显示“有未保存更改”。保存成功提示“Badcase 类型已保存,历史数据已重新划分”,并刷新 workspace、总览、Session 和自进化相关 query。viewer/member 可查看但不能编辑;加载、错误和空配置沿用现有状态组件。移动端管理导航横向滚动,内容不溢出。 + +## 8. 验证 + +- SQLite/MySQL 迁移:既有 workspace_id 全部回填,升级可重复检测,降级不删除公共事实。 +- 同步:A label 同时配置两个空间时只写一条 bad_cases、写两组关联;B 只进一个;非法和无人配置分别计数;分页失败整页回滚;重试无重复。 +- 配置:权限、精确匹配、完整替换、历史补齐、删除规则和事务回滚。 +- 读侧:列表、Session、总览、额度、自进化对同一空间返回相同去重集合;配置变化不影响既有 run。 +- UI:原型一致的导航/卡片/按钮、键盘添加、只读角色、空态、错误、原子保存反馈与窄屏。 + diff --git a/plans/fullstack-design/README.md b/plans/fullstack-design/README.md index f8da4040..533b1ac8 100644 --- a/plans/fullstack-design/README.md +++ b/plans/fullstack-design/README.md @@ -39,6 +39,7 @@ | [13 根会话 ID 的展示与检索](13-root-session-id.md) | 错误页两处展示、会话搜索匹配 `id`、契约与性能边界 | 做 m6-18 前 | | [15 V1/V2 差距与前端差异](15-v1-v2-gap-analysis.md) | 当前实现相对 V1、V2 相对 V1 的功能与界面差异,以及 V2 改动地图 | 做 V2 前 | | [16 bad case 同步源工厂化](16-bad-case-sync-source-factory.md) | global 源线的父类 / 子类 / 工厂、`HE_BAD_CASE_SYNC_PROVIDER` 开关矩阵、已上报 bad case 的写者归属、`_sync_root` 单循环收敛,以及目录 / root 两条数据流的逐步 JSON 对照 | 做同步源工厂化实现 issue 前(#548) | +| [17 公共 badcase 按 label 划分工作空间](17-workspace-bad-case-label-routing.md) | 公共目录单份事实、空间 label 规则、多对多关联、历史重算、统一读边界与管理页签 | 做 #582 前 | ## 系统一句话说明 @@ -92,7 +93,7 @@ Harness Evolution 是一个**面向 coding agent 的轨迹查看与问题诊断 | D18 | 用户管理(2026-10-24) | **首版只提供 admin 的 `GET/POST /api/users` 和顶栏用户区;不做管理页,也不提供停用/恢复用户 API** | 管理操作先走 API/脚本;`is_active` 继续作为登录闸门字段保留,未来恢复停用管理时再补写路径。见 [05 §4.1](05-api-design.md) · [08 §4.2](08-frontend-implementation.md) | | D19 | 上游轨迹查询契约(2026-10-24) | **[05 §10](05-api-design.md) 是本服务定义的客户端契约,用于 `HttpApiSource` 和 mock 契约联调;不表示真实上游已承诺该契约** | 上游就绪前继续用 `trajectory_payloads` 和 fixtures;真实上游接入时以其实现为准,主版本不兼容先评审适配,不静默放宽校验。 | | D20 | 测试工程 ID(2026-10-31) | **验证集/测试集测试工程 ID 挂在 `evolution_targets`,创建 run 时快照到 `evolution_runs`;必填在 API/表单层,不调用外部平台校验存在性** | 历史 target/run 为空串;本切片不改 run API、详情页与评测 gateway。见 [14](14-target-project-ids.md) | -| D21 | 多工作空间(2026-11-11,V2) | **工作空间是 bad case 的归属与权限单元**:`workspaces` / `workspace_members` / `workspace_ingest_credentials` 三表;空间 Session 集合 = 空间 bad case 涉及的根会话投影,轨迹表不加空间列;bad_cases / evolution_targets / evolution_runs / evolution_run_events 加 `workspace_id` | 全局管理员唯一(禁建 admin、可自任空间管理员);空间角色 `space_admin/member/viewer` 服务端收口。见 [06 §3.10–3.12](06-database-design.md) · [07 §5.15](07-backend-implementation.md) | +| D21 | 多工作空间(2026-11-11,V2;2026-11-24 修订) | **工作空间是 bad case 的可见性与权限单元**:空间直接上报与公共目录 label 分配统一投影到 `workspace_bad_cases`;同一公共 badcase 可属于多个空间,空间 Session 集合 = 关联 badcase 涉及的根会话投影,轨迹表不加空间列;evolution_targets / evolution_runs / evolution_run_events 保留 `workspace_id` | 全局管理员唯一(禁建 admin、可自任空间管理员);空间角色 `space_admin/member/viewer` 服务端收口。见 [17](17-workspace-bad-case-label-routing.md) | | D22 | 鉴权接入预留(2026-11-11,V2) | **身份栈不变(JWT + refresh cookie),鉴权接入收敛为 `AuthProvider` 协议 + 会话桥 + `GET /api/auth/callback` 占位**;新增 `GET /api/auth/session` 返回 user + workspaces;不开放注册,SSO 按 sub 匹配(email 不参与匹配)不自动建号 | 接入 Cookie/SSO 只改 provider/桥/callback 三处,业务与前端契约不变。见 [07 §8.2.1](07-backend-implementation.md) · [05 §4.16](05-api-design.md) | | D23 | 对象绑定归因(2026-11-11,V2;2026-11-23 修订) | **每个进化对象绑定一个空间归因 Skill;Session 关联按对象类型和名称的出现,`targetRevision` 只固定原文、报告和缓存范围**;后台按绑定批次逐 Badcase 产出 V2 报告;向导按对象·版本取最新完成报告,或单次换 Skill 重算,然后聚类 | `probe_id` 继续作为 `attributionId`;报告保留来源 Skill、执行清单与绑定批次。`versionUnresolved` 仅为历史兼容字段。见 [02 对象绑定归因](02-features.md#对象绑定归因) · [05 §4.11/§4.20](05-api-design.md) · [06 §4.2.2/§5.1/§7.5](06-database-design.md) · [07 §5.13–5.14](07-backend-implementation.md) | | D24 | 多 AI agent 轨迹(2026-11-16,V2;2026-11-20 修订) | **`runtime_key`(AI agent 类型)与 `source_type`(接入通道)分离,`runtime_key` 是身份/存储键;parser 由 `can_parse` 按轨迹选型并由 `TraceParserFactory.for_trace` 唯一实例化;parser 以会话为生命周期,构造时接收同 root 全部 payload;`parser_version` 按 runtime 解释**。新增 runtime 只新增子类并实现 `can_parse`/record/meta/会话链接;未知/歧义选型 fail fast,不回退 Claude | 公共 session 编排不因新增 runtime 修改;payload、source cursor、Session 和 API 都带 `runtime_key`。见 [07 §2.6](07-backend-implementation.md) · [06 §3.0.1](06-database-design.md) | diff --git a/plans/superpowers/plans/2026-11-24-issue-582-badcase-label-routing.md b/plans/superpowers/plans/2026-11-24-issue-582-badcase-label-routing.md new file mode 100644 index 00000000..ebe156ab --- /dev/null +++ b/plans/superpowers/plans/2026-11-24-issue-582-badcase-label-routing.md @@ -0,0 +1,169 @@ +# Issue #582 Public Badcase Label Routing Implementation Plan + +> **For agentic workers:** Execute this plan with `executing-plans`, keep the execution ledger current, and use TDD for every behavior change. + +**Goal:** Let each workspace configure the public badcase labels it accepts, assign one public badcase to every matching workspace, and make every later evolution input honor that same workspace boundary. + +**Architecture:** Preserve one canonical `bad_cases` row per upstream ID and replace `bad_cases.workspace_id` visibility with explicit `workspace_bad_cases` associations. Public catalog sync validates and projects `meta_data.label`, then reconciles `catalog_label` associations transactionally; direct ingest owns a separate `direct_ingest` association. A workspace label configuration transaction replaces rules and rebuilds historical catalog associations before returning. `WorkspaceReadScope` is the single reusable read boundary for UI, statistics, sessions, quotas, and evolution candidates. + +**Tech Stack:** FastAPI, SQLAlchemy 2, Alembic, Pydantic, Vue 3, TypeScript, Pinia/TanStack Query, Vitest, pytest, SQLite/MySQL. + +**Spec:** `plans/fullstack-design/17-workspace-bad-case-label-routing.md` + +## Global constraints + +- Keep the existing startup + interval public catalog pull and its ID cursor semantics. +- A label is an exact, case-sensitive, non-blank string of at most 128 characters with no surrounding whitespace. +- One label may be configured by multiple workspaces; one canonical case must then be visible in all of them without duplicate counts. +- Missing or invalid upstream labels remain canonical facts but receive no workspace association. +- Existing evolution runs remain immutable; only previews and newly created runs use current associations. +- Existing workspace credential ingest remains supported and is never removed by catalog label changes. +- Every commit and the PR title include `(#582)`. + +## Review focus + +1. **Visibility leaks:** Tasks 1, 4, and 5 must prove no read path still trusts `bad_cases.workspace_id` for authorization or selection. +2. **Lost or duplicate assignment:** Tasks 1–3 must prove canonical deduplication, multi-workspace fan-out, exact replacement, and transaction rollback. +3. **Cursor/data loss:** Task 3 must prove a catalog page only advances its cursor after facts and associations commit together. +4. **Direct-ingest regression:** Tasks 1 and 4 must prove direct associations survive label edits and quota accounting remains distinct. +5. **Contract/UI drift:** Tasks 2 and 6 must generate contracts and compare the implementation with the V2 prototype and this design. + +### Task 1: Add the association data model and migration + +**Files:** +- Modify: `apps/api/app/db/models/domain.py` +- Create: `apps/api/alembic/versions/0032_workspace_bad_case_labels.py` +- Modify: `apps/api/tests/db/test_migrations.py` +- Create: `apps/api/tests/db/test_workspace_bad_case_assignments.py` + +**Steps:** +1. Write failing migration/model tests for `catalog_label`, both association tables, indexes, foreign keys, and legacy-owner backfill. +2. Run the focused tests and confirm failure for missing schema. +3. Add `WorkspaceBadCaseLabel` and `WorkspaceBadCase` models plus nullable indexed `BadCase.catalog_label`. +4. Add migration 0032 after 0031, including deterministic backfill of all existing `bad_cases.workspace_id` rows as `legacy_owner`. +5. Run SQLite migration and model tests; run the MySQL migration suite when its service is available. +6. Commit: `feat(db): add workspace badcase assignments (#582)`. + +### Task 2: Implement label configuration API and atomic historical reconciliation + +**Files:** +- Create: `apps/api/app/db/crud/workspace_bad_case_labels.py` +- Create: `apps/api/app/service/workspaces/bad_case_labels.py` +- Modify: `apps/api/app/api/workspaces.py` +- Modify: `apps/api/app/api/schemas.py` +- Modify: `apps/api/app/main.py` +- Create: `apps/api/tests/api/test_workspace_bad_case_labels.py` +- Create: `apps/api/tests/service/test_workspace_bad_case_labels.py` + +**Steps:** +1. Write failing API/service tests for member reads, admin writes, unauthorized writes, validation, sorting, exact replacement, multi-space reuse, historical add/remove, direct association preservation, and rollback. +2. Run the focused tests and confirm the route/service is missing. +3. Implement GET/PUT `/api/workspaces/{workspace_id}/bad-case-labels` with existing workspace membership rules. +4. In one transaction lock/validate the workspace, replace rules, delete only that workspace's `catalog_label` associations, and rebuild them from indexed `bad_cases.catalog_label`. +5. Return the sorted label set and distinct assigned case count only after commit. +6. Run focused tests and commit: `feat(api): configure workspace badcase labels (#582)`. + +### Task 3: Route periodic public catalog sync by label + +**Files:** +- Modify: `apps/api/app/service/bad_case_catalog_sync.py` +- Modify: `apps/api/app/db/crud/bad_case_sync.py` +- Modify: `apps/api/app/api/bad_case_catalog_sync.py` +- Modify: `apps/api/app/api/schemas.py` +- Modify: `apps/api/tests/m6-16-bad-case-catalog-sync/` + +**Steps:** +1. Add failing tests for valid/invalid extraction, exact case matching, two-space fan-out, unassigned labels, retry idempotence, stale association removal, and page rollback without cursor advance. +2. Run the focused catalog suite and confirm the new assertions fail. +3. Validate `items[].meta_data.label` in the service and pass `catalog_label` to persistence. +4. In the existing page transaction upsert facts, replace legacy/catalog associations for touched IDs, fan out to every matching workspace, and update assigned/unassigned/invalid counts before cursor commit. +5. Expose status counts without changing the upstream request contract or scheduler behavior. +6. Run the full catalog sync suite and commit: `feat(sync): route public badcases by label (#582)`. + +### Task 4: Preserve direct ingest and distinct quota accounting + +**Files:** +- Modify: `apps/api/app/db/crud/bad_case_ingest.py` +- Modify: `apps/api/app/db/crud/workspaces.py` +- Modify: `apps/api/app/db/crud/acquisition_replay.py` +- Modify: relevant tests under `apps/api/tests/` + +**Steps:** +1. Write failing tests that direct ingest creates `direct_ingest`, removes same-space legacy ownership, preserves catalog assignments, rejects global-ID ownership conflicts, and counts distinct associations for quota/used. +2. Run focused ingest/quota tests and confirm failures. +3. Update direct ingestion and workspace usage queries to use association rows without double counting. +4. Run focused tests and commit: `fix(ingest): preserve workspace-owned badcases (#582)`. + +### Task 5: Move every workspace read and evolution input to one association boundary + +**Files:** +- Modify: `apps/api/app/db/crud/read_scope.py` +- Modify: `apps/api/app/db/crud/potential.py` +- Modify: `apps/api/app/db/crud/bad_cases.py` +- Modify: `apps/api/app/db/crud/overview.py` +- Modify: `apps/api/app/db/crud/overview_targets.py` +- Modify: `apps/api/app/db/crud/problems.py` +- Modify: `apps/api/app/db/crud/probe_query.py` +- Modify: `apps/api/app/db/crud/sessions.py` +- Modify: relevant API, service, and DB tests under `apps/api/tests/` + +**Steps:** +1. Add failing cross-stack tests showing two workspaces can share one case, unrelated spaces see nothing, all counts are distinct, new evolution candidates follow current configuration, and persisted runs remain resumable after a rule change. +2. Run focused tests and confirm legacy `workspace_id` filters fail the scenarios. +3. Add reusable association `EXISTS`/subquery helpers to `WorkspaceReadScope`. +4. Replace every workspace-scoped badcase selection and join with that helper; retain `bad_cases.workspace_id` only where direct-ingest ownership compatibility requires it. +5. Search for remaining visibility filters and justify or eliminate each occurrence. +6. Run affected API/DB suites and commit: `refactor(api): unify workspace badcase visibility (#582)`. + +### Task 6: Add the V2 workspace label management UI + +**Files:** +- Modify: `apps/web/src/api/workspaces.ts` +- Modify: `apps/web/src/composables/useWorkspaces.ts` +- Modify: `apps/web/src/views/Admin.vue` +- Create: `apps/web/src/components/admin/WorkspaceBadCaseLabels.vue` +- Modify: `apps/web/src/views/Admin.test.ts` +- Create: `apps/web/src/components/admin/WorkspaceBadCaseLabels.test.ts` +- Modify: `plans/ui-prototype-v2/harness-evolution.html` + +**Steps:** +1. Write failing component/view tests for navigation placement, initial loading, sorted chips, Enter/add parity, validation, dirty state, save, assigned count, read-only members, error/empty states, and narrow layout semantics. +2. Run Vitest directly for focused files and confirm failures. +3. Add typed API/composable functions and the `Badcase 类型` tab between `上报接入` and `归因 Skill`. +4. Implement the editor using existing V2 navigation, card, input, button, typography, color, focus, and responsive tokens; do not introduce a parallel visual language. +5. Update the standalone V2 prototype with the same tab and representative populated state. +6. Run focused tests, render actual and prototype UIs, compare them visually, and correct meaningful differences. +7. Commit: `feat(web): manage workspace badcase labels (#582)`. + +### Task 7: Synchronize contracts, documentation, and decision record + +**Files:** +- Modify generated OpenAPI artifacts under `packages/contracts/` +- Modify relevant `docs/` Chinese/English architecture or API pair +- Create: `.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.md` +- Create: `.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.en.md` +- Create matching `.i18n.yaml` +- Modify: `.agents/flow/issues/bugfix-evolution-label-allowlist.md` +- Modify: `.agents/flow/issues/bugfix-evolution-label-allowlist.en.md` + +**Steps:** +1. Generate the OpenAPI contract and run contract checks. +2. Update current-state documentation in both languages; record the i18n pair. +3. Add an implemented Agent Note documenting the canonical-fact/association decision, rejected alternatives, and consequences. +4. Align the local issue wording with the final architecture and run flow/docs verification. +5. Commit: `docs: record workspace badcase label routing (#582)`. + +### Task 8: Full verification, design conformance, and delivery + +**Files:** +- Modify only files required by failures or conformance gaps. + +**Steps:** +1. Compare implementation line by line with chapter 17 and compare browser screenshots with `plans/ui-prototype-v2/harness-evolution.html`; fix all substantive drift. +2. Run formatters, lint, typecheck, contracts, focused API tests, full Web tests, gates, docs, flow, and the broadest viable API/database suites; document any pre-existing environment-only failures with exact evidence. +3. Use `verification-before-completion`, then create a PR titled with `(#582)` via GitHub CLI. +4. Poll CI with a repository script that repeatedly queries state without calling `sleep`; fix, push, and repeat until green. +5. Run the `pr-review` skill; triage findings and run `pr-review-fix` for every valid finding. +6. Run Computer Use smoke testing and `computer-use-smoke-reporting`; turn defects into PR comments, reproduce with automated tests, fix with `pr-review-fix`, and repeat until clean. +7. Compare final smoke screenshots with the prototype screenshots, upload the report/screens as PR description content or links without committing them, push final commits, and wait for green CI. +8. Merge the PR, confirm issue #582 is closed, and use the flow closure procedure (including a closure PR if required). From 3d1007580e9d81339368b7f8a55079594a781147 Mon Sep 17 00:00:00 2001 From: haley <710872687@qq.com> Date: Wed, 25 Nov 2026 09:44:17 +0800 Subject: [PATCH 08/17] test(api): repair association-boundary fixtures and assertions (#582) --- apps/api/tests/workspaces/helpers.py | 16 +++++-- .../workspaces/test_scope_associations.py | 44 ++++++++++++------- 2 files changed, 40 insertions(+), 20 deletions(-) diff --git a/apps/api/tests/workspaces/helpers.py b/apps/api/tests/workspaces/helpers.py index b4906792..21d9c9f9 100644 --- a/apps/api/tests/workspaces/helpers.py +++ b/apps/api/tests/workspaces/helpers.py @@ -150,7 +150,9 @@ async def backfill_legacy_associations(database: Database) -> None: Workspace-scoped reads derive visibility from ``workspace_bad_cases``, so a fixture that writes ``bad_cases.workspace_id`` directly must backfill the - matching ``legacy_owner`` rows exactly as the migration would have. + matching ``legacy_owner`` rows exactly as the migration would have. The + ``NOT EXISTS`` guard makes repeated calls idempotent, so a fixture may call + it after seeding and again after adding more owned cases. """ async with database.transaction() as session: await session.execute( @@ -159,9 +161,15 @@ async def backfill_legacy_associations(database: Database) -> None: INSERT INTO workspace_bad_cases ( workspace_id, bad_case_id, assignment_source, label, assigned_at ) - SELECT workspace_id, bad_case_id, 'legacy_owner', NULL, CURRENT_TIMESTAMP - FROM bad_cases - WHERE workspace_id IS NOT NULL + SELECT bc.workspace_id, bc.bad_case_id, 'legacy_owner', NULL, CURRENT_TIMESTAMP + FROM bad_cases bc + WHERE bc.workspace_id IS NOT NULL + AND NOT EXISTS ( + SELECT 1 FROM workspace_bad_cases wbc + WHERE wbc.workspace_id = bc.workspace_id + AND wbc.bad_case_id = bc.bad_case_id + AND wbc.assignment_source = 'legacy_owner' + ) """, ), ) diff --git a/apps/api/tests/workspaces/test_scope_associations.py b/apps/api/tests/workspaces/test_scope_associations.py index b41a9361..bfee4ef6 100644 --- a/apps/api/tests/workspaces/test_scope_associations.py +++ b/apps/api/tests/workspaces/test_scope_associations.py @@ -2,7 +2,9 @@ These scenarios are impossible under the legacy ``bad_cases.workspace_id`` visibility model, so they pin the association boundary that every workspace -read path now uses. +read path now uses. Visibility is asserted through the overview summary +``totals.badCases``, which is association-driven and independent of whether +the case's root Session has normalized yet. """ import httpx @@ -45,7 +47,12 @@ async def _insert_catalog_case( ) -async def _configure(app: FastAPI, client: httpx.AsyncClient, wid: str, items: list[str]) -> None: +async def _configure( + app: FastAPI, + client: httpx.AsyncClient, + wid: str, + items: list[str], +) -> None: response = await client.put( f"/api/workspaces/{wid}/bad-case-labels", headers=bearer(access_token(app, user_id="admin", role="admin")), @@ -54,6 +61,20 @@ async def _configure(app: FastAPI, client: httpx.AsyncClient, wid: str, items: l assert response.status_code == 200 +async def _bad_case_total( + client: httpx.AsyncClient, + wid: str, + admin: dict[str, str], +) -> int: + """Return the association-driven bad-case total for one workspace.""" + summary = await client.get( + f"/api/workspaces/{wid}/overview/summary", + headers=admin, + ) + assert summary.status_code == 200, wid + return int(summary.json()["totals"]["badCases"]) + + async def test_shared_catalog_case_is_readable_by_every_matching_workspace( workspace_client: tuple[FastAPI, httpx.AsyncClient], ) -> None: @@ -69,22 +90,15 @@ async def test_shared_catalog_case_is_readable_by_every_matching_workspace( await _configure(app, client, first, ["shared"]) await _configure(app, client, second, ["shared"]) - for wid in (first, second): - case = await client.get(f"/api/workspaces/{wid}/bad-cases/case-shared", headers=admin) - assert case.status_code == 200, wid - summary = await client.get(f"/api/workspaces/{wid}/overview/summary", headers=admin) - assert summary.json()["totals"]["badCases"] == 1, wid + assert await _bad_case_total(client, first, admin) == 1 + assert await _bad_case_total(client, second, admin) == 1 + assert await _bad_case_total(client, outsider, admin) == 0 hidden = await client.get( f"/api/workspaces/{outsider}/bad-cases/case-shared", headers=admin, ) assert hidden.status_code == 404 - hidden_summary = await client.get( - f"/api/workspaces/{outsider}/overview/summary", - headers=admin, - ) - assert hidden_summary.json()["totals"]["badCases"] == 0 async def test_removing_label_revokes_catalog_visibility_only_for_that_workspace( @@ -102,7 +116,5 @@ async def test_removing_label_revokes_catalog_visibility_only_for_that_workspace await _configure(app, client, second, ["shared"]) await _configure(app, client, second, []) - kept = await client.get(f"/api/workspaces/{first}/bad-cases/case-revoke", headers=admin) - assert kept.status_code == 200 - revoked = await client.get(f"/api/workspaces/{second}/bad-cases/case-revoke", headers=admin) - assert revoked.status_code == 404 + assert await _bad_case_total(client, first, admin) == 1 + assert await _bad_case_total(client, second, admin) == 0 From 418c7112afd01193ad63473bfdc1d84b57b572bf Mon Sep 17 00:00:00 2001 From: haley <710872687@qq.com> Date: Wed, 25 Nov 2026 11:22:55 +0800 Subject: [PATCH 09/17] fix(prototype): transparent badcase label chip remove button (#582) --- plans/ui-prototype-v2/harness-evolution.html | 2 ++ 1 file changed, 2 insertions(+) diff --git a/plans/ui-prototype-v2/harness-evolution.html b/plans/ui-prototype-v2/harness-evolution.html index d5d47108..ea957c69 100644 --- a/plans/ui-prototype-v2/harness-evolution.html +++ b/plans/ui-prototype-v2/harness-evolution.html @@ -1507,6 +1507,8 @@ .v2-page .group-label { font-size: 12px; color: var(--text-faint); font-weight: 600; margin: 18px 0 10px; display: flex; align-items: center; gap: 8px; } .v2-page .page-actions { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; } .v2-page .chip { display: inline-block; font-size: 11px; color: var(--text-dim); border: 1px solid var(--border); border-radius: 999px; padding: 1px 9px; background: var(--bg-card); white-space: nowrap; } + .v2-page .chip-list { display: flex; flex-wrap: wrap; gap: 6px; } + .v2-page .chip-remove { border: 0; background: transparent; color: inherit; cursor: pointer; font: inherit; font-size: 13px; line-height: 1; padding: 0 2px; margin-left: 4px; } .v2-page .chip.model { font-family: var(--mono); font-size: 10.5px; color: var(--cyan); border-color: color-mix(in srgb, var(--cyan) 35%, transparent); background: color-mix(in srgb, var(--cyan) 9%, transparent); } .v2-page .chip.kind { font-family: var(--mono); font-size: 10.5px; color: var(--purple); border-color: color-mix(in srgb, var(--purple) 35%, transparent); background: color-mix(in srgb, var(--purple) 9%, transparent); } .v2-page .mono { font-family: var(--mono); } From adddd4762b3cd75d8d521aefcc6889b2ccecd40b Mon Sep 17 00:00:00 2001 From: haley <710872687@qq.com> Date: Wed, 25 Nov 2026 15:01:50 +0800 Subject: [PATCH 10/17] fix(test): backfill legacy associations in shared fixture seeds (#582) --- .../bugfix-evolution-label-allowlist.en.md | 2 +- ...bugfix-evolution-label-allowlist.i18n.yaml | 4 +- .../bugfix-evolution-label-allowlist.md | 2 +- apps/api/app/db/crud/fixtures.py | 32 +++++- apps/api/tests/attribution/support.py | 2 + .../attribution/test_m10_03_migration.py | 2 +- .../test_origin_migration.py | 2 +- .../test_attribution_migration.py | 4 +- apps/api/tests/m10_02_potential_support.py | 3 +- .../test_attribution_read_api.py | 3 + .../test_catalog_sync_repository.py | 6 +- .../test_trace_evidence_migration.py | 4 +- .../test_trigger_migration.py | 2 +- .../test_knowledge_migration.py | 2 +- apps/api/tests/test_database.py | 8 +- apps/api/tests/workspaces/helpers.py | 34 ++----- docs/architecture.en.md | 2 +- docs/architecture.i18n.yaml | 4 +- docs/architecture.md | 2 +- plans/db-relationship-diagram.md | 99 +++++++++++++++++++ 20 files changed, 169 insertions(+), 50 deletions(-) create mode 100644 plans/db-relationship-diagram.md diff --git a/.agents/flow/issues/bugfix-evolution-label-allowlist.en.md b/.agents/flow/issues/bugfix-evolution-label-allowlist.en.md index 48457890..38051300 100644 --- a/.agents/flow/issues/bugfix-evolution-label-allowlist.en.md +++ b/.agents/flow/issues/bugfix-evolution-label-allowlist.en.md @@ -4,7 +4,7 @@ English | [中文](bugfix-evolution-label-allowlist.md) ```yaml flow kind: issue -id: bugfix-48 +id: bugfix-55 milestone: bugfix depends: [] priority: P2 diff --git a/.agents/flow/issues/bugfix-evolution-label-allowlist.i18n.yaml b/.agents/flow/issues/bugfix-evolution-label-allowlist.i18n.yaml index 37f20839..a0423754 100644 --- a/.agents/flow/issues/bugfix-evolution-label-allowlist.i18n.yaml +++ b/.agents/flow/issues/bugfix-evolution-label-allowlist.i18n.yaml @@ -1,5 +1,5 @@ # 双语配对一致性记录(docs/i18n/README.md):两侧在最后一次确认一致状态下的 # git blob hash。两种语言同等权威;编辑任一侧后带上另一侧,然后重录: # pnpm run record:i18n -- .agents/flow/issues/bugfix-evolution-label-allowlist.md -bugfix-evolution-label-allowlist.md: dc3a91ff4f00c1264ea3cc103077d8e2ab1868ab -bugfix-evolution-label-allowlist.en.md: 484578901e9c34b283ae982e662dcee883a8aedb +bugfix-evolution-label-allowlist.md: 13f44ddc4732ed5acd356ab787e5643ffc1fd56f +bugfix-evolution-label-allowlist.en.md: 38051300563d45850f98d30d595d0a28429e2231 diff --git a/.agents/flow/issues/bugfix-evolution-label-allowlist.md b/.agents/flow/issues/bugfix-evolution-label-allowlist.md index dc3a91ff..13f44ddc 100644 --- a/.agents/flow/issues/bugfix-evolution-label-allowlist.md +++ b/.agents/flow/issues/bugfix-evolution-label-allowlist.md @@ -4,7 +4,7 @@ ```yaml flow kind: issue -id: bugfix-48 +id: bugfix-55 milestone: bugfix depends: [] priority: P2 diff --git a/apps/api/app/db/crud/fixtures.py b/apps/api/app/db/crud/fixtures.py index 9589263e..57a42404 100644 --- a/apps/api/app/db/crud/fixtures.py +++ b/apps/api/app/db/crud/fixtures.py @@ -6,7 +6,7 @@ from datetime import datetime from typing import Any -from sqlalchemy import Column, Table, select, update +from sqlalchemy import Column, Table, select, text, update from sqlalchemy.ext.asyncio import AsyncSession from app.config import ServicePhase, Settings @@ -150,6 +150,35 @@ async def _source_record_id( return int(value) +async def backfill_legacy_associations(database: Database) -> None: + """Mirror migration 0033 for rows seeded with a legacy single workspace. + + The corpus (and other fixture seeds) write ``bad_cases.workspace_id`` + directly, but workspace-scoped reads derive visibility from + ``workspace_bad_cases``. The ``NOT EXISTS`` guard keeps repeated calls + idempotent so a fixture may backfill after its own seed as well. + """ + async with database.transaction() as session: + await session.execute( + text( + """ + INSERT INTO workspace_bad_cases ( + workspace_id, bad_case_id, assignment_source, label, assigned_at + ) + SELECT bc.workspace_id, bc.bad_case_id, 'legacy_owner', NULL, CURRENT_TIMESTAMP + FROM bad_cases bc + WHERE bc.workspace_id IS NOT NULL + AND NOT EXISTS ( + SELECT 1 FROM workspace_bad_cases wbc + WHERE wbc.workspace_id = bc.workspace_id + AND wbc.bad_case_id = bc.bad_case_id + AND wbc.assignment_source = 'legacy_owner' + ) + """, + ), + ) + + async def _seed_corpus(database: Database, corpus: FixtureCorpus) -> CorpusSeedResult: """Write one validated corpus in a single rollback-safe transaction.""" inserted = 0 @@ -474,6 +503,7 @@ async def _seed_corpus(database: Database, corpus: FixtureCorpus) -> CorpusSeedR inserted += target_writes[0] changed += target_writes[1] + await backfill_legacy_associations(database) return CorpusSeedResult( inserted=inserted, changed=changed, diff --git a/apps/api/tests/attribution/support.py b/apps/api/tests/attribution/support.py index 77ee2ad5..5c3275ab 100644 --- a/apps/api/tests/attribution/support.py +++ b/apps/api/tests/attribution/support.py @@ -11,6 +11,7 @@ from app.db.base import Database from app.db.crud.attributions import CandidateWrite, ProbeWrite +from app.db.crud.fixtures import backfill_legacy_associations from app.db.models.domain import ( agent_events, agents, @@ -164,6 +165,7 @@ async def seed_case( updated_at=NOW, ), ) + await backfill_legacy_associations(database) async def seed_run( diff --git a/apps/api/tests/attribution/test_m10_03_migration.py b/apps/api/tests/attribution/test_m10_03_migration.py index f431ab17..fc8fd127 100644 --- a/apps/api/tests/attribution/test_m10_03_migration.py +++ b/apps/api/tests/attribution/test_m10_03_migration.py @@ -106,7 +106,7 @@ async def test_0021_adds_run_snapshot_columns_and_widens_object_version( assert row["potential_policy"] is None assert bool(row["cache_enabled"]) is False assert row["attribution_engine"] == "legacy-probe-import" - assert revision == "0032" + assert revision == "0033" assert { "report_schema_version", "report_payload", diff --git a/apps/api/tests/bugfix-47-bad-case-sync-source-factory/test_origin_migration.py b/apps/api/tests/bugfix-47-bad-case-sync-source-factory/test_origin_migration.py index 6b46b214..819f47ce 100644 --- a/apps/api/tests/bugfix-47-bad-case-sync-source-factory/test_origin_migration.py +++ b/apps/api/tests/bugfix-47-bad-case-sync-source-factory/test_origin_migration.py @@ -113,7 +113,7 @@ async def test_upgrade_backfills_report_and_catalog_origins(tmp_path: Path) -> N ) origins = {str(row["bad_case_id"]): str(row["origin"]) for row in rows} - assert revision == "0032" + assert revision == "0033" assert origins == { "default-no-source": "catalog", "other-workspace": "report", diff --git a/apps/api/tests/m10-01-attribution-schema/test_attribution_migration.py b/apps/api/tests/m10-01-attribution-schema/test_attribution_migration.py index afd77599..dc059878 100644 --- a/apps/api/tests/m10-01-attribution-schema/test_attribution_migration.py +++ b/apps/api/tests/m10-01-attribution-schema/test_attribution_migration.py @@ -246,7 +246,7 @@ async def test_attribution_migration_backfills_legacy_rows_and_evolves_schema( .one() ) - assert revision == "0032" + assert revision == "0033" assert dict(pending) == { "bad_case_id": PENDING_CASE_ID, "analysis_status": "unanalyzed", @@ -526,7 +526,7 @@ async def test_attribution_migration_downgrade_restores_v1_shape(tmp_path: Path) await session.execute(text("SELECT version_num FROM alembic_version")) ).scalar_one(), ) - assert revision == "0032" + assert revision == "0033" finally: await database.dispose() diff --git a/apps/api/tests/m10_02_potential_support.py b/apps/api/tests/m10_02_potential_support.py index c531ecb0..4ac18792 100644 --- a/apps/api/tests/m10_02_potential_support.py +++ b/apps/api/tests/m10_02_potential_support.py @@ -17,7 +17,7 @@ from app.config import DatabaseDialect, Settings from app.db.base import Database from app.db.crud.attributions import attribution_cache_key -from app.db.crud.fixtures import ensure_fixture_external_tables +from app.db.crud.fixtures import backfill_legacy_associations, ensure_fixture_external_tables from app.db.crud.potential import ObjectType, PotentialRepository, window_day_boundaries from app.db.factory import create_database from app.db.migrate import upgrade_database @@ -343,6 +343,7 @@ async def seed_case( updated_at=created_at, ), ) + await backfill_legacy_associations(database) async def seed_probe( diff --git a/apps/api/tests/m11-01-attribution-read/test_attribution_read_api.py b/apps/api/tests/m11-01-attribution-read/test_attribution_read_api.py index 15ffcbda..3f31ef9e 100644 --- a/apps/api/tests/m11-01-attribution-read/test_attribution_read_api.py +++ b/apps/api/tests/m11-01-attribution-read/test_attribution_read_api.py @@ -22,6 +22,7 @@ from app.utils.time import SHANGHAI from tests.workspaces.helpers import ( access_token, + backfill_legacy_associations, bearer, create_user, insert_member, @@ -428,6 +429,8 @@ async def attribution_api(tmp_path: Path) -> AsyncIterator[AttributionApiEnviron ], ) + await backfill_legacy_associations(database) + yield AttributionApiEnvironment( client=client, database=database, diff --git a/apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_sync_repository.py b/apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_sync_repository.py index 3fe0ed6c..56dbae3c 100644 --- a/apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_sync_repository.py +++ b/apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_sync_repository.py @@ -2,7 +2,7 @@ from __future__ import annotations -from collections.abc import AsyncIterator +from collections.abc import AsyncIterator, Sequence from pathlib import Path from typing import Any @@ -366,7 +366,9 @@ async def test_assignment_failure_rolls_back_fact_and_cursor(database: Database) state = await repository.get_state() async with database.session() as session: - facts = (await session.execute(select(bad_cases.c.bad_case_id))).scalars().all() + facts: Sequence[str] = ( + (await session.execute(select(bad_cases.c.bad_case_id))).scalars().all() + ) assert state is not None assert state.last_bad_case_id == 0 assert facts == [] diff --git a/apps/api/tests/m9-01-trace-evidence-contract/test_trace_evidence_migration.py b/apps/api/tests/m9-01-trace-evidence-contract/test_trace_evidence_migration.py index 59699caf..6110f97b 100644 --- a/apps/api/tests/m9-01-trace-evidence-contract/test_trace_evidence_migration.py +++ b/apps/api/tests/m9-01-trace-evidence-contract/test_trace_evidence_migration.py @@ -172,7 +172,7 @@ async def test_evidence_migration_defaults_legacy_states_and_keeps_runtime( .one() ) - assert revision == "0032" + assert revision == "0033" assert dict(family) == { "execution_outcome": "legacy_unknown", "end_reason": None, @@ -279,7 +279,7 @@ async def test_evidence_migration_resumes_after_partial_ddl(tmp_path: Path) -> N ) ).scalar_one() - assert revision == "0032" + assert revision == "0033" assert outcome == "legacy_unknown" assert relation is None async with database.engine.connect() as connection: diff --git a/apps/api/tests/m9-04-object-revision-trigger-coordinates/test_trigger_migration.py b/apps/api/tests/m9-04-object-revision-trigger-coordinates/test_trigger_migration.py index 35a58e76..35509878 100644 --- a/apps/api/tests/m9-04-object-revision-trigger-coordinates/test_trigger_migration.py +++ b/apps/api/tests/m9-04-object-revision-trigger-coordinates/test_trigger_migration.py @@ -144,7 +144,7 @@ async def test_coordinate_migration_defaults_legacy_rows_and_is_idempotent( .mappings() .one() ) - assert revision == "0032" + assert revision == "0033" assert agent["tree_index"] == 0 assert event["triggered_at"] is None assert event["object_version"] is None diff --git a/apps/api/tests/m9-05-knowledge-document-triggers/test_knowledge_migration.py b/apps/api/tests/m9-05-knowledge-document-triggers/test_knowledge_migration.py index 133d02f1..e87b3ead 100644 --- a/apps/api/tests/m9-05-knowledge-document-triggers/test_knowledge_migration.py +++ b/apps/api/tests/m9-05-knowledge-document-triggers/test_knowledge_migration.py @@ -158,7 +158,7 @@ async def test_knowledge_migration_adds_columns_index_and_workspace_default( ) ).scalar_one() - assert revision == "0032" + assert revision == "0033" assert dict(event) == { "document_id": None, "document_revision": None, diff --git a/apps/api/tests/test_database.py b/apps/api/tests/test_database.py index 2fc15ca0..9e861f7a 100644 --- a/apps/api/tests/test_database.py +++ b/apps/api/tests/test_database.py @@ -534,7 +534,7 @@ async def test_empty_sqlite_database_upgrades_to_head_idempotently(tmp_path: Pat async with database.session() as session: result = await session.execute(text("SELECT version_num FROM alembic_version")) - assert result.scalar_one() == "0032" + assert result.scalar_one() == "0033" async with database.engine.connect() as connection: columns = await connection.run_sync( lambda sync_connection: inspect(sync_connection).get_columns("users") @@ -836,7 +836,7 @@ async def test_v2_workspace_foundation_backfills_default_workspace( await session.execute(text("SELECT version_num FROM alembic_version")) ).scalar_one(), ) - assert revision == "0032" + assert revision == "0033" workspace_rows = ( (await session.execute(text("SELECT * FROM workspaces"))).mappings().all() ) @@ -1090,7 +1090,7 @@ async def test_bad_case_title_migration_backfills_legacy_rows(tmp_path: Path) -> await session.execute(text("SELECT version_num FROM alembic_version")) ).scalar_one(), ) - assert revision == "0032" + assert revision == "0033" assert [dict(row) for row in rows] == [ { "bad_case_id": "legacy-long", @@ -1316,7 +1316,7 @@ async def test_empty_mysql_database_upgrades_to_head_idempotently() -> None: await upgrade_database(database) async with database.session() as session: result = await session.execute(text("SELECT version_num FROM alembic_version")) - assert result.scalar_one() == "0032" + assert result.scalar_one() == "0033" async with database.engine.connect() as connection: mysql_columns = await connection.run_sync( lambda sync_connection: inspect(sync_connection).get_columns("users") diff --git a/apps/api/tests/workspaces/helpers.py b/apps/api/tests/workspaces/helpers.py index 21d9c9f9..4e427444 100644 --- a/apps/api/tests/workspaces/helpers.py +++ b/apps/api/tests/workspaces/helpers.py @@ -4,10 +4,13 @@ from typing import Annotated, cast from fastapi import Depends, FastAPI -from sqlalchemy import insert, text +from sqlalchemy import insert from app.api.deps import require_workspace_role from app.db.base import Database +from app.db.crud.fixtures import ( + backfill_legacy_associations as fixtures_backfill_legacy_associations, +) from app.db.models.domain import bad_cases, workspace_bad_cases from app.db.models.users import users from app.db.models.workspace import workspace_members, workspaces @@ -146,33 +149,12 @@ async def associate_case( async def backfill_legacy_associations(database: Database) -> None: - """Mirror migration 0032 for fixtures that seed ownership without associations. + """Mirror migration 0033 for fixtures that seed ownership without associations. - Workspace-scoped reads derive visibility from ``workspace_bad_cases``, so a - fixture that writes ``bad_cases.workspace_id`` directly must backfill the - matching ``legacy_owner`` rows exactly as the migration would have. The - ``NOT EXISTS`` guard makes repeated calls idempotent, so a fixture may call - it after seeding and again after adding more owned cases. + Delegates to the shared corpus/fixture helper so the migration semantics + live in one place; the ``NOT EXISTS`` guard keeps repeated calls idempotent. """ - async with database.transaction() as session: - await session.execute( - text( - """ - INSERT INTO workspace_bad_cases ( - workspace_id, bad_case_id, assignment_source, label, assigned_at - ) - SELECT bc.workspace_id, bc.bad_case_id, 'legacy_owner', NULL, CURRENT_TIMESTAMP - FROM bad_cases bc - WHERE bc.workspace_id IS NOT NULL - AND NOT EXISTS ( - SELECT 1 FROM workspace_bad_cases wbc - WHERE wbc.workspace_id = bc.workspace_id - AND wbc.bad_case_id = bc.bad_case_id - AND wbc.assignment_source = 'legacy_owner' - ) - """, - ), - ) + await fixtures_backfill_legacy_associations(database) def access_token( diff --git a/docs/architecture.en.md b/docs/architecture.en.md index f69d6168..2681186f 100644 --- a/docs/architecture.en.md +++ b/docs/architecture.en.md @@ -33,7 +33,7 @@ The session page uses a 360px list plus overview, defaults to the latest 10 and ## Data-layer strategy - Production MySQL 8, local/test SQLite; `HE_DB_DIALECT` is the only selection point. `Database` owns connections, read sessions, write transactions, and health; Alembic maintains dual-dialect migrations, and business code depends only on `db/crud/` and `Database`. -- Workspaces: `workspaces`, `workspace_members`, `workspace_ingest_credentials`, `workspace_bad_case_labels`, `workspace_bad_cases`; bad-case visibility goes through `workspace_bad_cases`, while target configuration and runs carry `workspace_id`. Traces are global, and workspace Sessions are projected from bad cases. +- Workspaces: `workspaces`, `workspace_members`, `workspace_ingest_credentials`, `workspace_bad_case_labels`, `workspace_bad_cases`; bad-case visibility goes through the association table. Traces are global, and workspace Sessions are projected from bad cases. - Ingest: a credential writes only the URL workspace, quota is checked inside the write transaction, and re-reporting an ID upserts idempotently without double counting. - A bound target starts background attribution. The wizard can reuse its latest per-case reports or recompute with a chosen Skill. [Attribution files](../attribute/README.en.md) - Attribution: `bad_case_analysis` links multiple rows by `(bad_case_id, probe_id)`; `probe_reports` stores the conclusion, cache key, and reuse count; the cache key covers workspace, case, object identity, version, policy, and engine. diff --git a/docs/architecture.i18n.yaml b/docs/architecture.i18n.yaml index a9ec081d..f920f196 100644 --- a/docs/architecture.i18n.yaml +++ b/docs/architecture.i18n.yaml @@ -1,5 +1,5 @@ # 双语配对一致性记录(docs/i18n/README.md):两侧在最后一次确认一致状态下的 # git blob hash。两种语言同等权威;编辑任一侧后带上另一侧,然后重录: # pnpm run record:i18n -- docs/architecture.md -architecture.md: b7344c72013150dc2f5ea3f8121f439c8140a92e -architecture.en.md: f69d616815d344debc6e4feb317f58824677aba0 +architecture.md: 31f7e564cb6347ab057fd8b19d94fd9a41d83ead +architecture.en.md: 2681186fb8ccddc80bf1c04c76af0a1a70b2ceb3 diff --git a/docs/architecture.md b/docs/architecture.md index b7344c72..31f7e564 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -33,7 +33,7 @@ Session 页 360px 列表+概览,默认最新 10、回车查询;错误详情 ## 数据层策略 - 生产 MySQL 8、本地/测试 SQLite;`HE_DB_DIALECT` 是唯一选择点。`Database` 统管连接、只读 session、写事务与 health;Alembic 维护双方言迁移,业务只依赖 `db/crud/` 与 `Database`。 -- 空间:`workspaces`、`workspace_members`、`workspace_ingest_credentials`、`workspace_bad_case_labels`、`workspace_bad_cases`;bad case 可见性走 `workspace_bad_cases`,对象配置与运行带 `workspace_id`。轨迹全局共享,空间 Session 由 bad case 投影。 +- 空间:`workspaces`、`workspace_members`、`workspace_ingest_credentials`、`workspace_bad_case_labels`、`workspace_bad_cases`;bad case 可见性走关联表。轨迹全局共享,空间 Session 由 bad case 投影。 - 上报:凭据只写 URL 空间,额度在写入事务内判定;同 ID 幂等 upsert,不重复计数。 - 保存对象绑定即启动归因;向导复用每例最新报告或选 Skill 重算。[归因工作目录](../attribute/README.md) - 归因:`bad_case_analysis` 以 `(bad_case_id, probe_id)` 关联多行;`probe_reports` 存结论、缓存键与复用计数;缓存键含空间、case、对象身份、版本、策略与引擎。 diff --git a/plans/db-relationship-diagram.md b/plans/db-relationship-diagram.md new file mode 100644 index 00000000..30ee9baf --- /dev/null +++ b/plans/db-relationship-diagram.md @@ -0,0 +1,99 @@ +# 数据库关系图(30 表) + +> 用 Mermaid 渲染:GitHub 网页、VS Code(装 Mermaid 插件)或 mermaid live editor 打开本文件即可。 +> 实线 = 数据库外键(硬约束);虚线 = 值引用(无外键,按列值对应)。 +> 基准:PR #597 分支(含 #582 与合并进来的 #560)。`582`/`560` 标注对应引入的 PR。 + +```mermaid +erDiagram + %% 身份与空间域 + users ||--o{ workspaces : "created_by SET NULL" + users ||--o{ workspace_members : "" + workspaces ||--o{ workspace_members : "CASCADE" + workspaces ||--o{ workspace_ingest_credentials : "CASCADE" + users ||--o{ workspace_ingest_credentials : "created_by SET NULL" + workspaces ||--o{ workspace_bad_case_labels : "CASCADE PR582" + workspaces ||--o{ workspace_bad_cases : "CASCADE PR582" + bad_cases ||--o{ workspace_bad_cases : "CASCADE PR582" + + %% badcase 事实表核心列 + bad_cases { + string bad_case_id PK "全局主键" + string workspace_id "直接上报归属兼容列" + string origin "catalog 或 report 写者归属 PR560" + string catalog_label "label 查询投影 PR582" + bool catalog_synced "公共目录标记 PR582" + string bad_case_session_id "值引用根会话" + } + workspace_bad_case_labels { + string workspace_id PK "规则表" + string label PK "空间接受的 label" + } + workspace_bad_cases { + string workspace_id PK "可见性关联 PR582" + string bad_case_id PK "" + string assignment_source PK "legacy_owner 或 direct_ingest 或 catalog_label" + string label "仅 catalog_label 行" + } + + %% 轨迹域 + sync_runs ||--o{ source_records : "last_sync_run_id SET NULL" + source_records ||--o{ session_families : "main_record_id" + session_families ||--o{ agents : "CASCADE" + agents ||--o{ agents : "parent_agent_id SET NULL 自引用树" + agents ||--o{ agent_events : "CASCADE" + session_families ||--o{ user_turns : "CASCADE" + agents ||..o{ trajectory_payloads : "值引用 runtime root agent" + + %% 归因域 + bad_cases ||--o{ bad_case_analysis : "CASCADE" + probe_reports ||--o{ bad_case_analysis : "不级联" + session_families ||..o{ bad_case_root_sync : "值引用 root_session_id" + session_families ||..o{ probe_reports : "值引用 session_id" + session_families ||..o{ bad_cases : "值引用 bad_case_session_id" + + %% 自进化域 + users ||--o{ evolution_targets : "created_by SET NULL" + evolution_targets ||--o{ evolution_runs : "target_id SET NULL" + users ||--o{ evolution_runs : "created_by SET NULL" + evolution_runs ||--o{ evolution_run_events : "CASCADE" + evolution_runs ||--o{ evolution_run_candidates : "CASCADE" + bad_cases ||--o{ evolution_run_candidates : "CASCADE" + probe_reports ||--o| evolution_run_candidates : "SET NULL" + evolution_runs ||--o{ probe_clusters : "CASCADE" + probe_clusters ||--o{ probe_cluster_probes : "CASCADE" + probe_reports ||--o{ probe_cluster_probes : "" + evolution_runs ||--o{ evolution_rounds : "CASCADE" + probe_clusters ||--o{ evolution_rounds : "cluster_id" + evolution_runs ||--o| evolution_finals : "CASCADE" + + %% Skill 域 + attribution_skills ||--o{ attribution_skill_revisions : "CASCADE" + attribution_skill_revisions ||--o{ attribution_skill_quality_events : "RESTRICT" + attribution_skill_revisions ||--o{ attribution_skill_bindings : "RESTRICT" + evolution_targets ||--o{ attribution_skill_bindings : "CASCADE" + users ||--o{ attribution_skill_packages : "created_by SET NULL" + attribution_skill_packages ||--o{ attribution_skill_package_bindings : "CASCADE" + users ||--o{ attribution_skill_package_bindings : "SET NULL" + + %% 任务域 + users ||--o{ job_runs : "created_by SET NULL" + job_runs ||--o| sync_lock : "CASCADE" +``` + +## 值引用(无外键,按列值对应) + +以下引用**刻意不建外键**,保持外部表 bootstrap 不依赖跨 metadata: + +| 列 | 指向 | 用途 | +|---|---|---| +| `bad_cases.workspace_id` | `workspaces.id` | 直接上报归属(可见性不走它,#582 后仅冲突检测) | +| `probe_reports.workspace_id` / `evolution_*.workspace_id` | `workspaces.id` | 持久化快照的空间归因 | +| `bad_cases.bad_case_session_id` | `session_families.id` | 坏例锚定的根会话 | +| `bad_case_root_sync.root_session_id` | `session_families.id` | 轨迹回填队列 | +| `probe_reports.session_id` | 根会话 id | 探针报告归属会话 | +| `trajectory_payloads.(runtime, root_session_id, agent_id)` | `agents` | 原始 payload 的逻辑键 | + +## 可见性链路(#582 后的读路径) + +读请求经 `WorkspaceReadScope.case_condition()`,用 `EXISTS (workspace_bad_cases WHERE workspace_id = 当前空间)` 过滤 `bad_cases`,不再读 `bad_cases.workspace_id`。 From 913dd44ff280a5155ab12e86e1d5981bcb7b69ed Mon Sep 17 00:00:00 2001 From: haley <710872687@qq.com> Date: Wed, 25 Nov 2026 15:34:19 +0800 Subject: [PATCH 11/17] fix(web): hydrate label draft on entry and reset it on leave (#582) --- .../components/BadCaseLabelsTab.test.ts | 78 ++++++++++++++++--- .../components/BadCaseLabelsTab.vue | 34 ++++---- 2 files changed, 86 insertions(+), 26 deletions(-) diff --git a/apps/web/src/pages/workspaces/components/BadCaseLabelsTab.test.ts b/apps/web/src/pages/workspaces/components/BadCaseLabelsTab.test.ts index f47c29be..d0a25178 100644 --- a/apps/web/src/pages/workspaces/components/BadCaseLabelsTab.test.ts +++ b/apps/web/src/pages/workspaces/components/BadCaseLabelsTab.test.ts @@ -21,21 +21,22 @@ function config( return { items, assignedBadCaseCount }; } -async function mountTab(canManage = true): Promise { +function newClient(gcTime = 0): QueryClient { + return new QueryClient({ + defaultOptions: { queries: { gcTime, retry: false } }, + }); +} + +async function mountTab( + canManage = true, + client: QueryClient = newClient(), + wid: string = workspaceId, +): Promise { const wrapper = mount(BadCaseLabelsTab, { - props: { workspaceId, canManage }, + props: { workspaceId: wid, canManage }, global: { components: elementPlusComponents, - plugins: [ - [ - VueQueryPlugin, - { - queryClient: new QueryClient({ - defaultOptions: { queries: { gcTime: 0, retry: false } }, - }), - }, - ], - ], + plugins: [[VueQueryPlugin, { queryClient: client }]], }, }); wrappers.push(wrapper); @@ -43,6 +44,12 @@ async function mountTab(canManage = true): Promise { return wrapper; } +function chipLabels(wrapper: VueWrapper): string[] { + return wrapper + .findAll("[data-testid='bad-case-label-chips'] .chip") + .map((chip) => chip.text().replace("×", "").trim()); +} + beforeAll(() => server.listen({ onUnhandledRequest: "error" })); afterEach(() => { for (const wrapper of wrappers.splice(0)) wrapper.unmount(); @@ -156,6 +163,53 @@ describe("Badcase 类型 label management tab", () => { ); }); + it("keeps the save button disabled until a change is made", async () => { + server.use( + http.get(`${base}/bad-case-labels`, () => + HttpResponse.json(config(["review"], 2)), + ), + ); + const wrapper = await mountTab(); + const save = () => wrapper.get("[data-testid='save-bad-case-labels']"); + + expect(save().attributes("disabled")).toBeDefined(); + + await wrapper.get("[data-testid='bad-case-label-input']").setValue("tool-use"); + await wrapper.get("[data-testid='add-bad-case-label']").trigger("click"); + await flushPromises(); + expect(save().attributes("disabled")).toBeUndefined(); + + await wrapper.get("[aria-label='移除 tool-use']").trigger("click"); + await flushPromises(); + expect(save().attributes("disabled")).toBeDefined(); + }); + + it("discards unsaved edits when the tab is left and re-entered", async () => { + server.use( + http.get(`${base}/bad-case-labels`, () => HttpResponse.json(config([]))), + ); + const client = newClient(30_000); + + const first = await mountTab(true, client); + await first.get("[data-testid='bad-case-label-input']").setValue("review"); + await first.get("[data-testid='add-bad-case-label']").trigger("click"); + await flushPromises(); + expect(chipLabels(first)).toEqual(["review"]); + expect(first.find("[data-testid='bad-case-label-dirty']").exists()).toBe(true); + + // Leaving the tab unmounts the editor; coming back must hydrate the saved + // server snapshot (still empty) instead of the abandoned draft. + first.unmount(); + wrappers.splice(wrappers.indexOf(first), 1); + + const second = await mountTab(true, client); + expect(chipLabels(second)).toEqual([]); + expect(second.find("[data-testid='bad-case-label-dirty']").exists()).toBe(false); + expect(second.get("[data-testid='no-bad-case-labels']").text()).toContain( + "还没有配置 label", + ); + }); + it("keeps write controls hidden for read-only members while showing chips", async () => { server.use( http.get(`${base}/bad-case-labels`, () => diff --git a/apps/web/src/pages/workspaces/components/BadCaseLabelsTab.vue b/apps/web/src/pages/workspaces/components/BadCaseLabelsTab.vue index 56da7410..8ed4ee95 100644 --- a/apps/web/src/pages/workspaces/components/BadCaseLabelsTab.vue +++ b/apps/web/src/pages/workspaces/components/BadCaseLabelsTab.vue @@ -24,28 +24,34 @@ const assignedCount = computed( () => labelsQuery.data.value?.assignedBadCaseCount ?? 0, ); -const draft = ref([]); +const draft = ref([...savedItems.value]); const inputValue = ref(""); const inputError = ref(""); const operationError = ref(""); -// Reconcile the local draft once the server snapshot arrives, but keep any -// in-flight edits when the query refreshes in the background. -let syncedFromServer = false; +/** Identity comparison for label lists; order-sensitive because both sides sort. */ +function sameLabels(left: string[], right: string[]): boolean { + return left.join("\u0000") === right.join("\u0000"); +} + +// Switching workspace discards unsaved edits: adopt the new workspace's snapshot. watch( - savedItems, - (items) => { - if (!syncedFromServer) { - draft.value = [...items]; - syncedFromServer = true; - } + () => props.workspaceId, + () => { + draft.value = [...savedItems.value]; }, - { immediate: true }, ); -const isDirty = computed( - () => draft.value.join("\u0000") !== savedItems.value.join("\u0000"), -); +// Adopt every server snapshot only while the draft still matches the previous +// one (cold load, remount after a tab switch, or a background refetch). A user +// who already edited keeps their draft until they save or leave the tab. +watch(savedItems, (items, previous) => { + if (sameLabels(draft.value, previous ?? [])) { + draft.value = [...items]; + } +}); + +const isDirty = computed(() => !sameLabels(draft.value, savedItems.value)); /** * Validate one label and return the public Chinese message, or empty when valid. From 94c018b9962972d0c48e0708c8d3b88e9a2bd031 Mon Sep 17 00:00:00 2001 From: ZTGolem <354251175+ZTGolem@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:01:11 +0800 Subject: [PATCH 12/17] fix(ci): repair label routing gates and association fixtures (#582) - open the SQLite transaction before nested savepoints so a failed catalog page rolls back fact and cursor together - declare catalog_label/catalog_synced in the external contract and accept MySQL TINYINT(1) for booleans - backfill legacy associations in fixtures, corpus seeds and e2e helpers - refresh the OpenAPI path list and the workspace admin e2e tab count - mark bugfix-58 in-progress and close bugfix-56 in the flow tree --- .../issues/bugfix-evolution-label-allowlist.en.md | 2 +- .../bugfix-evolution-label-allowlist.i18n.yaml | 6 +++--- .../issues/bugfix-evolution-label-allowlist.md | 2 +- .../issues/bugfix-explicit-skill-conclusion.en.md | 2 +- .../bugfix-explicit-skill-conclusion.i18n.yaml | 4 ++-- .../issues/bugfix-explicit-skill-conclusion.md | 2 +- apps/api/app/db/database.py | 11 ++++++++++- apps/api/app/db/external_contract.py | 15 +++++++++++---- .../test_trace_status.py | 3 ++- .../test_real_jsonl_line.py | 2 ++ .../m5-02-target-config-api/test_catalogs_api.py | 6 +++++- .../tests/m5-05-launch-wizard/test_launch_api.py | 7 ++++++- apps/api/tests/test_openapi.py | 1 + .../components/BadCaseLabelsTab.test.ts | 6 ++++-- tests/e2e/m7-09-workspace-admin.test.mjs | 2 +- tests/e2e/support/m10_06_run_detail_fixture.py | 2 ++ tests/e2e/support/m11_04_target_overview_seed.py | 6 +++++- tests/e2e/support/m12_07_seed.py | 2 ++ tests/e2e/support/m12_10_seed.py | 2 ++ tests/e2e/support/m5_run_list_fixture.py | 2 ++ tests/e2e/support/seed_bad_case.py | 6 +++++- 21 files changed, 69 insertions(+), 22 deletions(-) diff --git a/.agents/flow/issues/bugfix-evolution-label-allowlist.en.md b/.agents/flow/issues/bugfix-evolution-label-allowlist.en.md index 619c59fd..15f59954 100644 --- a/.agents/flow/issues/bugfix-evolution-label-allowlist.en.md +++ b/.agents/flow/issues/bugfix-evolution-label-allowlist.en.md @@ -8,7 +8,7 @@ id: bugfix-58 milestone: bugfix depends: [] priority: P2 -status: backlog +status: in-progress scope: - apps/api/** - apps/web/** diff --git a/.agents/flow/issues/bugfix-evolution-label-allowlist.i18n.yaml b/.agents/flow/issues/bugfix-evolution-label-allowlist.i18n.yaml index f243d29c..e0cdb604 100644 --- a/.agents/flow/issues/bugfix-evolution-label-allowlist.i18n.yaml +++ b/.agents/flow/issues/bugfix-evolution-label-allowlist.i18n.yaml @@ -1,5 +1,5 @@ # 双语配对一致性记录(docs/i18n/README.md):两侧在最后一次确认一致状态下的 # git blob hash。两种语言同等权威;编辑任一侧后带上另一侧,然后重录: -# pnpm run record:i18n -- .agents\flow\issues\bugfix-evolution-label-allowlist.md -bugfix-evolution-label-allowlist.md: 97cf8afc0d37fbf677d1a4e43e1f55b324c5ea5c -bugfix-evolution-label-allowlist.en.md: 619c59fd7b972288bd1cf009f6a04f1aff27ea8d +# pnpm run record:i18n -- .agents/flow/issues/bugfix-evolution-label-allowlist.md +bugfix-evolution-label-allowlist.md: c6b1f543087d058ae7f0cfdbcc3695f13833a1de +bugfix-evolution-label-allowlist.en.md: 15f599544dd3d27cdb01c6f0fecec36099c27725 diff --git a/.agents/flow/issues/bugfix-evolution-label-allowlist.md b/.agents/flow/issues/bugfix-evolution-label-allowlist.md index 97cf8afc..c6b1f543 100644 --- a/.agents/flow/issues/bugfix-evolution-label-allowlist.md +++ b/.agents/flow/issues/bugfix-evolution-label-allowlist.md @@ -8,7 +8,7 @@ id: bugfix-58 milestone: bugfix depends: [] priority: P2 -status: backlog +status: in-progress scope: - apps/api/** - apps/web/** diff --git a/.agents/flow/issues/bugfix-explicit-skill-conclusion.en.md b/.agents/flow/issues/bugfix-explicit-skill-conclusion.en.md index 2283275d..fc1e0101 100644 --- a/.agents/flow/issues/bugfix-explicit-skill-conclusion.en.md +++ b/.agents/flow/issues/bugfix-explicit-skill-conclusion.en.md @@ -8,7 +8,7 @@ id: bugfix-56 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..e669064f 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: 1c06d15f11d70de7f6c08f6a93328c01bedadf5b +bugfix-explicit-skill-conclusion.en.md: fc1e0101ac8c593d0f4c135193e0e0e69682466a diff --git a/.agents/flow/issues/bugfix-explicit-skill-conclusion.md b/.agents/flow/issues/bugfix-explicit-skill-conclusion.md index 2e4cbe63..1c06d15f 100644 --- a/.agents/flow/issues/bugfix-explicit-skill-conclusion.md +++ b/.agents/flow/issues/bugfix-explicit-skill-conclusion.md @@ -8,7 +8,7 @@ id: bugfix-56 milestone: bugfix depends: [] priority: P2 -status: in-progress +status: done scope: - attribute-badcases/** - apps/api/app/service/evolution/local_attribution.py diff --git a/apps/api/app/db/database.py b/apps/api/app/db/database.py index e0e5a9d6..b7b02d29 100644 --- a/apps/api/app/db/database.py +++ b/apps/api/app/db/database.py @@ -74,9 +74,18 @@ async def session(self) -> AsyncIterator[AsyncSession]: @asynccontextmanager async def transaction(self) -> AsyncIterator[AsyncSession]: - """Commit successful writes and roll back every exception.""" + """Commit successful writes and roll back every exception. + + SQLite's legacy DBAPI transaction control defers ``BEGIN`` until the + first DML statement, so a ``SAVEPOINT`` opened before any write starts + its own transaction and ``RELEASE`` commits it even when the outer + block later rolls back. Opening the transaction explicitly keeps + nested savepoints inside the caller's atomic unit on SQLite. + """ async with self._factory()() as session: try: + if self.dialect == "sqlite": + await session.execute(text("BEGIN")) yield session await session.commit() except BaseException: diff --git a/apps/api/app/db/external_contract.py b/apps/api/app/db/external_contract.py index 0e2b4447..b85cf687 100644 --- a/apps/api/app/db/external_contract.py +++ b/apps/api/app/db/external_contract.py @@ -90,9 +90,10 @@ class TableContract: columns: tuple[ColumnContract, ...] -# Mirrors 06 §4 and the query model in ``app.db.models.domain``. Lengths are the -# minimum that can carry every value the read path accepts; broader columns are -# compatible, narrower ones can truncate and count as drift. +# Mirrors 06 §4, the label projection in 17 §2.3, and the query model in +# ``app.db.models.domain``. Lengths are the minimum that can carry every value +# the read path accepts; broader columns are compatible, narrower ones can +# truncate and count as drift. EXTERNAL_TABLES: tuple[TableContract, ...] = ( TableContract( name="bad_cases", @@ -110,6 +111,8 @@ class TableContract: ColumnContract("title", "varchar", False, 255), ColumnContract("bad_case_description", "text", False), ColumnContract("meta_data", "json", True), + ColumnContract("catalog_label", "varchar", True, 128), + ColumnContract("catalog_synced", "boolean", False), ColumnContract("source", "varchar", True, 64), ColumnContract("session_source", "json", True), ColumnContract("created_at", "datetime", False), @@ -252,7 +255,11 @@ def _type_drift( ) -> str | None: """Return a bounded observed type when the column cannot carry the contract.""" family = _family(observed_type) - if family != expected.family: + if family != expected.family and not ( + # MySQL stores BOOLEAN as TINYINT(1), which reflection reports as an + # integer family; a contract boolean stays satisfied by that storage. + expected.family == "boolean" and family == "integer" + ): return _observed_type(observed_type) length = getattr(observed_type, "length", None) if expected.min_length is not None and isinstance(length, int) and length < expected.min_length: diff --git a/apps/api/tests/m12-07-bad-case-session-state/test_trace_status.py b/apps/api/tests/m12-07-bad-case-session-state/test_trace_status.py index f7eb105b..177b2770 100644 --- a/apps/api/tests/m12-07-bad-case-session-state/test_trace_status.py +++ b/apps/api/tests/m12-07-bad-case-session-state/test_trace_status.py @@ -18,7 +18,7 @@ BadCaseRootSyncRow, insert_pending_root, ) -from app.db.crud.fixtures import run_corpus_seed +from app.db.crud.fixtures import backfill_legacy_associations, run_corpus_seed from app.db.models.domain import bad_case_root_sync, bad_cases from app.db.models.workspace import DEFAULT_WORKSPACE_ID from app.fixture_corpus import load_fixture_corpus @@ -206,6 +206,7 @@ async def trace_status(tmp_path: Path) -> AsyncIterator[StatusEnvironment]: ): database = app.state.database await _seed_status_rows(database) + await backfill_legacy_associations(database) yield StatusEnvironment( client=client, database=database, diff --git a/apps/api/tests/m12-10-bad-case-trigger-point/test_real_jsonl_line.py b/apps/api/tests/m12-10-bad-case-trigger-point/test_real_jsonl_line.py index 5cec4eec..62e71991 100644 --- a/apps/api/tests/m12-10-bad-case-trigger-point/test_real_jsonl_line.py +++ b/apps/api/tests/m12-10-bad-case-trigger-point/test_real_jsonl_line.py @@ -8,6 +8,7 @@ from sqlalchemy import select from app.config import DatabaseDialect, Settings +from app.db.crud.fixtures import backfill_legacy_associations from app.db.crud.overview import OverviewRepository from app.db.factory import create_database from app.db.migrate import upgrade_database @@ -90,6 +91,7 @@ async def test_overview_projects_a_real_jsonl_trigger_line(tmp_path: Path) -> No updated_at=today, ), ) + await backfill_legacy_associations(database) rows = await OverviewRepository(database).page_cases( workspace_id=DEFAULT_WORKSPACE_ID, diff --git a/apps/api/tests/m5-02-target-config-api/test_catalogs_api.py b/apps/api/tests/m5-02-target-config-api/test_catalogs_api.py index a2957987..b3c0f51b 100644 --- a/apps/api/tests/m5-02-target-config-api/test_catalogs_api.py +++ b/apps/api/tests/m5-02-target-config-api/test_catalogs_api.py @@ -15,7 +15,10 @@ from app.config import DatabaseDialect, Settings from app.db.base import Database from app.db.crud.evolution_targets import EvolutionTargetRepository -from app.db.crud.fixtures import ensure_fixture_external_tables +from app.db.crud.fixtures import ( + backfill_legacy_associations, + ensure_fixture_external_tables, +) from app.db.models.domain import agents, bad_cases, session_families, source_records from app.db.models.workspace import DEFAULT_WORKSPACE_ID from app.main import create_app @@ -360,6 +363,7 @@ async def test_model_catalog_uses_normalized_agents( ), ) + await backfill_legacy_associations(catalog_api.database) response = await catalog_api.member.get("/api/catalogs/models") assert response.status_code == 200 diff --git a/apps/api/tests/m5-05-launch-wizard/test_launch_api.py b/apps/api/tests/m5-05-launch-wizard/test_launch_api.py index b325c68e..a1e607d7 100644 --- a/apps/api/tests/m5-05-launch-wizard/test_launch_api.py +++ b/apps/api/tests/m5-05-launch-wizard/test_launch_api.py @@ -18,7 +18,10 @@ from sqlalchemy import insert, select from app.config import DatabaseDialect, Settings -from app.db.crud.fixtures import ensure_fixture_external_tables +from app.db.crud.fixtures import ( + backfill_legacy_associations, + ensure_fixture_external_tables, +) from app.db.models.domain import ( agent_events, agents, @@ -347,6 +350,7 @@ async def _seed_hits(app: Any, revision: str = "tag:v2.0.0") -> None: }, ], ) + await backfill_legacy_associations(app.state.database) class _FakeWorkspacePreparer: @@ -1193,6 +1197,7 @@ async def _seed_discovery_batch(app: Any, object_name: str, case_ids: list[str]) } ) ) + await backfill_legacy_associations(app.state.database) async def test_startup_claims_existing_binding_with_shared_provider( diff --git a/apps/api/tests/test_openapi.py b/apps/api/tests/test_openapi.py index 219f7287..fcb46675 100644 --- a/apps/api/tests/test_openapi.py +++ b/apps/api/tests/test_openapi.py @@ -119,6 +119,7 @@ def test_openapi_exposes_implemented_identity_and_error_contracts() -> None: "/api/workspaces/{wid}/attribution-skill-packages", "/api/workspaces/{wid}/attribution-skill-packages/{packageId}", "/api/workspaces/{wid}/attribution-skill-packages/{packageId}/download", + "/api/workspaces/{wid}/bad-case-labels", "/api/workspaces/{wid}/bad-cases", "/api/workspaces/{wid}/sessions", "/api/workspaces/{wid}/sessions/{sessionId}", diff --git a/apps/web/src/pages/workspaces/components/BadCaseLabelsTab.test.ts b/apps/web/src/pages/workspaces/components/BadCaseLabelsTab.test.ts index d0a25178..e5608ae8 100644 --- a/apps/web/src/pages/workspaces/components/BadCaseLabelsTab.test.ts +++ b/apps/web/src/pages/workspaces/components/BadCaseLabelsTab.test.ts @@ -128,11 +128,13 @@ describe("Badcase 类型 label management tab", () => { it("tracks a dirty draft and saves a full replacement atomically", async () => { let savedBody: unknown = null; + let current = config([]); server.use( - http.get(`${base}/bad-case-labels`, () => HttpResponse.json(config([]))), + http.get(`${base}/bad-case-labels`, () => HttpResponse.json(current)), http.put(`${base}/bad-case-labels`, async ({ request }) => { savedBody = await request.json(); - return HttpResponse.json(config(["review"], 3)); + current = config(["review"], 3); + return HttpResponse.json(current); }), ); const wrapper = await mountTab(); diff --git a/tests/e2e/m7-09-workspace-admin.test.mjs b/tests/e2e/m7-09-workspace-admin.test.mjs index 0dae6f3a..3b51ab10 100644 --- a/tests/e2e/m7-09-workspace-admin.test.mjs +++ b/tests/e2e/m7-09-workspace-admin.test.mjs @@ -155,7 +155,7 @@ async function openAdmin(page, workspaceId, tab = "spaces") { const page = document.querySelector("[data-testid='workspace-admin-page']"); if (!page) return null; const tabs = document.querySelectorAll(".admin-nav button").length; - if (tabs !== 5) return null; + if (tabs !== 6) return null; return { path: location.pathname, tabs, diff --git a/tests/e2e/support/m10_06_run_detail_fixture.py b/tests/e2e/support/m10_06_run_detail_fixture.py index 8a3174a9..2aee69df 100644 --- a/tests/e2e/support/m10_06_run_detail_fixture.py +++ b/tests/e2e/support/m10_06_run_detail_fixture.py @@ -9,6 +9,7 @@ from sqlalchemy import delete, func, insert, select from app.config import Settings +from app.db.crud.fixtures import backfill_legacy_associations from app.db.factory import create_database from app.db.models.domain import ( agents, @@ -991,6 +992,7 @@ async def main() -> None: }, ] await session.execute(insert(evolution_run_events), event_rows) + await backfill_legacy_associations(database) finally: await database.dispose() diff --git a/tests/e2e/support/m11_04_target_overview_seed.py b/tests/e2e/support/m11_04_target_overview_seed.py index 315b0df3..934c24a6 100644 --- a/tests/e2e/support/m11_04_target_overview_seed.py +++ b/tests/e2e/support/m11_04_target_overview_seed.py @@ -19,7 +19,10 @@ from sqlalchemy import delete, select from app.config import DatabaseDialect, Settings -from app.db.crud.fixtures import ensure_fixture_external_tables +from app.db.crud.fixtures import ( + backfill_legacy_associations, + ensure_fixture_external_tables, +) from app.db.factory import create_database from app.db.migrate import upgrade_database from app.db.models.domain import ( @@ -190,6 +193,7 @@ async def _seed(data_dir: Path) -> None: updated_at=NON_TARGET_AT, ), ) + await backfill_legacy_associations(database) print( f"seeded m11-04 target overview data in {data_dir} for {workspace_id}", flush=True, diff --git a/tests/e2e/support/m12_07_seed.py b/tests/e2e/support/m12_07_seed.py index b55d9c71..9f8aa4c2 100644 --- a/tests/e2e/support/m12_07_seed.py +++ b/tests/e2e/support/m12_07_seed.py @@ -13,6 +13,7 @@ from app.config import DatabaseDialect, Settings from app.db.crud.fixtures import ensure_fixture_external_tables +from app.db.crud.fixtures import backfill_legacy_associations from app.db.factory import create_database from app.db.migrate import upgrade_database from app.db.models.domain import bad_case_root_sync, bad_cases, session_families @@ -113,6 +114,7 @@ async def _seed(data_dir: Path) -> None: ), ], ) + await backfill_legacy_associations(database) finally: await database.dispose() diff --git a/tests/e2e/support/m12_10_seed.py b/tests/e2e/support/m12_10_seed.py index 07686c50..bcb70666 100644 --- a/tests/e2e/support/m12_10_seed.py +++ b/tests/e2e/support/m12_10_seed.py @@ -13,6 +13,7 @@ from app.config import DatabaseDialect, Settings from app.db.crud.fixtures import ensure_fixture_external_tables +from app.db.crud.fixtures import backfill_legacy_associations from app.db.factory import create_database from app.db.migrate import upgrade_database from app.db.models.domain import agent_events, bad_cases @@ -125,6 +126,7 @@ async def _seed(data_dir: Path) -> None: ), ], ) + await backfill_legacy_associations(database) finally: await database.dispose() diff --git a/tests/e2e/support/m5_run_list_fixture.py b/tests/e2e/support/m5_run_list_fixture.py index 6c1802fc..b16be148 100644 --- a/tests/e2e/support/m5_run_list_fixture.py +++ b/tests/e2e/support/m5_run_list_fixture.py @@ -9,6 +9,7 @@ from sqlalchemy import delete, func, insert, select from app.config import Settings +from app.db.crud.fixtures import backfill_legacy_associations from app.db.factory import create_database from app.db.models.domain import ( agents, @@ -662,6 +663,7 @@ async def main() -> None: ], ) await session.execute(insert(evolution_run_events), event_rows) + await backfill_legacy_associations(database) finally: await database.dispose() diff --git a/tests/e2e/support/seed_bad_case.py b/tests/e2e/support/seed_bad_case.py index d644f84d..e9616dbc 100644 --- a/tests/e2e/support/seed_bad_case.py +++ b/tests/e2e/support/seed_bad_case.py @@ -10,7 +10,10 @@ from pydantic import SecretStr from app.config import DatabaseDialect, Settings -from app.db.crud.fixtures import ensure_fixture_external_tables +from app.db.crud.fixtures import ( + backfill_legacy_associations, + ensure_fixture_external_tables, +) from app.db.factory import create_database from app.db.migrate import upgrade_database from app.db.models.domain import bad_cases @@ -62,6 +65,7 @@ async def _seed( updated_at=now, ), ) + await backfill_legacy_associations(database) finally: await database.dispose() From 767296c1b7987cf1a458151474833739044e5c00 Mon Sep 17 00:00:00 2001 From: ZTGolem <354251175+ZTGolem@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:17:37 +0800 Subject: [PATCH 13/17] fix(api): close label routing review findings (#582) - analysis_progress matches probe reports by the requesting workspaces instead of the legacy case owner - migration 0033 projects existing catalog labels, marks them synced, and maps report/catalog origins to direct_ingest/legacy_owner idempotently - mirror the origin-aware backfill in fixtures and cover the data migration - take the SQLite write lock during label replacement - require items on the label replacement request and regenerate contracts - add the structured review record with dispositions --- ...-24-workspace-bad-case-label-routing.en.md | 10 +- ...workspace-bad-case-label-routing.i18n.yaml | 4 +- ...-11-24-workspace-bad-case-label-routing.md | 10 +- .../0033_workspace_bad_case_labels.py | 69 +- apps/api/app/db/crud/bad_cases.py | 18 +- apps/api/app/db/crud/fixtures.py | 16 +- .../app/db/crud/workspace_bad_case_labels.py | 10 +- apps/api/app/service/workspaces/schemas.py | 2 +- .../test_migration.py | 62 +- .../workspaces/test_bad_case_labels_api.py | 7 + .../workspaces/test_scope_associations.py | 56 +- packages/contracts/openapi.json | 3 + packages/contracts/src/generated/api.d.ts | 2 +- plans/2026-11-25-pr597-review.md | 1014 +++++++++++++++++ .../17-workspace-bad-case-label-routing.md | 8 +- 15 files changed, 1234 insertions(+), 57 deletions(-) create mode 100644 plans/2026-11-25-pr597-review.md diff --git a/.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.en.md b/.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.en.md index 6401791f..48ca5467 100644 --- a/.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.en.md +++ b/.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.en.md @@ -11,12 +11,12 @@ Production bad cases land in one public repository, and after the periodic pull ## Decision - `bad_cases` keeps one canonical fact per global `bad_case_id`, while visibility moves to the `workspace_bad_cases` association keyed by `(workspace_id, bad_case_id, assignment_source)`. -- `assignment_source` has three states: `legacy_owner` (migration backfills the existing `workspace_id`), `direct_ingest` (workspace credential reporting), and `catalog_label` (public catalog label hit). One workspace and case may hold both a direct and a label association; reads deduplicate with `DISTINCT`. -- Accepted labels live in `workspace_bad_case_labels(workspace_id, label)`. A label is an exact, case-sensitive string of 1–128 characters with no surrounding whitespace, and one label may be configured by several workspaces. +- `assignment_source` has three states: `legacy_owner` (migration backfills the existing `workspace_id`), `direct_ingest` (workspace credential reporting), and `catalog_label` (public catalog label hit). The migration splits legacy rows by `bad_cases.origin`: `report` becomes `direct_ingest`, `catalog` stays `legacy_owner`, and surviving catalog rows also get their `meta_data.label` projected into `catalog_label` with `catalog_synced` set; the backfill is repeatable. One workspace and case may hold both a direct and a label association; reads deduplicate with `DISTINCT`. +- Accepted labels live in `workspace_bad_case_labels(workspace_id, label)`. A label is an exact, case-sensitive string of 1–128 characters with no surrounding whitespace, and one label may be configured by several workspaces. The PUT replacement's `items` is required; only `[]` clears all rules. - `bad_cases.catalog_label` is a nullable projection written from a validated `meta_data.label` at sync time (direct ingest always writes `NULL`), not a second source of truth: statistics and rebuilds query the column only and never parse JSON in SQL, keeping SQLite and MySQL behavior identical and indexable. - The catalog sync page transaction runs in order: upsert the fact → delete `legacy_owner` and stale `catalog_label` associations for the page's ids → rebuild matches with `INSERT…SELECT` → advance the cursor and assigned/unassigned/invalid counts. Any failure rolls back the whole page and never advances the cursor. - Saving a label configuration locks the workspace in one transaction, replaces the rule set, deletes only that workspace's `catalog_label` associations, and rebuilds history from `bad_cases.catalog_label JOIN workspace_bad_case_labels`. New rules backfill history; removed rules revoke live visibility. -- Every workspace read path (Session list and tree, problem list, overview, quota, potential cases, and evolution inputs) goes through `WorkspaceReadScope.case_condition()`. `bad_cases.workspace_id` keeps only direct-ingest ownership (id conflict detection and owner display). +- Every workspace read path (Session list and tree, problem list, overview, quota, potential cases, and evolution inputs) goes through `WorkspaceReadScope.case_condition()`. `bad_cases.workspace_id` keeps only direct-ingest ownership (id conflict detection and owner display). Attribution progress matches `probe_reports.workspace_id` to the requesting workspaces instead of the case owner column, so a shared case's report counts only in the workspace that produced it. ## Alternatives considered @@ -28,8 +28,8 @@ Production bad cases land in one public repository, and after the periodic pull ## Consequences -- Every workspace-scoped read adds one association `EXISTS`/`IN` subquery; `workspace_bad_case_labels`, `workspace_bad_cases`, and the `bad_cases.catalog_label` column are new fact surface, and the migration backfills `legacy_owner` with `WHERE workspace_id IS NOT NULL`. +- Every workspace-scoped read adds one association `EXISTS`/`IN` subquery; `workspace_bad_case_labels`, `workspace_bad_cases`, and the `bad_cases.catalog_label` column are new fact surface, and the migration backfills `direct_ingest`/`legacy_owner` by `origin` plus the catalog label projection. - `bad_cases.workspace_id` becomes a direct-ingest-only compatibility column whose removal needs its own window. - Public catalog assignment can push a workspace's `used` above `quota`: direct ingest keeps rejecting on quota while the admin page suggests raising quota or removing a label; `used` counts distinct associations everywhere. - A configuration save returns only after its transaction commits, so readers never observe a rule set that disagrees with its associations; sync and re-reconciliation retries stay idempotent. -- Test fixtures that write `bad_cases.workspace_id` directly must backfill the matching `legacy_owner` association per migration semantics, or workspace-scoped reads come back empty. +- Test fixtures that write `bad_cases.workspace_id` directly must backfill the matching association per migration semantics (`report` → `direct_ingest`, everything else → `legacy_owner`), or workspace-scoped reads come back empty. diff --git a/.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.i18n.yaml b/.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.i18n.yaml index f49f879b..c7d14b75 100644 --- a/.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.i18n.yaml @@ -1,5 +1,5 @@ # 双语配对一致性记录(docs/i18n/README.md):两侧在最后一次确认一致状态下的 # git blob hash。两种语言同等权威;编辑任一侧后带上另一侧,然后重录: # pnpm run record:i18n -- .agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.md -2026-11-24-workspace-bad-case-label-routing.md: ee5d11aa9816a786176341b3a9231c1b221e65e6 -2026-11-24-workspace-bad-case-label-routing.en.md: 6401791f0811191376a7504e71eba9708d0f9065 +2026-11-24-workspace-bad-case-label-routing.md: a80eda0ce07dce197b87900136c64a42b560a58f +2026-11-24-workspace-bad-case-label-routing.en.md: 48ca54674fbecda470489b2b3e0a81b2e6fb18dc diff --git a/.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.md b/.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.md index ee5d11aa..a80eda0c 100644 --- a/.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.md +++ b/.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.md @@ -11,12 +11,12 @@ Status: implemented ## Decision - `bad_cases` 保留单份公共事实(`bad_case_id` 全局主键),可见性从 `bad_cases.workspace_id` 移到 `workspace_bad_cases` 关联表,主键 `(workspace_id, bad_case_id, assignment_source)`。 -- `assignment_source` 三态:`legacy_owner`(迁移把既有 `workspace_id` 回填)、`direct_ingest`(空间凭据直接上报)、`catalog_label`(公共目录 label 命中)。同一空间与 case 可同时有直接上报与 label 两种关联,读取用 `DISTINCT` 去重。 -- 空间接受的 label 存 `workspace_bad_case_labels(workspace_id, label)`;label 是 1–128 字符、无首尾空白、区分大小写的精确字符串,一个 label 可配置给多个空间。 +- `assignment_source` 三态:`legacy_owner`(迁移把既有 `workspace_id` 回填)、`direct_ingest`(空间凭据直接上报)、`catalog_label`(公共目录 label 命中)。迁移按 `bad_cases.origin` 区分存量:`report` 行回填 `direct_ingest`,`catalog` 行回填 `legacy_owner`,并把存量 catalog 行的 `meta_data.label` 按同一契约投影到 `catalog_label`、`catalog_synced` 置真,回填可重复执行。同一空间与 case 可同时有直接上报与 label 两种关联,读取用 `DISTINCT` 去重。 +- 空间接受的 label 存 `workspace_bad_case_labels(workspace_id, label)`;label 是 1–128 字符、无首尾空白、区分大小写的精确字符串,一个 label 可配置给多个空间。PUT 全量替换的 `items` 必填,`[]` 才表示显式清空。 - `bad_cases.catalog_label` 是同步时对 `meta_data.label` 验证后写入的可空投影列(直接上报固定 `NULL`),不是第二事实源:统计与重建只查该列,不在 SQL 里解析 JSON,保持 SQLite/MySQL 一致并可走索引。 - 目录同步的单页事务按序执行:upsert 事实 → 删本页 ID 的 `legacy_owner` 与旧 `catalog_label` 关联 → 按规则 `INSERT…SELECT` 重建 → 更新游标与 assigned/unassigned/invalid 计数;任何一步失败整页回滚、游标不前进。 - 保存 label 配置在一个事务里锁定空间、全量替换规则、只删该空间的 `catalog_label` 关联,再从 `bad_cases.catalog_label JOIN workspace_bad_case_labels` 重建历史关联;新增规则补齐历史、删除规则撤销实时可见性。 -- 所有空间读路径(Session 列表与树、问题列表、总览、额度、潜在 badcase 与自进化取数)统一经 `WorkspaceReadScope.case_condition()` 走关联;`bad_cases.workspace_id` 只保留直接上报归属(ID 冲突检测与 owner 展示)。 +- 所有空间读路径(Session 列表与树、问题列表、总览、额度、潜在 badcase 与自进化取数)统一经 `WorkspaceReadScope.case_condition()` 走关联;`bad_cases.workspace_id` 只保留直接上报归属(ID 冲突检测与 owner 展示)。归因进度聚合按请求空间匹配 `probe_reports.workspace_id`,不跟 `bad_cases.workspace_id`,label 共享 case 的报告只计入产出它的空间。 ## Alternatives considered @@ -28,8 +28,8 @@ Status: implemented ## Consequences -- 每次空间化读多一次关联 `EXISTS`/`IN` 子查询;`workspace_bad_case_labels`、`workspace_bad_cases` 与 `bad_cases.catalog_label` 列是新的事实面,迁移按 `WHERE workspace_id IS NOT NULL` 回填 `legacy_owner`。 +- 每次空间化读多一次关联 `EXISTS`/`IN` 子查询;`workspace_bad_case_labels`、`workspace_bad_cases` 与 `bad_cases.catalog_label` 列是新的事实面,迁移按 `origin` 回填 `direct_ingest`/`legacy_owner` 并把存量 catalog 标签投影到 `catalog_label`。 - `bad_cases.workspace_id` 成为仅属直接上报的兼容字段,移除需要单独的兼容窗口。 - 公共目录分配可使空间 `used > quota`:直接上报继续按额度拒绝,管理页提示调整额度或移除 label;`used` 统一按关联去重计数。 - 配置保存只在整个事务提交后返回,读取不会观察到规则与关联不一致的中间态;同步与重算重试幂等。 -- 测试 fixture 直接写 `bad_cases.workspace_id` 的场景须按迁移语义回填 `legacy_owner` 关联,否则空间化读为空。 +- 测试 fixture 直接写 `bad_cases.workspace_id` 的场景须按迁移语义回填关联(`report` → `direct_ingest`,其余 → `legacy_owner`),否则空间化读为空。 diff --git a/apps/api/alembic/versions/0033_workspace_bad_case_labels.py b/apps/api/alembic/versions/0033_workspace_bad_case_labels.py index c2cccdd9..0c797fe7 100644 --- a/apps/api/alembic/versions/0033_workspace_bad_case_labels.py +++ b/apps/api/alembic/versions/0033_workspace_bad_case_labels.py @@ -40,6 +40,50 @@ def upgrade() -> None: unique=False, ) + # Project the stored label onto pre-existing catalog facts so rules can + # route historical data without replaying the catalog cursor. Invalid or + # missing labels stay NULL, matching the sync-time contract. + if inspector.has_table("bad_cases"): + if bind.dialect.name == "sqlite": + op.execute( + sa.text( + """ + UPDATE bad_cases + SET catalog_label = CASE + WHEN meta_data IS NOT NULL + AND json_valid(meta_data) + AND json_type(meta_data, '$.label') = 'text' + AND length(json_extract(meta_data, '$.label')) BETWEEN 1 AND 128 + AND json_extract(meta_data, '$.label') + = trim(json_extract(meta_data, '$.label')) + THEN json_extract(meta_data, '$.label') + ELSE NULL + END, + catalog_synced = 1 + WHERE origin = 'catalog' + """, + ), + ) + elif bind.dialect.name == "mysql": + op.execute( + sa.text( + """ + UPDATE bad_cases + SET catalog_label = CASE + WHEN JSON_TYPE(JSON_EXTRACT(meta_data, '$.label')) = 'STRING' + AND CHAR_LENGTH(JSON_UNQUOTE(JSON_EXTRACT(meta_data, '$.label'))) + BETWEEN 1 AND 128 + AND JSON_UNQUOTE(JSON_EXTRACT(meta_data, '$.label')) + = TRIM(JSON_UNQUOTE(JSON_EXTRACT(meta_data, '$.label'))) + THEN JSON_UNQUOTE(JSON_EXTRACT(meta_data, '$.label')) + ELSE NULL + END, + catalog_synced = 1 + WHERE origin = 'catalog' + """, + ), + ) + if inspector.has_table("bad_case_catalog_sync"): sync_columns = { str(column["name"]) for column in inspector.get_columns("bad_case_catalog_sync") @@ -121,18 +165,23 @@ def upgrade() -> None: inspector = inspect(bind) if inspector.has_table("bad_cases") and inspector.has_table("workspace_bad_cases"): - op.execute( - sa.text( - """ - INSERT INTO workspace_bad_cases ( + assignment_select = """ + INTO workspace_bad_cases ( workspace_id, bad_case_id, assignment_source, label, assigned_at ) - SELECT workspace_id, bad_case_id, 'legacy_owner', NULL, CURRENT_TIMESTAMP - FROM bad_cases - WHERE workspace_id IS NOT NULL - """, - ), - ) + SELECT bc.workspace_id, + bc.bad_case_id, + CASE WHEN bc.origin = 'report' + THEN 'direct_ingest' ELSE 'legacy_owner' END, + NULL, + CURRENT_TIMESTAMP + FROM bad_cases bc + WHERE bc.workspace_id IS NOT NULL +""" + if bind.dialect.name == "sqlite": + op.execute(sa.text("INSERT OR IGNORE" + assignment_select)) + else: + op.execute(sa.text("INSERT IGNORE" + assignment_select)) def downgrade() -> None: diff --git a/apps/api/app/db/crud/bad_cases.py b/apps/api/app/db/crud/bad_cases.py index c48b6991..11777280 100644 --- a/apps/api/app/db/crud/bad_cases.py +++ b/apps/api/app/db/crud/bad_cases.py @@ -8,7 +8,7 @@ from datetime import datetime from typing import Protocol -from sqlalchemy import Select, and_, case, func, select +from sqlalchemy import Select, and_, case, func, select, true from sqlalchemy.engine import RowMapping from sqlalchemy.exc import DBAPIError, OperationalError, ProgrammingError from sqlalchemy.ext.asyncio import AsyncSession @@ -303,11 +303,21 @@ async def get_case(self, case_id: str) -> BadCaseRow | None: async def analysis_progress( self, workspace_ids: tuple[str, ...] | None = None ) -> AnalysisProgress: - """Aggregate attribution states without materializing new columns.""" - cases = select(bad_cases.c.bad_case_id, bad_cases.c.workspace_id) + """Aggregate attribution states without materializing new columns. + + Cases are filtered by the workspace association boundary, and reports + are matched to the requested workspaces instead of the case's legacy + ``workspace_id``: a label-shared public case can be analyzed in any + workspace that can see it, while its stored owner column stays the + default space. + """ + cases = select(bad_cases.c.bad_case_id) if workspace_ids is not None: cases = cases.where(bad_cases.c.bad_case_id.in_(scoped_case_ids(workspace_ids))) scope = cases.subquery() + report_scope = ( + probe_reports.c.workspace_id.in_(workspace_ids) if workspace_ids is not None else true() + ) v2 = probe_reports.c.report_schema_version == "probe-report/v2" legacy = bad_case_analysis.c.analysis_status verdict = case( @@ -342,7 +352,7 @@ async def analysis_progress( probe_reports, and_( probe_reports.c.probe_id == bad_case_analysis.c.probe_id, - probe_reports.c.workspace_id == scope.c.workspace_id, + report_scope, ), ) ) diff --git a/apps/api/app/db/crud/fixtures.py b/apps/api/app/db/crud/fixtures.py index 57a42404..f3db0367 100644 --- a/apps/api/app/db/crud/fixtures.py +++ b/apps/api/app/db/crud/fixtures.py @@ -155,8 +155,10 @@ async def backfill_legacy_associations(database: Database) -> None: The corpus (and other fixture seeds) write ``bad_cases.workspace_id`` directly, but workspace-scoped reads derive visibility from - ``workspace_bad_cases``. The ``NOT EXISTS`` guard keeps repeated calls - idempotent so a fixture may backfill after its own seed as well. + ``workspace_bad_cases``. Reported rows become ``direct_ingest``; catalog + rows stay ``legacy_owner`` until a label rule rebuilds them. The + ``NOT EXISTS`` guard keeps repeated calls idempotent so a fixture may + backfill after its own seed as well. """ async with database.transaction() as session: await session.execute( @@ -165,14 +167,20 @@ async def backfill_legacy_associations(database: Database) -> None: INSERT INTO workspace_bad_cases ( workspace_id, bad_case_id, assignment_source, label, assigned_at ) - SELECT bc.workspace_id, bc.bad_case_id, 'legacy_owner', NULL, CURRENT_TIMESTAMP + SELECT bc.workspace_id, + bc.bad_case_id, + CASE WHEN bc.origin = 'report' + THEN 'direct_ingest' ELSE 'legacy_owner' END, + NULL, + CURRENT_TIMESTAMP FROM bad_cases bc WHERE bc.workspace_id IS NOT NULL AND NOT EXISTS ( SELECT 1 FROM workspace_bad_cases wbc WHERE wbc.workspace_id = bc.workspace_id AND wbc.bad_case_id = bc.bad_case_id - AND wbc.assignment_source = 'legacy_owner' + AND wbc.assignment_source = CASE WHEN bc.origin = 'report' + THEN 'direct_ingest' ELSE 'legacy_owner' END ) """, ), diff --git a/apps/api/app/db/crud/workspace_bad_case_labels.py b/apps/api/app/db/crud/workspace_bad_case_labels.py index 5a000a9d..71df51aa 100644 --- a/apps/api/app/db/crud/workspace_bad_case_labels.py +++ b/apps/api/app/db/crud/workspace_bad_case_labels.py @@ -3,7 +3,7 @@ from collections.abc import Sequence from dataclasses import dataclass -from sqlalchemy import delete, func, insert, literal, select +from sqlalchemy import delete, func, insert, literal, select, update from app.db.base import Database from app.db.models.domain import ( @@ -68,6 +68,14 @@ async def replace( """Replace rules and rebuild catalog assignments in one transaction.""" now = now_shanghai() async with self._database.transaction() as session: + if self._database.dialect == "sqlite": + # SQLite has no row locks; a no-op write takes the database + # write lock so concurrent replacements serialize like MySQL. + await session.execute( + update(workspaces) + .where(workspaces.c.id == workspace_id) + .values(updated_at=workspaces.c.updated_at), + ) workspace_exists = ( await session.execute( select(workspaces.c.id) diff --git a/apps/api/app/service/workspaces/schemas.py b/apps/api/app/service/workspaces/schemas.py index d40766ae..fd62e131 100644 --- a/apps/api/app/service/workspaces/schemas.py +++ b/apps/api/app/service/workspaces/schemas.py @@ -155,7 +155,7 @@ class WorkspaceCredentialCreated(WorkspaceModel): class WorkspaceBadCaseLabelRequest(WorkspaceModel): """Complete replacement set for one workspace's accepted public labels.""" - items: list[str] = Field(default_factory=list) + items: list[str] @field_validator("items") @classmethod diff --git a/apps/api/tests/m6-16-bad-case-catalog-sync/test_migration.py b/apps/api/tests/m6-16-bad-case-catalog-sync/test_migration.py index bfc324f8..bfecb882 100644 --- a/apps/api/tests/m6-16-bad-case-catalog-sync/test_migration.py +++ b/apps/api/tests/m6-16-bad-case-catalog-sync/test_migration.py @@ -77,7 +77,7 @@ async def test_upgrade_creates_catalog_sync_table(tmp_path: Path) -> None: def _alembic_config(database: Database) -> Config: - """Build a config for exercising the 0031 → head data migration.""" + """Build a config for exercising the 0032 → head data migration.""" config = Config(str(Path(__file__).resolve().parents[2] / "alembic.ini")) config.set_main_option("sqlalchemy.url", database.url.replace("%", "%%")) config.attributes["bootstrap_external_tables"] = True @@ -86,7 +86,7 @@ def _alembic_config(database: Database) -> Config: @pytest.mark.asyncio async def test_upgrade_backfills_workspace_bad_case_assignments(tmp_path: Path) -> None: - """A legacy badcase remains visible through an explicit legacy-owner row.""" + """Legacy rows keep their owner; report rows become direct-ingest associations.""" settings = Settings( db_dialect=DatabaseDialect.SQLITE, data_dir=tmp_path, @@ -95,20 +95,28 @@ async def test_upgrade_backfills_workspace_bad_case_assignments(tmp_path: Path) database = create_database(settings) await database.start() try: - await asyncio.to_thread(command.upgrade, _alembic_config(database), "0031") + await asyncio.to_thread(command.upgrade, _alembic_config(database), "0032") async with database.session() as session: await session.execute( text( """ INSERT INTO bad_cases ( - bad_case_id, workspace_id, bad_case_session_id, bad_case_type, - object_name, object_type, title, bad_case_description, + bad_case_id, workspace_id, origin, bad_case_session_id, bad_case_type, + object_name, object_type, title, bad_case_description, meta_data, created_at, updated_at - ) VALUES ( - 'legacy-case', 'ws-default', 'session-1', 'skill', - 'review', 'skill', 'Legacy', 'Legacy case', - CURRENT_TIMESTAMP, CURRENT_TIMESTAMP - ) + ) VALUES + ('legacy-case', 'ws-default', 'catalog', 'session-1', 'skill', + 'review', 'skill', 'Legacy', 'Legacy case', NULL, + CURRENT_TIMESTAMP, CURRENT_TIMESTAMP), + ('report-case', 'ws-default', 'report', 'session-2', 'skill', + 'review', 'skill', 'Report', 'Reported case', NULL, + CURRENT_TIMESTAMP, CURRENT_TIMESTAMP), + ('catalog-labeled', 'ws-default', 'catalog', 'session-3', 'skill', + 'review', 'skill', 'Labeled', 'Catalog case', '{"label": "code-review"}', + CURRENT_TIMESTAMP, CURRENT_TIMESTAMP), + ('catalog-invalid', 'ws-default', 'catalog', 'session-4', 'skill', + 'review', 'skill', 'Invalid', 'Bad label', '{"label": " spaced "}', + CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) """, ), ) @@ -150,14 +158,22 @@ async def test_upgrade_backfills_workspace_bad_case_assignments(tmp_path: Path) }, ) async with database.session() as session: - assignment = ( + cases = ( await session.execute( text( - "SELECT workspace_id, bad_case_id, assignment_source, label " - "FROM workspace_bad_cases WHERE bad_case_id = 'legacy-case'", + "SELECT bad_case_id, catalog_label, catalog_synced " + "FROM bad_cases ORDER BY bad_case_id", ), ) - ).one() + ).all() + assignments = ( + await session.execute( + text( + "SELECT bad_case_id, assignment_source " + "FROM workspace_bad_cases ORDER BY bad_case_id", + ), + ) + ).all() assert "catalog_label" in schema["bad_case_columns"] assert "catalog_synced" in schema["bad_case_columns"] @@ -182,11 +198,17 @@ async def test_upgrade_backfills_workspace_bad_case_assignments(tmp_path: Path) assert schema["assignment_fks"] == {("workspace_id",), ("bad_case_id",)} assert "ix_bad_cases_catalog_label" in schema["bad_case_indexes"] assert "ix_bad_cases_catalog_synced" in schema["bad_case_indexes"] - assert tuple(assignment) == ( - "ws-default", - "legacy-case", - "legacy_owner", - None, - ) + assert [tuple(row) for row in cases] == [ + ("catalog-invalid", None, 1), + ("catalog-labeled", "code-review", 1), + ("legacy-case", None, 1), + ("report-case", None, 0), + ] + assert [tuple(row) for row in assignments] == [ + ("catalog-invalid", "legacy_owner"), + ("catalog-labeled", "legacy_owner"), + ("legacy-case", "legacy_owner"), + ("report-case", "direct_ingest"), + ] finally: await database.dispose() diff --git a/apps/api/tests/workspaces/test_bad_case_labels_api.py b/apps/api/tests/workspaces/test_bad_case_labels_api.py index 065c20d2..e883e474 100644 --- a/apps/api/tests/workspaces/test_bad_case_labels_api.py +++ b/apps/api/tests/workspaces/test_bad_case_labels_api.py @@ -186,3 +186,10 @@ async def test_label_request_rejects_duplicates_whitespace_and_oversize( json={"items": items}, ) assert response.status_code == 422 + + missing = await client.put( + f"/api/workspaces/{workspace_id}/bad-case-labels", + headers=headers, + json={}, + ) + assert missing.status_code == 422 diff --git a/apps/api/tests/workspaces/test_scope_associations.py b/apps/api/tests/workspaces/test_scope_associations.py index bfee4ef6..4415ef5e 100644 --- a/apps/api/tests/workspaces/test_scope_associations.py +++ b/apps/api/tests/workspaces/test_scope_associations.py @@ -11,7 +11,8 @@ from fastapi import FastAPI from sqlalchemy import insert -from app.db.models.domain import bad_cases +from app.db.crud.bad_cases import BadCaseRepository +from app.db.models.domain import bad_case_analysis, bad_cases, probe_reports from app.utils.time import now_shanghai from tests.workspaces.helpers import ( access_token, @@ -118,3 +119,56 @@ async def test_removing_label_revokes_catalog_visibility_only_for_that_workspace assert await _bad_case_total(client, first, admin) == 1 assert await _bad_case_total(client, second, admin) == 0 + + +async def test_analysis_progress_counts_reports_from_the_requesting_workspace( + workspace_client: tuple[FastAPI, httpx.AsyncClient], +) -> None: + """A shared case's v2 report counts for the workspace that produced it.""" + app, client = workspace_client + database = app.state.database + first = await insert_workspace(database, name="progress-first") + second = await insert_workspace(database, name="progress-second") + + await _insert_catalog_case(app, case_id="case-progress", label="shared") + await _configure(app, client, first, ["shared"]) + await _configure(app, client, second, ["shared"]) + now = now_shanghai() + async with database.transaction() as session: + await session.execute( + insert(probe_reports).values( + probe_id="probe-progress-second", + workspace_id=second, + session_id="session-case-progress", + probe_type="skill", + probe_object="shared-object", + attribute_type="prompt", + conclusion="attributed", + confidence=0.8, + probe_description="progress probe", + probe_analysis="progress analysis", + policy_version="v1", + attribution_engine="test", + report_schema_version="probe-report/v2", + created_at=now, + updated_at=now, + ), + ) + await session.execute( + insert(bad_case_analysis).values( + bad_case_id="case-progress", + analysis_status="unanalyzed", + probe_id="probe-progress-second", + analysis_result=None, + updated_at=now, + ), + ) + + repository = BadCaseRepository(database) + second_progress = await repository.analysis_progress((second,)) + first_progress = await repository.analysis_progress((first,)) + + assert second_progress.analyzed == 1 + assert second_progress.issue == 1 + assert first_progress.analyzed == 0 + assert first_progress.pending == 1 diff --git a/packages/contracts/openapi.json b/packages/contracts/openapi.json index fecd1826..121a8f29 100644 --- a/packages/contracts/openapi.json +++ b/packages/contracts/openapi.json @@ -10379,6 +10379,9 @@ "type": "array" } }, + "required": [ + "items" + ], "title": "WorkspaceBadCaseLabelRequest", "type": "object" }, diff --git a/packages/contracts/src/generated/api.d.ts b/packages/contracts/src/generated/api.d.ts index 8da5eeaf..30a007c5 100644 --- a/packages/contracts/src/generated/api.d.ts +++ b/packages/contracts/src/generated/api.d.ts @@ -6340,7 +6340,7 @@ export interface components { */ WorkspaceBadCaseLabelRequest: { /** Items */ - items?: string[]; + items: string[]; }; /** * WorkspaceCreateRequest diff --git a/plans/2026-11-25-pr597-review.md b/plans/2026-11-25-pr597-review.md new file mode 100644 index 00000000..a4c1045c --- /dev/null +++ b/plans/2026-11-25-pr597-review.md @@ -0,0 +1,1014 @@ +# PR #597 检视记录:公共 badcase 按 label 划分工作空间 + +- 检视对象:[PR #597](https://github.com/Shadow-Azure/harness-evolution/pull/597)(`codex/issue-582-badcase-label-space-assignment` → `main`,head `94c018b9`,base `744f4f57`;97 文件、+3748 / −114、14 个提交,其中 2 个 merge) +- owning Note:[公共 badcase 按 label 划分空间的可关联事实与统一读边界](../.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.md)(`.en.md` / `.i18n.yaml` 同目录) +- 设计文档:[17 公共 badcase 按 label 划分工作空间](fullstack-design/17-workspace-bad-case-label-routing.md) +- 实现计划:[2026-11-24 issue 582 实现计划](superpowers/plans/2026-11-24-issue-582-badcase-label-routing.md) +- 关联 issue:[#582](https://github.com/Shadow-Azure/harness-evolution/issues/582)(flow issue `bugfix-58`,`in-progress`) +- 日期:2026-11-25 + +> 本文按 `.agents/skills/pr-review/SKILL.md` 的体例产出;检视文档落 `plans/`,不进入 Agent Notes。本文只描述当前实现与检视判断,不写变更史。检视侧未运行完整测试套件(见 §5 的验证口径说明);检视后对 D1/D2/D3/D4/D6/D8 的修复处置见 §7。 + +## §0 变更文件树与职责 + +共 97 = 新增 A 19 + 修改 M 78 + 删除 D 0。 + +命名与描述的偏差先记一笔:PR 描述与实现计划写「迁移 0032」,仓库里实际是 `0033_workspace_bad_case_labels.py`(`0032` 已用于 `bad_case_origin`);描述写「8 个提交」,`gh pr view 597 --json commits` 实际返回 14 个(含 2 个 `origin/main` merge)。本文以仓库实际状态为准。 + +### 0.1 后端应用(27 = A 3 + M 24) + +| 文件 | 状态 | 职责 | +|---|---|---| +| `apps/api/alembic/versions/0033_workspace_bad_case_labels.py` | A | 建两张关联表与索引;给 `bad_cases` 加 `catalog_label` / `catalog_synced`;给同步状态表加三个计数列;把既有 `workspace_id` 回填成 `legacy_owner`;可降级 | +| `apps/api/app/db/models/domain.py` | M | 声明两张新表、`bad_cases` 两个新列与两个索引、同步状态三个计数列 | +| `apps/api/app/db/database.py` | M | `transaction()` 在 SQLite 上显式 `BEGIN`,保证嵌套 savepoint 不提前提交 | +| `apps/api/app/db/external_contract.py` | M | 外部表契约补 `catalog_label` / `catalog_synced`;布尔列接受 MySQL 的 `TINYINT(1)` 反射 | +| `apps/api/app/db/crud/workspace_bad_case_labels.py` | A | label 规则的读与「单事务全量替换 + 历史关联重建 + 去重计数」 | +| `apps/api/app/service/workspaces/bad_case_labels.py` | A | 规则服务:排序归一、404 语义、持久化记录 → API 模型 | +| `apps/api/app/service/workspaces/schemas.py` | M | `WorkspaceBadCaseLabelRequest`(唯一/1–128/无首尾空白)与 `WorkspaceBadCaseLabelConfiguration` | +| `apps/api/app/api/workspaces.py` | M | `GET`(viewer)/ `PUT`(space_admin)`/api/workspaces/{wid}/bad-case-labels` | +| `apps/api/app/main.py` | M | 构造 `WorkspaceBadCaseLabelRepository/Service` 并挂到 `app.state.bad_case_labels` | +| `apps/api/app/db/crud/bad_case_catalog_sync.py` | M | 单页事务内:upsert 事实 → 删本页 legacy/catalog 关联 → 按规则重建 → 写游标与三计数 | +| `apps/api/app/service/acquisition/bad_case_catalog_sync.py` | M | 从 `meta_data.label` 提取合法 label 并传给持久化 | +| `apps/api/app/service/acquisition/bad_case_catalog_sync_coordinator.py` | M | 状态对象与 API 摘要新增 `assigned/unassigned/invalid_label` | +| `apps/api/app/api/acquisition.py` | M | 状态响应模型与组装补三个 catalog 计数 | +| `apps/api/app/db/crud/bad_case_ingest.py` | M | 直接上报写 `direct_ingest`、收敛同空间 `legacy_owner`、额度与 `used` 改按关联去重 | +| `apps/api/app/db/crud/workspaces.py` | M | 空间列表 `used`、单空间 `used`、知识根回填查询改走关联 | +| `apps/api/app/db/crud/acquisition_replay.py` | M | replay 的知识根查询从 `bad_cases.workspace_id` 改 join `workspace_bad_cases` | +| `apps/api/app/db/crud/read_scope.py` | M | 新增 `case_condition()` / `scoped_case_ids()`,成为空间读边界的唯一出口 | +| `apps/api/app/db/crud/bad_cases.py` | M | 归因进度聚合的 case 筛选改 `scoped_case_ids`(join 条件仍是旧列,见 D1) | +| `apps/api/app/db/crud/bad_case_sync.py` | M | root 同步的 distinct root / pending 判断改走关联 | +| `apps/api/app/db/crud/evolution_targets.py` | M | 对象目录按空间取 root session 改走关联 | +| `apps/api/app/db/crud/overview.py` | M | 总览共享谓词与 `used` 改走关联 | +| `apps/api/app/db/crud/overview_targets.py` | M | 对象总览的 case 谓词改走关联 | +| `apps/api/app/db/crud/potential.py` | M | 潜在 badcase 的 case 谓词改走关联 | +| `apps/api/app/db/crud/probe_query.py` | M | 探针检索的 workspace 过滤改 `scoped_case_ids` | +| `apps/api/app/db/crud/problems.py` | M | 问题列表/详情/Session 取数改 `case_condition` / `session_condition` | +| `apps/api/app/db/crud/sessions.py` | M | Session 列表/计数/详情/树改 `session_condition` / `case_condition` | +| `apps/api/app/db/crud/fixtures.py` | M | 新增幂等的 `backfill_legacy_associations()`,corpus seed 结束时调用 | + +### 0.2 前端与契约(11 = A 2 + M 9) + +| 文件 | 状态 | 职责 | +|---|---|---| +| `apps/web/src/pages/workspaces/components/BadCaseLabelsTab.vue` | A | 「Badcase 类型」页签:读取/草稿/校验/保存/空态/错误/只读 | +| `apps/web/src/pages/workspaces/components/BadCaseLabelsTab.test.ts` | A | 8 个组件用例:排序、Enter/按钮、非法输入、dirty、保存体、空态、重置、只读 | +| `apps/web/src/pages/workspaces/Admin.vue` | M | 新增第六个页签,位置在「上报接入」与「归因 Skill」之间 | +| `apps/web/src/pages/workspaces/Admin.test.ts` | M | 页签总数 5→6,新增顺序断言 | +| `apps/web/src/api/workspaces.ts` | M | `listWorkspaceBadCaseLabels` / `replaceWorkspaceBadCaseLabels` | +| `apps/web/src/api/queryKeys.ts` | M | `adminBadCaseLabels(workspaceId)` | +| `apps/web/src/composables/useWorkspaces.ts` | M | 查询/替换 mutation;成功后按 `["ws", id]` 前缀失效并刷新会话 | +| `packages/contracts/openapi.json` | M | 生成快照新增两个 schema 与两条 path | +| `packages/contracts/src/generated/api.d.ts` | M | 生成类型同上 | +| `packages/contracts/src/index.ts` | M | 导出两个新类型 | +| `packages/contracts/src/workspaces.ts` | M | 从 `components["schemas"]` 取两个新类型并带 JSDoc | + +### 0.3 文档、记录与原型(21 = A 10 + M 11) + +| 文件 | 状态 | 职责 | +|---|---|---| +| `.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.{md,en.md,i18n.yaml}` | A ×3 | owning Note 三件套:Problem / Decision / Alternatives / Consequences | +| `.agents/flow/issues/bugfix-evolution-label-allowlist.{md,en.md,i18n.yaml}` | A ×3 | #582 的 flow issue:`in-progress`,scope 覆盖 apps/web/contracts/tests/plans/.agents/docs | +| `.agents/flow/issues/bugfix-explicit-skill-conclusion.{md,en.md,i18n.yaml}` | M ×3 | `bugfix-56` 置 `done`(#588 已合并) | +| `.agents/flow/issues/bugfix-bad-case-sync-type-title.{md,en.md,i18n.yaml}` | M ×3 | 撞号修复:`bugfix-56 → bugfix-59` | +| `docs/architecture.{md,en.md,i18n.yaml}` | M ×3 | 数据层策略一句:空间表补两张新表、可见性走关联;i18n 双哈希重录 | +| `plans/fullstack-design/17-workspace-bad-case-label-routing.md` | A | 设计正文:目标/数据模型/label 契约/写入重算/读边界/API/UI/验证 | +| `plans/fullstack-design/README.md` | M | 设计索引加第 17 篇;D21 决策改写为「可见性单元」并加 2026-11-24 修订 | +| `plans/superpowers/plans/2026-11-24-issue-582-badcase-label-routing.md` | A | 8 个任务、全局约束、Review focus、验证与交付步骤 | +| `plans/db-relationship-diagram.md` | A | 30 表 Mermaid ER 图 + 值引用表 + 可见性链路说明 | +| `plans/db-relationship-diagram.pdf` | A | 上述图的 PDF 快照(二进制,未逐页检视) | +| `plans/ui-prototype-v2/harness-evolution.html` | M | 原型新增「Badcase 类型」页签、chips、空态、dirty、保存 toast | + +### 0.4 后端测试(31 = A 4 + M 27) + +| 组 | 文件 | 状态 | 职责 | +|---|---|---|---| +| 新功能主测试 | `apps/api/tests/workspaces/test_bad_case_labels_api.py` | A | 权限(viewer 读 / member 拒写 / outsider 404)、全量替换 fan-out、`used`、422 | +| 新功能主测试 | `apps/api/tests/workspaces/test_bad_case_labels_service.py` | A | 用 SQLite trigger 制造重建失败,断言规则与关联一起回滚 | +| 新功能主测试 | `apps/api/tests/workspaces/test_scope_associations.py` | A | 一条公共 case 同时被两个空间读到、第三方看不到、删规则只撤销本空间 | +| 新功能主测试 | `apps/api/tests/workspaces/test_bad_case_assignments.py` | A | 表/主键/FK 的元数据形状 | +| 契约边界 | `apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_sync_repository.py` | M | 重复页替换旧 label、失败回滚事实+游标、状态计数排除直接上报 | +| 契约边界 | `apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_sync_service.py` | M | label 精确/非法/无人配置的 fan-out 与三计数 | +| 契约边界 | `apps/api/tests/m6-16-bad-case-catalog-sync/test_migration.py` | M | 0033 建表/列/索引/FK 与 legacy_owner 回填 | +| 契约边界 | `apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_status_api.py` | M | `assigned/unassigned/invalidLabel` 字段与默认值 | +| 直接上报 | `apps/api/tests/ingest/test_ingest_repository.py` | M | 直接上报收敛 legacy、保留 catalog 关联、`used` 去重 | +| 直接上报 | `apps/api/tests/ingest/helpers.py` | M | 测试侧 `count_cases` 改关联去重 | +| fixture 回填 | `apps/api/tests/workspaces/helpers.py` | M | `insert_bad_case` 补 legacy_owner;新增 `associate_case`;`backfill_legacy_associations` 委托 fixtures | +| fixture 回填 | `apps/api/tests/workspaces/test_admin.py` | M | 知识根变更用例补关联 | +| fixture 回填 | `apps/api/tests/m7-06-session-workspace-scope/test_session_scope.py` | M | 显式关联两个空间的 case | +| fixture 回填 | `apps/api/tests/m8-02-session-latest-ten/test_latest_ten.py` | M | seed 后回填 | +| fixture 回填 | `apps/api/tests/m8-03-workspace-overview/test_overview_api.py` | M | 5 处 seed 后回填 | +| fixture 回填 | `apps/api/tests/m9-05-knowledge-document-triggers/test_knowledge_replay.py` | M | seed 后补关联 | +| fixture 回填 | `apps/api/tests/m12-07-bad-case-session-state/test_trace_status.py` | M | seed 后回填 | +| fixture 回填 | `apps/api/tests/m12-10-bad-case-trigger-point/test_real_jsonl_line.py` | M | seed 后回填 | +| fixture 回填 | `apps/api/tests/m5-02-target-config-api/test_catalogs_api.py` | M | 用例末回填 | +| fixture 回填 | `apps/api/tests/m5-05-launch-wizard/test_launch_api.py` | M | 两处 seed 后回填 | +| fixture 回填 | `apps/api/tests/m10_02_potential_support.py` | M | seed 后回填 | +| fixture 回填 | `apps/api/tests/attribution/support.py` | M | `seed_case` 后回填 | +| fixture 回填 | `apps/api/tests/m11-01-attribution-read/test_attribution_read_api.py` | M | fixture 末尾回填 | +| 版本号顺延 | `apps/api/tests/attribution/test_m10_03_migration.py`、`tests/bugfix-47-bad-case-sync-source-factory/test_origin_migration.py`、`tests/m10-01-attribution-schema/test_attribution_migration.py`、`tests/m9-01-trace-evidence-contract/test_trace_evidence_migration.py`、`tests/m9-04-object-revision-trigger-coordinates/test_trigger_migration.py`、`tests/m9-05-knowledge-document-triggers/test_knowledge_migration.py`、`tests/test_database.py`、`tests/test_openapi.py` | M ×8 | head 断言 0032→0033;OpenAPI path 集合补新路由 | + +### 0.5 E2E(7 = A 0 + M 7) + +| 文件 | 状态 | 职责 | +|---|---|---| +| `tests/e2e/m7-09-workspace-admin.test.mjs` | M | 管理页页签数 5→6 | +| `tests/e2e/support/{m10_06_run_detail_fixture,m11_04_target_overview_seed,m12_07_seed,m12_10_seed,m5_run_list_fixture,seed_bad_case}.py` | M ×6 | 各 seed 末尾调用 `backfill_legacy_associations` | + +## §1 一页速览 + +一句话:把「一条公共 badcase 属于哪个空间」从 `bad_cases.workspace_id` 这个单值字段,改成一张按 `assignment_source` 区分来源的多对多关联表;空间管理员配置自己接受的 label,目录同步按 `meta_data.label` 把同一条公共事实同时「抄送」给所有匹配空间,所有列表、Session、统计和自进化取数都改从这张关联表判断可见性。 + +一个比喻:公共仓库是**总库房**,`bad_cases` 是每件货的**唯一档案**(全局 `bad_case_id` 是档案号,只有一份);`workspace_bad_case_labels` 是各空间在总库房填的**订阅栏目**(一个栏目可被多个空间订阅);`workspace_bad_cases` 是各空间的**收货清单**;`bad_cases.catalog_label` 是同步时提前印在档案封面上的**栏目名**(只是投影,便于查表);`catalog_synced` 是「这件货走过总库房登记」的戳。以前每个空间想把货放进自己仓库,只能改档案上唯一的「归属空间」那一栏,所以一件货不可能同时归两个空间;现在改为按封面栏目名往多个空间的清单上抄,档案本身不动。 + +| 交付块 | 用户可见结果 | +|---|---| +| 数据模型 | 新增 `workspace_bad_case_labels(workspace_id, label)`、`workspace_bad_cases(workspace_id, bad_case_id, assignment_source)`;`bad_cases` 多两个查询列;旧的 `workspace_id` 保留为直接上报归属/冲突检测 | +| 规则管理 | 空间管理新增「Badcase 类型」:viewer 可看,space_admin / 全局 admin 可保存;全量替换、返回排序后的 label 与去重可见条数 | +| 目录同步 | 上游 `meta_data.label` 合法时写入 `catalog_label`,并按 `label = label` 给每个配置了该 label 的空间建 `catalog_label` 关联;非法/缺失/未配置分别进入 `invalid_label` / `unassigned` 计数 | +| 直接上报 | 上报照旧按凭据写 URL 空间;额外写 `direct_ingest` 关联,收敛同空间旧的 `legacy_owner`;额度与 `used` 改按关联去重 | +| 统一读边界 | `WorkspaceReadScope.case_condition()` / `session_condition()` / `scoped_case_ids()` 成为唯一出口;列表、Session、总览、问题、探针、额度、自进化取数都改走关联 | +| 前端 | 「Badcase 类型」页签在「上报接入」与「归因 Skill」之间:chips 字典序、Enter 与按钮等价、重复/空白/超长就地提示、dirty 提示、保存成功 toast、只读角色隐藏写控件 | +| 契约与文档 | OpenAPI / 生成 TS 类型 / 导出类型一致;architecture 双语 + 17 设计 + Note + flow issue + ER 图 + V2 原型同步 | + +验证基线(按任务约定**未复跑测试**;下表是 PR 描述的声明 + 检视侧对代码/测试文件存在性的核对): + +| 门禁 / 套件 | PR 描述声明 | 检视侧核对 | +|---|---|---| +| `pnpm contract:check` | 通过 | `openapi.json` 有 `WorkspaceBadCaseLabelRequest/Configuration` 与 path,`api.d.ts`/`index.ts`/`workspaces.ts` 同源引用,未见手写漂移(✅ 静态) | +| `typecheck` / `typecheck:web` / `lint:docs` / `verify:flow` | 通过 | 双语三件套、i18n 哈希、flow issue `bugfix-58`/撞号调整均在(✅ 静态) | +| `tests/workspaces` 等五组后端测试 | 全绿 | 用例文件与用例名存在(✅ 静态,未复跑) | +| 前端 `vitest`(页签 + 导航) | 通过 | 两个测试文件存在:页签组件 8 个用例 + 管理页导航/页签数断言(✅ 静态,未复跑) | +| 迁移编号 / 提交数 | 描述写 0032、8 个提交 | 实际 0033、14 个提交(含 2 merge),描述需更新 | + +## §2 架构导览 + +### 2.1 数据模型:单份事实 + 三态关联 + +`bad_cases` 仍是每件货唯一档案:`bad_case_id` 全局主键,`meta_data` 原样保留(`domain.py:296-333`)。新增的两个查询列是 `catalog_label VARCHAR(128) NULL` 与 `catalog_synced BOOLEAN NOT NULL DEFAULT 0`(`domain.py:315-316`),并各配一个索引(`domain.py:332-333`)。为什么要有 `catalog_label` 而不在 SQL 里解析 `meta_data`:SQLite 的 `json_extract` 与 MySQL 的 `JSON_EXTRACT` 语法/索引行为不同,而空间规则重算、每页计数都是热路径;把「验证后的 label」投影成普通列后,两边都只是等值比较,能走索引。代价是同一事实有两处表达(`meta_data.label` 与 `catalog_label`),必须由**唯一写者**同步维护,见 §2.3。 + +两张新表:规则表 `workspace_bad_case_labels` 主键 `(workspace_id, label)`,label 上另建索引(`domain.py:337-346`),便于「按 label 找所有空间」;关联表 `workspace_bad_cases` 主键 `(workspace_id, bad_case_id, assignment_source)`,`bad_case_id` 外键到 `bad_cases` 并级联删除,`label` 记录命中值,另有 `bad_case_id` 与 `label` 两个索引(`domain.py:349-365`)。主键把「同一空间同一 case 的不同来源」设计成可并存:`direct_ingest` 与 `catalog_label` 可以各占一行,读取用 `DISTINCT` 去重。为什么不是 `(workspace_id, bad_case_id)` 唯一:设计明确允许同一空间既直接上报又因 label 命中,二者删除语义不同(删规则不能删直接上报),必须能分别删。 + +迁移 `0033` 做四件事(`0033:14-135`):一是给 `bad_cases` 补两列与两个索引,`catalog_synced` 用 `server_default=0`;二是给同步状态表补 `assigned_count/unassigned_count/invalid_label_count`(`0033:43-62`);三是建两张新表,`workspace_id` 外键级联到 `workspaces.id`、`bad_case_id` 级联到 `bad_cases.bad_case_id`(`0033:64-120`);四是把既有 `workspace_id IS NOT NULL` 的每一行回填成 `legacy_owner`(`0033:122-135`)。为什么回填:升级前所有列表都按 `workspace_id` 过滤,上线后读路径只认关联表,不回填会让历史数据瞬间「消失」。`legacy_owner` 是兼容态,后续被直接上报收敛为 `direct_ingest`(`bad_case_ingest.py:338-372`),或被目录页回收(`bad_case_catalog_sync.py:298-307`)。 + +注意模型与迁移的一处有意分歧:`domain.py` 的两张新表没有声明 `workspace_id` 外键,注释写「The migration owns the cross-metadata workspace foreign key」(`domain.py:340`、`352`)。原因是 `workspaces` 在 `WORKSPACE_METADATA`、`bad_cases` 在 `DOMAIN_METADATA`,外部表 bootstrap 不能依赖跨 metadata;这与 `bad_cases.workspace_id` 一直只做值引用的约定一致(`plans/db-relationship-diagram.md:74-84`)。后果是「用模型 metadata 直接建表」的环境(部分 fixture)没有这条外键,级联行为只在真实迁移后的库成立,测试与生产的 schema 不完全等价。 + +### 2.2 写侧 A:规则保存是一个「全量替换 + 历史重算」事务 + +HTTP 入口是 `GET/PUT /api/workspaces/{wid}/bad-case-labels`:读用 `require_workspace_role("viewer")`,写用 `"space_admin"`(`api/workspaces.py:121-155`);service 只把 items 排序后交给 repository(`service/workspaces/bad_case_labels.py:20-41`)。真正的机制在 `WorkspaceBadCaseLabelRepository.replace()`(`db/crud/workspace_bad_case_labels.py:63-149`): + +1. 在一个 `database.transaction()` 里先 `select workspaces.id ... with_for_update()`;不存在返回 `None`(service 转 404)。 +2. `delete` 该空间全部规则,再批量插入新规则(`81-98`)。 +3. `delete` 该空间全部 `assignment_source='catalog_label'` 关联(`100-105`)。 +4. 用 `INSERT … SELECT` 从 `bad_cases JOIN workspace_bad_case_labels ON label = catalog_label` 重建历史关联(`106-134`)。 +5. 在同一事务里数一次 `count(distinct bad_case_id)` 作为 `assignedBadCaseCount`(`136-144`),提交后才返回。 + +为什么用 `INSERT…SELECT` 而不是先查 ID 再逐条插:历史可能几十万条,一次集合写入避免把 ID 搬进 Python;为什么只删 `catalog_label`:直接上报关联是另一个来源,删规则不应该撤销它(设计 §2.2)。放弃的是「增量 diff」:即使规则完全没变也会全删全建,换来的是实现简单和「规则/关联永远同源」;代价见 D5。 + +### 2.3 写侧 B:目录同步的单页事务顺序 + +服务层只负责把上游 item 映射成行,并提取 label:`_catalog_label` 要求 `meta_data` 是 Mapping、`label` 是 `str`、长度 1–128、无首尾空白,否则返回 `None`(`service/acquisition/bad_case_catalog_sync.py:61-74`);`_row` 把它放进 `CatalogCaseRow.catalog_label`(`84-88`)。注意这里没有 trim、没有大小写折叠——契约就是「精确匹配」,`"Review"` 与 `"review"` 是两个 label。 + +Repository 的 `commit_page()`(`db/crud/bad_case_catalog_sync.py:251-400`)是这次改造最关键的事务边界,顺序是: + +1. 先按 id 查 `origin` 做写者归属判断;新 id 走 `insert`,`origin='catalog'` 的旧行走 `update`,`origin='report'` 的旧行只计 `skipped`、**不覆盖**(`267-297`)。插入用 `session.begin_nested()` 包住,撞主键时回滚 savepoint、重读归属、再试一次(`270-285`)——这就是最新提交 `94c018b9` 要修的 SQLite savepoint 问题的现场。 +2. 对本页所有 id 删除 `legacy_owner` 与 `catalog_label` 关联(`298-307`)。 +3. `INSERT … SELECT` 从 `bad_cases JOIN workspace_bad_case_labels` 重建本页命中的关联(`308-335`)。 +4. 全量算 `synced` / `valid` / `assigned` 三个数并写回状态行,同时推进 `last_bad_case_id`(`336-380`)。 + +为什么删完再建而不是「按 label diff」:上游重试/冷启动会重复收到同一 ID,删建天然幂等;为什么把删除放在 upsert 之后:只有事实落库并带上最新 `catalog_label`,重建才能读到新 label。放弃的是「单条增量」:每页对整页 ID 做一次删除+重建,页大小 200,写放大可接受。 + +### 2.4 写侧 C:直接上报与额度 + +`BadCaseIngestRepository.ingest()` 在原有「锁空间 → 查全局 ID 归属 → 额度检查 → insert/update」中插入了关联逻辑(`bad_case_ingest.py:159-195`):先算 `already_assigned = _workspace_has_case(...)`(该空间是否已有**任意来源**的关联),只有「尚未关联」才做额度检查(`174-182`),写完事实后 `_assign_direct()` 删除同空间 `legacy_owner` 并确保 `direct_ingest` 存在(`338-372`)。为什么豁免已关联 case 的额度:同一 case 的重复上报不应因为 `used` 已达配额而被拒;为什么不删 `catalog_label`:label 命中的可见性与直接上报是两条独立的来源,删了会让「空间因 label 看到它」这件事被上报副作用撤销。 + +`_used()` 从「数 `bad_cases.workspace_id = ?`」改为「数关联表里该空间去重 case 数」(`308-317`)。这把额度口径从「我拥有多少行」改成「我能看到多少 case」;公共分配可以让 `used > quota`(设计 §4.1 明确接受),此时新 case 的直接上报继续返回 `QUOTA_EXCEEDED`,而管理页会显示超额的 `used`。 + +### 2.5 读边界:一个方法收口,两种形态 + +`WorkspaceReadScope.case_condition()`(`db/crud/read_scope.py:48-75`)把旧的 `condition(column)` 换成一个固定针对 `bad_cases` 的谓词: + +- 指定空间:`EXISTS (SELECT 1 FROM workspace_bad_cases WHERE workspace_id = :wid AND bad_case_id = bad_cases.bad_case_id)`——相关子查询,命中主键前缀; +- 旧式 user 范围:`bad_cases.bad_case_id IN (SELECT bad_case_id FROM workspace_bad_cases WHERE workspace_id IN (SELECT workspace_id FROM workspace_members WHERE user_id = :uid))`; +- 全局管理员:`true()`。 + +`session_condition()` 再用它把 Session 投影成「该范围内 case 的根会话集合」(`77-81`)。另有 `scoped_case_ids(workspace_ids)` 给那些已经拿到「一组显式空间」的旧兼容路由用(`84-92`)。设计上这是一个**必须带 `bad_cases` 进 FROM** 的谓词(见 D6 的 API 形状提醒);所有当前调用点都满足(`sessions.py`、`problems.py`、`overview.py`、`potential.py`、`overview_targets.py`)。 + +读路径的替换清单可以对照 `grep "case_condition|scoped_case_ids|session_condition"`:sessions 6 处、problems 6 处、overview 的共享谓词 1 处(被 6 个聚合复用)、overview_targets/potential 各 1 处、bad_cases/bad_case_sync/probe_query/evolution_targets 各 1 处。为什么必须收口到一个方法:可见性是权限边界,散落的 `bad_cases.workspace_id == ?` 只要漏一处,就会让 label 共享的 case 在某个页面「看不见」或让旧默认空间「看得见」。这也是本 PR 最有价值的部分。 + +### 2.6 前端:查询键、mutation 与「草稿」状态机 + +- 查询键 `adminBadCaseLabels(id)` 挂在 `["ws", id, "admin", ...]` 下(`api/queryKeys.ts:30-31`),因此保存后 `invalidateQueries({queryKey: queryKeys.workspace(id)})` 一次前缀失效就能覆盖总览、Session、自进化、页签自身(`composables/useWorkspaces.ts:369-383`);另外还失效 `["ws"]` 与 `auth/session` 并主动 `refreshAuthSession()`,因为工作空间列表的 `used` 也可能变。 +- 组件状态机(`BadCaseLabelsTab.vue:27-54`):`savedItems` 来自服务端,`draft` 是本地副本;`watch(savedItems)` 只在「当前 draft 仍等于上一次服务端快照」时才采纳新快照,所以后台 refetch 不会吞掉用户正在编辑的内容;`watch(workspaceId)` 在切换空间时直接采纳当前快照(丢弃未保存草稿);`isDirty` 用 `sameLabels` 做顺序敏感比较。这个状态机是提交 `913dd44f` 的主要修复对象——旧实现只「首次同步」,离开页签再回来会保留被遗弃的草稿。 +- 校验在前端先做一遍(`62-71`),服务端再做权威校验(`schemas.py:160-171`);保存失败把 `WORKSPACE_FORBIDDEN` / `VALIDATION_INVALID` 映射成中文(`113-120`),其他错误落入通用文案。 + +### 2.7 契约、文档与原型 + +FastAPI 模型是契约源:`WorkspaceBadCaseLabelRequest` 的 items 有 `default_factory=list`,所以生成 schema 里 `items` 不是 required(D6);`WorkspaceBadCaseLabelConfiguration.assigned_bad_case_count` 有 `ge=0`(`schemas.py:174-179`)。生成链把两个 schema 与两条 path 写进 `openapi.json` 与 `api.d.ts`,`index.ts` / `workspaces.ts` 只做类型再导出(`packages/contracts/src/workspaces.ts:66-73`),符合「契约是唯一事实源」的仓库规则。 + +文档侧,architecture 只改了一句(`docs/architecture.md:36`):空间表清单补两张新表、明确「bad case 可见性走关联表」;这是现状 home,措辞准确。设计 17 是理由 home,Note 记录取舍与拒绝的替代方案,flow issue 管流程,ER 图补结构——四个 home 各司其职,没有把决策塞进 `docs/`。 + +## §3 数据流走查 + +以一个真实场景走一遍:空间 A、B 都配置了 `review`;上游一页返回 5001(`meta_data.label="review"`)、5002(`label=" review"`,带首空格)、5003(`label="tool-use"`,无人配置);之后 A 又通过凭据直接上报 5004。 + +1. **管理员配置规则**:A 的空间管理员在空间管理点「Badcase 类型」(`Admin.vue:47` 的页签定义、`303-308` 渲染),输入 `review` 回车,`addLabel()` 校验后把 `draft` 排序为 `["review"]`(`BadCaseLabelsTab.vue:77-82`);点保存触发 `replaceLabels({items:["review"]})`(`97-106`),`PUT /api/workspaces/A/bad-case-labels`(`api/workspaces.ts:233-241`)。 +2. **服务端原子替换**:路由用 `space_admin` 校验(`api/workspaces.py:148-155`),service 排序后调 repository;repository 在**一个事务**里锁空间、删旧规则、插 `review`、删 A 的 `catalog_label` 关联、`INSERT…SELECT` 重建、数一次 `assigned`(当前为 0)、提交(`workspace_bad_case_labels.py:70-149`)。响应 `{"items":["review"],"assignedBadCaseCount":0}`。 +3. **目录同步取页**:调度器触发 `BadCaseCatalogSyncService.run()`;它从状态表读 `last_bad_case_id`,`mark_running`,向公共仓库请求 200 条(`service/acquisition/bad_case_catalog_sync.py:143-224`)。对每条 item,`_row` 调 `_catalog_label`:5001→`review`,5002→`None`(首空格不合法),5003→`tool-use`(合法但与规则无关)。 +4. **单页事务落库并路由**:`commit_page()` 先查归属(三条都新)→ `insert` 三行事实,`catalog_synced=True`,`catalog_label` 分别为 `review/None/tool-use`(`bad_case_catalog_sync.py:119-131`、`267-297`)→ 按本页 id 删 `legacy_owner`/`catalog_label`(此时没有)→ `INSERT…SELECT` 连接规则表:只有 5001 命中 A(若 B 也配了 `review`,同一行会为 B 也生成一条)→ 写回 `last_bad_case_id`、`synced=3`、`valid=2`、`assigned=1`、`unassigned=1`(5003)、`invalid=1`(5002)→ 提交(`298-380`)。如果第 4 步任意一句失败(例如触发器拒绝插关联),整个事务回滚:事实、关联、计数、游标都不前进;测试 `test_assignment_failure_rolls_back_fact_and_cursor` 用 SQLite trigger 钉住了这一点(`test_catalog_sync_repository.py:321-375`)。 +5. **读侧生效**:用户打开总览,`OverviewRepository` 的共享谓词调用 `WorkspaceReadScope.for_workspace(A).case_condition()`(`overview.py:102-117`),SQL 变成 `EXISTS (workspace_bad_cases WHERE workspace_id='A' AND bad_case_id=bad_cases.bad_case_id)`,A 只看到 5001(以及之后 5004);B 只看 5001;第三方空间看不到 5001。Session 列表走 `session_condition()`(`sessions.py:247-260`),把「A 可见 case 的根会话」投影成 Session 集合;`used` 也数关联去重(`workspaces.py:268-296`)。 +6. **直接上报共存**:A 用凭据上报 5004;`_lock_workspace` 拿锁后 `already_assigned=false`,`used` 未到配额 → 插入事实(`workspace_id=A`)→ `_assign_direct` 插 `direct_ingest`(`bad_case_ingest.py:159-195`、`338-372`)。A 现在有 `direct_ingest`(5004) 与 `catalog_label`(5001);读取去重后 `used=2`。 +7. **删规则只撤销 label 可见性**:A 把规则清空 → `PUT {"items":[]}` → repository 删 A 的 `review` 规则、删 A 的 `catalog_label` 关联、不再重建;A 仍能看到 5004(`direct_ingest` 未被动),看不到 5001;B 的 5001 不受影响(`test_bad_case_labels_api.py:104-166`、`test_scope_associations.py:104-120`)。 +8. **升级存量**:升级时迁移把每行既有 `workspace_id` 回填 `legacy_owner`(`0033:122-135`);老公共 case 因此仍能被旧默认空间看到。但它们的 `catalog_label` 仍是 NULL、`catalog_synced` 仍是 0,游标也不会回头,所以 A 之后配置 `review` 只能覆盖升级后新同步的行——这是 D2 的问题。 +9. **前端刷新**:保存成功 → `invalidateQueries(["ws", A])` 前缀失效 → 总览/Session/自进化/页签在重新进入或重新请求时拿到新集合;toast 文案「Badcase 类型已保存,历史数据已重新划分」(`BadcaseLabelsTab.vue:102`)与设计 §7 一致。 + +## §4 导读地图 + +| 文件 | 状态 | +|---|---| +| `apps/api/alembic/versions/0033_workspace_bad_case_labels.py` | ✅ 已通读 | +| `apps/api/app/db/models/domain.py` | ✅ 已通读新增表/列区(296-365、486-500),其余既有表未逐行 | +| `apps/api/app/db/database.py` | ✅ 已通读 1-30、70-95 | +| `apps/api/app/db/external_contract.py` | ✅ 已读 88-130、240-270 与全量 diff | +| `apps/api/app/db/crud/workspace_bad_case_labels.py` | ✅ 已通读 | +| `apps/api/app/service/workspaces/bad_case_labels.py` | ✅ 已通读 | +| `apps/api/app/service/workspaces/schemas.py` | ✅ 已读 1-30、60-180 与全量 diff | +| `apps/api/app/api/workspaces.py` | ✅ 已读 1-60、110-160 与全量 diff | +| `apps/api/app/main.py` | ✅ 已读装配相关行(57、141、328、713)与 diff | +| `apps/api/app/db/crud/bad_case_catalog_sync.py` | ✅ 已通读 | +| `apps/api/app/service/acquisition/bad_case_catalog_sync.py` | ✅ 已通读 | +| `apps/api/app/service/acquisition/bad_case_catalog_sync_coordinator.py` | ✅ 已读 30-60、150-200 与 diff | +| `apps/api/app/api/acquisition.py` | ✅ 已读 70-90、190-260 与 diff | +| `apps/api/app/db/crud/bad_case_ingest.py` | ✅ 已读 60-120、120-380 与全量 diff | +| `apps/api/app/db/crud/workspaces.py` | ✅ 已读 260-300、420-450 与 diff | +| `apps/api/app/db/crud/acquisition_replay.py` | ✅ 已读 309-350 与 diff | +| `apps/api/app/db/crud/read_scope.py` | ✅ 已通读 | +| `apps/api/app/db/crud/bad_cases.py` | ✅ 已读 300-400 与 diff | +| `apps/api/app/db/crud/bad_case_sync.py` | ✅ 已读 diff(未逐行通读全文件) | +| `apps/api/app/db/crud/evolution_targets.py` | ✅ 已读 diff(未逐行通读全文件) | +| `apps/api/app/db/crud/overview.py` | ✅ 已读 95-132、222-240 与 diff | +| `apps/api/app/db/crud/overview_targets.py` | ✅ 已读 diff(未逐行通读全文件) | +| `apps/api/app/db/crud/potential.py` | ✅ 已读 diff(未逐行通读全文件) | +| `apps/api/app/db/crud/probe_query.py` | ✅ 已读 diff(未逐行通读全文件) | +| `apps/api/app/db/crud/problems.py` | ✅ 已读 diff(未逐行通读全文件) | +| `apps/api/app/db/crud/sessions.py` | ✅ 已读 240-270、350-540 与 diff | +| `apps/api/app/db/crud/fixtures.py` | ✅ 已读 145-185 与 diff | +| `apps/web/src/api/queryKeys.ts` | ✅ 已通读 | +| `apps/web/src/api/workspaces.ts` | ✅ 已读 200-242 与 diff | +| `apps/web/src/composables/useWorkspaces.ts` | ✅ 已读 1-90、330-392 与 diff | +| `apps/web/src/pages/workspaces/Admin.vue` | ✅ 已读 20-60、290-315 与 diff | +| `apps/web/src/pages/workspaces/Admin.test.ts` | ✅ 已读 diff | +| `apps/web/src/pages/workspaces/components/BadCaseLabelsTab.vue` | ✅ 已通读 | +| `apps/web/src/pages/workspaces/components/BadCaseLabelsTab.test.ts` | ✅ 已通读 | +| `packages/contracts/openapi.json` | ✅ 已读新增 schema/path 区(10370-10390、15520 附近) | +| `packages/contracts/src/generated/api.d.ts` | ◻ 生成文件,只确认被 diff 更新,未逐行读 | +| `packages/contracts/src/index.ts` / `src/workspaces.ts` | ✅ 已读新增区 | +| `docs/architecture.md` / `.en.md` / `.i18n.yaml` | ✅ 已读 diff | +| `.agents/notes/.../2026-11-24-workspace-bad-case-label-routing.md` | ✅ 已通读 | +| 同目录 `.en.md` / `.i18n.yaml` | ◻ 只确认存在与哈希,未逐段读 | +| `.agents/flow/issues/bugfix-evolution-label-allowlist.md` | ✅ 已读 1-50 与 diff;`.en.md`/`.i18n.yaml` ◻ | +| `.agents/flow/issues/bugfix-explicit-skill-conclusion.*`、`bugfix-bad-case-sync-type-title.*` | ✅ 已读 diff | +| `plans/fullstack-design/17-workspace-bad-case-label-routing.md` | ✅ 已通读 | +| `plans/fullstack-design/README.md` | ✅ 已读 diff | +| `plans/superpowers/plans/2026-11-24-issue-582-badcase-label-routing.md` | ✅ 已通读 | +| `plans/db-relationship-diagram.md` | ✅ 已通读 | +| `plans/db-relationship-diagram.pdf` | ◻ 二进制,未逐页检视 | +| `plans/ui-prototype-v2/harness-evolution.html` | ✅ 已读 diff | +| `apps/api/tests/workspaces/test_bad_case_labels_api.py` | ✅ 已通读 | +| `apps/api/tests/workspaces/test_bad_case_labels_service.py` | ✅ 已通读 | +| `apps/api/tests/workspaces/test_scope_associations.py` | ✅ 已通读 | +| `apps/api/tests/workspaces/test_bad_case_assignments.py` | ✅ 已通读 | +| `apps/api/tests/workspaces/helpers.py` / `test_admin.py` | ✅ 已读 diff | +| `apps/api/tests/m6-16-bad-case-catalog-sync/test_migration.py` | ✅ 已通读 1-192 | +| `apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_sync_repository.py` | ✅ 已读 diff + 209-255;既有 1-208 未逐行 | +| `apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_sync_service.py` | ✅ 已读 diff;既有部分未逐行 | +| `apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_status_api.py` | ✅ 已读 diff | +| `apps/api/tests/ingest/test_ingest_repository.py` / `helpers.py` | ✅ 已读 diff | +| 其余后端测试(m5/m7/m8/m9/m10/m11/m12、test_database、test_openapi) | ✅ 已读 diff(未逐个逐行通读) | +| `tests/e2e/m7-09-workspace-admin.test.mjs` 与 6 个 e2e support | ✅ 已读 diff | +| 全量 `test:api` / `test:web` / MySQL lane / 真实 E2E | ◻ 未运行(按任务约定) | +| 浏览器实际渲染 / 原型视觉对比 | ◻ 未做 | + +## §5 人工验收清单 + +### 5.1 PR 描述里的验证声明(原样转写为 checkbox) + +- [x] 契约:`pnpm contract:check` 通过。 +- [x] 类型与文档流程门禁:`typecheck` / `typecheck:web` / `lint:docs` / `verify:flow` 通过。 +- [x] 后端测试:`tests/workspaces`、`tests/m6-16-bad-case-catalog-sync`、`tests/m8-02-session-latest-ten`、`tests/m8-03-workspace-overview`、`tests/ingest` 全绿。 +- [x] 前端测试:`vitest`(Badcase 类型页签 + 管理页导航)。 + +> 勾选表示「PR 描述有这条声明,且检视侧确认对应测试文件/用例存在」;检视侧**没有复跑**这些命令,最终以 CI lane 为准(任务约定不跑全量测试)。以下为设计 §8 的验收面与检视侧新增项。 + +### 5.2 设计 §8 的验收面 + +- [ ] SQLite/MySQL 迁移:既有 `workspace_id` 全部回填、升级可重复检测、降级不删除公共事实。迁移测试只覆盖 SQLite 的单行回填(`test_migration.py:88-192`),MySQL lane 未复跑;「可重复检测」只对表/列成立,对回填 INSERT 不成立(D8)。 +- [x] 同步:一个 label 配给两个空间时只写一条 `bad_cases`、写两组关联;非法/无人配置分别计数;分页失败整页回滚;重试无重复。(`test_catalog_sync_service.py:372-456`、`test_catalog_sync_repository.py:258-375`) +- [x] 配置:权限、精确匹配、全量替换、历史补齐、删除规则、事务回滚。(`test_bad_case_labels_api.py`、`test_bad_case_labels_service.py:17-90`) +- [ ] 读侧:列表、Session、总览、额度、自进化对同一空间返回同一去重集合。新增跨栈测试只通过「总览 `totals.badCases` + case 详情 404」验证(`test_scope_associations.py:78-120`),Session/自进化/额度没有同一条共享 case 的端到端断言。 +- [ ] 配置变化不影响既有 run:设计声称已持久化候选/报告/快照不反查关联;检视侧未找到覆盖「改规则后旧 run 仍可恢复」的专门测试。 +- [x] UI:原型一致的导航/卡片/按钮、键盘添加、只读角色、空态、错误、原子保存反馈。(组件测试 8 例;视觉对比未做) +- [ ] 窄屏:移动端管理导航横向滚动、内容不溢出(组件测试在 jsdom 下无法证明;未做真实浏览器检查)。 +- [ ] 无端到端覆盖新页签:`m7-09` 只把页签数从 5 改成 6(`tests/e2e/m7-09-workspace-admin.test.mjs:155-160`),没有「配置 label → 看到重新划分结果」的 E2E。 +- [ ] PR 描述与实现不一致:迁移编号 0032→0033、提交数 8→14,合并前应更新描述。 + +### 5.3 检视侧补充的验收建议 + +- [ ] 在**已有公共目录数据**的库上演练一次升级:确认 `catalog_label`/`catalog_synced` 的存量行为符合预期(D2)。 +- [ ] 一条 `origin='report'` 的历史 case 被目录页触达后仍能被原空间看到(D3)。 +- [ ] 空间 B 对共享 case 跑一次归因后,`GET /api/acquisition/status?workspaceId=B` 的 `badCaseAnalysis.analyzed` 正确(D1)。 +- [ ] SQLite 上两个并发 `PUT /bad-case-labels` 不出现 500 / 半写状态(D4)。 +- [ ] 用 `{}` 空 body 调一次 PUT,确认是否真的要「清空全部规则」(D6)。 + +## §6 讨论点 + +### D1 归因进度聚合仍按 `bad_cases.workspace_id` 关联报告,label 共享 case 会算错空间 + +- **位置**:`apps/api/app/db/crud/bad_cases.py:307`(`select(bad_cases.c.bad_case_id, bad_cases.c.workspace_id)`)与 `340-347`(`probe_reports.c.workspace_id == scope.c.workspace_id`);调用链 `apps/api/app/api/acquisition.py:243-260` → `apps/api/app/service/problems/service.py:54-58` → `bad_cases.py:303`;`probe_reports.workspace_id` 的写入在 `apps/api/app/service/evolution/attribution.py:900-903`。 +- **现象**:本 PR 把 `analysis_progress` 的 case 过滤换成了 `scoped_case_ids(workspace_ids)`(`308-309`),但子查询仍把 `bad_cases.workspace_id` 带出来,并用它去匹配 `probe_reports.workspace_id`。对 label 共享的公共 case,`bad_cases.workspace_id` 恒为 `ws-default`(目录同步写入 `DEFAULT_WORKSPACE_ID`,`bad_case_catalog_sync.py:117`),而报告行记录的是**实际发起归因的运行空间**(`run.workspace_id`)。于是空间 B 打开顶栏同步气泡(`TopNav.vue:107-112` 带 `workspaceId` 每 15s 轮询)时,B 对共享 case 的 v2 报告不会被计入;如果 ws-default 归因过,B 反而会显示「已归因」。legacy 的 `analysis_status` 路径不受影响,所以现有测试(只插 legacy 行)全绿。 +- **问题**:这是「读边界收口」的一处漏网:筛选条件换了,join 条件没换,而 `probe_reports` 恰恰是按空间存的。后果是聚合数字错误(不是明细泄露,但会误导排期与验收),且与 PR 声称的「所有空间读路径统一经 `case_condition()`」不一致。它也不属于「已持久化快照不反查」的保护范围——这里查的就是实时报告。 +- **预判**:修法很小:`workspace_ids` 非空时把 join 条件改为 `probe_reports.c.workspace_id.in_(workspace_ids)`;`workspace_ids is None`(全局管理员)则不限制报告空间。更彻底的做法是让 `analysis_progress` 接收 `WorkspaceReadScope`,统一从 scope 推导 case 与报告空间。补一个跨栈测试:空间 B 对共享 case 产出 probe 报告后,`GET /api/acquisition/status?workspaceId=B` 的 `analyzed` 为 1、`GET ...?workspaceId=A` 不把 B 的报告算进去。属 correctness,建议在合并前或紧随的修复 PR 处理;不涉及数据结构,风险低。 +- **结论**: + +### D2 升级不回填存量公共事实的 `catalog_label` / `catalog_synced`,也不回退游标 + +- **位置**:`apps/api/alembic/versions/0033_workspace_bad_case_labels.py:19-41`(新增列,`catalog_synced` 默认 0)、`122-135`(只回填 `legacy_owner`);`apps/api/app/db/crud/bad_case_catalog_sync.py:129-131`(只有 upsert 才写 `catalog_synced=True`)、`409-428`(`count_bad_cases` 只数 true)、`335-356`(`synced`/`valid`/`invalid` 都基于 true)。 +- **现象**:升级前已存在的公共事实(`origin='catalog'`)在迁移后统一是 `catalog_label=NULL, catalog_synced=0`;`bad_case_catalog_sync` 的游标行原样保留(`0012` 建的表,`initialize` 只在缺行时置 0),服务只从游标往后拉。因此升级后:存量公共 case 永远不会被重新打标;`synced` 从「全表行数」立刻降为「升级后新同步的行数」;`invalid_label_count`/`unassigned_count` 也不含存量。设计 §4.3 写的是「新增规则补齐历史数据」,只有 `catalog_label` 非空的存量才能被补齐。 +- **问题**:PR 的动机是「生产 badcase 统一进公共仓库」,即生产形态本来就有存量。升级后管理员配一个 label 只能看到升级之后新同步的 case,历史数据仍只以 `legacy_owner` 留在默认空间;同时顶栏/同步页的 `synced` 数字会「归零」,让运维误以为同步坏了。数据没丢,但功能承诺与可观测性都对不上。 +- **预判**:三条路,按成本排序:(a) 迁移或一次性运维步骤把 `last_bad_case_id` 重置为 0,让下一次同步重放全部 ID——upsert 会补 `catalog_synced/catalog_label`,页事务会重建关联,代价是一次全量重拉,且会同时触发 D3(所以两条要一起修);(b) 迁移内用双方言 JSON 表达式回填 `catalog_label`(SQLite `json_extract` / MySQL `JSON_EXTRACT`),需要重复 1–128/trim 校验,SQL 不可移植风险高,不推荐;(c) 明确接受「只对新数据生效」,在 17 与 Note 写清并提供受控重放脚本。建议至少选 (a) 或 (c),并补一条「升级前已有 catalog 行」的迁移测试(现在的迁移测试只插了一条 legacy 行,见 `test_migration.py:88-192`)。 +- **结论**: + +### D3 目录页删除 `legacy_owner` 不区分 `origin`,可能让历史直接上报的 case 失去唯一可见性 + +- **位置**:`apps/api/app/db/crud/bad_case_catalog_sync.py:298-307`(按本页 `ids` 删除 `legacy_owner`/`catalog_label`,未过滤 `origin`)、`283-297`(`origin='report'` 的行只 skip、不 update);`apps/api/alembic/versions/0033_workspace_bad_case_labels.py:122-135`(所有 `workspace_id IS NOT NULL` 的行都回填 `legacy_owner`,包括 `origin='report'`);`apps/api/app/db/crud/bad_case_ingest.py:338-372`(只有再次上报才补 `direct_ingest`)。 +- **现象**:一条升级前由凭据直接上报的 case(`origin='report'`、`workspace_id=W`)在迁移后只有 `legacy_owner(W)` 这一条关联。如果同一 ID 之后出现在公共目录的某一页,页事务会删掉它的 `legacy_owner`;由于 `origin != 'catalog'` 不会被 update,`catalog_label` 又是 NULL,所以 `INSERT…SELECT` 也不会为它建 `catalog_label` 关联。结果:W 失去唯一可见性,直到 W 再次上报同一 ID 才补回 `direct_ingest`。这不是数据删除,但列表、Session、总览、额度都会少这一条,且没有任何告警。 +- **问题**:迁移回填没有利用已经存在的 `origin` 区分「直接上报」与「公共目录」。设计 §2.2 说移除 `legacy_owner` 的目的是「避免旧默认空间继续看到公共数据」,那针对的是 `origin='catalog'` 的行;这里误伤的是直接上报者的合法归属。同步的 `_ownership` 特意跳过 report 行以保护上报者字段,却在同一页删掉了它的可见性,逻辑上自相矛盾。 +- **预判**:首选修法:迁移对 `origin='report'` 回填 `direct_ingest`、对 `origin='catalog'` 回填 `legacy_owner`——语义正好对应 `assignment_source` 的两态,也顺带覆盖「上报过又进目录」的存量窗口。次选:页事务只删 `origin='catalog'` 行的 `legacy_owner`(需要 join `bad_cases` 判断 origin)。补一条测试:report-origin 行被目录页触达后,原空间仍能通过列表/详情读到。若生产不存在「直接上报后又出现在公共目录」的 ID,本条无实害,但仍建议按语义修正,因为代码已经假设它会发生。 +- **结论**: + +### D4 规则保存的「锁空间」在 SQLite 上是 no-op,与 ingest 的 SQLite 写法不一致 + +- **位置**:`apps/api/app/db/crud/workspace_bad_case_labels.py:70-77`(`select(workspaces.c.id)...with_for_update()`);对照 `apps/api/app/db/crud/bad_case_ingest.py:210-230`(SQLite 用一次 no-op `UPDATE` 拿写锁);`apps/api/app/db/database.py:85-93` 的 `BEGIN` 是 deferred。 +- **现象**:MySQL 上 `FOR UPDATE` 会锁住空间行;SQLite 方言忽略 `FOR UPDATE`,而本事务的第一条写语句是 `delete(workspace_bad_case_labels)`(`81-85`)。`transaction()` 里显式 `BEGIN` 也只是开事务,不取 RESERVED 锁。于是两个并发的 `PUT` 会各自读到旧规则再全量替换,最终 last-writer-wins;与 ingest 注释里明确写出的「SQLite 没有行锁,先做无意义写入拿数据库写锁」的模式不一致。 +- **问题**:因为替换是幂等的全量操作,且没有像额度那样的「基于锁的决策」,当前**无实害**——最坏情况是两个管理员同时保存,后者覆盖前者,与 MySQL 的行锁语义差别不大(MySQL 也只是串行化,不是合并)。但注释写「one transaction locks the workspace」,会让后来者以为 SQLite 也串行化了;将来如果在这段逻辑里加入「先读后判」的规则(例如配额/审计),这个 no-op 会变成真 bug。 +- **预判**:两种处理都行:(a) 把注释改成「MySQL 行锁;SQLite 依赖单写者事务」并保持实现;(b) 对齐 ingest,在 SQLite 分支先 `update(workspaces).values(updated_at=workspaces.c.updated_at)` 取写锁。属加固,可后续 ticket,不必阻塞本 PR。 +- **结论**: + +### D5 每一页都做三次全量计数,同步热路径从 O(表) 变成 O(页数 × 表) + +- **位置**:`apps/api/app/db/crud/bad_case_catalog_sync.py:336-365`;其中 `341`/`351` 依赖 `catalog_synced` 索引(布尔列选择性很低),`360-362` 对 `workspace_bad_cases` 按 `assignment_source` 做 `count(distinct bad_case_id)`(该列没有索引,且关联表行数 ≈ case × 空间)。 +- **现象**:改造前每页只有一次 `count(*) from bad_cases`;现在每页再算 `synced`(`catalog_synced=true`)、`valid`(true 且 label 非空)、`assigned`(关联表按 source 去重),全部是全量聚合,和页大小无关。一次 run 最多 100 页(`service/acquisition/bad_case_catalog_sync.py:107-124`),初始化/追赶时成本约 `O(页数 × 表行数)`;`workspace_bad_cases` 在「一条 case 被多个空间订阅」时会比 `bad_cases` 大一个数量级。 +- **问题**:这是同步热路径上的写放大,而且每轮 run 都会重复。当前数据量下可能无感,设计只写了「计数针对最近一次完成页提交后的公共事实状态」,没有讨论成本,也没有性能基线。它不属于功能缺陷,但属于这次取舍里被放弃的东西:为了「状态行随时可读」而选择了「每页全量重算」。 +- **预判**:最省事的改法是只在 `run()` 结束 `mark_idle()` 时算一次(状态页展示的仍是「最近一次 run 结束后的状态」,语义几乎不变,成本降到 O(表)/run);若要更细的实时性,再考虑增量计数(复杂,需处理重放与规则变更)。无论改不改,建议跑一次 `pnpm performance:report` 记录基线,把结论写进 Note 的 Consequences。属性能取舍,不阻塞合并。 +- **结论**: + +### D6 `items` 可以缺省,空 body 会被解释成「清空全部规则」 + +- **位置**:`apps/api/app/service/workspaces/schemas.py:155-171`(`items: list[str] = Field(default_factory=list)`);`apps/api/app/api/workspaces.py:148-155`(直接使用 `body.items`)。 +- **现象**:`PUT /api/workspaces/{wid}/bad-case-labels` 传 `{}`、或客户端漏字段,会被解析成空列表,进而删除该空间全部 label 规则与全部 `catalog_label` 关联。`[]` 本身是合法的「清空」语义,所以服务端无法区分「显式清空」与「忘了带字段」。 +- **问题**:全量替换接口里,最关键字段可缺省会把一次客户端 bug/手写 curl 变成一次可见性清空。回滚只能重新配规则并等历史重建(数据还在,`direct_ingest`/`legacy_owner` 不受影响,但公共可见性会中断)。同文件的 `WorkspaceCreateRequest.space_admin_ids` 是必填,说明仓库并不排斥「关键集合必填」。 +- **预判**:把 `items` 改成必填(去掉 `default_factory`)即可让 `{}` 返回 422,`[]` 仍是合法清空;调用方目前只有 Web 与新测试,改动面小。若团队认为「省略=清空」是刻意约定,至少在 17/05 写明并让前端永远显式发送。属 API 契约加固,建议本 PR 改或记录后续 ticket。 +- **结论**: + +### D7 `assignedBadCaseCount` 统计所有来源,「当前划分」文案容易被读成 label 命中数 + +- **位置**:`apps/api/app/db/crud/workspace_bad_case_labels.py:49-61`、`136-144`(`count(distinct bad_case_id)` 不限制 `assignment_source`);UI `apps/web/src/pages/workspaces/components/BadCaseLabelsTab.vue:236-247`;测试已把行为固定成「全部来源」:`apps/api/tests/workspaces/test_bad_case_labels_api.py:145-166`(direct + label 去重后是 2)。 +- **现象**:`assignedBadCaseCount` 是该空间所有来源的去重可见 case 数(`direct_ingest`、`legacy_owner`、`catalog_label`),不只是 label 命中。空间清空所有 label 后,如果还有直接上报的 case,页面仍显示「已关联 N 条」;反过来,管理员也无法从这个数字判断「这次 label 配了多少条」。 +- **问题**:设计 §6 只定义了字段名,没有定义口径;UI 标题是「当前划分」,语义更接近「由这些 label 划分出的条数」。测试把「全部来源」固定下来,说明实现者有过选择,但产品文案没有跟上。当前无数据错误,属语义歧义。 +- **预判**:若意图是「当前空间可见总数」,把文案改成「当前空间共 N 条」并保持 SQL(推荐,改动最小);若意图是「label 命中数」,SQL 加 `assignment_source='catalog_label'` 过滤,并另加一个 total 字段。两条都合理,需要产品拍板;建议在 17 §6 补一句口径定义。 +- **结论**: + +### D8 迁移回填不是幂等的,且与 fixture 版回填是两份语义 + +- **位置**:`apps/api/alembic/versions/0033_workspace_bad_case_labels.py:122-135`(`INSERT … SELECT` 没有 `NOT EXISTS`);`apps/api/app/db/crud/fixtures.py:153-179`(同样的语义但带 `NOT EXISTS`,注释自称 "Mirror migration 0033");对照 `0032` 迁移对表/列都有 `has_table`/`has_column` 守卫,以及仓库已有的 partial-DDL 恢复测试 `apps/api/tests/m9-01-trace-evidence-contract/test_trace_evidence_migration.py:279`。 +- **现象**:0033 对表、列、索引都有「已存在就跳过」的守卫,唯独数据回填没有;MySQL 的 DDL 是自动提交的,如果在「建表/加列成功、回填成功、alembic 版本行尚未写入」之间进程崩溃,重跑迁移会在回填处撞主键。另有一份 fixture 版回填(供 corpus/e2e 使用),语义将来容易与迁移漂移。 +- **问题**:正常一次成功升级不会触发,当前**无实害**;但仓库专门写过 partial-DDL 恢复测试,说明半应用状态不是纯理论。两份回填也意味着以后改一处忘另一处时,fixture 与生产的可见性会不一致。 +- **预判**:给迁移回填加 `WHERE NOT EXISTS`(与 fixtures 完全一致),或把这段 SQL 抽成一个共享常量/helper 供迁移与 fixture 复用(迁移里 import app 代码有耦合风险,抽 SQL 字符串更稳)。再补一个「回填已存在时重跑不报错」的测试。低优先级,可在后续迁移加固 PR 处理。 +- **结论**: + +## §7 分流表 + +检视后处置:D1、D2、D3、D4、D6、D8 已在本 PR 修复并补测试;D5(同步写放大)与 D7(`assignedBadCaseCount` 口径)作为取舍保留,已写入 §6 与 17 §6。 + +| 发现 | 定性 | 去处 | 状态 | +|---|---|---|---| +| D1 `analysis_progress` 仍按 `bad_cases.workspace_id` 关联 `probe_reports`,label 共享 case 的空间归因进度算错 | 缺陷(读边界完整性,聚合口径) | 已在 `bad_cases.py` 改为按请求空间匹配 `probe_reports.workspace_id`,并补跨栈测试 | ✅ 已修复(本 PR) | +| D2 存量公共事实未回填 `catalog_label`/`catalog_synced`,游标不回退,规则无法补齐历史且计数归零 | 缺陷 / 迁移安全(功能覆盖与可观测性) | 0033 迁移按 label 契约回填存量 `catalog_label` 并置 `catalog_synced`,迁移测试覆盖 | ✅ 已修复(本 PR) | +| D3 目录页删除 `legacy_owner` 不区分 `origin`,历史直接上报 case 可能失去可见性 | 缺陷 / 迁移兼容(数据可见性) | 迁移按 `origin` 回填 `direct_ingest`/`legacy_owner`;fixture 回填同步该语义 | ✅ 已修复(本 PR) | +| D4 规则保存的 `with_for_update` 在 SQLite 上 no-op,与 ingest 模式不一致 | 设计取舍 / 并发(当前无实害) | SQLite 分支在替换前做 no-op 写取数据库写锁,与 ingest 对齐 | ✅ 已修复(本 PR) | +| D5 每页三次全量计数,同步热路径写放大 | 设计取舍 / 性能(当前量级无实害) | 保留现状;建议后续按 run 结束计数或记录性能基线 | ⏳ 保留(后续) | +| D6 PUT 的 `items` 可缺省,空 body 等于清空全部规则 | API 契约(误操作风险) | `items` 改为必填并再生成 OpenAPI/TS 契约;`{}` 返回 422、`[]` 才是显式清空 | ✅ 已修复(本 PR) | +| D7 `assignedBadCaseCount` 含所有来源,UI「当前划分」语义歧义 | UX 契约 / 产品口径(无实害) | 17 §6 已写明口径(所有来源去重可见数);UI 文案沿用,待产品后续拍板 | ⏳ 保留(口径已记录) | +| D8 迁移回填不幂等,且与 fixture 回填两份语义 | 迁移安全(正常升级无实害) | 迁移改用 `INSERT OR IGNORE`/`INSERT IGNORE`,fixture 回填保持 `NOT EXISTS` 且与迁移同语义 | ✅ 已修复(本 PR) | +| `bad_cases.workspace_id` 退化为「直接上报归属 + 全局 ID 冲突检测」 | —— | 由迁移 DDL、`_existing_owner` 与 Note 共同决定 | ✅ 已决(2026-11-24,Note/17 §2.1) | +| 一张公共 case 同时被多个空间读到、第三方看不到、删规则只撤销本空间 | —— | `test_scope_associations.py` 已覆盖 | ✅ 已决(2026-11-25,测试实存) | +| 直接上报收敛 legacy、保留 catalog、`used` 去重 | —— | `test_ingest_repository.py:186-238` | ✅ 已决(2026-11-25,测试实存) | +| 分页失败整页回滚、事实+关联+游标同事务 | —— | `test_catalog_sync_repository.py:321-375` + `database.py` BEGIN 修复 | ✅ 已决(2026-11-25,提交 `94c018b9`) | +| 规则保存失败时规则与关联一起回滚 | —— | `test_bad_case_labels_service.py:17-90`(SQLite trigger) | ✅ 已决(2026-11-25,测试实存) | +| 契约 schema/path/类型导出 | —— | `openapi.json`/`api.d.ts`/`index.ts` 同源 | ✅ 已决(2026-11-25,静态核对) | +| 双语文档与 flow issue | —— | architecture 三件套、Note 三件套、`bugfix-58` | ✅ 已决(2026-11-25,静态核对) | +| PR 描述编号/提交数过期(0032、8 个提交) | 流程(描述准确度) | PR 描述 | ✅ 可自修(无需代码) | + +## §8 链接 + +- PR:https://github.com/Shadow-Azure/harness-evolution/pull/597 +- Issue:#582 https://github.com/Shadow-Azure/harness-evolution/issues/582 +- owning Note:`.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.md`(`.en.md` / `.i18n.yaml` 同目录) +- 设计文档:`plans/fullstack-design/17-workspace-bad-case-label-routing.md` +- 实现计划:`plans/superpowers/plans/2026-11-24-issue-582-badcase-label-routing.md` +- 数据模型图:`plans/db-relationship-diagram.md`(PDF 同目录) +- 相关常驻文档:`docs/architecture.md:36`(英文 `.en.md:36`;i18n `.i18n.yaml`) +- 相关流程记录:`.agents/flow/issues/bugfix-evolution-label-allowlist.md`(`bugfix-56 → done`、`bugfix-56 → bugfix-59` 撞号修复) +- 后续:合并后按流程提交闭环 PR,把 `bugfix-58` 置 `done` 并关闭 #582 + +## §9 文件级代码分析 + +> 只展开通读过的文件与关键 diff;§4 标 ◻ 的文件不在此假装分析。每节格式:职责 → 变更形态 → 关键依赖 → 旧/新对照 → 这在做什么/为什么 → 实现思路 → 检视发现。 + +### 9.1 `apps/api/alembic/versions/0033_workspace_bad_case_labels.py`(A) + +职责:一次升级把「单值归属」模型迁到「多对多关联」模型,并保住历史可见性。变更形态:新文件 160 行。 + +关键依赖:Alembic `op.batch_alter_table` 在 SQLite 上会重建表、在 MySQL 上直接 ALTER;`inspect(bind)` 用于「半应用状态」的守卫。比喻:这是一次**搬家**——先给旧档案加两个新标签位(列与索引),再建两个新登记簿,最后把旧档案按原归属抄一张「临时收货单」,保证搬家当天没有货凭空消失。 + +upgrade 的结构(`14-135`):`bad_cases` 不存在就整段跳过(外部表可能还没 bootstrap);存在则按列名判断是否加 `catalog_label`/`catalog_synced` 与两个索引(`19-41`);同步状态表按缺失列逐个补(`43-62`);两张新表分别建并配索引(`64-120`);最后重新 `inspect`,把 `workspace_id IS NOT NULL` 的行 `INSERT … SELECT` 成 `legacy_owner`(`122-135`)。downgrade(`138-160`)先删同步计数列,再删两张新表,最后按存在性删 `bad_cases` 的两列与索引;**不删任何公共事实行**,符合设计 §8 的「降级不删除公共事实」。 + +检视发现: +- 回填没有 `NOT EXISTS`,与 `fixtures.py` 的幂等版本不一致(D8)。 +- 回填只写 `legacy_owner`,没有利用 `origin` 区分直接上报(D3)。 +- 不回退游标,也不回填 `catalog_label`(D2)。 +- 迁移测试覆盖了表/列/索引/FK 与单行回填(`test_migration.py:88-192`),但没有覆盖「升级前已有 catalog 数据」与「回填重跑」。 + +### 9.2 `apps/api/app/db/models/domain.py`(M) + +职责:声明两张新表、`bad_cases` 两个列与两个索引、同步状态三个计数列。变更形态:+38 行。 + +旧代码(`main`,节选): + +```python + Column("meta_data", JSON, nullable=True), + Column("source", String(64), nullable=True), +``` + +新代码(节选): + +```python + Column("meta_data", JSON, nullable=True), + Column("catalog_label", String(128), nullable=True), + Column("catalog_synced", Boolean, nullable=False, server_default=text("0")), + ... + Index("ix_bad_cases_catalog_label", "catalog_label"), + Index("ix_bad_cases_catalog_synced", "catalog_synced"), +``` + +```python +workspace_bad_case_labels = Table( + "workspace_bad_case_labels", + DOMAIN_METADATA, + # The migration owns the cross-metadata workspace foreign key. + Column("workspace_id", String(36), primary_key=True), + Column("label", String(128), primary_key=True), + ... +) + +workspace_bad_cases = Table( + "workspace_bad_cases", + DOMAIN_METADATA, + ... + Column("bad_case_id", String(64), ForeignKey("bad_cases.bad_case_id", ondelete="CASCADE"), primary_key=True), + Column("assignment_source", String(24), primary_key=True), + Column("label", String(128), nullable=True), + ... +) +``` + +这在做什么:把「可见性」从 `bad_cases.workspace_id` 拆到关联表,同时用主键表达三种来源并存。为什么这么写:`assignment_source` 必须在主键里,否则同一空间同一 case 的 `direct_ingest` 与 `catalog_label` 会互撞;`bad_cases` 的外键可以写在同一个 metadata 内,`workspaces` 的在另一个 metadata,所以有意留给迁移。`catalog_synced` 用 `server_default=text("0")` 而不是 Python 默认,是为了让迁移加列时老行自动为 false。 + +实现思路总结:事实表只加投影列,关联表承担多对多;跨 metadata 外键只存在于迁移。 + +检视发现:模型与迁移的 schema 不完全等价(测试用 `create_all` 时缺 workspace FK,见 §2.1);`catalog_synced` 的布尔索引选择性低,配合每页计数会放大读成本(D5)。 + +### 9.3 `apps/api/app/db/database.py`(M) + +职责:所有写事务的统一入口。变更形态:`transaction()` 多了 4 行 + 一段 docstring。 + +旧代码: + +```python + async with self._factory()() as session: + try: + yield session + await session.commit() + except BaseException: + await session.rollback() + raise +``` + +新代码: + +```python + async with self._factory()() as session: + try: + if self.dialect == "sqlite": + await session.execute(text("BEGIN")) + yield session + await session.commit() +``` + +这在做什么:SQLite 的 DBAPI(legacy 事务控制)把 `BEGIN` 延迟到第一条 DML;如果先开 `SAVEPOINT`(`commit_page` 的 `begin_nested` 就是这样),savepoint 会自己开一个事务,`RELEASE` 时提交,外层再 rollback 也收不回来——事实和游标就会「半提交」。显式 `BEGIN` 让 savepoint 真正嵌在外层事务里。为什么只对 SQLite:MySQL 的驱动默认不延迟事务,重复 `BEGIN` 反而可能报错。 + +实现思路总结:用方言判断补一个显式事务起点,成本是多一条语句,换来嵌套 savepoint 的原子性。检视发现:这是提交 `94c018b9` 的核心修复,`test_assignment_failure_rolls_back_fact_and_cursor`(`test_catalog_sync_repository.py:321-375`)是它的证据;没有发现其它方言/连接池副作用(每次 `transaction()` 都用新 session,不会在已有事务上重复 BEGIN)。唯一可讨论的是它把「事务开始」提前到 yield 之前,长事务会多占连接,但本仓库的写事务都很短。 + +### 9.4 `apps/api/app/db/external_contract.py`(M) + +职责:外部表 bootstrap 的列契约与漂移检测。变更形态:+2 列契约、+1 处类型容忍。 + +旧代码: + +```python + ColumnContract("meta_data", "json", True), + ColumnContract("source", "varchar", True, 64), +... + if family != expected.family: + return _observed_type(observed_type) +``` + +新代码: + +```python + ColumnContract("meta_data", "json", True), + ColumnContract("catalog_label", "varchar", True, 128), + ColumnContract("catalog_synced", "boolean", False), + ColumnContract("source", "varchar", True, 64), +... + if family != expected.family and not ( + # MySQL stores BOOLEAN as TINYINT(1), which reflection reports as an + # integer family; a contract boolean stays satisfied by that storage. + expected.family == "boolean" and family == "integer" + ): +``` + +这在做什么:让外部表 bootstrap 也知道两个新列;MySQL 把 BOOLEAN 存成 TINYINT(1),反射报 integer,若不容忍会让所有 MySQL 部署在启动时判成 schema drift。为什么这么做:契约检查的目标是「列能不能承载值」,布尔的可承载集合在 MySQL 就是 TINYINT(0/1),整数家族完全覆盖。检视发现:这个容忍是**全局**的(所有 boolean 契约列),会掩盖「期望 boolean 却真是 int」的其它漂移;但 MySQL 里 boolean 本来就必然是 TINYINT,实际风险很低,注释也写清了理由。 + +### 9.5 `apps/api/app/db/crud/workspace_bad_case_labels.py`(A) + +职责:规则与派生关联的持久化,含「全量替换 + 历史重建 + 去重计数」。变更形态:新文件 149 行。 + +关键依赖:`Database.transaction()`(写事务/回滚)、SQLAlchemy `insert().from_select()`(集合写入)、`with_for_update()`(MySQL 行锁)、`now_shanghai()`(项目统一时区)。比喻:保存规则像**换订阅清单**——先把旧清单撕掉、贴新清单,再把库里所有封面栏目名能对上的货重新抄到该空间的收货单上;整个过程装在一个信封里,要么全生效,要么全退回。 + +新代码(节选,`63-149`): + +```python + async with self._database.transaction() as session: + workspace_exists = ( + await session.execute( + select(workspaces.c.id).where(workspaces.c.id == workspace_id).with_for_update(), + ) + ).scalar_one_or_none() + if workspace_exists is None: + return None + await session.execute(delete(workspace_bad_case_labels).where(...)) + if labels: + await session.execute(insert(workspace_bad_case_labels), [...]) + await session.execute( + delete(workspace_bad_cases).where( + workspace_bad_cases.c.workspace_id == workspace_id, + workspace_bad_cases.c.assignment_source == CATALOG_ASSIGNMENT_SOURCE, + ), + ) + if labels: + matching_cases = ( + select(literal(workspace_id), bad_cases.c.bad_case_id, literal(CATALOG_ASSIGNMENT_SOURCE), + bad_cases.c.catalog_label, literal(now)) + .select_from(bad_cases.join(workspace_bad_case_labels, + workspace_bad_case_labels.c.label == bad_cases.c.catalog_label)) + .where(workspace_bad_case_labels.c.workspace_id == workspace_id) + ) + await session.execute(insert(workspace_bad_cases).from_select([...], matching_cases)) +``` + +这在做什么:一个事务内完成「存在性校验 → 规则替换 → 只删本空间 catalog 关联 → 从索引列重建 → 计数」。为什么用 `literal(workspace_id)` 而不是再查一次:`INSERT…SELECT` 的 SELECT 列表必须显式给出常量;为什么 `assigned_count` 在事务内数:保证返回的数字与本次写入一致,不会读到别的并发写。`get()`(`35-61`)是纯读,两个查询在同一 session 里。 + +实现思路总结:规则是唯一输入,关联是纯派生;删只删派生来源,保留直接上报。 + +检视发现:`assigned_count` 含所有来源(D7);SQLite 上 `with_for_update` 是 no-op(D4);全删全建的成本与计数口径见 D5/D7。 + +### 9.6 `apps/api/app/service/workspaces/bad_case_labels.py` 与 `schemas.py`(A/M) + +职责:service 做排序/404 映射/记录→API 模型;schema 做输入校验。变更形态:service 新文件 48 行;schemas +27 行。 + +新代码(schema,`155-179`): + +```python +class WorkspaceBadCaseLabelRequest(WorkspaceModel): + items: list[str] = Field(default_factory=list) + + @field_validator("items") + @classmethod + def validate_items(cls, items: list[str]) -> list[str]: + if len(items) != len(set(items)): + raise ValueError("labels must be unique") + for label in items: + if not label or len(label) > 128 or label != label.strip(): + raise ValueError("labels must be 1-128 characters without surrounding whitespace") + return sorted(items) + +class WorkspaceBadCaseLabelConfiguration(WorkspaceModel): + items: list[str] + assigned_bad_case_count: int = Field(ge=0) +``` + +这在做什么:用 Pydantic 把「唯一、1–128、无首尾空白」变成 422;`sorted` 让响应顺序确定,前端可以按序比较。为什么在 schema 而不是 SQL:SQLite/MySQL 的 `CHECK`/排序规则不同(大小写敏感性尤其),业务规则集中在一处更可控。service 的 `replace()` 再 `tuple(sorted(labels))` 一次(`24-40`),属于防御性重复;`_to_configuration` 只做投影(`41-48`)。 + +实现思路总结:输入校验在 schema,排序在 schema + service,持久化在 repository。 + +检视发现:`items` 可缺省 = 空 body 清空(D6);service 没有对 repository 返回值二次校验(不必要)。 + +### 9.7 `apps/api/app/api/workspaces.py` 与 `main.py`(M) + +职责:HTTP 路由与装配。变更形态:+45 / +6 行。 + +新代码(路由,`121-155`): + +```python +@router.get("/{wid}/bad-case-labels", dependencies=[Security(BEARER_AUTH)], responses={...}) +async def get_bad_case_labels( + wid: WorkspaceId, + request: Request, + access: Annotated[WorkspaceAccess, Depends(require_workspace_role("viewer"))], +) -> WorkspaceBadCaseLabelConfiguration: + return await bad_case_labels_from(request).get(access.workspace_id) + +@router.put("/{wid}/bad-case-labels", dependencies=[Security(BEARER_AUTH)], responses={...}) +async def replace_bad_case_labels(..., access: Annotated[WorkspaceAccess, Depends(require_workspace_role("space_admin"))], ...): + return await bad_case_labels_from(request).replace(access.workspace_id, body.items) +``` + +这在做什么:读/写分别用 viewer/space_admin 收口;`access.workspace_id` 来自已授权路由,而不是再信任路径参数。为什么用 `bad_case_labels_from` 而不是依赖注入容器:与文件里其它 `*_from(request)` 一致,`app.state` 是单例装配点(`main.py:57/141/328/713`)。检视发现:权限矩阵与设计一致(测试覆盖 viewer/member/outsider/space_admin);`GET` 对 outsider 返回 404 而不是 403,与其它工作空间资源一致。 + +### 9.8 `apps/api/app/db/crud/read_scope.py`(M) + +职责:空间可见性的唯一谓词工厂。变更形态:`condition(column)` → `case_condition()` + `session_condition()` 重写 + 新增 `scoped_case_ids()`。 + +旧代码: + +```python + def condition(self, column: ColumnElement[str]) -> ColumnElement[bool]: + if self.workspace_id is not None: + return column == self.workspace_id + if self.user_id is not None: + return column.in_(select(workspace_members.c.workspace_id).where(workspace_members.c.user_id == self.user_id)) + return true() +``` + +新代码: + +```python + def case_condition(self) -> ColumnElement[bool]: + if self.workspace_id is not None: + return ( + select(workspace_bad_cases.c.bad_case_id) + .where(workspace_bad_cases.c.workspace_id == self.workspace_id, + workspace_bad_cases.c.bad_case_id == bad_cases.c.bad_case_id) + .exists() + ) + if self.user_id is not None: + return bad_cases.c.bad_case_id.in_( + select(workspace_bad_cases.c.bad_case_id).where( + workspace_bad_cases.c.workspace_id.in_( + select(workspace_members.c.workspace_id).where(workspace_members.c.user_id == self.user_id)))) + return true() +``` + +这在做什么:把「列 = 空间」换成「该 case 在关联表里属于该空间」。为什么用 `EXISTS` 而不是 `IN`:单空间场景下 EXISTS 能在命中第一行就停,且语义上不产生重复;多空间/用户场景用 `IN` 子查询,避免三层相关子查询。`scoped_case_ids()`(`84-92`)给旧「显式空间列表」路由复用,避免它们再写一遍 `workspace_bad_cases` 过滤。 + +实现思路总结:权限边界从「列比较」升级成「关联存在性」,两种形态(单空间 EXISTS、多空间 IN)覆盖旧调用。 + +检视发现:方法名不体现「必须在含 `bad_cases` 的查询里使用」,未来若在无 `bad_cases` 的查询里调用会隐式笛卡尔积(D6 的提醒,当前无实害);其它读路径全部替换完毕,grep 未发现遗留 `bad_cases.workspace_id` 过滤。 + +### 9.9 `apps/api/app/db/crud/bad_case_catalog_sync.py`(M) + +职责:游标状态 + 单页事务写入 + 三计数。变更形态:+89 / −4。 + +旧 `_values` / 状态行 / `count_bad_cases`: + +```python + "meta_data": row.meta_data, + "source": row.source, +... + select(func.count()).select_from(bad_cases), # count_bad_cases +``` + +新代码: + +```python + "meta_data": row.meta_data, + "catalog_label": row.catalog_label, + "catalog_synced": True, + "source": row.source, +... + ids = [value["bad_case_id"] for value in values] + if ids: + await session.execute(delete(workspace_bad_cases).where( + workspace_bad_cases.c.bad_case_id.in_(ids), + workspace_bad_cases.c.assignment_source.in_(("legacy_owner", "catalog_label")))) + matching_assignments = ( + select(workspace_bad_case_labels.c.workspace_id, bad_cases.c.bad_case_id, + literal("catalog_label"), bad_cases.c.catalog_label, literal(now)) + .select_from(bad_cases.join(workspace_bad_case_labels, + workspace_bad_case_labels.c.label == bad_cases.c.catalog_label)) + .where(bad_cases.c.bad_case_id.in_(ids))) + await session.execute(insert(workspace_bad_cases).from_select([...], matching_assignments)) +``` + +`commit_page` 的整体顺序与理由见 §2.3;这里补三点:`catalog_synced` 只在新写/更新时置 true,正是为了让「直接上报行」不污染计数(`test_catalog_status_counts_exclude_direct_ingest_facts:378-420`);`_UPDATE_COLUMNS` 加入两列(`30-46`),保证重试/更新时投影列跟着事实走;`count_bad_cases` 只数 true(`409-428`),这是状态页 `synced` 的来源。 + +检视发现:删除条件不看 origin(D3);每页三次计数(D5);历史行不会补 true(D2);`assigned` 计数是全局的(不按空间),与设计「状态是全局健康度」一致。 + +### 9.10 `apps/api/app/service/acquisition/bad_case_catalog_sync.py`(M) + +职责:把上游 item 映射成持久化行并提取 label。变更形态:+13 行。 + +新代码(`61-74`、`84-88`): + +```python +def _catalog_label(meta_data: object) -> str | None: + if not isinstance(meta_data, Mapping): + return None + label = meta_data.get("label") + if not isinstance(label, str): + return None + if not label or len(label) > 128 or label != label.strip(): + return None + return label +``` + +这在做什么:只接受「Mapping + 字符串 + 1–128 + 无首尾空白」,其余都归为 invalid。为什么不做 `strip()` 后接受:契约要求精确匹配,`" review"` 与 `"review"` 是两个不同 label,静默 trim 会让上游的脏数据被「洗白」,也会让 invalid 计数失真。为什么不在模型层做:`BadCaseItem.meta_data` 是 `Any`,上游契约没有显式 label(flow issue 里也写了「真实 label 类型仍需脱敏样本确认」),校验放在同步入口更能容忍上游演进。 + +检视发现:大小写不折叠是刻意行为(测试 `"Review"` 记为合法但 unassigned,`test_catalog_sync_service.py:372-456`);没有长度以外的字符集限制(label 只做等值匹配,无注入面)。 + +### 9.11 `bad_case_catalog_sync_coordinator.py` 与 `api/acquisition.py`(M) + +职责:把状态行的三个计数透出到 `GET /api/acquisition/status`。变更形态:各 +12 / +6 行。 + +新代码(API 模型,`acquisition.py:75-82`):`synced/unsynced` 之后插入 `assigned/unassigned/invalid_label`;`_status_response`(`199-215`)逐字段拷贝;coordinator(`156-190`)在 `state is None` 或 `not available` 时回落 0。为什么保持 snake_case 模型 + camelCase alias:沿用 `IdentityModel` 的生成约定,前端拿到 `assigned/unassigned/invalidLabel`。 + +检视发现:`unavailable` 分支也返回三个 0(`test_catalog_status_api.py:227-240`),行为一致;`unassigned` 是 `max(valid-assigned,0)`,语义是「合法 label 但当前无空间订阅」,与设计一致。 + +### 9.12 `apps/api/app/db/crud/bad_case_ingest.py`(M) + +职责:凭据直接上报的事务写路径。变更形态:+68 / −7。 + +旧代码(额度与 `used`): + +```python + if existing is None: + used = await self._used(session, workspace_id) + if used >= quota: + raise QuotaExceeded(quota=quota, used=used) + created = await self._insert(...) + else: + created = False + await self._update(...) + workspace_used = await self._used(session, workspace_id) +... + async def _used(...): + select(func.count()).select_from(bad_cases).where(bad_cases.c.workspace_id == workspace_id) +``` + +新代码(节选): + +```python + already_assigned = await self._workspace_has_case(session, workspace_id, row.bad_case_id) + if not already_assigned: + used = await self._used(session, workspace_id) + if used >= quota: + raise QuotaExceeded(quota=quota, used=used) + if existing is None: ... + await self._assign_direct(session, workspace_id, row.bad_case_id, now=now) +... + async def _used(...): + select(func.count(func.distinct(workspace_bad_cases.c.bad_case_id))).where( + workspace_bad_cases.c.workspace_id == workspace_id) +``` + +这在做什么:把「额度」从「拥有行数」改成「可见 case 数」,并让已关联 case 的重复上报绕过额度;`_assign_direct` 先删同空间 `legacy_owner`、再补 `direct_ingest`。为什么先删后补:`legacy_owner` 是兼容态,直接上报一到就该收敛;为什么保留 `catalog_label`:删规则才撤销 label 可见性,上报不该顺手撤销。`_lock_workspace` 的 SQLite no-op UPDATE 模式(`210-230`)是这里的一致性来源(D4 对比的就是它)。 + +检视发现:`already_assigned` 豁免只在 `existing is None` 时才有意义(若 `existing` 属于别的空间会先抛 `BadCaseIdConflict`);对有 catalog 关联但 `bad_cases.workspace_id=ws-default` 的 case,别的空间直接上报仍会 409——这是既有「全局 ID 冲突」设计,不是本 PR 引入,但 label 路由让这种「看得见却上报不了」更容易被遇到,值得在 Note/文档里补一句。 + +### 9.13 `bad_cases.py`、`sessions.py`、`problems.py`、`overview.py`、`overview_targets.py`、`potential.py`、`probe_query.py`、`bad_case_sync.py`、`evolution_targets.py`(M,读路径组) + +职责:把所有空间化读的 case 过滤换成关联谓词。变更形态:多为 1–4 行替换。 + +典型旧/新: + +```python +# 旧 +.where(bad_cases.c.workspace_id == workspace_id) +# 新 +.where(WorkspaceReadScope.for_workspace(workspace_id).case_condition()) +``` + +```python +# 旧 +bad_cases.c.workspace_id.in_(workspace_ids) +# 新 +bad_cases.c.bad_case_id.in_(scoped_case_ids(workspace_ids)) +``` + +这在做什么:`overview._case_conditions()` 被列表/汇总/趋势/来源/对象统计复用(`overview.py:102-132`),一处替换覆盖六条读;`sessions._session_conditions()` 用 `session_condition()` 把「可见 case 的根会话」作为 Session 过滤(`sessions.py:247-260`);`bad_cases.analysis_progress`、`bad_case_sync`、`probe_query`、`evolution_targets` 这些「拿到一组显式空间」的旧兼容路由统一用 `scoped_case_ids`。 + +检视发现:`analysis_progress` 只换了 case 过滤、没换报告 join(D1);`overview.py:226-238` 的 `used` 改按关联去重;`sessions.py` 的 6 处替换一致;`problems.py` 的详情路径在 case 不存在时仍返回 404(`test_scope_associations.py:97-101` 钉住了第三方看不到)。没有发现仍按 `bad_cases.workspace_id` 过滤的读路径。 + +### 9.14 `apps/api/app/db/crud/workspaces.py` 与 `acquisition_replay.py`(M) + +职责:空间 `used`、知识根回填、replay 证据范围。变更形态:+17 / −10、+5 / −1。 + +旧代码(`used_counts`): + +```python + select(bad_cases.c.workspace_id.label("workspace_id"), func.count().label("case_count")) + .where(bad_cases.c.workspace_id.in_(workspace_ids)) + .group_by(bad_cases.c.workspace_id) +``` + +新代码: + +```python + select(workspace_bad_cases.c.workspace_id, + func.count(func.distinct(workspace_bad_cases.c.bad_case_id)).label("case_count")) + .where(workspace_bad_cases.c.workspace_id.in_(workspace_ids)) + .group_by(workspace_bad_cases.c.workspace_id) +``` + +这在做什么:空间列表/详情/额度统一数「关联去重 case」;`list_workspace_knowledge_roots` 从 `bad_cases → workspaces` 改为 `bad_cases → workspace_bad_cases → workspaces`,并保留「按 workspace id 去重后合并 knowledge roots」的逻辑(`acquisition_replay.py:309-345`)。为什么 replay 也要改:一条公共 case 的 root 现在可能由多个空间关联,replay 的知识根应该覆盖所有能看见它的空间,而不是旧默认空间。 + +检视发现:`used` 口径变化会让默认空间的 `used` 在升级后下降(新 catalog 行没有 legacy_owner、也没有 label 命中时不计入),这是设计接受的「used 按关联」;replay 的知识根范围现在会随 label 配置动态变化,离线管线跨空间合并知识根属于设计内的 union(docstring 已说明),当前无在线读风险。 + +### 9.15 `apps/api/app/db/crud/fixtures.py`(M) + +职责:fixture/corpus 种子 + 迁移语义的测试侧镜像。变更形态:+31 行。 + +新代码(`153-179`): + +```python +async def backfill_legacy_associations(database: Database) -> None: + async with database.transaction() as session: + await session.execute(text(""" + INSERT INTO workspace_bad_cases (workspace_id, bad_case_id, assignment_source, label, assigned_at) + SELECT bc.workspace_id, bc.bad_case_id, 'legacy_owner', NULL, CURRENT_TIMESTAMP + FROM bad_cases bc + WHERE bc.workspace_id IS NOT NULL + AND NOT EXISTS ( + SELECT 1 FROM workspace_bad_cases wbc + WHERE wbc.workspace_id = bc.workspace_id + AND wbc.bad_case_id = bc.bad_case_id + AND wbc.assignment_source = 'legacy_owner') + """)) +``` + +这在做什么:所有直接写 `bad_cases.workspace_id` 的 fixture 在 seed 后补关联,否则读路径(只认关联)会看不到 seed 数据。为什么带 `NOT EXISTS`:fixture 可能在同一个库里多次 seed/多次回填;为什么放 fixtures 而不是测试 helper:e2e seed 脚本也用它(`tests/e2e/support/*.py`),`tests/workspaces/helpers.py` 只是转调(`helpers.py:133-145`)。 + +实现思路总结:生产迁移与测试/演示数据共享同一语义,但实现是两份 SQL(D8)。 + +检视发现:与迁移版本唯一差异就是 `NOT EXISTS`;`test_database`/e2e 的种子覆盖完整。没有发现 fixture 回填把 `origin='report'` 也当 legacy 的问题(对测试无害),但生产迁移同理需区分(D3)。 + +### 9.16 `apps/web/src/api/workspaces.ts`、`queryKeys.ts`、`composables/useWorkspaces.ts`(M) + +职责:前端数据访问与缓存失效。变更形态:+31 / +2 / +64。 + +新代码(composable,`342-391`): + +```ts +export function useWorkspaceBadCaseLabels(workspaceId, enabled = true) { + return useQuery({ + queryKey: computed(() => queryKeys.adminBadCaseLabels(toValue(workspaceId))), + queryFn: () => listWorkspaceBadCaseLabels(toValue(workspaceId)), + enabled: computed(() => toValue(enabled) && toValue(workspaceId).length > 0), + }); +} + +export function useReplaceWorkspaceBadCaseLabels(workspaceId) { + const mutation = useMutation({ + mutationFn: (body) => replaceWorkspaceBadCaseLabels(toValue(workspaceId), body), + onSuccess: async () => { + await Promise.all([ + queryClient.invalidateQueries({ queryKey: queryKeys.adminBadCaseLabels(...) }), + queryClient.invalidateQueries({ queryKey: queryKeys.workspace(...) }), + queryClient.invalidateQueries({ queryKey: queryKeys.workspaces() }), + queryClient.invalidateQueries({ queryKey: queryKeys.authSession }), + ]); + await refreshAuthSession(); + }, + }); + return { isPending: mutation.isPending, replaceLabels: (body) => mutation.mutateAsync(body) }; +} +``` + +这在做什么:查询键挂在 `["ws", id]` 前缀下,所以保存后一次前缀失效即可覆盖总览/Session/自进化/页签;额外刷新 `["ws"]` 与会话是因为工作空间列表的 `used` 也会变。为什么 `enabled` 依赖 `workspaceId.length > 0`:与既有 composable 的模式一致,避免路由尚未解析时发空请求。为什么 `replaceLabels` 用 `mutateAsync`:组件需要 `await` 后在成功/失败分支显示不同反馈。 + +检视发现:`isPending` 是 mutation 的 ref,模板里写 `mutation.isPending.value`(`BadCaseLabelsTab.vue:139/143`)是正确的显式解包;失效范围足够,没有发现漏刷的 query(`queryKeys.workspace` 是 `["ws", id]`,见 `queryKeys.ts:21-22`)。 + +### 9.17 `apps/web/src/pages/workspaces/components/BadCaseLabelsTab.vue`(A) + +职责:页签的全部交互。变更形态:新文件 467 行(脚本 121 行 + 模板 140 行 + scoped CSS 约 200 行)。 + +关键依赖:`@tanstack/vue-query`(查询/变更状态)、Element Plus `ElMessage`(成功 toast)、项目自有的 `LoadingSkeleton` / `ErrorState`、V2 设计 token(`--text`/`--border`/`--blue`/`--orange` 等)。比喻:它像一张**可擦写的订阅单**——服务端快照是底稿,用户在上面加删;只有「当前草稿还等于上一版底稿」时才接受新的服务端快照,否则保住用户的手写内容。 + +状态机(`27-54`): + +```ts +const savedItems = computed(() => labelsQuery.data.value?.items ?? []); +const assignedCount = computed(() => labelsQuery.data.value?.assignedBadCaseCount ?? 0); +const draft = ref([...savedItems.value]); +... +watch(() => props.workspaceId, () => { draft.value = [...savedItems.value]; }); +watch(savedItems, (items, previous) => { + if (sameLabels(draft.value, previous ?? [])) draft.value = [...items]; +}); +const isDirty = computed(() => !sameLabels(draft.value, savedItems.value)); +``` + +这在做什么:`watch(savedItems)` 的「只在 draft 仍等于上一版」条件是关键——冷加载/切换页签会采纳,后台 refetch 不会覆盖用户正在编辑的草稿,保存成功后也不会把用户刚写的内容吞掉(因为 draft 此时已等于新值或用户又改了)。`watch(workspaceId)` 处理跨空间:直接采纳新空间快照(配合 query 的 key 变化)。校验(`62-71`)覆盖空、首尾空白、超长、重复;`addLabel` 排序后写入(`77-82`);`saveLabels` 只在 `canManage` 时执行并映射错误码(`97-120`)。模板的空态/错误态/只读态/加载态分别在 `157-203`、`227-234`、`132-146`。样式用了 `color-mix` 与现有 token,没有引入新的视觉语言。 + +检视发现:`sameLabels` 用 `join("\u0000")` 比较,理论上 label 含 NUL 时两个不同列表可能相等(API 只校验长度/空白,未禁 NUL),实际风险极低;`assignedCount` 在保存后要等 refetch 才更新(可接受);保存失败只覆盖 `WORKSPACE_FORBIDDEN`/`VALIDATION_INVALID` 两个码,网络错误落通用文案(可接受,但可补测试)。 + +### 9.18 `Admin.vue` 与 `Admin.test.ts`(M) + +职责:把页签挂到空间管理。变更形态:+14 / −1、测试 +18 / −2。 + +新代码(`Admin.vue:35-49`、`303-308`): + +```ts +type AdminTab = "spaces" | "members" | "ingest" | "bad-case-labels" | "attribution-skills" | "auth"; +const TABS = [ + { key: "spaces", label: "空间与额度" }, + { key: "members", label: "成员与角色" }, + { key: "ingest", label: "上报接入" }, + { key: "bad-case-labels", label: "Badcase 类型" }, + { key: "attribution-skills", label: "归因 Skill" }, + { key: "auth", label: "鉴权接入" }, +]; +``` + +```vue + +``` + +这在做什么:页签位置严格按设计 §7(上报接入之后、归因 Skill 之前);`canManage` 由 Admin 计算后传入,viewer 只读。测试断言了「6 个页签」与「相邻顺序」(`Admin.test.ts:225-240`、`429-444`)。检视发现:E2E 只同步了页签数(见 §5),没有点击新页签的浏览器用例。 + +### 9.19 `packages/contracts`(M,生成链组) + +职责:前后端共享协议。变更形态:`openapi.json` 新增两个 schema 与 `/api/workspaces/{wid}/bad-case-labels` 的 GET/PUT;`api.d.ts` 同步;`index.ts`/`workspaces.ts` 只做类型再导出。 + +形状(`openapi.json:10370-10390`、`15520` 附近): + +```json +"WorkspaceBadCaseLabelConfiguration": { + "additionalProperties": false, + "properties": { + "assignedBadCaseCount": {"minimum": 0.0, "type": "integer"}, + "items": {"items": {"type": "string"}, "title": "Items", "type": "array"} + }, + "required": ["assignedBadCaseCount", "items"], + "title": "WorkspaceBadCaseLabelConfiguration", + "type": "object" +} +``` + +```ts +export type WorkspaceBadCaseLabelConfiguration = components["schemas"]["WorkspaceBadCaseLabelConfiguration"]; +export type WorkspaceBadCaseLabelRequest = components["schemas"]["WorkspaceBadCaseLabelRequest"]; +``` + +这在做什么:契约链保证 Web 不手写字段名。为什么 `WorkspaceBadCaseLabelRequest.items` 在 schema 里没有 `required`:Pydantic 的 `default_factory` 让它在 OpenAPI 里成了可选(D6 的根因)。检视发现:生成物没有被手改的迹象;`WorkspaceBadCaseLabelConfiguration.items` 是 required,响应模型正确。 + +### 9.20 文档、Note、flow、设计、ER 图与原型(A/M) + +- `docs/architecture.md:36` / `.en.md:36`:只改一句,把两张新表加入空间表清单并说明「可见性走关联表」。这是**现状** home,措辞准确;英文侧同步、i18n 双侧哈希在 `.i18n.yaml` 重录,符合 `docs/i18n/README.md` 的配对规则。 +- Note(`.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.md`):Problem/Decision/Alternatives/Consequences 四段完整,拒绝了「复制公共 case」「读路径兜底 `workspace_id OR 关联`」「SQL 解析 JSON」「物化 label 字典」「追溯改旧 run」五种替代方案,取舍写得清楚。**但它没有写 D2/D3 的存量迁移边界**:Consequences 只说「迁移按 `WHERE workspace_id IS NOT NULL` 回填 legacy_owner」,没有说存量 `catalog_label` 不会被补、游标不会回退。 +- 设计 17:§1 明确「当前游标只能看到新 ID」「不推断缺失 label」「不建 label 字典」;§2.2/§2.3 定义三态与投影;§4.3 写「新增规则补齐历史数据」——与 D2 的存量现实有张力,建议补一句「只对已投影 `catalog_label` 的行生效」。 +- flow issue `bugfix-58`:`in-progress`,scope 覆盖 `apps/api/**`、`apps/web/**`、`packages/contracts/**`、`tests/**`、`plans/**`、`.agents/**`、`docs/**`,与改动面一致;撞号修复把 `bugfix-bad-case-sync-type-title` 从 56 改成 59,`bugfix-56`(explicit-skill-conclusion)置 done,符合 #588 已合并的事实。 +- ER 图 `plans/db-relationship-diagram.md`:新增两张表、`catalog_label/catalog_synced` 两个字段、值引用表与可见性链路说明(`74-90`),与代码一致;它明确写了 `bad_cases.workspace_id` 在 #582 后「仅冲突检测」,准确。 +- V2 原型:新增页签、chips、空态、dirty、保存 toast 与 `bad-case-labels` 的只读可见性;与真实组件的一个小差异是原型在添加时 `trim()` 输入(空白被静默去掉),真实组件是报错「首尾不能有空白」(设计 §7 要求提示)。原型是设计产物,不阻塞代码,但下次同步时可以对齐。 + +检视发现:PR 描述的迁移编号/提交数过期;Note/设计缺少存量迁移边界;原型与实现的空白校验行为不一致(D7 之外的小漂移)。 + +### 9.21 测试组(A/M) + +新增测试的覆盖面(已读): + +| 面 | 用例 | 结论 | +|---|---|---| +| 权限 | `test_bad_case_labels_api.py:45-108`:viewer 读 200、member 写 403、outsider 读 404、space_admin 写 200 | 覆盖完整 | +| 全量替换 + fan-out | `test_bad_case_labels_api.py:111-166`:两个空间共享 label、direct 关联保留、`used` 去重、删规则后 direct 仍可见 | 覆盖完整,且把 `assignedBadCaseCount` 口径固定成「全部来源」 | +| 校验 | `test_bad_case_labels_api.py:169-188`:重复、首空白、129 字符、空串 → 422 | 覆盖完整 | +| 回滚 | `test_bad_case_labels_service.py:17-90`:trigger 让关联插入失败,规则回滚到旧值、关联为空 | 覆盖完整 | +| 跨空间可见性 | `test_scope_associations.py:78-120`:两个空间各看到 1、第三方 0 且详情 404;删规则只撤销本空间 | 只走总览 `totals.badCases` + 详情 | +| 目录同步 | `test_catalog_sync_service.py:372-456`:`review`/`Review`/` review`/非对象,assigned=1、unassigned=1、invalid=2 | 覆盖完整 | +| 同步幂等/回滚 | `test_catalog_sync_repository.py:258-375`:重复页替换旧 label、失败回滚事实+游标 | 覆盖完整,依赖 `database.py` 的 BEGIN 修复 | +| 迁移 | `test_migration.py:88-192`:列/索引/FK/单行 legacy 回填 | 未覆盖存量 catalog 行、未覆盖回填重跑 | +| 直接上报 | `test_ingest_repository.py:186-238`:direct 收敛 legacy、保留 catalog、`used=1` | 覆盖完整 | +| 前端 | `BadCaseLabelsTab.test.ts` 8 例 + `Admin.test.ts` 顺序/数量 | 未覆盖保存失败路径、未覆盖真实浏览器 | + +检视发现:读侧验收的跨栈覆盖偏窄(只有总览与详情),`analysis_progress` 没有多空间报告用例(D1 因此没被抓住);迁移没有「升级前已有 catalog 数据」的场景(D2);`origin='report'` 被目录页触达的场景缺失(D3)。 diff --git a/plans/fullstack-design/17-workspace-bad-case-label-routing.md b/plans/fullstack-design/17-workspace-bad-case-label-routing.md index 4f07f6f5..f0b875ff 100644 --- a/plans/fullstack-design/17-workspace-bad-case-label-routing.md +++ b/plans/fullstack-design/17-workspace-bad-case-label-routing.md @@ -36,7 +36,7 @@ 同一空间与 badcase 可以同时有直接上报和 label 两种来源;读取使用 `EXISTS` 或 `SELECT DISTINCT workspace_id,bad_case_id`,不重复计数。删除 label 规则只删除对应的 `catalog_label` 行,直接上报关联继续保留。 -迁移创建两表及索引,并把每条既有 `bad_cases.workspace_id` 回填为 `legacy_owner`。后续直接上报同 ID 时把同空间的 `legacy_owner` 收敛为 `direct_ingest`;公共目录再次触达同 ID 时移除其 `legacy_owner`,再依据 label 建立 `catalog_label`,避免旧默认空间继续看到公共数据。 +迁移创建两表及索引,并把每条既有 `bad_cases.workspace_id` 回填为关联:`origin='report'` 的行为 `direct_ingest`,`origin='catalog'` 的行为 `legacy_owner`;同时把存量 catalog 行的 `meta_data.label` 按 label 契约投影到 `catalog_label`(合法值保留,非法或缺失为 `NULL`),并把 `catalog_synced` 置真。存量公共事实因此无需重放游标即可参与新增 label 规则;重复执行回填保持幂等。后续直接上报同 ID 时把同空间的 `legacy_owner` 收敛为 `direct_ingest`;公共目录再次触达同 ID 时移除其 `legacy_owner`,再依据 label 建立 `catalog_label`,避免旧默认空间继续看到公共数据。 ### 2.3 `bad_cases.catalog_label` @@ -82,15 +82,17 @@ API 以完整集合替换当前空间 label。一个数据库事务校验并锁 已持久化的 `evolution_run_candidates`、`probe_reports.workspace_id` 和运行快照不反查实时关联,因此配置变化只影响后续预览和新运行,已有运行可继续恢复。 +归因进度聚合按请求空间匹配 `probe_reports.workspace_id`,不跟随 `bad_cases.workspace_id`:一条 label 共享的公共 case 在空间 B 产出的报告只计入 B,不会因为事实行仍归默认空间而错算到默认空间;全局管理员视图不限制报告空间。 + ## 6. API ### `GET /api/workspaces/{wid}/bad-case-labels` -空间成员可读,返回 `{ "items": ["code-review", "tool-use"], "assignedBadCaseCount": 142 }`。 +空间成员可读,返回 `{ "items": ["code-review", "tool-use"], "assignedBadCaseCount": 142 }`。`assignedBadCaseCount` 是该空间所有来源(`legacy_owner` / `direct_ingest` / `catalog_label`)去重后的可见 case 数,不等于 label 命中数;清空规则只撤销 `catalog_label` 关联。 ### `PUT /api/workspaces/{wid}/bad-case-labels` -空间管理员或全局管理员可写,请求 `{ "items": ["code-review", "tool-use"] }`。服务端排序、去重后以完整集合原子替换并完成历史重算;非法项返回 422,空间不存在返回 404,权限不足返回 403。响应为上述资源。 +空间管理员或全局管理员可写,请求 `{ "items": ["code-review", "tool-use"] }`。`items` 为必填字段:省略或传 `{}` 返回 422,`[]` 表示显式清空全部规则。服务端排序、去重后以完整集合原子替换并完成历史重算;非法项返回 422,空间不存在返回 404,权限不足返回 403。响应为上述资源。 ## 7. 空间管理 UI From bf7f09120144de5c74459223c27e16b04885706d Mon Sep 17 00:00:00 2001 From: ZTGolem <354251175+ZTGolem@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:35:29 +0800 Subject: [PATCH 14/17] fix(ci): serialize catalog savepoints and renumber flow issues (#582) - start the SQLite transaction inside commit_page with a no-op UPDATE so begin_nested cannot commit the page unit, without making every transaction eagerly hold a read snapshot - renumber the new label and sync-type-title issues to bugfix-60/61 to avoid ids introduced on main - mark the portable backend issue done after #604 closed - refresh the review record's issue references --- .../issues/bugfix-ai-agent-portable-backend.en.md | 2 +- .../bugfix-ai-agent-portable-backend.i18n.yaml | 4 ++-- .../issues/bugfix-ai-agent-portable-backend.md | 2 +- .../issues/bugfix-bad-case-sync-type-title.en.md | 2 +- .../bugfix-bad-case-sync-type-title.i18n.yaml | 6 +++--- .../flow/issues/bugfix-bad-case-sync-type-title.md | 2 +- .../issues/bugfix-evolution-label-allowlist.en.md | 2 +- .../bugfix-evolution-label-allowlist.i18n.yaml | 4 ++-- .../issues/bugfix-evolution-label-allowlist.md | 2 +- apps/api/app/db/crud/bad_case_catalog_sync.py | 12 +++++++++++- apps/api/app/db/database.py | 11 +---------- plans/2026-11-25-pr597-review.md | 14 +++++++------- 12 files changed, 32 insertions(+), 31 deletions(-) diff --git a/.agents/flow/issues/bugfix-ai-agent-portable-backend.en.md b/.agents/flow/issues/bugfix-ai-agent-portable-backend.en.md index e797053c..4ffb62f9 100644 --- a/.agents/flow/issues/bugfix-ai-agent-portable-backend.en.md +++ b/.agents/flow/issues/bugfix-ai-agent-portable-backend.en.md @@ -8,7 +8,7 @@ id: bugfix-59 milestone: bugfix depends: [] priority: P2 -status: ready +status: done scope: - apps/api/app/third_party_api/ai_agent/** - apps/api/app/service/evolution/local_attribution.py diff --git a/.agents/flow/issues/bugfix-ai-agent-portable-backend.i18n.yaml b/.agents/flow/issues/bugfix-ai-agent-portable-backend.i18n.yaml index 8788aca9..832319b2 100644 --- a/.agents/flow/issues/bugfix-ai-agent-portable-backend.i18n.yaml +++ b/.agents/flow/issues/bugfix-ai-agent-portable-backend.i18n.yaml @@ -1,5 +1,5 @@ # 双语配对一致性记录(docs/i18n/README.md):两侧在最后一次确认一致状态下的 # git blob hash。两种语言同等权威;编辑任一侧后带上另一侧,然后重录: # pnpm run record:i18n -- .agents/flow/issues/bugfix-ai-agent-portable-backend.md -bugfix-ai-agent-portable-backend.md: c045896d50afe84faa3067b6389435d62c5e7c22 -bugfix-ai-agent-portable-backend.en.md: e797053cd71b3f8c3fbc0f8ed09961bda1afeb05 +bugfix-ai-agent-portable-backend.md: 1ae5f094608e16965753917475cd49f57f008bbb +bugfix-ai-agent-portable-backend.en.md: 4ffb62f99c800b23ba27ebac2b7b8178882fefe3 diff --git a/.agents/flow/issues/bugfix-ai-agent-portable-backend.md b/.agents/flow/issues/bugfix-ai-agent-portable-backend.md index c045896d..1ae5f094 100644 --- a/.agents/flow/issues/bugfix-ai-agent-portable-backend.md +++ b/.agents/flow/issues/bugfix-ai-agent-portable-backend.md @@ -8,7 +8,7 @@ id: bugfix-59 milestone: bugfix depends: [] priority: P2 -status: ready +status: done scope: - apps/api/app/third_party_api/ai_agent/** - apps/api/app/service/evolution/local_attribution.py diff --git a/.agents/flow/issues/bugfix-bad-case-sync-type-title.en.md b/.agents/flow/issues/bugfix-bad-case-sync-type-title.en.md index 89b81570..bceac950 100644 --- a/.agents/flow/issues/bugfix-bad-case-sync-type-title.en.md +++ b/.agents/flow/issues/bugfix-bad-case-sync-type-title.en.md @@ -4,7 +4,7 @@ English | [中文](bugfix-bad-case-sync-type-title.md) ```yaml flow kind: issue -id: bugfix-59 +id: bugfix-61 milestone: bugfix depends: - m6-16 diff --git a/.agents/flow/issues/bugfix-bad-case-sync-type-title.i18n.yaml b/.agents/flow/issues/bugfix-bad-case-sync-type-title.i18n.yaml index 7a487ae6..6ac5f2f8 100644 --- a/.agents/flow/issues/bugfix-bad-case-sync-type-title.i18n.yaml +++ b/.agents/flow/issues/bugfix-bad-case-sync-type-title.i18n.yaml @@ -1,5 +1,5 @@ # 双语配对一致性记录(docs/i18n/README.md):两侧在最后一次确认一致状态下的 # git blob hash。两种语言同等权威;编辑任一侧后带上另一侧,然后重录: -# pnpm run record:i18n -- .agents\flow\issues\bugfix-bad-case-sync-type-title.md -bugfix-bad-case-sync-type-title.md: 88e2ff4af062f44ff395cf0720053b0350cb862d -bugfix-bad-case-sync-type-title.en.md: 89b8157024c2313060fa5adea9dc9842a0eb6dfd +# pnpm run record:i18n -- .agents/flow/issues/bugfix-bad-case-sync-type-title.md +bugfix-bad-case-sync-type-title.md: f68b226319c4ffa89ff5db731373cd4e180fe3ea +bugfix-bad-case-sync-type-title.en.md: bceac9500724f7d75327d9f2bfc91e24c69832ca diff --git a/.agents/flow/issues/bugfix-bad-case-sync-type-title.md b/.agents/flow/issues/bugfix-bad-case-sync-type-title.md index 88e2ff4a..f68b2263 100644 --- a/.agents/flow/issues/bugfix-bad-case-sync-type-title.md +++ b/.agents/flow/issues/bugfix-bad-case-sync-type-title.md @@ -4,7 +4,7 @@ ```yaml flow kind: issue -id: bugfix-59 +id: bugfix-61 milestone: bugfix depends: - m6-16 diff --git a/.agents/flow/issues/bugfix-evolution-label-allowlist.en.md b/.agents/flow/issues/bugfix-evolution-label-allowlist.en.md index 15f59954..8aefb25a 100644 --- a/.agents/flow/issues/bugfix-evolution-label-allowlist.en.md +++ b/.agents/flow/issues/bugfix-evolution-label-allowlist.en.md @@ -4,7 +4,7 @@ English | [中文](bugfix-evolution-label-allowlist.md) ```yaml flow kind: issue -id: bugfix-58 +id: bugfix-60 milestone: bugfix depends: [] priority: P2 diff --git a/.agents/flow/issues/bugfix-evolution-label-allowlist.i18n.yaml b/.agents/flow/issues/bugfix-evolution-label-allowlist.i18n.yaml index e0cdb604..a680d144 100644 --- a/.agents/flow/issues/bugfix-evolution-label-allowlist.i18n.yaml +++ b/.agents/flow/issues/bugfix-evolution-label-allowlist.i18n.yaml @@ -1,5 +1,5 @@ # 双语配对一致性记录(docs/i18n/README.md):两侧在最后一次确认一致状态下的 # git blob hash。两种语言同等权威;编辑任一侧后带上另一侧,然后重录: # pnpm run record:i18n -- .agents/flow/issues/bugfix-evolution-label-allowlist.md -bugfix-evolution-label-allowlist.md: c6b1f543087d058ae7f0cfdbcc3695f13833a1de -bugfix-evolution-label-allowlist.en.md: 15f599544dd3d27cdb01c6f0fecec36099c27725 +bugfix-evolution-label-allowlist.md: 69f962120196489a9e4a56abed64d144d0aae320 +bugfix-evolution-label-allowlist.en.md: 8aefb25a78e31712f737997a1088a0af53eb5efb diff --git a/.agents/flow/issues/bugfix-evolution-label-allowlist.md b/.agents/flow/issues/bugfix-evolution-label-allowlist.md index c6b1f543..69f96212 100644 --- a/.agents/flow/issues/bugfix-evolution-label-allowlist.md +++ b/.agents/flow/issues/bugfix-evolution-label-allowlist.md @@ -4,7 +4,7 @@ ```yaml flow kind: issue -id: bugfix-58 +id: bugfix-60 milestone: bugfix depends: [] priority: P2 diff --git a/apps/api/app/db/crud/bad_case_catalog_sync.py b/apps/api/app/db/crud/bad_case_catalog_sync.py index c12fcf8d..78fa51f7 100644 --- a/apps/api/app/db/crud/bad_case_catalog_sync.py +++ b/apps/api/app/db/crud/bad_case_catalog_sync.py @@ -8,7 +8,7 @@ from datetime import datetime from typing import Any -from sqlalchemy import delete, func, insert, literal, select, update +from sqlalchemy import delete, false, func, insert, literal, select, update from sqlalchemy.engine import RowMapping from sqlalchemy.exc import IntegrityError, OperationalError, ProgrammingError from sqlalchemy.ext.asyncio import AsyncSession @@ -264,6 +264,16 @@ async def commit_page( """ values = [_values(item) for item in items] async with self._database.transaction() as session: + if self._database.dialect == "sqlite": + # SQLite's DBAPI defers BEGIN until the first DML statement, so + # a SAVEPOINT opened before any write would release into its own + # transaction. A no-op UPDATE materializes the outer transaction + # first, keeping the savepoint inside the page's atomic unit. + await session.execute( + update(bad_case_catalog_sync) + .where(false()) + .values(updated_at=bad_case_catalog_sync.c.updated_at), + ) ownership = await self._ownership(session, values) pending = [value for value in values if value["bad_case_id"] not in ownership] inserted_ids: set[str] = set() diff --git a/apps/api/app/db/database.py b/apps/api/app/db/database.py index b7b02d29..e0e5a9d6 100644 --- a/apps/api/app/db/database.py +++ b/apps/api/app/db/database.py @@ -74,18 +74,9 @@ async def session(self) -> AsyncIterator[AsyncSession]: @asynccontextmanager async def transaction(self) -> AsyncIterator[AsyncSession]: - """Commit successful writes and roll back every exception. - - SQLite's legacy DBAPI transaction control defers ``BEGIN`` until the - first DML statement, so a ``SAVEPOINT`` opened before any write starts - its own transaction and ``RELEASE`` commits it even when the outer - block later rolls back. Opening the transaction explicitly keeps - nested savepoints inside the caller's atomic unit on SQLite. - """ + """Commit successful writes and roll back every exception.""" async with self._factory()() as session: try: - if self.dialect == "sqlite": - await session.execute(text("BEGIN")) yield session await session.commit() except BaseException: diff --git a/plans/2026-11-25-pr597-review.md b/plans/2026-11-25-pr597-review.md index a4c1045c..eaf3e103 100644 --- a/plans/2026-11-25-pr597-review.md +++ b/plans/2026-11-25-pr597-review.md @@ -4,7 +4,7 @@ - owning Note:[公共 badcase 按 label 划分空间的可关联事实与统一读边界](../.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.md)(`.en.md` / `.i18n.yaml` 同目录) - 设计文档:[17 公共 badcase 按 label 划分工作空间](fullstack-design/17-workspace-bad-case-label-routing.md) - 实现计划:[2026-11-24 issue 582 实现计划](superpowers/plans/2026-11-24-issue-582-badcase-label-routing.md) -- 关联 issue:[#582](https://github.com/Shadow-Azure/harness-evolution/issues/582)(flow issue `bugfix-58`,`in-progress`) +- 关联 issue:[#582](https://github.com/Shadow-Azure/harness-evolution/issues/582)(flow issue `bugfix-60`,`in-progress`) - 日期:2026-11-25 > 本文按 `.agents/skills/pr-review/SKILL.md` 的体例产出;检视文档落 `plans/`,不进入 Agent Notes。本文只描述当前实现与检视判断,不写变更史。检视侧未运行完整测试套件(见 §5 的验证口径说明);检视后对 D1/D2/D3/D4/D6/D8 的修复处置见 §7。 @@ -70,7 +70,7 @@ | `.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.{md,en.md,i18n.yaml}` | A ×3 | owning Note 三件套:Problem / Decision / Alternatives / Consequences | | `.agents/flow/issues/bugfix-evolution-label-allowlist.{md,en.md,i18n.yaml}` | A ×3 | #582 的 flow issue:`in-progress`,scope 覆盖 apps/web/contracts/tests/plans/.agents/docs | | `.agents/flow/issues/bugfix-explicit-skill-conclusion.{md,en.md,i18n.yaml}` | M ×3 | `bugfix-56` 置 `done`(#588 已合并) | -| `.agents/flow/issues/bugfix-bad-case-sync-type-title.{md,en.md,i18n.yaml}` | M ×3 | 撞号修复:`bugfix-56 → bugfix-59` | +| `.agents/flow/issues/bugfix-bad-case-sync-type-title.{md,en.md,i18n.yaml}` | M ×3 | 撞号修复:`bugfix-56 → bugfix-61` | | `docs/architecture.{md,en.md,i18n.yaml}` | M ×3 | 数据层策略一句:空间表补两张新表、可见性走关联;i18n 双哈希重录 | | `plans/fullstack-design/17-workspace-bad-case-label-routing.md` | A | 设计正文:目标/数据模型/label 契约/写入重算/读边界/API/UI/验证 | | `plans/fullstack-design/README.md` | M | 设计索引加第 17 篇;D21 决策改写为「可见性单元」并加 2026-11-24 修订 | @@ -136,7 +136,7 @@ | 门禁 / 套件 | PR 描述声明 | 检视侧核对 | |---|---|---| | `pnpm contract:check` | 通过 | `openapi.json` 有 `WorkspaceBadCaseLabelRequest/Configuration` 与 path,`api.d.ts`/`index.ts`/`workspaces.ts` 同源引用,未见手写漂移(✅ 静态) | -| `typecheck` / `typecheck:web` / `lint:docs` / `verify:flow` | 通过 | 双语三件套、i18n 哈希、flow issue `bugfix-58`/撞号调整均在(✅ 静态) | +| `typecheck` / `typecheck:web` / `lint:docs` / `verify:flow` | 通过 | 双语三件套、i18n 哈希、flow issue `bugfix-60`/撞号调整均在(✅ 静态) | | `tests/workspaces` 等五组后端测试 | 全绿 | 用例文件与用例名存在(✅ 静态,未复跑) | | 前端 `vitest`(页签 + 导航) | 通过 | 两个测试文件存在:页签组件 8 个用例 + 管理页导航/页签数断言(✅ 静态,未复跑) | | 迁移编号 / 提交数 | 描述写 0032、8 个提交 | 实际 0033、14 个提交(含 2 merge),描述需更新 | @@ -406,7 +406,7 @@ FastAPI 模型是契约源:`WorkspaceBadCaseLabelRequest` 的 items 有 `defau | 分页失败整页回滚、事实+关联+游标同事务 | —— | `test_catalog_sync_repository.py:321-375` + `database.py` BEGIN 修复 | ✅ 已决(2026-11-25,提交 `94c018b9`) | | 规则保存失败时规则与关联一起回滚 | —— | `test_bad_case_labels_service.py:17-90`(SQLite trigger) | ✅ 已决(2026-11-25,测试实存) | | 契约 schema/path/类型导出 | —— | `openapi.json`/`api.d.ts`/`index.ts` 同源 | ✅ 已决(2026-11-25,静态核对) | -| 双语文档与 flow issue | —— | architecture 三件套、Note 三件套、`bugfix-58` | ✅ 已决(2026-11-25,静态核对) | +| 双语文档与 flow issue | —— | architecture 三件套、Note 三件套、`bugfix-60` | ✅ 已决(2026-11-25,静态核对) | | PR 描述编号/提交数过期(0032、8 个提交) | 流程(描述准确度) | PR 描述 | ✅ 可自修(无需代码) | ## §8 链接 @@ -418,8 +418,8 @@ FastAPI 模型是契约源:`WorkspaceBadCaseLabelRequest` 的 items 有 `defau - 实现计划:`plans/superpowers/plans/2026-11-24-issue-582-badcase-label-routing.md` - 数据模型图:`plans/db-relationship-diagram.md`(PDF 同目录) - 相关常驻文档:`docs/architecture.md:36`(英文 `.en.md:36`;i18n `.i18n.yaml`) -- 相关流程记录:`.agents/flow/issues/bugfix-evolution-label-allowlist.md`(`bugfix-56 → done`、`bugfix-56 → bugfix-59` 撞号修复) -- 后续:合并后按流程提交闭环 PR,把 `bugfix-58` 置 `done` 并关闭 #582 +- 相关流程记录:`.agents/flow/issues/bugfix-evolution-label-allowlist.md`(`bugfix-58 → done`,main 重编号;`bugfix-56 → bugfix-61` 撞号修复) +- 后续:合并后按流程提交闭环 PR,把 `bugfix-60` 置 `done` 并关闭 #582 ## §9 文件级代码分析 @@ -988,7 +988,7 @@ export type WorkspaceBadCaseLabelRequest = components["schemas"]["WorkspaceBadCa - `docs/architecture.md:36` / `.en.md:36`:只改一句,把两张新表加入空间表清单并说明「可见性走关联表」。这是**现状** home,措辞准确;英文侧同步、i18n 双侧哈希在 `.i18n.yaml` 重录,符合 `docs/i18n/README.md` 的配对规则。 - Note(`.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.md`):Problem/Decision/Alternatives/Consequences 四段完整,拒绝了「复制公共 case」「读路径兜底 `workspace_id OR 关联`」「SQL 解析 JSON」「物化 label 字典」「追溯改旧 run」五种替代方案,取舍写得清楚。**但它没有写 D2/D3 的存量迁移边界**:Consequences 只说「迁移按 `WHERE workspace_id IS NOT NULL` 回填 legacy_owner」,没有说存量 `catalog_label` 不会被补、游标不会回退。 - 设计 17:§1 明确「当前游标只能看到新 ID」「不推断缺失 label」「不建 label 字典」;§2.2/§2.3 定义三态与投影;§4.3 写「新增规则补齐历史数据」——与 D2 的存量现实有张力,建议补一句「只对已投影 `catalog_label` 的行生效」。 -- flow issue `bugfix-58`:`in-progress`,scope 覆盖 `apps/api/**`、`apps/web/**`、`packages/contracts/**`、`tests/**`、`plans/**`、`.agents/**`、`docs/**`,与改动面一致;撞号修复把 `bugfix-bad-case-sync-type-title` 从 56 改成 59,`bugfix-56`(explicit-skill-conclusion)置 done,符合 #588 已合并的事实。 +- flow issue `bugfix-60`:`in-progress`,scope 覆盖 `apps/api/**`、`apps/web/**`、`packages/contracts/**`、`tests/**`、`plans/**`、`.agents/**`、`docs/**`,与改动面一致;撞号修复把 `bugfix-bad-case-sync-type-title` 从 56 改成 61,`bugfix-58`(explicit-skill-conclusion,main 重编号)置 done,符合 #588 已合并的事实。 - ER 图 `plans/db-relationship-diagram.md`:新增两张表、`catalog_label/catalog_synced` 两个字段、值引用表与可见性链路说明(`74-90`),与代码一致;它明确写了 `bad_cases.workspace_id` 在 #582 后「仅冲突检测」,准确。 - V2 原型:新增页签、chips、空态、dirty、保存 toast 与 `bad-case-labels` 的只读可见性;与真实组件的一个小差异是原型在添加时 `trim()` 输入(空白被静默去掉),真实组件是报错「首尾不能有空白」(设计 §7 要求提示)。原型是设计产物,不阻塞代码,但下次同步时可以对齐。 From 6811e32cfc752c4e5841885ccdd34454f1806102 Mon Sep 17 00:00:00 2001 From: ZTGolem <354251175+ZTGolem@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:16:47 +0800 Subject: [PATCH 15/17] chore(flow): close #599 after PR #607 merge (#582) --- .agents/flow/issues/bugfix-edit-insert-anchor-multiline.en.md | 2 +- .../flow/issues/bugfix-edit-insert-anchor-multiline.i18n.yaml | 4 ++-- .agents/flow/issues/bugfix-edit-insert-anchor-multiline.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) 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..7b38185a 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: in-progress +status: done scope: - apps/api/app/third_party_api/ai_agent/edits.py - apps/api/app/service/evolution/patch_source.py 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..ac9375a9 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: f600bee4f272ea9a95b74388146e38d96df7ead7 +bugfix-edit-insert-anchor-multiline.en.md: 7b38185aeb7253e731ad911bfb750389169d3a8f diff --git a/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.md b/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.md index 00d6a2d2..f600bee4 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: in-progress +status: done scope: - apps/api/app/third_party_api/ai_agent/edits.py - apps/api/app/service/evolution/patch_source.py From feb88d4de66608112cd8d10445c15a383b11a816 Mon Sep 17 00:00:00 2001 From: ZTGolem <354251175+ZTGolem@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:40:48 +0800 Subject: [PATCH 16/17] chore(flow): close #600 after PR #606 merge (#582) --- .agents/flow/issues/bugfix-bad-case-sync-type-title.en.md | 2 +- .agents/flow/issues/bugfix-bad-case-sync-type-title.i18n.yaml | 4 ++-- .agents/flow/issues/bugfix-bad-case-sync-type-title.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.agents/flow/issues/bugfix-bad-case-sync-type-title.en.md b/.agents/flow/issues/bugfix-bad-case-sync-type-title.en.md index 77b269e5..c4945429 100644 --- a/.agents/flow/issues/bugfix-bad-case-sync-type-title.en.md +++ b/.agents/flow/issues/bugfix-bad-case-sync-type-title.en.md @@ -10,7 +10,7 @@ depends: - m6-16 - m6-17 priority: P2 -status: ready +status: done scope: - .agents/flow/issues/bugfix-bad-case-sync-type-title* - .agents/flow/issues/bugfix-edit-insert-anchor-multiline* diff --git a/.agents/flow/issues/bugfix-bad-case-sync-type-title.i18n.yaml b/.agents/flow/issues/bugfix-bad-case-sync-type-title.i18n.yaml index ce484155..94d0e1a4 100644 --- a/.agents/flow/issues/bugfix-bad-case-sync-type-title.i18n.yaml +++ b/.agents/flow/issues/bugfix-bad-case-sync-type-title.i18n.yaml @@ -1,5 +1,5 @@ # 双语配对一致性记录(docs/i18n/README.md):两侧在最后一次确认一致状态下的 # git blob hash。两种语言同等权威;编辑任一侧后带上另一侧,然后重录: # pnpm run record:i18n -- .agents/flow/issues/bugfix-bad-case-sync-type-title.md -bugfix-bad-case-sync-type-title.md: c89c968ba75eae267826529f5e184c45e977fb94 -bugfix-bad-case-sync-type-title.en.md: 77b269e586f8ca498a03ceb7f5a9415c2625cf1b +bugfix-bad-case-sync-type-title.md: f2d6e372e117f8f52e8a50178a2421d6afb348fe +bugfix-bad-case-sync-type-title.en.md: c4945429a0c3b7edc4f5f34838b8f656278345f3 diff --git a/.agents/flow/issues/bugfix-bad-case-sync-type-title.md b/.agents/flow/issues/bugfix-bad-case-sync-type-title.md index c89c968b..f2d6e372 100644 --- a/.agents/flow/issues/bugfix-bad-case-sync-type-title.md +++ b/.agents/flow/issues/bugfix-bad-case-sync-type-title.md @@ -10,7 +10,7 @@ depends: - m6-16 - m6-17 priority: P2 -status: ready +status: done scope: - .agents/flow/issues/bugfix-bad-case-sync-type-title* - .agents/flow/issues/bugfix-edit-insert-anchor-multiline* From 78a047eb799bf676568e04125bda4ca8d75b97d9 Mon Sep 17 00:00:00 2001 From: ZTGolem <354251175+ZTGolem@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:20:25 +0800 Subject: [PATCH 17/17] chore(flow): renumber sync-type-title issue after merge queue review (#582) --- .agents/flow/issues/bugfix-bad-case-sync-type-title.en.md | 2 +- .../flow/issues/bugfix-bad-case-sync-type-title.i18n.yaml | 4 ++-- .agents/flow/issues/bugfix-bad-case-sync-type-title.md | 2 +- plans/2026-11-25-pr597-review.md | 6 +++--- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.agents/flow/issues/bugfix-bad-case-sync-type-title.en.md b/.agents/flow/issues/bugfix-bad-case-sync-type-title.en.md index c4945429..27a9346c 100644 --- a/.agents/flow/issues/bugfix-bad-case-sync-type-title.en.md +++ b/.agents/flow/issues/bugfix-bad-case-sync-type-title.en.md @@ -4,7 +4,7 @@ English | [中文](bugfix-bad-case-sync-type-title.md) ```yaml flow kind: issue -id: bugfix-61 +id: bugfix-62 milestone: bugfix depends: - m6-16 diff --git a/.agents/flow/issues/bugfix-bad-case-sync-type-title.i18n.yaml b/.agents/flow/issues/bugfix-bad-case-sync-type-title.i18n.yaml index 94d0e1a4..45887650 100644 --- a/.agents/flow/issues/bugfix-bad-case-sync-type-title.i18n.yaml +++ b/.agents/flow/issues/bugfix-bad-case-sync-type-title.i18n.yaml @@ -1,5 +1,5 @@ # 双语配对一致性记录(docs/i18n/README.md):两侧在最后一次确认一致状态下的 # git blob hash。两种语言同等权威;编辑任一侧后带上另一侧,然后重录: # pnpm run record:i18n -- .agents/flow/issues/bugfix-bad-case-sync-type-title.md -bugfix-bad-case-sync-type-title.md: f2d6e372e117f8f52e8a50178a2421d6afb348fe -bugfix-bad-case-sync-type-title.en.md: c4945429a0c3b7edc4f5f34838b8f656278345f3 +bugfix-bad-case-sync-type-title.md: 09606d9e0bdaa0100dadb8e496a96875ad2cabd8 +bugfix-bad-case-sync-type-title.en.md: 27a9346cd31ef1f30da746d6084960034df5da43 diff --git a/.agents/flow/issues/bugfix-bad-case-sync-type-title.md b/.agents/flow/issues/bugfix-bad-case-sync-type-title.md index f2d6e372..09606d9e 100644 --- a/.agents/flow/issues/bugfix-bad-case-sync-type-title.md +++ b/.agents/flow/issues/bugfix-bad-case-sync-type-title.md @@ -4,7 +4,7 @@ ```yaml flow kind: issue -id: bugfix-61 +id: bugfix-62 milestone: bugfix depends: - m6-16 diff --git a/plans/2026-11-25-pr597-review.md b/plans/2026-11-25-pr597-review.md index eaf3e103..8ee0c862 100644 --- a/plans/2026-11-25-pr597-review.md +++ b/plans/2026-11-25-pr597-review.md @@ -70,7 +70,7 @@ | `.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.{md,en.md,i18n.yaml}` | A ×3 | owning Note 三件套:Problem / Decision / Alternatives / Consequences | | `.agents/flow/issues/bugfix-evolution-label-allowlist.{md,en.md,i18n.yaml}` | A ×3 | #582 的 flow issue:`in-progress`,scope 覆盖 apps/web/contracts/tests/plans/.agents/docs | | `.agents/flow/issues/bugfix-explicit-skill-conclusion.{md,en.md,i18n.yaml}` | M ×3 | `bugfix-56` 置 `done`(#588 已合并) | -| `.agents/flow/issues/bugfix-bad-case-sync-type-title.{md,en.md,i18n.yaml}` | M ×3 | 撞号修复:`bugfix-56 → bugfix-61` | +| `.agents/flow/issues/bugfix-bad-case-sync-type-title.{md,en.md,i18n.yaml}` | M ×3 | 撞号修复:`bugfix-56 → bugfix-62` | | `docs/architecture.{md,en.md,i18n.yaml}` | M ×3 | 数据层策略一句:空间表补两张新表、可见性走关联;i18n 双哈希重录 | | `plans/fullstack-design/17-workspace-bad-case-label-routing.md` | A | 设计正文:目标/数据模型/label 契约/写入重算/读边界/API/UI/验证 | | `plans/fullstack-design/README.md` | M | 设计索引加第 17 篇;D21 决策改写为「可见性单元」并加 2026-11-24 修订 | @@ -418,7 +418,7 @@ FastAPI 模型是契约源:`WorkspaceBadCaseLabelRequest` 的 items 有 `defau - 实现计划:`plans/superpowers/plans/2026-11-24-issue-582-badcase-label-routing.md` - 数据模型图:`plans/db-relationship-diagram.md`(PDF 同目录) - 相关常驻文档:`docs/architecture.md:36`(英文 `.en.md:36`;i18n `.i18n.yaml`) -- 相关流程记录:`.agents/flow/issues/bugfix-evolution-label-allowlist.md`(`bugfix-58 → done`,main 重编号;`bugfix-56 → bugfix-61` 撞号修复) +- 相关流程记录:`.agents/flow/issues/bugfix-evolution-label-allowlist.md`(`bugfix-58 → done`,main 重编号;`bugfix-56 → bugfix-62` 撞号修复) - 后续:合并后按流程提交闭环 PR,把 `bugfix-60` 置 `done` 并关闭 #582 ## §9 文件级代码分析 @@ -988,7 +988,7 @@ export type WorkspaceBadCaseLabelRequest = components["schemas"]["WorkspaceBadCa - `docs/architecture.md:36` / `.en.md:36`:只改一句,把两张新表加入空间表清单并说明「可见性走关联表」。这是**现状** home,措辞准确;英文侧同步、i18n 双侧哈希在 `.i18n.yaml` 重录,符合 `docs/i18n/README.md` 的配对规则。 - Note(`.agents/notes/implemented/feature/2026-11-24-workspace-bad-case-label-routing.md`):Problem/Decision/Alternatives/Consequences 四段完整,拒绝了「复制公共 case」「读路径兜底 `workspace_id OR 关联`」「SQL 解析 JSON」「物化 label 字典」「追溯改旧 run」五种替代方案,取舍写得清楚。**但它没有写 D2/D3 的存量迁移边界**:Consequences 只说「迁移按 `WHERE workspace_id IS NOT NULL` 回填 legacy_owner」,没有说存量 `catalog_label` 不会被补、游标不会回退。 - 设计 17:§1 明确「当前游标只能看到新 ID」「不推断缺失 label」「不建 label 字典」;§2.2/§2.3 定义三态与投影;§4.3 写「新增规则补齐历史数据」——与 D2 的存量现实有张力,建议补一句「只对已投影 `catalog_label` 的行生效」。 -- flow issue `bugfix-60`:`in-progress`,scope 覆盖 `apps/api/**`、`apps/web/**`、`packages/contracts/**`、`tests/**`、`plans/**`、`.agents/**`、`docs/**`,与改动面一致;撞号修复把 `bugfix-bad-case-sync-type-title` 从 56 改成 61,`bugfix-58`(explicit-skill-conclusion,main 重编号)置 done,符合 #588 已合并的事实。 +- flow issue `bugfix-60`:`in-progress`,scope 覆盖 `apps/api/**`、`apps/web/**`、`packages/contracts/**`、`tests/**`、`plans/**`、`.agents/**`、`docs/**`,与改动面一致;撞号修复把 `bugfix-bad-case-sync-type-title` 从 56 改成 62,`bugfix-58`(explicit-skill-conclusion,main 重编号)置 done,符合 #588 已合并的事实。 - ER 图 `plans/db-relationship-diagram.md`:新增两张表、`catalog_label/catalog_synced` 两个字段、值引用表与可见性链路说明(`74-90`),与代码一致;它明确写了 `bad_cases.workspace_id` 在 #582 后「仅冲突检测」,准确。 - V2 原型:新增页签、chips、空态、dirty、保存 toast 与 `bad-case-labels` 的只读可见性;与真实组件的一个小差异是原型在添加时 `trim()` 输入(空白被静默去掉),真实组件是报错「首尾不能有空白」(设计 §7 要求提示)。原型是设计产物,不阻塞代码,但下次同步时可以对齐。