相对第一版 46fc976 的完整变更。组员迁移对照表见 docs/20。
一、对外契约对齐 docs/05(破坏性,共 4 处,组员需按 docs/20 调整)
1) 配置发布端点改为文档规定的复数资源名:submit→validations、
approve→reviews(需 body decision)、activate→activations、
rollback→rollbacks;第一版这 4 个动词式路径 docs/05 从未定义过。
2) 错误码由 8 个笼统码改为 15 个具体语义码(FORBIDDEN→AGENT_PERMISSION_DENIED、
UNAUTHORIZED→AUTHENTICATION_REQUIRED、CONFLICT→RESOURCE_VERSION_CONFLICT、
RESOURCE_NOT_FOUND→RUN_NOT_FOUND/SESSION_NOT_FOUND 等),
输入类错误状态码 400→422。
3) POST /api/v1/agent-runs 与 GET /api/v1/agent-runs/{run_id} 统一为
{data, meta} 信封(data 内字段名与语义未变)。
4) 错误响应体统一为 {error:{code,message,retryable,field_errors}, meta:{trace_id}},
不再返回 FastAPI 默认的 {"detail": ...}。
二、数据库基线与约束
新增 39 张表的基线迁移(链根)与联合唯一键纠偏(4 张表、删 8 增 4,幂等收敛);
撤下 config_release 的双人复核 CHECK(应用层已允许自审,审核节点保留,
自审如实写入 reviewer_id);记忆 active key 生成列与唯一键;
activate 开始记录 supersedes_release_id 使版本链可追溯。
docs/00 基线未修改,未重命名或删除任何表与字段。
三、修复会静默出错或无报错的缺陷
- 跑完集成测试后平台会静默失去生效配置:清理只删自己创建的版本,却没有恢复被它
顶成 superseded 的原生效版本,且审计一并删除因而完全无痕,表现为所有工具被拒
但没有任何报错。已修清理逻辑并加恢复。
- Worker 单轮异常导致进程退出;记忆抽取调用方的“事务已开始”异常;
召回缓存丢失 degraded 标记;连接时区未生效导致 created_at/updated_at 差 8 小时;
.env 与 os.getenv 密钥来源分裂导致“没有可用的已批准模型端点”。
- 记忆信号识别漏判与跨键误命中;SSE 未带 Accept 的协商行为。
四、功能补齐
记忆链路 P1/P2/P3(抽取、受控词表、召回与缓存、生命周期级联及投影事件)、
fin_* 场内交易只读 ORM 层、agent_intent_config 状态流转并在运行期真正生效、
限流(Redis 固定窗口、故障一律放行)、游标校验、trace_id 中间件、
示例业务 Agent fund_query_demo 与一键端到端验证脚本,以及审计/指纹/迁移状态工具。
五、文档与验证
新增 docs/19(业务 Agent 接入实操)、docs/20(第一版迁移指南)与 docs/evidence 证据;
docs/01/02/06/08/09/17 同步实现现状。
验证结果:ruff 通过、mypy 103 文件无错、unit+contract 447 passed、
integration 29 passed、acceptance_check --production 7 PASS、
demo_agent_e2e 9/9 PASS(含失败关闭反证)。
133 lines
6.3 KiB
Python
133 lines
6.3 KiB
Python
from typing import Any
|
|
|
|
from fastapi import APIRouter, Depends, Header, Path, Query, Response
|
|
from pydantic import BaseModel
|
|
|
|
from app.api.dependencies.auth import build_request_context
|
|
from app.api.dependencies.rate_limit import enforce_rate_limit
|
|
from app.api.schemas.admin import (
|
|
EmptyPayload,
|
|
EndpointPayload,
|
|
IntentPayload,
|
|
ItemPayload,
|
|
NegativePayload,
|
|
PromptPayload,
|
|
ReleasePayload,
|
|
ReplyPayload,
|
|
ReviewPayload,
|
|
RoutingPayload,
|
|
)
|
|
from app.core.contracts import RequestContext
|
|
from app.service.admin_service import AdminService
|
|
|
|
router = APIRouter(prefix="/api/v1/admin", tags=["platform-admin"],
|
|
dependencies=[Depends(enforce_rate_limit)])
|
|
|
|
|
|
def register_resource(
|
|
resource: str, schema: type[BaseModel], id_name: str, *, scoped: bool = False,
|
|
update: bool = True, detail: bool = True,
|
|
) -> None:
|
|
prefix = f"/config-releases/{{release_id}}/{resource}" if scoped else f"/{resource}"
|
|
|
|
async def create(
|
|
payload: BaseModel, response: Response, release_id: int | None = None,
|
|
context: RequestContext = Depends(build_request_context), # noqa: B008
|
|
key: str | None = Header(default=None, alias="Idempotency-Key"),
|
|
) -> dict[str, Any]:
|
|
result = await AdminService().mutate(resource, context, payload.model_dump(mode="json"),
|
|
key, None, release_id=release_id)
|
|
response.headers["ETag"] = f'"{result["meta"]["etag"]}"'
|
|
return result
|
|
|
|
create.__annotations__["payload"] = schema
|
|
router.add_api_route(prefix, create, methods=["POST"], status_code=201,
|
|
operation_id=f"create_{resource}")
|
|
|
|
async def list_rows(
|
|
release_id: int | None = None, limit: int = Query(default=20, ge=1, le=100),
|
|
cursor: str | None = Query(default=None),
|
|
context: RequestContext = Depends(build_request_context), # noqa: B008
|
|
) -> dict[str, Any]:
|
|
"""列表查询(文档 §3.8 统一游标)。游标校验在 Service 的权限闸门之后进行。"""
|
|
return await AdminService().query(
|
|
resource, context, release_id=release_id, limit=limit, cursor=cursor
|
|
)
|
|
|
|
router.add_api_route(prefix, list_rows, methods=["GET"], operation_id=f"list_{resource}")
|
|
|
|
async def get(
|
|
response: Response, row_id: int = Path(alias=id_name, gt=0),
|
|
context: RequestContext = Depends(build_request_context), # noqa: B008
|
|
) -> dict[str, Any]:
|
|
result = await AdminService().query(resource, context, row_id=row_id)
|
|
response.headers["ETag"] = f'"{result["meta"]["etag"]}"'
|
|
return result
|
|
|
|
if detail:
|
|
router.add_api_route(f"{prefix}/{{{id_name}}}", get, methods=["GET"],
|
|
operation_id=f"get_{resource}")
|
|
|
|
async def put(
|
|
payload: BaseModel, response: Response, row_id: int = Path(alias=id_name, gt=0),
|
|
release_id: int | None = None,
|
|
context: RequestContext = Depends(build_request_context), # noqa: B008
|
|
key: str | None = Header(default=None, alias="Idempotency-Key"),
|
|
if_match: str | None = Header(default=None, alias="If-Match"),
|
|
) -> dict[str, Any]:
|
|
result = await AdminService().mutate(resource, context, payload.model_dump(mode="json"),
|
|
key, if_match, row_id=row_id, release_id=release_id)
|
|
response.headers["ETag"] = f'"{result["meta"]["etag"]}"'
|
|
return result
|
|
|
|
put.__annotations__["payload"] = schema
|
|
if update:
|
|
router.add_api_route(f"{prefix}/{{{id_name}}}", put, methods=["PUT"],
|
|
operation_id=f"update_{resource}")
|
|
|
|
|
|
def register_transition(resource: str, id_name: str, action: str) -> None:
|
|
async def transition(
|
|
payload: BaseModel, response: Response, row_id: int = Path(alias=id_name, gt=0),
|
|
context: RequestContext = Depends(build_request_context), # noqa: B008
|
|
key: str | None = Header(default=None, alias="Idempotency-Key"),
|
|
if_match: str | None = Header(default=None, alias="If-Match"),
|
|
) -> dict[str, Any]:
|
|
result = await AdminService().mutate(resource, context, payload.model_dump(mode="json"),
|
|
key, if_match, row_id=row_id, action=action)
|
|
response.headers["ETag"] = f'"{result["meta"]["etag"]}"'
|
|
return result
|
|
|
|
transition.__annotations__["payload"] = ReviewPayload if action == "reviews" else EmptyPayload
|
|
router.add_api_route(f"/{resource}/{{{id_name}}}/{action}", transition, methods=["POST"],
|
|
status_code=201 if action == "rollbacks" else 200,
|
|
operation_id=f"{action}_{resource}")
|
|
|
|
|
|
register_resource("config-releases", ReleasePayload, "release_id", update=False)
|
|
register_resource("platform-config-items", ItemPayload, "item_id", scoped=True, detail=False)
|
|
register_resource("model-endpoints", EndpointPayload, "endpoint_id")
|
|
register_resource("model-routing-rules", RoutingPayload, "rule_id", scoped=True, detail=False)
|
|
register_resource("prompt-templates", PromptPayload, "prompt_id", update=False)
|
|
register_resource("agent-intent-configs", IntentPayload, "config_id")
|
|
register_resource("reply-templates", ReplyPayload, "template_id", detail=False)
|
|
register_resource("negative-word-rules", NegativePayload, "rule_id", detail=False)
|
|
for action in ("validations", "reviews", "activations", "rollbacks"):
|
|
register_transition("config-releases", "release_id", action)
|
|
for action in ("reviews", "activations", "disablements"):
|
|
register_transition("model-endpoints", "endpoint_id", action)
|
|
# 意图配置沿用同一套"审核 → 生效 → 归档"流转;归档落 `archived`
|
|
# (该表 CHECK 约束只允许 draft/approved/active/archived,没有 disabled)。
|
|
for action in ("reviews", "activations", "archivals"):
|
|
register_transition("agent-intent-configs", "config_id", action)
|
|
|
|
|
|
@router.get("/audit-records")
|
|
async def audit_records(
|
|
limit: int = Query(default=20, ge=1, le=100),
|
|
cursor: str | None = Query(default=None),
|
|
context: RequestContext = Depends(build_request_context), # noqa: B008
|
|
) -> dict[str, Any]:
|
|
"""审计查询(文档 §9.6 支持游标过滤)。游标非法时返回 `400 INVALID_CURSOR`。"""
|
|
return await AdminService().query("audit-records", context, limit=limit, cursor=cursor)
|