From 277982ead34ec143352679947ef54cba84e6da32 Mon Sep 17 00:00:00 2001 From: ThearchyHelios Date: Thu, 15 Oct 2026 12:09:29 +0800 Subject: [PATCH] =?UTF-8?q?=E6=99=AE=E9=80=9A=E7=94=A8=E6=88=B7=E5=BB=BA?= =?UTF-8?q?=E5=BA=94=E7=94=A8=EF=BC=88=E5=90=8E=E7=AB=AF=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=20-=20=E8=93=9D=E5=9B=BE=EF=BC=9Abp=5F*=20=E6=93=8D=E4=BD=9C?= =?UTF-8?q?=E5=92=8C=E9=80=90=E5=8D=A1=E7=99=BD=E5=90=8D=E5=8D=95=E3=80=81?= =?UTF-8?q?=E8=93=9D=E5=9B=BE=E6=A3=80=E6=9F=A5=E3=80=81=E7=95=99=E7=97=95?= =?UTF-8?q?=E3=80=81=E6=8C=89=E8=93=9D=E5=9B=BE=E5=88=A4=E6=9D=83=E9=99=90?= =?UTF-8?q?=EF=BC=9B=E4=BA=94=E4=B8=AA=E5=9C=BA=E6=99=AF=E6=A8=A1=E6=9D=BF?= =?UTF-8?q?=E5=8A=A0=E8=87=AA=E7=94=B1=E5=BD=A2=EF=BC=88=E9=AA=A8=E6=9E=B6?= =?UTF-8?q?=E3=80=81=E5=85=B3=E8=8A=82=E3=80=81=E5=BA=94=E7=94=A8=E9=AA=A8?= =?UTF-8?q?=E6=9E=B6=E3=80=81=E5=AE=9A=E6=97=B6=E4=BB=BB=E5=8A=A1=EF=BC=89?= =?UTF-8?q?=EF=BC=8C=E5=AE=9E=E4=BE=8B=E5=8C=96=E4=B8=8E=E9=AA=A8=E6=9E=B6?= =?UTF-8?q?=E6=AF=94=E5=AF=B9=EF=BC=9BBlueprintApplier=20/=20TemplateAppli?= =?UTF-8?q?er=EF=BC=88=E5=8F=AA=E6=94=B6=E6=A8=A1=E6=9D=BF=E5=A3=B0?= =?UTF-8?q?=E6=98=8E=E8=BF=87=E7=9A=84=E5=85=B3=E8=8A=82=EF=BC=89=E4=B8=8E?= =?UTF-8?q?=E8=87=AA=E6=9F=A5=EF=BC=9Blook=20=E6=96=B0=E7=B1=BB=E5=88=AB?= =?UTF-8?q?=E5=8F=A3=E5=BE=84=E5=8D=A1=EF=BC=9B=E8=93=9D=E5=9B=BE=E5=AF=B9?= =?UTF-8?q?=E8=AF=9D=E5=92=8C=E5=A1=AB=E5=85=B3=E8=8A=82=E4=B8=A4=E4=B8=AA?= =?UTF-8?q?=E6=B5=81=E5=BC=8F=E6=8E=A5=E5=8F=A3=EF=BC=8C=E4=B8=8D=E5=90=8C?= =?UTF-8?q?=E7=BB=84=E7=9A=84=E5=85=B3=E8=8A=82=E5=B9=B6=E8=A1=8C=E5=A1=AB?= =?UTF-8?q?=E3=80=81=E5=87=BA=E9=94=99=E7=9A=84=E7=BB=84=E4=B8=B2=E8=A1=8C?= =?UTF-8?q?=E9=87=8D=E8=AF=95=EF=BC=9B=E6=A8=A1=E6=9D=BF=E5=88=97=E8=A1=A8?= =?UTF-8?q?=20-=20=E8=AF=95=E8=BF=90=E8=A1=8C=E4=B8=8E=E5=8F=91=E5=B8=83?= =?UTF-8?q?=E5=8D=95=EF=BC=9A=E5=9B=9B=E7=A7=8D=E8=B5=B7=E7=82=B9=EF=BC=88?= =?UTF-8?q?=E5=AF=B9=E8=AF=9D=E3=80=81=E6=A8=A1=E6=9D=BF=E3=80=81=E9=97=AE?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E7=9A=84=E4=B8=80=E8=BD=AE=E3=80=81=E5=B7=B2?= =?UTF-8?q?=E5=8F=91=E5=B8=83=E7=89=88=E6=9C=AC=EF=BC=89=EF=BC=9B=E8=AF=95?= =?UTF-8?q?=E8=BF=90=E8=A1=8C=E6=98=AF=E6=8E=A2=E7=B4=A2=E8=BF=90=E8=A1=8C?= =?UTF-8?q?=EF=BC=8C=E8=8D=89=E7=A8=BF=E5=BA=94=E7=94=A8=E6=8C=89=E8=BF=99?= =?UTF-8?q?=E6=AC=A1=E8=BF=90=E8=A1=8C=E8=A7=A3=E6=9E=90=E3=80=81=E5=8D=B0?= =?UTF-8?q?=E7=AB=A0=E5=86=99=E8=AF=95=E8=BF=90=E8=A1=8C=EF=BC=8C=E6=B5=81?= =?UTF-8?q?=E7=A8=8B=E7=B1=BB=E6=B4=BE=E7=BB=99=E8=87=AA=E5=B7=B1=E3=80=81?= =?UTF-8?q?=E4=B8=8D=E8=A7=A6=E5=8F=91=E5=8D=87=E7=BA=A7=EF=BC=9B=E5=8F=91?= =?UTF-8?q?=E5=B8=83=E5=8D=95=E4=B9=9D=E6=AD=A5=E3=80=81=E9=A2=84=E6=A3=80?= =?UTF-8?q?=E5=8F=AA=E8=AF=BB=E3=80=81=E6=AF=8F=E6=AD=A5=E7=95=99=E7=97=95?= =?UTF-8?q?=E3=80=81=E5=81=9C=E4=B8=8B=E5=90=8E=E6=8E=A5=E7=9D=80=E5=81=9A?= =?UTF-8?q?=E3=80=81=E6=A0=B8=E5=AF=B9=E5=8D=A1=E7=89=87=E6=8C=87=E7=BA=B9?= =?UTF-8?q?=E5=92=8C=E5=BA=94=E7=94=A8=E7=AE=A1=E7=90=86=E6=9D=83=E3=80=81?= =?UTF-8?q?=E5=90=AF=E5=8A=A8=E6=97=B6=E6=95=B4=E7=90=86=E4=B8=AD=E6=96=AD?= =?UTF-8?q?=E7=9A=84=E5=8D=95=EF=BC=9B=E7=99=BD=E8=AF=9D=E5=B1=82=E8=A6=86?= =?UTF-8?q?=E7=9B=96=E5=85=A8=E9=83=A8=E9=97=AE=E9=A2=98=E7=BC=96=E5=8F=B7?= =?UTF-8?q?=20-=20=E8=AE=B0=E5=BD=95=E8=A1=A8=E4=B8=8E=E6=96=87=E4=BB=B6?= =?UTF-8?q?=EF=BC=9A=E5=B9=B3=E5=8F=B0=E6=89=98=E7=AE=A1=E5=8F=AA=E8=BF=BD?= =?UTF-8?q?=E5=8A=A0=E7=9A=84=E8=AE=B0=E5=BD=95=E8=A1=A8=E3=80=81=E6=8C=89?= =?UTF-8?q?=E9=AB=98=E6=B0=B4=E4=BD=8D=E5=9B=BA=E5=AE=9A=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E3=80=81=E8=BF=9E=E6=8E=A5=E4=B8=8A=E7=9A=84=E4=B8=B4=E6=97=B6?= =?UTF-8?q?=E8=A7=86=E5=9B=BE=E5=81=9A=E8=A1=8C=E7=BA=A7=E5=8F=AF=E8=A7=81?= =?UTF-8?q?=E3=80=81=E5=86=99=E5=85=A5=E8=B5=B0=E5=8A=A8=E4=BD=9C=EF=BC=88?= =?UTF-8?q?records=5Fappend=EF=BC=89=E3=80=81=E8=A1=A8=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E5=9C=A8=E5=8F=91=E5=B8=83=E6=97=B6=E5=88=87=E6=8D=A2=E3=80=81?= =?UTF-8?q?=E8=8D=89=E7=A8=BF=E4=B8=8D=E5=BD=B1=E5=93=8D=E7=BA=BF=E4=B8=8A?= =?UTF-8?q?=E3=80=81=E8=AE=B0=E5=BD=95=E5=88=97=E8=A1=A8=E9=81=AE=E6=95=8F?= =?UTF-8?q?=E6=84=9F=E5=88=97=EF=BC=9B=E6=96=87=E4=BB=B6=E6=8C=89=E5=93=88?= =?UTF-8?q?=E5=B8=8C=E5=AD=98=E3=80=81=E4=B8=A4=E6=AD=A5=E4=B8=8A=E4=BC=A0?= =?UTF-8?q?=E3=80=81=E6=8F=90=E4=BA=A4=E6=97=B6=E7=BB=91=E5=AE=9A=E8=BF=90?= =?UTF-8?q?=E8=A1=8C=E3=80=81=E4=B8=8B=E8=BD=BD=E6=8C=89=E8=AF=BB=E6=9D=83?= =?UTF-8?q?=E9=99=90=E3=80=81=E6=B8=85=E7=90=86=E3=80=81file=5Ftext?= =?UTF-8?q?=E3=80=81=E6=8C=89=E9=85=8D=E6=96=B9=E5=AF=BC=E5=85=A5=E4=B8=80?= =?UTF-8?q?=E6=9C=9F=EF=BC=88table=5Fimport=5Fperiod=EF=BC=89=20-=20?= =?UTF-8?q?=E4=B8=AA=E4=BA=BA=E5=BA=94=E7=94=A8=EF=BC=9A=E5=AD=98=E6=88=90?= =?UTF-8?q?=E4=B8=AA=E4=BA=BA=E5=BA=94=E7=94=A8=EF=BC=88=E9=97=AE=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E7=9A=84=E7=BA=A6=E6=9D=9F=EF=BC=89=E3=80=81=E5=88=B7?= =?UTF-8?q?=E6=96=B0=EF=BC=88=E9=81=AE=E7=BD=A9=E3=80=81=E5=8F=AA=E8=AF=BB?= =?UTF-8?q?=E3=80=81=E6=AF=8F=E6=97=A5=E4=B8=8A=E9=99=90=EF=BC=89=E3=80=81?= =?UTF-8?q?=E5=8F=AA=E6=9C=89=E6=8B=A5=E6=9C=89=E8=80=85=E7=9C=8B=E5=BE=97?= =?UTF-8?q?=E8=A7=81=E3=80=81=E6=8F=90=E4=BA=A4=E5=AE=A1=E6=A0=B8=E4=B8=8E?= =?UTF-8?q?=E5=85=B1=E4=BA=AB=E5=89=AF=E6=9C=AC=E3=80=81=E5=BC=80=E5=85=B3?= =?UTF-8?q?=E4=B8=8B=E5=8F=91=E5=88=B0=E8=AE=A4=E4=BA=BA=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=EF=BC=9B=E9=A1=B5=E9=9D=A2=E7=BC=96=E8=BE=91=E7=9A=84=E5=80=99?= =?UTF-8?q?=E9=80=89=EF=BC=9B=E9=9A=90=E8=97=8F=E7=BB=84=E4=BB=B6=E4=B8=8D?= =?UTF-8?q?=E4=B8=8B=E5=8F=91=EF=BC=9B=E4=B8=89=E6=9D=A1=E6=96=B0=E6=A3=80?= =?UTF-8?q?=E6=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/api/apps.py | 179 +++- backend/app/api/auth.py | 18 +- backend/app/api/blueprints.py | 457 +++++++- backend/app/api/conversations.py | 25 +- backend/app/api/copilot.py | 169 ++- backend/app/api/copilot_blueprint.py | 539 +++++++++- backend/app/api/copilot_gen.py | 24 +- backend/app/api/datasources.py | 31 +- backend/app/api/files.py | 100 +- backend/app/api/personal.py | 168 ++- backend/app/api/schedules.py | 82 +- backend/app/api/settings.py | 24 +- backend/app/api/templates.py | 27 +- backend/app/api/workflows.py | 73 +- backend/app/apps/access.py | 23 + backend/app/apps/candidates.py | 66 ++ backend/app/apps/catalog.py | 23 +- backend/app/apps/derive.py | 132 ++- backend/app/apps/entries.py | 34 +- backend/app/apps/forms.py | 83 +- backend/app/apps/lint.py | 135 ++- backend/app/apps/ops.py | 10 +- backend/app/apps/pins.py | 28 +- backend/app/apps/resolve.py | 239 ++++- backend/app/auth/access.py | 12 + backend/app/auth/chat_policy.py | 17 +- backend/app/blueprints/generation.py | 378 +++++++ backend/app/blueprints/instantiate.py | 308 +++++- backend/app/blueprints/ops.py | 813 +++++++++++++- backend/app/blueprints/personal.py | 702 ++++++++++++- backend/app/blueprints/publish_plan.py | 993 +++++++++++++++++- backend/app/blueprints/store.py | 292 +++++ backend/app/blueprints/templates/__init__.py | 2 + backend/app/blueprints/templates/_common.py | 820 +++++++++++++++ backend/app/blueprints/templates/approval.py | 113 ++ .../templates/exception_handling.py | 181 ++++ backend/app/blueprints/templates/freeform.py | 110 ++ .../blueprints/templates/periodic_board.py | 127 +++ .../templates/reconcile_writeback.py | 202 ++++ backend/app/blueprints/templates/records.py | 213 ++++ backend/app/blueprints/trial.py | 355 ++++++- backend/app/capabilities/platform.py | 73 ++ backend/app/capabilities/registry.py | 33 +- backend/app/data/engine.py | 16 + backend/app/data/guard.py | 36 + backend/app/data/raw_store.py | 8 +- backend/app/data/table_versions.py | 8 +- backend/app/engine/compiler.py | 5 +- backend/app/engine/expressions.py | 110 +- backend/app/engine/inquiry.py | 3 +- backend/app/engine/launch.py | 6 +- backend/app/engine/runner.py | 18 +- backend/app/engine/variables.py | 7 +- backend/app/files/__init__.py | 3 +- backend/app/files/imports.py | 90 ++ backend/app/files/store.py | 550 ++++++++++ backend/app/files/text.py | 174 +++ backend/app/look/base.py | 4 +- backend/app/look/calibers.py | 306 ++++++ backend/app/main.py | 8 + backend/app/memory/parsing.py | 48 +- backend/app/notify/service.py | 30 +- backend/app/plain.py | 358 ++++++- backend/app/process/actions.py | 12 +- backend/app/process/tasks.py | 131 ++- backend/app/records/__init__.py | 4 +- backend/app/records/access.py | 72 ++ backend/app/records/actions.py | 162 +++ backend/app/records/listing.py | 107 ++ backend/app/records/store.py | 482 +++++++++ backend/app/records/tables.py | 409 ++++++++ backend/app/records/views.py | 145 +++ backend/app/scheduler/loop.py | 7 +- backend/app/tools/builtin/__init__.py | 4 +- backend/app/tools/builtin/platform.py | 71 ++ backend/app/tools/datasource.py | 67 ++ backend/app/tools/registry.py | 5 + backend/tests/blueprint_samples.py | 128 +++ backend/tests/test_app_catalog.py | 15 + backend/tests/test_app_spec_tools.py | 22 +- backend/tests/test_blueprint_generation.py | 300 ++++++ backend/tests/test_blueprint_ops.py | 238 +++++ backend/tests/test_blueprint_starts.py | 242 +++++ backend/tests/test_blueprint_template_run.py | 73 ++ backend/tests/test_blueprint_templates.py | 252 +++++ backend/tests/test_blueprint_trial.py | 350 ++++++ .../tests/test_copilot_blueprint_stream.py | 452 ++++++++ backend/tests/test_copilot_look.py | 10 +- backend/tests/test_files.py | 420 ++++++++ backend/tests/test_personal_apps.py | 832 +++++++++++++++ backend/tests/test_plain_layer.py | 151 +++ backend/tests/test_publish_plan.py | 653 ++++++++++++ backend/tests/test_records.py | 672 ++++++++++++ backend/tests/test_settings_apps_auth.py | 23 +- 94 files changed, 16347 insertions(+), 385 deletions(-) create mode 100644 backend/app/apps/candidates.py create mode 100644 backend/app/blueprints/generation.py create mode 100644 backend/app/blueprints/store.py create mode 100644 backend/app/blueprints/templates/_common.py create mode 100644 backend/app/blueprints/templates/approval.py create mode 100644 backend/app/blueprints/templates/exception_handling.py create mode 100644 backend/app/blueprints/templates/freeform.py create mode 100644 backend/app/blueprints/templates/periodic_board.py create mode 100644 backend/app/blueprints/templates/reconcile_writeback.py create mode 100644 backend/app/blueprints/templates/records.py create mode 100644 backend/app/capabilities/platform.py create mode 100644 backend/app/files/imports.py create mode 100644 backend/app/files/store.py create mode 100644 backend/app/files/text.py create mode 100644 backend/app/look/calibers.py create mode 100644 backend/app/records/access.py create mode 100644 backend/app/records/actions.py create mode 100644 backend/app/records/listing.py create mode 100644 backend/app/records/store.py create mode 100644 backend/app/records/tables.py create mode 100644 backend/app/records/views.py create mode 100644 backend/app/tools/builtin/platform.py create mode 100644 backend/tests/blueprint_samples.py create mode 100644 backend/tests/test_blueprint_generation.py create mode 100644 backend/tests/test_blueprint_ops.py create mode 100644 backend/tests/test_blueprint_starts.py create mode 100644 backend/tests/test_blueprint_template_run.py create mode 100644 backend/tests/test_blueprint_templates.py create mode 100644 backend/tests/test_blueprint_trial.py create mode 100644 backend/tests/test_copilot_blueprint_stream.py create mode 100644 backend/tests/test_files.py create mode 100644 backend/tests/test_personal_apps.py create mode 100644 backend/tests/test_plain_layer.py create mode 100644 backend/tests/test_publish_plan.py create mode 100644 backend/tests/test_records.py diff --git a/backend/app/api/apps.py b/backend/app/api/apps.py index 4a55b5c5..bd532f5a 100644 --- a/backend/app/api/apps.py +++ b/backend/app/api/apps.py @@ -75,12 +75,27 @@ def _refuse_archived(app: App, what: str) -> None: raise CodedHTTPException(409, f"「{app.name}」已归档,不能再{what}", APP_ARCHIVED) +#: 个人应用(docs/design/normal-user-apps.md N7)没有的那几样:发布、授权 +PERSONAL_ONLY_MINE = "personal.not_shareable" + + +def _refuse_personal(app: App, what: str) -> None: + """个人应用没有应用版本(草稿就是在用的那一份)、不能分享:发布、授权一律不收,说清想给别人用怎么办。""" + if getattr(app, "scope", "shared") == "personal": + raise CodedHTTPException(409, f"「{app.name}」是个人应用,只给你自己用,不能{what}。想给别人用,请提交审核,由搭建者" + "发布成正式应用", PERSONAL_ONLY_MINE) + + def _require_builder(principal: Principal) -> None: if not principal.at_least("builder"): raise CodedHTTPException(403, "搭建应用需要搭建者权限", NO_ACCESS) async def _current_version(session: AsyncSession, app: App) -> AppVersion: + if getattr(app, "scope", "shared") == "personal": + # 个人应用没有发布版本:不发起实例、没有按需视图,页面直接按存的样子显示,要新数点「刷新」 + raise CodedHTTPException(409, f"「{app.name}」是个人应用,不发起实例、没有按需视图:要看最新的数请点「刷新」", + NOT_PUBLISHED) if not app.published_version: raise CodedHTTPException(409, f"「{app.name}」还没有发布", NOT_PUBLISHED) return (await session.execute(select(AppVersion).where( @@ -118,7 +133,17 @@ async def _summary(session: AsyncSession, app: App, principal: Principal, role: "published_version": app.published_version, "level": version.level if version else None, "needs_upgrade": await _needs_upgrade(session, version), "pending_tasks": await _pending(session, app.id, principal), "my_role": role, - "updated_at": app.updated_at.isoformat() if app.updated_at else None} + "updated_at": app.updated_at.isoformat() if app.updated_at else None, + # 个人应用(N7):scope=personal、拥有者;出自哪个蓝图(共享应用经发布单生成的也有) + "scope": app.scope or "shared", "owner": app.owner, "blueprint_id": app.blueprint_id} + + +def _personal_stub(app: App) -> dict[str, Any]: + """管理员在应用列表里看到的别人的个人应用:在不在、谁的、叫什么、状态,能归档;说明、页面、数一概不给(P4)。""" + return {"id": app.id, "name": app.name, "description": "", "icon": "app", "status": app.status, + "published_version": None, "level": None, "needs_upgrade": False, "pending_tasks": 0, "my_role": None, + "updated_at": app.updated_at.isoformat() if app.updated_at else None, + "scope": "personal", "owner": app.owner, "blueprint_id": None} def _published_outline(version: AppVersion | None) -> dict[str, Any] | None: @@ -148,6 +173,12 @@ async def _detail(session: AsyncSession, app: App, principal: Principal, role: s return out out.update(draft=app.draft or empty_spec(app.name), draft_bindings={"slots": {}, **(app.draft_bindings or {})}, created_by=app.created_by) + if app.scope == "personal": + # 个人应用给拥有者的那一块:今天还能刷新几次、蓝图改过没有、审核到哪了(blueprints/personal.personal_state) + from app.blueprints.personal import personal_state + + out["personal"] = await personal_state(session, app, principal) + return out if with_backfill: from app.apps.backfill import backfillable @@ -161,19 +192,35 @@ async def _detail(session: AsyncSession, app: App, principal: Principal, role: s @router.get("") -async def list_apps(include_archived: bool = False, session: AsyncSession = Depends(get_session), +async def list_apps(include_archived: bool = False, scope: str | None = None, + session: AsyncSession = Depends(get_session), x_actor: str | None = Header(default=None)) -> dict[str, Any]: + """应用列表。个人应用只列给拥有者;管理员另外看得到别人的个人应用在不在(_personal_stub,不含内容),能归档。 + scope 给了只列那一种(shared / personal)。can_create 是这个人能建哪种应用:新建应用的入口按它给(共享要搭建者及以上, + 个人看管理员的开关,blueprints/personal.allowed)。""" + from sqlalchemy import or_ + + from app.apps.access import is_personal + from app.blueprints.personal import allowed + principal = _principal(x_actor) query = select(App).order_by(App.updated_at.desc()) if not include_archived: query = query.where(App.status != "archived") + if scope == "personal": + query = query.where(App.scope == "personal") + elif scope == "shared": + query = query.where(or_(App.scope == "shared", App.scope.is_(None))) items = [] for app in (await session.execute(query)).scalars(): role = await app_role(session, principal, app) if role is None: + if is_personal(app) and principal.mode != "off" and principal.role == "admin": + items.append(_personal_stub(app)) continue items.append(await _summary(session, app, principal, role)) - return {"items": items} + return {"items": items, "can_create": {"shared": principal.mode == "off" or principal.at_least("builder"), + "personal": await allowed(session, principal)}} class AppIn(BaseModel): @@ -186,18 +233,28 @@ class AppIn(BaseModel): @router.post("", status_code=201) async def create_app(payload: AppIn, session: AsyncSession = Depends(get_session), x_actor: str | None = Header(default=None)) -> dict[str, Any]: - from app.apps.spec import empty_spec - principal = _principal(x_actor) _require_builder(principal) - draft = dict(payload.spec) if payload.spec else empty_spec(payload.name) - draft["name"] = payload.name - app = App(name=payload.name, description=payload.description, icon=payload.icon, draft=draft, - draft_bindings={"slots": {}}, created_by=actor_of(x_actor), updated_by=actor_of(x_actor)) + app = await new_app(session, name=payload.name, description=payload.description, icon=payload.icon, + spec=payload.spec, actor=actor_of(x_actor)) + return await _detail(session, app, principal, "manage") + + +async def new_app(session: AsyncSession, *, name: str, description: str = "", icon: str = "app", + spec: dict[str, Any] | None = None, bindings: dict[str, Any] | None = None, + actor: str | None, blueprint_id: str | None = None) -> App: + """建一个应用(只有草稿,提交)。建应用的接口和发布单共用;发布单另带上岗位绑定和出自哪个蓝图。""" + from app.apps.spec import empty_spec + + draft = dict(spec) if spec else empty_spec(name) + draft["name"] = name + app = App(name=name, description=description, icon=icon, draft=draft, + draft_bindings={"slots": {}, **(bindings or {})}, created_by=actor, updated_by=actor, + blueprint_id=blueprint_id) session.add(app) await session.commit() await session.refresh(app) - return await _detail(session, app, principal, "manage") + return app class DeriveIn(BaseModel): @@ -257,6 +314,12 @@ async def update_app(app_id: str, payload: AppPatch, session: AsyncSession = Dep _refuse_archived(app, "修改") if payload.draft_bindings is not None and (problem := _bindings_problem(payload.draft_bindings)): raise HTTPException(422, problem) + if app.scope == "personal" and payload.draft is not None: + # 个人应用的草稿就是在用的那一份:只许改呈现,固定的蓝图、视图来源只由「存成我的应用」改 + from app.blueprints.personal import draft_problem + + if problem := draft_problem(app.draft or {}, payload.draft): + raise HTTPException(422, problem) for key in ("name", "description", "icon"): if (value := getattr(payload, key)) is not None: setattr(app, key, value) @@ -275,16 +338,23 @@ async def archive_app(app_id: str, session: AsyncSession = Depends(get_session), x_actor: str | None = Header(default=None)) -> dict[str, Any]: """归档:不再出现在应用列表里,入口拒绝发起、入站钩子一律拒收(apps/entries.py、process/hooks.py),不再改草稿、 不再发布;进行中的实例照常走完,版本、实例、生效记录都留着。没有恢复的接口。""" + from app.apps.access import can_archive from app.apps.audit import record principal = _principal(x_actor) - app, role = await _app(session, app_id, principal, "manage") + app = await session.get(App, app_id) + role = await app_role(session, principal, app) if app is not None else None + if app is None or not can_archive(principal, app, role): + # 管理员能归档别人的个人应用(看不到内容,能收起来);其余照旧要管理权限 + app, role = await _app(session, app_id, principal, "manage") app.status = "archived" app.updated_by = actor_of(x_actor) await record(session, action="app.archive", subject_kind="app", subject_id=app.id, actor=actor_of(x_actor), - data={"name": app.name}) + data={"name": app.name, **({"owner": app.owner} if app.scope == "personal" else {})}) await session.commit() await session.refresh(app) + if role is None: + return _personal_stub(app) return await _detail(session, app, principal, role) @@ -356,8 +426,12 @@ async def lint(app_id: str, session: AsyncSession = Depends(get_session), principal = _principal(x_actor) app, _ = await _app(session, app_id, principal, "manage") - issues = await lint_app(session, app.draft or {}, app.draft_bindings or {}, previous=await _previous(session, app)) - issues += await acl_issues(session, app.id) + scope = app.scope or "shared" + issues = await lint_app(session, app.draft or {}, app.draft_bindings or {}, previous=await _previous(session, app), + scope=scope) + if scope != "personal": + # 个人应用不能授权给别人,「还没有授权」不是问题 + issues += await acl_issues(session, app.id) pins = await load_pins(session, app.draft or {}) return {"issues": issues, "level": app_level([{"level": p.level} for p in pins.values()]) if pins else None} @@ -373,6 +447,18 @@ async def publish(app_id: str, payload: PublishIn, session: AsyncSession = Depen """把草稿冻结成一个不可变的应用版本。钉住项相对上一版升了版而没选处置的不发布(ok=false,needs_disposition 列出)。 返回 200 + ok/issues 而不是抛错,前端把问题列表渲染出来(同工作流发布)。""" + principal = _principal(x_actor) + app, _ = await _app(session, app_id, principal, "manage") + _refuse_archived(app, "发布") + _refuse_personal(app, "发布") + return await publish_draft(session, app, note=payload.note, dispositions=payload.dispositions, + actor=actor_of(x_actor)) + + +async def publish_draft(session: AsyncSession, app: App, *, note: str, dispositions: dict[str, str], + actor: str | None) -> dict[str, Any]: + """检查草稿,过了就冻结成新的应用版本并提交;没过交回 ok=false 和问题(不写库)。发布接口和发布单共用。 + 两个人同时发布时后到的那个抛 409(app_publish_conflict)。""" from app.apps.audit import record from app.apps.lint import acl_issues, lint_app, needs_disposition, pins_with_state from app.apps.pins import load_pins @@ -381,18 +467,14 @@ async def publish(app_id: str, payload: PublishIn, session: AsyncSession = Depen from app.apps.tree import app_level, spec_hash from app.db.base import utcnow - principal = _principal(x_actor) - app, _ = await _app(session, app_id, principal, "manage") - _refuse_archived(app, "发布") previous = await _previous(session, app) draft = app.draft or {} - issues = await lint_app(session, draft, app.draft_bindings or {}, previous=previous, - dispositions=payload.dispositions) + issues = await lint_app(session, draft, app.draft_bindings or {}, previous=previous, dispositions=dispositions) issues += await acl_issues(session, app.id) upgraded = needs_disposition(previous, draft.get("pins") or []) if isinstance(draft.get("pins"), list) else [] if any(i["level"] == "error" for i in issues): return {"ok": False, "issues": issues, - "needs_disposition": [u for u in upgraded if payload.dispositions.get(u["alias"]) is None]} + "needs_disposition": [u for u in upgraded if dispositions.get(u["alias"]) is None]} pins = await load_pins(session, draft) spec = parse_spec(draft).model_dump(mode="json", by_alias=True) spec["pins"] = pins_with_state(spec, pins) @@ -400,14 +482,14 @@ async def publish(app_id: str, payload: PublishIn, session: AsyncSession = Depen level = app_level(spec["pins"]) row = AppVersion(app_id=app.id, version=number, spec=spec, spec_hash=spec_hash(spec), pins=spec["pins"], bindings={"slots": {}, **(app.draft_bindings or {})}, level=level, - dispositions={u["alias"]: payload.dispositions[u["alias"]] for u in upgraded}, - note=payload.note, published_by=actor_of(x_actor), published_at=utcnow()) + dispositions={u["alias"]: dispositions[u["alias"]] for u in upgraded}, + note=note, published_by=actor, published_at=utcnow()) session.add(row) app.published_version = number - app.updated_by = actor_of(x_actor) - await record(session, action="app.publish", subject_kind="app", subject_id=app.id, actor=actor_of(x_actor), + app.updated_by = actor + await record(session, action="app.publish", subject_kind="app", subject_id=app.id, actor=actor, data={"version": number, "spec_hash": row.spec_hash, "level": level, "pins": spec["pins"], - "dispositions": row.dispositions, "note": payload.note}) + "dispositions": row.dispositions, "note": note}) try: await session.commit() except IntegrityError as e: @@ -479,20 +561,30 @@ async def put_grants(app_id: str, payload: GrantsIn, session: AsyncSession = Dep 给的人和组按名录核对(auth/directory.py,同选人控件、同应用检查):账号密码登录时名录里没有的、任何登录方式下停用了 的拒收,说清是哪一档、哪个名字——界面上选人时已经拦着,这里拦旧客户端和直接调接口的。单点登录的人第一次登录后才进 名录,名录里还没有的照收(检查里提醒);关登录不核对。""" + app, _ = await _app(session, app_id, _principal(x_actor), "manage") + _refuse_personal(app, "授权给别人") + wanted, problem = await grants_problem(session, [(i.principal_kind, i.principal, i.role) for i in payload.items]) + if problem: + raise HTTPException(422, problem) + return {"items": await replace_grants(session, app, wanted, actor=actor_of(x_actor))} + + +async def grants_problem(session: AsyncSession, items: list[tuple[str, str, str]] + ) -> tuple[list[tuple[str, str, str]], str | None]: + """要给的授权 [(principal_kind, principal, role)] → (去重规范化之后的, 收不下的说明),只读。形状不对、名录核对不过 + (同上面的规则)时说明不为空。授权接口和发布单(预检只检查、最后一步照它授权)共用。""" from app.api.deps import auth_mode - from app.apps.audit import record from app.auth.directory import load_directory, mismatch from app.db.models_apps import GRANT_ROLES - app, _ = await _app(session, app_id, _principal(x_actor), "manage") wanted: list[tuple[str, str, str]] = [] - for item in payload.items: - if item.principal_kind not in ("user", "group", "everyone") or item.role not in GRANT_ROLES: - raise HTTPException(422, "授权只能给人、组或所有人,权限只能是使用、查看全部实例或管理") - principal = "" if item.principal_kind == "everyone" else item.principal.strip() - if item.principal_kind != "everyone" and not principal: - raise HTTPException(422, "授权给人或组时需要写明是谁") - key = (item.principal_kind, principal, item.role) + for kind, name, role in items: + if kind not in ("user", "group", "everyone") or role not in GRANT_ROLES: + return wanted, "授权只能给人、组或所有人,权限只能是使用、查看全部实例或管理" + principal = "" if kind == "everyone" else (name or "").strip() + if kind != "everyone" and not principal: + return wanted, "授权给人或组时需要写明是谁" + key = (kind, principal, role) if key not in wanted: wanted.append(key) if (mode := auth_mode()) != "off": @@ -500,18 +592,26 @@ async def put_grants(app_id: str, payload: GrantsIn, session: AsyncSession = Dep refused = [f"「{ROLE_TEXT[role]}」里的{m.text}" for kind, who, role in wanted if (m := mismatch(known, mode, kind, who)) is not None and m.blocking] if refused: - raise HTTPException(422, f"{';'.join(refused)}:授权只能给名录里在用的人和组,请移除或从候选中重新选择") + return wanted, f"{';'.join(refused)}:授权只能给名录里在用的人和组,请移除或从候选中重新选择" + return wanted, None + + +async def replace_grants(session: AsyncSession, app: App, wanted: list[tuple[str, str, str]], *, + actor: str | None) -> list[dict[str, str]]: + """整份替换授权(调用方先过了 grants_problem),写审计并提交。""" + from app.apps.audit import record + before = [_grant_out(g) for g in await grants_of(session, app.id)] for g in await grants_of(session, app.id): await session.delete(g) await session.flush() for kind, who, role in wanted: - session.add(AppGrant(app_id=app.id, principal_kind=kind, principal=who, role=role, granted_by=actor_of(x_actor))) + session.add(AppGrant(app_id=app.id, principal_kind=kind, principal=who, role=role, granted_by=actor)) after = [{"principal_kind": k, "principal": p, "role": r} for k, p, r in wanted] - await record(session, action="app.grants", subject_kind="app", subject_id=app.id, actor=actor_of(x_actor), + await record(session, action="app.grants", subject_kind="app", subject_id=app.id, actor=actor, data={"before": before, "after": after}) await session.commit() - return {"items": after} + return after # -------------------------------------------------------------------------- @@ -661,7 +761,8 @@ async def get_page(app_id: str, page_id: str, instance: str | None = None, param principal = _principal(x_actor) app, role = await _app(session, app_id, principal, "manage" if draft else "use") - version = None if draft else await _current_version(session, app) + # 个人应用没有应用版本:草稿就是在用的那一份(resolve_page 按 scope 认) + version = None if draft or app.scope == "personal" else await _current_version(session, app) run = await _instance(session, app, instance, principal, role) if instance else None try: return await resolve_page(session, app, page_id=page_id, principal=principal, role=role, instance=run, diff --git a/backend/app/api/auth.py b/backend/app/api/auth.py index 77ca9adf..6a4c87d9 100644 --- a/backend/app/api/auth.py +++ b/backend/app/api/auth.py @@ -41,6 +41,14 @@ def principal_out(p: Principal) -> dict[str, Any]: "user_can_chat": user_can_chat()} +async def principal_full(session: AsyncSession, p: Principal) -> dict[str, Any]: + """认人接口、登录交回的那一份:principal_out 再加上管理员开没开「使用者可以建个人应用」(同 user_can_chat,使用者 + 读不到设置,新建应用的入口、个人蓝图页按它给)。""" + from app.blueprints.personal import enabled + + return {**principal_out(p), "user_personal_apps": await enabled(session)} + + @router.get("/me") async def me(x_actor: str | None = Header(default=None), session: AsyncSession = Depends(get_session)) -> Any: """当前是谁。关登录:mode=off、role=admin、username 是自报的署名。开登录没登录:401,带 mode(登录页据此显示 @@ -49,12 +57,12 @@ async def me(x_actor: str | None = Header(default=None), session: AsyncSession = principal = current_principal() if principal.mode == "off": actor = decode_actor(x_actor) - return principal_out(Principal(username=actor, display_name=actor, role="admin", mode="off")) + return await principal_full(session, Principal(username=actor, display_name=actor, role="admin", mode="off")) if not principal.username: can_bootstrap = principal.mode == "local" and not await _local_admin_exists(session) return JSONResponse(status_code=401, content={"detail": "请先登录", "code": "auth_required", "mode": principal.mode, "can_bootstrap": can_bootstrap}) - return principal_out(principal) + return await principal_full(session, principal) def _client_ip(request: Request) -> str: @@ -89,7 +97,7 @@ async def login(payload: LoginIn, request: Request, response: Response, user_agent=request.headers.get("user-agent")) await session.commit() _login_response(request, response, token) - return principal_out(await sessions.principal_of(session, user, mode)) + return await principal_full(session, await sessions.principal_of(session, user, mode)) @router.post("/logout", status_code=204) @@ -301,7 +309,7 @@ async def put_settings(payload: SettingsIn, request: Request, response: Response out = _settings_out(value) if token is not None and created is not None: _login_response(request, response, token) - out["principal"] = principal_out(await sessions.principal_of(session, created, current_mode())) + out["principal"] = await principal_full(session, await sessions.principal_of(session, created, current_mode())) return out @@ -318,4 +326,4 @@ async def bootstrap(payload: BootstrapIn, request: Request, response: Response, user_agent=request.headers.get("user-agent")) await session.commit() _login_response(request, response, token) - return principal_out(await sessions.principal_of(session, user, "local")) + return await principal_full(session, await sessions.principal_of(session, user, "local")) diff --git a/backend/app/api/blueprints.py b/backend/app/api/blueprints.py index d5cd1585..c71504b1 100644 --- a/backend/app/api/blueprints.py +++ b/backend/app/api/blueprints.py @@ -1,71 +1,472 @@ """蓝图、试运行、发布单的接口(docs/design/normal-user-apps.md §3.5、§3.6、§3.10)。 -权限在接口里判:共享蓝图要 builder(受管级发布单再要 admin),个人蓝图要拥有者且管理员开了 apps.user_personal_apps。 -骨架阶段全部 501,包 B2 实现(CRUD 调 blueprints/ops,试运行调 blueprints/trial,发布单调 blueprints/publish_plan)。 +权限在接口里判:共享蓝图要 builder(受管级发布单再要 admin),个人蓝图要拥有者且能用个人应用(blueprints/personal.allowed: +开了登录的搭建者及以上随时能,使用者和关登录时看管理员开没开 apps.user_personal_apps)。别人的个人蓝图一律当不存在(404)。 + +- 起点四个,都落到同一个蓝图(N1):conversation(空蓝图,另建一段蓝图对话)、template(按模板预置卡片)、run(问数据 + 的一轮回答:按 /copilot/from-run 同一个提取规则取出执行路径,模板记「自由形」)、workflow_version(已发布的版本: + 图原样导入,模板记「自由形」,蓝图就挂在那个工作流上)。 +- 卡片上的修改(PATCH)走 bp_* 操作(blueprints/store.apply_ops_and_save),来源记成 user。 +- 实例化、试运行、预览调 blueprints/trial;发布单调 blueprints/publish_plan。 """ from __future__ import annotations -from typing import Any +import dataclasses +from typing import Any, Literal -from fastapi import APIRouter, HTTPException +from fastapi import APIRouter, Depends, Header, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, Field +from sqlalchemy import or_, select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.api.coded import CodedHTTPException +from app.api.deps import Principal, actor_of, current_principal +from app.db.base import get_session +from app.db.models_blueprints import Blueprint router = APIRouter(prefix="/api", tags=["blueprints"]) -_TODO = "尚未实现" +#: 机器码 +NO_ACCESS = "blueprint_forbidden" +BAD_SOURCE = "blueprint_source_invalid" +ADMIN_ONLY = "admin_only" +#: 没选模板、从已有的东西导入时记的模板 +FREEFORM = "freeform" +#: 蓝图对话(Conversation.kind) +CONVERSATION_KIND = "blueprint" +DEFAULT_NAME = "新应用" + + +# -------------------------------------------------------------------------- +# 身份、取蓝图、判权限 +# -------------------------------------------------------------------------- + + +def _principal(x_actor: str | None) -> Principal: + """这次请求的身份。关登录时 username 换成自报的署名(X-Actor),蓝图的拥有者、留痕都按它记(同 api/apps.py)。""" + principal = current_principal() + if principal.mode == "off" and principal.username is None: + return dataclasses.replace(principal, username=actor_of(x_actor)) + return principal + + +def _require_builder(principal: Principal, what: str = "共享蓝图") -> None: + if not principal.at_least("builder"): + raise CodedHTTPException(403, f"{what}需要搭建者权限", NO_ACCESS) + + +async def _personal_allowed(session: AsyncSession, principal: Principal) -> None: + from app.blueprints.personal import PersonalRefused, ensure_allowed + + try: + await ensure_allowed(session, principal) + except PersonalRefused as e: + raise CodedHTTPException(e.status_code, e.message, e.code or NO_ACCESS) from e + + +async def _blueprint(session: AsyncSession, blueprint_id: str) -> Blueprint: + """取蓝图并判权限(blueprints/store.load,蓝图接口和蓝图助手同一条规则):共享的要搭建者;个人的要拥有者(别人的 + 个人蓝图当不存在)且能用个人应用。""" + from app.blueprints.store import load + + return await load(session, blueprint_id) + + +def blueprint_out(bp: Blueprint) -> dict[str, Any]: + """接口形状(frontend/src/typesBlueprint.ts 的 Blueprint,blueprints/store.blueprint_out):图本身不下发(只给哈希), + 关节只给状态,问题带白话。""" + from app.blueprints.store import blueprint_out as shaped + + return shaped(bp) + + +def _refused(e: Any) -> HTTPException: + """各服务的拒绝(status_code / message / code)→ HTTP(带 code 的回 {detail, code})。""" + if getattr(e, "code", None): + return CodedHTTPException(e.status_code, e.message, e.code) + return HTTPException(e.status_code, e.message) + + +def _blocked(e: Any) -> JSONResponse: + """被检查问题挡住的拒绝(试运行遇到缺项、待填的关节):{detail, code, issues},问题带白话,界面逐条列出来。""" + return JSONResponse(status_code=e.status_code, content={ + "detail": e.message, **({"code": e.code} if getattr(e, "code", None) else {}), + "issues": getattr(e, "issues", None) or []}) + + +# -------------------------------------------------------------------------- +# 起点 +# -------------------------------------------------------------------------- + + +class SourceIn(BaseModel): + kind: Literal["conversation", "template", "run", "workflow_version"] + id: str | None = None + version: int | None = None + + +class BlueprintIn(BaseModel): + source: SourceIn + scope: Literal["shared", "personal"] = "shared" + name: str | None = Field(default=None, max_length=200) + #: 从模板开始时的模板 id(也可以写在 source.id) + template: str | None = None + + +def _freeform_ref() -> dict[str, Any]: + from app.blueprints.templates import get_template + + template = get_template(FREEFORM) + return {"id": FREEFORM, "version": template.version if template is not None else 1} + + +def _proposed(value: Any) -> dict[str, Any]: + """起点带来的一项(运行时的问题、工作流的说明):是从已有的东西里取的,没经用户确认,记「待确认」。""" + return {"value": value, "source": "assistant", "status": "proposed", "why": None} @router.post("/blueprints", status_code=201) -async def create_blueprint() -> dict[str, Any]: +async def create_blueprint(payload: BlueprintIn, session: AsyncSession = Depends(get_session), + x_actor: str | None = Header(default=None)) -> dict[str, Any]: """起点:{source: {kind: conversation|template|run|workflow_version, id?, version?}, scope: shared|personal, name?}""" - raise HTTPException(501, _TODO) + from app.blueprints.spec import empty_blueprint + from app.blueprints.trial import record_event + from app.core.artifact_store import graph_hash + + principal = _principal(x_actor) + if payload.scope == "personal": + await _personal_allowed(session, principal) + else: + _require_builder(principal) + spec = empty_blueprint() + bp = Blueprint(name=(payload.name or "").strip(), owner=principal.username, scope=payload.scope, + status="drafting", source={"kind": payload.source.kind}, updated_by=principal.username) + kind = payload.source.kind + if kind == "conversation": + from app.db.models import Conversation + + bp.name = bp.name or DEFAULT_NAME + conversation = Conversation(kind=CONVERSATION_KIND, created_by=principal.username, title=f"「{bp.name}」的蓝图") + session.add(conversation) + await session.flush() + bp.conversation_id = conversation.id + elif kind == "template": + spec = _template_spec(spec, payload.template or payload.source.id) + bp.name = bp.name or DEFAULT_NAME + bp.source = {"kind": kind, "id": spec["template"]["id"]} + elif kind == "run": + spec, graph = await _from_run(session, spec, payload.source.id, principal) + bp.graph, bp.graph_hash = graph, graph_hash(graph) + bp.name = bp.name or str((spec.get("purpose") or {}).get("value") or DEFAULT_NAME)[:40] + bp.source = {"kind": kind, "id": payload.source.id} + else: + _require_builder(principal, "从已发布的工作流开始") + spec, workflow, row = await _from_version(session, spec, payload.source.id, payload.source.version) + bp.graph, bp.graph_hash = row.graph or {}, row.graph_hash or graph_hash(row.graph or {}) + bp.workflow_id = workflow.id + bp.name = bp.name or workflow.name + bp.source = {"kind": kind, "id": workflow.id, "version": row.version} + ref = spec.get("template") + if isinstance(ref, dict): + bp.template_id, bp.template_version = ref.get("id"), ref.get("version") + bp.spec = spec + session.add(bp) + await session.flush() + await record_event(session, bp, "create", {"source": bp.source, "scope": bp.scope}, principal=principal) + await session.commit() + await session.refresh(bp) + return blueprint_out(bp) + + +def _template_spec(spec: dict[str, Any], template_id: str | None) -> dict[str, Any]: + """从模板开始:按模板预置卡片(选模板走 bp_template,来源记成用户:是用户挑的模板)。""" + from app.blueprints.ops import BpRefused, apply_bp_op + from app.blueprints.templates import get_template + + template = get_template(template_id or "") + if template is None: + raise CodedHTTPException(422, f"没有叫「{template_id or ''}」的场景模板", BAD_SOURCE, field="template") + try: + return apply_bp_op(spec, {"op": "bp_template", "template": {"id": template.id, "version": template.version}}, + source="user") + except BpRefused as e: + raise CodedHTTPException(422, e.message, e.code) from e + + +async def _from_run(session: AsyncSession, spec: dict[str, Any], run_id: str | None, + principal: Principal) -> tuple[dict[str, Any], dict[str, Any]]: + """从问数据的一轮回答开始:按「提取成工作流」同一个规则取出这次运行实际走过的路径(api/copilot.extract_run_path), + 不建工作流——图存在蓝图上,发布单保存版本时才建。读不到这次运行的人当它不存在。""" + from app.api.copilot import PathRefused, extract_run_path + from app.api.deps import can_read_run + from app.db.models import Run + + if not run_id: + raise CodedHTTPException(422, "从问数据的回答开始,需要说明是哪一次运行", BAD_SOURCE, field="source") + run = await session.get(Run, run_id) + if run is None or not await can_read_run(principal, run): + raise HTTPException(404, "运行记录不存在,可能已被删除") + try: + path = await extract_run_path(session, run_id) + except PathRefused as e: + raise HTTPException(e.status_code, e.message) from e + question = (run.input or {}).get("question") + spec = {**spec, "template": _freeform_ref()} + if isinstance(question, str) and question.strip(): + spec["purpose"] = _proposed(question.strip()[:500]) + return spec, path.graph + + +async def _from_version(session: AsyncSession, spec: dict[str, Any], workflow_id: str | None, + version: int | None) -> tuple[dict[str, Any], Any, Any]: + """从已发布的工作流版本开始:图原样导入,模板记「自由形」,蓝图挂在这个工作流上(发布单按图哈希复用这一版)。""" + from app.apps.versions import is_published, version_row + from app.db.models import Workflow + + workflow = await session.get(Workflow, workflow_id or "") + if workflow is None: + raise HTTPException(404, "工作流不存在,可能已被删除") + wanted = version or workflow.published_version + row = await version_row(session, workflow.id, wanted) if wanted else None + if row is None or not is_published(row, current=workflow.published_version): + raise CodedHTTPException(409, f"「{workflow.name}」{f'v{wanted} ' if wanted else ''}不是在用的发布版本:" + "只能从已发布、没退役的版本开始", BAD_SOURCE, field="source") + spec = {**spec, "template": _freeform_ref()} + if (workflow.description or "").strip(): + spec["purpose"] = _proposed(workflow.description.strip()[:500]) + return spec, workflow, row + + +# -------------------------------------------------------------------------- +# 列表、详情、卡片上的修改 +# -------------------------------------------------------------------------- @router.get("/blueprints") -async def list_blueprints() -> dict[str, Any]: - raise HTTPException(501, _TODO) +async def list_blueprints(scope: Literal["shared", "personal"] | None = None, + session: AsyncSession = Depends(get_session), + x_actor: str | None = Header(default=None)) -> dict[str, Any]: + """共享蓝图(搭建者看得到)和我的个人蓝图(能用个人应用时),按最近改动排。""" + from app.blueprints.personal import allowed + + principal = _principal(x_actor) + wanted = [] + if scope in (None, "shared") and principal.at_least("builder"): + wanted.append(Blueprint.scope == "shared") + if scope in (None, "personal") and await allowed(session, principal): + mine = Blueprint.scope == "personal" + if principal.mode != "off": + mine = mine & (Blueprint.owner == (principal.username or "")) + wanted.append(mine) + if not wanted: + return {"items": []} + rows = (await session.execute(select(Blueprint).where(or_(*wanted)).order_by(Blueprint.updated_at.desc()) + .limit(200))).scalars() + return {"items": [blueprint_out(bp) for bp in rows]} @router.get("/blueprints/{blueprint_id}") -async def get_blueprint(blueprint_id: str) -> dict[str, Any]: - raise HTTPException(501, _TODO) +async def get_blueprint(blueprint_id: str, session: AsyncSession = Depends(get_session), + x_actor: str | None = Header(default=None)) -> dict[str, Any]: + from app.blueprints.trial import settle + + bp = await _blueprint(session, blueprint_id) + return blueprint_out(await settle(session, bp)) + + +@router.get("/blueprints/{blueprint_id}/conversation") +async def blueprint_conversation(blueprint_id: str, session: AsyncSession = Depends(get_session), + x_actor: str | None = Header(default=None)) -> Any: + """蓝图对话的历史(ConversationDetail):权限按蓝图判(同读蓝图),不经问数据的路由——没开问数据的使用者也读得到 + 自己个人蓝图的对话。蓝图没有对话(从模板、运行开始的)回 404。""" + from app.api.conversations import conversation_detail + from app.db.models import Conversation + + bp = await _blueprint(session, blueprint_id) + row = await session.get(Conversation, bp.conversation_id) if bp.conversation_id else None + if row is None: + raise HTTPException(404, "这张蓝图没有对话") + return await conversation_detail(session, row) + + +class BlueprintPatch(BaseModel): + ops: list[dict[str, Any]] = Field(default_factory=list) + name: str | None = Field(default=None, min_length=1, max_length=200) @router.patch("/blueprints/{blueprint_id}") -async def patch_blueprint(blueprint_id: str) -> dict[str, Any]: - """{ops: [bp_* 操作], name?}:用户在卡片上的修改,来源记成 user。""" - raise HTTPException(501, _TODO) +async def patch_blueprint(blueprint_id: str, payload: BlueprintPatch, session: AsyncSession = Depends(get_session), + x_actor: str | None = Header(default=None)) -> dict[str, Any]: + """{ops: [bp_* 操作], name?}:用户在卡片上的修改,来源记成 user。一个操作被拒整批不落(422,带 code)。""" + from app.blueprints.ops import BpRefused + + principal = _principal(x_actor) + bp = await _blueprint(session, blueprint_id) + if payload.name is not None and payload.name.strip() != (bp.name or ""): + # 改名也留痕(P2):名字进工作流和应用的名字、口径卡的标题 + from app.blueprints.trial import record_event + + before, bp.name = bp.name, payload.name.strip() + bp.updated_by = principal.username + await record_event(session, bp, "rename", {"source": "user", "before": before, "after": bp.name}, + principal=principal) + if payload.ops: + from app.blueprints.store import apply_ops_and_save + + try: + await apply_ops_and_save(session, bp, payload.ops, principal.username, principal.verified, "user") + except BpRefused as e: + await session.rollback() + raise CodedHTTPException(422, e.message, e.code) from e + await session.commit() + await session.refresh(bp) + return blueprint_out(bp) + + +# -------------------------------------------------------------------------- +# 实例化、试运行、预览 +# -------------------------------------------------------------------------- @router.post("/blueprints/{blueprint_id}/instantiate") -async def instantiate_blueprint(blueprint_id: str) -> dict[str, Any]: - raise HTTPException(501, _TODO) +async def instantiate_blueprint(blueprint_id: str, session: AsyncSession = Depends(get_session), + x_actor: str | None = Header(default=None)) -> dict[str, Any]: + """按模板实例化:图、关节存到蓝图上,交回应用草稿和问题(缺项、待填的关节,带白话)。不发起运行。""" + from app.blueprints.trial import TrialRefused, materialize + + principal = _principal(x_actor) + bp = await _blueprint(session, blueprint_id) + try: + result = await materialize(session, bp, principal=principal) + except TrialRefused as e: + raise _refused(e) from e + return {"blueprint": blueprint_out(bp), "app_spec": result.app_spec, "problems": result.problems} + + +class TrialIn(BaseModel): + inputs: dict[str, Any] = Field(default_factory=dict) @router.post("/blueprints/{blueprint_id}/trial") -async def trial(blueprint_id: str) -> dict[str, Any]: - raise HTTPException(501, _TODO) +async def trial(blueprint_id: str, payload: TrialIn, session: AsyncSession = Depends(get_session), + x_actor: str | None = Header(default=None)) -> Any: + """用真数试运行:实例化 → 保存图 → 发起探索运行,交回 {run_id, blueprint}。缺项、待填的关节挡住时回 409 和问题。""" + from app.blueprints.trial import TrialRefused, start_trial + from app.engine.launch import LaunchRefused + + principal = _principal(x_actor) + bp = await _blueprint(session, blueprint_id) + try: + run, _ = await start_trial(session, bp, inputs=payload.inputs, principal=principal, actor=principal.username) + except TrialRefused as e: + if e.issues: + return _blocked(e) + raise _refused(e) from e + except LaunchRefused as e: + raise _refused(e) from e + return {"run_id": run.id, "blueprint": blueprint_out(bp)} @router.get("/blueprints/{blueprint_id}/preview") -async def preview(blueprint_id: str) -> dict[str, Any]: - raise HTTPException(501, _TODO) +async def preview(blueprint_id: str, page: str | None = None, run: str | None = None, + session: AsyncSession = Depends(get_session), + x_actor: str | None = Header(default=None)) -> dict[str, Any]: + """按这次试运行解析应用草稿的一页(agentlab.view/1):印章写「试运行」,流程组件对着这次运行。""" + from app.apps.resolve import ViewRefused + from app.blueprints.trial import TrialRefused, preview_page + + principal = _principal(x_actor) + bp = await _blueprint(session, blueprint_id) + try: + return await preview_page(session, bp, page_id=page, run_id=run, principal=principal) + except (TrialRefused, ViewRefused) as e: + raise _refused(e) from e + + +# -------------------------------------------------------------------------- +# 发布单 +# -------------------------------------------------------------------------- + + +class PlanIn(BaseModel): + level: Literal["published", "governed"] = "published" + #: 跑第一次(不给时看板类为真、流程类为假) + first_run: bool | None = None + #: 钉住项升版时的处置 {别名: recompute|dual|incomparable} + dispositions: dict[str, Literal["recompute", "dual", "incomparable"]] = Field(default_factory=dict) + + +async def _shared_for_plan(session: AsyncSession, blueprint_id: str, principal: Principal) -> Blueprint: + bp = await _blueprint(session, blueprint_id) + if bp.scope != "shared": + raise CodedHTTPException(409, "个人蓝图不走发布单:存成你的应用自己用,想给别人用请提交审核", "plan_state") + _require_builder(principal, "发布") + return bp @router.post("/blueprints/{blueprint_id}/publish-plan") -async def publish_plan(blueprint_id: str) -> dict[str, Any]: - raise HTTPException(501, _TODO) +async def publish_plan(blueprint_id: str, payload: PlanIn, session: AsyncSession = Depends(get_session), + x_actor: str | None = Header(default=None)) -> dict[str, Any]: + """出发布单(只读预检):{id, steps, summary, problems(带白话、谁来改), ok}。受管级由搭建者出单时,问题里写明要管理员。""" + from app.blueprints import publish_plan as plans + from app.blueprints.trial import settle + + principal = _principal(x_actor) + bp = await settle(session, await _shared_for_plan(session, blueprint_id, principal)) + try: + row = await plans.plan(session, bp, level=payload.level, principal=principal, + options={"dispositions": payload.dispositions, + **({"first_run": payload.first_run} if payload.first_run is not None else {})}) + except plans.PlanRefused as e: + raise _refused(e) from e + return plans.plan_out(row) + + +async def _plan_for(session: AsyncSession, plan_id: str, principal: Principal) -> Any: + from app.blueprints import publish_plan as plans + + try: + row = await plans.get_plan(session, plan_id) + except plans.PlanRefused as e: + raise _refused(e) from e + await _shared_for_plan(session, row.blueprint_id, principal) + return row @router.get("/publish-plans/{plan_id}") -async def get_plan(plan_id: str) -> dict[str, Any]: - raise HTTPException(501, _TODO) +async def get_plan(plan_id: str, session: AsyncSession = Depends(get_session), + x_actor: str | None = Header(default=None)) -> dict[str, Any]: + from app.blueprints.publish_plan import plan_out + + return plan_out(await _plan_for(session, plan_id, _principal(x_actor))) + + +async def _drive(plan_id: str, x_actor: str | None, session: AsyncSession, how: str) -> dict[str, Any]: + from app.blueprints import publish_plan as plans + + principal = _principal(x_actor) + row = await _plan_for(session, plan_id, principal) + if row.level == "governed" and not principal.at_least("admin"): + # 受管级只有管理员能发(Q8,同工作流发布接口):搭建者出的单可以看,执行要管理员 + raise CodedHTTPException(403, "以受管级别发布需要管理员权限", ADMIN_ONLY) + try: + done = await (plans.run if how == "run" else plans.resume)(session, plan_id, principal=principal) + except plans.PlanRefused as e: + raise _refused(e) from e + return plans.plan_out(done) @router.post("/publish-plans/{plan_id}/run") -async def run_plan(plan_id: str) -> dict[str, Any]: - raise HTTPException(501, _TODO) +async def run_plan(plan_id: str, session: AsyncSession = Depends(get_session), + x_actor: str | None = Header(default=None)) -> dict[str, Any]: + """确认后按序执行。某步停下时 status=stopped,那一步写明原因(白话);修好后用「接着做」。""" + return await _drive(plan_id, x_actor, session, "run") @router.post("/publish-plans/{plan_id}/resume") -async def resume_plan(plan_id: str) -> dict[str, Any]: - raise HTTPException(501, _TODO) +async def resume_plan(plan_id: str, session: AsyncSession = Depends(get_session), + x_actor: str | None = Header(default=None)) -> dict[str, Any]: + """从停下的那一步接着做:已完成的按结果里的 id 核对,不重做。""" + return await _drive(plan_id, x_actor, session, "resume") + diff --git a/backend/app/api/conversations.py b/backend/app/api/conversations.py index d273aae5..75e73ebc 100644 --- a/backend/app/api/conversations.py +++ b/backend/app/api/conversations.py @@ -287,12 +287,21 @@ async def _manages_app(session: AsyncSession, app_id: str) -> bool: async def _check_access(session: AsyncSession, row: Conversation) -> None: - """这段对话这个人能不能用,不能用抛 403。""" + """这段对话这个人能不能用,不能用抛 403。蓝图对话跟着蓝图走(blueprints/store.ensure_access):别人的个人蓝图的对话, + 搭建者、管理员也看不到(§3.12:别人的个人应用内容谁都不看),当它不存在(404,同蓝图)。""" mine = _isolated() if mine is not None and (not row.created_by or row.created_by != mine): raise HTTPException(403, NOT_YOURS) if row.kind == "app" and row.app_id and not await _manages_app(session, row.app_id): raise HTTPException(403, APP_MANAGE_ONLY) + if row.kind == "blueprint": + from app.blueprints.store import BLUEPRINT_GONE, ensure_access + from app.db.models_blueprints import Blueprint + + bp = (await session.execute(select(Blueprint).where(Blueprint.conversation_id == row.id))).scalars().first() + if bp is None: + raise HTTPException(404, BLUEPRINT_GONE) + await ensure_access(session, bp) async def ensure_conversation_access(session: AsyncSession, conversation_id: str | None) -> Conversation | None: @@ -348,6 +357,12 @@ async def list_conversations( managed[row.app_id] = await _manages_app(session, row.app_id) if not managed[row.app_id]: continue + if row.kind == "blueprint": + # 蓝图对话跟着蓝图走:别人的个人蓝图的对话不列 + try: + await _check_access(session, row) + except HTTPException: + continue kept.append(row) rows = kept if not rows: @@ -398,7 +413,13 @@ async def create_conversation( async def get_conversation( conversation_id: str, session: AsyncSession = Depends(get_session) ) -> ConversationDetail: - row = await _get(session, conversation_id) + return await conversation_detail(session, await _get(session, conversation_id)) + + +async def conversation_detail(session: AsyncSession, row: Conversation) -> ConversationDetail: + """一段对话连同各轮(权限由调用方先判过)。蓝图对话另经 GET /api/blueprints/{id}/conversation 取:那条路按蓝图判, + 没开问数据的使用者也读得到自己蓝图的对话。""" + conversation_id = row.id turns = list((await session.execute( select(ConversationTurn) .where(ConversationTurn.conversation_id == conversation_id) diff --git a/backend/app/api/copilot.py b/backend/app/api/copilot.py index 3892954a..6111d378 100644 --- a/backend/app/api/copilot.py +++ b/backend/app/api/copilot.py @@ -7,6 +7,7 @@ import logging import math import re import time +from dataclasses import dataclass from typing import Any, Literal from fastapi import APIRouter, Depends, HTTPException @@ -449,7 +450,29 @@ async def _previous_graph( if not conversation_id: return None turns = await recent_turns(session, conversation_id) - return next((t.graph for t in reversed(turns) if t.graph), None) + return next((t.graph for t in reversed(turns) if _has_nodes(t.graph)), None) + + +def _has_nodes(graph: Any) -> bool: + """一轮记下的图里有没有节点:只问了一句、没搭图的那一轮记的是空图,不算「上一轮的图」。""" + return isinstance(graph, dict) and bool(graph.get("nodes")) + + +def _asked_of(asked: dict[str, Any]) -> dict[str, Any]: + """模型的反问(ask 操作)→ 交给前端、记进这一轮 meta.asked 的形状 {question, options}。""" + options = asked.get("options") + listed = options if isinstance(options, list) else [] + return {"question": str(asked.get("question") or ""), + "options": [str(o) for o in listed if isinstance(o, (str, int, float))]} + + +def _asked_final(asked: dict[str, Any], base_graph: dict[str, Any] | None, + prev_graph: dict[str, Any] | None) -> dict[str, Any]: + """只问不改的一轮的收尾:图原样交回(画布上原来的图、问数据上一轮的图,都没有就是空图),不运行、不重排。""" + graph = base_graph if _has_nodes(base_graph) else prev_graph if _has_nodes(prev_graph) else None + graph = graph or {"nodes": [], "edges": []} + return {"op": "final", "graph": graph, "issues": [], "explanation": "", "autorun": False, + "layout": {"mode": "keep", "placed": []}, "tool_changes": [], "asked": _asked_of(asked)} async def _history_section(session: AsyncSession, conversation_id: str | None) -> str: @@ -472,7 +495,7 @@ async def _history_section(session: AsyncSession, conversation_id: str | None) - return "" lines = [ - f"第 {i} 轮\n 问:{t.question}\n 答:{_answer_of(t) or '(没有结果)'}" + f"第 {i} 轮\n 问:{t.question}\n 答:{_asked_line(t) or _answer_of(t) or '(没有结果)'}" for i, t in enumerate(turns, 1) if t.question ] @@ -481,7 +504,7 @@ async def _history_section(session: AsyncSession, conversation_id: str | None) - block = "# 这次对话之前聊过的\n" + "\n".join(lines) - last_graph = next((t.graph for t in reversed(turns) if t.graph), None) + last_graph = next((t.graph for t in reversed(turns) if _has_nodes(t.graph)), None) if last_graph: # 和 _previous_graph 取的是同一张,兜底重放靠的就是它 block += ( "\n\n上一轮用的工作流(数据源和表都已经对好了):\n" @@ -492,6 +515,25 @@ async def _history_section(session: AsyncSession, conversation_id: str | None) - return block +#: 只问不改的那一轮在历史里的写法:下一轮用户的话就是在回答它 +ASKED_PROMPT = "(助手反问,等用户回答:{question}{options})" + + +def _asked_line(turn: Any) -> str: + """这一轮是助手反问(前端记进 meta.asked:final 带的 {question, options},或者只记 true、问题写在答案里):写成「助手 + 反问了什么」——不然下一轮模型把它当成自己给出的答案,不知道用户的话是在回答它的问题。不是反问的轮次是空串。""" + from app.api.conversations import turn_meta + + asked = (turn_meta(turn) or {}).get("asked") + if asked is True: + asked = {"question": turn.answer or ""} + if not isinstance(asked, dict) or not str(asked.get("question") or "").strip(): + return "" + options = [str(o) for o in asked.get("options") or [] if isinstance(o, (str, int, float))] + return ASKED_PROMPT.format(question=str(asked["question"]).strip(), + options=f";候选:{'、'.join(options)}" if options else "") + + LOOKED_PROMPT = "上一轮查看过:{items}(要再看时直接点名)" LOOKED_KIND_PROMPT = {"capability": "能力 {names}", "workflow_version": "工作流版本 {names}"} @@ -1024,6 +1066,8 @@ async def _op_model(session: AsyncSession, payload: GenerateIn) -> tuple[Any, st # 多久没动静就补一拍心跳。3 秒是"用户开始怀疑是不是卡了"的量级。 _HEARTBEAT_SECONDS = 3.0 +#: 蓝图助手和填关节里算「正在搭」的操作(bp_ask 是反问,不算) +_BLUEPRINT_BUILD_OPS = ("bp_set", "bp_add", "bp_remove", "bp_template", "fill_joint") async def _with_heartbeat(source: Any, phase: str = "planning", *, started: float | None = None): @@ -1048,7 +1092,8 @@ async def _with_heartbeat(source: Any, phase: str = "planning", *, started: floa return kind = op.get("op") # 阶段跟着实际操作走,前端据此换文案。查看时生成过程自己发一拍 looking,查看完回到 planning - if kind == "add_node" or kind in APP_OPS: + # 蓝图助手的 bp_* 操作、填关节的 fill_joint 也是在动手(api/copilot_blueprint.py) + if kind == "add_node" or kind in APP_OPS or kind in _BLUEPRINT_BUILD_OPS: phase = "building" elif kind in ("add_edge", "connect"): phase = "wiring" @@ -1742,7 +1787,10 @@ async def generate_stream(payload: GenerateIn, session: AsyncSession = Depends(g yield _sse(applier.replied) return if gen.asked is not None and not applier.effective: - # 先问清楚才能动手,什么都还没改:问题已经转出去了,这一轮到此为止 + # 先问清楚才能动手,什么都还没改:这一轮到此为止。照样发一条 final 收尾,带上问题(asked)和没动过的图: + # 前端据此把这一轮记成「助手反问」、问题进历史(以前流就这么断了,问数据页一直停在「进行中」), + # 不运行、不重排。图给一份对象(画布上原来的图、问数据上一轮的图,都没有就是空图),老前端照样认得 + yield _sse(_asked_final(gen.asked, payload.base_graph, prev_graph)) return # 只发了目录修改提案,既没回答也没改图(用户只是在说一条数据事实):补一句回答收尾, # 不能按下面的「模型没有给出任何修改」报错——提案已经摆在用户面前了 @@ -1828,6 +1876,8 @@ async def generate_stream(payload: GenerateIn, session: AsyncSession = Depends(g "layout": layout, # 改图回执:哪些节点、成员的工具变了。画布上看不出来,得明说 "tool_changes": changes, + # 改了图又问了用户(这一轮照样结束、不自动运行):问题跟着 final 交付,前端记进这一轮 + **({"asked": _asked_of(gen.asked)} if gen.asked is not None else {}), } except Exception as e: # noqa: BLE001 final = {"op": "error", "message": f"模型返回的工作流结构有误:{graph_error(e)}", @@ -2409,7 +2459,7 @@ async def app_stream(payload: AppStreamIn, session: AsyncSession = Depends(get_s APP_REQUEST_PROMPT.format(spec=json.dumps(spec, ensure_ascii=False, indent=2), instruction=payload.instruction), await _history_section(session, payload.conversation_id)) applier = AppApplier(spec) - checker = AppChecker(applier, bindings=bindings) + checker = AppChecker(applier, bindings=bindings, scope=(row.scope if row is not None else None) or "shared") started = time.monotonic() gen = Generation(model, system=system, applier=applier, checker=checker, looks=looks, started=started) @@ -2479,25 +2529,84 @@ async def extract_template( 新工作流记下来源(workflows.origin = {run_id, conversation_id?, turn_id?}):从这里发布、再做成应用的那条路 (总方案 A8)事后查得到它出自哪次运行、哪段对话。 """ - from sqlalchemy import select as _sel - - from app.db.models import Run, RunEvent, Workflow, WorkflowVersion + from app.db.models import WorkflowVersion from app.core.artifact_store import graph_hash # 对话只是记进来源:不能用的不让记(D-d),不存在的照旧记下 id await _ensure_conversation_access(session, payload.conversation_id) - run = await session.get(Run, payload.run_id) + try: + path = await extract_run_path(session, payload.run_id) + except PathRefused as e: + raise HTTPException(e.status_code, e.message) from e + run, graph = path.run, path.graph + workflow = Workflow( + name=payload.name or f"{run.workflow_name or '探索'}(提取的模板)", + description=f"从运行 {run.id[:8]} 的实际执行路径提取({path.nodes} 个节点),经人工审核后发布", + graph=graph, + tags=["extracted"], + status="draft", + origin={"run_id": run.id, + **({"conversation_id": payload.conversation_id} if payload.conversation_id else {}), + **({"turn_id": payload.turn_id} if payload.turn_id else {})}, + ) + session.add(workflow) + await session.flush() + session.add( + WorkflowVersion( + workflow_id=workflow.id, version=1, graph=graph, + graph_hash=graph_hash(graph), note=f"从运行 {run.id} 提取", + ) + ) + await session.commit() + return { + "workflow_id": workflow.id, + "name": workflow.name, + "nodes": path.nodes, + "edges": path.edges, + "dropped_nodes": path.dropped, + "source_run": run.id, + } + + +class PathRefused(Exception): + """提取不了:status_code / message 就是 HTTP 回的状态码和 detail。""" + + def __init__(self, status_code: int, message: str) -> None: + super().__init__(message) + self.status_code = status_code + self.message = message + + +@dataclass +class RunPath: + """从一次运行提取出的执行路径:草稿图(已排版)和节点、连线、剪掉的节点数。""" + + run: Any + graph: dict[str, Any] + nodes: int + edges: int + dropped: int + + +async def extract_run_path(session: AsyncSession, run_id: str) -> RunPath: + """一次成功运行实际走过的路径 → 草稿图(确定性):只留执行过的节点和它们之间的边,分支上没走的岔路剪掉,输入值 + 参数化成入口字段的默认值。不落库。「提取成工作流」(/from-run)和蓝图的「从问数据的回答开始」共用。""" + from sqlalchemy import select as _sel + + from app.db.models import Run, RunEvent + + run = await session.get(Run, run_id) if not run: - raise HTTPException(404, "运行记录不存在,可能已被删除") + raise PathRefused(404, "运行记录不存在,可能已被删除") # 没跑通的路径提出来是半截骨架:失败节点之后的步骤一步都不在里面, # 人拿去审改时却看不出它缺了什么 if run.status != "succeeded": - raise HTTPException( + raise PathRefused( 409, "这次运行未成功结束,提取出的执行路径不完整。" "请先让它成功运行一次,再从该次运行提取", ) - if not run.graph.get("nodes"): - raise HTTPException(400, "这次运行没有保存工作流快照,无法提取") + if not (run.graph or {}).get("nodes"): + raise PathRefused(400, "这次运行没有保存工作流快照,无法提取") events = list( ( @@ -2513,7 +2622,7 @@ async def extract_template( if e.type == "edge.taken" and e.node_id } if not executed: - raise HTTPException(400, "这次运行没有节点执行记录") + raise PathRefused(400, "这次运行没有节点执行记录") spec = GraphSpec.model_validate(run.graph) kept_nodes = [n for n in spec.nodes if n.id in executed] @@ -2540,34 +2649,8 @@ async def extract_template( draft_spec = auto_layout( GraphSpec(nodes=kept_nodes, edges=kept_edges, defaults=spec.defaults) ) - graph = draft_spec.model_dump(mode="json") - workflow = Workflow( - name=payload.name or f"{run.workflow_name or '探索'}(提取的模板)", - description=f"从运行 {run.id[:8]} 的实际执行路径提取({len(kept_nodes)} 个节点),经人工审核后发布", - graph=graph, - tags=["extracted"], - status="draft", - origin={"run_id": run.id, - **({"conversation_id": payload.conversation_id} if payload.conversation_id else {}), - **({"turn_id": payload.turn_id} if payload.turn_id else {})}, - ) - session.add(workflow) - await session.flush() - session.add( - WorkflowVersion( - workflow_id=workflow.id, version=1, graph=graph, - graph_hash=graph_hash(graph), note=f"从运行 {run.id} 提取", - ) - ) - await session.commit() - return { - "workflow_id": workflow.id, - "name": workflow.name, - "nodes": len(kept_nodes), - "edges": len(kept_edges), - "dropped_nodes": len(spec.nodes) - len(kept_nodes), - "source_run": run.id, - } + return RunPath(run=run, graph=draft_spec.model_dump(mode="json"), nodes=len(kept_nodes), edges=len(kept_edges), + dropped=len(spec.nodes) - len(kept_nodes)) class ExplainIn(BaseModel): diff --git a/backend/app/api/copilot_blueprint.py b/backend/app/api/copilot_blueprint.py index 5b28e2ad..b7cac612 100644 --- a/backend/app/api/copilot_blueprint.py +++ b/backend/app/api/copilot_blueprint.py @@ -4,22 +4,549 @@ - POST /api/copilot/fill-joints-stream:按模板填生成关节(sql、metric_expr)。TemplateApplier 只收 fill_joint、只收模板声明过的 关节;不同 group 的关节并行填。 -都复用 api/copilot_gen.Generation。包 B1 实现。 +都复用 api/copilot_gen.Generation。权限按蓝图判(blueprints/store.ensure_access):共享蓝图要搭建者;个人蓝图只给拥有者,且 +管理员开了个人应用。 + +**调用次数的预算**(N11):起草蓝图 1 次主调用加最多 2 次查看;填关节每组 1 次调用、各自最多 1 次查看(系统先代为查看 +这一组要用的表,不占次数),不同的组并行。并行调用出错(多半是模型服务限流)的组,等别的组做完再按顺序试一次。 + +**留痕**(P2):蓝图对话每轮落一条对话记录(kind=blueprint 的 Conversation,问题和回答都进历史;助手反问的那一轮回答 +记成反问,meta.asked 同问数据和画布的写法),蓝图的每个 bp_* 操作、每个填上的关节各写一条 blueprint_events。 """ from __future__ import annotations +import asyncio +import copy +import json +import logging +import time from typing import Any -from fastapi import APIRouter, HTTPException +from fastapi import APIRouter, Depends, Header, HTTPException +from pydantic import BaseModel, Field +from sqlalchemy.ext.asyncio import AsyncSession + +from app.db.base import get_session router = APIRouter(prefix="/api/copilot", tags=["copilot-blueprint"]) +logger = logging.getLogger(__name__) + +#: 起草蓝图最多查看几次;填关节每组最多查看几次(N11) +BLUEPRINT_LOOK_LIMIT = 2 +FILL_LOOK_LIMIT = 1 + +# ========================================================================== +# 写给模型的文字 +# ========================================================================== + +BLUEPRINT_SYSTEM_PROMPT = """\ +你是应用蓝图助手。用户说想要一个应用,你把他的话整理成蓝图:几张白话卡片,每张是用户能判断对错的一件事。蓝图之后按场景模板 +确定性地生成工作流和应用,你不写工作流、不写 SQL。 + +卡片(路径是 JSON 指针,值照下面的写法): +- /purpose 目的:一句话,这个应用解决什么问题、给谁用 +- 场景:用 bp_template 选模板(见下面的模板清单),选了之后模板会预置几项默认值 +- /data 看哪些数,每一项:{"id":"gmv","label":"销售额","unit":"元","table":{"source":"库名","table":"表名"}, + "measure":"怎么算(白话或简单聚合)","date":{"column":"业务日期的列","rule":"按支付日"},"filter":"筛选条件","grain":"粒度"} + 对到已发布的口径卡时写 "reuse"(照抄 look 给的复用写法),不写 table +- /cadence 多久更新:{"preset":"daily|weekly|monthly","weekday":1,"day":1,"time":"09:00","tz":"Asia/Shanghai", + "period":"yesterday|last_iso_week|last_month|today|this_iso_week|this_month"}(weekly 写 weekday,1 是周一;monthly 写 day) +- /people 谁来做,每一步:{"id":"finance","label":"财务会签","who":[{"kind":"user|group|slot|initiator","name":"…"}], + "policy":{"kind":"any|all|quorum","m":2},"due":"48 小时","on_timeout":{"action":"remind|escalate|reject","to":[…]}, + "threshold":{"field":"amount","op":">","value":5000}};threshold 只许「字段 比较 常量」,字段要在「填什么」里 +- /fields 填什么,每个字段:{"name":"amount","spec":{"type":"number","title":"金额(元)","minimum":0.01,"required":true}, + "sensitive":false};type 只能是 string、number、integer、boolean、array,x-widget 可写 textarea、select、date 这类控件 +- /writeback 写回哪里:{"capability":"能力登记里的写入能力","mapping":{"参数":"form.字段 | metric.指标 id | rows | '常量'"}, + "confirm":true} +- 谁能看(/access)由用户自己在卡片上定,你不填 + +规则: +- 只提议:你写的每一项都是「待确认」,用户确认了才算数;用户已经确认过的项不要改,除非他这一轮明确要改 +- 只改要改的:已有的项用 bp_set 改(写到项上,例如 /data/0/table),列表用 bp_add 加、bp_remove 删 +- 对到数据:先 look 数据目录里的表(kind table),对到表和业务日期的列,用 bp_set …/why 写一句为什么对到这张表; + 有已发布的口径能直接用的(kind caliber),优先复用,不重写怎么算 +- 缺了只有用户知道的事(按下单日还是支付日、金额线多少、谁来审批),用 bp_ask 问:一次只问一件事、给出候选,这一轮就此结束 +- 不要编表名、列名、人名、能力名;看不到的就问""" + +BLUEPRINT_PROTOCOL_PROMPT = """\ +输出格式(严格遵守): +- 每行一个完整的 JSON 对象,除此之外不输出任何东西——不要 markdown 围栏、不要解释文字 +- 可用操作: + {"op":"plan","summary":"一句话说明打算怎么整理"} ← 第一行 + {"op":"bp_template","template":{"id":"periodic_board","version":1}} + {"op":"bp_set","path":"/purpose","value":"…"} + {"op":"bp_add","path":"/data","value":{"id":"gmv","label":"销售额"}} + {"op":"bp_remove","path":"/data/1"} + {"op":"bp_set","path":"/data/0/table/why","value":"一句话说为什么对到这张表"} + {"op":"bp_ask","question":"销售额按下单日还是支付日算?","options":["按下单日","按支付日"],"path":"/data/0/date"} ← 问了就停 + {"op":"done","explanation":"两三句话说明整理了什么,还缺什么"} ← 最后一行 +- 这句话不需要改蓝图(只是问个问题)时,第一行也是最后一行输出 {"op":"reply","text":"直接回答的内容"} +- 要看表、口径、能力时输出一行 look(用法见下),输出之后就停下等查看结果,拿到结果再接着写""" + +BLUEPRINT_LOOK_WHEN_PROMPT = """\ +什么时候看:对「看哪些数」先看数据目录里的表(kind table);用户说的指标可能已经有人做过时看口径(kind caliber); +定「写回哪里」时看能力(kind capability),只能选写入能力。只改目的、谁来做、填什么的不看""" + +TEMPLATES_HEAD_PROMPT = "场景模板(bp_template 选一个;卡片照约束写):" +PERSONAL_PROMPT = """\ +这是使用者给自己做的个人应用:只读、只有自己看得见、自己点刷新。不能有审批步骤(不写「谁来做」),不能写回别的系统(不写 +「写回哪里」),只能选下面列出的场景、用模板里「个人应用能用」的那一部分。想给别人用,告诉用户做好之后提交给搭建者审核""" +TEMPLATE_PERSONAL_PROMPT = "\n 个人应用能用:{personal}" +TEMPLATE_LINE_PROMPT = "- {id} v{version} {label}:适用于{applies}\n 卡片:{cards}" +BLUEPRINT_REQUEST_PROMPT = "这是蓝图现在的样子:\n{spec}\n\n{issues}用户说:{instruction}" +BLUEPRINT_ISSUES_PROMPT = "试运行前还要补齐的:\n{lines}\n\n" +ANSWERED_PROMPT = "(这是在回答你上一轮的反问:{question})" + +FILL_SYSTEM_PROMPT = """\ +你在给场景模板「{template}」填关节。模板的骨架(节点、连线、别的配置)已经按用户确认的蓝图定好、锁住了,你只能填下面列出的 +这几个位置:取数的 SQL(只读的一条 SELECT)、口径卡的指标式(只许 cell() 取格加算术)。别的位置改不了,改了也不会被采纳。 + +输出格式(严格遵守): +- 每行一个完整的 JSON 对象,除此之外不输出任何东西 +- 可用操作: + {{"op":"plan","summary":"一句话说明打算怎么写"}} ← 第一行 + {{"op":"fill_joint","joint":"关节 id","value":"SQL 或指标式"}} ← 每个关节一行,整段写完 + {{"op":"done","explanation":"一两句话说明写了什么、有什么拿不准的"}} ← 最后一行 +- 要看表结构时输出一行 look(用法见下),输出之后就停下等查看结果;要用的表系统已经代为查看过一次,下面就有 +- 拿不准的按最合理的写,在 done 的说明里写清楚;不要问用户""" +FILL_REQUEST_PROMPT = "这一组要填的关节:\n{joints}\n\n说明:\n{brief}\n\n模板的骨架(只读):\n{graph}" +FILL_JOINT_LINE_PROMPT = "- {id}:{label}({kind})" +FILL_SYSTEM_LOOK_NEED = "这一组关节要用的表" +FILL_KIND_PROMPT = {"sql": "SQL", "metric_expr": "指标式"} + +#: 交付时写进关节状态的说明(界面上照原话显示) +FILL_FAILED_NOTE = "助手填的没通过检查:{reason}。请补充说明或换个说法再试" +FILL_ERROR_NOTE = "助手这一组没填完:{reason}。可以重试" +FILL_STALE_NOTE = "填的时候卡片又改过了,请重新填" + + +class BlueprintStreamIn(BaseModel): + blueprint_id: str + instruction: str = Field(min_length=1, description="用自然语言说想要什么、要怎么改,或者回答助手的反问") + provider: str | None = None + model: str | None = None + + +class FillJointsIn(BaseModel): + blueprint_id: str + #: 只填这几组(不给就填还没填上的那几组) + groups: list[str] | None = None + provider: str | None = None + model: str | None = None + + +def _sse(obj: dict[str, Any]) -> str: + return f"data: {json.dumps(obj, ensure_ascii=False, default=str)}\n\n" + + +def _streaming(gen: Any) -> Any: + from fastapi.responses import StreamingResponse + + return StreamingResponse(gen, media_type="text/event-stream", + headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}) + + +async def _model(session: AsyncSession, provider: str | None, model: str | None) -> tuple[Any, str, Any]: + """按操作流写的模型(同改图助手的额度和退回),和挑选模型的规格。没配接入 400。""" + from app.api import copilot + + request = copilot.GenerateIn(instruction="-", provider=provider, model=model) + try: + op_model, model_id = await copilot._op_model(session, request) + except copilot.ProviderNotConfigured as e: + raise HTTPException(400, copilot._unconfigured(e)) from e + spec = await copilot.copilot_model_spec(session, request, max_tokens=copilot.copilot_context.PICK_MAX_TOKENS) + return op_model, model_id, spec + + +def _templates_text(*, personal: bool = False) -> str: + """模板清单(给助手选场景)。个人蓝图只列能做成个人应用的那几个,并写明能用哪一部分。""" + from app.blueprints.templates import list_templates + + lines = [PERSONAL_PROMPT, TEMPLATES_HEAD_PROMPT] if personal else [TEMPLATES_HEAD_PROMPT] + for t in list_templates(): + if personal and t.personal is None: + continue + lines.append(TEMPLATE_LINE_PROMPT.format(id=t.id, version=t.version, label=t.label, applies=t.applies_when, + cards=";".join(f"{k} {v}" for k, v in t.cards.items())) + + (TEMPLATE_PERSONAL_PROMPT.format(personal=t.personal) if personal else "")) + return "\n".join(lines) + + +def _actor(x_actor: str | None) -> tuple[str | None, bool]: + from app.api.deps import actor_of, actor_verified + + return actor_of(x_actor), actor_verified() + + +# ========================================================================== +# 蓝图对话 +# ========================================================================== + + +async def _conversation(session: AsyncSession, blueprint: Any, actor: str | None, title: str) -> Any: + """这张蓝图的对话(kind=blueprint):没有就建一段挂上去。对话按人隔离的规则照旧(api/conversations)。""" + from app.api.deps import ensure_conversation_access + from app.db.models import Conversation + + if blueprint.conversation_id: + row = await ensure_conversation_access(session, blueprint.conversation_id) + if row is not None: + return row + from app.api.conversations import title_from + + row = Conversation(kind="blueprint", title=blueprint.name or title_from(title), created_by=actor) + session.add(row) + await session.flush() + blueprint.conversation_id = row.id + await session.commit() + return row + + +async def _open_turn(session: AsyncSession, conversation: Any, question: str) -> str: + from sqlalchemy import func, select + + from app.db.base import utcnow + from app.db.models import ConversationTurn + + seq = int((await session.execute(select(func.coalesce(func.max(ConversationTurn.seq), -1)) + .where(ConversationTurn.conversation_id == conversation.id))).scalar_one()) + 1 + turn = ConversationTurn(conversation_id=conversation.id, seq=seq, question=question, status="running") + session.add(turn) + conversation.last_active_at = utcnow() + await session.commit() + return turn.id + + +async def _close_turn(turn_id: str, *, status: str, answer: str = "", error: str = "", + meta: dict[str, Any] | None = None) -> None: + """回填这一轮(另开短会话:流里请求的会话已经不能用了)。""" + from app.db.base import SessionLocal + from app.db.models import ConversationTurn + + async with SessionLocal() as session: + turn = await session.get(ConversationTurn, turn_id) + if turn is None: + return + turn.status, turn.answer, turn.error = status, answer, error + if meta is not None: + turn.meta = meta + await session.commit() + + +def _open_ask(spec: dict[str, Any]) -> tuple[int, dict[str, Any]] | None: + """上一轮的反问还没回答:这一轮用户的话就是在回答它。只看最后一个(更早的反问后面已经有过一轮了)。""" + asks = spec.get("asks") or [] + if asks and not asks[-1].get("answer"): + return len(asks) - 1, asks[-1] + return None + + +def _as_bp_ask(op: dict[str, Any]) -> dict[str, Any]: + """模型写成了通用的 ask(画布、问数据的写法)也认:换成 bp_ask 记进蓝图的反问。""" + options = op.get("options") if isinstance(op.get("options"), list) else [] + return {"op": "bp_ask", "question": str(op.get("question") or ""), + "options": [str(o) for o in options if isinstance(o, (str, int, float))][:6], + **({"path": op["path"]} if isinstance(op.get("path"), str) else {})} @router.post("/blueprint-stream") -async def blueprint_stream() -> Any: - raise HTTPException(501, "尚未实现") +async def blueprint_stream(payload: BlueprintStreamIn, session: AsyncSession = Depends(get_session), + x_actor: str | None = Header(default=None)) -> Any: + """蓝图对话:SSE 推送,形状同 /generate-stream。 + + 事件:model;模型的 plan、bp_* 操作(已经落到服务端维护的那一份蓝图上,来源记 assistant)、look、thinking、heartbeat; + bp_ask(反问,这一轮就此结束);自查的 check;最后 final {blueprint, explanation, issues, asked?}——blueprint 是存好的 + 蓝图(typesBlueprint.Blueprint),issues 是这一轮没采纳的操作(越界、和卡片冲突)。只回答了一句的发 reply 收尾。 + """ + from app.api import copilot + from app.blueprints import store + from app.blueprints.generation import BlueprintApplier, BlueprintChecker + from app.blueprints.ops import blueprint_issues + from app.look.calibers import CaliberKind + from app.look.capabilities import CapabilityKind + from app.look.pick import Picker + from app.look.service import LookService + from app.look.tables import TableKind + + row = await store.load(session, payload.blueprint_id) + actor, verified = _actor(x_actor) + op_model, model_id, pick_spec = await _model(session, payload.provider, payload.model) + conversation = await _conversation(session, row, actor, payload.instruction) + history = await copilot._history_section(session, conversation.id) + # 用户这一轮的话是在回答上一轮的反问:先记下回答(来源 user),助手看到的就是答过的那一份 + instruction = payload.instruction.strip() + if (open_ask := _open_ask(row.spec or {})) is not None: + await store.apply_ops_and_save(session, row, [{"op": "bp_set", "path": f"/asks/{open_ask[0]}/answer", + "value": instruction[:500]}], actor, verified, "user") + instruction = f"{instruction}\n{ANSWERED_PROMPT.format(question=open_ask[1]['question'])}" + turn_id = await _open_turn(session, conversation, payload.instruction) + blueprint_id = row.id + spec = copy.deepcopy(row.spec or {}) + picker = Picker(pick_spec) + personal = row.scope == "personal" + calibers = await CaliberKind.load(session, picker=picker) + # 个人蓝图不写回别的系统:能力只列只读的(同使用者的问数据,P4) + looks = LookService([await TableKind.load(await copilot._sources(session, None), picker=picker), calibers, + await CapabilityKind.load(picker=picker, read_only=personal)]) + system = "\n\n".join(part for part in ( + BLUEPRINT_SYSTEM_PROMPT, _templates_text(personal=personal), await looks.overview(), BLUEPRINT_PROTOCOL_PROMPT, + looks.guide(), BLUEPRINT_LOOK_WHEN_PROMPT) if part) + missing = [i for i in blueprint_issues(spec, for_="trial") if i["level"] == "error"] + human = copilot._with_history(BLUEPRINT_REQUEST_PROMPT.format( + spec=json.dumps(spec, ensure_ascii=False), instruction=instruction, + issues=BLUEPRINT_ISSUES_PROMPT.format(lines="\n".join(f"- {i['path']} {i['message']}" for i in missing)) + if missing else ""), history) + applier = BlueprintApplier(spec, calibers=calibers) + checker = BlueprintChecker(applier) + started = time.monotonic() + gen = copilot.Generation(op_model, system=system, applier=applier, checker=checker, looks=looks, started=started, + look_limit=BLUEPRINT_LOOK_LIMIT) + + async def event_stream(): + from app.db.base import SessionLocal + from app.db.models_blueprints import Blueprint + + yield _sse({"op": "model", "model": model_id}) + try: + async for op in copilot._with_heartbeat(gen.draft(human), started=started): + yield _sse(op) + if applier.replied is not None and not applier.effective and gen.asked is None: + yield _sse(applier.replied) + await _close_turn(turn_id, status="done", answer=str(applier.replied.get("text") or ""), + meta={"looks": looks.records}) + return + if gen.asked is None and gen.done is None and not applier.effective: + raise copilot.CopilotIncomplete("模型没有给出任何修改,也没有说明原因", + hint="蓝图未修改。可以重试,或把需求描述得更具体") + async for op in copilot._with_heartbeat(gen.repair(), phase="repairing", started=started): + yield _sse(op) + remaining = await checker.issues() if gen.asked is None else [] + yield _sse({"op": "check", "status": "failed" if remaining else "passed", "repaired": gen.repaired, + **({"issues": remaining} if remaining else {})}) + asked = _as_bp_ask(gen.asked) if gen.asked is not None else None + async with SessionLocal() as own: + target = await own.get(Blueprint, blueprint_id) + saved = await store.apply_ops_and_save(own, target, [*applier.effective, *([asked] if asked else [])], + actor, verified, "assistant", partial=True) + out = store.blueprint_out(target) + conflicts = [{"code": r["code"], "level": "warning", "path": r["op"].get("path"), + "message": f"助手提的这一处没有采纳:{r['message']}"} for r in saved.refused] + answer = applier.explanation or (asked["question"] if asked else "") + await _close_turn(turn_id, status="done", answer=answer, meta={ + "looks": looks.records, "calls": gen.calls, + **({"asked": {"question": asked["question"], "options": asked["options"]}} if asked else {})}) + yield _sse({"op": "final", "blueprint": out, "explanation": applier.explanation, + "issues": [*applier.refusals(), *conflicts], + **({"asked": {"question": asked["question"], "options": asked["options"]}} if asked else {})}) + except copilot.CopilotIncomplete as e: + await _close_turn(turn_id, status="error", error=str(e)) + yield _sse({"op": "error", "message": f"助手本轮未完成:{e}", "hint": e.hint, "detail": e.detail}) + except Exception as e: # noqa: BLE001 + reason, hint = copilot.explain_error(e) + logger.exception("蓝图助手这一轮没完成") + await _close_turn(turn_id, status="error", error=reason) + yield _sse({"op": "error", "message": f"助手本轮未完成:{reason}", "hint": hint, + "detail": copilot.raw_error(e)}) + + return _streaming(event_stream()) + + +# ========================================================================== +# 填关节 +# ========================================================================== + + +def _slim(graph: dict[str, Any]) -> dict[str, Any]: + """给模型看的骨架:节点的 id、类型、标题、配置和连线,不带坐标。""" + return {"nodes": [{"id": n["id"], "type": n["type"], "label": (n.get("data") or {}).get("label"), + "config": (n.get("data") or {}).get("config")} for n in graph.get("nodes") or []], + "edges": [{k: e.get(k) for k in ("source", "target", "sourceHandle") if e.get(k)} + for e in graph.get("edges") or []]} + + +def _group_tables(spec: dict[str, Any], joints: list[Any], graph: dict[str, Any]) -> list[dict[str, str]]: + """这一组要用的表(系统代为查看):组里取数节点查的库 × 「看哪些数」里对到这个库的表。""" + from app.blueprints.instantiate import node_config + + sources = {str((node_config(graph, j.node_id) or {}).get("tool") or "").removeprefix("db_query__") + for j in joints if j.kind == "sql"} + out: list[dict[str, str]] = [] + for item in spec.get("data") or []: + table = (item.get("table") or {}).get("value") + if isinstance(table, dict) and table.get("source") in sources: + target = {"kind": "table", "source": table["source"], "name": table["table"]} + if target not in out: + out.append(target) + for source in sources: + if not any(t["source"] == source for t in out): + out.append({"kind": "table", "source": source}) + return out @router.post("/fill-joints-stream") -async def fill_joints_stream() -> Any: - raise HTTPException(501, "尚未实现") +async def fill_joints_stream(payload: FillJointsIn, session: AsyncSession = Depends(get_session), + x_actor: str | None = Header(default=None)) -> Any: + """按模板填生成关节:SSE 推送。不同 group 的关节并行填,每组各自一个 Generation,事件都带 group。 + + 事件:model;每组的 group {status: started}、系统代为查看的 look(by=system)、plan、fill_joint、look、check、 + group {status: filled | failed, issues?, message?};最后 final {blueprint, groups, problems}——blueprint 是存好的蓝图, + 图和关节状态都更新了;失败的组照实报,留占位(标「待填」),不挡别的组。""" + from app.api import copilot + from app.blueprints import store + from app.blueprints.generation import JOINT_REFUSED, TemplateApplier, TemplateChecker + from app.blueprints.instantiate import filled_from, generated_groups, instantiate + from app.blueprints.templates import get_template + from app.data.sqlcheck import load_checkers + from app.look.pick import Picker + from app.look.service import LookService + from app.look.tables import TableKind + + row = await store.load(session, payload.blueprint_id) + if not ((row.spec or {}).get("template") or None): + raise HTTPException(409, "这张蓝图还没选场景,没有要填的关节:先说说要做什么,或者从场景模板开始") + actor, verified = _actor(x_actor) + op_model, model_id, pick_spec = await _model(session, payload.provider, payload.model) + spec = copy.deepcopy(row.spec) + # 填报登记要按记录表的结构写 SQL:起草这边的那一版还没建的先建(和试运行同一个入口;草稿不影响线上那一版) + from app.api.coded import CodedHTTPException + from app.records.store import RecordsRefused + + try: + ctx = await store.instantiate_context(session, row, create_records=True) + except RecordsRefused as e: + await session.rollback() + raise CodedHTTPException(422, e.message, e.code) from e + await session.commit() + keep = filled_from(spec, row.joints or {}, graph=ctx.get("graph"), records=ctx.get("records")) + inst = instantiate(spec, filled=keep, **ctx) + groups = generated_groups(inst) + wanted = [g for g in (payload.groups or []) if g in groups] if payload.groups else \ + [g for g, joints in groups.items() if any(inst.joints[j.id]["status"] != "filled" for j in joints)] + if payload.groups and not wanted: + raise HTTPException(400, f"这张蓝图没有这些关节组:{'、'.join(payload.groups)}(有的是:{'、'.join(groups) or '没有'})") + sources = await copilot._sources(session, None) + checkers = await load_checkers(session, sources) + tables = await TableKind.load(sources, picker=Picker(pick_spec)) + template = get_template(str(spec["template"]["id"])) + system = FILL_SYSTEM_PROMPT.format(template=template.label if template else spec["template"]["id"]) \ + + await copilot.copilot_context.section(LookService([tables])) + "\n\n" + LookService([tables]).guide() + blueprint_id = row.id + started = time.monotonic() + + queue: asyncio.Queue[dict[str, Any] | None] = asyncio.Queue() + results: dict[str, dict[str, Any]] = {} + + async def fill(group: str) -> None: + joints = groups[group] + applier = TemplateApplier(copy.deepcopy(inst.graph), inst.joint_defs, joints) + checker = TemplateChecker(applier, skeleton=inst.skeleton, sources=sources, checkers=checkers) + looks = LookService([tables]) + gen = copilot.Generation(op_model, system=system, applier=applier, checker=checker, looks=looks, + started=started, look_limit=FILL_LOOK_LIMIT) + await queue.put({"op": "group", "group": group, "status": "started", "joints": [j.id for j in joints]}) + try: + request = FILL_REQUEST_PROMPT.format( + joints="\n".join(FILL_JOINT_LINE_PROMPT.format(id=j.id, label=j.label, kind=FILL_KIND_PROMPT[j.kind]) + for j in joints), + brief=inst.briefs.get(group, ""), graph=json.dumps(_slim(inst.skeleton), ensure_ascii=False)) + targets = _group_tables(spec, joints, inst.graph) + if targets: + looked = await looks.look({"op": "look", "need": FILL_SYSTEM_LOOK_NEED, "targets": targets}, + by="system") + if looked.record is not None: + await queue.put({**looked.record, "group": group}) + request = f"{request}\n\n{looked.text}" + async for op in gen.draft(request): + await queue.put({**op, "group": group}) + async for op in gen.repair(): + await queue.put({**op, "group": group}) + # 越界被拒的不算这一组没填好:没采纳的那一处骨架原样留着,照实列给人看(refusals) + remaining = [i for i in await checker.issues() if i["code"] != JOINT_REFUSED] + results[group] = {"values": dict(applier.values), "issues": remaining, "error": None, + "refusals": applier.refusals(), "calls": gen.calls} + await queue.put({"op": "group", "group": group, "status": "failed" if remaining else "filled", + **({"issues": remaining} if remaining else {})}) + except Exception as e: # noqa: BLE001 - 一组失败不挡别的组,照实报 + reason, _ = copilot.explain_error(e) + logger.exception("填关节的一组没完成:%s", group) + results[group] = {"values": {}, "issues": [], "error": reason, "refusals": [], "calls": gen.calls} + await queue.put({"op": "group", "group": group, "status": "failed", "message": reason}) + + async def run_all() -> None: + try: + await asyncio.gather(*(fill(g) for g in wanted)) + # 并行调用出错的组(多半是模型服务限流)退回串行:等别的组做完,再按顺序各试一次 + for g in [g for g in wanted if results.get(g, {}).get("error")]: + await queue.put({"op": "group", "group": g, "status": "retrying"}) + await fill(g) + finally: + await queue.put(None) + + async def drained(): + while (item := await queue.get()) is not None: + yield item + + async def event_stream(): + from app.core.artifact_store import graph_hash + from app.db.base import SessionLocal + from app.db.models_blueprints import Blueprint + from app.plain import with_plain + + yield _sse({"op": "model", "model": model_id}) + task = asyncio.create_task(run_all()) + try: + async for item in copilot._with_heartbeat(drained(), phase="building", started=started): + yield _sse(item) + await task + filled = dict(keep) + notes: dict[str, str] = {} + for g in wanted: + result = results.get(g) or {"values": {}, "issues": [], "error": "没有结果"} + ids = [j.id for j in groups[g]] + if result["error"] is None and not result["issues"]: + filled.update({jid: result["values"][jid] for jid in ids if jid in result["values"]}) + continue + why = (FILL_ERROR_NOTE.format(reason=result["error"]) if result["error"] else + FILL_FAILED_NOTE.format(reason=result["issues"][0].get("message") or "")) + notes.update({jid: why for jid in ids if jid not in keep}) + async with SessionLocal() as own: + target = await own.get(Blueprint, blueprint_id) + ctx_now = await store.instantiate_context(own, target) + done = instantiate(target.spec or {}, filled=filled, **ctx_now) + for g in wanted: + if done.basis.get(g) != inst.basis.get(g): + # 填的时候卡片又改过:这一组按旧的说明填的,不算数 + filled = {k: v for k, v in filled.items() if k not in {j.id for j in groups[g]}} + notes.update({j.id: FILL_STALE_NOTE for j in groups[g]}) + done = instantiate(target.spec or {}, filled=filled, **ctx_now) + joints = {jid: ({**state, "note": notes[jid]} if jid in notes and state["status"] != "filled" else state) + for jid, state in done.joints.items()} + for g in wanted: + for j in groups[g]: + state = joints.get(j.id) or {} + await store.record_event(own, target, op="fill_joint", actor=actor, verified=verified, data={ + "joint": j.id, "group": g, "by": "assistant", "status": state.get("status"), + **({"note": state["note"]} if state.get("note") else {})}) + target.graph = done.graph + target.graph_hash = graph_hash(done.graph) + target.joints = joints + target.updated_by = actor + await own.commit() + out = store.blueprint_out(target) + yield _sse({"op": "final", "blueprint": out, + "groups": {g: {"status": "filled" if not (results.get(g) or {}).get("error") + and not (results.get(g) or {}).get("issues") else "failed", + "calls": (results.get(g) or {}).get("calls", 0), + "refusals": (results.get(g) or {}).get("refusals", [])} for g in wanted}, + "problems": [with_plain(p) for p in done.problems]}) + except Exception as e: # noqa: BLE001 + reason, hint = copilot.explain_error(e) + logger.exception("填关节没完成") + yield _sse({"op": "error", "message": f"助手本轮未完成:{reason}", "hint": hint, + "detail": copilot.raw_error(e)}) + finally: + if not task.done(): + task.cancel() + + return _streaming(event_stream()) diff --git a/backend/app/api/copilot_gen.py b/backend/app/api/copilot_gen.py index f33abc79..e88c1b41 100644 --- a/backend/app/api/copilot_gen.py +++ b/backend/app/api/copilot_gen.py @@ -36,8 +36,9 @@ from app.providers.budget import cut_off as _cut_off #: 自查最多交回去改几轮。一轮只花一次"只输出改动"的调用;两轮还改不好,多半是需求本身有歧义,该让人看了 SELF_CHECK_ROUNDS = 2 -#: 读到这几种操作就停下:done 说完了,look 要查看,ask 要等用户回答 -_STOP_OPS = ("done", "look", "ask") +#: 读到这几种操作就停下:done 说完了,look 要查看,ask 要等用户回答(蓝图助手的反问是 bp_ask,normal-user-apps N2) +_ASK_OPS = ("ask", "bp_ask") +_STOP_OPS = ("done", "look", *_ASK_OPS) #: 不占次数的查看回话(need 没写、次数用完)连着来几次就不再接着写:模型在原地打转,再要下去只是花钱 _IDLE_LOOKS = 2 @@ -418,6 +419,11 @@ APP_HUMAN_ONLY = frozenset({ "app.slot_principal_unknown", "app.reconciler_unbound", "app.acl_empty", "app.acl_principal_unknown", "app.notify_channel_missing", "app.process_unsafe", "app.view_source_empty", "subgraph_version_unpublished", "subgraph_version_retired", + # 个人应用(docs/design/normal-user-apps.md N7、N6):视图来源和应用范围对不上、图违反使用者的约束要回到蓝图改, + # 隐藏哪块是作者的决定——润色只改呈现,改不了视图来源,也不该替人取消隐藏 + "app.view_source_personal", "app.hidden_bound", "personal.policy", + # 看板表格逐行列出记录表(N8):公开不公开是作者的决定,助手不替人把表格换掉 + "app.records_rows_exposed", }) @@ -533,9 +539,11 @@ POLISH_REFUSED = "app.polish_refused" class AppChecker: """应用的自查:app/apps/lint.lint_app 的 error,去掉只有人能处理的(APP_HUMAN_ONLY),交回模型改。""" - def __init__(self, applier: AppApplier, *, bindings: dict[str, Any] | None = None) -> None: + def __init__(self, applier: AppApplier, *, bindings: dict[str, Any] | None = None, scope: str = "shared") -> None: self.applier = applier self.bindings = bindings or {} + #: 应用的范围(App.scope):个人应用按个人应用的规则查(apps/lint.lint_app 的 scope) + self.scope = scope async def lint(self) -> list[dict[str, Any]]: """全部问题(各级都在),交付时列出来。另开短会话:流里请求的会话已经不能用了。""" @@ -543,7 +551,7 @@ class AppChecker: from app.db.base import SessionLocal async with SessionLocal() as session: - return list(await app_lint.lint_app(session, self.applier.spec, self.bindings)) + return list(await app_lint.lint_app(session, self.applier.spec, self.bindings, scope=self.scope)) async def issues(self) -> list[dict[str, Any]]: """交回模型改的:应用检查的 error(去掉只有人能处理的),加上这之前越界被拒、还没交回过的操作。""" @@ -572,8 +580,10 @@ class Generation: """ def __init__(self, model: Any, *, system: str, applier: Applier, checker: Checker | None = None, - looks: LookService | None = None, started: float | None = None) -> None: + looks: LookService | None = None, started: float | None = None, look_limit: int = LOOK_LIMIT) -> None: self.model = model + #: 起草阶段最多查看几次。蓝图、填关节按调用次数的预算收得更紧(normal-user-apps N11) + self.look_limit = look_limit self.system = system self.applier = applier self.checker = checker @@ -587,7 +597,7 @@ class Generation: self.calls = 0 async def draft(self, request: str) -> AsyncIterator[dict[str, Any]]: - async for op in self._converse(request, LookBudget(LOOK_LIMIT), repair=False): + async for op in self._converse(request, LookBudget(self.look_limit), repair=False): yield op async def repair(self, rounds: int = SELF_CHECK_ROUNDS) -> AsyncIterator[dict[str, Any]]: @@ -635,7 +645,7 @@ class Generation: yield op elif kind == "look": look = op - elif kind == "ask": + elif kind in _ASK_OPS: self.asked = op yield op elif repair and kind in ("plan", "done"): diff --git a/backend/app/api/datasources.py b/backend/app/api/datasources.py index 5b15bf67..2680e59b 100644 --- a/backend/app/api/datasources.py +++ b/backend/app/api/datasources.py @@ -195,6 +195,15 @@ def _is_upload(row: DataSource) -> bool: return (row.origin or "manual") == "upload" +def _is_records(row: DataSource) -> bool: + """记录表(docs/design/normal-user-apps.md N8)登记的只读源:连接、结构由平台维护,随应用的表单变,不在这里改、删。""" + return (row.origin or "manual") == "records" + + +_RECORDS_LOCKED = "记录表由应用的表单维护,不能在这里修改「{}」。要改字段,请到应用的「填什么」里改" +_RECORDS_KEEP = "记录表由应用维护,不能在这里删除:旧记录要一直留着备查" + + async def _snapshot_infos(session: AsyncSession, rows: list[DataSource]) -> dict[str, dict[str, Any]]: """各上传源当前版本的摘要:{源 id: {id, created_at, file_name, raw_state, mode, periods, period_start, period_end, activated_at}}。两次查询取齐,不逐个查。 @@ -479,7 +488,14 @@ async def update_source( ) -> DataSourceOut: row = await _get_or_404(session, source_id) data = payload.model_dump(exclude_unset=True) - if _is_upload(row): + if _is_records(row): + # 连接、只读、结构都由记录表维护(records/tables.py);说明、遮罩列这类照常能改 + changed = _locked_changes(row, data) + if changed: + raise HTTPException(422, _RECORDS_LOCKED.format("」「".join(changed))) + for key in _UPLOAD_LOCKED: + data.pop(key, None) + elif _is_upload(row): # 上传源的连接由版本底座维护(见 _locked_changes) changed = _locked_changes(row, data) if changed: @@ -527,6 +543,8 @@ async def update_source( @router.delete("/{source_id}", status_code=204) async def delete_source(source_id: str, session: AsyncSession = Depends(get_session)) -> None: row = await _get_or_404(session, source_id) + if _is_records(row): + raise HTTPException(409, _RECORDS_KEEP) # 上传源的导入记录置 retired 留作审计;库文件和原件交给回收,被运行引用的版本会保留。只读进程(没拿到 # 版本存储的守卫)不删上传源:retire_source 要删隔离文件、放弃暂存区(第 8 节遗留项 5)。 # 手工登记的源没有导入记录、配方、暂存区和隔离文件,根本不碰版本存储:不调 retire_source,只读进程里也照常 @@ -718,6 +736,12 @@ async def test_draft( return {"ok": False, "error": f"不支持「{payload.kind}」类型的数据库", "hint": f"目前支持:{'、'.join(SUPPORTED_KINDS)}", "detail": "", "elapsed_ms": 0, "url": ""} saved = await session.get(DataSource, payload.id) if payload.id else None + if saved is not None and _is_records(saved): + # 记录表:连接字段由应用维护(同上传源),测的就是登记的那个文件 + changed = _locked_changes(saved, payload.model_dump(exclude_unset=True, include=set(_UPLOAD_LOCKED))) + if changed: + return _refused(_RECORDS_LOCKED.format("」「".join(changed))) + return await _test_saved(session, saved) if saved is not None and _is_upload(saved): # 上传源:连接字段由系统维护。改了就和保存一样拒;没改,测的就是它当前版本的快照, # 不拿表单里的路径去连——否则带上一个上传源的 id,就能把上传目录里任何文件拿来试 @@ -765,6 +789,9 @@ async def _test_saved(session: AsyncSession, row: DataSource) -> dict[str, Any]: result = _refused(str(e)) else: result = await _probe(view, cached=True) + elif _is_records(row): + # 记录表的文件在应用自己的数据目录里,是平台登记的只读源,照常测 + result = await _probe(row, cached=True) elif _in_app_files(row.kind, row.database): result = _refused(_APP_FILES_REFUSED) else: @@ -806,6 +833,8 @@ async def introspect_source( row = await _get_or_404(session, source_id) if _is_upload(row): raise HTTPException(409, "上传的表格无需重新探查,重新上传即可更新") + if _is_records(row): + raise HTTPException(409, "记录表的结构由应用的表单维护,无需重新探查") try: cache = await introspect_mod.introspect(row, schema=schema) except Exception as e: # noqa: BLE001 diff --git a/backend/app/api/files.py b/backend/app/api/files.py index f10ea5f2..dcabf378 100644 --- a/backend/app/api/files.py +++ b/backend/app/api/files.py @@ -1,24 +1,106 @@ -"""文件的上传、下载、删除(docs/design/normal-user-apps.md §3.8)。包 B3 实现。""" +"""文件的上传、下载、删除(docs/design/normal-user-apps.md §3.8)。存放、绑定、读权限都在 app/files/store.py。 + +- POST /api/files:multipart,file + context(JSON:{app_id, entry} | {task_id} | {blueprint_id},可带 field 说明是哪个 + 字段),交回引用 {file_id, name, size, sha256, type}。大小上限同上传表格(max_upload_mb),类型按白名单、按内容核对; + 能用那个入口、能处理那条待办、能改那个蓝图的人才传得上来; +- GET /api/files/{id}:下载。读得到绑定的那次运行、看得到绑定的那一行记录的人,以及上传的人自己; +- DELETE /api/files/{id}:只能删自己传的、还没提交的。 +""" from __future__ import annotations +import asyncio +import dataclasses from typing import Any +from urllib.parse import quote -from fastapi import APIRouter, HTTPException +from fastapi import APIRouter, Depends, File, Form, Header, UploadFile +from fastapi.responses import Response +from sqlalchemy.ext.asyncio import AsyncSession + +from app.api.coded import CodedHTTPException +from app.api.deps import Principal, actor_of, current_principal +from app.db.base import get_session +from app.db.models_blueprints import StoredFile +from app.files import store router = APIRouter(prefix="/api/files", tags=["files"]) +#: 后台预抽取文字的任务:留着引用,不让它们半路被回收 +_WARMING: set[asyncio.Task[Any]] = set() + + +def _principal(x_actor: str | None) -> Principal: + """这次请求的身份。关登录时 username 换成自报的署名(X-Actor):上传人、只能删自己的都按它认(同 api/apps.py)。""" + principal = current_principal() + if principal.mode == "off" and principal.username is None: + return dataclasses.replace(principal, username=actor_of(x_actor)) + return principal + + +def _refused(e: store.FileRefused) -> CodedHTTPException: + return CodedHTTPException(e.status, e.message, e.code, field=e.field) + @router.post("", status_code=201) -async def upload() -> dict[str, Any]: - """multipart:file + context({app_id, entry} | {task_id} | {blueprint_id}),交回引用 {file_id, name, size, sha256, type}。""" - raise HTTPException(501, "尚未实现") +async def upload(file: UploadFile | None = File(None), context: str = Form(""), + session: AsyncSession = Depends(get_session), + x_actor: str | None = Header(default=None)) -> dict[str, Any]: + """multipart:file + context({app_id, entry} | {task_id} | {blueprint_id}),交回引用 + {file_id, name, size, sha256, type}。""" + from app.api.datasources import read_upload + from app.files.text import warm + + principal = _principal(x_actor) + try: + ctx = store.parse_context(context) + setting = await store.check_context(session, principal, ctx) + except store.FileRefused as e: + raise _refused(e) from e + if file is None: + raise CodedHTTPException(422, "请选择要上传的文件", "files.missing") + raw = await read_upload(file) + name = file.filename or "附件" + try: + mime = store.type_of(name, raw) + if problem := store.accept_problem(setting, name=name, mime=mime, size=len(raw)): + raise store.FileRefused(415, "files.type_not_accepted", problem, field=ctx.get("field")) + row = await store.save(session, raw, name, uploaded_by=principal.username, context=ctx) + except store.FileRefused as e: + raise _refused(e) from e + # 先在后台把文字抽一遍:运行里 file_text 多半直接读缓存 + task = asyncio.create_task(warm(row.sha256, row.name, row.mime)) + _WARMING.add(task) + task.add_done_callback(_WARMING.discard) + return store.ref_of(row) @router.get("/{file_id}") -async def download(file_id: str) -> Any: - raise HTTPException(501, "尚未实现") +async def download(file_id: str, session: AsyncSession = Depends(get_session), + x_actor: str | None = Header(default=None)) -> Response: + principal = _principal(x_actor) + row = await session.get(StoredFile, file_id) + if row is None: + raise CodedHTTPException(404, "文件不存在,可能没有提交、已被清理", "files.not_found") + if not await store.readable(session, principal, row): + if row.bound_run_id is None and row.bound_record is None: + # 没提交的文件只有上传的人看得到:别人不该知道它在不在 + raise CodedHTTPException(404, "文件不存在,可能没有提交、已被清理", "files.not_found") + raise CodedHTTPException(403, "没有下载这个文件的权限:只有能看到它所属的那次运行或那一行记录的人才能下载", + "files.forbidden") + data = await asyncio.to_thread(store.read_blob, row.sha256) + if data is None: + raise CodedHTTPException(409, "文件内容不在了,或者和登记的不一致(可能被改动过),不能下载", "files.content_lost") + return Response(content=data, media_type=row.mime, headers={ + "Content-Disposition": f"attachment; filename*=UTF-8''{quote(row.name)}", + "X-Content-Type-Options": "nosniff", + "Cache-Control": "private, no-store", + }) @router.delete("/{file_id}", status_code=204) -async def delete(file_id: str) -> None: - raise HTTPException(501, "尚未实现") +async def delete(file_id: str, session: AsyncSession = Depends(get_session), + x_actor: str | None = Header(default=None)) -> None: + try: + await store.remove(session, _principal(x_actor), file_id) + except store.FileRefused as e: + raise _refused(e) from e diff --git a/backend/app/api/personal.py b/backend/app/api/personal.py index 43c389c2..5959ad13 100644 --- a/backend/app/api/personal.py +++ b/backend/app/api/personal.py @@ -1,43 +1,185 @@ """个人应用与审核(docs/design/normal-user-apps.md §3.9)、页面编辑的候选(§2.6),以及记录的逐行查看(§3.7 records_list)。 要在 apps.router 之前登记(共用 /api/apps 前缀,路径不冲突)。包 B4 实现个人应用和候选,记录列表由包 B3 实现。 + +- POST /api/blueprints/{id}/save-personal:存成个人应用(拥有者;使用者要管理员开了开关)→ {app_id, blueprint} +- POST /api/blueprints/{id}/copy:审核的搭建者取共享副本 → Blueprint +- POST /api/apps/{id}/refresh:个人应用刷新一次(探索运行,受每日上限)→ {run_id, remaining} +- POST /api/apps/{id}/submit-review {to, note?}:提交审核 → {task_id} +- GET /api/apps/{id}/candidates:页面编辑「加一张数据卡片」的候选(要 manage)→ {items} +- GET /api/apps/{id}/records:记录表的逐行,按看的人实时过滤(包 B3,records/listing.py)→ RecordsPage + +业务规则都在 blueprints/personal.py、apps/candidates.py,这里只把拒绝换成 HTTP 响应(带 personal.* 机器码)。 """ from __future__ import annotations +import dataclasses from typing import Any -from fastapi import APIRouter, HTTPException +from fastapi import APIRouter, Depends, Header, HTTPException, Query +from fastapi.responses import JSONResponse +from pydantic import BaseModel, Field +from sqlalchemy.ext.asyncio import AsyncSession + +from app.api.coded import CodedHTTPException +from app.api.deps import Principal, actor_of, current_principal +from app.db.base import get_session router = APIRouter(prefix="/api", tags=["personal"]) _TODO = "尚未实现" +def _principal(x_actor: str | None) -> Principal: + """这次请求的身份。关登录时 username 换成自报的署名(X-Actor),同应用接口:拥有者、发起人按它认。""" + principal = current_principal() + if principal.mode == "off" and principal.username is None: + return dataclasses.replace(principal, username=actor_of(x_actor)) + return principal + + +def _refused(e: Any) -> HTTPException: + """blueprints/personal.PersonalRefused → HTTP(带 personal.* 机器码的回 {detail, code})。""" + if e.code: + return CodedHTTPException(e.status_code, e.message, e.code) + return HTTPException(e.status_code, e.message) + + +def blueprint_out(row: Any) -> dict[str, Any]: + """蓝图的接口形状只有一份(api/blueprints.blueprint_out,带蓝图检查的白话):存成个人应用、取副本交回的也是它。""" + from app.api.blueprints import blueprint_out as out + + return out(row) + + +async def _blueprint(session: AsyncSession, blueprint_id: str) -> Any: + from app.db.models_blueprints import Blueprint + + return await session.get(Blueprint, blueprint_id) + + +async def _personal_app(session: AsyncSession, app_id: str, principal: Principal) -> Any: + """个人应用:只有拥有者看得见。不存在、不是你的,一律 404(不说它在不在);不是个人应用的另说(409)。""" + from app.apps.access import app_role + from app.blueprints.personal import APP_GONE + from app.db.models_apps import App + + app = await session.get(App, app_id) + if app is None or await app_role(session, principal, app) is None: + raise HTTPException(404, APP_GONE) + return app + + +# -------------------------------------------------------------------------- +# 存成个人应用、共享副本 +# -------------------------------------------------------------------------- + + @router.post("/blueprints/{blueprint_id}/save-personal") -async def save_personal(blueprint_id: str) -> dict[str, Any]: - raise HTTPException(501, _TODO) +async def save_personal(blueprint_id: str, session: AsyncSession = Depends(get_session), + x_actor: str | None = Header(default=None)) -> Any: + from app.blueprints.personal import PersonalRefused, save_personal as save + + principal = _principal(x_actor) + try: + app = await save(session, await _blueprint(session, blueprint_id), principal=principal) + except PersonalRefused as e: + if e.issues: + # 蓝图检查没过(缺项、模板不能做成个人应用……):问题带白话原样交回,卡片上逐条标出来 + return JSONResponse(status_code=e.status_code, + content={"detail": e.message, "code": e.code, "issues": e.issues}) + raise _refused(e) from e + return {"app_id": app.id, "blueprint": blueprint_out(await _blueprint(session, blueprint_id))} @router.post("/blueprints/{blueprint_id}/copy", status_code=201) -async def copy_for_review(blueprint_id: str) -> dict[str, Any]: - raise HTTPException(501, _TODO) +async def copy_for_review(blueprint_id: str, session: AsyncSession = Depends(get_session), + x_actor: str | None = Header(default=None)) -> dict[str, Any]: + from app.blueprints.personal import PersonalRefused, copy_for_review as copy + + try: + row = await copy(session, await _blueprint(session, blueprint_id), principal=_principal(x_actor)) + except PersonalRefused as e: + raise _refused(e) from e + return blueprint_out(row) + + +# -------------------------------------------------------------------------- +# 刷新、提交审核 +# -------------------------------------------------------------------------- @router.post("/apps/{app_id}/refresh") -async def refresh(app_id: str) -> dict[str, Any]: - raise HTTPException(501, _TODO) +async def refresh(app_id: str, session: AsyncSession = Depends(get_session), + x_actor: str | None = Header(default=None)) -> dict[str, Any]: + """个人应用刷新一次:交回这次运行(正在刷新的接上那一次)和今天还能刷新几次。""" + from app.blueprints.personal import PersonalRefused, refresh as run_refresh + from app.engine.launch import LaunchRefused + + principal = _principal(x_actor) + app = await _personal_app(session, app_id, principal) + try: + run, remaining = await run_refresh(session, app, principal=principal) + except PersonalRefused as e: + raise _refused(e) from e + except LaunchRefused as e: + raise (CodedHTTPException(e.status_code, e.message, e.code) if e.code + else HTTPException(e.status_code, e.message)) from e + return {"run_id": run.id, "remaining": remaining} + + +class ReviewIn(BaseModel): + #: 交给谁:[{kind: user|group, name}] + to: list[dict[str, str]] = Field(default_factory=list) + note: str | None = Field(default=None, max_length=2000) @router.post("/apps/{app_id}/submit-review") -async def submit_review(app_id: str) -> dict[str, Any]: - raise HTTPException(501, _TODO) +async def submit_review(app_id: str, payload: ReviewIn, session: AsyncSession = Depends(get_session), + x_actor: str | None = Header(default=None)) -> dict[str, Any]: + from app.blueprints.personal import PersonalRefused, submit_review as submit + + principal = _principal(x_actor) + app = await _personal_app(session, app_id, principal) + try: + task = await submit(session, app, to=payload.to, note=payload.note, principal=principal) + except PersonalRefused as e: + raise _refused(e) from e + return {"task_id": task.id} + + +# -------------------------------------------------------------------------- +# 页面编辑的候选 +# -------------------------------------------------------------------------- @router.get("/apps/{app_id}/candidates") -async def candidates(app_id: str) -> dict[str, Any]: - raise HTTPException(501, _TODO) +async def candidates(app_id: str, session: AsyncSession = Depends(get_session), + x_actor: str | None = Header(default=None)) -> dict[str, Any]: + """「加一张数据卡片」的候选:要这个应用的管理权限(个人应用的拥有者算管理)。按草稿列(页面编辑改的是草稿)。""" + from app.api.apps import _app + from app.apps.candidates import app_candidates + + app, _ = await _app(session, app_id, _principal(x_actor), "manage") + return {"items": await app_candidates(session, app.draft or {})} + + +# -------------------------------------------------------------------------- +# 记录的逐行查看(包 B3) +# -------------------------------------------------------------------------- @router.get("/apps/{app_id}/records") -async def records(app_id: str) -> dict[str, Any]: - raise HTTPException(501, _TODO) +async def records(app_id: str, table: str | None = None, cursor: str | None = None, history: bool = False, + who: str | None = None, limit: int = Query(default=50, ge=1, le=200), + session: AsyncSession = Depends(get_session), + x_actor: str | None = Header(default=None)) -> dict[str, Any]: + """记录表的逐行(组件 records_list):每次打开按看的人实时过滤,不走封存。use 只看自己提交的,observe、manage 看 + 全部(who=mine 只看自己的);history 连被更正过的行一起列。形状同前端的 RecordsPage(records/listing.py)。""" + from app.api.apps import _app + from app.records.listing import page + + principal = _principal(x_actor) + app, role = await _app(session, app_id, principal, "use") + return await page(session, app, principal=principal, role=role, table=table, who=who, cursor=cursor, + history=history, limit=limit) diff --git a/backend/app/api/schedules.py b/backend/app/api/schedules.py index 327405f2..35e8cca1 100644 --- a/backend/app/api/schedules.py +++ b/backend/app/api/schedules.py @@ -461,25 +461,43 @@ async def list_schedules(session: AsyncSession = Depends(get_session)) -> dict[s @router.post("", status_code=201) async def create_schedule(request: Request, session: AsyncSession = Depends(get_session), x_actor: str | None = Header(default=None)) -> dict[str, Any]: - body = await _body(request) - name = _name(body.get("name")) - workflow_id = _workflow_id(body.get("workflow_id")) - cron_expr, tz = _cron(body.get("cron")), _timezone(body.get("timezone")) - run_class = _run_class(body.get("run_class", "formal")) - template = _template(body.get("input_template")) - enabled = _enabled(body.get("enabled", True)) - overlap = _overlap(body.get("overlap", "skip")) - grace = _grace(body.get("misfire_grace_s", DEFAULT_GRACE_S)) - hook = _new_webhook(body.get("webhook")) - workflow = await _check_workflow(session, workflow_id, run_class, template) - row = Schedule(name=name, workflow_id=workflow_id, workflow_name=workflow.name, cron=cron_expr, timezone=tz, - run_class=run_class, input_template=template, enabled=enabled, overlap=overlap, - misfire_grace_s=grace, next_run_at=service.next_run(cron_expr, tz, enabled), - created_by=actor_of(x_actor), **_webhook_columns(hook)) + row = await create_schedule_row(session, await _body(request), actor=actor_of(x_actor)) + return await _schedule_out(session, row) + + +def schedule_values(body: dict[str, Any]) -> dict[str, Any]: + """建定时任务的请求体 → 规范化之后的列(不含工作流名、下一次触发),逐项校验,不对抛 422(带 field)。只读, + 不碰库:发布单的预检用它「只检查」,建任务的接口和发布单建任务都先过它。""" + values = {"name": _name(body.get("name")), "workflow_id": _workflow_id(body.get("workflow_id")), + "cron": _cron(body.get("cron")), "timezone": _timezone(body.get("timezone")), + "run_class": _run_class(body.get("run_class", "formal")), + "input_template": _template(body.get("input_template")), + "enabled": _enabled(body.get("enabled", True)), "overlap": _overlap(body.get("overlap", "skip")), + "misfire_grace_s": _grace(body.get("misfire_grace_s", DEFAULT_GRACE_S))} + return {**values, "webhook": _new_webhook(body.get("webhook"))} + + +def template_problem(template: dict[str, str], graph: Any, workflow_name: str) -> str | None: + """输入模板对不上这张图的入口字段(字段名、必填项):说明;对得上为 None。发布单的预检按将要发布的图查。""" + try: + service.check_fields(template, service.input_fields(graph), workflow_name) + except service.TemplateError as e: + return str(e) + return None + + +async def create_schedule_row(session: AsyncSession, body: dict[str, Any], *, actor: str | None) -> Schedule: + """校验并建一个定时任务(提交)。建任务的接口和发布单(停用着建,应用发布后再启用)共用。""" + values = schedule_values(body) + hook = values.pop("webhook") + workflow = await _check_workflow(session, values["workflow_id"], values["run_class"], values["input_template"]) + row = Schedule(**values, workflow_name=workflow.name, + next_run_at=service.next_run(values["cron"], values["timezone"], values["enabled"]), + created_by=actor, **_webhook_columns(hook)) session.add(row) await session.commit() await session.refresh(row) - return await _schedule_out(session, row) + return row @router.get("/{schedule_id}") @@ -555,6 +573,38 @@ async def update_schedule(schedule_id: str, request: Request, return await _schedule_out(session, await _get(session, schedule_id)) +async def retime(session: AsyncSession, row: Schedule, body: dict[str, Any]) -> Schedule: + """按新的设置改一个已有的定时任务(提交):名称、cron、时区、输入模板,校验同建任务;启用状态不动。cron、时区真改了才 + 按 PATCH 同一个规则重算下一次触发。发布单给已经发布过的蓝图再发一版时用它沿用原来的任务,不另建一个(两个任务会 + 在同一时刻各发起一次)。""" + values = schedule_values({**body, "workflow_id": row.workflow_id, "enabled": row.enabled}) + workflow = await _check_workflow(session, row.workflow_id, row.run_class, values["input_template"]) + changed = {"name": values["name"], "cron": values["cron"], "timezone": values["timezone"], + "input_template": values["input_template"], "workflow_name": workflow.name} + if values["cron"] != row.cron or values["timezone"] != row.timezone: + changed["next_run_at"] = _next_after_edit(row, values["cron"], values["timezone"], row.enabled) + await session.execute(update(Schedule).where(Schedule.id == row.id) + .values(**changed, version=row.version + 1).execution_options(synchronize_session=False)) + await session.commit() + await session.refresh(row) + return row + + +async def set_enabled(session: AsyncSession, row: Schedule, enabled: bool) -> Schedule: + """启用、停用一个定时任务(提交),下一次触发按 PATCH 同一个规则算,版本号加一。发布单在应用发布之后用它启用 + 先停用着建的任务;已经是这个状态的不动。""" + if row.enabled == enabled: + return row + await session.execute( + update(Schedule).where(Schedule.id == row.id) + .values(enabled=enabled, next_run_at=_next_after_edit(row, row.cron, row.timezone, enabled), + version=row.version + 1).execution_options(synchronize_session=False)) + await session.commit() + # 只重读这一行:调用方(发布单)同一个会话里还拿着别的对象,不能整个会话过期 + await session.refresh(row) + return row + + def _next_after_edit(row: Schedule, cron_expr: str, tz: str, enabled: bool) -> datetime | None: """改了 cron、时区或启用状态之后的下一次触发。 diff --git a/backend/app/api/settings.py b/backend/app/api/settings.py index 1717a79f..83fcaaf7 100644 --- a/backend/app/api/settings.py +++ b/backend/app/api/settings.py @@ -664,14 +664,17 @@ async def notify_settings(session: AsyncSession) -> dict[str, Any]: # -------------------------------------------------------------------------- -# 应用:按需视图的每日上限(D-j) +# 应用:按需视图的每日上限(D-j)、使用者能不能建个人应用(docs/design/normal-user-apps.md N7) # -------------------------------------------------------------------------- #: 设置里 apps 这一组。on_demand_daily_limit:每个应用每天最多发起几次按需视图的正式运行(app/apps/resolve.py 的 -#: daily_limit 读它),点「刷新」才运行、同一个键只运行一份之外,再兜一道花费的底。0 表示不再发起按需运行 +#: daily_limit 读它),点「刷新」才运行、同一个键只运行一份之外,再兜一道花费的底。0 表示不再发起按需运行;个人应用的刷新 +#: 共用这一项,按人计(blueprints/personal.py)。 +#: user_personal_apps:开了登录时使用者能不能建个人应用、刷新、提交审核(默认关,同问数据的开关;搭建者及以上不受它管)。 +#: 关登录时它照样生效:关着就没有个人应用的入口。只有管理员能改(整个设置接口的改动都要管理员) APPS_GROUP = "apps" -APPS_DEFAULTS: dict[str, Any] = {"on_demand_daily_limit": 200} -APPS_SETTING_LABEL = {"on_demand_daily_limit": "按需视图每日上限"} +APPS_DEFAULTS: dict[str, Any] = {"on_demand_daily_limit": 200, "user_personal_apps": False} +APPS_SETTING_LABEL = {"on_demand_daily_limit": "按需视图每日上限", "user_personal_apps": "使用者可以建个人应用"} #: 上限的上限:再大就等于不限,要不限的不该靠这一项 APPS_DAILY_LIMIT_MAX = 100_000 @@ -688,17 +691,22 @@ def apps_problem(value: Any) -> str | None: if key not in APPS_DEFAULTS: return (f"「应用」设置中不支持「{key}」,可设置的项:" + "、".join(f"「{APPS_SETTING_LABEL[k]}」" for k in APPS_DEFAULTS)) - if not _daily_limit_ok(item): + if key == "user_personal_apps": + if not isinstance(item, bool): + return f"「{APPS_SETTING_LABEL[key]}」只能是开或关,当前为「{item}」" + elif not _daily_limit_ok(item): return (f"「{APPS_SETTING_LABEL[key]}」需要是 0 到 {APPS_DAILY_LIMIT_MAX:,} 之间的整数(0 表示不再发起按需运行)," f"当前为「{item}」") return None def apps_values(stored: Any) -> dict[str, Any]: - """库里存的(或刚写进来的)apps 一组 → 补齐默认;存坏了的项按默认。""" + """库里存的(或刚写进来的)apps 一组 → 补齐默认;存坏了的项按默认(个人应用的开关存坏了按关)。""" stored = stored if isinstance(stored, dict) else {} limit = stored.get("on_demand_daily_limit") - return {"on_demand_daily_limit": limit if _daily_limit_ok(limit) else APPS_DEFAULTS["on_demand_daily_limit"]} + personal = stored.get("user_personal_apps") + return {"on_demand_daily_limit": limit if _daily_limit_ok(limit) else APPS_DEFAULTS["on_demand_daily_limit"], + "user_personal_apps": personal if isinstance(personal, bool) else APPS_DEFAULTS["user_personal_apps"]} async def apps_settings(session: AsyncSession) -> dict[str, Any]: @@ -750,7 +758,7 @@ DEFAULT_SETTINGS: dict[str, Any] = { NOTIFY_GROUP: notify_values(None), # 起草模型:数据目录起草、按配方导入的 AI 起草用的模型,留空沿用助手的模型 CATALOG_DRAFT_GROUP: catalog_draft_values(None), - # 应用:按需视图的每日上限(管理员在设置页改) + # 应用:按需视图的每日上限、使用者能不能建个人应用(管理员在设置页改) APPS_GROUP: apps_values(None), } diff --git a/backend/app/api/templates.py b/backend/app/api/templates.py index 440f05db..4e41b4bd 100644 --- a/backend/app/api/templates.py +++ b/backend/app/api/templates.py @@ -1,13 +1,32 @@ -"""场景模板列表(docs/design/normal-user-apps.md §3.3):GET /api/templates。包 B1 实现。""" +"""场景模板列表(docs/design/normal-user-apps.md §3.3):GET /api/templates。登录即可看(新建应用的「从场景模板开始」)。 + +模板登记在导入这个模块时核对一遍(blueprints/instantiate.registry_problems):首批都登记了、关节类型认得、每个模板的 +示例蓝图实例化出来过得了画布校验、骨架比对没有差异。缺一样启动即报错(N3:模板定义、实例化、测试三样都要给)。 +""" from __future__ import annotations from typing import Any -from fastapi import APIRouter, HTTPException +from fastapi import APIRouter + +from app.blueprints.instantiate import registry_problems +from app.blueprints.templates import list_templates router = APIRouter(prefix="/api/templates", tags=["templates"]) +_PROBLEMS = registry_problems() +if _PROBLEMS: + raise RuntimeError("场景模板登记不完整:" + ";".join(_PROBLEMS)) + + +def template_out(template: Any) -> dict[str, Any]: + """一个模板交给前端的样子(frontend/src/typesBlueprint.ts 的 TemplateInfo)。""" + return {"id": template.id, "version": template.version, "label": template.label, + "description": template.description, "applies_when": template.applies_when, + "cards": [{"card": card, "note": note} for card, note in template.cards.items()], + "personal": template.personal, "tags": list(template.tags)} + @router.get("") -async def list_templates() -> dict[str, Any]: - raise HTTPException(501, "尚未实现") +async def list_templates_api() -> dict[str, Any]: + return {"items": [template_out(t) for t in list_templates()]} diff --git a/backend/app/api/workflows.py b/backend/app/api/workflows.py index f68c6fb4..044a9297 100644 --- a/backend/app/api/workflows.py +++ b/backend/app/api/workflows.py @@ -449,8 +449,7 @@ async def publish_workflow( workflow = await session.get(Workflow, workflow_id) if not workflow: raise HTTPException(404, _GONE) - if payload.level != "governed" and workflow.published_version and \ - (await _published_levels(session, [workflow_id])).get(workflow_id) == "governed": + if await downgrades_governed(session, workflow, payload.level): # 把受管工作流降成已发布,之后的正式运行就不再过治理门禁:和以受管级别发布是同一级的决定(Q8) _require_admin("把受管工作流降为已发布") @@ -466,49 +465,75 @@ async def publish_workflow( if not snapshot: raise HTTPException(404, f"不存在 v{version} 版本:画布上的修改还没有保存,请先保存再发布") - try: - spec = GraphSpec.model_validate(snapshot.graph) - except Exception as e: # noqa: BLE001 - return {"ok": False, "issues": [{"level": "error", "message": f"无法解析工作流结构:{graph_error(e)}"}]} + issues = await gate_issues(session, snapshot.graph, payload.level) + if issues is None: + return {"ok": False, "issues": [{"level": "error", "message": _unparsed(snapshot.graph)}]} + if any(i["level"] == "error" for i in issues): + return {"ok": False, "level": payload.level, "version": version, "issues": issues} + return {**await commit_publish(session, workflow, snapshot, payload.level, actor_of(x_actor)), + "issues": issues} # 剩下的都是警告 + +async def downgrades_governed(session: AsyncSession, workflow: Workflow, level: str) -> bool: + """这次发布会不会把受管工作流降成已发布(Q8:只给管理员)。发布接口和发布单的预检共用。""" + return level != "governed" and bool(workflow.published_version) and \ + (await _published_levels(session, [workflow.id])).get(workflow.id) == "governed" + + +def _unparsed(graph: Any) -> str: + try: + GraphSpec.model_validate(graph) + except Exception as e: # noqa: BLE001 + return f"无法解析工作流结构:{graph_error(e)}" + return "无法解析工作流结构" + + +async def gate_issues(session: AsyncSession, graph: Any, level: str) -> list[dict[str, Any]] | None: + """发布这张图会遇到的问题(validate + 门禁),只读:不改库、不发布。图不成形时为 None。 + 发布接口和发布单的预检(blueprints/publish_plan.py)共用,口径只有这一份。""" + try: + spec = GraphSpec.model_validate(graph) + except Exception: # noqa: BLE001 + return None checkers = await _sql_checkers(session, spec) providers = await _providers(session, spec) with with_subgraphs(await load_subgraphs(session, spec)): - issues = [i.model_dump() for i in publish_issues(spec, level=payload.level, checkers=checkers, - providers=providers)] - if any(i["level"] == "error" for i in issues): - return {"ok": False, "level": payload.level, "version": version, "issues": issues} + return [i.model_dump() for i in publish_issues(spec, level=level, checkers=checkers, providers=providers)] + +async def commit_publish(session: AsyncSession, workflow: Workflow, snapshot: WorkflowVersion, level: str, + actor: str | None) -> dict[str, Any]: + """把这一版立为正式版本并提交(调用方先过了 gate_issues、权限)。发布接口和发布单共用。""" # 发布时用到的能力的治理版本(F5)。在改这一版之前取:能力登记缺了的要另开会话同步、提交,这个会话手里不能先有写 from app.capabilities.registry import capability_versions_for from app.db.base import utcnow from app.engine.launch import graph_tool_names + spec = GraphSpec.model_validate(snapshot.graph) capabilities = await capability_versions_for(session, graph_tool_names(snapshot.graph)) if not snapshot.graph_hash: snapshot.graph_hash = graph_hash(snapshot.graph) # 级别记在这一版上:之后改画布(status 退回 draft),从这一版发起的正式运行照样按发布时的级别出具 - snapshot.level = payload.level + snapshot.level = level # 发布时的目录版本也记在这一版上:重新发布同一版等于按现在的目录重新认可它,跟着更新 snapshot.catalog_versions = await catalog_versions_for(session, spec) # 发布人、发布时间、用到的能力版本也记在这一版上(F5):工作流上的 published_by 只记最近一次。退役过的版本重新 # 发布等于重新认可它,退役信息清掉 snapshot.published_at = utcnow() - snapshot.published_by = actor_of(x_actor) + snapshot.published_by = actor snapshot.capability_versions = capabilities snapshot.retired_at = snapshot.retired_by = snapshot.retire_note = None - workflow.status = payload.level - workflow.published_version = version - workflow.published_by = actor_of(x_actor) + workflow.status = level + workflow.published_version = snapshot.version + workflow.published_by = actor await session.commit() return { "ok": True, - "level": payload.level, - "version": version, + "level": level, + "version": snapshot.version, "graph_hash": snapshot.graph_hash, "published_by": workflow.published_by, "catalog_versions": recorded_versions(snapshot.catalog_versions), - "issues": issues, # 剩下的都是警告 } @@ -595,19 +620,23 @@ async def publish_check( 只读:不改库、不发布。发布弹窗一打开就调它,不用等点了发布才知道被拦。 """ + return await check_graph(session, await _draft(session, workflow_id, payload), payload.level) + + +async def check_graph(session: AsyncSession, graph: Any, level: str) -> dict[str, Any]: + """发布前检查的本体:问题加上能怎么修(每条问题带 fix 的种类 auto / choice / assist)。只读。 + 发布前检查接口和发布单的预检共用(发布单按修复的种类把问题分给「你来定」「助手可以修」)。""" from app.engine.autofix import check - graph = await _draft(session, workflow_id, payload) try: spec = GraphSpec.model_validate(graph) except Exception as e: # noqa: BLE001 - return _unreadable(payload.level, e) + return _unreadable(level, e) versions, cards = await _gate_context(session, spec) checkers = await _sql_checkers(session, spec) providers = await _providers(session, spec) with with_subgraphs(await load_subgraphs(session, spec)): - return check(spec, level=payload.level, versions=versions, cards=cards, checkers=checkers, - providers=providers) + return check(spec, level=level, versions=versions, cards=cards, checkers=checkers, providers=providers) @router.post("/{workflow_id}/autofix") diff --git a/backend/app/apps/access.py b/backend/app/apps/access.py index a0ce020e..c3121f13 100644 --- a/backend/app/apps/access.py +++ b/backend/app/apps/access.py @@ -5,6 +5,9 @@ - builder:所有应用至少 observe(能用、能看全部实例);自己建的、或者有 manage 授权的才 manage; - user:按授权(给本人、给所在的组、给所有人)取最高的那一档,最高到 observe:搭建、发布、绑定岗位、授权、钩子、按草稿 预览、改派催办都不给 user 角色(§3.12),授给它的 manage 按 observe 算。没有授权就看不到这个应用。 +- 个人应用(scope=personal,docs/design/normal-user-apps.md N7):只有拥有者能用,按 manage 算(改页面、刷新、提交审核); + 别人一律没有权限、看不到,管理员也一样——管理员只在应用列表里看得到它存在、能归档(can_archive),不看内容(P4)。 + 个人应用没有授权(不能分享),授权表里不会有它。 """ from __future__ import annotations @@ -38,7 +41,25 @@ def granted_role(principal: Principal, grants: list[Any]) -> str | None: return best +def personal_role(principal: Principal, app: Any) -> str | None: + """个人应用上这个人的权限:拥有者 manage,别人 None。关登录时全部放行(没有可信的身份,同共享应用)。""" + if principal.mode == "off": + return "manage" + return "manage" if app.owner and principal.username == app.owner else None + + +def is_personal(app: Any) -> bool: + return getattr(app, "scope", "shared") == "personal" + + +def can_archive(principal: Principal, app: Any, role: str | None) -> bool: + """能不能归档:管理权限;个人应用另外管理员也能(看不到内容,但能把它收起来)。""" + return at_least(role, "manage") or (is_personal(app) and principal.role == "admin") + + def role_of(principal: Principal, app: Any, grants: list[Any]) -> str | None: + if is_personal(app): + return personal_role(principal, app) if principal.mode == "off" or principal.role == "admin": return "manage" granted = granted_role(principal, grants) @@ -55,6 +76,8 @@ async def grants_of(session: AsyncSession, app_id: str) -> list[AppGrant]: async def app_role(session: AsyncSession, principal: Principal, app: Any) -> str | None: + if is_personal(app): + return personal_role(principal, app) if principal.mode == "off" or principal.role == "admin": return "manage" return role_of(principal, app, await grants_of(session, app.id)) diff --git a/backend/app/apps/candidates.py b/backend/app/apps/candidates.py new file mode 100644 index 00000000..7c5e8c88 --- /dev/null +++ b/backend/app/apps/candidates.py @@ -0,0 +1,66 @@ +"""页面编辑的候选(docs/design/normal-user-apps.md N6、§4.5「加一张数据卡片」):GET /api/apps/{id}/candidates。 + +从草稿里各视图固定的版本(共享应用是工作流版本,个人应用是蓝图上的图)列出能加的数据卡片:口径卡的指标、趋势、报告、 +取数节点的表格,规则同派生(apps/derive.data_candidates)。每个候选交回一个可以直接 app_add 的组件:绑定写好了视图, +id 在这份草稿里不重名。草稿里已经有一模一样的(同类组件、同一个绑定)不再列——要再显示一次,把隐藏的那个取消隐藏。 + +实例视图不列:实例页上的数跟着某一次实例走,「加一张数据卡片」是给应用页的。还没有图的视图(固定的版本不存在、试运行 +派生的草稿没有版本)也不列,界面照实写「没有能加的」。 +""" +from __future__ import annotations + +import copy +import json +from typing import Any + +from sqlalchemy.ext.asyncio import AsyncSession + +#: 候选组件 id 的前缀 +PREFIX = "add" +#: 视图来源在候选分组里的说法:草稿里不止一个视图时,分组写清是哪一种来源的数 +SOURCE_TEXT = {"latest_sealed": "最近一次出数", "on_demand": "按条件查看", "exploratory": "最近一次刷新"} + + +def _key(comp: dict[str, Any]) -> tuple[str, str]: + return str(comp.get("type")), json.dumps(comp.get("bind"), sort_keys=True, ensure_ascii=False) + + +async def app_candidates(session: AsyncSession, spec: dict[str, Any]) -> list[dict[str, Any]]: + """[{kind: metric|series|report|table, label, group, component}],按视图、再按派生规则的顺序。""" + from app.apps.derive import data_candidates + from app.apps.pins import load_pins + from app.apps.tree import components, node_map + + pins = await load_pins(session, spec) + views = {vid: v for vid, v in (spec.get("views") or {}).items() + if isinstance(v, dict) and ((v.get("source") or {}).get("kind")) != "instance"} + present = {_key(c) for c, _, _ in components(spec)} + taken = {str(c.get("id")) for c, _, _ in components(spec)} | { + str(p.get("id")) for p in spec.get("pages") or [] if isinstance(p, dict)} + out: list[dict[str, Any]] = [] + for vid, view in views.items(): + source = view.get("source") or {} + state = pins.get(source.get("pin")) + graph = state.graph if state is not None else {} + if not graph: + continue + for item in data_candidates(node_map(graph), vid, PREFIX): + comp = copy.deepcopy(item["component"]) + if _key(comp) in present: + continue + comp["id"] = _unique(f"{comp['id']}_{vid}" if len(views) > 1 else comp["id"], taken) + taken.add(comp["id"]) + group = item["group"] + if len(views) > 1: + group = f"{group} · {SOURCE_TEXT.get(str(source.get('kind')), vid)}" + out.append({"kind": item["kind"], "label": item["label"], "group": group, "component": comp}) + return out + + +def _unique(base: str, taken: set[str]) -> str: + if base not in taken: + return base + n = 2 + while f"{base}_{n}" in taken: + n += 1 + return f"{base}_{n}" diff --git a/backend/app/apps/catalog.py b/backend/app/apps/catalog.py index e3642ddc..163198f2 100644 --- a/backend/app/apps/catalog.py +++ b/backend/app/apps/catalog.py @@ -5,7 +5,8 @@ 每个组件登记:名字、中文名、类别、版本、props 的 JSON Schema、允许的绑定种类、能不能有子组件。 props 里每一项都写 title(属性面板上的中文名),取值不直观的另写 description;枚举写 x-enum-labels(和 enum 按位置 -对应,同表单 agentlab.form/1 的写法)。这几样是注解,不参与校验。 +对应,同表单 agentlab.form/1 的写法);给人看的文字(标题、名称、说明)标 x-text,应用页上直接改的「改文字」只改这几项, +列名、换算这类写给解析器的字符串不标。这几样是注解,不参与校验。 服务端校验器和解析器由 app/apps/ 的实现按名字注册(BE-3);开发者扩展组件时,目录项、校验器、解析器、前端渲染器 四样都要给,缺一样启动即报错(check_registry)。 """ @@ -22,11 +23,17 @@ def _props(**properties: Any) -> dict[str, Any]: def _text(title: str, **more: Any) -> dict[str, Any]: - return {"type": "string", "maxLength": 200, "title": title, **more} + """给人看的一行字(标题、名称、单位):x-text 标出来,页面上直接改的「改文字」改它(normal-user-apps N6)。""" + return {"type": "string", "maxLength": 200, "title": title, "x-text": True, **more} def _long(title: str) -> dict[str, Any]: - return {"type": "string", "maxLength": 4000, "title": title} + return {"type": "string", "maxLength": 4000, "title": title, "x-text": True} + + +def _code(title: str, **more: Any) -> dict[str, Any]: + """写给解析器的短字符串(列名、换算):不是给人看的文字,「改文字」不碰。""" + return {"type": "string", "maxLength": 200, "title": title, **more} def _enum(title: str, **labels: str) -> dict[str, Any]: @@ -56,7 +63,7 @@ COMPONENTS: list[dict[str, Any]] = [ "bindings": ["metric", "cell"], "props": _props(label=_text("名称"), unit=_text("单位", description="绑定单元格时写在数下面;绑定指标时数里已经带着口径卡的单位"), - conv=_text("换算", description="万、亿、pct(百分比)、int(取整)或 .N(保留 N 位小数)"))}, + conv=_code("换算", description="万、亿、pct(百分比)、int(取整)或 .N(保留 N 位小数)"))}, {"name": "series", "label": "趋势", "category": "display", "version": 1, "children": False, "bindings": ["series"], "props": _props(label=_text("名称"), chart=_CHART)}, {"name": "table", "label": "表格", "category": "display", "version": 1, "children": False, @@ -68,7 +75,7 @@ COMPONENTS: list[dict[str, Any]] = [ limit={"type": "integer", "minimum": 1, "title": "最多显示行数"})}, {"name": "chart", "label": "图表", "category": "display", "version": 1, "children": False, "bindings": ["query"], - "props": _props(title=_text("标题"), chart=_CHART, x=_text("横轴列"), + "props": _props(title=_text("标题"), chart=_CHART, x=_code("横轴列"), y={"type": "array", "items": {"type": "string", "maxLength": 200}, "maxItems": 4, "title": "纵轴列", "description": "最多 4 列"})}, {"name": "report", "label": "报告", "category": "display", "version": 1, "children": False, @@ -103,6 +110,12 @@ COMPONENTS: list[dict[str, Any]] = [ "bindings": ["task"], "props": _props()}, {"name": "action_status", "label": "动作状态", "category": "process", "version": 1, "children": False, "bindings": ["action"], "props": _props(label=_text("名称"))}, + # 记录表的逐行(docs/design/normal-user-apps.md N8):每次打开按看的人实时过滤(use 只看自己提交的),不走封存 + {"name": "records_list", "label": "记录列表", "category": "process", "version": 1, "children": False, + "bindings": [], "props": _props(title=_text("标题"), + table=_code("记录表", description="不填就是这个应用的第一张记录表"), + who=_enum("显示谁的", mine="我提交的", all="全部(要有查看全部的权限)"), + limit={"type": "integer", "minimum": 1, "maximum": 200, "title": "最多显示几条"})}, ] BY_NAME: dict[str, dict[str, Any]] = {c["name"]: c for c in COMPONENTS} diff --git a/backend/app/apps/derive.py b/backend/app/apps/derive.py index e368d3cf..069b9672 100644 --- a/backend/app/apps/derive.py +++ b/backend/app/apps/derive.py @@ -39,7 +39,7 @@ def _safe(text: str) -> str: async def derive_app(session: AsyncSession, workflow_id: str, version: int, *, name: str | None = None) -> dict[str, Any]: """返回一份 agentlab.app/1 spec(未发布的草稿)。""" - from app.apps.pins import PinState, write_nodes + from app.apps.pins import PinState from app.apps.versions import version_row from app.db.models import Schedule, Workflow @@ -50,7 +50,38 @@ async def derive_app(session: AsyncSession, workflow_id: str, version: int, *, n if row is None: raise DeriveRefused(404, f"「{workflow.name}」不存在 v{version} 版本") state = PinState(alias=PIN, pin={"workflow_id": workflow_id, "version": version}, workflow=workflow, row=row) - graph = row.graph or {} + schedule = (await session.execute(select(Schedule).where( + Schedule.workflow_id == workflow_id, Schedule.run_class == "formal", Schedule.enabled.is_(True)) + .order_by(Schedule.created_at))).scalars().first() + return await _derive(session, row.graph or {}, title=workflow.name, name=name, + description=workflow.description or "", + pin={"alias": PIN, "workflow_id": workflow_id, "version": version, "graph_hash": state.hash, + "level": state.level}, + schedule_id=schedule.id if schedule else None) + + +async def derive_from_graph(session: AsyncSession, graph: dict[str, Any], *, name: str, description: str = "", + workflow_id: str | None = None, blueprint_id: str | None = None, + schedule_id: str | None = None) -> dict[str, Any]: + """从一张还没发布的图派生应用草稿(docs/design/normal-user-apps.md N4:蓝图的试运行、发布单建应用之前)。派生规则和 + derive_app 同一份,只是钉住项没有版本号(version 为空)、graph_hash 取这张图的哈希。挂在工作流上的写 workflow_id, + 还没有工作流的(蓝图刚实例化出来的图、个人应用)写 blueprint。schedule_id 给了,看板的视图绑这个定时任务。 + + 这样的草稿发布不了(应用检查报 app.pin_unpublished):发布单在工作流发布之后把钉住项换成那一版再建应用。""" + from app.core.artifact_store import graph_hash + + pin: dict[str, Any] = {"alias": PIN, "version": None, "graph_hash": graph_hash(graph), "level": None} + pin.update({"workflow_id": workflow_id} if workflow_id else {"blueprint": blueprint_id}) + return await _derive(session, graph, title=name, name=name, description=description, pin=pin, + schedule_id=schedule_id) + + +async def _derive(session: AsyncSession, graph: dict[str, Any], *, title: str, name: str | None, description: str, + pin: dict[str, Any], schedule_id: str | None) -> dict[str, Any]: + """派生规则本身:title 是工作流(或蓝图)的名字,写进首页标题、入口的说法;pin 是钉住项(还缺 use), + schedule_id 是看板的视图要绑的定时任务(没有就看正式运行)。""" + from app.apps.pins import write_nodes + nodes = node_map(graph) fields = input_fields(graph) humans = {nid: n for nid, n in nodes.items() if n["type"] == "human"} @@ -60,10 +91,9 @@ async def derive_app(session: AsyncSession, workflow_id: str, version: int, *, n lookups = all(getattr(cap, "lookup", None) for cap in caps.values()) process = bool(humans or writes) spec: dict[str, Any] = { - "format": APP_FORMAT, "name": name or workflow.name, "description": workflow.description or "", + "format": APP_FORMAT, "name": name or title, "description": description, "icon": "app", - "pins": [{"alias": PIN, "workflow_id": workflow_id, "version": version, "graph_hash": state.hash, - "level": state.level, "use": "process" if process else "view"}], + "pins": [{**pin, "use": "process" if process else "view"}], "slots": {}, "entries": [], "forms": {}, "task_ui": {}, "views": {}, "pages": [], "hooks": [], "notify": [], } for ref in slot_refs(graph, writes): @@ -77,20 +107,17 @@ async def derive_app(session: AsyncSession, workflow_id: str, version: int, *, n names = list(spec["forms"][ENTRY]["properties"]) first = next((n for n in names if n in spec["forms"][ENTRY]["required"]), names[0] if names else None) spec["entries"].append({ - "id": ENTRY, "label": f"发起{workflow.name}" if process else "按条件运行", "pin": PIN, + "id": ENTRY, "label": f"发起{title}" if process else "按条件运行", "pin": PIN, "form": {"$ref": f"#/forms/{ENTRY}"}, "map": {n: f"form.{n}" for n in names}, - **({"instance_title": {"pattern": f"{workflow.name}·{{{first}}}", "fields": [first]}} + **({"instance_title": {"pattern": f"{title}·{{{first}}}", "fields": [first]}} if first and re.fullmatch(r"[A-Za-z0-9_㐀-鿿]+", first) else {}), }) if not process: - schedule = (await session.execute(select(Schedule).where( - Schedule.workflow_id == workflow_id, Schedule.run_class == "formal", Schedule.enabled.is_(True)) - .order_by(Schedule.created_at))).scalars().first() spec["views"][VIEW] = {"source": {"kind": "latest_sealed", "pin": PIN, - "from": f"schedule:{schedule.id}" if schedule else "formal"}} + "from": f"schedule:{schedule_id}" if schedule_id else "formal"}} if spec["entries"]: spec["views"][INSTANCE_VIEW] = {"source": {"kind": "instance"}} - spec["pages"].append({"id": "home", "title": workflow.name, + spec["pages"].append({"id": "home", "title": title, "body": ([] if process else _results(nodes, VIEW, "home")) + _entries(spec)}) if spec["entries"]: spec["pages"].append({"id": "instance", "title": "实例", "body": [ @@ -108,33 +135,84 @@ async def derive_app(session: AsyncSession, workflow_id: str, version: int, *, n def _results(nodes: dict[str, dict[str, Any]], view: str, prefix: str) -> list[dict[str, Any]]: - """看结果的那几块:印章、口径卡的指标(分栏)、报告、取数节点的表格。""" + """看结果的那几块:印章、口径卡的指标(分栏)、报告、取数节点的表格。每一块怎么绑定见 _metric_block 等,页面编辑的 + 「加一张数据卡片」(data_candidates)用的是同一份规则。""" body: list[dict[str, Any]] = [{"id": f"{prefix}_stamp", "type": "stamp", "bind": {"view": view}}] for nid, node in nodes.items(): - if node["type"] != "metrics": - continue - metrics = [m for m in node["config"].get("metrics") or [] if isinstance(m, dict) and m.get("id")] + metrics = _card_metrics(node) if not metrics: continue body.append({"id": f"{prefix}_kpis_{_safe(nid)}", "type": "section", "props": {"title": node["title"][:200]}, "children": [{"id": f"{prefix}_cols_{_safe(nid)}", "type": "columns", - "props": {"count": min(len(metrics), 4)}, "children": [ - {"id": f"{prefix}_m_{_safe(nid)}_{_safe(str(m['id']))}", "type": "metric", - "props": {"label": str(m.get("name") or m["id"])[:200], - **({"unit": str(m["unit"])[:200]} if m.get("unit") else {})}, - "bind": {"view": view, "metric": f"{nid}.{m['id']}"}} - for m in metrics]}]}) + "props": {"count": min(len(metrics), 4)}, + "children": [_metric_block(nid, m, view, prefix) for m in metrics]}]}) for nid, node in nodes.items(): if node["type"] == "report": - body.append({"id": f"{prefix}_report_{_safe(nid)}", "type": "report", "props": {"title": node["title"][:200]}, - "bind": {"view": view, "report": nid}}) + body.append(_report_block(nid, node, view, prefix)) for nid, node in nodes.items(): - if node["type"] == "tool" and str(node["config"].get("tool") or "").startswith("db_query__"): - body.append({"id": f"{prefix}_table_{_safe(nid)}", "type": "table", "props": {"title": node["title"][:200]}, - "bind": {"view": view, "query": {"node": nid}}}) + if _query_node(node): + body.append(_table_block(nid, node, view, prefix)) return body +def _card_metrics(node: dict[str, Any]) -> list[dict[str, Any]]: + """口径卡上声明了 id 的指标;不是口径卡的是空的。""" + if node["type"] != "metrics": + return [] + return [m for m in node["config"].get("metrics") or [] if isinstance(m, dict) and m.get("id")] + + +def _query_node(node: dict[str, Any]) -> bool: + """取数节点:调用工具节点绑的是数据源查询。""" + return node["type"] == "tool" and str(node["config"].get("tool") or "").startswith("db_query__") + + +def _metric_block(nid: str, metric: dict[str, Any], view: str, prefix: str) -> dict[str, Any]: + return {"id": f"{prefix}_m_{_safe(nid)}_{_safe(str(metric['id']))}", "type": "metric", + "props": {"label": str(metric.get("name") or metric["id"])[:200], + **({"unit": str(metric["unit"])[:200]} if metric.get("unit") else {})}, + "bind": {"view": view, "metric": f"{nid}.{metric['id']}"}} + + +def _series_block(nid: str, metric: dict[str, Any], view: str, prefix: str) -> dict[str, Any]: + return {"id": f"{prefix}_s_{_safe(nid)}_{_safe(str(metric['id']))}", "type": "series", + "props": {"label": str(metric.get("name") or metric["id"])[:200]}, + "bind": {"view": view, "series": f"{nid}.{metric['id']}"}} + + +def _report_block(nid: str, node: dict[str, Any], view: str, prefix: str) -> dict[str, Any]: + return {"id": f"{prefix}_report_{_safe(nid)}", "type": "report", "props": {"title": node["title"][:200]}, + "bind": {"view": view, "report": nid}} + + +def _table_block(nid: str, node: dict[str, Any], view: str, prefix: str) -> dict[str, Any]: + return {"id": f"{prefix}_table_{_safe(nid)}", "type": "table", "props": {"title": node["title"][:200]}, + "bind": {"view": view, "query": {"node": nid}}} + + +def data_candidates(nodes: dict[str, dict[str, Any]], view: str, prefix: str) -> list[dict[str, Any]]: + """页面编辑「加一张数据卡片」能加的(docs/design/normal-user-apps.md N6):[{kind, label, group, component}], + component 可以直接交给 app_add。规则和派生的结果块(_results)同一份——口径卡的每个指标、报告、取数节点的表格—— + 另加每个指标的趋势(派生不放趋势:新应用只有一期数)。group 是出自哪个节点(口径卡、报告、取数的标题)。""" + out: list[dict[str, Any]] = [] + for nid, node in nodes.items(): + for metric in _card_metrics(node): + name = str(metric.get("name") or metric["id"])[:200] + out.append({"kind": "metric", "label": name, "group": node["title"][:200], + "component": _metric_block(nid, metric, view, prefix)}) + out.append({"kind": "series", "label": f"{name}的趋势", "group": node["title"][:200], + "component": _series_block(nid, metric, view, prefix)}) + for nid, node in nodes.items(): + if node["type"] == "report": + out.append({"kind": "report", "label": node["title"][:200], "group": node["title"][:200], + "component": _report_block(nid, node, view, prefix)}) + for nid, node in nodes.items(): + if _query_node(node): + out.append({"kind": "table", "label": node["title"][:200], "group": node["title"][:200], + "component": _table_block(nid, node, view, prefix)}) + return out + + def _entries(spec: dict[str, Any]) -> list[dict[str, Any]]: out: list[dict[str, Any]] = [] for entry in spec["entries"]: diff --git a/backend/app/apps/entries.py b/backend/app/apps/entries.py index 060fd075..56bd7c69 100644 --- a/backend/app/apps/entries.py +++ b/backend/app/apps/entries.py @@ -9,6 +9,7 @@ import re from typing import Any from app.apps.tree import entry_of, pins_by_alias, resolve_form +from app.files import store as files_store #: 入口发起被拒时的机器码 APP_GONE = "app_not_found" @@ -112,12 +113,31 @@ async def start_entry(app_id: str, entry_id: str, values: dict[str, Any], princi form = resolve_form(spec, entry.get("form")) or {"type": "object", "properties": {}} if errors := validate_form(form, values if isinstance(values, dict) else None): raise FormRejected(errors) + # 表单里的文件(docs/design/normal-user-apps.md N9):核对是提交人在这个入口传的、还没用过,先占住;表单值换成 + # 登记的那一份引用(连同 sha256 进运行输入、随封存固定)。发起成功绑到这次运行,发起不成放回去 + values, claimed = await _claim_files(form, values, principal, app.id, entry_id) inputs = map_inputs(entry, values, principal) title = render_title(entry, inputs) - return await launch_run( - session, workflow_id=pin["workflow_id"], run_class="formal", version=pin["version"], - expect_hash=pin["graph_hash"], input_payload=inputs, actor=getattr(principal, "username", None), - origin_kind=origin_kind, app_id=app.id, app_version=version.version, - origin={"entry": entry_id, "spec_hash": version.spec_hash, "title": title, "hook": hook, "hook_key": hook_key, - "actor_verified": bool(getattr(principal, "verified", False)), - "auth_mode": getattr(principal, "mode", "off")}) + try: + run = await launch_run( + session, workflow_id=pin["workflow_id"], run_class="formal", version=pin["version"], + expect_hash=pin["graph_hash"], input_payload=inputs, actor=getattr(principal, "username", None), + origin_kind=origin_kind, app_id=app.id, app_version=version.version, + origin={"entry": entry_id, "spec_hash": version.spec_hash, "title": title, "hook": hook, + "hook_key": hook_key, "actor_verified": bool(getattr(principal, "verified", False)), + "auth_mode": getattr(principal, "mode", "off")}) + except BaseException: + await files_store.release(claimed) + raise + await files_store.finish(claimed, run.id) + return run + + +async def _claim_files(form: dict[str, Any], values: dict[str, Any], principal: Any, app_id: str, + entry_id: str) -> tuple[dict[str, Any], Any]: + """占住表单里的文件;引用不对(不是自己传的、在别处传的、已经用过)按表单错误交回,落到那个字段上。""" + try: + return await files_store.claim(form, values, principal=principal, + context={"app_id": app_id, "entry": entry_id}) + except files_store.FileRefused as e: + raise FormRejected([{"path": e.field or "", "code": files_store.FILE_ERROR_CODE, "message": e.message}]) from e diff --git a/backend/app/apps/forms.py b/backend/app/apps/forms.py index 632d670e..fc4f5ff1 100644 --- a/backend/app/apps/forms.py +++ b/backend/app/apps/forms.py @@ -13,7 +13,7 @@ from datetime import date, datetime from typing import Any, TypedDict from urllib.parse import urlsplit -from app.apps.spec import FORM_FORMAT, FORM_FORMATS, FORM_TYPES, FORM_WIDGETS +from app.apps.spec import FILE_FIELD_TYPE, FILE_REF_KEYS, FORM_FORMAT, FORM_FORMATS, FORM_TYPES, FORM_WIDGETS class FormError(TypedDict): @@ -26,7 +26,11 @@ _TOP_KEYS = frozenset({"format", "type", "title", "description", "required", "pr _FIELD_KEYS = frozenset({ "type", "title", "description", "default", "readOnly", "enum", "x-enum-labels", "minimum", "maximum", "minLength", "maxLength", "maxItems", "format", "items", "x-widget", + # 文件控件的限制:accept(类型或扩展名的列表)、max_mb(docs/design/normal-user-apps.md §3.8) + "x-file", }) +#: 文件控件只认这几项写法 +_FILE_FIELD_KEYS = frozenset({"type", "title", "description", "readOnly", "x-widget", "x-file"}) _NUMBER_KEYS = ("minimum", "maximum") _COUNT_KEYS = ("minLength", "maxLength", "maxItems") _LIMIT_LABEL = {"minimum": "最小值", "maximum": "最大值", "minLength": "最少字数", "maxLength": "最多字数", @@ -80,6 +84,10 @@ def _field_problems(field: Any) -> list[str]: if extra := sorted(k for k in field if k not in _FIELD_KEYS and k != "pattern"): out.append(f"不支持这些写法:{'、'.join(extra)}") kind = field.get("type") + if field.get("x-widget") == "file" or kind == FILE_FIELD_TYPE: + return out + _file_field_problems(field) + if "x-file" in field: + out.append("不是文件控件,不能写文件的限制") if kind not in FORM_TYPES: out.append(f"的类型只能是 {' / '.join(FORM_TYPES)}") if "format" in field and field["format"] not in FORM_FORMATS: @@ -108,11 +116,40 @@ def _field_problems(field: Any) -> list[str]: return out +def _file_field_problems(field: dict[str, Any]) -> list[str]: + """文件控件:类型只能是对象、控件只能是 file(只有这个控件能用对象),限制写在 x-file 里。""" + out: list[str] = [] + if field.get("x-widget") != "file": + out.append(f"的类型只能是 {' / '.join(FORM_TYPES)}(对象只有文件控件能用)") + if field.get("type") != FILE_FIELD_TYPE: + out.append("是文件控件,类型只能是对象") + if extra := sorted(k for k in field if k not in _FILE_FIELD_KEYS and k != "pattern"): + out.append(f"是文件控件,不支持这些写法:{'、'.join(extra)}") + setting = field.get("x-file") + if setting is not None: + if not isinstance(setting, dict) or not set(setting) <= {"accept", "max_mb"}: + out.append("的文件限制只能写可选的类型(accept)和大小上限(max_mb)") + else: + accept = setting.get("accept") + if accept is not None and not (isinstance(accept, list) and all(isinstance(a, str) and a for a in accept)): + out.append("的可选类型需要是类型或扩展名的列表,例如 [\".pdf\", \"image/png\"]") + max_mb = setting.get("max_mb") + if max_mb is not None and not (_number(max_mb) and max_mb > 0): + out.append("的大小上限需要是大于 0 的数(MB)") + return out + + +def _file_fields(form: dict[str, Any]) -> set[str]: + return {name for name, field in (form.get("properties") or {}).items() + if isinstance(field, dict) and (field.get("x-widget") == "file" or field.get("type") == FILE_FIELD_TYPE)} + + def _clean_schema(form: dict[str, Any]) -> dict[str, Any]: - """交给 jsonschema 的那一份:去掉展示用的键和 format(format 自己查,见文件开头)。""" + """交给 jsonschema 的那一份:去掉展示用的键和 format(format 自己查,见文件开头)。文件控件自己查(_file_errors)。""" props: dict[str, Any] = {} + files = _file_fields(form) for name, field in (form.get("properties") or {}).items(): - if not isinstance(field, dict): + if not isinstance(field, dict) or name in files: continue props[name] = {k: v for k, v in field.items() if k in _FIELD_KEYS and k not in ("format", "x-widget", "x-enum-labels", "title", @@ -154,9 +191,34 @@ def validate_form(form: dict[str, Any], values: Any) -> list[FormError]: if isinstance(field, dict) and field.get("format") and isinstance(value, str) and (name, "type") not in seen \ and not _format_ok(field["format"], value): errors.append(_error(name, "format", field)) + errors += _file_errors(form, present) return errors +def _file_errors(form: dict[str, Any], present: dict[str, Any]) -> list[FormError]: + """文件控件的值:上传后拿回的引用 {file_id, name, size, sha256, type},按 x-file 的类型、大小核对。引用是不是这个人 + 传的、有没有用过,提交时绑定那一步(files/store.py)按登记核对。""" + from app.files.store import FILE_ERROR_CODE, accept_problem + + out: list[FormError] = [] + props = form.get("properties") or {} + for name in sorted(_file_fields(form)): + if name not in present: + continue + field = props.get(name) or {} + label = field.get("title") or name + value = present[name] + if not (isinstance(value, dict) and set(value) == set(FILE_REF_KEYS) and isinstance(value.get("file_id"), str) + and value["file_id"] and isinstance(value.get("size"), int) and isinstance(value.get("name"), str) + and isinstance(value.get("type"), str) and isinstance(value.get("sha256"), str)): + out.append({"path": name, "code": FILE_ERROR_CODE, "message": f"「{label}」需要先上传文件"}) + continue + setting = field.get("x-file") if isinstance(field.get("x-file"), dict) else None + if problem := accept_problem(setting, name=value["name"], mime=value["type"], size=value["size"]): + out.append({"path": name, "code": FILE_ERROR_CODE, "message": f"「{label}」{problem}"}) + return out + + def _format_ok(fmt: str, value: str) -> bool: if fmt == "date": try: @@ -203,7 +265,8 @@ def _error(path: str, code: str, field: dict[str, Any]) -> FormError: def input_schema(fields: list[dict[str, Any]]) -> dict[str, Any]: """输入节点的 fields(name / required / default / description / example,以及新增的 type / enum / format,数字类型的 minimum / maximum)→ agentlab.form/1。没写 type 的按 string。上下限只带数字类型的、写成数的那几个:表单子集只有闭区间的 - minimum / maximum(没有 exclusiveMinimum),「大于 0」的金额写成 minimum 0.01。 + minimum / maximum(没有 exclusiveMinimum),「大于 0」的金额写成 minimum 0.01。type 为 file 的是文件字段(可带 accept、 + max_mb,进 x-file)。 有默认值的必填字段不进 required:没填时入口节点补默认值(engine/nodes/io.py 的 run_input),表单不该逼人填。 不认识的 type、format 退回文字:老图里随手写的值不该让整张表单作废。""" @@ -213,6 +276,18 @@ def input_schema(fields: list[dict[str, Any]]) -> dict[str, Any]: if not isinstance(f, dict) or not isinstance(f.get("name"), str) or not f["name"].strip(): continue name = f["name"].strip() + if f.get("type") == "file" or f.get("widget") == "file": + # 文件字段(docs/design/normal-user-apps.md N9):值是上传后拿回的引用;限制(可选类型、大小上限)照写 + upload: dict[str, Any] = {"type": FILE_FIELD_TYPE, "x-widget": "file", "title": str(f.get("label") or name)} + if isinstance(f.get("description"), str) and f["description"].strip(): + upload["description"] = f["description"].strip() + limits = {k: f[k] for k in ("accept", "max_mb") if f.get(k) not in (None, "", [])} + if limits: + upload["x-file"] = limits + props[name] = upload + if f.get("required"): + required.append(name) + continue kind = f.get("type") if f.get("type") in FORM_TYPES else "string" prop: dict[str, Any] = {"type": kind, "title": str(f.get("label") or name)} if isinstance(f.get("description"), str) and f["description"].strip(): diff --git a/backend/app/apps/lint.py b/backend/app/apps/lint.py index 98f13295..f4b6a896 100644 --- a/backend/app/apps/lint.py +++ b/backend/app/apps/lint.py @@ -83,8 +83,15 @@ def needs_disposition(previous: Any | None, pins: list[dict[str, Any]]) -> list[ async def lint_app(session: AsyncSession, spec: dict[str, Any], bindings: dict[str, Any], *, - previous: Any | None = None, dispositions: dict[str, str] | None = None) -> list[dict[str, Any]]: - """检查一份待发布的应用。previous 是上一个应用版本(判断钉住项升版要不要处置)。""" + previous: Any | None = None, dispositions: dict[str, str] | None = None, + pins: dict[str, Any] | None = None, scope: str = "shared") -> list[dict[str, Any]]: + """检查一份待发布的应用。previous 是上一个应用版本(判断钉住项升版要不要处置)。 + + pins 给了就按它认钉住项(别名 → PinState),不读库:发布单的预检按「将要发布的那一版」检查(版本已经存下、还没发布, + blueprints/publish_plan.py 把它当作已发布的样子交进来),其余调用方不给。 + + scope 是应用的范围(App.scope)。个人应用(personal,docs/design/normal-user-apps.md N7)固定的是它自己的蓝图、视图只取 + 探索运行、图要满足使用者的约束(_lint_personal);共享应用里出现蓝图、探索运行的照实报错。""" from app.apps.pins import load_pins out = _Issues() @@ -95,15 +102,19 @@ async def lint_app(session: AsyncSession, spec: dict[str, Any], bindings: dict[s loc = ".".join(str(x) for x in err.get("loc") or ()) out.error("app.format", f"应用描述的格式不对:{loc}({err.get('msg')})", loc or None) return out.items - pins = await load_pins(session, spec) + pins = pins if pins is not None else await load_pins(session, spec) level = _level(pins) _lint_unique(spec, out) - _lint_pins(spec, pins, out) + _lint_pins(spec, pins, out, scope) await _lint_subgraph_pins(session, spec, pins, out) _lint_upgrade(spec, previous, dispositions or {}, out) views = spec.get("views") or {} - await _lint_views(session, spec, pins, out) + await _lint_views(session, spec, pins, out, scope) _lint_components(spec, pins, views, level, out) + await _lint_records_rows(session, spec, pins, out) + _lint_hidden(spec, out) + if scope == "personal": + _lint_personal(spec, pins, out) _lint_entries(spec, pins, out) await _lint_process(session, spec, pins, bindings or {}, out) _lint_hooks(spec, out) @@ -139,10 +150,18 @@ def _lint_unique(spec: dict[str, Any], out: _Issues) -> None: entries.add(entry.get("id")) -def _lint_pins(spec: dict[str, Any], pins: dict[str, Any], out: _Issues) -> None: +def _lint_pins(spec: dict[str, Any], pins: dict[str, Any], out: _Issues, scope: str = "shared") -> None: for i, pin in enumerate(spec.get("pins") or []): state = pins.get(pin.get("alias")) at = f"pins[{i}]" + if pin.get("blueprint") or scope == "personal": + # 个人应用的蓝图在 _lint_personal 里查;两种范围和两种固定版本对不上的在这里报 + if pin.get("blueprint") and scope != "personal": + out.error("app.pin_unpublished", f"引用的「{pin.get('alias')}」是蓝图里还没发布的图:共享应用只能引用已发布的" + "工作流版本", at) + elif not pin.get("blueprint"): + out.error("personal.policy", "个人应用只能引用它自己的蓝图,不能引用工作流版本", at) + continue if state is None or state.row is None: out.error("app.pin_unpublished", f"引用的工作流版本「{pin.get('alias')}」不存在(工作流或 v{pin.get('version')} 已删除)", at) elif state.retired: @@ -186,7 +205,8 @@ def _lint_upgrade(spec: dict[str, Any], previous: Any | None, dispositions: dict f"请选择 {choices} 中的一种", f"pins[{index}]", alias=item["alias"]) -async def _lint_views(session: AsyncSession, spec: dict[str, Any], pins: dict[str, Any], out: _Issues) -> None: +async def _lint_views(session: AsyncSession, spec: dict[str, Any], pins: dict[str, Any], out: _Issues, + scope: str = "shared") -> None: from app.apps.pins import reads_live from app.apps.resolve import latest_sealed_run from app.db.models import Schedule @@ -195,12 +215,22 @@ async def _lint_views(session: AsyncSession, spec: dict[str, Any], pins: dict[st source = (view or {}).get("source") or {} at = f"views.{vid}.source" kind = source.get("kind") + if (kind == "exploratory") != (scope == "personal"): + # 探索运行只在个人应用里合法(N7):共享应用的视图取了它,等于把没发布的图的结果当正式结果给人看;个人应用 + # 只有蓝图上的图、没有正式运行,取别的来源永远是空的 + out.error("app.view_source_personal", + f"视图「{vid}」取的是探索运行:只有个人应用能这样取数,共享应用的视图要取正式运行(最近一次出数、" + "按条件查看或本实例)" if kind == "exploratory" else + f"视图「{vid}」:个人应用的视图只能取它自己的探索运行(每次刷新的结果)", f"{at}.kind") + continue if kind == "instance": continue state = pins.get(source.get("pin")) if state is None: out.error("app.binding_target_missing", f"视图「{vid}」引用的工作流版本「{source.get('pin')}」不在应用里", at) continue + if kind == "exploratory": + continue if kind == "latest_sealed": origin = source.get("from") if origin not in (None, "formal") and not (isinstance(origin, str) and origin.startswith("schedule:")): @@ -241,7 +271,8 @@ def _view_graphs(spec: dict[str, Any], pins: dict[str, Any], view_id: str | None aliases = {e.get("pin") for e in spec.get("entries") or []} or set(pins) return [pins[a].graph for a in aliases if a in pins and pins[a].row is not None] state = pins.get(source.get("pin")) - return [state.graph] if state is not None and state.row is not None else [] + # 个人应用的固定版本是蓝图:图在蓝图上(row 为空) + return [state.graph] if state is not None and (state.row is not None or state.blueprint is not None) else [] def _lint_components(spec: dict[str, Any], pins: dict[str, Any], views: dict[str, Any], level: str, @@ -476,6 +507,94 @@ def _lint_refs(spec: dict[str, Any], comp: dict[str, Any], at: str, out: _Issues out.error("app.binding_target_missing", f"组件「{comp.get('id')}」引用的表单「{props.get('form')}」不存在", f"{at}.props.form") +#: SQL 里出现这些就算汇总过了:分组,或者聚合函数 +_AGGREGATED = re.compile(r"\bgroup\s+by\b|\b(?:count|sum|avg|min|max|total|group_concat)\s*\(", re.I) + + +async def _lint_records_rows(session: AsyncSession, spec: dict[str, Any], pins: dict[str, Any], out: _Issues) -> None: + """表格组件绑定的查询直接列出记录表的逐行、没有汇总(app.records_rows_exposed,docs/design/normal-user-apps.md N8): + 看板读的是正式运行的结果,正式运行看得到全部行,这样等于所有使用者都能看到别人的记录,绕过了行级可见。只提醒: + 作者可能就是要公开(排行榜);逐行查看请用记录列表组件,它按看的人过滤。只看调用工具节点写在图里的 SQL。""" + from app.data.guard import _blank_quoted + from app.db.models import DataSource + from app.records import RECORDS_ORIGIN + from app.tools.datasource import QUERY_PREFIX + + records: set[str] | None = None + for comp, _, at in components(spec): + bind = comp.get("bind") if isinstance(comp.get("bind"), dict) else None + if comp.get("type") != "table" or bind is None or bind_kind(bind) != "query": + continue + target = bind.get("query") if isinstance(bind.get("query"), dict) else {} + for graph in _view_graphs(spec, pins, bind.get("view")): + node = node_map(graph).get(str(target.get("node") or "")) + tool = str(((node or {}).get("config") or {}).get("tool") or "") + sql = (((node or {}).get("config") or {}).get("args") or {}).get("sql") + if node is None or node["type"] != "tool" or not tool.startswith(QUERY_PREFIX) or not isinstance(sql, str): + continue + if records is None: + records = set((await session.execute(select(DataSource.name).where( + DataSource.origin == RECORDS_ORIGIN))).scalars()) + if tool[len(QUERY_PREFIX):] not in records or _AGGREGATED.search(_blank_quoted(sql, dialect="sqlite")): + continue + out.warning("app.records_rows_exposed", + f"组件「{comp.get('id')}」(表格)直接列出了记录表的逐行:看板的数据是正式运行查的,看得到全部行," + "所有能用这个应用的人都会看到别人提交的记录。要逐行查看请改用「记录列表」组件(按看的人过滤);" + "看板上的表格请改成汇总", f"{at}.bind", node_id=str(target.get("node"))) + break + + +def _lint_hidden(spec: dict[str, Any], out: _Issues) -> None: + """隐藏了的组件是唯一绑定某个视图的组件(N6,app.hidden_bound):隐藏之后这个视图的数在页面上一处都看不到了——可能 + 隐藏错了,或者这个视图连同组件可以删掉。只提醒:作者也许就是暂时不想让人看。放在隐藏了的布局组件里的算隐藏。""" + binders: dict[str, list[tuple[bool, str, str]]] = {} + + def walk(items: list[Any], hidden: bool, at: str) -> None: + for i, comp in enumerate(items): + if not isinstance(comp, dict): + continue + here = f"{at}[{i}]" + off = hidden or bool(comp.get("hidden")) + bind = comp.get("bind") if isinstance(comp.get("bind"), dict) else {} + if isinstance(bind.get("view"), str): + binders.setdefault(bind["view"], []).append((off, str(comp.get("id")), here)) + walk(comp.get("children") or [], off, f"{here}.children") + + for pi, page in enumerate(spec.get("pages") or []): + if isinstance(page, dict): + walk(page.get("body") or [], False, f"pages[{pi}].body") + for vid, items in binders.items(): + if not all(off for off, _, _ in items): + continue + _, cid, at = items[0] + what = f"组件「{cid}」是唯一绑定视图「{vid}」的组件" if len(items) == 1 else f"绑定视图「{vid}」的组件都" + out.warning("app.hidden_bound", f"{what},隐藏之后页面上一处都看不到这个视图的数了。确实不要了可以删掉它", + f"{at}.hidden") + + +def _lint_personal(spec: dict[str, Any], pins: dict[str, Any], out: _Issues) -> None: + """个人应用(N7):固定版本是它自己的蓝图(还在、图的指纹和应用记的一样),图满足使用者的约束(同问数据的白名单, + blueprints/personal.policy_problem,personal.policy),不能有入口、钩子、通知订阅、岗位。""" + from app.blueprints.personal import NOT_IN_PERSONAL, policy_problem + + for i, pin in enumerate(spec.get("pins") or []): + if not pin.get("blueprint"): + continue + state = pins.get(pin.get("alias")) + at = f"pins[{i}]" + if state is None or state.blueprint is None: + out.error("personal.policy", "个人应用出自的蓝图已经不在了:没法再刷新,可以归档这个应用", at) + continue + if state.hash != pin.get("graph_hash"): + out.error("app.pin_hash", "蓝图在存成个人应用之后又改过:请回到蓝图重新「存成我的应用」", at) + if problem := policy_problem(state.graph): + out.error("personal.policy", problem, at) + declared = [(key, label) for key, label in NOT_IN_PERSONAL if spec.get(key)] + if declared: + out.error("personal.policy", f"个人应用不发起实例、不派待办,不能有{'、'.join(label for _, label in declared)}:请删掉", + declared[0][0]) + + def _lint_entries(spec: dict[str, Any], pins: dict[str, Any], out: _Issues) -> None: for i, entry in enumerate(spec.get("entries") or []): at = f"entries[{i}]" diff --git a/backend/app/apps/ops.py b/backend/app/apps/ops.py index f0d28eb3..adb20b38 100644 --- a/backend/app/apps/ops.py +++ b/backend/app/apps/ops.py @@ -2,7 +2,7 @@ 操作(一行一个 JSON): {"op":"app_add","parent":"<组件 id>|<页面 id>","index":0,"component":{...}} - {"op":"app_update","id":"<组件 id>","props":{...},"bind":{...},"visible":"..."} + {"op":"app_update","id":"<组件 id>","props":{...},"bind":{...},"visible":"...","hidden":true} {"op":"app_remove","id":"<组件 id>"} {"op":"app_move","id":"<组件 id>","parent":"...","index":0} {"op":"app_page","page":{"id","title"}} 新增或改页面标题 @@ -125,6 +125,8 @@ def _update(spec: dict[str, Any], op: dict[str, Any]) -> Applied: if found is None: return _refuse(f"找不到组件「{op.get('id')}」") items, i = found + if "hidden" in op and op["hidden"] not in (True, False, None): + return _refuse("隐藏只能写是或否") before = copy.deepcopy(items[i]) comp = items[i] if isinstance(op.get("props"), dict): @@ -142,6 +144,12 @@ def _update(spec: dict[str, Any], op: dict[str, Any]) -> Applied: comp.pop(key, None) else: comp[key] = op[key] + # 隐藏(normal-user-apps N6):作者不要它,只是呈现;为真才写,取消隐藏去掉这一项(组件模型的默认值是 false) + if "hidden" in op: + if op["hidden"] is True: + comp["hidden"] = True + else: + comp.pop("hidden", None) try: Component.model_validate(comp) except ValidationError as e: diff --git a/backend/app/apps/pins.py b/backend/app/apps/pins.py index 438097da..71b8b590 100644 --- a/backend/app/apps/pins.py +++ b/backend/app/apps/pins.py @@ -18,24 +18,32 @@ class PinState: pin: dict[str, Any] workflow: Any | None row: Any | None + #: 个人应用(docs/design/normal-user-apps.md N7)的固定版本写的是蓝图:图在蓝图上,没有工作流、没有版本 + blueprint: Any | None = None @property def name(self) -> str: + if self.blueprint is not None: + return self.blueprint.name or "" return self.workflow.name if self.workflow is not None else str(self.pin.get("workflow_id") or "") @property def label(self) -> str: - """「周销售 v7」。""" + """「周销售 v7」。个人应用的蓝图没有版本,只写名字。""" + if self.blueprint is not None: + return f"「{self.name}」" return f"{self.name} v{self.pin.get('version')}" @property def graph(self) -> dict[str, Any]: + if self.row is None and self.blueprint is not None: + return self.blueprint.graph or {} return (self.row.graph if self.row is not None else None) or {} @property def hash(self) -> str | None: if self.row is None: - return None + return graph_hash(self.blueprint.graph or {}) if self.blueprint is not None else None return self.row.graph_hash or graph_hash(self.row.graph or {}) @property @@ -65,10 +73,18 @@ class PinState: async def load_pins(session: AsyncSession, spec: dict[str, Any]) -> dict[str, PinState]: + from app.db.models_blueprints import Blueprint + out: dict[str, PinState] = {} for pin in spec.get("pins") or []: if not isinstance(pin, dict) or not pin.get("alias"): continue + if isinstance(pin.get("blueprint"), str): + # 个人应用:图在蓝图上。蓝图删了 blueprint 为空,检查和解析照实报 + blueprint = await session.get(Blueprint, pin["blueprint"]) + out[str(pin["alias"])] = PinState(alias=str(pin["alias"]), pin=pin, workflow=None, row=None, + blueprint=blueprint) + continue wf_id, version = pin.get("workflow_id"), pin.get("version") workflow = await session.get(Workflow, wf_id) if isinstance(wf_id, str) else None row = None @@ -80,8 +96,9 @@ async def load_pins(session: AsyncSession, spec: dict[str, Any]) -> dict[str, Pi def needs_upgrade(pins: dict[str, PinState]) -> bool: - """钉住的版本有退役的(或者已经不能用了):入口拒绝发起新实例,视图照实写明(A1)。""" - return any(not p.usable for p in pins.values()) + """钉住的版本有退役的(或者已经不能用了):入口拒绝发起新实例,视图照实写明(A1)。个人应用的蓝图没有版本可退役、 + 可升级,不算(它的图改过没重新存,刷新时照实拒绝,见 blueprints/personal.refresh)。""" + return any(not p.usable for p in pins.values() if not p.pin.get("blueprint")) #: 结果只由参数决定的内置工具:同样的输入算出同样的东西。别的(联网、读文件、知识库、记忆、当前时间、执行代码)都算活的 @@ -113,7 +130,8 @@ async def reads_live(session: AsyncSession, graph: dict[str, Any]) -> bool: return False origins = dict((await session.execute(select(DataSource.name, DataSource.origin) .where(DataSource.name.in_(sorted(sources))))).all()) - return any(origins.get(s) != "upload" for s in sources) + # 记录表按高水位固定(records/views.pin_entry),缓存键里带着它,同上传表格 + return any(origins.get(s) not in ("upload", "records") for s in sources) async def write_nodes(session: AsyncSession, graph: dict[str, Any]) -> dict[str, Any]: diff --git a/backend/app/apps/resolve.py b/backend/app/apps/resolve.py index 652dbfe3..1025d12a 100644 --- a/backend/app/apps/resolve.py +++ b/backend/app/apps/resolve.py @@ -53,6 +53,20 @@ STATUS_TEXT = {"queued": "排队中", "running": "运行中", "interrupted": " "failed": "失败", "cancelled": "已取消"} TIER_TEXT = {"formal": "完整出具", "degraded": "降档出具", "withheld": "不予出具"} NO_TIER = "未声明出具契约" +#: 蓝图试运行(docs/design/normal-user-apps.md N4):印章的来源、说明,趋势只有一个点时的说明,预览里入口按钮为什么点不了 +TRIAL_FROM = "试运行" +TRIAL_NOTE = "数据是真的,但这不是正式结果:发布之后才会按设定出数" +TRIAL_SERIES = "试运行只有一次,没有趋势:发布之后每出一期数,这里多一个点" +TRIAL_ENTRY = "试运行预览里不能发起;要换一份示例再试,请回到蓝图重新试运行" +#: 钉住项还没有版本号(蓝图试运行派生的草稿):没有正式运行可看,趋势也画不出来 +UNPUBLISHED_EMPTY = "还没有发布:发布之后有一次正式运行成功并封存,这里才有数" +UNPUBLISHED_SERIES = "还没有发布,没有趋势:发布之后每出一期数,这里多一个点" +#: 个人应用的视图(exploratory,N7):印章的来源,还没刷新过、最近一次没成功、写在共享应用里时写什么 +EXPLORATORY_FROM = "探索 · 未经发布审核" +EXPLORATORY_EMPTY = "还没有数据:点「刷新」后按当前的图运行一次" +EXPLORATORY_FAILED = "最近一次刷新没有成功,这里是上一次成功刷新的结果" +EXPLORATORY_SHARED = "这个视图取的是探索运行,只有个人应用能这样取数:请管理应用的人改成取正式运行" +EXPLORATORY_SERIES = "每次刷新" TIER_BY_METRICS = "(按指标)" EMPTY_TEXT = "还没有数据" _ACTIVE = ("queued", "running", "interrupted") @@ -172,11 +186,14 @@ class Source: stamp: dict[str, Any] | None = None message: str | None = None origin: str | None = None + #: 蓝图试运行的预览(resolve_page 的 trial 旁路):不管视图声明的是哪种来源,都取这次试运行 + trial: bool = False _masks: Any = None def out(self) -> dict[str, Any]: - # kind(latest_sealed / on_demand / instance):界面据此在按需视图的印章旁给「刷新」 - return {"state": self.state, "kind": self.kind, "run_id": self.run.id if self.run else None, + # kind(latest_sealed / on_demand / instance):界面据此在按需视图的印章旁给「刷新」;试运行预览里一律是 trial + return {"state": self.state, "kind": "trial" if self.trial else self.kind, + "run_id": self.run.id if self.run else None, "stamp": self.stamp, **({"message": self.message} if self.message else {})} @property @@ -202,6 +219,10 @@ def _when(value: datetime | None) -> str: async def _from_text(session: AsyncSession, source: Source) -> str: run = source.run + if source.trial: + return TRIAL_FROM + if source.kind == "exploratory": + return EXPLORATORY_FROM if source.kind == "instance": return "本实例" if source.kind == "on_demand": @@ -236,8 +257,7 @@ async def stamp_of(session: AsyncSession, source: Source) -> dict[str, Any]: if period: parts.append("统计期 " + "、".join(period)) if run.data_versions: - parts.append("数据版本 " + "、".join(f"{v.get('name')} {str(v.get('snapshot') or '')[:8]}" - for v in run.data_versions.values() if isinstance(v, dict))) + parts.append("数据版本 " + "、".join(_version_text(v) for v in run.data_versions.values() if isinstance(v, dict))) calibers: list[dict[str, str]] = [] for _, _, card in _sealed_cards(sealed): item = {"name": str(card.get("caliber") or ""), "version": str(card.get("caliber_version") or "")} @@ -246,8 +266,11 @@ async def stamp_of(session: AsyncSession, source: Source) -> dict[str, Any]: issuance = _issuance_of(sealed) tier = issuance.get("tier") if isinstance(issuance, dict) else None notes: list[str] = [] - workflow_name = pin.name if pin is not None else run.workflow_name - if pin is not None and pin.workflow is not None: + # 试运行跑的是还没发布的图:钉住项没有版本号,名字取运行上记的(蓝图名),版本错位一类的说明不适用 + workflow_name = pin.name if pin is not None and not source.trial else run.workflow_name + if source.trial: + notes.append(TRIAL_NOTE) + elif pin is not None and pin.workflow is not None: current = pin.workflow.published_version if pin.retired: notes.append(f"固定的 v{pin.pin.get('version')} 已退役,这里保留最后一次的数据;应用需要升级") @@ -256,6 +279,9 @@ async def stamp_of(session: AsyncSession, source: Source) -> dict[str, Any]: notes.append(f"定时任务已改为运行 v{current},本应用固定在 v{pin.pin.get('version')}") else: notes.append(f"工作流的当前发布版本是 v{current},本应用固定在 v{pin.pin.get('version')}") + if source.kind == "exploratory" and source.state == "ok" and source.message: + # 个人应用最近一次刷新没成功、这里给的是上一次的(_exploratory_source) + notes.append(source.message) if not sealed.trusted: notes.append("这次运行还没有封存(或封存核对不一致),数字仅供参考") return { @@ -270,10 +296,18 @@ async def stamp_of(session: AsyncSession, source: Source) -> dict[str, Any]: issuance, dict) and issuance.get("mode") == "metrics" else ""), "from": await _from_text(session, source), "sealed": bool(sealed.trusted), + **({"trial": True} if source.trial else {}), **({"notes": notes} if notes else {}), } +def _version_text(entry: dict[str, Any]) -> str: + """印章上一个数据源固定的版本:上传表格写快照 id 前 8 位;记录表写「截至第 N 条」(records/views.pin_entry)。""" + if entry.get("origin") == "records": + return f"{entry.get('name')} 截至第 {entry.get('seq') or 0} 条" + return f"{entry.get('name')} {str(entry.get('snapshot') or '')[:8]}" + + # -------------------------------------------------------------------------- # 按需视图:缓存键、单飞、每日上限 # -------------------------------------------------------------------------- @@ -308,7 +342,9 @@ async def cache_key(session: AsyncSession, state: PinState, inputs: dict[str, An versions = {} capabilities = await capability_versions_for(session, graph_tool_names(state.graph)) text = canonical_json({"graph_hash": state.hash, "input": inputs, - "data_versions": {k: (v or {}).get("snapshot") for k, v in sorted(versions.items())}, + # 记录表按高水位(seq):有新的提交,缓存就不再算数 + "data_versions": {k: (v or {}).get("snapshot") or (v or {}).get("seq") + for k, v in sorted(versions.items())}, "capabilities": capabilities}) return hashlib.sha256(text.encode()).hexdigest() @@ -407,6 +443,8 @@ class _Page: actor: str | None #: 正在解析的这一页(组件之间要互相知道的:同一页上有没有绑同一条待办的会签组件) page: dict[str, Any] = field(default_factory=dict) + #: 蓝图的试运行(trial 旁路):草稿里所有视图来源都解析到这次运行,流程组件也对着它 + trial: Run | None = None pins: dict[str, PinState] = field(default_factory=dict) sources: dict[str, Source] = field(default_factory=dict) problems: list[dict[str, Any]] = field(default_factory=list) @@ -445,28 +483,41 @@ async def _backfilled(session: AsyncSession, app_id: str) -> int: async def resolve_page(session: AsyncSession, app: Any, *, page_id: str, principal: Principal, role: str | None, instance: Run | None = None, params: dict[str, Any] | None = None, draft: bool = False, - version: AppVersion | None = None, actor: str | None = None) -> dict[str, Any]: - """解析一页,返回 agentlab.view/1。draft 为真时按草稿解析:不发起任何运行,视图取钉住版本已有的封存运行。""" + version: AppVersion | None = None, actor: str | None = None, + trial: Run | None = None) -> dict[str, Any]: + """解析一页,返回 agentlab.view/1。draft 为真时按草稿解析:不发起任何运行,视图取钉住版本已有的封存运行。 + + trial 是蓝图的一次试运行(docs/design/normal-user-apps.md N4,只和 draft 一起用):草稿里所有视图来源(最近封存、 + 按需、本实例)都解析到这次运行,流程组件(实例进度、待办)也对着它;印章的来源写「试运行」、trial 为真、说明里写 + 「这不是正式结果」;趋势只有这一个点。不改 agentlab.app/1 的视图来源,只是解析时的旁路。 + + 个人应用(N7)没有应用版本:草稿就是在用的那一份,不按草稿预览时也解析它(version 为空)。作者隐藏了的组件(hidden) + 不下发;按草稿解析(编辑状态)时照常解析、带上 hidden,界面画成半透明。""" import copy - from app.apps.tree import app_level + from app.apps.tree import app_level, spec_hash - spec = copy.deepcopy(app.draft if draft else (version.spec if version is not None else {})) or {} + personal = getattr(app, "scope", "shared") == "personal" + spec = copy.deepcopy(app.draft if draft or personal else (version.spec if version is not None else {})) or {} page = page_of(spec, page_id) if page is None: raise ViewRefused(404, f"应用里没有页面「{page_id}」", "app_page_not_found") + trial = trial if draft else None ctx = _Page(app=app, spec=spec, version=None if draft else version, principal=principal, role=role, - instance=instance, params=params or {}, draft=draft, actor=actor, page=page) + instance=instance or trial, params=params or {}, draft=draft, actor=actor, page=page, trial=trial) ctx.pins = await load_pins(session, spec) - upgrade = needs_upgrade(ctx.pins) + # 试运行的钉住项本来就没有版本(还没发布),不是「需要升级」 + upgrade = needs_upgrade(ctx.pins) if trial is None else False level = version.level if (version is not None and not draft) else app_level( [{"level": p.level} for p in ctx.pins.values()]) - wanted = _views_of(page) + wanted = _views_of(page, hidden=draft) for vid in wanted: ctx.sources[vid] = await _source(session, ctx, vid) # 键:应用版本、页面、各来源取的那次运行、角色。另加各钉住项所在工作流的当前发布版和退役与否:印章上「定时任务已改为 # 运行 vN」「已退役」随它们变,运行没换也得重新算;遮罩设置的指纹同理(_mask_fingerprint) - key = (app.id, "draft" if draft else (version.version if version else None), page_id, + # 个人应用没有版本号,草稿改了就生效:按草稿的指纹认 + key = (app.id, "draft" if draft else (version.version if version else (spec_hash(spec) if personal else None)), + page_id, tuple((v, s.run.id if s.run else None, s.state, s.message) for v, s in sorted(ctx.sources.items())), tuple((a, p.workflow.published_version if p.workflow else None, p.retired) for a, p in sorted(ctx.pins.items())), @@ -498,6 +549,8 @@ async def resolve_page(session: AsyncSession, app: Any, *, page_id: str, princip "tree": tree, "forms": ctx.forms, "problems": ctx.problems, + **({"trial": {"run_id": trial.id, "status": trial.status, + "status_text": STATUS_TEXT.get(trial.status, trial.status)}} if trial is not None else {}), } if cacheable: _PAGE_CACHE[key] = copy.deepcopy(out) @@ -507,7 +560,7 @@ async def resolve_page(session: AsyncSession, app: Any, *, page_id: str, princip _DYNAMIC = frozenset({"instance_list", "task_list", "instance_header", "instance_timeline", "task_form", "signoffs", - "action_status", "entry_button"}) + "action_status", "entry_button", "records_list"}) def _dynamic(page: dict[str, Any]) -> bool: @@ -517,11 +570,11 @@ def _dynamic(page: dict[str, Any]) -> bool: return any(c.get("type") in _DYNAMIC for c, _, _ in components({"pages": [page]})) -def _views_of(page: dict[str, Any]) -> list[str]: - from app.apps.tree import components - +def _views_of(page: dict[str, Any], *, hidden: bool = False) -> list[str]: + """这一页要解析哪些视图。hidden 为假时跳过作者隐藏了的组件(连同它里面的):只被它们绑定的视图不取运行,按需视图也 + 不会因为一块看不见的组件自动发起。""" out: list[str] = [] - for comp, _, _ in components({"pages": [page]}): + for comp in _shown(page.get("body") or [], hidden=hidden): for vid in ((comp.get("bind") or {}).get("view") if isinstance(comp.get("bind"), dict) else None, comp.get("scope")): if isinstance(vid, str) and vid not in out: @@ -529,6 +582,17 @@ def _views_of(page: dict[str, Any]) -> list[str]: return out +def _shown(items: list[Any], *, hidden: bool) -> list[dict[str, Any]]: + """深度优先列出组件;hidden 为假时隐藏了的组件和它里面的都不列。""" + out: list[dict[str, Any]] = [] + for comp in items: + if not isinstance(comp, dict) or (comp.get("hidden") and not hidden): + continue + out.append(comp) + out += _shown(comp.get("children") or [], hidden=hidden) + return out + + async def _source(session: AsyncSession, ctx: _Page, vid: str) -> Source: """这个视图取哪一次运行(还不读封存范围,见 _load)。""" view = (ctx.spec.get("views") or {}).get(vid) @@ -536,6 +600,8 @@ async def _source(session: AsyncSession, ctx: _Page, vid: str) -> Source: kind = src.get("kind") if kind is None: return Source(id=vid, kind="", state="error", message=f"视图「{vid}」不存在") + if ctx.trial is not None: + return await _trial_source(session, ctx, vid, kind, src) state = ctx.pins.get(src.get("pin")) if kind != "instance" else None run: Run | None = None if kind == "instance": @@ -546,6 +612,8 @@ async def _source(session: AsyncSession, ctx: _Page, vid: str) -> Source: and p.pin.get("version") == run.version), None) elif state is None: return Source(id=vid, kind=kind, state="error", message=f"视图「{vid}」引用的工作流版本不在应用里") + elif kind == "exploratory": + return await _exploratory_source(session, ctx, vid, state) elif kind == "latest_sealed": run = await latest_sealed_run(session, state, src.get("from")) if run is None: @@ -565,6 +633,47 @@ async def _source(session: AsyncSession, ctx: _Page, vid: str) -> Source: return source +async def _exploratory_source(session: AsyncSession, ctx: _Page, vid: str, state: PinState) -> Source: + """个人应用的视图(docs/design/normal-user-apps.md N7):这个应用、这个拥有者、这张图下最近一次成功封存的刷新 + (blueprints/personal.exploratory_runs)。只在个人应用里合法(应用检查报 app.view_source_personal):共享应用里写了的 + 照实报错、不取数。正在刷新的照实写;最近一次刷新没成功的,给上一次成功的结果并写明(印章的说明里也有)。""" + from app.blueprints.personal import exploratory_runs, latest_refresh + + if getattr(ctx.app, "scope", "shared") != "personal": + return Source(id=vid, kind="exploratory", state="error", message=EXPLORATORY_SHARED) + hash_ = state.pin.get("graph_hash") + latest = await latest_refresh(session, ctx.app.id, hash_) + if latest is not None and latest.status in _ACTIVE: + return Source(id=vid, kind="exploratory", state="running", run=latest, pin=state, message=RUNNING_TEXT) + # 开了登录时刷新只能由拥有者发起,按人筛是多一道保险;关登录没有可信的身份,不按人筛 + owner = ctx.app.owner if ctx.principal.mode != "off" else None + runs = await exploratory_runs(session, ctx.app.id, hash_, 1, owner) + if not runs: + if latest is not None: + return Source(id=vid, kind="exploratory", state="error", run=latest, pin=state, + message=f"最近一次刷新{STATUS_TEXT.get(latest.status, latest.status)}") + return Source(id=vid, kind="exploratory", state="empty", pin=state, message=EXPLORATORY_EMPTY) + source = Source(id=vid, kind="exploratory", state="ok", run=runs[0], pin=state) + if latest is not None and latest.id != runs[0].id and latest.status in ("failed", "cancelled"): + source.message = EXPLORATORY_FAILED + return source + + +async def _trial_source(session: AsyncSession, ctx: _Page, vid: str, kind: str, src: dict[str, Any]) -> Source: + """试运行预览:这个视图声明的是哪种来源都取这次试运行。钉住项按视图引用的那个认(实例视图不引用,取第一个)。""" + run = ctx.trial + assert run is not None + state = ctx.pins.get(src.get("pin")) or next(iter(ctx.pins.values()), None) + if run.status in _ACTIVE: + return Source(id=vid, kind=kind, state="running", run=run, pin=state, trial=True, + message=await _active_text(session, run)) + source = Source(id=vid, kind=kind, state="ok" if run.status == "succeeded" else "error", run=run, pin=state, + trial=True) + if run.status != "succeeded": + source.message = f"这次试运行{STATUS_TEXT.get(run.status, run.status)}" + return source + + #: 来源的运行还没结束时各块写什么。页面在跟着(应用页轮询、实例页轮询或接事件流),不用人去刷新 RUNNING_TEXT = "正在运行,完成后自动刷新" @@ -580,6 +689,8 @@ async def _active_text(session: AsyncSession, run: Run) -> str: async def _empty_text(session: AsyncSession, state: PinState, origin: Any) -> str: """最近封存运行的视图还没有数据时说什么:还没有、什么时候会有(定时任务的下次运行时间,或者要等一次正式运行)。""" + if not isinstance(state.pin.get("version"), int): + return UNPUBLISHED_EMPTY if isinstance(origin, str) and origin.startswith("schedule:"): schedule = await session.get(Schedule, origin[len("schedule:"):]) if schedule is None: @@ -629,9 +740,13 @@ async def _node(session: AsyncSession, ctx: _Page, comp: dict[str, Any]) -> dict if not isinstance(comp, dict): return None cid = str(comp.get("id")) + # 作者隐藏了的(N6)不下发,里面的也不下发;按草稿解析(编辑状态)时照常解析,带上 hidden 由界面画成半透明 + if comp.get("hidden") and not ctx.draft: + return None if comp.get("visible") and not await _visible(session, ctx, comp): return None - node: dict[str, Any] = {"id": cid, "type": comp.get("type"), "props": dict(comp.get("props") or {})} + node: dict[str, Any] = {"id": cid, "type": comp.get("type"), "props": dict(comp.get("props") or {}), + **({"hidden": True} if comp.get("hidden") else {})} entry = BY_NAME.get(str(comp.get("type"))) if entry is not None and entry["children"]: node["children"] = [n for c in comp.get("children") or [] if (n := await _node(session, ctx, c)) is not None] @@ -703,6 +818,10 @@ async def _data(session: AsyncSession, ctx: _Page, comp: dict[str, Any]) -> dict cid = str(comp.get("id")) if ctype == "entry_button": entry = next((e for e in ctx.spec.get("entries") or [] if e.get("id") == props.get("entry")), None) + if ctx.trial is not None: + # 试运行预览:入口照常画出来(发布后长这样),发起不了——试运行的输入在蓝图上填 + return {"entry": props.get("entry"), "label": props.get("label") or (entry or {}).get("label") or "", + "disabled": True, "reason": TRIAL_ENTRY} blocked = needs_upgrade({a: p for a, p in ctx.pins.items() if entry and a == entry.get("pin")}) return {"entry": props.get("entry"), "label": props.get("label") or (entry or {}).get("label") or "", "disabled": blocked or entry is None, @@ -714,6 +833,8 @@ async def _data(session: AsyncSession, ctx: _Page, comp: dict[str, Any]) -> dict return {"form": props.get("form")} if ctype == "instance_list": return await _instance_list(session, ctx, props) + if ctype == "records_list": + return await _records_list(session, ctx, props) if ctype == "instance_header": return await _instance_header(session, ctx) if ctype == "instance_timeline": @@ -810,9 +931,17 @@ async def _series(session: AsyncSession, ctx: _Page, source: Source, cid: str, r n = min(last, SERIES_MAX) if isinstance(last, int) and not isinstance(last, bool) and last > 0 else 12 node_id, _, metric_id = ref.partition(".") + if source.trial: + return await _trial_series(source, node_id, metric_id) + if source.kind == "exploratory": + return await _exploratory_series(session, ctx, source, node_id, metric_id, n) pin = source.pin if pin is None: return {"state": "error"} + if not isinstance(pin.pin.get("version"), int): + # 钉住项还没有版本号(蓝图试运行派生的草稿按草稿预览):没有一期一期的封存运行可画,照实说,不算解析出错 + return {"state": "empty", "mode": "single", "unit": "", "series": [], "breaks": [], + "message": UNPUBLISHED_SERIES} origin = source.origin segments: list[tuple[int, str, list[Run]]] = [] mode = "single" @@ -858,6 +987,47 @@ async def _series(session: AsyncSession, ctx: _Page, source: Source, cid: str, r return {"state": "ok", "mode": mode, "unit": unit, "series": series, "breaks": breaks} +async def _exploratory_series(session: AsyncSession, ctx: _Page, source: Source, node_id: str, metric_id: str, + n: int) -> dict[str, Any]: + """个人应用的趋势:同一个应用、同一张图最近 n 次成功封存的刷新,按时间从早到晚排成一列(同 exploratory 视图取数的 + 规则)。图改过、重新存成个人应用之后从新图的第一次刷新画起,旧图的点不混进来。""" + from app.api.evidence import _sealed + from app.blueprints.personal import exploratory_runs + + assert source.pin is not None + owner = ctx.app.owner if ctx.principal.mode != "off" else None + runs = list(reversed(await exploratory_runs(session, ctx.app.id, source.pin.pin.get("graph_hash"), n, owner))) + points = [] + unit = "" + for run in runs: + sealed = source.sealed if source.run is not None and run.id == source.run.id else await _sealed(run.id) + point_source = Source(id=source.id, kind=source.kind, state="ok", run=run, pin=source.pin, sealed=sealed) + metric, text, eid, held = await _metric_value(point_source, node_id, metric_id, None) + if metric is not None: + unit = unit or str(metric.get("unit") or "") + period = period_of(run) + points.append({"run_id": run.id, "as_of": period.isoformat() if period else None, + "value": None if held or metric is None else metric.get("value"), "text": text, + "evidence": _evidence(point_source, "metric", node=node_id, metric=metric_id, eid=eid) + if metric is not None else None}) + return {"state": "ok", "mode": "single", "unit": unit, + "series": [{"version": None, "label": EXPLORATORY_SERIES, "points": points}], "breaks": []} + + +async def _trial_series(source: Source, node_id: str, metric_id: str) -> dict[str, Any]: + """试运行预览里的趋势:只有这一次试运行一个点,照实写「没有趋势」(note),不报错。""" + metric, text, eid, held = await _metric_value(source, node_id, metric_id, None) + run = source.run + assert run is not None + period = period_of(run) + point = {"run_id": run.id, "as_of": period.isoformat() if period else None, + "value": None if held or metric is None else metric.get("value"), "text": text, + "evidence": _evidence(source, "metric", node=node_id, metric=metric_id, eid=eid) + if metric is not None else None} + return {"state": "ok", "mode": "single", "unit": str((metric or {}).get("unit") or ""), "trial": True, + "series": [{"version": None, "label": TRIAL_FROM, "points": [point]}], "breaks": [], "note": TRIAL_SERIES} + + async def _upgrade_of(session: AsyncSession, ctx: _Page, alias: str) -> tuple[dict[str, Any] | None, str | None]: if ctx.version is None: return None, None @@ -1234,11 +1404,29 @@ async def _instance_list(session: AsyncSession, ctx: _Page, props: dict[str, Any # 关登录、又没填署名时分不出谁是谁,「我发起的」就是全部(同待办箱,A4.6) mine = (ctx.principal.username or ctx.actor) if who == "mine" else None limit = props.get("limit") if isinstance(props.get("limit"), int) else 50 + if ctx.trial is not None: + # 试运行预览:「我发起的」里就是这一次试运行 + return {"who": who, "entry": props.get("entry"), "trial": True, + "items": await instance_rows(session, [ctx.trial])} return {"who": who, "entry": props.get("entry"), "items": [] if ctx.draft else await list_instances(session, ctx.app.id, mine=mine, entry=props.get("entry"), limit=limit)} +async def _records_list(session: AsyncSession, ctx: _Page, props: dict[str, Any]) -> dict[str, Any]: + """记录列表(docs/design/normal-user-apps.md N8):每次打开按看的人实时过滤(records/listing.py),不走封存,同实例列表。 + 草稿预览不列真实的记录。""" + from app.records.listing import page + + who = props.get("who") if props.get("who") in ("mine", "all") else None + limit = props.get("limit") if isinstance(props.get("limit"), int) else 50 + if ctx.draft: + return {"table": props.get("table"), "version": 0, "columns": [], "items": [], "mine_only": who == "mine", + "state": "empty", "next_cursor": None} + return await page(session, ctx.app, principal=ctx.principal, role=ctx.role, table=props.get("table"), who=who, + limit=limit) + + async def _instance_header(session: AsyncSession, ctx: _Page) -> dict[str, Any]: run = ctx.instance if run is None: @@ -1315,7 +1503,10 @@ async def _task_list(session: AsyncSession, ctx: _Page, props: dict[str, Any]) - scope = props.get("scope") if props.get("scope") in ("mine", "instance") else "mine" query = select(Task).where(Task.app_id == ctx.app.id) - if scope == "instance": + if ctx.trial is not None: + # 试运行的待办不属于任何应用,都派给了发起试运行的人自己(process/tasks.py):列这次试运行的 + query = select(Task).where(Task.run_id == ctx.trial.id) + elif scope == "instance": if ctx.instance is None: return {"scope": scope, "items": []} query = query.where(Task.run_id == ctx.instance.id) @@ -1404,7 +1595,9 @@ async def _process_data(session: AsyncSession, ctx: _Page, ctype: Any, kind: str "handler": handles(rows, reader), "assignments": [_assignment_row(a) for a in rows], "progress": progress(task, rows), "my_response": my_response(rows, reader), "people": await display_names(session, people_of(task, rows)), - **({"signoffs_on_page": True} if signoffs else {})} + **({"signoffs_on_page": True} if signoffs else {}), + # 试运行的待办派给了发起试运行的人自己:界面上按钮写「以试运行身份同意 / 驳回」 + **({"trial": True} if ctx.trial is not None else {})} records = (await session.execute(select(ActionRecord).where(ActionRecord.run_id == run.id, ActionRecord.node_id == node_id) .order_by(ActionRecord.created_at, ActionRecord.attempt))).scalars() diff --git a/backend/app/auth/access.py b/backend/app/auth/access.py index 77aef1cc..ead2e70d 100644 --- a/backend/app/auth/access.py +++ b/backend/app/auth/access.py @@ -4,6 +4,7 @@ - 自己发起的运行; - 自己参与的实例:派给过自己(或自己所在的组)的待办,或者自己回复过的待办所在的运行。派给「任何人」的不算:那是没有 应用绑定的运行(画布、定时任务),user 角色不该因此读到; +- 自己的个人应用(docs/design/normal-user-apps.md N7)的刷新:只有拥有者,别人的个人应用即使有人自报同名也不算; - 有授权(use / observe / manage,含 everyone 和自己所在的组)的应用里: - 视图运行(来源是应用视图、按新口径补算); - observe、manage 授权另能读全部实例; @@ -87,6 +88,8 @@ async def run_readable(principal: Any, run: Any) -> bool: return False if run.started_by == principal.username: return True + if run.origin_kind == "personal_app" and run.app_id: + return await _owns_personal_app(session, principal, run.app_id) if await _participated(session, principal, run.id): return True apps = await app_roles(session, principal) @@ -96,6 +99,15 @@ async def run_readable(principal: Any, run: Any) -> bool: return await _viewed_by_granted_app(session, run, set(apps)) +async def _owns_personal_app(session: AsyncSession, principal: Any, app_id: str) -> bool: + """个人应用的刷新只有这个应用的拥有者能读:别人参与不了(不派待办)、也没有授权可言(个人应用不能分享)。按应用上记的 + 拥有者认,不按发起人——刷新只能由拥有者发起,这里不靠它。""" + from app.db.models import App + + owner = await session.scalar(select(App.owner).where(App.id == app_id, App.scope == "personal")) + return bool(owner) and owner == principal.username + + async def artifact_readable(principal: Any, artifact_id: str) -> bool: """能不能读这件工件:引用它的某次运行能读就能读。工件按内容寻址,同一件可能被好几次运行引用。""" if _unrestricted(principal): diff --git a/backend/app/auth/chat_policy.py b/backend/app/auth/chat_policy.py index 736c1146..f42ed761 100644 --- a/backend/app/auth/chat_policy.py +++ b/backend/app/auth/chat_policy.py @@ -47,11 +47,13 @@ def _set(value: Any) -> bool: return value not in (None, "") -def chat_graph_problem(graph: Any) -> str | None: +def chat_graph_problem(graph: Any, *, where: str = "问数据") -> str | None: """这张图 user 角色能不能在问数据里运行:能用返回 None,不能用交回一句给人看的原因(403 的 detail)。 图不成形(GraphSpec 校验不过)时也返回 None:交给 launch_run 照常报校验问题——两边用的是同一个 GraphSpec,过不了 - 校验的图本来就发起不了。""" + 校验的图本来就发起不了。 + + where 是说法里的「在哪」:个人应用(blueprints/personal.py)用的是同一份白名单,只把「问数据」换成「个人应用」。""" from app.engine.launch import tool_bindings from app.engine.schema import GraphSpec, type_label @@ -61,19 +63,20 @@ def chat_graph_problem(graph: Any) -> str | None: spec = GraphSpec.model_validate(graph) except ValueError: return None + scope_refused = SCOPE_REFUSED.replace("问数据", where) if any(_set(spec.defaults.get(key)) for key in SCOPE_KEYS): - return SCOPE_REFUSED + return scope_refused for node in spec.nodes: if str(node.type) not in CHAT_NODE_TYPES: - return (f"没有权限:使用者在问数据中不能使用「{type_label(node.type)}」节点(「{node.title}」)。" + return (f"没有权限:使用者在{where}中不能使用「{type_label(node.type)}」节点(「{node.title}」)。" "如需这类处理,请联系搭建者做成应用") if any(_set(node.config.get(key)) for key in SCOPE_KEYS): - return f"{SCOPE_REFUSED}(「{node.title}」)" + return f"{scope_refused}(「{node.title}」)" for who, name in tool_bindings(spec): if "{{" in name: - return f"没有权限:{who}的工具名由模板拼成,发起前无法确定是哪个工具,使用者在问数据中不能这样绑定工具" + return f"没有权限:{who}的工具名由模板拼成,发起前无法确定是哪个工具,使用者在{where}中不能这样绑定工具" if not _tool_allowed(name): - return (f"没有权限:{who}绑定了工具「{name}」。使用者在问数据中只能使用数据源查询和只读的内置工具" + return (f"没有权限:{who}绑定了工具「{name}」。使用者在{where}中只能使用数据源查询和只读的内置工具" "(计算、当前时间、JSON 取值、知识库检索、记忆读取)") return None diff --git a/backend/app/blueprints/generation.py b/backend/app/blueprints/generation.py new file mode 100644 index 00000000..fc3ab8b0 --- /dev/null +++ b/backend/app/blueprints/generation.py @@ -0,0 +1,378 @@ +"""蓝图和关节的生成(N2、N3、N11):接到 api/copilot_gen.Generation 上的两对落地与自查。 + +- BlueprintApplier / BlueprintChecker:蓝图助手只收 bp_* 操作,落地走 blueprints/ops.apply_bp_op(来源记 assistant, + 只提议:助手写的项都是「待确认」)。复用口径卡的操作按这一轮读好的口径核对并补上它读的列(look/calibers); + 越界被拒的照实交回模型一次、交付时列给人看(同 AppApplier 的做法)。 +- TemplateApplier / TemplateChecker:填关节只收 fill_joint {joint, value},而且只收这一组里模板声明过的生成关节; + 改别的位置、别的组的关节、或者用别的操作,一律拒绝并照实交回(照 apps/ops.polish_problem 的写法)。自查跑 GraphChecker + 的 SQL 检查(只读守卫、猜列、数据源范围、目录检查)、指标式的白名单(只许 cell() 取格加算术)和 engine/lineage.static_stops + (静态追到原始数据),再和骨架逐节点比对(tpl.skeleton_changed)。 +""" +from __future__ import annotations + +import copy +import json +import re +from typing import Any + +from app.blueprints.ops import BpRefused, apply_bp_op +from app.blueprints.spec import BP_OPS +from app.look.base import Applied + +#: 越界被拒的编号(交回模型、列给人看) +BP_REFUSED = "bp.refused" +JOINT_REFUSED = "tpl.joint_refused" +JOINT_UNFILLED = "tpl.joint_unfilled" +METRIC_EXPR = "tpl.metric_expr" +METRIC_COLUMN = "tpl.metric_column" +SQL_REJECTED = "tpl.sql_rejected" +#: 指标式里能用的函数:取格和算术(叙述层不做算术,算术只在口径卡里,P7) +METRIC_FUNCS = frozenset({"cell", "round", "abs", "min", "max"}) + +BLUEPRINT_REPAIR_PROMPT = ( + "这是你刚改好的蓝图:\n{spec}\n\n检查发现下面这些问题:\n{issues}\n\n" + "只修这些问题,别的不要动。用 bp_* 操作输出修正;拿不准、要用户拿主意的用 bp_ask 问。最后一行输出 done。{looks}") +TEMPLATE_REPAIR_PROMPT = ( + "这是你刚填的关节:\n{values}\n\n检查(和发布同一套规则)发现下面这些问题:\n{issues}\n\n" + "只修这些问题:用 fill_joint 重新填有问题的关节(整段重写),别的不要动。最后一行输出 done。{looks}") +REPAIR_LOOKS_PROMPT = "\n\n这一轮查看过的内容(和起草时看到的是同一份):\n{text}" +ISSUE_LINE_PROMPT = "- {where}{message}" + + +def _issue_lines(issues: list[dict[str, Any]]) -> str: + return "\n".join(ISSUE_LINE_PROMPT.format(where=f"{i.get('path') or i.get('joint') or i.get('node_id') or ''} ", + message=i.get("for_model") or i.get("message") or "").replace(" ", " ") + for i in issues) + + +# ========================================================================== +# 蓝图 +# ========================================================================== + + +class BlueprintApplier: + """蓝图的落地:bp_* 操作按 ops.apply_bp_op 落到 spec 上(每落一个换一份新的),来源记 assistant。 + + plan、done 记下说明;reply 记下(这句话不需要改蓝图);bp_ask 记进反问(Generation 读到它就结束这一轮);别的操作一概 + 不收。calibers 是这一轮读好的口径(look/calibers.CaliberKind):复用口径卡的操作按它核对、补上读的列。""" + + def __init__(self, spec: dict[str, Any], *, calibers: Any = None) -> None: + self.spec = spec + self.calibers = calibers + self.effective: list[dict[str, Any]] = [] + self.plan: dict[str, Any] | None = None + self.replied: dict[str, Any] | None = None + self.explanation = "" + #: 越界被拒的操作:[{op, path, message, code}] + self.refused: list[dict[str, Any]] = [] + self._reported = 0 + self._landed: list[str] = [] + self._continuing = False + self._repairing = False + + def apply(self, op: dict[str, Any]) -> Applied: + kind = str(op.get("op") or "") + if kind == "plan": + if self.plan is not None and self._continuing: + return Applied(False, False) + self.plan = self.plan or op + return Applied(False, True) + if kind == "done": + self.explanation = str(op.get("explanation", "")) + return Applied(False, True) + if kind == "reply": + if self.replied is None and not self._repairing: + self.replied = op + return Applied(False, False) + if kind not in BP_OPS: + return Applied(False, False) + if self._continuing and op in self.effective: + return Applied(False, False) + op = {k: v for k, v in op.items() if k in ("op", "path", "value", "question", "options", "template")} + try: + op = self._with_reuse(op) + self.spec = apply_bp_op(self.spec, op, source="assistant") + except BpRefused as e: + self.refused.append({"op": kind, "path": op.get("path"), "message": e.message, "code": e.code}) + return Applied(False, False, e.message) + self.effective.append(op) + where = str(op.get("path") or op.get("op")) + if where not in self._landed: + self._landed.append(where) + return Applied(True, True) + + def _with_reuse(self, op: dict[str, Any]) -> dict[str, Any]: + """复用口径卡:按这一轮读好的口径核对,补上那张卡读的取数节点和列。没读口径(calibers 为空)时原样交给存的那一步核。""" + if self.calibers is None: + return op + path = str(op.get("path") or "") + if op.get("op") == "bp_set" and path.endswith("/reuse") and isinstance(op.get("value"), dict): + return {**op, "value": self._reuse(op["value"])} + if op.get("op") == "bp_add" and isinstance(op.get("value"), dict) and isinstance(op["value"].get("reuse"), dict): + return {**op, "value": {**op["value"], "reuse": self._reuse(op["value"]["reuse"])}} + return op + + def _reuse(self, ref: dict[str, Any]) -> dict[str, Any]: + reuse, reason = self.calibers.reuse_for(ref) + if reuse is None: + raise BpRefused(f"这张口径卡不能复用:{reason}", code="bp.data_unmapped") + return reuse + + def landed(self) -> list[str]: + return list(self._landed) + + def continuing(self) -> None: + self._continuing = True + + def repairing(self) -> None: + self._repairing = True + + def unreported(self) -> list[dict[str, Any]]: + out = self.refused[self._reported:] + self._reported = len(self.refused) + return out + + def refusals(self) -> list[dict[str, Any]]: + """交付时列给人看的:助手想改什么、为什么没改(警告级)。""" + return [{"code": r["code"], "level": "warning", "path": r["path"], + "message": f"助手提的这一处没有采纳:{r['message']}"} for r in self.refused] + + +class BlueprintChecker: + """蓝图的自查:越界被拒、还没交回过的操作,加上卡片内容超出模板能力的地方(bp.template_mismatch)——这些是助手提错了, + 交回它改。缺的项(bp.missing、bp.data_unmapped……)不交回:缺的往往是只有用户知道的事,逼它补只会让它编,由它在 + 这一轮里 bp_ask 问,或者留给用户在卡片上填。""" + + def __init__(self, applier: BlueprintApplier) -> None: + self.applier = applier + + def lint(self) -> list[dict[str, Any]]: + from app.blueprints.ops import blueprint_issues + + return blueprint_issues(self.applier.spec, for_="trial") + + async def issues(self) -> list[dict[str, Any]]: + refused = [{"code": r["code"], "level": "error", "path": r["path"], "message": r["message"]} + for r in self.applier.unreported()] + return [*refused, *(i for i in self.lint() if i["code"] == "bp.template_mismatch" and i["level"] == "error")] + + def repair_request(self, issues: list[dict[str, Any]], looks_text: str) -> str: + return BLUEPRINT_REPAIR_PROMPT.format(spec=json.dumps(self.applier.spec, ensure_ascii=False), + issues=_issue_lines(issues), + looks=REPAIR_LOOKS_PROMPT.format(text=looks_text) if looks_text else "") + + +# ========================================================================== +# 模板的生成关节 +# ========================================================================== + + +def joint_problem(joints: dict[str, Any], group: list[Any], op: dict[str, Any]) -> str | None: + """填关节时这个操作有没有越界:越界返回交回模型的一句话,没越界返回 None(同 apps/ops.polish_problem 的写法)。 + + joints 是模板声明的全部关节(id → Joint),group 是这一组要填的生成关节。只收 fill_joint、只收这一组的关节、值是一段 + 非空的文字。骨架是锁住的:节点、连线、确定性关节(按卡片填的)和别的配置都不归模型管。""" + from app.blueprints.templates import GENERATED_JOINT_KINDS + + kind = op.get("op") if isinstance(op, dict) else None + mine = {j.id for j in group} + if kind != "fill_joint": + return (f"填关节只能用 fill_joint 填模板留给你的位置({'、'.join(sorted(mine))}),不能用 {kind}:" + "模板的节点、连线和别的配置是锁住的") + joint_id = str(op.get("joint") or "") + joint = joints.get(joint_id) + if joint is None: + return f"模板里没有关节「{joint_id}」:这一轮只能填 {'、'.join(sorted(mine))}" + if joint.kind not in GENERATED_JOINT_KINDS: + return f"「{joint.label or joint_id}」按卡片确定地填,不归助手管:要改请回到蓝图卡片" + if joint_id not in mine: + return f"「{joint.label or joint_id}」不在这一组里(这一组只填 {'、'.join(sorted(mine))}),由别的那一组填" + value = op.get("value") + if not isinstance(value, str) or not value.strip(): + return f"「{joint.label or joint_id}」要写一段非空的文字({'SQL' if joint.kind == 'sql' else '指标式'})" + if len(value) > 20_000: + return f"「{joint.label or joint_id}」太长了(超过 20000 字)" + return None + + +class TemplateApplier: + """一组生成关节的落地:fill_joint 把值写到图上那个位置(graph 是这一组自己的那一份,原地改),值记在 values 里。 + + 越界的照实交回(refused),自查时交回模型一次,交付时列给人看。""" + + def __init__(self, graph: dict[str, Any], joints: list[Any], group: list[Any]) -> None: + self.graph = graph + self.joints = {j.id: j for j in joints} + self.group = list(group) + self.values: dict[str, str] = {} + self.plan: dict[str, Any] | None = None + self.replied: dict[str, Any] | None = None + self.explanation = "" + self.refused: list[dict[str, Any]] = [] + self.effective: list[dict[str, Any]] = [] + self._reported = 0 + self._continuing = False + self._repairing = False + + def apply(self, op: dict[str, Any]) -> Applied: + from app.blueprints.instantiate import node_config, write_at + + kind = str(op.get("op") or "") + if kind == "plan": + if self.plan is not None and self._continuing: + return Applied(False, False) + self.plan = self.plan or op + return Applied(False, True) + if kind == "done": + self.explanation = str(op.get("explanation", "")) + return Applied(False, True) + if kind == "reply": + if self.replied is None and not self._repairing: + self.replied = op + return Applied(False, False) + if problem := joint_problem(self.joints, self.group, op): + self.refused.append({"op": kind, "joint": op.get("joint"), "message": problem}) + return Applied(False, False, problem) + joint = self.joints[str(op["joint"])] + value = str(op["value"]).strip() + if self.values.get(joint.id) == value: + return Applied(False, False) + config = node_config(self.graph, joint.node_id) + if config is None: + return Applied(False, False, f"图上没有节点 {joint.node_id}") + write_at(config, joint.field, value) + self.values[joint.id] = value + self.effective.append(op) + return Applied(True, True) + + def landed(self) -> list[str]: + return list(self.values) + + def continuing(self) -> None: + self._continuing = True + + def repairing(self) -> None: + self._repairing = True + + def unreported(self) -> list[dict[str, Any]]: + out = self.refused[self._reported:] + self._reported = len(self.refused) + return out + + def refusals(self) -> list[dict[str, Any]]: + return [{"code": JOINT_REFUSED, "level": "warning", "joint": r.get("joint"), + "message": f"助手想改的这一处没有采纳:{r['message']}"} for r in self.refused] + + +class TemplateChecker: + """一组生成关节的自查:越界被拒的、还没填的、SQL 检查(GraphChecker:只读守卫、猜列、目录检查)、指标式白名单和 + 静态追到原始数据(engine/lineage.static_stops)、骨架比对。只报这一组的节点上的问题:别的组在并行地填,它们的占位 + 不归这一组管。""" + + def __init__(self, applier: TemplateApplier, *, skeleton: dict[str, Any], sources: list[Any] | None = None, + checkers: dict[str, Any] | None = None) -> None: + self.applier = applier + self.skeleton = skeleton + self.sources = sources or [] + self.checkers = checkers + + def _nodes(self) -> dict[str, dict[str, Any]]: + return {n["id"]: n for n in self.applier.graph.get("nodes") or [] if isinstance(n, dict) and n.get("id")} + + async def issues(self) -> list[dict[str, Any]]: + from app.blueprints.instantiate import skeleton_changes + + out = [{"code": JOINT_REFUSED, "level": "error", "joint": r.get("joint"), "message": r["message"]} + for r in self.applier.unreported()] + out += [{"code": JOINT_UNFILLED, "level": "error", "joint": j.id, "node_id": j.node_id, + "message": f"「{j.label or j.id}」还没填:用 fill_joint 填上"} + for j in self.applier.group if j.id not in self.applier.values] + out += self._sql_issues() + out += self._metric_issues() + out += skeleton_changes(self.skeleton, self.applier.graph, list(self.applier.joints.values())) + return out + + def _sql_issues(self) -> list[dict[str, Any]]: + """这一组 SQL 关节所在的取数节点:只读守卫、再按 GraphChecker(和改图助手同一套:猜列、目录检查、画布校验)。""" + from app.api.copilot_gen import GraphApplier, GraphChecker + from app.data.guard import SqlRejected, check + + nodes = self._nodes() + mine = {j.node_id for j in self.applier.group if j.kind == "sql" and j.id in self.applier.values} + if not mine: + return [] + out: list[dict[str, Any]] = [] + kinds = {getattr(s, "name", None): getattr(s, "kind", None) for s in self.sources} + for node_id in sorted(mine): + config = (nodes[node_id].get("data") or {}).get("config") or {} + sql = str((config.get("args") or {}).get("sql") or "") + source = str(config.get("tool") or "").removeprefix("db_query__") + try: + # 模板写法({{ input.period_start }})换成一个字面量再查:守卫按 SQL 本身判,不按渲染出来的值判 + check(re.sub(r"\{\{.*?\}\}", "0", sql, flags=re.S), readonly=True, source_name=source, + dialect=kinds.get(source)) + except SqlRejected as e: + out.append({"code": SQL_REJECTED, "level": "error", "node_id": node_id, "field": "args.sql", + "message": f"取数的 SQL 过不了只读检查:{e}"}) + graph = GraphApplier(copy.deepcopy(nodes), copy.deepcopy(self.applier.graph.get("edges") or [])) + checker = GraphChecker(graph, sources=self.sources, checkers=self.checkers) + out += [i for i in checker.blocking() or [] if i.get("node_id") in mine] + return out + + def _metric_issues(self) -> list[dict[str, Any]]: + """指标式:只许 cell(nodes.<这一组的取数节点>, 0, '列名') 取格加算术、比较;静态追得到原始数据;取的列在那条 SQL 里。""" + import ast + + from app.engine.expressions import ExpressionError, cell_parts, leaf_refs, parse_expression + from app.engine.lineage import static_stops + + nodes = self._nodes() + fetches = {j.node_id for j in self.applier.group if j.kind == "sql"} + flat = {nid: {"type": n.get("type"), "title": (n.get("data") or {}).get("label") or nid, + "config": (n.get("data") or {}).get("config") or {}} for nid, n in nodes.items()} + out: list[dict[str, Any]] = [] + for j in self.applier.group: + if j.kind != "metric_expr" or j.id not in self.applier.values: + continue + expr = self.applier.values[j.id] + + def bad(message: str, code: str = METRIC_EXPR) -> None: + out.append({"code": code, "level": "error", "joint": j.id, "node_id": j.node_id, + "message": f"「{j.label or j.id}」{message}"}) + + try: + tree = parse_expression(expr)[0] + except ExpressionError as e: + bad(f"写得不对:{e}") + continue + calls = {n.func.id for n in ast.walk(tree) if isinstance(n, ast.Call) and isinstance(n.func, ast.Name)} + if extra := sorted(calls - METRIC_FUNCS): + bad(f"只能用 cell() 取格再做算术(可以用 {'、'.join(sorted(METRIC_FUNCS))}),不能用 {'、'.join(extra)}") + continue + refs = leaf_refs(tree) + if not refs: + bad("没有取任何数:要用 cell() 从取数的结果里取格") + continue + for path in refs: + parts = cell_parts(path) + node_id = parts[0][len("nodes."):] if parts and parts[0].startswith("nodes.") else "" + if parts is None or node_id not in fetches: + bad(f"只能用 cell(nodes.{'/'.join(sorted(fetches))}, 0, '列名') 取这一组取数的格,不能写 {path}") + break + if parts[1].strip() != "0": + bad("取数只出一行:行号写 0") + break + column = parts[2].strip().strip("'\"") + sql = str(((flat[node_id]["config"].get("args") or {}).get("sql")) or "") + if not re.search(rf"(? str: + values = "\n".join(f"{jid}:{value}" for jid, value in self.applier.values.items()) or "(还没填)" + return TEMPLATE_REPAIR_PROMPT.format(values=values, issues=_issue_lines(issues), + looks=REPAIR_LOOKS_PROMPT.format(text=looks_text) if looks_text else "") diff --git a/backend/app/blueprints/instantiate.py b/backend/app/blueprints/instantiate.py index 47468559..e7a59e1c 100644 --- a/backend/app/blueprints/instantiate.py +++ b/backend/app/blueprints/instantiate.py @@ -1,13 +1,26 @@ """按模板实例化蓝图(N3、§3.3–§3.4):确定性关节按卡片填,生成关节留给模型(TemplateApplier 的 fill_joint), 实例化后的图和骨架逐节点比对,只许关节位置不同。模型失败时生成关节留空、标「待填」(P3)。 -包 B1 实现。 +实例化是纯函数:不读库、不落库。读库的那几样由调用方先读好放进上下文(工作流 id、蓝图 id、定时任务 id、记录表、 +自由形导入的图)。图按画布保存时的样子规范化(GraphSpec 解析、自动排版、序列化):图哈希、试运行和发布单按哈希对齐 +(N4)都认这一份。 + +生成关节的值和依据存在蓝图的 joints 上({joint_id: {status, by, note?, value?, basis?}}):卡片改了、这一组关节的 +说明变了(basis 对不上),之前填的就不算数,重新标「待填」(filled_from)。 """ from __future__ import annotations +import copy from dataclasses import dataclass, field +from datetime import datetime from typing import Any +#: 关节的状态 +JOINT_STATUSES = ("filled", "pending", "refused") +#: 骨架比对的问题编号 +SKELETON_CHANGED = "tpl.skeleton_changed" +JOINT_UNFILLED = "tpl.joint_unfilled" + @dataclass class Instantiated: @@ -20,13 +33,296 @@ class Instantiated: #: 定时任务参数(看板类)或 None schedule: dict[str, Any] | None problems: list[dict[str, Any]] = field(default_factory=list) + #: 岗位绑定(应用的 draft_bindings 形状):「谁来做」里写了具体的人或组的那几个岗位 + bindings: dict[str, Any] = field(default_factory=dict) + #: 模板的骨架(规范化后的、生成关节是占位的那张图):骨架比对、TemplateChecker 用 + skeleton: dict[str, Any] = field(default_factory=dict) + #: 模板声明的关节(blueprints/templates.Joint) + joint_defs: list[Any] = field(default_factory=list) + #: 每组生成关节给模型的说明 {group: 说明},和依据的指纹 {group: basis} + briefs: dict[str, str] = field(default_factory=dict) + basis: dict[str, str] = field(default_factory=dict) -def instantiate(blueprint: dict[str, Any], *, filled: dict[str, Any] | None = None) -> Instantiated: - """蓝图 + 已填的生成关节({joint_id: value})→ 图、关节状态、应用草稿、定时任务参数。纯函数,不落库。""" - raise NotImplementedError +# ========================================================================== +# 图上的位置(关节的 field 是节点配置里的 JSON 指针) +# ========================================================================== + + +def _tokens(pointer: str) -> list[str]: + return [p.replace("~1", "/").replace("~0", "~") for p in pointer.lstrip("/").split("/")] if pointer.strip("/") else [] + + +def read_at(config: Any, pointer: str) -> Any: + cur = config + for token in _tokens(pointer): + if isinstance(cur, list) and token.isdigit() and int(token) < len(cur): + cur = cur[int(token)] + elif isinstance(cur, dict): + cur = cur.get(token) + else: + return None + return cur + + +def write_at(config: dict[str, Any], pointer: str, value: Any) -> None: + tokens = _tokens(pointer) + cur: Any = config + for token in tokens[:-1]: + cur = cur[int(token)] if isinstance(cur, list) else cur.setdefault(token, {}) + if isinstance(cur, list): + cur[int(tokens[-1])] = value + else: + cur[tokens[-1]] = value + + +def _blank_at(config: dict[str, Any], pointer: str) -> None: + """骨架比对时把关节位置抹掉:两边都抹,只比别的地方。""" + tokens = _tokens(pointer) + cur: Any = config + for token in tokens[:-1]: + if isinstance(cur, list) and token.isdigit() and int(token) < len(cur): + cur = cur[int(token)] + elif isinstance(cur, dict) and token in cur: + cur = cur[token] + else: + return + if isinstance(cur, list) and tokens[-1].isdigit() and int(tokens[-1]) < len(cur): + cur[int(tokens[-1])] = None + elif isinstance(cur, dict): + cur.pop(tokens[-1], None) + + +def node_config(graph: dict[str, Any], node_id: str) -> dict[str, Any] | None: + for n in graph.get("nodes") or []: + if isinstance(n, dict) and n.get("id") == node_id: + data = n.setdefault("data", {}) + if not isinstance(data.get("config"), dict): + data["config"] = {} + return data["config"] + return None + + +def normalize(graph: dict[str, Any]) -> dict[str, Any]: + """按画布保存时的样子规范化:GraphSpec 解析、自动排版、序列化。坐标由结构定,同一张图每次都一样。""" + from app.engine.layout import auto_layout + from app.engine.schema import GraphSpec + + return auto_layout(GraphSpec.model_validate(graph)).model_dump(mode="json") + + +# ========================================================================== +# 骨架比对 +# ========================================================================== def skeleton_changes(template_graph: dict[str, Any], graph: dict[str, Any], joints: list[Any]) -> list[dict[str, Any]]: - """骨架比对:除关节位置外的任何差异都交回(tpl.skeleton_changed)。""" - raise NotImplementedError + """骨架比对:除关节位置外的任何差异都交回(tpl.skeleton_changed)。照 engine/autofix.forbidden_changes 的写法逐节点比: + 节点增删、换类型、改标题、配置里关节以外的地方、连线、全图默认。坐标不比(排版的事)。""" + from app.engine.schema import type_label + + def nodes_of(g: dict[str, Any]) -> dict[str, dict[str, Any]]: + return {str(n["id"]): n for n in g.get("nodes") or [] if isinstance(n, dict) and n.get("id")} + + def title(n: dict[str, Any]) -> str: + return str((n.get("data") or {}).get("label") or n.get("id")) + + old, new = nodes_of(template_graph), nodes_of(graph) + at: dict[str, list[str]] = {} + for j in joints: + at.setdefault(j.node_id, []).append(j.field) + out: list[dict[str, Any]] = [] + + def add(message: str, node_id: str | None = None, field: str | None = None) -> None: + out.append({"code": SKELETON_CHANGED, "level": "error", "node_id": node_id, "field": field, + "message": f"改动超出了模板的关节:{message}"}) + + for nid, n in old.items(): + if nid not in new: + add(f"删除了节点「{title(n)}」", nid) + for nid, n in new.items(): + was = old.get(nid) + if was is None: + add(f"多出了节点「{title(n)}」", nid) + continue + if was.get("type") != n.get("type"): + add(f"把「{title(was)}」从{type_label(was.get('type'))}换成了{type_label(n.get('type'))}", nid) + if title(was) != title(n): + add(f"改了节点「{title(was)}」的标题", nid) + before = copy.deepcopy((was.get("data") or {}).get("config") or {}) + after = copy.deepcopy((n.get("data") or {}).get("config") or {}) + for pointer in at.get(nid, []): + _blank_at(before, pointer) + _blank_at(after, pointer) + if before != after: + keys = sorted(k for k in set(before) | set(after) if before.get(k) != after.get(k)) + add(f"改了「{title(n)}」关节以外的配置({'、'.join(keys)})", nid, keys[0] if keys else None) + + def edges_of(g: dict[str, Any]) -> set[tuple[str, str, str]]: + return {(str(e.get("source")), str(e.get("target")), str(e.get("sourceHandle") or "")) + for e in g.get("edges") or [] if isinstance(e, dict)} + + for s, t, _ in sorted(edges_of(template_graph) - edges_of(graph)): + add(f"删除了连线「{title(old.get(s) or {'id': s})}」→「{title(old.get(t) or {'id': t})}」") + for s, t, _ in sorted(edges_of(graph) - edges_of(template_graph)): + add(f"多出了连线「{title(new.get(s) or {'id': s})}」→「{title(new.get(t) or {'id': t})}」") + if (template_graph.get("defaults") or {}) != (graph.get("defaults") or {}): + add("改了全图默认") + return out + + +# ========================================================================== +# 实例化 +# ========================================================================== + + +def _spec_of(blueprint: Any) -> dict[str, Any]: + from app.blueprints.spec import parse_blueprint + + raw = getattr(blueprint, "spec", blueprint) + return parse_blueprint(raw or {}).model_dump(mode="json", by_alias=True) + + +def instantiate(blueprint: dict[str, Any], *, filled: dict[str, Any] | None = None, name: str | None = None, + workflow_id: str | None = None, blueprint_id: str | None = None, schedule_id: str | None = None, + records: dict[str, str] | None = None, graph: dict[str, Any] | None = None) -> Instantiated: + """蓝图 + 已填的生成关节({joint_id: value})→ 图、关节状态、应用草稿、定时任务参数。纯函数,不落库。 + + blueprint 是 agentlab.blueprint/1(或带 spec 的蓝图行)。另几样是调用方读好的上下文:name 是应用和工作流的名字; + workflow_id 给了,应用草稿的钉住项挂在这个工作流上,没给挂在蓝图上(blueprint_id);schedule_id 是看板视图要绑的 + 定时任务;records 是填报登记的记录表 {table, source};graph 是自由形导入的图。""" + from app.blueprints.ops import blueprint_issues + from app.blueprints.templates import GENERATED_JOINT_KINDS, get_template + from app.blueprints.templates import _common as c + + spec = _spec_of(blueprint) + ref = spec.get("template") or {} + template = get_template(str(ref.get("id") or "")) + problems = [i for i in blueprint_issues(spec, for_="trial") if i["level"] == "error"] + if template is None: + from app.apps.spec import empty_spec + + return Instantiated(graph={"nodes": [], "edges": []}, joints={}, app_spec=empty_spec(name or "应用"), + schedule=None, problems=problems) + bp = {**copy.deepcopy(spec), c.CONTEXT_KEY: { + "name": name, "workflow_id": workflow_id, "blueprint_id": blueprint_id, "schedule_id": schedule_id, + "records": records, "graph": graph}} + raw, joint_defs = template.skeleton(bp) + extras = c.EXTRAS.get(template.id) + # 自由形导入的图原样用、不重新排版:它的哈希要和导入的那一版对得上,发布单才按哈希复用那一版 + skeleton = copy.deepcopy(raw) if extras is not None and extras.imports_graph else normalize(raw) + out = copy.deepcopy(skeleton) + briefs = extras.briefs(bp) if extras is not None and extras.briefs is not None else {} + basis = {g: c.basis_of(text, template.id, template.version) for g, text in briefs.items()} + joints: dict[str, Any] = {} + filled = filled or {} + for j in joint_defs: + if j.kind not in GENERATED_JOINT_KINDS: + joints[j.id] = {"status": "filled", "by": "template"} + continue + value = filled.get(j.id) + config = node_config(out, j.node_id) + if isinstance(value, str) and value.strip() and config is not None: + write_at(config, j.field, value.strip()) + joints[j.id] = {"status": "filled", "by": "assistant", "value": value.strip(), + **({"basis": basis[j.group]} if j.group in basis else {})} + else: + joints[j.id] = {"status": "pending", "by": "template", "note": "这一项助手还没填上:可以请助手填,或者换个说法再试"} + problems.append({"code": JOINT_UNFILLED, "level": "error", "node_id": j.node_id, "field": j.field, + "joint": j.id, "message": f"「{j.label or j.id}」还没填"}) + problems += skeleton_changes(skeleton, out, joint_defs) + problems += _graph_errors(out) + app_spec = template.app_skeleton(bp, out) if template.app_skeleton is not None else {} + schedule = template.schedule(bp) if template.schedule is not None else None + return Instantiated(graph=out, joints=joints, app_spec=app_spec, schedule=schedule, + problems=_dedupe(problems), bindings=c.bindings_of(bp), skeleton=skeleton, + joint_defs=list(joint_defs), briefs=briefs, basis=basis) + + +def _graph_errors(graph: dict[str, Any]) -> list[dict[str, Any]]: + """实例化出来的图过画布校验(engine/schema.validate_graph):error 照实交回。""" + from app.engine.schema import GraphSpec, validate_graph + + return [i.model_dump() for i in validate_graph(GraphSpec.model_validate(graph)).issues if i.level == "error"] + + +def _dedupe(problems: list[dict[str, Any]]) -> list[dict[str, Any]]: + seen: set[tuple[Any, ...]] = set() + out = [] + for p in problems: + key = (p.get("code"), p.get("path"), p.get("node_id"), p.get("field"), p.get("message")) + if key not in seen: + seen.add(key) + out.append(p) + return out + + +def filled_from(blueprint: dict[str, Any], joints: dict[str, Any] | None, *, + graph: dict[str, Any] | None = None, records: dict[str, str] | None = None) -> dict[str, Any]: + """蓝图上存的生成关节里还算数的值:状态是已填、依据(这一组的说明的指纹)没变。卡片改过、说明变了的不算(要重新填)。""" + probe = instantiate(blueprint, records=records, graph=graph) + out: dict[str, Any] = {} + for j in probe.joint_defs: + state = (joints or {}).get(j.id) or {} + if state.get("status") == "filled" and isinstance(state.get("value"), str) \ + and state.get("basis") == probe.basis.get(j.group or ""): + out[j.id] = state["value"] + return out + + +def generated_groups(inst: Instantiated) -> dict[str, list[Any]]: + """生成关节按组:{group: [Joint]}。不同组的并行填(N11)。""" + from app.blueprints.templates import GENERATED_JOINT_KINDS + + out: dict[str, list[Any]] = {} + for j in inst.joint_defs: + if j.kind in GENERATED_JOINT_KINDS: + out.setdefault(j.group or j.id, []).append(j) + return out + + +def trial_inputs(blueprint: dict[str, Any], *, at: datetime | None = None) -> dict[str, Any]: + """试运行的输入(N4):看板类按「多久更新」算出最近一期(和定时任务到点渲染的是同一份),流程类没有(用户填示例表单)。""" + from datetime import timezone + + from app.scheduler import service + + inst = instantiate(blueprint) + if inst.schedule is None: + return {} + moment = at or datetime.now(timezone.utc) + values = service.template_values(moment, inst.schedule["timezone"], inst.schedule["cron"]) + return service.render_inputs(inst.schedule["input_template"], values) + + +# ========================================================================== +# 模板登记的核对(启动时、测试里) +# ========================================================================== + + +def registry_problems() -> list[str]: + """模板登记齐不齐:首批都登记了(check_registry)、关节类型都认得、每个模板都给了示例蓝图,示例实例化出来过得了 + 画布校验、骨架比对没有差异(模板定义、实例化、测试三样都要给,缺一样启动即报错,N3)。""" + from app.blueprints.templates import JOINT_KINDS, check_registry, list_templates + from app.blueprints.templates import _common as c + + problems = list(check_registry()) + for template in list_templates(): + extras = c.EXTRAS.get(template.id) + if extras is None: + problems.append(f"模板「{template.id}」没有示例蓝图") + continue + try: + graph = None + if extras.imports_graph: + from app.blueprints.templates.freeform import example_graph + + graph = example_graph() + inst = instantiate(extras.example(), filled=extras.example_fill(), graph=graph) + except Exception as e: # noqa: BLE001 - 核对本身出错也照实报,不让启动卡在异常上 + problems.append(f"模板「{template.id}」的示例实例化出错:{e}") + continue + problems += [f"模板「{template.id}」的关节类型「{j.kind}」不认得" for j in inst.joint_defs + if j.kind not in JOINT_KINDS] + problems += [f"模板「{template.id}」的示例:{p['message']}" for p in inst.problems if p["level"] == "error"] + return problems diff --git a/backend/app/blueprints/ops.py b/backend/app/blueprints/ops.py index 8adc7358..8ce2798f 100644 --- a/backend/app/blueprints/ops.py +++ b/backend/app/blueprints/ops.py @@ -1,12 +1,29 @@ """bp_* 操作的确定性落地(N2、§3.2)。模型(BlueprintApplier)和用户(PATCH /api/blueprints/{id})用同一组操作, 只是来源记成 assistant 或 user。每张卡片有白名单(例如 people[].policy.kind 只能是 any / all / quorum),越界的拒绝并照实交回。 -包 B1 实现。 +路径是 JSON 指针,能写的位置逐项列在 _SETTERS 里: +- 卡片上的一项(Item):写值(/purpose、/data/0/table、/people/1/due……),来源记成这次操作的来源,用户写的记「已确认」, + 助手写的记「待确认」,写空记「缺」;/…/why 写一句「为什么」;/…/status 只收用户的「确认」(值不变、来源不变); +- 列表(/data、/people、/fields、/access/use……):bp_add 追加(/data、/data/- )或插到某个位置(/data/2),bp_remove 删一项; + 新加的一项里卡片字段写纯值,来源和状态按这次操作记; +- /asks:bp_ask 追加一个反问(只有助手问),/asks//answer 记用户的回答; +- 选模板只走 bp_template:记下模板和版本,按模板预置还没填的卡片(来源记「模板默认」、状态「待确认」)。 + +「谁能看」(access)只收用户的操作:授权是人的决定,助手提的没有「待确认」可挂(P2)。 +落地前后都按 agentlab.blueprint/1 的形状核一遍(spec.parse_blueprint),不合形状的一律拒。 """ from __future__ import annotations +import copy +import keyword +import re +from collections.abc import Callable from typing import Any +from pydantic import ValidationError + +from app.blueprints.spec import BP_OPS, BpOp, parse_blueprint + class BpRefused(Exception): """操作被拒:message 是写给人看的一句话,code 是 bp.* 机器码。""" @@ -17,12 +34,802 @@ class BpRefused(Exception): self.code = code +#: 操作的来源:用户在卡片上改的、助手提的 +BP_SOURCES = ("user", "assistant") +#: 统计哪一期(入口字段和定时任务的输入模板按它取,blueprints/templates/_common.PERIODS) +PERIODS = ("today", "yesterday", "this_iso_week", "last_iso_week", "this_month", "last_month") +CADENCE_PRESETS = ("daily", "weekly", "monthly") +#: 「谁来做」里一个处理人的种类:人、组、岗位、发起人 +WHO_KINDS = ("user", "group", "slot", "initiator") +POLICY_KINDS = ("any", "all", "quorum") +TIMEOUT_ACTIONS = ("remind", "escalate", "reject") +#: 金额线只许「字段 比较 常量」 +THRESHOLD_OPS = (">", ">=", "<", "<=", "==", "!=") +#: 「谁能看」的三档和能授权的对象 +ACCESS_KINDS = ("use", "observe", "manage") +GRANTEE_KINDS = ("user", "group") +#: 入口字段里模板自己要用的名字(统计期),「填什么」不能占 +RESERVED_FIELDS = frozenset({"period", "period_start", "period_end", "mode"}) +#: 列表的上限:再多就不是普通人在卡片上能判断对错的颗粒度了 +LIST_LIMITS = {"data": 20, "people": 6, "fields": 40, "use": 50, "observe": 50, "manage": 50} + +#: 数据项、步骤的 id 进节点 id 和指标 id:只用小写字母、数字、下划线 +_ID = re.compile(r"^[a-z][a-z0-9_]{0,31}$") +_TIME = re.compile(r"^([01]\d|2[0-3]):([0-5]\d)$") +#: 卡片上的时限说法:「48 小时」「2 天」「1 周」「30 分钟」 +_PLAIN_DURATION = re.compile(r"^\s*(\d{1,4})\s*(分钟|小时|个小时|天|日|周|星期)\s*$") +_DURATION_UNIT = {"分钟": ("T", "M"), "小时": ("T", "H"), "个小时": ("T", "H"), "天": ("", "D"), "日": ("", "D"), + "周": ("", "W"), "星期": ("", "W")} +#: 写回的参数映射:入口表单字段、指标、核对出来的那几行(核对写回) +_MAP_SOURCE = re.compile(r"^(form|metric)\.([^\s.]{1,64})$") +_MAP_ROWS = "rows" + +_ITEM_FIELDS = { + "data": ("label", "unit", "table", "measure", "date", "filter", "grain"), + "people": ("label", "who", "policy", "due", "on_timeout", "threshold"), +} +_LABEL = {"purpose": "目的", "template": "场景", "data": "看哪些数", "cadence": "多久更新", "people": "谁来做", + "fields": "填什么", "writeback": "写回哪里", "access": "谁能看", "asks": "反问"} + + +# ========================================================================== +# JSON 指针 +# ========================================================================== + + +def parse_pointer(path: Any) -> list[str]: + """/data/0/table → ["data", "0", "table"]。不是 JSON 指针的抛 BpRefused。""" + if not isinstance(path, str) or not path.startswith("/") or path == "/": + raise BpRefused(f"位置要写成 /purpose、/data/0/table 这样的路径,当前为「{path}」") + return [p.replace("~1", "/").replace("~0", "~") for p in path[1:].split("/")] + + +def _index(token: str, size: int, *, allow_end: bool = False) -> int: + if allow_end and token == "-": + return size + if not token.isdigit(): + raise BpRefused(f"列表的位置要写成数字,当前为「{token}」") + at = int(token) + if at > size or (at == size and not allow_end): + raise BpRefused(f"位置 {at} 超出了列表的范围(现有 {size} 项)") + return at + + +# ========================================================================== +# 各项的白名单(值 → 规范化后的值;不合规抛 BpRefused) +# ========================================================================== + + +def _text(limit: int, what: str) -> Callable[[Any, dict[str, Any]], Any]: + def check(value: Any, _spec: dict[str, Any]) -> Any: + if not isinstance(value, str) or not value.strip(): + raise BpRefused(f"「{what}」要写一段文字") + if len(value.strip()) > limit: + raise BpRefused(f"「{what}」最多 {limit} 个字") + return value.strip() + + return check + + +def _identifier(name: Any) -> bool: + return isinstance(name, str) and 0 < len(name) <= 40 and name.isidentifier() and not keyword.iskeyword(name) + + +def _table(value: Any, _spec: dict[str, Any]) -> Any: + if not isinstance(value, dict) or set(value) - {"source", "table"}: + raise BpRefused("对到的表要写明数据源和表名两项") + out = {k: str(value.get(k) or "").strip() for k in ("source", "table")} + if not all(out.values()) or any(len(v) > 200 for v in out.values()): + raise BpRefused("对到的表要写明数据源和表名") + return out + + +def _date(value: Any, _spec: dict[str, Any]) -> Any: + if not isinstance(value, dict) or set(value) - {"column", "rule"} or not str(value.get("column") or "").strip(): + raise BpRefused("业务日期要写明按哪一列算,可以加一句规则(例如按支付日)") + out = {"column": str(value["column"]).strip()[:200]} + if value.get("rule") not in (None, ""): + out["rule"] = _text(60, "业务日期的规则")(value["rule"], _spec) + return out + + +def _cadence(value: Any, _spec: dict[str, Any]) -> Any: + from app.scheduler.cron import TimezoneError, timezone_name + + if not isinstance(value, dict) or set(value) - {"preset", "weekday", "day", "time", "tz", "period"}: + raise BpRefused("「多久更新」要写明每天、每周还是每月,几点,哪个时区,统计哪一期") + preset = value.get("preset") + if preset not in CADENCE_PRESETS: + raise BpRefused("「多久更新」只能是每天、每周或每月") + time = str(value.get("time") or "") + if not _TIME.match(time): + raise BpRefused(f"更新的时间要写成 09:00 这样的 24 小时制,当前为「{time}」") + try: + tz = timezone_name(str(value.get("tz") or "")) + except TimezoneError as e: + raise BpRefused(str(e)) from e + out: dict[str, Any] = {"preset": preset, "time": time, "tz": tz} + if preset == "weekly": + weekday = value.get("weekday") + if isinstance(weekday, bool) or not isinstance(weekday, int) or not 1 <= weekday <= 7: + raise BpRefused("每周更新要写明周几(1 是周一,7 是周日)") + out["weekday"] = weekday + if preset == "monthly": + day = value.get("day") + # 只收 1–28:29 日以后不是每个月都有,那几个月就不出数了 + if isinstance(day, bool) or not isinstance(day, int) or not 1 <= day <= 28: + raise BpRefused("每月更新要写明几号(1 到 28 号,29 号以后不是每个月都有)") + out["day"] = day + period = value.get("period") + if period not in (None, ""): + if period not in PERIODS: + raise BpRefused("统计哪一期只能是今天、昨天、本周、上周、本月或上月") + out["period"] = period + return out + + +def _principal(value: Any, kinds: tuple[str, ...], what: str) -> dict[str, str]: + if not isinstance(value, dict) or set(value) - {"kind", "name"} or value.get("kind") not in kinds: + raise BpRefused(f"{what}要写明种类和名字,种类只能是{_kinds_text(kinds)}") + name = str(value.get("name") or "").strip() + if value["kind"] != "initiator" and not name: + raise BpRefused(f"{what}要写明是谁") + if len(name) > 100: + raise BpRefused(f"{what}的名字最多 100 个字") + return {"kind": value["kind"], "name": name} + + +_KIND_WORDS = {"user": "人", "group": "组", "slot": "岗位", "initiator": "发起人"} + + +def _kinds_text(kinds: tuple[str, ...]) -> str: + words = [_KIND_WORDS[k] for k in kinds] + return "、".join(words[:-1]) + f"或{words[-1]}" if len(words) > 1 else words[0] + + +def _who(value: Any, _spec: dict[str, Any]) -> Any: + if not isinstance(value, list) or len(value) > 20: + raise BpRefused("处理人要写成一组人、组或岗位(最多 20 个)") + out = [_principal(v, WHO_KINDS, "处理人") for v in value] + if any(p["kind"] == "initiator" for p in out) and len(out) > 1: + raise BpRefused("处理人选了发起人时,不能再加别的人") + # 岗位是一个整体(绑到哪些人在应用里定):和具体的人、组混在一起,就说不清这一步派给岗位还是派给这几个人 + if any(p["kind"] == "slot" for p in out) and len(out) > 1: + raise BpRefused("处理人选了岗位时,不能再加别的人、组或岗位") + return out or None + + +def _policy(value: Any, _spec: dict[str, Any]) -> Any: + if isinstance(value, str): + value = {"kind": value} + if not isinstance(value, dict) or set(value) - {"kind", "m"} or value.get("kind") not in POLICY_KINDS: + raise BpRefused("几个人同意算通过,只能是任一人、全体同意或其中若干人同意") + if value["kind"] != "quorum": + if "m" in value: + raise BpRefused("只有「若干人同意」要写人数") + return {"kind": value["kind"]} + m = value.get("m") + if isinstance(m, bool) or not isinstance(m, int) or not 1 <= m <= 50: + raise BpRefused("「若干人同意」要写明几个人(1 到 50)") + return {"kind": "quorum", "m": m} + + +def duration_of(value: Any) -> str | None: + """卡片上的时限 → ISO 8601 时长:「48 小时」→ PT48H,「2 天」→ P2D,ISO 写法原样(大写)。换算不了返回 None。""" + from app.engine.lint_process import parse_duration + + if not isinstance(value, str) or not value.strip(): + return None + text = value.strip() + if m := _PLAIN_DURATION.match(text): + prefix, unit = _DURATION_UNIT[m.group(2)] + text = f"P{prefix}{int(m.group(1))}{unit}" + text = text.upper() + return text if parse_duration(text) is not None else None + + +def _due(value: Any, _spec: dict[str, Any]) -> Any: + iso = duration_of(value) + if iso is None: + raise BpRefused(f"时限要写成「48 小时」「2 天」「1 周」这样的时长,当前为「{value}」(工作日换算不了,请写成天数)") + return iso + + +def _on_timeout(value: Any, _spec: dict[str, Any]) -> Any: + if not isinstance(value, dict) or set(value) - {"action", "to", "every"} or value.get("action") not in TIMEOUT_ACTIONS: + raise BpRefused("超时以后只能提醒、升级给别人或驳回(不会自动同意)") + out: dict[str, Any] = {"action": value["action"]} + if value["action"] == "escalate": + to = value.get("to") + if not isinstance(to, list) or not to: + raise BpRefused("超时升级要写明升级给谁") + out["to"] = [_principal(v, ("user", "group", "slot"), "升级给的人") for v in to[:20]] + elif value.get("to"): + raise BpRefused("只有超时升级要写升级给谁") + if value.get("every") not in (None, ""): + if value["action"] != "remind": + raise BpRefused("只有超时提醒能写提醒间隔") + every = duration_of(value["every"]) + if every is None: + raise BpRefused(f"提醒间隔要写成「1 小时」这样的时长,当前为「{value['every']}」") + out["every"] = every + return out + + +def _threshold(value: Any, spec: dict[str, Any]) -> Any: + if not isinstance(value, dict) or set(value) != {"field", "op", "value"}: + raise BpRefused("走这一步的条件只能写成「字段 比较 常量」,例如金额大于 5000") + field, op, const = value["field"], value["op"], value["value"] + if not _identifier(field): + raise BpRefused(f"条件里的字段要写字段名(不能写算式),当前为「{field}」") + if op not in THRESHOLD_OPS: + raise BpRefused(f"条件只能用这几种比较:{'、'.join(THRESHOLD_OPS)}") + if isinstance(const, bool) or not isinstance(const, (int, float, str)) or (isinstance(const, str) and len(const) > 100): + raise BpRefused("条件里比较的只能是一个数或一段文字,不能写算式") + if isinstance(const, str) and op not in ("==", "!="): + raise BpRefused("和文字只能比较相等或不相等") + names = [f.get("name") for f in spec.get("fields") or [] if isinstance(f, dict)] + if names and field not in names: + raise BpRefused(f"条件用到的字段「{field}」不在「填什么」里") + return {"field": field, "op": op, "value": const} + + +def _field_spec(value: Any, spec: dict[str, Any], name: str = "x") -> Any: + """「填什么」的一个字段:agentlab.form/1 的一个属性,另可写 required(是否必填)。按表单同一份规则核(P5)。""" + from app.apps.forms import validate_form_schema + + if not isinstance(value, dict): + raise BpRefused("字段要写明类型、名称这些表单属性") + prop = {k: v for k, v in value.items() if k != "required"} + if "required" in value and not isinstance(value["required"], bool): + raise BpRefused("「必填」只能是是或否") + problems = validate_form_schema({"type": "object", "properties": {name: prop}}) + if problems: + raise BpRefused(f"字段不符合表单的写法:{problems[0]}") + return copy.deepcopy(value) + + +def _capability(value: Any, _spec: dict[str, Any]) -> Any: + """写回的目标:能力登记里效果为写入的能力(写外部系统只经调用工具节点,总方案 A5)。读进程内快照,不查库。""" + from app.capabilities.registry import cached_view, writes_externally + + name = str(value or "").strip() + if not name: + raise BpRefused("写回要选一项能力") + view = cached_view(name) + if view is None or view.get("missing"): + raise BpRefused(f"能力登记里没有「{name}」,请从能力登记里选一项写入能力") + if not writes_externally(name, view.get("effect"), view.get("endpoint_id")) and view.get("effect") != "write": + raise BpRefused(f"「{name}」不是写入能力(它是只读的或在登记里没有定为写入),不能用来写回") + return name + + +def _mapping(value: Any, _spec: dict[str, Any]) -> Any: + if not isinstance(value, dict) or not value or len(value) > 40: + raise BpRefused("字段对应要写成「参数:取值」的一组") + out: dict[str, Any] = {} + for param, source in value.items(): + if not isinstance(param, str) or not param.strip() or len(param) > 64: + raise BpRefused("字段对应里的参数名要写清楚") + if isinstance(source, bool) or isinstance(source, (int, float)): + out[param] = source + elif isinstance(source, str) and (_MAP_SOURCE.match(source) or source == _MAP_ROWS): + out[param] = source + elif isinstance(source, str) and len(source) >= 2 and source[0] == source[-1] == "'": + out[param] = source + else: + raise BpRefused(f"参数「{param}」的取值只能是表单字段、指标、核对出来的行或一个常量(文字要加单引号)," + f"当前为「{source}」") + return out + + +def _confirm(value: Any, _spec: dict[str, Any]) -> Any: + if not isinstance(value, bool): + raise BpRefused("要不要人确认只能是是或否") + return value + + +def _reuse(value: Any, _spec: dict[str, Any]) -> Any: + """复用已发布的口径卡:{workflow_id, version, node_id, metric_id},另可带 inputs(那张卡读哪几个取数节点的哪几列, + look/calibers 认出来写上,蓝图存的时候按库里那一版再核一遍)。""" + if value is None: + return None + keys = {"workflow_id", "version", "node_id", "metric_id"} + if not isinstance(value, dict) or not keys <= set(value) or set(value) - keys - {"inputs"}: + raise BpRefused("复用口径卡要写明工作流、版本、口径卡节点和指标") + version = value["version"] + if isinstance(version, bool) or not isinstance(version, int) or version < 1: + raise BpRefused("复用口径卡要写明具体的版本号(1、2…)") + out = {k: str(value[k]).strip() for k in ("workflow_id", "node_id", "metric_id")} + if not all(out.values()): + raise BpRefused("复用口径卡要写明工作流、版本、口径卡节点和指标") + out["version"] = version + inputs = value.get("inputs") + if inputs is not None: + if not isinstance(inputs, list) or not all( + isinstance(i, dict) and isinstance(i.get("node"), str) and isinstance(i.get("tool"), str) + and isinstance(i.get("columns"), list) for i in inputs): + raise BpRefused("复用口径卡的输入要逐项写明节点、工具和列") + out["inputs"] = copy.deepcopy(inputs) + return out + + +def _grantees(value: Any, _spec: dict[str, Any]) -> Any: + if not isinstance(value, list): + raise BpRefused("「谁能看」要写成一组人或组") + return [_principal(v, GRANTEE_KINDS, "授权的对象") for v in value] + + +#: 各项的检查。键是 (卡片, 项);卡片本身就是一项的写 (卡片, None) +_CHECKS: dict[tuple[str, str | None], Callable[[Any, dict[str, Any]], Any]] = { + ("purpose", None): _text(500, "目的"), + ("cadence", None): _cadence, + ("data", "label"): _text(60, "名称"), + ("data", "unit"): _text(20, "单位"), + ("data", "table"): _table, + ("data", "measure"): _text(300, "怎么算"), + ("data", "date"): _date, + ("data", "filter"): _text(300, "筛选条件"), + ("data", "grain"): _text(60, "粒度"), + ("people", "label"): _text(60, "这一步叫什么"), + ("people", "who"): _who, + ("people", "policy"): _policy, + ("people", "due"): _due, + ("people", "on_timeout"): _on_timeout, + ("people", "threshold"): _threshold, + ("writeback", "capability"): _capability, + ("writeback", "mapping"): _mapping, + ("writeback", "confirm"): _confirm, +} + + +# ========================================================================== +# 落地 +# ========================================================================== + + +def _item(value: Any, source: str, *, why: Any = None) -> dict[str, Any]: + """卡片上的一项:写空的记「缺」,用户写的记「已确认」,助手写的记「待确认」。""" + if value is None: + return {"value": None, "source": source, "status": "missing", "why": why} + return {"value": value, "source": source, "status": "confirmed" if source == "user" else "proposed", "why": why} + + +def _checked(card: str, key: str | None, value: Any, spec: dict[str, Any]) -> Any: + if value is None or value == "" or value == []: + return None + return _CHECKS[(card, key)](value, spec) + + +def _new_entry(card: str, raw: Any, source: str, spec: dict[str, Any]) -> dict[str, Any]: + """bp_add 加的一项:数据项、步骤、字段。卡片字段写纯值,来源和状态按这次操作记。""" + if not isinstance(raw, dict): + raise BpRefused(f"「{_LABEL[card]}」加的一项要写成一个对象") + existing = spec.get(card) or [] + if card == "fields": + name = raw.get("name") + if not _identifier(name): + raise BpRefused(f"字段名要写成字母、汉字、数字和下划线(不以数字开头),当前为「{name}」") + if name in RESERVED_FIELDS: + raise BpRefused(f"字段名「{name}」留给统计期用了,请换一个") + if any(f.get("name") == name for f in existing): + raise BpRefused(f"已经有一个叫「{name}」的字段了") + if set(raw) - {"name", "spec", "sensitive"}: + raise BpRefused("字段只能写名字、表单属性和是否敏感") + sensitive = raw.get("sensitive", False) + if not isinstance(sensitive, bool): + raise BpRefused("「敏感」只能是是或否") + prop = None if raw.get("spec") is None else _field_spec(raw["spec"], spec, name) + return {"name": name, "spec": _item(prop, source), "sensitive": sensitive} + entry_id = raw.get("id") + if not isinstance(entry_id, str) or not _ID.match(entry_id): + raise BpRefused(f"每一项要有一个 id(小写字母开头,只用小写字母、数字、下划线),当前为「{entry_id}」") + if any(e.get("id") == entry_id for e in existing): + raise BpRefused(f"「{_LABEL[card]}」里已经有 id 为「{entry_id}」的一项了") + allowed = {"id", *(_ITEM_FIELDS[card]), *(("reuse",) if card == "data" else ())} + if extra := sorted(set(raw) - allowed): + raise BpRefused(f"「{_LABEL[card]}」的一项不能写这些:{'、'.join(extra)}") + out: dict[str, Any] = {"id": entry_id} + for key in _ITEM_FIELDS[card]: + out[key] = _item(_checked(card, key, raw.get(key), spec), source) + if card == "data": + out["reuse"] = _reuse(raw.get("reuse"), spec) + return out + + +def _writeback(raw: Any, source: str, spec: dict[str, Any]) -> dict[str, Any] | None: + if raw is None: + return None + if not isinstance(raw, dict) or set(raw) - {"capability", "mapping", "confirm"}: + raise BpRefused("「写回哪里」只能写目标能力、字段对应和要不要人确认") + return {key: _item(_checked("writeback", key, raw.get(key), spec), source) + for key in ("capability", "mapping", "confirm")} + + +def _set_item_part(item: dict[str, Any], part: str, value: Any, source: str) -> None: + """一项里的 status(只收用户的确认)、why(一句为什么)。""" + if part == "why": + if value is not None and (not isinstance(value, str) or len(value) > 300): + raise BpRefused("「为什么」要写一句话(最多 300 字)") + item["why"] = value.strip() if isinstance(value, str) and value.strip() else None + return + if part != "status": + raise BpRefused(f"卡片上的一项只能改值、确认或写一句为什么,不能改「{part}」") + if source != "user": + raise BpRefused("确认只能由你来做:助手提的项要你看过才算数") + if value != "confirmed": + raise BpRefused("只能把一项标成已确认;要改就直接改它的值") + if item.get("value") is None: + raise BpRefused("这一项还没有值,没法确认") + item["status"] = "confirmed" + + +def _container(spec: dict[str, Any], tokens: list[str]) -> tuple[dict[str, Any], str]: + """卡片上的一项所在的对象和键:/purpose → (spec, "purpose"),/data/0/table → (spec.data[0], "table")。""" + card = tokens[0] + if card in ("purpose", "cadence") and len(tokens) == 1: + return spec, card + if card in ("data", "people") and len(tokens) == 3: + entries = spec.get(card) or [] + at = _index(tokens[1], len(entries)) + if tokens[2] not in _ITEM_FIELDS[card]: + raise BpRefused(f"「{_LABEL[card]}」的一项没有「{tokens[2]}」") + return entries[at], tokens[2] + if card == "fields" and len(tokens) == 3 and tokens[2] == "spec": + entries = spec.get("fields") or [] + return entries[_index(tokens[1], len(entries))], "spec" + if card == "writeback" and len(tokens) == 2 and tokens[1] in ("capability", "mapping", "confirm"): + if spec.get("writeback") is None: + spec["writeback"] = {k: _item(None, "template") for k in ("capability", "mapping", "confirm")} + return spec["writeback"], tokens[1] + raise BpRefused(f"不能改这个位置:/{'/'.join(tokens)}") + + +def _set(spec: dict[str, Any], tokens: list[str], value: Any, source: str) -> None: + card = tokens[0] + if card == "access": + if len(tokens) != 2 or tokens[1] not in ACCESS_KINDS: + raise BpRefused("「谁能看」只有使用、查看全部、管理三档") + grantees = _grantees(value if value is not None else [], spec) + if len(grantees) > LIST_LIMITS[tokens[1]]: + raise BpRefused(f"每一档最多授权 {LIST_LIMITS[tokens[1]]} 个人或组") + spec["access"][tokens[1]] = grantees + return + if card == "asks": + if len(tokens) != 3 or tokens[2] != "answer": + raise BpRefused("反问只能记下回答") + asks = spec.get("asks") or [] + ask = asks[_index(tokens[1], len(asks))] + if source != "user": + raise BpRefused("反问要由你来回答") + if not isinstance(value, str) or not value.strip() or len(value) > 500: + raise BpRefused("回答要写一句话(最多 500 字)") + ask["answer"] = value.strip() + return + if card == "writeback" and len(tokens) == 1: + spec["writeback"] = _writeback(value, source, spec) + return + if card == "data" and len(tokens) == 3 and tokens[2] == "reuse": + entries = spec.get("data") or [] + entries[_index(tokens[1], len(entries))]["reuse"] = _reuse(value, spec) + return + if card == "fields" and len(tokens) == 3 and tokens[2] in ("name", "sensitive"): + entries = spec.get("fields") or [] + entry = entries[_index(tokens[1], len(entries))] + if tokens[2] == "sensitive": + if not isinstance(value, bool): + raise BpRefused("「敏感」只能是是或否") + entry["sensitive"] = value + return + if not _identifier(value) or value in RESERVED_FIELDS: + raise BpRefused(f"字段名「{value}」不能用:要写成字母、汉字、数字和下划线,也不能和统计期重名") + if any(f is not entry and f.get("name") == value for f in entries): + raise BpRefused(f"已经有一个叫「{value}」的字段了") + entry["name"] = value + return + if tokens[-1] in ("status", "why") and len(tokens) >= 2: + holder, key = _container(spec, tokens[:-1]) + _set_item_part(holder[key], tokens[-1], value, source) + return + holder, key = _container(spec, tokens) + if card == "fields": + checked = None if value is None else _field_spec(value, spec, holder.get("name") or "x") + else: + checked = _checked(card, None if card in ("purpose", "cadence") else key, value, spec) + why = (holder.get(key) or {}).get("why") if checked is not None else None + holder[key] = _item(checked, source, why=why) + + +def _add(spec: dict[str, Any], tokens: list[str], value: Any, source: str) -> None: + card = tokens[0] + if card == "access": + if len(tokens) not in (2, 3) or tokens[1] not in ACCESS_KINDS: + raise BpRefused("「谁能看」只有使用、查看全部、管理三档") + grantees = spec["access"][tokens[1]] + at = _index(tokens[2], len(grantees), allow_end=True) if len(tokens) == 3 else len(grantees) + grantee = _principal(value, GRANTEE_KINDS, "授权的对象") + if grantee in grantees: + raise BpRefused(f"「{grantee['name']}」已经在这一档里了") + if len(grantees) >= LIST_LIMITS[tokens[1]]: + raise BpRefused(f"每一档最多授权 {LIST_LIMITS[tokens[1]]} 个人或组") + grantees.insert(at, grantee) + return + if card not in ("data", "people", "fields") or len(tokens) > 2: + raise BpRefused(f"只能往「看哪些数」「谁来做」「填什么」「谁能看」里加,不能加到 /{'/'.join(tokens)}") + entries = spec.setdefault(card, []) + at = _index(tokens[1], len(entries), allow_end=True) if len(tokens) == 2 else len(entries) + if len(entries) >= LIST_LIMITS[card]: + raise BpRefused(f"「{_LABEL[card]}」最多 {LIST_LIMITS[card]} 项") + entries.insert(at, _new_entry(card, value, source, spec)) + + +def _remove(spec: dict[str, Any], tokens: list[str], source: str) -> None: + card = tokens[0] + if card == "access": + if len(tokens) != 3 or tokens[1] not in ACCESS_KINDS: + raise BpRefused("「谁能看」要写明删哪一档的第几个") + grantees = spec["access"][tokens[1]] + del grantees[_index(tokens[2], len(grantees))] + return + if card in ("data", "people", "fields") and len(tokens) == 2: + entries = spec.get(card) or [] + del entries[_index(tokens[1], len(entries))] + return + if card == "writeback" and len(tokens) == 1: + spec["writeback"] = None + return + if card == "data" and len(tokens) == 3 and tokens[2] == "reuse": + entries = spec.get("data") or [] + entries[_index(tokens[1], len(entries))]["reuse"] = None + return + # 卡片上的一项:清空等于记成「缺」 + _set(spec, tokens, None, source) + + +def _ask(spec: dict[str, Any], op: BpOp, source: str) -> None: + if source != "assistant": + raise BpRefused("反问是助手问你的,你直接回答就好") + question = (op.question or "").strip() + if not question or len(question) > 300: + raise BpRefused("反问要写一个问题(最多 300 字)") + options = [o.strip() for o in op.options if isinstance(o, str) and o.strip()] + if len(options) > 6 or any(len(o) > 100 for o in options): + raise BpRefused("反问最多给 6 个候选,每个最多 100 字") + if op.path is not None: + parse_pointer(op.path) + asks = spec.setdefault("asks", []) + asks.append({"id": f"q{len(asks) + 1}", "question": question, "options": options, "path": op.path, + "answer": None}) + + +def _template(spec: dict[str, Any], op: BpOp, source: str) -> None: + from app.blueprints.templates import get_template + + ref = op.template + if ref is None: + raise BpRefused("选模板要写明是哪一个") + template = get_template(ref.id) + if template is None: + raise BpRefused(f"没有叫「{ref.id}」的场景模板", code="bp.template_mismatch") + if ref.version != template.version: + raise BpRefused(f"场景模板「{template.label}」现在是第 {template.version} 版,请按这一版选", + code="bp.template_mismatch") + spec["template"] = {"id": template.id, "version": template.version} + from app.blueprints.templates._common import prefill + + prefill(template.id, spec) + + def apply_bp_op(spec: dict[str, Any], op: dict[str, Any], *, source: str) -> dict[str, Any]: """把一个 bp_* 操作落到蓝图上,交回新的蓝图(不改入参)。source 是 user / assistant。不合规时抛 BpRefused。""" - raise NotImplementedError + if source not in BP_SOURCES: + raise BpRefused(f"操作的来源只能是用户或助手,当前为「{source}」") + if not isinstance(op, dict) or op.get("op") not in BP_OPS: + raise BpRefused(f"只能用这几种操作:{'、'.join(BP_OPS)}") + try: + parsed = BpOp.model_validate(op) + out = parse_blueprint(copy.deepcopy(spec)).model_dump(mode="json", by_alias=True) + except ValidationError as e: + raise BpRefused(f"操作的写法不对:{_first(e)}") from e + if parsed.op == "bp_ask": + _ask(out, parsed, source) + elif parsed.op == "bp_template": + _template(out, parsed, source) + else: + tokens = parse_pointer(parsed.path) + if tokens[0] not in _LABEL or tokens[0] == "template": + raise BpRefused(f"没有这张卡片:/{tokens[0]}(选模板用 bp_template)") + if tokens[0] == "access" and source != "user": + raise BpRefused("「谁能看」要由你来定:授权是人的决定,助手不替你填") + if parsed.op == "bp_set": + _set(out, tokens, parsed.value, source) + elif parsed.op == "bp_add": + _add(out, tokens, parsed.value, source) + else: + _remove(out, tokens, source) + try: + return parse_blueprint(out).model_dump(mode="json", by_alias=True) + except ValidationError as e: + raise BpRefused(f"改完的蓝图不合格式:{_first(e)}") from e + + +def _first(e: ValidationError) -> str: + err = e.errors()[0] if e.errors() else {} + where = ".".join(str(x) for x in err.get("loc") or ()) + return f"{where} {err.get('msg', '')}".strip() + + +# ========================================================================== +# 蓝图检查(§3.13 bp.*) +# ========================================================================== + +#: 检查的用途:试运行(缺项挡)、发布(再加待确认项挡)、个人应用(缺项挡,另查模板的个人应用部分) +ISSUE_PURPOSES = ("trial", "publish", "personal") +#: 卡片约束说明以这两个词开头:模板登记里 cards 的写法(blueprints/templates) +REQUIRED_MARK = "必填" + + +def _value(item: Any) -> Any: + return item.get("value") if isinstance(item, dict) else None def blueprint_issues(spec: dict[str, Any], *, for_: str) -> list[dict[str, Any]]: """蓝图检查(§3.13 bp.*):for_ = trial(缺项挡试运行)/ publish(待确认项挡发布)/ personal。 每条 {code, level, path, message}。""" - raise NotImplementedError + from app.blueprints.templates import get_template + + if for_ not in ISSUE_PURPOSES: + raise ValueError(for_) + out: list[dict[str, Any]] = [] + + def add(code: str, path: str, message: str, level: str = "error") -> None: + out.append({"code": code, "level": level, "path": path, "message": message}) + + ref = spec.get("template") or None + template = get_template(ref["id"]) if isinstance(ref, dict) else None + if not isinstance(ref, dict): + add("bp.missing", "/template", "还没有选场景:先说说要做什么,或者从场景模板开始") + return out + if template is None: + add("bp.template_mismatch", "/template", f"场景模板「{ref.get('id')}」已经不在了,请换一个场景") + return out + if ref.get("version") != template.version: + add("bp.template_mismatch", "/template", + f"这张蓝图按场景模板「{template.label}」第 {ref.get('version')} 版做的,模板现在是第 {template.version} 版:" + "请重新选一次模板,卡片会按新版本核一遍", level="warning") + used = set(template.cards) + required = {c for c, note in template.cards.items() if note.startswith(REQUIRED_MARK)} + publish = for_ == "publish" + + if "purpose" in required and _value(spec.get("purpose")) is None: + add("bp.missing", "/purpose", "「目的」还没写:一句话说清这个应用解决什么问题、给谁用") + # 模板用不到的卡片只报一条 bp.template_mismatch(见下),里面的项不再逐条查 + if "data" in used: + _data_issues(spec, "data" in required, add) + if "cadence" in required and _value(spec.get("cadence")) is None: + add("bp.missing", "/cadence", "「多久更新」还没定:每天、每周还是每月,几点,统计哪一期") + if "people" in used: + _people_issues(spec, "people" in required, publish, add) + if "fields" in used: + _field_issues(spec, "fields" in required, add) + wb = spec.get("writeback") + if "writeback" in required and (not isinstance(wb, dict) or _value(wb.get("capability")) is None): + add("bp.missing", "/writeback", "「写回哪里」还没定:要写回哪个系统、哪些字段") + elif isinstance(wb, dict) and _value(wb.get("capability")) is not None and _value(wb.get("mapping")) is None: + add("bp.missing", "/writeback/mapping", "写回的字段对应还没写:目标系统的每个参数取哪个字段或指标") + + for card in ("data", "people", "fields"): + if spec.get(card) and card not in used: + add("bp.template_mismatch", f"/{card}", + f"场景「{template.label}」用不到「{_LABEL[card]}」:这张卡片上写的不会生效。请删掉,或者换一个场景") + if isinstance(wb, dict) and _value(wb.get("capability")) is not None and "writeback" not in used: + add("bp.template_mismatch", "/writeback", + f"场景「{template.label}」不写回别的系统:「写回哪里」不会生效。请删掉,或者换成核对写回、审批流程") + # 模板自己认的:卡片内容超出模板能力(只能从一个库查、复用的口径卡接不上、写回取不到的字段……) + from app.blueprints.templates._common import template_problems + + out += template_problems(template.id, spec) + if for_ == "personal": + if template.personal is None: + add("bp.template_mismatch", "/template", f"场景「{template.label}」不能做成个人应用:它要有人审批或写回别的系统") + if spec.get("people"): + add("bp.template_mismatch", "/people", "个人应用不能有审批步骤:想给别人用,请提交给搭建者审核发布") + if isinstance(wb, dict) and _value(wb.get("capability")) is not None: + add("bp.template_mismatch", "/writeback", "个人应用只读,不能写回别的系统") + if publish: + for path, item in _items(spec): + if item.get("status") == "proposed" and item.get("value") is not None: + add("bp.unconfirmed", path, f"「{_where(path)}」是{_SOURCE_WORD.get(item.get('source'), '')}提的," + "还没确认:发布前要你看过") + return out + + +_SOURCE_WORD = {"assistant": "助手", "template": "模板默认", "catalog": "按数据目录对到", "caliber": "按口径卡对到"} + + +def _data_issues(spec: dict[str, Any], required: bool, add: Callable[..., None]) -> None: + data = spec.get("data") or [] + if required and not data: + add("bp.missing", "/data", "「看哪些数」还没写:至少要有一项,比如销售额、订单数") + seen: set[str] = set() + for i, item in enumerate(data): + if _value(item.get("label")) is None: + add("bp.missing", f"/data/{i}/label", f"第 {i + 1} 项数还没有名字") + reuse = item.get("reuse") + if _value(item.get("table")) is None and not reuse: + add("bp.data_unmapped", f"/data/{i}/table", + f"「{_value(item.get('label')) or item.get('id')}」还没对到表或已发布的口径卡") + if reuse and reuse.get("metric_id") in seen: + add("bp.template_mismatch", f"/data/{i}/reuse", f"复用的指标「{reuse['metric_id']}」和别的项重名,请只留一项") + seen.add(str(reuse.get("metric_id") if reuse else item.get("id"))) + + +def _people_issues(spec: dict[str, Any], required: bool, publish: bool, add: Callable[..., None]) -> None: + people = spec.get("people") or [] + if required and not people: + add("bp.missing", "/people", "「谁来做」还没写:至少要有一步,写明谁处理") + numeric = {f.get("name") for f in spec.get("fields") or [] + if (_value(f.get("spec")) or {}).get("type") in ("number", "integer")} + names = {f.get("name") for f in spec.get("fields") or []} + for i, step in enumerate(people): + label = _value(step.get("label")) or step.get("id") + if _value(step.get("who")) is None: + # 试运行时人工步骤派给试运行的人自己,岗位没人不挡试运行,只挡发布 + add("bp.people_unbound", f"/people/{i}/who", f"「{label}」还没定谁来处理", + level="error" if publish else "warning") + if _value(step.get("policy")) is None: + add("bp.missing", f"/people/{i}/policy", f"「{label}」还没定几个人同意算通过") + timeout = _value(step.get("on_timeout")) + if timeout and _value(step.get("due")) is None: + add("bp.missing", f"/people/{i}/due", f"「{label}」写了超时怎么办,还要写时限") + threshold = _value(step.get("threshold")) + if threshold: + if threshold["field"] not in names: + add("bp.template_mismatch", f"/people/{i}/threshold", + f"「{label}」的条件用到的字段「{threshold['field']}」不在「填什么」里") + elif threshold["op"] not in ("==", "!=") and threshold["field"] not in numeric: + add("bp.template_mismatch", f"/people/{i}/threshold", + f"「{label}」的条件拿「{threshold['field']}」比大小,它要是数字字段") + + +def _field_issues(spec: dict[str, Any], required: bool, add: Callable[..., None]) -> None: + fields = spec.get("fields") or [] + if required and not fields: + add("bp.missing", "/fields", "「填什么」还没写:至少要有一个字段") + for i, f in enumerate(fields): + if _value(f.get("spec")) is None: + add("bp.missing", f"/fields/{i}/spec", f"字段「{f.get('name')}」还没定类型") + + +def _items(spec: dict[str, Any]) -> list[tuple[str, dict[str, Any]]]: + """蓝图里所有带状态的项:(路径, 项)。""" + out: list[tuple[str, dict[str, Any]]] = [] + for card in ("purpose", "cadence"): + if isinstance(spec.get(card), dict): + out.append((f"/{card}", spec[card])) + for card in ("data", "people"): + for i, entry in enumerate(spec.get(card) or []): + out += [(f"/{card}/{i}/{k}", entry[k]) for k in _ITEM_FIELDS[card] if isinstance(entry.get(k), dict)] + for i, f in enumerate(spec.get("fields") or []): + if isinstance(f.get("spec"), dict): + out.append((f"/fields/{i}/spec", f["spec"])) + wb = spec.get("writeback") + if isinstance(wb, dict): + out += [(f"/writeback/{k}", wb[k]) for k in ("capability", "mapping", "confirm") if isinstance(wb.get(k), dict)] + return out + + +_PART_LABEL = {"label": "名称", "unit": "单位", "table": "对到的表", "measure": "怎么算", "date": "业务日期", + "filter": "筛选条件", "grain": "粒度", "who": "处理人", "policy": "几个人同意", "due": "时限", + "on_timeout": "超时怎么办", "threshold": "条件", "spec": "字段", "capability": "目标能力", + "mapping": "字段对应", "confirm": "要不要人确认"} + + +def _where(path: str) -> str: + tokens = parse_pointer(path) + card = _LABEL.get(tokens[0], tokens[0]) + if len(tokens) == 1: + return card + if len(tokens) == 3: + return f"{card}·第 {int(tokens[1]) + 1} 项·{_PART_LABEL.get(tokens[2], tokens[2])}" + return f"{card}·{_PART_LABEL.get(tokens[-1], tokens[-1])}" diff --git a/backend/app/blueprints/personal.py b/backend/app/blueprints/personal.py index f5e2f8c2..d1bb7dad 100644 --- a/backend/app/blueprints/personal.py +++ b/backend/app/blueprints/personal.py @@ -1,31 +1,707 @@ """个人应用(N7、§3.9):使用者自己的应用。图存在蓝图上(不进工作流表)、只有拥有者看得见、永远跑探索运行 (origin_kind=personal_app,强加 MASK_RESULTS / READ_ONLY)、受每日上限约束;想给别人用就提交审核,搭建者在共享副本上发布。 -包 B4 实现。 +- 开关:设置里 apps 这一组的「使用者可以建个人应用」(默认关,只有管理员能改,api/settings.py)。开了登录时搭建者及以上 + 随时能用(§3.12);使用者要开关开着;关登录时全部放行,开关照样生效(关着就没有入口)。 +- 约束:和使用者问数据同一份白名单(auth/chat_policy.py)——节点只许读数据、整理、撰写这一类,工具只许数据源查询和只读的 + 内置工具;没有人工节点、不写任何东西。存的时候查(save_personal),刷新时再查一次(白名单以后可能收紧),应用检查也按它 + 报(personal.policy)。 +- 应用:scope=personal、owner=蓝图的拥有者、blueprint_id=蓝图;没有应用版本,草稿就是在用的那一份(改了就生效)。固定版本 + 写 blueprint(apps/spec.Pin),视图来源一律 exploratory:取这个应用、这个拥有者、这张图下最近一次成功封存的 personal_app + 运行(exploratory_runs,apps/resolve.py 解析时调)。 +- 刷新:以拥有者的身份发起探索运行,和按需视图共用每日上限(apps.on_demand_daily_limit),按人计。同一个应用正在刷新时 + 再点,接上那一次,不另花一次。 +- 提交审核:开一条 review 待办(process/tasks.open_review),派给选定的搭建者或组。待办的 run_id 不能为空(带外键,开待办、 + 记事件、通知都按运行走),挂在最近一次成功的刷新上——审核的人要看的也正是这次用真数出的结果;所以提交前要至少成功刷新 + 一次。搭建者取共享副本(copy_for_review,原个人应用不动),在副本上试运行、走发布单;发布单做完调 review_published, + 待办记为已发布、通知提交人;不发布就在待办里退回(reject_review)。 """ from __future__ import annotations +import asyncio +import copy as copy_module +from datetime import datetime, timezone from typing import Any +from sqlalchemy import func, select +from sqlalchemy.ext.asyncio import AsyncSession + #: 管理员开关:使用者能不能建个人应用(apps 设置组里,默认关) SETTING_KEY = "user_personal_apps" +#: 个人应用刷新的运行来源(engine/origin.py) +ORIGIN = "personal_app" +#: 提交审核开的待办种类(§3.1 tasks.kind 新增 review) +REVIEW = "review" +#: 审核待办按它找回蓝图(Task.correlation_key) +REVIEW_KEY = "blueprint:" +#: 个人应用的那一个固定版本的别名(as_personal 把固定版本换成它) +PIN = "main" + +# 机器码(接口回 {detail, code};白话在 app/plain.py) +PERSONAL_OFF = "personal.off" +POLICY = "personal.policy" +DAILY_LIMIT = "personal.daily_limit" +GRAPH_CHANGED = "personal.graph_changed" +NOT_TRIALED = "personal.not_trialed" +NO_RUN = "personal.no_run" +IN_REVIEW = "personal.in_review" +NOT_PERSONAL = "personal.not_personal" +REVIEW_TARGET = "personal.review_target" + +BLUEPRINT_GONE = "蓝图不存在,可能已被删除" +APP_GONE = "应用不存在,可能已被删除" -async def save_personal(session: Any, blueprint: Any, *, principal: Any) -> Any: - """校验图满足 chat_policy(节点、工具、无人工、无写入),建或更新 scope=personal 的 App。""" - raise NotImplementedError +class PersonalRefused(Exception): + """不做这件事:status_code 照 HTTP 语义,message 是给人看的一句话,code 是 personal.* 机器码。issues 是蓝图检查交回的 + 问题(存个人应用时缺项、待填),接口原样带给前端。""" + + def __init__(self, status_code: int, message: str, code: str | None = None, + issues: list[dict[str, Any]] | None = None) -> None: + super().__init__(message) + self.status_code = status_code + self.message = message + self.code = code + self.issues = issues or [] -async def refresh(session: Any, app: Any, *, principal: Any) -> str: - """发起一次个人应用的刷新(探索运行),交回 run_id;受每日上限约束。""" - raise NotImplementedError +# -------------------------------------------------------------------------- +# 开关、拥有者、约束 +# -------------------------------------------------------------------------- -async def submit_review(session: Any, app: Any, *, to: list[dict[str, str]], principal: Any) -> Any: - """开一条 review 待办派给搭建者。""" - raise NotImplementedError +async def enabled(session: AsyncSession) -> bool: + from app.api.settings import apps_settings + + return bool((await apps_settings(session))[SETTING_KEY]) -async def copy_for_review(session: Any, blueprint: Any, *, principal: Any) -> Any: - """搭建者处理审核时得到这个蓝图的共享副本(copied_from 指向原蓝图),原个人应用不动。""" - raise NotImplementedError +async def allowed(session: AsyncSession, principal: Any) -> bool: + """这个人能不能建个人应用、刷新、提交审核:开了登录的搭建者及以上随时能;使用者和关登录时看开关。""" + if principal.mode != "off" and principal.at_least("builder"): + return True + return await enabled(session) + + +async def ensure_allowed(session: AsyncSession, principal: Any) -> None: + from app.api.settings import APPS_SETTING_LABEL + + if not await allowed(session, principal): + label = APPS_SETTING_LABEL[SETTING_KEY] + raise PersonalRefused(403, f"没有权限:管理员还没有开放个人应用(「设置 → 应用」里的「{label}」)。" + "想要一个给自己看的看板,可以请管理员打开,或请搭建者做成应用", PERSONAL_OFF) + + +def owns(principal: Any, owner: str | None) -> bool: + """是不是拥有者。关登录时全部放行(没有可信的身份,同应用级权限)。""" + return principal.mode == "off" or (bool(principal.username) and principal.username == owner) + + +def policy_problem(graph: Any) -> str | None: + """个人应用的图能不能用:和使用者问数据同一份白名单(auth/chat_policy.chat_graph_problem),说法只换「在哪」。 + 能用返回 None。没有人工节点、不写入都在白名单里:人工、调用工具、代码、记忆写入这几类节点不在名单上,写入能力和 + 自定义工具不是只读工具;数据源查询在运行时另按 READ_ONLY 只读。""" + from app.auth.chat_policy import chat_graph_problem + + return chat_graph_problem(graph, where="个人应用") + + +def _pin(spec: dict[str, Any] | None) -> dict[str, Any] | None: + """个人应用的那一个固定版本(写 blueprint 的那一项)。""" + return next((p for p in (spec or {}).get("pins") or [] if isinstance(p, dict) and p.get("blueprint")), None) + + +def graph_hash_of(blueprint: Any) -> str: + """蓝图现在这张图的指纹:按图算,不信库里记的(实例化之后记没记上由别处保证,这里不赌)。""" + from app.core.artifact_store import graph_hash + + return graph_hash(blueprint.graph or {}) + + +async def _blueprint_of(session: AsyncSession, app: Any) -> Any: + from app.db.models_blueprints import Blueprint + + blueprint = await session.get(Blueprint, app.blueprint_id) if app.blueprint_id else None + if blueprint is None: + raise PersonalRefused(409, "这个个人应用出自的蓝图已经不在了,没法再刷新;可以归档它,再从新的蓝图存一个", NOT_PERSONAL) + return blueprint + + +def _personal_app(app: Any, principal: Any) -> None: + """个人应用的接口只认个人应用、只给拥有者。别人一律当没有这个应用(不说它在不在,同应用级权限)。共享应用能不能看 + 由接口先按应用级权限判过,这里只说它不是个人应用。""" + if app is None: + raise PersonalRefused(404, APP_GONE) + if getattr(app, "scope", "shared") != "personal": + raise PersonalRefused(409, "这是共享应用,不是个人应用:刷新、提交审核只对个人应用", NOT_PERSONAL) + if not owns(principal, app.owner): + raise PersonalRefused(404, APP_GONE) + if app.status == "archived": + raise PersonalRefused(409, f"「{app.name}」已归档,不能再刷新或提交审核", "app_archived") + + +# -------------------------------------------------------------------------- +# 个人应用的描述 +# -------------------------------------------------------------------------- + + +def as_personal(spec: dict[str, Any], *, blueprint_id: str, graph_hash: str) -> dict[str, Any]: + """任一份应用描述(模板的应用骨架、派生出来的草稿)改成个人应用的样子:固定版本换成这个蓝图;看结果的视图一律改取 + 探索运行(exploratory);入口、表单、岗位、待办外观、钩子、通知订阅都去掉(个人应用不发起实例、不派待办);实例视图、 + 流程组件、表单组件、绑定了去掉的视图或待办、动作的组件一并去掉,去空了的页面不留。""" + from app.apps.catalog import BY_NAME + from app.apps.spec import parse_spec + from app.apps.tree import bind_kind + + out = copy_module.deepcopy(spec) + out["pins"] = [{"alias": PIN, "blueprint": blueprint_id, "graph_hash": graph_hash, "use": "view"}] + views: dict[str, Any] = {} + for vid, view in (out.get("views") or {}).items(): + if ((view or {}).get("source") or {}).get("kind") != "instance": + views[vid] = {"source": {"kind": "exploratory", "pin": PIN}} + out["views"] = views + for key in ("entries", "hooks", "notify"): + out[key] = [] + for key in ("forms", "slots", "task_ui"): + out[key] = {} + + def keep(comp: Any) -> bool: + if not isinstance(comp, dict): + return False + entry = BY_NAME.get(str(comp.get("type"))) or {} + if entry.get("category") in ("process", "input"): + return False + bind = comp.get("bind") if isinstance(comp.get("bind"), dict) else None + if bind is not None and (bind_kind(bind) in ("task", "action") or bind.get("view") not in views): + return False + return comp.get("scope") is None or comp.get("scope") in views + + def prune(items: list[Any]) -> list[Any]: + kept = [] + for comp in items: + if keep(comp): + comp["children"] = prune(comp.get("children") or []) + kept.append(comp) + return kept + + pages = [] + for page in out.get("pages") or []: + if isinstance(page, dict) and (body := prune(page.get("body") or [])): + pages.append({**page, "body": body}) + out["pages"] = pages + return parse_spec(out).model_dump(mode="json", by_alias=True) + + +async def _base_spec(session: AsyncSession, blueprint: Any, graph: dict[str, Any], name: str, description: str, + graph_hash: str) -> dict[str, Any]: + """新存的个人应用用哪份描述:这张图实例化时模板排布的应用草稿(blueprints/trial.app_spec_for,P6);没有的(自由形) + 按派生规则从图出(trial.draft_app_spec,和共享应用同一份规则,P3);再改成个人应用的样子(as_personal)。""" + from app.blueprints.trial import app_spec_for, draft_app_spec + + base, _ = await app_spec_for(session, blueprint, graph_hash) + if base is None: + base = await draft_app_spec(session, blueprint, graph) + return as_personal({**base, "name": name, "description": description}, blueprint_id=blueprint.id, + graph_hash=graph_hash) + + +#: 个人应用不能有的几样:它不发起实例、不派待办(spec 里的键 → 说法;应用检查 apps/lint._lint_personal 用同一份) +NOT_IN_PERSONAL = (("entries", "入口"), ("hooks", "钩子"), ("notify", "通知订阅"), ("slots", "岗位")) + + +def draft_problem(current: dict[str, Any], draft: dict[str, Any]) -> str | None: + """个人应用的草稿就是在用的那一份,改了就生效(PATCH /api/apps/{id} 调):只许改呈现——页面、组件、文字、隐藏、名称。 + 固定的蓝图只由「存成我的应用」改(改取数要回到蓝图、重新试运行);视图只能取探索运行;入口、钩子、通知订阅、岗位 + 个人应用不能有。合规返回 None,不合规交回一句话(422)。绑定找不到数这类问题照旧在页面和检查里照实报,不挡保存。""" + def pins(spec: dict[str, Any]) -> list[tuple[Any, Any, Any]]: + return [(p.get("alias"), p.get("blueprint"), p.get("graph_hash")) for p in spec.get("pins") or [] + if isinstance(p, dict)] + + if not isinstance(draft, dict): + return "应用描述需要是一个对象" + if pins(draft) != pins(current): + return "个人应用固定的是它自己的蓝图,不能在这里改:要改取数,请回到蓝图修改、用真数试一次,再存成你的应用" + aliases = {alias for alias, _, _ in pins(current)} + for vid, view in (draft.get("views") or {}).items(): + source = (view or {}).get("source") if isinstance(view, dict) else None + if not isinstance(source, dict) or source.get("kind") != "exploratory" or source.get("pin") not in aliases: + return f"视图「{vid}」:个人应用的视图只能取它自己的探索运行(每次刷新的结果)" + if declared := [label for key, label in NOT_IN_PERSONAL if draft.get(key)]: + return f"个人应用不发起实例、不派待办,不能有{'、'.join(declared)}" + return None + + +def _purpose(blueprint: Any) -> str: + value = ((blueprint.spec or {}).get("purpose") or {}).get("value") + return value.strip()[:2000] if isinstance(value, str) else "" + + +# -------------------------------------------------------------------------- +# 存成个人应用 +# -------------------------------------------------------------------------- + + +async def save_personal(session: AsyncSession, blueprint: Any, *, principal: Any) -> Any: + """校验图满足使用者的约束,建或更新 scope=personal 的 App(提交),交回 App。 + + 要先用真数试过(蓝图上有试运行)——界面上也是试过之后才有「存成我的应用」,服务端一样拦。蓝图检查(bp.*,按个人应用 + 的要求)有错的不存,问题原样交回。新建时名字、说明取蓝图的;再存一次时应用上的名字、页面都是拥有者的,图没变的什么都 + 不动;图变了的,原来的页面绑定在新图上都还找得到的留着(改过的文字、隐藏、顺序不丢),有找不到的按新图重新派生—— + 页面上不会挂着找不到数的块。""" + from app.apps.audit import record + from app.db.models_apps import App + + await ensure_allowed(session, principal) + if blueprint is None or blueprint.scope != "personal" or not owns(principal, blueprint.owner): + raise PersonalRefused(404, BLUEPRINT_GONE) + graph = blueprint.graph or {} + if not graph.get("nodes"): + raise PersonalRefused(409, "蓝图还没有生成图:请先把卡片补齐、用真数试一次", NOT_TRIALED) + if not blueprint.last_trial_run_id: + raise PersonalRefused(409, "还没有用真数试过:先试一次、看过结果,再存成你的应用", NOT_TRIALED) + # 卡片上的问题先说(「个人应用不能有审批步骤」比「不能使用人工节点」好懂),图本身的约束再核一遍 + if issues := _blocking_issues(blueprint): + raise PersonalRefused(422, f"蓝图还有要改的地方:{issues[0]['message']}", issues[0]["code"], issues=issues) + if problem := policy_problem(graph): + raise PersonalRefused(403, problem, POLICY) + hash_ = graph_hash_of(blueprint) + name = (blueprint.name or "").strip()[:200] or _purpose(blueprint)[:200] or "我的应用" + description = _purpose(blueprint) + actor = principal.username + app = await session.get(App, blueprint.app_id) if blueprint.app_id else None + if app is not None and (app.scope != "personal" or app.status == "archived"): + # 原来的个人应用归档了(拥有者自己、或管理员归的):不复活它,另建一个 + app = None + created = app is None + if app is None: + app = App(name=name, description=description, icon="app", + draft=await _base_spec(session, blueprint, graph, name, description, hash_), + draft_bindings={"slots": {}}, + created_by=actor, updated_by=actor, scope="personal", owner=blueprint.owner, + blueprint_id=blueprint.id) + session.add(app) + await session.flush() + else: + app.draft = await _kept_or_fresh(session, app, blueprint, graph, app.name, app.description or "", hash_) + app.updated_by = actor + blueprint.app_id = app.id + blueprint.graph_hash = hash_ + if blueprint.status != "in_review": + blueprint.status = "personal" + await event(session, blueprint, "save_personal", principal, {"app_id": app.id, "graph_hash": hash_, + "created": created}) + await record(session, action="app.personal_save", subject_kind="app", subject_id=app.id, actor=actor, + data={"blueprint_id": blueprint.id, "graph_hash": hash_, "created": created}) + await session.commit() + await session.refresh(app) + return app + + +def _blocking_issues(blueprint: Any) -> list[dict[str, Any]]: + """蓝图检查(blueprints/ops.blueprint_issues,按个人应用的要求:缺项、模板不能做成个人应用、有审批步骤、要写回)里 + 挡住存的:error 一级,带白话。""" + from app.blueprints.ops import blueprint_issues + from app.blueprints.trial import FREEFORM, template_of + from app.plain import with_plain + + # 自由形(从运行、工作流版本导入的)卡片上可以没选模板,「还没有选场景」不算(同试运行、蓝图接口) + freeform = template_of(blueprint) == FREEFORM + return [with_plain(i) for i in blueprint_issues(blueprint.spec or {}, for_="personal") + if i.get("level") == "error" and not (freeform and i.get("path") == "/template")] + + +async def _kept_or_fresh(session: AsyncSession, app: Any, blueprint: Any, graph: dict[str, Any], name: str, + description: str, hash_: str) -> dict[str, Any]: + from app.apps.lint import lint_app + + current = copy_module.deepcopy(app.draft or {}) + pin = _pin(current) + if pin is not None and pin.get("graph_hash") == hash_: + return {**current, "name": name, "description": description} + kept = {**current, "name": name, "description": description, + "pins": [{"alias": PIN, "blueprint": blueprint.id, "graph_hash": hash_, "use": "view"}]} + issues = await lint_app(session, kept, {}, scope="personal") + if any(i["level"] == "error" for i in issues): + return await _base_spec(session, blueprint, graph, name, description, hash_) + return kept + + +async def event(session: AsyncSession, blueprint: Any, op: str, principal: Any, data: dict[str, Any]) -> None: + """记一条蓝图留痕(blueprint_events,blueprints/trial.record_event),和改动同一个事务,调用方提交。""" + from app.blueprints.trial import record_event + + await record_event(session, blueprint, op, data, principal=principal) + + +# -------------------------------------------------------------------------- +# 刷新 +# -------------------------------------------------------------------------- + +#: 每人一把锁:查上限和发起在同一把锁里,同一个人连点两下不会多跑一次 +_LOCKS: dict[str, asyncio.Lock] = {} + + +def _lock(who: str | None) -> asyncio.Lock: + return _LOCKS.setdefault(who or "", asyncio.Lock()) + + +def _today_start() -> datetime: + """「每天」按服务端所在时区的自然日算(同按需视图,apps/resolve.run_view)。""" + return datetime.now().astimezone().replace(hour=0, minute=0, second=0, microsecond=0).astimezone(timezone.utc) + + +async def used_today(session: AsyncSession, who: str | None) -> int: + from app.db.models import Run + + query = select(func.count(Run.id)).where(Run.origin_kind == ORIGIN, Run.created_at >= _today_start()) + query = query.where(Run.started_by == who) if who else query.where(Run.started_by.is_(None)) + return int(await session.scalar(query) or 0) + + +async def remaining_today(session: AsyncSession, who: str | None) -> tuple[int, int]: + """(今天还能刷新几次, 每天的上限)。上限和按需视图共用设置项 apps.on_demand_daily_limit,按人计。""" + from app.apps.resolve import daily_limit + + limit = await daily_limit(session) + return max(limit - await used_today(session, who), 0), limit + + +def refresh_inputs(blueprint: Any) -> dict[str, Any]: + """刷新时交给入口的输入:和试运行同一个规则(blueprints/trial.trial_inputs)——看板类按「多久更新」卡片、按现在这一刻 + 算出最近一期(和定时任务到点渲染的是同一份),统计期跟着日子走;算不出的(自由形、没有统计期的)交空的,入口节点按 + 字段的默认值补。""" + from app.blueprints.trial import trial_inputs + + return trial_inputs(blueprint, None) + + +async def refresh(session: AsyncSession, app: Any, *, principal: Any) -> tuple[Any, int]: + """发起一次个人应用的刷新(探索运行),交回 (运行, 今天还剩几次)。 + + 以拥有者的身份发起(记忆固定为他自己的范围,知识库取设置里的默认值,同问数据),强加 MASK_RESULTS、READ_ONLY:查询 + 结果在工具边界就遮,数据源只读。跑的是蓝图上的图,和应用记的指纹对不上(蓝图改过、还没重新存)就不跑——跑了页面也 + 取不到它。同一个应用这张图正在刷新的,接上那一次,不另花一次。""" + from app.auth.chat_policy import chat_memory_scope + from app.engine.launch import launch_run + from app.tools.datasource import MASK_RESULTS_OPTION, READ_ONLY_OPTION + + await ensure_allowed(session, principal) + _personal_app(app, principal) + blueprint = await _blueprint_of(session, app) + pin = _pin(app.draft) + hash_ = graph_hash_of(blueprint) + if pin is None or pin.get("graph_hash") != hash_: + raise PersonalRefused(409, "蓝图在存成个人应用之后又改过:请先回到蓝图「存成我的应用」,再刷新", GRAPH_CHANGED) + if problem := policy_problem(blueprint.graph): + raise PersonalRefused(403, problem, POLICY) + who = principal.username + async with _lock(who): + active = await latest_refresh(session, app.id, hash_, active_only=True) + if active is not None: + return active, (await remaining_today(session, who))[0] + remaining, limit = await remaining_today(session, who) + if remaining <= 0: + raise PersonalRefused(429, f"今天的刷新次数已经用完(每人每天 {limit} 次),请明天再试,或请管理员调整上限", + DAILY_LIMIT) + run = await launch_run( + session, graph=blueprint.graph, input_payload=refresh_inputs(blueprint), + run_class="exploratory", workflow_name=app.name, + actor=who, origin_kind=ORIGIN, app_id=app.id, memory_scope=chat_memory_scope(app.owner), + origin={"blueprint_id": blueprint.id, "graph_hash": hash_, "actor_verified": principal.verified, + "auth_mode": principal.mode}, + options={MASK_RESULTS_OPTION: True, READ_ONLY_OPTION: True}) + return run, remaining - 1 + + +def _runs_of(app_id: str, graph_hash: str) -> Any: + from app.db.models import Run + + return select(Run).where(Run.app_id == app_id, Run.origin_kind == ORIGIN, + func.json_extract(Run.origin, "$.graph_hash") == graph_hash) + + +async def latest_refresh(session: AsyncSession, app_id: str, graph_hash: str, *, active_only: bool = False) -> Any: + """这个应用这张图最近一次刷新(不论成败);active_only 只要还没结束的。""" + from app.db.models import Run + + query = _runs_of(app_id, graph_hash) + if active_only: + query = query.where(Run.status.in_(("queued", "running", "interrupted"))) + return (await session.execute(query.order_by(Run.created_at.desc()).limit(1))).scalars().first() + + +async def exploratory_runs(session: AsyncSession, app_id: str, graph_hash: str | None, n: int, + owner: str | None = None) -> list[Any]: + """视图来源 exploratory:这个应用、这个拥有者、这张图(run.origin 里记的指纹,发起时由服务端写)下最近 n 次成功且 + 已封存的刷新,新的在前。sealed_now 认的是「这一次结束时封的」(同 apps/resolve.sealed_runs)。owner 给了只认他发起的 + (开了登录时刷新只能由拥有者发起;关登录没有可信的身份,不按人筛)。""" + from app.db.models import Run + from app.scheduler.auto_compare import sealed_now + + if not graph_hash: + return [] + query = _runs_of(app_id, graph_hash).where(Run.status == "succeeded") + if owner: + query = query.where(Run.started_by == owner) + rows = list((await session.execute(query.order_by(Run.finished_at.desc(), Run.created_at.desc()) + .limit(max(n, 1) * 3 + 5))).scalars()) + out = [] + for run in rows: + if await sealed_now(session, run): + out.append(run) + if len(out) >= n: + break + return out + + +# -------------------------------------------------------------------------- +# 提交审核、共享副本 +# -------------------------------------------------------------------------- + + +async def review_task(session: AsyncSession, blueprint_id: str, *, pending: bool = True) -> Any: + """这个蓝图最近一条审核待办;pending 只要还在等的。""" + from app.db.models_process import Task + + query = select(Task).where(Task.kind == REVIEW, Task.correlation_key == f"{REVIEW_KEY}{blueprint_id}") + if pending: + query = query.where(Task.status == "pending") + return (await session.execute(query.order_by(Task.created_at.desc()).limit(1))).scalars().first() + + +async def _review_targets(session: AsyncSession, to: Any) -> list[tuple[str, str]]: + """提交给谁:一位或几位搭建者(用户),或者一个组。开了登录时按名录核对(同岗位绑定、授权):没有的、停用的拒收; + 点名的人要是搭建者或管理员——使用者拿不到共享副本,派给他等于没人能审。组里的人在打开待办那一刻展开成成员,取副本时 + 再按角色判。""" + from app.api.deps import auth_mode + from app.auth.directory import load_directory, mismatch + from app.db.models import User + + targets = list(dict.fromkeys((str((t or {}).get("kind") or ""), str((t or {}).get("name") or "").strip()) + for t in to or [] if isinstance(t, dict))) + if not targets or any(kind not in ("user", "group") or not name for kind, name in targets): + raise PersonalRefused(422, "提交审核要选一位搭建者,或者交给一个组", REVIEW_TARGET) + if (mode := auth_mode()) == "off": + return targets + known = await load_directory(session) + for kind, name in targets: + if (m := mismatch(known, mode, kind, name)) is not None and m.blocking: + raise PersonalRefused(422, f"{m.text}:请从候选中重新选择审核的人", REVIEW_TARGET) + if kind == "user": + role = await session.scalar(select(User.role).where(User.username == name)) + if role is not None and role not in ("builder", "admin"): + raise PersonalRefused(422, f"「{name}」不是搭建者:审核个人应用要交给搭建者或管理员,他们才能把它做成正式应用", + REVIEW_TARGET) + return targets + + +async def submit_review(session: AsyncSession, app: Any, *, to: list[dict[str, str]], principal: Any, + note: str | None = None) -> Any: + """开一条 review 待办派给搭建者(提交),交回 Task。蓝图记为审核中;同一个蓝图已经有一条在等的,不另开。""" + from app.apps.audit import record + from app.process.tasks import announce, open_review + + await ensure_allowed(session, principal) + _personal_app(app, principal) + blueprint = await _blueprint_of(session, app) + targets = await _review_targets(session, to) + if await review_task(session, blueprint.id) is not None: + raise PersonalRefused(409, "已经提交过审核,正在等搭建者处理;处理完(发布或退回)之后才能再提交", IN_REVIEW) + pin = _pin(app.draft) + runs = await exploratory_runs(session, app.id, (pin or {}).get("graph_hash"), 1, + app.owner if principal.mode != "off" else None) + if not runs: + raise PersonalRefused(409, "提交审核前请先成功刷新一次:审核的人要看到这个应用用真数出的结果", NO_RUN) + note = (note or "").strip()[:2000] + task = await open_review(session, run=runs[0], app_id=app.id, blueprint_id=blueprint.id, + title=f"审核个人应用「{app.name}」", to=targets) + blueprint.status = "in_review" + await event(session, blueprint, "submit_review", principal, + {"task_id": task.id, "run_id": runs[0].id, "to": [{"kind": k, "name": n} for k, n in targets], + "note": note}) + await record(session, action="personal.submit_review", subject_kind="app", subject_id=app.id, + actor=principal.username, data={"blueprint_id": blueprint.id, "task_id": task.id, + "to": [{"kind": k, "name": n} for k, n in targets]}) + await session.commit() + await announce(task.id) + return task + + +async def copy_for_review(session: AsyncSession, blueprint: Any, *, principal: Any) -> Any: + """搭建者处理审核时得到这个蓝图的共享副本(copied_from 指向原蓝图,提交),原个人应用和原蓝图都不动。 + + 只有这条审核派给的人能取(同待办的处理人,process/tasks.handles):个人蓝图只有拥有者看得见,管理员也不例外,审核是 + 拥有者主动交出去的那一次。同一个人再取,交回他上次取的那一份。审核已经结束(发布、退回)的,取过的照样交回,没取过的 + 不再给。""" + from app.db.models_blueprints import Blueprint + from app.process.tasks import review_handler + + if principal.mode != "off" and not principal.at_least("builder"): + raise PersonalRefused(403, "没有权限:审核个人应用需要搭建者及以上的角色", "personal.review_forbidden") + if blueprint is None or blueprint.scope != "personal": + raise PersonalRefused(404, BLUEPRINT_GONE) + mine = await _copy_by(session, blueprint.id, principal.username) + if mine is not None: + return mine + task = await review_task(session, blueprint.id) + if task is None or not await review_handler(session, task, principal): + raise PersonalRefused(404, BLUEPRINT_GONE) + copied = Blueprint(name=blueprint.name, owner=principal.username, scope="shared", status="drafting", + spec=copy_module.deepcopy(blueprint.spec or {}), template_id=blueprint.template_id, + template_version=blueprint.template_version, source=dict(blueprint.source or {}), + graph=copy_module.deepcopy(blueprint.graph or {}), graph_hash=graph_hash_of(blueprint), + joints=copy_module.deepcopy(blueprint.joints or {}), copied_from=blueprint.id, + updated_by=principal.username) + session.add(copied) + await session.flush() + await event(session, copied, "copy", principal, {"from": blueprint.id, "task_id": task.id}) + await event(session, blueprint, "copy", principal, {"to": copied.id, "task_id": task.id}) + await session.commit() + await session.refresh(copied) + return copied + + +async def _copy_by(session: AsyncSession, blueprint_id: str, who: str | None) -> Any: + from app.db.models_blueprints import Blueprint + + query = select(Blueprint).where(Blueprint.copied_from == blueprint_id) + query = query.where(Blueprint.owner == who) if who else query.where(Blueprint.owner.is_(None)) + return (await session.execute(query.order_by(Blueprint.created_at.desc()).limit(1))).scalars().first() + + +async def review_published(session: AsyncSession, blueprint: Any, *, app_id: str, principal: Any) -> str | None: + """发布单把审核副本发布完之后调(包 B2 的 publish_plan 在最后一步提交之后调,这里自己提交):原蓝图的审核待办记为 + 已发布(结论里记副本和发布出来的应用),原蓝图回到「个人应用」,通知提交人。不是审核副本的、原蓝图的待办已经结束的, + 什么都不做,交回 None;做了交回待办 id。提交人自己决定个人应用留不留,这里不动它。""" + from app.db.models_blueprints import Blueprint + from app.process.tasks import close_review + + if blueprint is None or not blueprint.copied_from: + return None + original = await session.get(Blueprint, blueprint.copied_from) + if original is None: + return None + task_id = await close_review(session, original.id, principal, + {"decision": "published", "copy": blueprint.id, "app_id": app_id}) + if task_id is None: + return None + if original.status == "in_review": + original.status = "personal" + await event(session, original, "review_published", principal, {"task_id": task_id, "copy": blueprint.id, + "app_id": app_id}) + await session.commit() + await _announce_review(session, original, task_id, "published", app_id) + return task_id + + +async def settle_review(session: AsyncSession, original: Any) -> str | None: + """审核副本已经发布、原蓝图的审核待办却还挂着(发布单做完时没能结束它:通知、写库出了错只记了日志):补上。拥有者 + 打开个人应用、处理人打开待办时顺带看一眼(同试运行的 settle),不让原蓝图一直停在「审核中」。记的处理人是发布那份 + 副本的人。做了交回待办 id,不用做为 None。""" + from types import SimpleNamespace + + from app.db.models_blueprints import Blueprint + + if original is None or original.scope != "personal" or original.status != "in_review": + return None + published = (await session.execute(select(Blueprint).where( + Blueprint.copied_from == original.id, Blueprint.status == "published", Blueprint.app_id.is_not(None)) + .order_by(Blueprint.updated_at.desc()).limit(1))).scalars().first() + if published is None or await review_task(session, original.id) is None: + return None + publisher = SimpleNamespace(username=published.owner, verified=False, groups=(), mode="local", + at_least=lambda _role: False) + return await review_published(session, published, app_id=published.app_id, principal=publisher) + + +async def reject_review(task_id: str, principal: Any, *, note: str | None) -> None: + """审核的人在待办里退回(process/tasks.respond 转过来):待办记为退回,原蓝图回到「个人应用」,通知提交人。""" + from app.db.base import SessionLocal + from app.db.models_blueprints import Blueprint + from app.db.models_process import Task + from app.process.tasks import TaskRefused, close_review + + async with SessionLocal() as session: + task = await session.get(Task, task_id) + blueprint_id = (task.correlation_key or "").removeprefix(REVIEW_KEY) if task is not None else "" + original = await session.get(Blueprint, blueprint_id) if blueprint_id else None + if task is None or original is None: + raise TaskRefused("待办不存在,提交审核的蓝图可能已被删除", status_code=404) + closed = await close_review(session, original.id, principal, + {"decision": "reject", "note": (note or "").strip()[:2000]}, require_handler=True) + if closed is None: + raise TaskRefused("这条待办已经处理过了,请刷新页面查看最新状态") + if original.status == "in_review": + original.status = "personal" + await event(session, original, "review_rejected", principal, {"task_id": closed, "note": note or ""}) + await session.commit() + await _announce_review(session, original, closed, "rejected", original.app_id) + + +async def _announce_review(session: AsyncSession, blueprint: Any, task_id: str, decision: str, + app_id: str | None) -> None: + """通知提交人(蓝图的拥有者)审核有了结果:订阅了「我提交审核的应用有结果」的个人渠道和全局渠道收到。app_id 是链接 + 过去的应用(发布了的是正式应用,退回的是他的个人应用)。""" + from app.notify.service import notify_review, spawn + + if blueprint.owner: + spawn(notify_review(task_id, decision, owner=blueprint.owner, name=blueprint.name or "", app_id=app_id)) + + +async def review_payload(session: AsyncSession, task: Any) -> dict[str, Any]: + """审核待办给处理人看的内容(待办箱、待办详情的 payload):提交的是哪个蓝图、哪个个人应用、谁提交的、留了什么话、 + 这个人取过副本没有。不含个人应用页面上的数——要看数,取副本后在副本上用真数试一次。""" + from app.db.models_blueprints import Blueprint, BlueprintEvent + + blueprint_id = (task.correlation_key or "").removeprefix(REVIEW_KEY) + blueprint = await session.get(Blueprint, blueprint_id) if blueprint_id else None + if blueprint is None: + return {"kind": REVIEW} + await settle_review(session, blueprint) + submitted = (await session.execute(select(BlueprintEvent).where( + BlueprintEvent.blueprint_id == blueprint.id, BlueprintEvent.op == "submit_review") + .order_by(BlueprintEvent.seq.desc()).limit(1))).scalars().first() + copies = (await session.execute(select(Blueprint.id, Blueprint.owner, Blueprint.status, Blueprint.app_id) + .where(Blueprint.copied_from == blueprint.id) + .order_by(Blueprint.created_at))).all() + return {"kind": REVIEW, "blueprint_id": blueprint.id, "app_id": task.app_id, "name": blueprint.name, + "purpose": _purpose(blueprint), "template_id": blueprint.template_id, + "submitted_by": submitted.actor if submitted is not None else blueprint.owner, + "note": (submitted.data or {}).get("note") or "" if submitted is not None else "", + "copies": [{"id": c.id, "owner": c.owner, "status": c.status, "app_id": c.app_id} for c in copies]} + + +# -------------------------------------------------------------------------- +# 给拥有者看的状态 +# -------------------------------------------------------------------------- + + +async def personal_state(session: AsyncSession, app: Any, principal: Any) -> dict[str, Any]: + """个人应用详情里给拥有者的那一块:今天还能刷新几次、蓝图的状态(是不是改过还没重新存)、审核到哪了(在等谁、退回了、 + 已发布成哪个正式应用)。""" + from app.db.models_blueprints import Blueprint + + remaining, limit = await remaining_today(session, principal.username) + blueprint = await session.get(Blueprint, app.blueprint_id) if app.blueprint_id else None + pin = _pin(app.draft) + out: dict[str, Any] = {"remaining_today": remaining, "daily_limit": limit, + "blueprint_status": blueprint.status if blueprint is not None else None, + "graph_changed": blueprint is not None and pin is not None + and pin.get("graph_hash") != graph_hash_of(blueprint), + "review": None} + if blueprint is None: + return out + if await settle_review(session, blueprint) is not None: + out["blueprint_status"] = blueprint.status + task = await review_task(session, blueprint.id, pending=False) + if task is not None: + from app.process.tasks import _assignments + + rows = (await _assignments(session, [task.id])).get(task.id, []) + outcome = task.outcome or {} + out["review"] = {"task_id": task.id, "status": task.status, "decision": outcome.get("decision"), + "note": outcome.get("note") or "", "app_id": outcome.get("app_id"), + "to": [{"kind": a.principal_kind, "name": a.principal} for a in rows + if a.status != "withdrawn"], + "resolved_at": task.resolved_at.isoformat() if task.resolved_at else None} + return out diff --git a/backend/app/blueprints/publish_plan.py b/backend/app/blueprints/publish_plan.py index 12a42204..f738b3ef 100644 --- a/backend/app/blueprints/publish_plan.py +++ b/backend/app/blueprints/publish_plan.py @@ -2,12 +2,48 @@ 步骤的顺序让中途失败的状态无害:定时任务先停用、应用发布后才启用;授权放最后。 -包 B2 实现。 +- 出单(plan):先按卡片现在的样子重新实例化(blueprints/trial.materialize:试运行之后改了「谁来做」「多久更新」 + 「填什么」这类卡片,图、定时任务参数、应用草稿都跟着变,发布的就是卡片上写的),再按这张图(graph_hash)算出要做的 + 九步、一页白话摘要和全量预检的问题(带白话、分给「你来定」「助手可以修」「要找管理员」),落成一行 publish_plans + (status=planned),记下卡片内容的指纹(options.spec_hash)。除了蓝图自己的图,什么都不写。 +- 预检(_preflight)只读:工作流发布前检查(api/workflows.check_graph,同发布前检查接口)、按将要生成的那一版跑应用检查 + (apps/lint.lint_app,把那一版当作已发布交进去)、定时任务的设置(api/schedules.schedule_values、template_problem)、 + 授权名单核对名录(api/apps.grants_problem)、蓝图检查(待确认项挡发布)、发布的级别要不要管理员。执行时在保存版本之前 + 再预检一次:任何 error 都停在预检,什么都没写(连版本都不存)。 +- 执行(run)、接着做(resume):每一步直接调现有的服务函数(存版本、发布、建定时任务、建应用、发布应用、启用、授权、 + 发起第一次),不走 HTTP;每步结束写 steps[i]、写审计(publish_plan.*)。某步失败 status=stopped,写明哪一步、白话原因; + 接着做从那一步开始,已完成的按结果里的 id 核对(还在、还是那个状态),不重做。 +- 发布单针对的那张图(graph_hash)、卡片内容(spec_hash)变了就拒绝执行,要求重新出单;发布的图和最近一次试运行的 + 不同,摘要里照实说(不拦)。 +- 应用的管理权限:蓝图已经发布成应用的,出单、执行都要对那个应用有管理权限(发布单会改它的草稿、发布它、整份替换 + 它的授权),只有查看权限的搭建者出单时预检报 plan.app_forbidden,执行 403。 +- 填报登记:发布应用那一步把图里写的记录表版本切成往里写的那一版(records/tables.publish_table),线上原来那一版 + 这时才停用,和应用的新一版一起提交。 +- 补偿:工作流发布之后的失败不撤回发布(本来就撤不回),摘要照实说「工作流已发布,应用还没有」;停用的定时任务在应用发布前 + 不会运行;应用停在草稿时不授权。 +- 中断:执行是在请求里按步做的,进程没了(重启、被杀)时单子停在「正在执行」。启动时(startup)把这样的单改成停下, + 停在还没做完的那一步、写明「执行中断」,就能接着做。 """ from __future__ import annotations +import copy +import logging +from dataclasses import dataclass, field +from types import SimpleNamespace from typing import Any +from fastapi import HTTPException +from sqlalchemy import select, update +from sqlalchemy.ext.asyncio import AsyncSession + +from app.api.deps import Principal +from app.db.base import utcnow +from app.db.models import Run, Schedule, Workflow, WorkflowVersion +from app.db.models_apps import App, AppVersion +from app.db.models_blueprints import Blueprint, PublishPlan + +logger = logging.getLogger(__name__) + #: 发布单的步骤(顺序即执行顺序) STEP_KINDS = ( "save_version", # 保存版本(按图哈希复用已有的) @@ -22,18 +58,955 @@ STEP_KINDS = ( ) #: 问题的三类(N10 的 who) PROBLEM_WHO = ("you", "assistant", "admin") +LEVELS = ("published", "governed") +LEVEL_TEXT = {"published": "已发布", "governed": "受管"} +#: 口径升版的处置在摘要里怎么说(apps/spec.DISPOSITIONS) +DISPOSITION_TEXT = {"recompute": "以前的数按新口径重算,旧数据留底", "dual": "新旧口径的数并列", + "incomparable": "注明前后不可比"} +GRANT_ROLES = ("use", "observe", "manage") + +# 问题和步骤失败的编号(白话在 app/plain.py) +NOT_INSTANTIATED = "plan.not_instantiated" +GRAPH_CHANGED = "plan.graph_changed" +UNTRIALED = "plan.untrialed" +TRIAL_DIFFERS = "plan.trial_differs" +ADMIN_REQUIRED = "plan.admin_required" +DOWNGRADE_ADMIN = "plan.downgrade_admin" +PREFLIGHT = "plan.preflight" +WORKFLOW_PUBLISH = "plan.workflow_publish" +SCHEDULE_INVALID = "plan.schedule_invalid" +APP_PUBLISH = "plan.app_publish" +APP_ARCHIVED = "plan.app_archived" +APP_FORBIDDEN = "plan.app_forbidden" +GRANT_REFUSED = "plan.grant_refused" +FIRST_RUN = "plan.first_run" +OBJECT_MISSING = "plan.object_missing" +STEP_FAILED = "plan.step_failed" +INTERRUPTED = "plan.interrupted" +#: 接口拒绝执行时的机器码:发布单不在能执行的状态(已在执行、已做完、没停下) +PLAN_STATE = "plan_state" +PLAN_GONE = "发布单不存在,可能已被删除" + +#: 预检时还没有工作流(新蓝图第一次发布):应用检查里钉住项先写这个占位,执行时换成真的工作流 id +_PENDING_WORKFLOW = "__pending__" -async def plan(session: Any, blueprint: Any, *, level: str, principal: Any, options: dict[str, Any] | None = None) -> Any: - """出发布单(只读预检),交回 PublishPlan(已落库,status=planned)。""" - raise NotImplementedError +class PlanRefused(Exception): + """不出单 / 不执行:status_code 照 HTTP 语义,message 是给人看的一句话,code 是机器码。""" + + def __init__(self, status_code: int, message: str, code: str | None = None) -> None: + super().__init__(message) + self.status_code = status_code + self.message = message + self.code = code -async def run(session: Any, plan_id: str, *, principal: Any) -> Any: - """按序执行;某步失败时 status=stopped 并写明原因。""" - raise NotImplementedError +class StepFailed(Exception): + """一步没做成:code 是 plan.* 编号,message 是白话原因,problems 是挡住它的检查问题(带白话)。""" + + def __init__(self, code: str, message: str, problems: list[dict[str, Any]] | None = None) -> None: + super().__init__(message) + self.code = code + self.message = message + self.problems = problems or [] -async def resume(session: Any, plan_id: str, *, principal: Any) -> Any: - """从停下的那一步接着做;已完成的步骤按结果里的 id 核对,不重做。""" - raise NotImplementedError +@dataclass +class _Target: + """这份发布单要发布的东西:图、哈希、应用草稿、定时任务参数,以及「将要生成的那一版」(已有相同哈希的复用)。""" + + graph: dict[str, Any] + digest: str + app_spec: dict[str, Any] + schedule: dict[str, Any] | None + workflow: Workflow | None + version: int + reused: bool + name: str + app: App | None = None + previous: AppVersion | None = None + #: 蓝图已经发布过(再发一版):应用视图正在用的那个定时任务,沿用它、按新设置改,不另建一个 + schedule_row: Schedule | None = None + #: 复用的那一版已经发布过的话,发布时的级别(同一级别就不重复发布) + published_as: str | None = None + + @property + def process(self) -> bool: + return any((p or {}).get("use") == "process" for p in self.app_spec.get("pins") or []) + + +# -------------------------------------------------------------------------- +# 要发布的东西 +# -------------------------------------------------------------------------- + + +async def _target(session: AsyncSession, bp: Blueprint) -> _Target: + from app.blueprints.trial import app_spec_for + from app.core.artifact_store import graph_hash + + graph = bp.graph or {} + if not graph.get("nodes"): + raise PlanRefused(409, "蓝图还没有生成工作流:请先把卡片补齐,用真数试运行一次", NOT_INSTANTIATED) + digest = bp.graph_hash or graph_hash(graph) + # 应用草稿和定时任务参数用实例化这张图时记下的那一份(试运行看到的就是它) + app_spec, schedule = await app_spec_for(session, bp, digest) + if app_spec is None: + raise PlanRefused(409, "蓝图现在的图还没有实例化过:请先用真数试运行一次", NOT_INSTANTIATED) + workflow = await session.get(Workflow, bp.workflow_id) if bp.workflow_id else None + same = None + if workflow is not None: + same = (await session.execute(select(WorkflowVersion).where( + WorkflowVersion.workflow_id == workflow.id, WorkflowVersion.graph_hash == digest) + .order_by(WorkflowVersion.version.desc()).limit(1))).scalar_one_or_none() + app = await session.get(App, bp.app_id) if bp.app_id else None + previous = None + if app is not None and app.published_version: + previous = (await session.execute(select(AppVersion).where( + AppVersion.app_id == app.id, AppVersion.version == app.published_version))).scalar_one_or_none() + from app.apps.versions import is_published + + return _Target(graph=graph, digest=digest, app_spec=app_spec, schedule=schedule, workflow=workflow, + version=same.version if same is not None else (workflow.version + 1 if workflow else 1), + reused=same is not None, name=workflow.name if workflow is not None else (bp.name or "未命名应用"), + app=app, previous=previous, schedule_row=await _app_schedule(session, app, workflow), + published_as=same.level if same is not None and workflow is not None + and is_published(same, current=workflow.published_version) else None) + + +async def _app_schedule(session: AsyncSession, app: App | None, workflow: Workflow | None) -> Schedule | None: + """已有应用的「最近封存」视图正在看的那个定时任务(跑的是这个工作流):再发一版时沿用它。""" + if app is None or workflow is None: + return None + for view in ((app.draft or {}).get("views") or {}).values(): + origin = ((view or {}).get("source") or {}).get("from") + if isinstance(origin, str) and origin.startswith("schedule:"): + row = await session.get(Schedule, origin[len("schedule:"):]) + if row is not None and row.workflow_id == workflow.id: + return row + return None + + +def _ours(pin: dict[str, Any], workflow_id: str) -> bool: + """这个钉住项是不是蓝图的那张图:还没发布的草稿(固定到蓝图上、还没有工作流)或者就是这个工作流。应用里另加的 + 别的工作流不动。""" + return bool(pin.get("blueprint")) or pin.get("workflow_id") in (None, workflow_id, _PENDING_WORKFLOW) + + +def formal_spec(draft: dict[str, Any], *, workflow_id: str, version: int, digest: str, level: str, + schedule_id: str | None) -> dict[str, Any]: + """应用草稿 → 引用发布出来的那一版:蓝图那张图的钉住项写工作流 id、版本号、哈希、级别;绑着它的「最近封存」视图有 + 定时任务的只看它出的数。""" + spec = copy.deepcopy(draft) + pins, ours = [], set() + for pin in spec.get("pins") or []: + if not isinstance(pin, dict): + continue + if _ours(pin, workflow_id): + ours.add(pin.get("alias")) + pin = {"alias": pin.get("alias"), "workflow_id": workflow_id, "version": version, "graph_hash": digest, + "level": level, "use": pin.get("use") or "view"} + pins.append(pin) + spec["pins"] = pins + for view in (spec.get("views") or {}).values(): + source = (view or {}).get("source") or {} + if source.get("kind") == "latest_sealed" and source.get("pin") in ours: + source["from"] = f"schedule:{schedule_id}" if schedule_id else "formal" + return spec + + +async def _simulated_pins(session: AsyncSession, spec: dict[str, Any], target: _Target, *, workflow_id: str, + level: str) -> dict[str, Any]: + """应用检查认的钉住项(apps/pins.PinState):蓝图那张图的钉住项当作将要发布的那一版已经发布的样子(不读库), + 应用里另加的别的工作流照常从库里读。""" + from app.apps.pins import PinState, load_pins + + pins = await load_pins(session, spec) + workflow = SimpleNamespace(id=workflow_id, name=target.name, published_version=target.version, status=level) + row = SimpleNamespace(workflow_id=workflow_id, version=target.version, graph=target.graph, + graph_hash=target.digest, level=level, retired_at=None) + for pin in spec.get("pins") or []: + if isinstance(pin, dict) and pin.get("alias") and pin.get("workflow_id") == workflow_id \ + and pin.get("version") == target.version: + pins[str(pin["alias"])] = PinState(alias=str(pin["alias"]), pin=pin, workflow=workflow, row=row) + return pins + + +def bindings_of(bp: Blueprint) -> dict[str, Any]: + """岗位绑定:「谁来做」卡片上写了具体的人或组的,按模板定的岗位名绑上(templates/_common.bindings_of)。""" + from app.blueprints.templates._common import bindings_of as from_cards + + return from_cards(bp.spec or {}) + + +def grant_items(bp: Blueprint) -> list[tuple[str, str, str]]: + """「谁能看」卡片 → 授权 [(kind, name, role)]。""" + access = (bp.spec or {}).get("access") or {} + return [(str(item.get("kind") or ""), str(item.get("name") or ""), role) + for role in GRANT_ROLES for item in access.get(role) or [] if isinstance(item, dict)] + + +def _app_draft(target: _Target) -> dict[str, Any]: + """要发布的应用草稿:新应用用实例化时的那一份;已有应用的沿用它现在的草稿(页面上改过的呈现都留着),只把跟着卡片 + 走的结构换成这一版的——入口表单和入口映射(「填什么」)、新加的岗位和待办外观(「谁来做」)。不换的话,表单改过 + 之后应用还按旧表单收提交,和新的图、新的记录表版本对不上。""" + if not (target.app is not None and isinstance(target.app.draft, dict) and target.app.draft.get("pins")): + return target.app_spec + draft = copy.deepcopy(target.app.draft) + fresh = target.app_spec + forms = draft.setdefault("forms", {}) + for name, form in (fresh.get("forms") or {}).items(): + forms[name] = copy.deepcopy(form) + for key in ("slots", "task_ui"): + have = draft.setdefault(key, {}) + for name, value in (fresh.get(key) or {}).items(): + have.setdefault(name, copy.deepcopy(value)) + wanted = {e["id"]: e for e in fresh.get("entries") or [] if isinstance(e, dict) and e.get("id")} + entries = [] + for entry in draft.get("entries") or []: + new = wanted.pop(entry.get("id"), None) if isinstance(entry, dict) else None + entries.append({**entry, **{k: copy.deepcopy(new[k]) for k in ("form", "map") if k in new}} if new else entry) + draft["entries"] = entries + [copy.deepcopy(e) for e in wanted.values()] + return draft + + +def _draft_bindings(bp: Blueprint, target: _Target) -> dict[str, Any]: + """应用的岗位绑定:已有应用里绑过的留着,蓝图上写了而应用里还没绑的补上。""" + have = copy.deepcopy((target.app.draft_bindings if target.app is not None else None) or {"slots": {}}) + slots = have.setdefault("slots", {}) + for slot, people in (bindings_of(bp).get("slots") or {}).items(): + if not slots.get(slot): + slots[slot] = people + return have + + +def _schedule_name(target: _Target) -> str: + return str((target.schedule or {}).get("name") or f"{target.name}(定时)") + + +# -------------------------------------------------------------------------- +# 预检(只读) +# -------------------------------------------------------------------------- + + +def _problem(code: str, message: str, level: str = "error", **extra: Any) -> dict[str, Any]: + return {"code": code, "level": level, "message": message, **extra} + + +async def _preflight(session: AsyncSession, bp: Blueprint, target: _Target, *, level: str, principal: Principal, + options: dict[str, Any]) -> list[dict[str, Any]]: + """全量预检,只读:交回问题(带白话、谁来改)。任何 error 都挡住发布单。""" + from app.api.apps import grants_problem + from app.api.schedules import schedule_values, template_problem + from app.api.workflows import check_graph, downgrades_governed + from app.apps.lint import lint_app + from app.blueprints.store import blueprint_issues_of + from app.blueprints.trial import is_trial_of + from app.core.artifact_store import graph_hash + + # 蓝图:缺的项、待确认的项(发布前要人看过,bp.unconfirmed)、还没填的生成关节(同蓝图卡片上显示的那一份) + out: list[dict[str, Any]] = [{**i, "source": "blueprint"} for i in blueprint_issues_of(bp)] + # 发布的级别:受管级、把受管降为已发布都只给管理员(Q8,同发布接口) + if level == "governed" and not principal.at_least("admin"): + out.append(_problem(ADMIN_REQUIRED, "以受管级别发布需要管理员", source="plan")) + elif target.workflow is not None and not principal.at_least("admin") \ + and await downgrades_governed(session, target.workflow, level): + out.append(_problem(DOWNGRADE_ADMIN, f"「{target.workflow.name}」现在是受管级别,按已发布级别发布会把它降级," + "需要管理员", source="plan")) + # 工作流发布前检查(和发布前检查接口同一套口径,带修复的种类) + checked = await check_graph(session, target.graph, level) + kinds = {f.get("id"): f.get("kind") for f in checked.get("fixes") or []} + for issue in checked.get("issues") or []: + out.append({**issue, "fix_kind": kinds.get(issue.get("fix")), "source": "workflow"}) + workflow_id = target.workflow.id if target.workflow is not None else _PENDING_WORKFLOW + # 定时任务:设置本身、输入模板对不对得上这张图的入口字段 + if target.schedule: + body = {**target.schedule, "name": _schedule_name(target), "workflow_id": workflow_id, + "run_class": "formal", "enabled": False} + try: + values = schedule_values(body) + except HTTPException as e: + out.append(_problem(SCHEDULE_INVALID, str(e.detail), source="schedule")) + else: + if problem := template_problem(values["input_template"], target.graph, target.name): + out.append(_problem(SCHEDULE_INVALID, problem, source="schedule")) + # 应用:按将要生成的那一版(当作已发布)跑应用检查;已有应用的另核对能不能再发布、要不要处置、出单的人能不能管它 + if target.app is not None and target.app.status == "archived": + out.append(_problem(APP_ARCHIVED, f"应用「{target.app.name}」已归档,不能再发布", source="app")) + if (refused := await app_forbidden(session, target.app, principal)) is not None: + out.append(_problem(APP_FORBIDDEN, refused, source="app")) + spec = formal_spec(_app_draft(target), workflow_id=workflow_id, version=target.version, digest=target.digest, + level=level, schedule_id=None) + issues = await lint_app(session, spec, _draft_bindings(bp, target), previous=target.previous, + dispositions=options.get("dispositions") or {}, + pins=await _simulated_pins(session, spec, target, workflow_id=workflow_id, level=level)) + out += [{**i, "source": "app"} for i in issues] + # 授权:给的人和组要在名录里(同授权接口) + _, problem = await grants_problem(session, grant_items(bp)) + if problem: + out.append(_problem(GRANT_REFUSED, problem, source="grants")) + # 试运行:没用真数试过、试过之后又改了,照实说(不拦) + trial = await session.get(Run, bp.last_trial_run_id) if bp.last_trial_run_id else None + if not is_trial_of(trial, bp) or trial.status != "succeeded": + out.append(_problem(UNTRIALED, "还没有成功的试运行:发布之前没用真数看过结果", "warning", source="plan")) + elif graph_hash(trial.graph or {}) != target.digest: + out.append(_problem(TRIAL_DIFFERS, "发布的内容和最近一次试运行不同:试运行之后又改过", "warning", source="plan")) + return [_with_who(p) for p in out] + + +def _with_who(issue: dict[str, Any]) -> dict[str, Any]: + """问题带上白话(没登记白话的照旧只有技术说法)和归谁处理(you / assistant / admin,摘要按它分三栏)。""" + from app.plain import who_of, with_plain + + out = with_plain(issue) + return {**out, "who": (out.get("plain") or {}).get("who") or who_of(issue)} + + +def _errors(problems: list[dict[str, Any]]) -> list[dict[str, Any]]: + return [p for p in problems if p.get("level") == "error"] + + +async def app_forbidden(session: AsyncSession, app: App | None, principal: Principal) -> str | None: + """蓝图已经发布成的那个应用,这个人能不能管:发布单要改它的草稿、发布它、整份替换它的授权,和应用编辑器、授权接口 + 一样要管理权限(apps/access.app_role)。能管或还没有应用时为 None,不能管交回原因。""" + from app.apps.access import app_role, at_least + + if app is None or at_least(await app_role(session, principal, app), "manage"): + return None + return (f"蓝图已经发布成应用「{app.name}」,你对它没有管理权限:发布单会改它的页面、发布新的一版、替换它的授权," + "请应用的管理者或管理员来发布") + + +# -------------------------------------------------------------------------- +# 白话摘要 +# -------------------------------------------------------------------------- + + +def _names(items: list[tuple[str, str, str]], role: str) -> str: + return "、".join("所有人" if kind == "everyone" else f"{name}(组)" if kind == "group" else name + for kind, name, r in items if r == role) + + +def _summary(bp: Blueprint, target: _Target, *, level: str, first_run: bool, options: dict[str, Any], + problems: list[dict[str, Any]]) -> list[dict[str, str]]: + """每一步一句「会发生什么」。""" + from app.apps.access import ROLE_TEXT + from app.blueprints.trial import RECORDS_TEMPLATE, template_of + from app.scheduler import cron + + out: list[dict[str, str]] = [] + + def say(step: str, text: str) -> None: + out.append({"step": step, "text": text}) + + name = target.name + if target.reused: + say("save_version", f"沿用「{name}」已有的 v{target.version}(内容和蓝图现在的图相同),不另存新版本") + elif target.workflow is None: + say("save_version", f"把蓝图的图存成工作流「{name}」的 v{target.version}") + else: + say("save_version", f"把蓝图的图存成「{name}」的 v{target.version}") + say("preflight", "发布前把工作流、应用、定时任务、授权名单都检查一遍:有问题就停在这里,什么都不写") + current = target.workflow.published_version if target.workflow is not None else None + again = f";「{name}」现在发布的是 v{current},这次会把 v{target.version} 立为当前版本" \ + if current and current > target.version else "" + codes = {p.get("code") for p in problems} + tried = ";发布的内容和最近一次试运行不同(试运行之后又改过),建议再试一次" if TRIAL_DIFFERS in codes else \ + ";还没有用真数试运行过" if UNTRIALED in codes else "" + if target.published_as == level: + say("publish_workflow", f"「{name}」v{target.version} 已经按{LEVEL_TEXT[level]}级别发布过,不重复发布{tried}") + else: + say("publish_workflow", + f"按{LEVEL_TEXT[level]}级别发布「{name}」v{target.version}:此后正式运行只从这一版发起{again}{tried}") + when = "" + if target.schedule: + try: + when = cron.describe(str(target.schedule.get("cron")), str(target.schedule.get("timezone"))) + except Exception: # noqa: BLE001 - 说不清的设置预检会报 + when = "按设定的时间" + if target.schedule_row is not None: + say("create_schedule", f"沿用应用正在用的定时任务「{target.schedule_row.name}」,时间按蓝图更新:{when}") + else: + say("create_schedule", f"建定时任务(先停用,应用发布后再启用):{when}") + else: + say("create_schedule", "不建定时任务:这个应用不按时间自动出数") + if target.app is not None: + say("create_app", f"更新应用「{target.app.name}」:沿用它现在的页面(页面上改过的都留着),换成新发布的这一版," + "表单按「填什么」更新;新加的数请在页面上加数据卡片") + else: + say("create_app", f"建应用「{bp.name or name}」,页面就是试运行时看到的样子") + chosen = list((options.get("dispositions") or {}).values()) + if target.previous is not None and chosen: + say("publish_app", "发布应用。口径变了:" + ";".join(DISPOSITION_TEXT.get(v, v) for v in chosen)) + else: + say("publish_app", "发布应用:使用者打开的就是这一版") + if target.schedule: + say("enable_schedule", f"启用定时任务:此后{when}按这一版自动出数") + else: + say("enable_schedule", "没有定时任务要启用") + items = grant_items(bp) + parts = [f"{who}可以{ROLE_TEXT[role]}" for role in GRANT_ROLES if (who := _names(items, role))] + # 填报登记:看板读的是正式运行的封存结果(看得到全部行),汇总是全量的,这是作者的选择,照实写(N8) + records = ";使用者能看到全部提交的汇总数,逐条记录只看得到自己提交的" if template_of(bp) == RECORDS_TEMPLATE else "" + if parts: + say("grant", ";".join(parts) + f"(应用的授权按「谁能看」整份替换){records}") + else: + say("grant", f"「谁能看」里没有人:不改授权,只有管理员和搭建者能打开{records}") + if first_run: + say("first_run", "立即运行一次,应用一打开就有数") + else: + say("first_run", "不立即运行:流程类应用等有人发起" if target.process else "不立即运行:等定时任务出第一期数") + return out + + +# -------------------------------------------------------------------------- +# 出单 +# -------------------------------------------------------------------------- + + +def _steps(target: _Target, *, first_run: bool) -> list[dict[str, Any]]: + skipped = set() + if not target.schedule: + skipped |= {"create_schedule", "enable_schedule"} + if not first_run: + skipped.add("first_run") + return [{"kind": k, "status": "skipped" if k in skipped else "pending", "result": None, "error_code": None, + "message": None, "at": None} for k in STEP_KINDS] + + +async def _instantiate(session: AsyncSession, blueprint: Blueprint, principal: Principal) -> None: + """出单前按卡片现在的样子重新实例化(试运行时也是这一步):图、关节存到蓝图上,应用草稿和定时任务参数记进留痕, + _target 取的就是这一份。卡片没改过的,图和哈希都不变(实例化是确定的)。""" + from app.blueprints.trial import TrialRefused, materialize + + try: + await materialize(session, blueprint, principal=principal) + except TrialRefused as e: + raise PlanRefused(e.status_code, e.message, NOT_INSTANTIATED if e.status_code == 409 else e.code) from e + + +async def plan(session: AsyncSession, blueprint: Blueprint, *, level: str, principal: Principal, + options: dict[str, Any] | None = None) -> PublishPlan: + """出发布单(按卡片重新实例化,再只读预检),交回 PublishPlan(已落库,status=planned)。options:first_run(不给时 + 看板类为真、流程类为假)、dispositions(钉住项升版时的处置,{别名: recompute|dual|incomparable});另记 spec_hash + (卡片内容的指纹,执行前核对)。""" + from app.apps.audit import record + from app.blueprints.store import spec_digest + + if level not in LEVELS: + raise PlanRefused(422, "发布级别只能是「已发布」或「受管」") + if blueprint.scope != "shared": + raise PlanRefused(409, "个人蓝图不走发布单:存成你的应用自己用,想给别人用请提交审核", PLAN_STATE) + # 实例化挡路的问题(缺项、没填的关节、画布校验)预检里都有(蓝图检查、发布前检查),这里不另列:执行时的预检同一份 + await _instantiate(session, blueprint, principal) + target = await _target(session, blueprint) + options = dict(options or {}) + first_run = bool(options["first_run"]) if isinstance(options.get("first_run"), bool) else not target.process + options["first_run"] = first_run + options["spec_hash"] = spec_digest(blueprint) + problems = await _preflight(session, blueprint, target, level=level, principal=principal, options=options) + row = PublishPlan(blueprint_id=blueprint.id, actor=principal.username, level=level, graph_hash=target.digest, + options=options, steps=_steps(target, first_run=first_run), + summary=_summary(blueprint, target, level=level, first_run=first_run, options=options, + problems=problems), + problems=problems, status="planned") + session.add(row) + await session.flush() + await record(session, action="publish_plan.plan", subject_kind="publish_plan", subject_id=row.id, + actor=principal.username, data={"blueprint_id": blueprint.id, "level": level, + "graph_hash": target.digest, "errors": len(_errors(problems))}) + await session.commit() + await session.refresh(row) + return row + + +def plan_out(row: PublishPlan) -> dict[str, Any]: + """接口形状(frontend/src/typesBlueprint.ts 的 PublishPlanRow),另带 ok(没有挡路的问题)。""" + return {"id": row.id, "blueprint_id": row.blueprint_id, "level": row.level, "graph_hash": row.graph_hash, + "status": row.status, "steps": row.steps or [], "summary": row.summary or [], + "problems": row.problems or [], "options": row.options or {}, + "ok": not _errors(row.problems or []) and row.status != "stopped", + "actor": row.actor, + "created_at": row.created_at.isoformat() if row.created_at else None, + "updated_at": row.updated_at.isoformat() if row.updated_at else None} + + +# -------------------------------------------------------------------------- +# 执行 +# -------------------------------------------------------------------------- + + +async def get_plan(session: AsyncSession, plan_id: str) -> PublishPlan: + row = await session.get(PublishPlan, plan_id) + if row is None: + raise PlanRefused(404, PLAN_GONE) + return row + + +async def run(session: AsyncSession, plan_id: str, *, principal: Principal) -> PublishPlan: + """按序执行;某步失败时 status=stopped 并写明原因。只有刚出的单(planned)能执行。""" + return await _start(session, plan_id, principal=principal, want="planned", action="publish_plan.start") + + +async def resume(session: AsyncSession, plan_id: str, *, principal: Principal) -> PublishPlan: + """从停下的那一步接着做;已完成的步骤按结果里的 id 核对,不重做。只有停下的单(stopped)能接着做。""" + return await _start(session, plan_id, principal=principal, want="stopped", action="publish_plan.resume") + + +async def _start(session: AsyncSession, plan_id: str, *, principal: Principal, want: str, action: str) -> PublishPlan: + from app.apps.audit import record + + row = await get_plan(session, plan_id) + bp = await session.get(Blueprint, row.blueprint_id) + if bp is None: + raise PlanRefused(404, "发布单对应的蓝图不存在,可能已被删除") + from app.blueprints.store import spec_digest + + if (bp.graph_hash or "") != (row.graph_hash or ""): + raise PlanRefused(409, "出单之后蓝图又改过:要发布的已经不是这份发布单看过的那张图,请重新出一份发布单", + GRAPH_CHANGED) + if (row.options or {}).get("spec_hash") and row.options["spec_hash"] != spec_digest(bp): + raise PlanRefused(409, "出单之后卡片又改过:摘要里写的已经不是现在要发布的,请重新出一份发布单", GRAPH_CHANGED) + app = await session.get(App, bp.app_id) if bp.app_id else None + if (refused := await app_forbidden(session, app, principal)) is not None: + raise PlanRefused(403, refused, APP_FORBIDDEN) + if row.status != want: + state = {"planned": "还没开始执行", "running": "正在执行", "stopped": "停在了某一步", "done": "已经做完"} + hint = ",请用「接着做」" if row.status == "stopped" else "" + raise PlanRefused(409, f"这份发布单{state.get(row.status, row.status)}{hint}", PLAN_STATE) + if any(s.get("error_code") == OBJECT_MISSING for s in row.steps or []): + # 前面建好的东西不见了:接着做会把后面几步接到一个对不上的状态上,只能重新出单(新单按现在的样子重新算) + raise PlanRefused(409, "这份发布单前面建好的东西不见了,不能接着做:请重新出一份发布单", OBJECT_MISSING) + # 条件更新抢到执行权:两个人同时点「确认发布」,只有先到的那个做 + claimed = await session.execute(update(PublishPlan).where(PublishPlan.id == row.id, PublishPlan.status == want) + .values(status="running").execution_options(synchronize_session=False)) + if claimed.rowcount != 1: + await session.rollback() + raise PlanRefused(409, "这份发布单刚刚被别人开始执行了,请刷新后查看进度", PLAN_STATE) + await record(session, action=action, subject_kind="publish_plan", subject_id=row.id, actor=principal.username, + data={"blueprint_id": bp.id, "level": row.level, "graph_hash": row.graph_hash}) + await session.commit() + await session.refresh(row) + await _drive(session, row, bp, principal) + await session.refresh(row) + return row + + +def _set_step(row: PublishPlan, kind: str, **values: Any) -> None: + steps = copy.deepcopy(row.steps or []) + for step in steps: + if step.get("kind") == kind: + step.update(values, at=utcnow().isoformat()) + row.steps = steps + + +def _step(row: PublishPlan, kind: str) -> dict[str, Any]: + return next((s for s in row.steps or [] if s.get("kind") == kind), {"kind": kind, "status": "pending"}) + + +async def _drive(session: AsyncSession, row: PublishPlan, bp: Blueprint, principal: Principal) -> None: + from app.apps.audit import record + + ctx = _Run(row=row, bp=bp, principal=principal, actor=principal.username, + options=dict(row.options or {}), level=row.level) + for kind in STEP_KINDS: + step = _step(row, kind) + if step.get("status") == "skipped": + continue + try: + if step.get("status") == "done": + await _verify(session, ctx, kind, step.get("result") or {}) + ctx.results[kind] = step.get("result") or {} + continue + if kind == "save_version" and _step(row, "preflight").get("status") != "done": + # 预检在保存版本之前:挡住了就什么都不写(连版本都不存) + await _execute(session, ctx, "preflight") + ctx.prechecked = True + result = await _execute(session, ctx, kind) + except StepFailed as e: + await _reset(session, row, bp) + failed = "preflight" if kind == "save_version" and not ctx.prechecked else kind + _set_step(row, failed, status="failed", error_code=e.code, message=_where_we_stand(ctx, failed, e.message)) + if e.problems: + row.problems = e.problems + row.status = "stopped" + await record(session, action="publish_plan.stop", subject_kind="publish_plan", subject_id=row.id, + actor=ctx.actor, data={"step": failed, "code": e.code, "message": e.message}) + await session.commit() + return + except Exception as e: # noqa: BLE001 - 意外的错照实停在这一步,接着做时从这里开始 + logger.exception("发布单 %s 的「%s」这一步出错", row.id, kind) + await _reset(session, row, bp) + _set_step(row, kind, status="failed", error_code=STEP_FAILED, message=_where_we_stand( + ctx, kind, f"这一步出了意外的错({type(e).__name__}),后面的步骤都没有做")) + row.status = "stopped" + await record(session, action="publish_plan.stop", subject_kind="publish_plan", subject_id=row.id, + actor=ctx.actor, data={"step": kind, "code": STEP_FAILED, "error": type(e).__name__}) + await session.commit() + return + ctx.results[kind] = result + _set_step(row, kind, status="done", result=result, error_code=None, message=None) + await record(session, action="publish_plan.step", subject_kind="publish_plan", subject_id=row.id, + actor=ctx.actor, data={"step": kind, "result": result}) + await session.commit() + row.status = "done" + bp.status = "published" + app_id = (ctx.results.get("create_app") or {}).get("app_id") + await record(session, action="publish_plan.done", subject_kind="publish_plan", subject_id=row.id, actor=ctx.actor, + data={"blueprint_id": bp.id, "results": ctx.results}) + await session.commit() + if bp.copied_from and app_id: + # 个人应用的审核副本:原蓝图的审核待办记为已发布、通知提交人(blueprints/personal.py) + from app.blueprints.personal import review_published + + try: + await review_published(session, bp, app_id=app_id, principal=principal) + except Exception: # noqa: BLE001 - 发布已经做完,不因此回滚;拥有者打开个人应用、处理人打开待办时会补上 + # (blueprints/personal.settle_review),审核待办不会一直挂着 + logger.exception("发布单 %s 做完后没能结束审核待办,等下次有人打开时补上", row.id) + await session.rollback() + + +#: 停在这几步时工作流已经发布、应用还没有(发布撤不回,照实说);停在这几步时应用已经发布好了 +_PUBLISHED_NO_APP = ("create_schedule", "create_app", "publish_app") +_APP_PUBLISHED = ("enable_schedule", "grant", "first_run") + + +def _where_we_stand(ctx: _Run, kind: str, message: str) -> str: + """停下时的白话原因前面说清现在的状态:工作流已发布、应用还没有;或者应用已经发布好了(补偿:发布撤不回,P1)。""" + if kind in _PUBLISHED_NO_APP and "publish_workflow" in ctx.results and not message.startswith("工作流已经发布"): + return f"工作流已经发布,应用还没有:{message}" + if kind in _APP_PUBLISHED and not message.startswith("应用已经发布"): + return f"应用已经发布好了,这一步没做完:{message}" + return message + + +async def _reset(session: AsyncSession, row: PublishPlan, bp: Blueprint) -> None: + """一步没做成:丢掉这一步没提交的改动,重新读发布单和蓝图(回滚之后它们的属性过期了,异步会话里不能隐式重读)。""" + await session.rollback() + await session.refresh(row) + await session.refresh(bp) + + +@dataclass +class _Run: + row: PublishPlan + bp: Blueprint + principal: Principal + actor: str | None + options: dict[str, Any] + level: str + results: dict[str, Any] = field(default_factory=dict) + prechecked: bool = False + target: _Target | None = None + + +async def _execute(session: AsyncSession, ctx: _Run, kind: str) -> dict[str, Any]: + return await _STEPS[kind](session, ctx) + + +async def _fresh_target(session: AsyncSession, ctx: _Run) -> _Target: + ctx.target = await _target(session, ctx.bp) + return ctx.target + + +async def _do_preflight(session: AsyncSession, ctx: _Run) -> dict[str, Any]: + if ctx.prechecked and ctx.target is not None: + return {"errors": 0, "warnings": len([p for p in ctx.row.problems or [] if p.get("level") == "warning"])} + target = await _fresh_target(session, ctx) + problems = await _preflight(session, ctx.bp, target, level=ctx.level, principal=ctx.principal, options=ctx.options) + ctx.row.problems = problems + if errors := _errors(problems): + raise StepFailed(PREFLIGHT, f"发布前检查有 {len(errors)} 个问题没解决,什么都没写:请按问题处理,再接着做", problems) + return {"errors": 0, "warnings": len(problems)} + + +async def _do_save_version(session: AsyncSession, ctx: _Run) -> dict[str, Any]: + """按图哈希判断:已有相同的版本就复用;没有就存一版(同画布保存:版本号加一、画布状态退回草稿)。""" + from app.blueprints.trial import template_of + + bp = ctx.bp + target = ctx.target or await _fresh_target(session, ctx) + if target.reused and target.workflow is not None: + return {"workflow_id": target.workflow.id, "version": target.version, "graph_hash": target.digest, + "reused": True} + workflow = target.workflow + purpose = ((bp.spec or {}).get("purpose") or {}).get("value") + ref = (bp.spec or {}).get("template") or {} + note = f"出自蓝图「{bp.name}」" + if workflow is None: + source = bp.source or {} + workflow = Workflow(name=bp.name or "未命名应用", description=str(purpose) if isinstance(purpose, str) else "", + graph=target.graph, tags=["blueprint"], status="draft", + origin={"blueprint_id": bp.id, "template": f"{template_of(bp)}@{ref.get('version') or 1}", + **({"run_id": source.get("id")} if source.get("kind") == "run" else {})}) + session.add(workflow) + await session.flush() + version = 1 + else: + workflow.graph = target.graph + workflow.version += 1 + version = workflow.version + if workflow.status in ("published", "governed"): + workflow.status = "draft" + session.add(WorkflowVersion(workflow_id=workflow.id, version=version, graph=target.graph, + graph_hash=target.digest, note=note)) + bp.workflow_id = workflow.id + await session.commit() + await session.refresh(workflow) + target.workflow, target.version, target.reused = workflow, version, True + return {"workflow_id": workflow.id, "version": version, "graph_hash": target.digest, "reused": False} + + +async def _version_row(session: AsyncSession, ctx: _Run) -> tuple[Workflow, WorkflowVersion]: + saved = ctx.results.get("save_version") or {} + workflow = await session.get(Workflow, saved.get("workflow_id") or "") + row = (await session.execute(select(WorkflowVersion).where( + WorkflowVersion.workflow_id == saved.get("workflow_id"), + WorkflowVersion.version == saved.get("version")))).scalar_one_or_none() if workflow else None + if workflow is None or row is None: + raise StepFailed(OBJECT_MISSING, "保存过的工作流版本不见了(可能被删除),请重新出一份发布单") + return workflow, row + + +async def _do_publish_workflow(session: AsyncSession, ctx: _Run) -> dict[str, Any]: + from app.api.workflows import commit_publish, downgrades_governed, gate_issues + from app.apps.versions import is_published + + workflow, snapshot = await _version_row(session, ctx) + if ctx.level == "governed" and not ctx.principal.at_least("admin"): + raise StepFailed(ADMIN_REQUIRED, "以受管级别发布需要管理员") + if is_published(snapshot, current=workflow.published_version) and snapshot.level == ctx.level: + return {"workflow_id": workflow.id, "version": snapshot.version, "level": ctx.level, "already": True} + if not ctx.principal.at_least("admin") and await downgrades_governed(session, workflow, ctx.level): + raise StepFailed(DOWNGRADE_ADMIN, f"「{workflow.name}」现在是受管级别,降为已发布需要管理员") + issues = await gate_issues(session, snapshot.graph, ctx.level) + if issues is None or any(i["level"] == "error" for i in issues): + problems = [_with_who({**i, "source": "workflow"}) for i in issues or []] + raise StepFailed(WORKFLOW_PUBLISH, "工作流没有通过发布检查,还没有发布", problems) + out = await commit_publish(session, workflow, snapshot, ctx.level, ctx.actor) + return {"workflow_id": workflow.id, "version": out["version"], "level": out["level"]} + + +async def _do_create_schedule(session: AsyncSession, ctx: _Run) -> dict[str, Any]: + """建定时任务,先停用:应用发布之后才启用,不会在没有应用的时候产生无主的正式运行。""" + from app.api.schedules import create_schedule_row, retime + + target = ctx.target or await _fresh_target(session, ctx) + workflow, _ = await _version_row(session, ctx) + body = {**(target.schedule or {}), "name": _schedule_name(target), "workflow_id": workflow.id, + "run_class": "formal", "enabled": False} + try: + if target.schedule_row is not None: + row = await retime(session, target.schedule_row, body) + return {"schedule_id": row.id, "enabled": row.enabled, "reused": True} + row = await create_schedule_row(session, body, actor=ctx.actor) + except HTTPException as e: + await session.rollback() + raise StepFailed(SCHEDULE_INVALID, str(e.detail)) from e + return {"schedule_id": row.id, "enabled": False} + + +async def _do_create_app(session: AsyncSession, ctx: _Run) -> dict[str, Any]: + """建应用(或更新蓝图已有的那个应用的草稿):钉住项换成刚发布的那一版,看板视图绑上定时任务,岗位按「谁来做」绑上。""" + from app.api.apps import new_app + + bp = ctx.bp + target = ctx.target or await _fresh_target(session, ctx) + _, snapshot = await _version_row(session, ctx) + spec = formal_spec(_app_draft(target), workflow_id=snapshot.workflow_id, version=snapshot.version, + digest=target.digest, level=ctx.level, + schedule_id=(ctx.results.get("create_schedule") or {}).get("schedule_id")) + bindings = _draft_bindings(bp, target) + if target.app is not None: + if target.app.status == "archived": + raise StepFailed(APP_ARCHIVED, f"应用「{target.app.name}」已归档,不能再发布") + target.app.draft, target.app.draft_bindings = spec, bindings + target.app.blueprint_id = bp.id + target.app.updated_by = ctx.actor + await session.commit() + return {"app_id": target.app.id, "created": False} + purpose = ((bp.spec or {}).get("purpose") or {}).get("value") + app = await new_app(session, name=bp.name or target.name, + description=str(purpose) if isinstance(purpose, str) else "", + spec=spec, bindings=bindings, actor=ctx.actor, blueprint_id=bp.id) + bp.app_id = app.id + target.app = app + await session.commit() + return {"app_id": app.id, "created": True} + + +def records_refs(graph: dict[str, Any]) -> list[str]: + """图里写记录表的那几个调用工具节点写的表(args.table,「键.v版本」)。""" + from app.records import RECORDS_APPEND + + out: list[str] = [] + for node in graph.get("nodes") or []: + config = ((node or {}).get("data") or {}).get("config") or {} + if (node or {}).get("type") == "tool" and config.get("tool") == RECORDS_APPEND: + ref = str((config.get("args") or {}).get("table") or "").strip() + if ref and ref not in out: + out.append(ref) + return out + + +async def _switch_records(session: AsyncSession, bp: Blueprint, app: App, graph: dict[str, Any]) -> list[str]: + """填报登记:图里写的那一版记录表成为往里写的那一版(records/tables.publish_table),线上原来那一版这时才停用。 + 只 flush:和应用的新一版一起提交(publish_draft),应用没发布成就一起回滚,线上照常写旧的那一版。""" + from app.blueprints.trial import RECORDS_TEMPLATE, template_of + from app.records.store import RecordsRefused + from app.records.tables import columns_from_fields, publish_table + + if template_of(bp) != RECORDS_TEMPLATE: + return [] + out = [] + for ref in records_refs(graph): + try: + row = await publish_table(session, app, ref, columns_from_fields((bp.spec or {}).get("fields") or [])) + except RecordsRefused as e: + raise StepFailed(e.code, f"工作流已经发布,应用还没有:{e.message}") from e + out.append(f"{row.table_key}.v{row.version}") + return out + + +async def _the_app(session: AsyncSession, ctx: _Run) -> App: + app = await session.get(App, (ctx.results.get("create_app") or {}).get("app_id") or "") + if app is None: + raise StepFailed(OBJECT_MISSING, "建好的应用不见了(可能被删除),请重新出一份发布单") + return app + + +async def _do_publish_app(session: AsyncSession, ctx: _Run) -> dict[str, Any]: + from app.api.apps import publish_draft + + app = await _the_app(session, ctx) + if app.status == "archived": + raise StepFailed(APP_ARCHIVED, f"应用「{app.name}」已归档,不能再发布") + target = ctx.target or await _fresh_target(session, ctx) + tables = await _switch_records(session, ctx.bp, app, target.graph) + try: + out = await publish_draft(session, app, note=f"发布单 {ctx.row.id[:8]}", + dispositions=ctx.options.get("dispositions") or {}, actor=ctx.actor) + except HTTPException as e: + await session.rollback() + raise StepFailed(APP_PUBLISH, f"工作流已经发布,应用还没有:{e.detail}") from e + if not out.get("ok"): + problems = [_with_who({**i, "source": "app"}) for i in out.get("issues") or []] + raise StepFailed(APP_PUBLISH, "工作流已经发布,应用没有通过检查、还没有发布;使用者暂时看不到它", problems) + return {"app_id": app.id, "version": out["version"], **({"records": tables} if tables else {})} + + +async def _the_schedule(session: AsyncSession, ctx: _Run) -> Schedule: + row = await session.get(Schedule, (ctx.results.get("create_schedule") or {}).get("schedule_id") or "") + if row is None: + raise StepFailed(OBJECT_MISSING, "建好的定时任务不见了(可能被删除),请重新出一份发布单") + return row + + +async def _do_enable_schedule(session: AsyncSession, ctx: _Run) -> dict[str, Any]: + from app.api.schedules import set_enabled + + row = await set_enabled(session, await _the_schedule(session, ctx), True) + return {"schedule_id": row.id, "enabled": True, + "next_run_at": row.next_run_at.isoformat() if row.next_run_at else None} + + +async def _do_grant(session: AsyncSession, ctx: _Run) -> dict[str, Any]: + """按「谁能看」整份替换应用的授权(名录核对同授权接口)。卡片上没有人的不改授权(已有应用的授权留着)。""" + from app.api.apps import grants_problem, replace_grants + + app = await _the_app(session, ctx) + wanted, problem = await grants_problem(session, grant_items(ctx.bp)) + if problem: + raise StepFailed(GRANT_REFUSED, f"应用已经发布,授权没有改:{problem}") + if not wanted: + return {"app_id": app.id, "grants": None} + after = await replace_grants(session, app, wanted, actor=ctx.actor) + return {"app_id": app.id, "grants": len(after)} + + +async def _do_first_run(session: AsyncSession, ctx: _Run) -> dict[str, Any]: + """立即运行一次:有定时任务的按它触发一次(应用的视图只看它出的数),没有的从这一版发起一次正式运行。""" + from app.engine.launch import LaunchRefused, launch_run + from app.scheduler import service + + schedule_id = (ctx.results.get("create_schedule") or {}).get("schedule_id") + if schedule_id: + fire = await service.fire_once(schedule_id, utcnow().replace(microsecond=0), "manual", actor=ctx.actor) + if fire is None or not fire.run_id: + reason = (fire.reason if fire is not None else None) or "定时任务没能发起这次运行" + raise StepFailed(FIRST_RUN, f"应用已经发布好了,第一次运行没能发起:{reason}") + return {"run_id": fire.run_id, "schedule_id": schedule_id} + _, snapshot = await _version_row(session, ctx) + try: + run = await launch_run(session, workflow_id=snapshot.workflow_id, run_class="formal", version=snapshot.version, + expect_hash=snapshot.graph_hash, actor=ctx.actor, origin_kind="launcher", + origin={"publish_plan": ctx.row.id}) + except LaunchRefused as e: + raise StepFailed(FIRST_RUN, f"应用已经发布好了,第一次运行没能发起:{e.message}") from e + return {"run_id": run.id} + + +_STEPS = { + "preflight": _do_preflight, "save_version": _do_save_version, "publish_workflow": _do_publish_workflow, + "create_schedule": _do_create_schedule, "create_app": _do_create_app, "publish_app": _do_publish_app, + "enable_schedule": _do_enable_schedule, "grant": _do_grant, "first_run": _do_first_run, +} + + +# -------------------------------------------------------------------------- +# 启动整理:上次进程没了时还在执行的单 +# -------------------------------------------------------------------------- + + +async def startup() -> int: + """上次进程没了时还在执行的发布单(status=running,执行是在请求里做的,进程一没就再没有人接着推):改成停下,停在第一个 + 还没做完的步骤上、写明执行中断,这样就能「接着做」。那一步可能已经做了一半:接着做时按图哈希复用版本、按应用 id 更新 + 同一个应用,不会另建一份工作流版本或应用。交回整理了几份。""" + from app.apps.audit import record + from app.db.base import SessionLocal + + async with SessionLocal() as session: + rows = list((await session.execute(select(PublishPlan).where(PublishPlan.status == "running"))).scalars()) + for row in rows: + kind = next((st.get("kind") for st in row.steps or [] if st.get("status") not in ("done", "skipped")), None) + if kind: + _set_step(row, kind, status="failed", error_code=INTERRUPTED, + message="执行到这一步时服务重启了,这一步可能只做了一半:请核对后接着做") + row.status = "stopped" + await record(session, action="publish_plan.stop", subject_kind="publish_plan", subject_id=row.id, + actor=None, data={"step": kind, "code": INTERRUPTED}) + await session.commit() + return len(rows) + + +# -------------------------------------------------------------------------- +# 接着做:已完成的步骤按结果里的 id 核对 +# -------------------------------------------------------------------------- + + +async def _verify(session: AsyncSession, ctx: _Run, kind: str, result: dict[str, Any]) -> None: + """已完成的这一步做出来的东西还在、还是那个状态;不在了就停下(plan.object_missing),不重做、不另建一份。""" + from app.apps.versions import is_published + + ctx.results[kind] = result + if kind == "save_version": + workflow, row = await _version_row(session, ctx) + if row.graph_hash != ctx.row.graph_hash: + raise StepFailed(OBJECT_MISSING, f"「{workflow.name}」v{row.version} 的内容和发布单针对的图不一致,请重新出单") + ctx.target = await _fresh_target(session, ctx) + elif kind == "preflight": + ctx.prechecked = True + elif kind == "publish_workflow": + workflow, row = await _version_row(session, ctx) + if not is_published(row, current=workflow.published_version): + raise StepFailed(OBJECT_MISSING, f"「{workflow.name}」v{row.version} 已经不是发布状态(可能已退役),请重新出单") + elif kind in ("create_schedule", "enable_schedule"): + await _the_schedule(session, ctx) + elif kind == "create_app": + app = await _the_app(session, ctx) + if ctx.target is not None: + ctx.target.app = app + elif kind == "publish_app": + app = await _the_app(session, ctx) + if (app.published_version or 0) < int(result.get("version") or 0): + raise StepFailed(OBJECT_MISSING, f"应用「{app.name}」的发布版本对不上发布单记下的,请重新出单") diff --git a/backend/app/blueprints/store.py b/backend/app/blueprints/store.py new file mode 100644 index 00000000..d09ed7c3 --- /dev/null +++ b/backend/app/blueprints/store.py @@ -0,0 +1,292 @@ +"""蓝图的读写与留痕(N2、§3.1、§3.10)。蓝图接口(api/blueprints.py 的 PATCH)、蓝图助手和填关节的流式接口 +(api/copilot_blueprint.py)都经这里落地,规则只有一处: + +- 权限:共享蓝图要搭建者;个人蓝图只给拥有者,而且管理员开了个人应用(blueprints/personal.allowed)。别人的个人蓝图 + 当没有(404),不说它在不在; +- 落地:bp_* 操作按 blueprints/ops.apply_bp_op 逐个落到存着的那一份上,每个操作写一条 blueprint_events(谁、核实过没有、 + 来源、位置、改之前、改之后,P2)。复用口径卡的操作先按库里那一版核对(look/calibers.verify_reuse)并补上它读的列; +- 关节:卡片改了,生成关节的依据跟着变的那几组标回「待填」(instantiate.filled_from),蓝图上的关节状态随之更新。 +""" +from __future__ import annotations + +import copy +from dataclasses import dataclass, field +from typing import Any + +from fastapi import HTTPException +from sqlalchemy import func, select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.blueprints.ops import BpRefused, apply_bp_op, parse_pointer + +#: 蓝图不存在(或者是别人的个人蓝图) +BLUEPRINT_GONE = "蓝图不存在,可能已被删除" +PERSONAL_OFF = "管理员还没有开放个人应用:想给自己做一个看板,可以请管理员打开,或请搭建者做成应用" + + +@dataclass +class Saved: + """apply_ops_and_save 的结果:落地后的蓝图、落地了的操作、被拒的操作(partial 时才有)。""" + + spec: dict[str, Any] + applied: list[dict[str, Any]] = field(default_factory=list) + refused: list[dict[str, Any]] = field(default_factory=list) + + +# ========================================================================== +# 读与权限 +# ========================================================================== + + +async def load(session: AsyncSession, blueprint_id: str) -> Any: + """按 id 读蓝图并核对权限(ensure_access)。不存在、看不到的一律 404。""" + from app.db.models_blueprints import Blueprint + + row = await session.get(Blueprint, blueprint_id) + if row is None: + raise HTTPException(404, BLUEPRINT_GONE) + await ensure_access(session, row) + return row + + +async def ensure_access(session: AsyncSession, blueprint: Any) -> None: + """这个人能不能读写这张蓝图:共享的要搭建者及以上;个人的要拥有者,且个人应用开着(关登录时只看开关)。""" + from app.api.deps import current_principal, ensure_role + from app.blueprints import personal + + principal = current_principal() + if getattr(blueprint, "scope", "shared") == "personal": + if not personal.owns(principal, blueprint.owner): + raise HTTPException(404, BLUEPRINT_GONE) + if not await personal.allowed(session, principal): + raise HTTPException(403, PERSONAL_OFF) + return + ensure_role("builder") + + +# ========================================================================== +# 落地与留痕 +# ========================================================================== + + +def _at(spec: dict[str, Any], path: str | None) -> Any: + """蓝图上某个位置现在的值(留痕的改之前 / 改之后)。位置不存在为 None。""" + if not path: + return None + try: + tokens = parse_pointer(path) + except BpRefused: + return None + cur: Any = spec + for token in tokens: + if isinstance(cur, list) and token.isdigit() and int(token) < len(cur): + cur = cur[int(token)] + elif isinstance(cur, dict): + cur = cur.get(token) + else: + return None + return copy.deepcopy(cur) + + +async def _verified_reuse(session: AsyncSession, op: dict[str, Any]) -> dict[str, Any]: + """复用口径卡的操作(设 /data/i/reuse,或加一项带 reuse 的数据):按库里那一版核对,补上那张卡读的取数节点和列。""" + from app.look.calibers import verify_reuse + + path = str(op.get("path") or "") + if op.get("op") == "bp_set" and path.startswith("/data/") and path.endswith("/reuse") \ + and isinstance(op.get("value"), dict): + return {**op, "value": await verify_reuse(session, op["value"])} + if op.get("op") == "bp_add" and path.startswith("/data") and isinstance(op.get("value"), dict) \ + and isinstance(op["value"].get("reuse"), dict): + return {**op, "value": {**op["value"], "reuse": await verify_reuse(session, op["value"]["reuse"])}} + return op + + +async def _next_seq(session: AsyncSession, blueprint_id: str) -> int: + from app.db.models_blueprints import BlueprintEvent + + return int((await session.execute(select(func.coalesce(func.max(BlueprintEvent.seq), 0)) + .where(BlueprintEvent.blueprint_id == blueprint_id))).scalar_one()) + 1 + + +async def record_event(session: AsyncSession, blueprint: Any, *, op: str, data: dict[str, Any], actor: str | None, + verified: bool) -> None: + """记一条蓝图留痕(不提交)。op 是 bp_* 操作,或 instantiate、fill_joint、trial、publish 这类蓝图上的动作。""" + from app.db.models_blueprints import BlueprintEvent + + session.add(BlueprintEvent(blueprint_id=blueprint.id, seq=await _next_seq(session, blueprint.id), actor=actor, + verified=verified, op=op, data=data)) + await session.flush() + + +async def apply_ops_and_save(session: AsyncSession, blueprint: Any, ops: list[dict[str, Any]], actor: str | None, + verified: bool, source: str, *, partial: bool = False) -> Saved: + """把一串 bp_* 操作落到蓝图上、写留痕、提交。source 是 user / assistant。 + + partial=False(卡片上的修改):一个被拒就整串不落,抛 BpRefused。partial=True(助手这一轮提的):被拒的跳过、照实交回, + 别的照常落——助手的操作是按它看到的那一份写的,人在这期间改过卡片的话,冲突的那几个让人看见,不悄悄吞掉。""" + from app.blueprints.spec import empty_blueprint + + spec = copy.deepcopy(blueprint.spec or empty_blueprint()) + saved = Saved(spec=spec) + events: list[tuple[str, dict[str, Any]]] = [] + for raw in ops: + try: + op = await _verified_reuse(session, raw) + before = _at(spec, op.get("path")) + spec = apply_bp_op(spec, op, source=source) + except BpRefused as e: + if not partial: + raise + saved.refused.append({"op": raw, "message": e.message, "code": e.code}) + continue + saved.applied.append(op) + events.append((str(op.get("op")), _event_data(op, before, spec, source))) + saved.spec = spec + if not saved.applied: + return saved + for op_name, data in events: + await record_event(session, blueprint, op=op_name, data=data, actor=actor, verified=verified) + blueprint.spec = spec + template = spec.get("template") or None + blueprint.template_id = template["id"] if template else None + blueprint.template_version = template["version"] if template else None + blueprint.joints = refreshed_joints(blueprint, spec, ctx=await instantiate_context(session, blueprint)) + blueprint.updated_by = actor + await session.commit() + return saved + + +def _event_data(op: dict[str, Any], before: Any, spec: dict[str, Any], source: str) -> dict[str, Any]: + kind = op.get("op") + if kind == "bp_ask": + return {"source": source, "question": op.get("question"), "options": op.get("options") or []} + if kind == "bp_template": + return {"source": source, "template": op.get("template"), "after": copy.deepcopy(spec.get("template"))} + data: dict[str, Any] = {"source": source, "path": op.get("path"), "before": before} + if kind != "bp_remove": + data["after"] = _at(spec, op.get("path")) if kind == "bp_set" else copy.deepcopy(op.get("value")) + return data + + +# ========================================================================== +# 关节 +# ========================================================================== + + +#: 不算「卡片内容」的键:助手反问的记录(问答不改要发布的东西) +_DIGEST_SKIP = ("asks",) + + +def spec_digest(blueprint: Any) -> str: + """卡片内容的指纹(加上名字,名字进工作流和应用):发布单出单时记下,执行、接着做之前再算一遍,对不上就是出单之后 + 卡片又改过——改「谁来做」「多久更新」「谁能看」这类不一定改图哈希的卡片,也认得出来(P1:摘要里说的就是要发布的)。""" + from app.core.artifact_store import canonical_json, content_hash + + spec = {k: v for k, v in (blueprint.spec or {}).items() if k not in _DIGEST_SKIP} + return content_hash(canonical_json({"name": blueprint.name or "", "spec": spec})) + + +def context_of(blueprint: Any) -> dict[str, Any]: + """实例化这张蓝图要的上下文(instantiate 的关键字参数):名字、工作流、蓝图 id;自由形导入的图存在蓝图的 graph 上。""" + from app.blueprints.templates.freeform import ID as FREEFORM + + out: dict[str, Any] = {"name": blueprint.name or None, "workflow_id": blueprint.workflow_id, + "blueprint_id": blueprint.id} + if blueprint.template_id == FREEFORM or ((blueprint.spec or {}).get("template") or {}).get("id") == FREEFORM: + out["graph"] = blueprint.graph or None + return out + + +async def records_context(session: AsyncSession, blueprint: Any, *, create: bool = False) -> dict[str, str] | None: + """填报登记的记录表 {table, source}(records/tables):不是填报登记的为 None。实例化、试运行、填关节、发布单都从这里取, + 同一张蓝图只有这一种写法(P5)。 + + table 写「键.v版本」:写入时 records/tables.find_table 认得它,图也就固定在这一个表版本上(N8:应用版本固定表版本, + 表单不兼容地改了出新版本,图跟着变、要重新发布)。source 是这一版登记成的数据源名(汇总的 SQL 查它)。 + create=False 只读(records/tables.pick_table:和「填什么」兼容的那一版;要出新版本才对得上的、还没建过的为 None, + 模板按记录表服务的起名规则猜第一版);create=True 没有就建(records/tables.draft_table:草稿不影响线上——兼容的 + 只补列,不兼容的出下一版、线上那一版照常收提交,切换在发布单里做;只 flush,调用方提交)。个人蓝图从不建表: + 个人应用只读,建了也没人往里写,使用者也不该凭一张草稿在全局的数据源里添一个(只读现有的)。""" + from app.blueprints.templates.records import ID as RECORDS + from app.db.models import DataSource + from app.records.tables import columns_from_fields, draft_table, pick_table + + spec = blueprint.spec or {} + if ((spec.get("template") or {}).get("id") or blueprint.template_id) != RECORDS: + return None + from app.records.store import RecordsRefused + + columns = columns_from_fields(spec.get("fields") or []) + if create and getattr(blueprint, "scope", "shared") != "personal": + # 字段名不合规(records.column_invalid)照实抛给调用方:试运行、填关节要说清是哪个字段 + row = await draft_table(session, blueprint, columns) + else: + try: + row = await pick_table(session, blueprint.id, columns) + except RecordsRefused: + row = None + if row is None: + return None + source = await session.get(DataSource, row.source_id) if row.source_id else None + return {"table": f"{row.table_key}.v{row.version}", "source": source.name if source is not None else ""} + + +async def instantiate_context(session: AsyncSession, blueprint: Any, *, create_records: bool = False) -> dict[str, Any]: + """context_of 再加上填报登记的记录表:生成关节的依据(取数说明)里有记录表的数据源名,算依据要用真名。""" + ctx = context_of(blueprint) + if (records := await records_context(session, blueprint, create=create_records)) is not None: + ctx["records"] = records + return ctx + + +def refreshed_joints(blueprint: Any, spec: dict[str, Any], *, ctx: dict[str, Any] | None = None) -> dict[str, Any]: + """卡片改过之后的关节状态:还算数的生成关节(依据没变)保留,别的标「待填」;确定性关节按卡片重新填。没选模板的为空。 + ctx 是实例化的上下文(instantiate_context),不给按 context_of。""" + from app.blueprints.instantiate import filled_from, instantiate + + if not (spec.get("template") or None): + return {} + ctx = ctx if ctx is not None else context_of(blueprint) + keep = filled_from(spec, blueprint.joints or {}, graph=ctx.get("graph"), records=ctx.get("records")) + return instantiate(spec, filled=keep, **ctx).joints + + +# ========================================================================== +# 交给前端的形状(typesBlueprint.Blueprint) +# ========================================================================== + + +def blueprint_issues_of(blueprint: Any) -> list[dict[str, Any]]: + """蓝图卡片上显示的问题:共享蓝图按发布的口径(缺项、待确认都列),个人蓝图按个人应用的口径;再加还没填的生成关节。 + 每条带白话(app/plain.with_plain)。""" + from app.blueprints.ops import blueprint_issues + from app.plain import with_plain + + spec = blueprint.spec or {} + issues = blueprint_issues(spec, for_="personal" if blueprint.scope == "personal" else "publish") + for joint_id, state in (blueprint.joints or {}).items(): + if isinstance(state, dict) and state.get("status") in ("pending", "refused"): + issues.append({"code": "tpl.joint_unfilled" if state["status"] == "pending" else "tpl.joint_refused", + "level": "error", "path": None, "joint": joint_id, + "message": state.get("note") or "这一项助手还没填上"}) + return [with_plain(i) for i in issues] + + +def blueprint_out(blueprint: Any, *, issues: bool = True) -> dict[str, Any]: + """一张蓝图交给前端的样子(frontend/src/typesBlueprint.ts 的 Blueprint)。关节只给状态,不给填的值(值在图上看)。""" + joints = {jid: {k: v for k, v in state.items() if k in ("status", "by", "note")} + for jid, state in (blueprint.joints or {}).items() if isinstance(state, dict)} + out = { + "id": blueprint.id, "name": blueprint.name, "owner": blueprint.owner, "scope": blueprint.scope, + "status": blueprint.status, "spec": blueprint.spec or {}, "template_id": blueprint.template_id, + "template_version": blueprint.template_version, "source": blueprint.source or {}, + "conversation_id": blueprint.conversation_id, "workflow_id": blueprint.workflow_id, "app_id": blueprint.app_id, + "last_trial_run_id": blueprint.last_trial_run_id, "graph_hash": blueprint.graph_hash, "joints": joints, + "copied_from": blueprint.copied_from, + "created_at": blueprint.created_at.isoformat() if blueprint.created_at else None, + "updated_at": blueprint.updated_at.isoformat() if blueprint.updated_at else None, + } + if issues: + out["issues"] = blueprint_issues_of(blueprint) + return out diff --git a/backend/app/blueprints/templates/__init__.py b/backend/app/blueprints/templates/__init__.py index 3e566cac..25751dd4 100644 --- a/backend/app/blueprints/templates/__init__.py +++ b/backend/app/blueprints/templates/__init__.py @@ -80,3 +80,5 @@ def check_registry() -> list[str]: """启动时核对:首批模板都登记了、关节类型都认得。交回问题清单(空 = 没问题)。""" problems = [f"模板「{t}」没有登记" for t in TEMPLATE_IDS if t not in _REGISTRY] return problems + +from app.blueprints.templates import approval, exception_handling, freeform, periodic_board, reconcile_writeback, records # noqa: E402,F401 diff --git a/backend/app/blueprints/templates/_common.py b/backend/app/blueprints/templates/_common.py new file mode 100644 index 00000000..c810f306 --- /dev/null +++ b/backend/app/blueprints/templates/_common.py @@ -0,0 +1,820 @@ +"""场景模板共用的零件(N3、§3.3–§3.4):画节点、按卡片填确定性关节、按库分组的取数、口径卡、应用骨架、定时任务。 + +每个模板模块只写自己的骨架长什么样,怎么从卡片换成节点配置都在这里,各模板说法一致(P5): +- 统计期:入口字段 period / period_start / period_end,定时任务的输入模板按「多久更新」卡片取(scheduler 的模板变量); +- 谁来做:人工节点只写岗位(派给谁、超时升级给谁),岗位绑到哪些人由应用的岗位绑定定(bindings),和样例⑩同一个做法; +- 看哪些数:按取数节点分组,同一组一条 SQL(生成关节 sql),口径卡每个数一个指标式(生成关节 metric_expr),复用已发布 + 口径卡的项落成 caliber_from; +- 应用骨架:apps/derive.py 的派生规则(_results、_entries、岗位、待办外观)加模板自己的排布。 + +模板登记(TemplateDef)之外每个模板另给几样(EXTRAS):一张完整的示例蓝图(测试和启动核对用)、选模板时的预置、 +给模型看的每组关节说明。 +""" +from __future__ import annotations + +import copy +import hashlib +import json +import re +from collections.abc import Callable +from dataclasses import dataclass, field +from typing import Any + +from app.blueprints.templates import Joint + +#: 实例化时交给模板的上下文(蓝图 id、工作流 id、定时任务 id、记录表、导入的图):放在 bp 的这个键下,模板读、不写回 +CONTEXT_KEY = "_context" +#: 生成关节没填时的占位。SQL 是一句注释(试运行和发布前由 tpl.joint_unfilled 挡住);指标式是空值(照常能过画布校验) +SQL_PLACEHOLDER = "-- 待填:助手还没写这条 SQL" +METRIC_PLACEHOLDER = "None" +#: 口径卡、成果、解析节点的固定 id +CALIBER = "caliber" +DONE = "done" +START = "start" + +# ========================================================================== +# 写给模型的文字(每组关节的说明) +# ========================================================================== + +SQL_BRIEF_HEAD_PROMPT = ("取数节点 {node}(工具 db_query__{source}):写一条只读 SQL(只能 SELECT,一条语句),结果{shape}。" + "{period}") +SQL_PERIOD_PROMPT = ("统计期用入口字段:从 '{{ input.period_start }}' 到 '{{ input.period_end }}'(日期,含两端," + "写在 SQL 里要带单引号)。") +SQL_ONE_ROW_PROMPT = "只出一行,每个要算的数一列(或者算它要用的基础量各一列),列名用英文小写和下划线" +SQL_ITEM_PROMPT = "- {label}(指标 id {id}{unit}):怎么算:{measure};表:{table};业务日期:{date};筛选:{filter};粒度:{grain}" +SQL_REUSED_PROMPT = "复用的已发布口径卡要这条 SQL 交出这几列(列名照抄,别改):{columns}" +METRIC_BRIEF_PROMPT = ("口径卡 {card} 每个数写一个指标式(关节 metric_<指标 id>):{metrics}。只能用 cell(nodes.{node}, 0, '列名') " + "取上面那条 SQL 第一行的格,再做加减乘除、round、abs、min、max、比较和 … if … else …;分母可能为 0 " + "时写成 … if 分母 else None。不能用别的函数,不能引用别的节点。") +METRIC_ITEM_PROMPT = "{id}({label}{unit})" +UNKNOWN_PROMPT = "未写" + + +# ========================================================================== +# 节点、连线、卡片上的值 +# ========================================================================== + + +def node(node_id: str, node_type: str, label: str, **config: Any) -> dict[str, Any]: + """一个节点(和 seed.py 的 _n 同一种写法)。""" + return {"id": node_id, "type": node_type, "position": {"x": 0, "y": 0}, + "data": {"label": label, "config": config}} + + +def edge(source: str, target: str, handle: str | None = None) -> dict[str, Any]: + out: dict[str, Any] = {"source": source, "target": target} + if handle: + out["sourceHandle"] = handle + return out + + +def value(item: Any) -> Any: + """卡片上一项的值({value, source, status} → value)。""" + return item.get("value") if isinstance(item, dict) else None + + +def context(bp: dict[str, Any]) -> dict[str, Any]: + ctx = bp.get(CONTEXT_KEY) + return ctx if isinstance(ctx, dict) else {} + + +def app_name(bp: dict[str, Any], fallback: str) -> str: + """应用和工作流的名字:实例化时给的名字,没给就用目的的前一段。""" + name = str(context(bp).get("name") or "").strip() + if name: + return name[:200] + purpose = str(value(bp.get("purpose")) or "").strip() + return (re.split(r"[,。;,;\n]", purpose)[0][:40] if purpose else "") or fallback + + +def safe_id(text: str) -> str: + """节点 id 用的一段:小写字母、数字、下划线;全是中文的名字换不出来时为空串,由调用方编号。""" + return re.sub(r"_+", "_", re.sub(r"[^a-z0-9_]", "_", text.lower())).strip("_")[:24] + + +# ========================================================================== +# 统计期与定时任务 +# ========================================================================== + +#: 统计哪一期 → (说法, 期名、第一天、最后一天各取哪个定时任务模板变量,scheduler/service.VARIABLES) +PERIODS: dict[str, tuple[str, str, str, str]] = { + "today": ("今天", "today", "today", "today"), + "yesterday": ("昨天", "yesterday", "yesterday", "yesterday"), + "this_iso_week": ("本周", "this_week", "this_week_start", "today"), + "last_iso_week": ("上周", "last_week", "last_week_start", "last_week_end"), + "this_month": ("本月", "this_month", "this_month_start", "today"), + "last_month": ("上月", "last_month", "last_month_start", "last_month_end"), +} +#: 没写统计哪一期时按更新频率取:每天看昨天,每周看上周,每月看上月 +DEFAULT_PERIOD = {"daily": "yesterday", "weekly": "last_iso_week", "monthly": "last_month"} +PERIOD_FIELDS = ("period", "period_start", "period_end") + + +def period_fields() -> list[dict[str, Any]]: + """统计期的入口字段。第一天、最后一天都含在内(SQL 说明里照这个写)。""" + return [ + {"name": "period", "label": "统计期", "description": "这一期叫什么,例如 2026-W41、2026-09"}, + {"name": "period_start", "label": "第一天", "type": "string", "format": "date", "required": True, + "description": "统计期的第一天(含)"}, + {"name": "period_end", "label": "最后一天", "type": "string", "format": "date", "required": True, + "description": "统计期的最后一天(含)"}, + ] + + +def period_of(cadence: dict[str, Any] | None) -> str: + if not isinstance(cadence, dict): + return "yesterday" + return cadence.get("period") or DEFAULT_PERIOD.get(cadence.get("preset") or "", "yesterday") + + +def cron_of(cadence: dict[str, Any]) -> str: + """更新频率 → 五字段 cron。周几按卡片的 1–7(周一到周日),cron 里周日写 0。""" + hour, minute = (int(x) for x in str(cadence["time"]).split(":")) + if cadence["preset"] == "weekly": + return f"{minute} {hour} * * {int(cadence['weekday']) % 7}" + if cadence["preset"] == "monthly": + return f"{minute} {hour} {int(cadence['day'])} * *" + return f"{minute} {hour} * * *" + + +def period_template(cadence: dict[str, Any] | None) -> dict[str, str]: + """定时任务的输入模板:统计期三个字段各取哪个变量。""" + _, name, start, end = PERIODS[period_of(cadence)] + return {"period": f"{{{{ schedule.{name} }}}}", "period_start": f"{{{{ schedule.{start} }}}}", + "period_end": f"{{{{ schedule.{end} }}}}"} + + +def schedule_of(bp: dict[str, Any], name: str, *, inputs: dict[str, str] | None = None) -> dict[str, Any] | None: + """定时任务参数(api/schedules 建任务的字段):正式运行、先停用(发布单在应用发布后才启用,N5)。没定更新频率为 None。""" + cadence = value(bp.get("cadence")) + if not isinstance(cadence, dict): + return None + return {"name": f"{name}(定时)", "cron": cron_of(cadence), "timezone": cadence["tz"], "run_class": "formal", + "input_template": period_template(cadence) if inputs is None else inputs, "enabled": False} + + +# ========================================================================== +# 填什么:入口字段与表单 +# ========================================================================== + +#: 「填什么」的字段属性里能带进入口节点字段的键(engine/nodes/io.py、apps/forms.input_schema 认的那几样) +_INPUT_KEYS = ("type", "description", "default", "enum", "format", "minimum", "maximum", "x-widget", "x-enum-labels") + + +def form_fields(bp: dict[str, Any], *, required: bool = True) -> list[dict[str, Any]]: + """「填什么」→ 入口节点的字段。required=False 时都不在入口节点上必填(同一张图另有不填表单的路径,必填由应用的入口 + 表单把关)。""" + out: list[dict[str, Any]] = [] + for f in bp.get("fields") or []: + prop = value(f.get("spec")) or {} + out.append({"name": f["name"], "label": str(prop.get("title") or f["name"]), + **{k: copy.deepcopy(prop[k]) for k in _INPUT_KEYS if k in prop}, + **({"required": True} if required and prop.get("required") else {})}) + return out + + +def entry_form(bp: dict[str, Any], title: str = "") -> dict[str, Any]: + """入口表单(agentlab.form/1):直接用「填什么」卡片上的表单属性,选项文字、控件这些外观也带上。""" + from app.apps.spec import FORM_FORMAT + + props: dict[str, Any] = {} + required: list[str] = [] + for f in bp.get("fields") or []: + prop = dict(value(f.get("spec")) or {"type": "string"}) + if prop.pop("required", False): + required.append(f["name"]) + prop.setdefault("title", f["name"]) + props[f["name"]] = prop + return {"format": FORM_FORMAT, "type": "object", **({"title": title} if title else {}), "properties": props, + "required": required, "x-order": list(props)} + + +def field_ref(name: str) -> str: + return f"{{{{ input.{name} }}}}" + + +def fields_message(bp: dict[str, Any]) -> str: + """待办里列出表单内容:每个字段一行「名称:值」。""" + lines = [] + for f in bp.get("fields") or []: + title = (value(f.get("spec")) or {}).get("title") or f["name"] + lines.append(f"{title}:{field_ref(f['name'])}") + return "\n".join(lines) + + +# ========================================================================== +# 谁来做:人工节点的确定性关节 +# ========================================================================== + + +def slot_of(step: dict[str, Any]) -> str: + """这一步派给哪个岗位:处理人就是一个岗位时用它的名字(同一个岗位可以出现在几步里),否则用步骤 id。""" + who = value(step.get("who")) or [] + if len(who) == 1 and who[0].get("kind") == "slot": + return str(who[0]["name"]) + return str(step["id"]) + + +def escalate_slot(step: dict[str, Any]) -> str | None: + timeout = value(step.get("on_timeout")) + if not isinstance(timeout, dict) or timeout.get("action") != "escalate": + return None + to = timeout.get("to") or [] + if len(to) == 1 and to[0].get("kind") == "slot": + return str(to[0]["name"]) + return f"{step['id']}_up" + + +def assignee_of(step: dict[str, Any]) -> dict[str, Any]: + who = value(step.get("who")) or [] + if len(who) == 1 and who[0].get("kind") == "initiator": + return {"kind": "initiator"} + return {"kind": "slot", "slot": slot_of(step)} + + +def policy_of(step: dict[str, Any]) -> Any: + policy = value(step.get("policy")) or {"kind": "any"} + if policy["kind"] == "quorum": + return {"quorum": int(policy["m"])} + return policy["kind"] + + +def timeout_of(step: dict[str, Any]) -> dict[str, Any] | None: + timeout = value(step.get("on_timeout")) + if not isinstance(timeout, dict): + return None + out: dict[str, Any] = {"action": timeout["action"]} + if timeout["action"] == "escalate": + out["to_slot"] = escalate_slot(step) + if timeout.get("every"): + out["every"] = timeout["every"] + return out + + +def human(step: dict[str, Any], index: int, node_id: str, *, title: str, message: str, mode: str = "approve", + form: dict[str, Any] | None = None, **extra: Any) -> tuple[dict[str, Any], list[Joint]]: + """「谁来做」的一步 → 人工节点和它的确定性关节(派给谁、几个人同意、时限、超时怎么办)。""" + config: dict[str, Any] = {"mode": mode, "title": title, "message": message, "assignee": assignee_of(step)} + policy = policy_of(step) + if mode == "approve" or policy == "any": + config["policy"] = policy + if due := value(step.get("due")): + config["due"] = due + if timeout := timeout_of(step): + config["on_timeout"] = timeout + if form is not None: + config["form"] = form + config.update(extra) + label = str(value(step.get("label")) or step["id"]) + base = f"/people/{index}" + joints = [Joint(id=f"{node_id}.assignee", kind="assignee", node_id=node_id, field="/assignee", + from_card=f"{base}/who", label=f"{label}:派给谁"), + Joint(id=f"{node_id}.policy", kind="policy", node_id=node_id, field="/policy", + from_card=f"{base}/policy", label=f"{label}:几个人同意算通过")] + if "due" in config: + joints.append(Joint(id=f"{node_id}.due", kind="due", node_id=node_id, field="/due", from_card=f"{base}/due", + label=f"{label}:时限")) + if "on_timeout" in config: + joints.append(Joint(id=f"{node_id}.on_timeout", kind="on_timeout", node_id=node_id, field="/on_timeout", + from_card=f"{base}/on_timeout", label=f"{label}:超时怎么办")) + return node(node_id, "human", label, **config), joints + + +def threshold_condition(threshold: dict[str, Any]) -> str: + """金额线 → 分支条件「input.字段 比较 常量」(只有比较,没有算术,§3.4 threshold)。""" + return f"input.{threshold['field']} {threshold['op']} {json.dumps(threshold['value'], ensure_ascii=False)}" + + +def title_of(bp: dict[str, Any], label: str) -> str: + """待办标题带上表单的前两个字段:同一个人的两笔申请,待办列表里一眼分得开(同样例⑩)。""" + refs = [field_ref(f["name"]) for f in (bp.get("fields") or [])[:2]] + return f"{label}:{' · '.join(refs)}" if refs else label + + +@dataclass +class Chain: + """一串审批:入口连到 head,每一步通过去下一步(写了条件的先过分支,不满足直接跳过),驳回都到 rejected。""" + + head: str + nodes: list[dict[str, Any]] + edges: list[dict[str, Any]] + joints: list[Joint] + #: 每一步的意见(成果字段) + notes: list[dict[str, Any]] + + +def approval_chain(bp: dict[str, Any], *, after: str, rejected: str) -> Chain: + """「谁来做」→ 一串人工节点。从后往前排:每一步通过之后去哪(下一步的分支或人工节点,最后是 after)。""" + steps = bp.get("people") or [] + parts: list[tuple[list[dict[str, Any]], list[dict[str, Any]], list[Joint]]] = [] + notes: list[dict[str, Any]] = [] + for i in range(len(steps) - 1, -1, -1): + step = steps[i] + review_id = f"review_{step['id']}" + label = str(value(step.get("label")) or step["id"]) + review, review_joints = human(step, i, review_id, title=title_of(bp, label), message=fields_message(bp)) + step_nodes = [review] + step_edges = [edge(review_id, after, "approved"), edge(review_id, rejected, "rejected")] + step_joints = list(review_joints) + head = review_id + threshold = value(step.get("threshold")) + if isinstance(threshold, dict): + gate_id = f"gate_{step['id']}" + step_nodes.insert(0, node(gate_id, "branch", f"是否要{label}", mode="expression", cases=[ + {"key": "hit", "condition": threshold_condition(threshold), "label": f"要{label}"}])) + step_edges = [edge(gate_id, review_id, "hit"), edge(gate_id, after, "default"), *step_edges] + step_joints.append(Joint(id=f"{gate_id}.threshold", kind="threshold", node_id=gate_id, + field="/cases/0/condition", from_card=f"/people/{i}/threshold", + label=f"{label}:走这一步的条件")) + head = gate_id + parts.insert(0, (step_nodes, step_edges, step_joints)) + notes.insert(0, {"name": f"{label}意见", "value": f"{{{{ nodes.{review_id}.note }}}}"}) + after = head + return Chain(head=after, nodes=[n for p in parts for n in p[0]], edges=[e for p in parts for e in p[1]], + joints=[j for p in parts for j in p[2]], notes=notes) + + +def bindings_of(bp: dict[str, Any]) -> dict[str, Any]: + """岗位绑定(应用的 draft_bindings 形状 {"slots": {岗位: [{kind: user|group, name}]}}):处理人、超时升级给的人 + 写的是具体的人或组的,按这一步的岗位绑上;写的是岗位的,岗位绑到谁要在应用里定(发布单的「你来定」)。""" + slots: dict[str, list[dict[str, str]]] = {} + + def bind(slot: str | None, principals: list[dict[str, Any]]) -> None: + if not slot: + return + people = [{"kind": p["kind"], "name": p["name"]} for p in principals if p.get("kind") in ("user", "group")] + if people: + have = slots.setdefault(slot, []) + have += [p for p in people if p not in have] + + for step in bp.get("people") or []: + bind(slot_of(step), value(step.get("who")) or []) + timeout = value(step.get("on_timeout")) + if isinstance(timeout, dict): + bind(escalate_slot(step), timeout.get("to") or []) + return {"slots": slots} + + +def slot_labels(bp: dict[str, Any]) -> dict[str, str]: + """岗位 → 给人看的名字:步骤的名字,升级岗位写「……超时升级」。""" + out: dict[str, str] = {} + for step in bp.get("people") or []: + label = str(value(step.get("label")) or step["id"]) + out.setdefault(slot_of(step), slot_of(step) if slot_of(step) != step["id"] else label) + if up := escalate_slot(step): + out.setdefault(up, up if up != f"{step['id']}_up" else f"{label}超时升级") + return out + + +# ========================================================================== +# 写回哪里:调用工具节点的确定性关节 +# ========================================================================== + + +def write_args(mapping: dict[str, Any], *, metrics: dict[str, str] | None = None, + rows: str | None = None) -> tuple[dict[str, Any], list[str]]: + """字段对应 → 调用工具节点的 args(模板写法)。metrics:指标 id → 取值链;rows:核对出来的行的取值链。 + 交回 (args, 对不上的取值)。""" + args: dict[str, Any] = {} + bad: list[str] = [] + for param, source in (mapping or {}).items(): + if isinstance(source, bool) or isinstance(source, (int, float)): + args[param] = source + elif source == "rows" and rows: + args[param] = f"{{{{ {rows} | compact }}}}" + elif isinstance(source, str) and source.startswith("form."): + args[param] = field_ref(source[len("form."):]) + elif isinstance(source, str) and source.startswith("metric.") and source[len("metric."):] in (metrics or {}): + args[param] = f"{{{{ {(metrics or {})[source[len('metric.'):]]} }}}}" + elif isinstance(source, str) and len(source) >= 2 and source[0] == source[-1] == "'": + args[param] = source[1:-1] + else: + bad.append(f"{param}:{source}") + return args, bad + + +def write_node(bp: dict[str, Any], node_id: str, *, confirm_slot: str | None, metrics: dict[str, str] | None = None, + rows: str | None = None, label: str = "写回") -> tuple[dict[str, Any], list[Joint], list[str]]: + """「写回哪里」→ 调用工具节点:工具是目标能力,参数按字段对应;要人确认时审批写「每次都审批」并派给 confirm_slot, + 不要确认时写「全部自动放行」(能力登记里还要允许无人值守写入才真不问人,nodes/tools._run_write)。""" + wb = bp.get("writeback") or {} + capability = value(wb.get("capability")) or "" + args, bad = write_args(value(wb.get("mapping")) or {}, metrics=metrics, rows=rows) + config: dict[str, Any] = {"tool": capability, "args": args} + if value(wb.get("confirm")) is False: + config["approval"] = "never" + else: + config["approval"] = "always" + if confirm_slot: + config["assignee"] = {"kind": "slot", "slot": confirm_slot} + joints = [Joint(id=f"{node_id}.capability", kind="capability", node_id=node_id, field="/tool", + from_card="/writeback/capability", label=f"{label}:目标能力"), + Joint(id=f"{node_id}.args", kind="capability", node_id=node_id, field="/args", + from_card="/writeback/mapping", label=f"{label}:字段对应")] + return node(node_id, "tool", label, **config), joints, bad + + +def write_lookup(capability: str) -> bool: + """写入能力有没有登记查询(结果未知时按幂等键查实际结果):没有的要绑核实岗位(apps/derive.RECONCILER)。""" + from app.capabilities.registry import cached_view + + view = cached_view(capability) or {} + return bool(view.get("lookup")) + + +# ========================================================================== +# 看哪些数:按取数节点分组 +# ========================================================================== + + +@dataclass +class Group: + """一个取数节点和它要算的数。同一组的 SQL 和指标式一起交给模型填(生成关节的 group),不同组并行填。""" + + node_id: str + source: str + #: 本地算的数据项(口径卡里各一个指标) + items: list[dict[str, Any]] = field(default_factory=list) + #: 复用已发布口径卡的数据项:它们读这个取数节点(reuse.inputs) + reused: list[dict[str, Any]] = field(default_factory=list) + #: 复用的口径卡要这条 SQL 交出的列 + columns: list[str] = field(default_factory=list) + + +def data_groups(bp: dict[str, Any], *, source_map: dict[str, str] | None = None, + prefix: str = "fetch") -> tuple[list[Group], list[dict[str, Any]]]: + """「看哪些数」→ 取数分组:同一个库一条 SQL。复用的口径卡读的是原工作流里某个取数节点(cell(nodes.X, …)),新图里 + 那个库的取数节点就叫 X、交出同样的列,复用才算得出来。交回 (分组, 问题)。source_map 把模板自己的占位库名换成真名 + (填报登记的记录表)。""" + from app.tools.datasource import QUERY_PREFIX + + groups: dict[str, Group] = {} + by_source: dict[str, str] = {} + problems: list[dict[str, Any]] = [] + source_map = source_map or {} + + def problem(code: str, i: int, message: str) -> None: + problems.append({"code": code, "level": "error", "path": f"/data/{i}", "message": message}) + + for i, item in enumerate(bp.get("data") or []): + reuse = item.get("reuse") + if not reuse: + continue + label = value(item.get("label")) or item["id"] + inputs = reuse.get("inputs") + if not inputs: + problem("bp.data_unmapped", i, f"「{label}」复用的口径卡还没核对过它读哪些列:请重新从口径卡里选一次") + continue + for inp in inputs: + tool = str(inp.get("tool") or "") + if not tool.startswith(QUERY_PREFIX): + problem("bp.template_mismatch", i, f"「{label}」复用的口径卡不是从数据库取数的,模板里接不上:请按表重新对") + break + source, node_id = tool[len(QUERY_PREFIX):], str(inp["node"]) + if by_source.get(source, node_id) != node_id or (node_id in groups and groups[node_id].source != source): + problem("bp.template_mismatch", i, f"「{label}」复用的口径卡和别的口径卡取数的方式对不上:请只复用其中一张," + "其余按表重新对") + break + by_source[source] = node_id + group = groups.setdefault(node_id, Group(node_id=node_id, source=source)) + if item not in group.reused: + group.reused.append(item) + group.columns += [str(c) for c in inp.get("columns") or [] if str(c) not in group.columns] + used = set(groups) + for item in bp.get("data") or []: + table = value(item.get("table")) + if item.get("reuse") or not isinstance(table, dict): + continue + source = source_map.get(table["source"], table["source"]) + node_id = by_source.get(source) + if node_id is None: + base = safe_id(source) + node_id = f"{prefix}_{base}" if base else f"{prefix}_{len(used) + 1}" + while node_id in used: + node_id = f"{node_id}_{len(used) + 1}" + used.add(node_id) + by_source[source] = node_id + groups.setdefault(node_id, Group(node_id=node_id, source=source)).items.append(item) + return list(groups.values()), problems + + +def fetch_nodes(groups: list[Group]) -> tuple[list[dict[str, Any]], list[Joint]]: + """每组一个取数节点(调用工具 db_query__库名),SQL 是生成关节。""" + nodes: list[dict[str, Any]] = [] + joints: list[Joint] = [] + for g in groups: + nodes.append(node(g.node_id, "tool", f"取数({g.source})", tool=f"db_query__{g.source}", + args={"sql": SQL_PLACEHOLDER})) + joints.append(Joint(id=f"sql_{g.node_id}", kind="sql", node_id=g.node_id, field="/args/sql", group=g.node_id, + label=f"取数的 SQL({g.source})")) + return nodes, joints + + +def caliber_node(bp: dict[str, Any], groups: list[Group], name: str) -> tuple[dict[str, Any] | None, list[Joint]]: + """本地算的数都进一张口径卡,每个数一个指标式(生成关节)。缺输入记成空值,交给出具契约按必需指标判档。""" + metrics: list[dict[str, Any]] = [] + joints: list[Joint] = [] + for g in groups: + for item in g.items: + metric: dict[str, Any] = {"id": item["id"], "name": str(value(item.get("label")) or item["id"]), + "expression": METRIC_PLACEHOLDER} + if unit := value(item.get("unit")): + metric["unit"] = unit + joints.append(Joint(id=f"metric_{item['id']}", kind="metric_expr", node_id=CALIBER, + field=f"/metrics/{len(metrics)}/expression", group=g.node_id, + label=f"指标式:{metric['name']}")) + metrics.append(metric) + if not metrics: + return None, [] + return node(CALIBER, "metrics", "口径卡", caliber=f"{name}口径", caliber_version="v1", on_missing="null", + metrics=metrics), joints + + +def reuse_nodes(groups: list[Group]) -> list[tuple[dict[str, Any], dict[str, Any], str]]: + """复用已发布口径卡的项各一张卡(caliber_from 固定到那一版),交回 (节点, 数据项, 读的取数节点)。""" + out = [] + for g in groups: + for item in g.reused: + reuse = item["reuse"] + out.append((node(f"reuse_{item['id']}", "metrics", f"复用口径:{value(item.get('label')) or item['id']}", + caliber_from={"workflow_id": reuse["workflow_id"], "workflow_version": reuse["version"], + "node_id": reuse["node_id"]}), item, g.node_id)) + return out + + +def metric_paths(caliber: dict[str, Any] | None) -> dict[str, str]: + """口径卡里每个指标的取值链(成果字段、写回参数用):指标 id → nodes.caliber.metrics[i].value。""" + if caliber is None: + return {} + return {m["id"]: f"nodes.{CALIBER}.metrics[{i}].value" + for i, m in enumerate(caliber["data"]["config"].get("metrics") or [])} + + +def board_output(bp: dict[str, Any], caliber: dict[str, Any] | None, + reused: list[tuple[dict[str, Any], dict[str, Any], str]], + node_id: str = DONE, label: str = "出具") -> tuple[dict[str, Any], list[Joint]]: + """按指标出具的成果(engine/issuance.metrics_only、governance.board_only):契约只写「指标来自」和必需指标,成果字段 + 每个本地指标一项(值就是指标值,回指得上)。复用的指标在应用里按指标块看,不进成果字段。""" + paths = metric_paths(caliber) + fields = [] + for m in (caliber["data"]["config"]["metrics"] if caliber else []): + unit = f"({m['unit']})" if m.get("unit") else "" + fields.append({"name": f"{m['name']}{unit}", "value": f"{{{{ {paths[m['id']]} }}}}"}) + sources = ([CALIBER] if caliber else []) + [n["id"] for n, _, _ in reused] + required = [m["id"] for m in (caliber["data"]["config"]["metrics"] if caliber else [])] + \ + [item["reuse"]["metric_id"] for _, item, _ in reused] + contract = {"metrics_from": sources, "required": required, "strict": True} + joints = [Joint(id=f"{node_id}.contract", kind="contract", node_id=node_id, field="/contract", from_card="/data", + label="出具契约:必需指标")] + return node(node_id, "output", label, fields=fields, contract=contract), joints + + +def data_briefs(bp: dict[str, Any], groups: list[Group], *, shape: str = SQL_ONE_ROW_PROMPT, + period: bool = True) -> dict[str, str]: + """每组关节给模型的说明:要算哪些数、用哪张表、业务日期、筛选,口径卡的指标式怎么写。""" + out: dict[str, str] = {} + for g in groups: + lines = [SQL_BRIEF_HEAD_PROMPT.format(node=g.node_id, source=g.source, shape=shape, + period=SQL_PERIOD_PROMPT if period else "")] + for item in g.items: + lines.append(item_brief(item)) + if g.columns: + lines.append(SQL_REUSED_PROMPT.format(columns="、".join(g.columns))) + if g.items: + metrics = [METRIC_ITEM_PROMPT.format(id=item["id"], label=value(item.get("label")) or item["id"], + unit=f",单位 {value(item.get('unit'))}" if value(item.get("unit")) else "") + for item in g.items] + lines.append(METRIC_BRIEF_PROMPT.format(card=CALIBER, node=g.node_id, metrics="、".join(metrics))) + out[g.node_id] = "\n".join(lines) + return out + + +def item_brief(item: dict[str, Any]) -> str: + table = value(item.get("table")) or {} + date = value(item.get("date")) or {} + unit = value(item.get("unit")) + + def text(key: str) -> str: + return str(value(item.get(key)) or UNKNOWN_PROMPT) + + return SQL_ITEM_PROMPT.format( + label=value(item.get("label")) or item["id"], id=item["id"], unit=f",单位 {unit}" if unit else "", + measure=text("measure"), table=f"{table.get('source')}.{table.get('table')}" if table else UNKNOWN_PROMPT, + date=(f"{date.get('column')}" + (f"({date['rule']})" if date.get("rule") else "")) if date else UNKNOWN_PROMPT, + filter=text("filter"), grain=text("grain")) + + +def basis_of(brief: str, template_id: str, version: int) -> str: + """一组生成关节的依据的指纹:说明变了(卡片改了),之前填的就不算数了,要重新填。""" + return hashlib.sha256(f"{template_id}@{version}\n{brief}".encode()).hexdigest()[:16] + + +# ========================================================================== +# 应用骨架 +# ========================================================================== + + +def app_base(bp: dict[str, Any], graph: dict[str, Any], *, use: str, name: str, description: str = "", + writes: dict[str, str] | None = None) -> dict[str, Any]: + """按 apps/derive.py 的派生规则出应用骨架的公共部分:钉住项(还没发布,版本为空)、岗位、待办外观、核实岗位。 + writes 是写外部系统的调用工具节点 → 能力名(模板知道哪几个是写入,不用查库)。页面、视图、入口由各模板排。""" + from app.apps.derive import PIN, RECONCILER + from app.apps.spec import APP_FORMAT + from app.apps.tree import node_map, slot_refs + from app.core.artifact_store import graph_hash + + ctx = context(bp) + pin: dict[str, Any] = {"alias": PIN, "version": None, "graph_hash": graph_hash(graph), "level": None, "use": use} + if ctx.get("workflow_id"): + pin["workflow_id"] = ctx["workflow_id"] + else: + # 还没有工作流(个人应用、还没保存的草稿):固定到蓝图上,图在蓝图里 + pin["blueprint"] = ctx.get("blueprint_id") or "draft" + spec: dict[str, Any] = { + "format": APP_FORMAT, "name": name, "description": description, "icon": "app", "pins": [pin], "slots": {}, + "entries": [], "forms": {}, "task_ui": {}, "views": {}, "pages": [], "hooks": [], "notify": [], + } + labels = slot_labels(bp) + for ref in slot_refs(graph, writes or {}): + spec["slots"].setdefault(ref["slot"], {"label": labels.get(ref["slot"], ref["slot"])}) + for nid, n in node_map(graph).items(): + if n["type"] == "human": + spec["task_ui"][nid] = {"title": n["title"]} + if writes and not all(write_lookup(cap) for cap in writes.values()): + spec["slots"][RECONCILER] = {"label": "动作核实"} + return spec + + +def instance_page(graph: dict[str, Any], writes: dict[str, str] | None = None, *, + results: bool = True) -> dict[str, Any]: + """实例页(同 apps/derive.py):概况、进度、各人工节点的待办表单和会签进度、写入动作的状态、这一次的结果。""" + from app.apps.derive import INSTANCE_VIEW, _results, _safe + from app.apps.tree import node_map + + nodes = node_map(graph) + humans = [nid for nid, n in nodes.items() if n["type"] == "human"] + return {"id": "instance", "title": "实例", "body": [ + {"id": "inst_header", "type": "instance_header"}, + {"id": "inst_timeline", "type": "instance_timeline"}, + *[c for nid in humans for c in ( + {"id": f"task_{_safe(nid)}", "type": "task_form", "bind": {"task": nid}}, + {"id": f"signoffs_{_safe(nid)}", "type": "signoffs", "bind": {"task": nid}})], + *[{"id": f"action_{_safe(nid)}", "type": "action_status", "props": {"label": nodes[nid]["title"][:200]}, + "bind": {"action": nid}} for nid in (writes or {})], + *(_results(nodes, INSTANCE_VIEW, "inst") if results else []), + ]} + + +def series_section(graph: dict[str, Any], view: str, prefix: str) -> list[dict[str, Any]]: + """趋势:口径卡每个本地指标一条(同一来源最近几次封存运行的值,apps/resolve._series)。""" + from app.apps.derive import _safe + from app.apps.tree import node_map + + card = node_map(graph).get(CALIBER) + metrics = [m for m in (card or {}).get("config", {}).get("metrics") or [] if isinstance(m, dict) and m.get("id")] + if not metrics: + return [] + return [{"id": f"{prefix}_trend", "type": "section", "props": {"title": "趋势"}, "children": [ + {"id": f"{prefix}_series_{_safe(str(m['id']))}", "type": "series", + "props": {"label": str(m.get("name") or m["id"])[:200], "chart": "line"}, + "bind": {"view": view, "series": f"{CALIBER}.{m['id']}"}} for m in metrics]}] + + +def reused_section(bp: dict[str, Any], graph: dict[str, Any], view: str, prefix: str) -> list[dict[str, Any]]: + """复用口径卡的指标:派生规则只认本地写了指标的口径卡,复用的那几个按数据项各放一个指标块。""" + from app.apps.derive import _safe + from app.apps.tree import node_map + + nodes = node_map(graph) + blocks = [] + for item in bp.get("data") or []: + reuse = item.get("reuse") + if reuse and f"reuse_{item['id']}" in nodes: + blocks.append({"id": f"{prefix}_reuse_{_safe(item['id'])}", "type": "metric", + "props": {"label": str(value(item.get("label")) or reuse["metric_id"])[:200]}, + "bind": {"view": view, "metric": f"reuse_{item['id']}.{reuse['metric_id']}"}}) + if not blocks: + return [] + return [{"id": f"{prefix}_reused", "type": "section", "props": {"title": "复用的口径"}, + "children": [{"id": f"{prefix}_reused_cols", "type": "columns", "props": {"count": min(len(blocks), 4)}, + "children": blocks}]}] + + +def latest_view(ctx: dict[str, Any]) -> dict[str, Any]: + """看板首页的视图:最近封存的正式运行,有定时任务就只看它出的数(派生规则同 apps/derive.py)。""" + from app.apps.derive import PIN + + schedule = ctx.get("schedule_id") + return {"source": {"kind": "latest_sealed", "pin": PIN, "from": f"schedule:{schedule}" if schedule else "formal"}} + + +def entry_and_pages(spec: dict[str, Any], bp: dict[str, Any], graph: dict[str, Any], *, label: str, + writes: dict[str, str] | None = None, home_extra: list[dict[str, Any]] | None = None, + entry_map: dict[str, str] | None = None) -> None: + """流程类应用(同 apps/derive.py 的流程规则):入口表单就是「填什么」,首页放发起按钮、我发起的、派给我的待办, + 每件事的结果在它自己的实例页看。entry_map 另加的入口映射(常量写 'x')。""" + from app.apps.derive import ENTRY, INSTANCE_VIEW, PIN, _entries + + spec["forms"][ENTRY] = entry_form(bp) + names = list(spec["forms"][ENTRY]["properties"]) + first = next((n for n in names if n in spec["forms"][ENTRY]["required"]), names[0] if names else None) + spec["entries"].append({ + "id": ENTRY, "label": label, "pin": PIN, "form": {"$ref": f"#/forms/{ENTRY}"}, + "map": {**{n: f"form.{n}" for n in names}, **(entry_map or {})}, + **({"instance_title": {"pattern": f"{spec['name']}·{{{first}}}", "fields": [first]}} + if first and re.fullmatch(r"[A-Za-z0-9_㐀-鿿]+", first) else {}), + }) + spec["views"][INSTANCE_VIEW] = {"source": {"kind": "instance"}} + spec["pages"] = [ + {"id": "home", "title": spec["name"], "body": [ + *(home_extra or []), *_entries(spec), + {"id": "my_tasks", "type": "task_list", "props": {"scope": "mine"}}]}, + instance_page(graph, writes), + ] + + +def finish_app(spec: dict[str, Any]) -> dict[str, Any]: + """形状对不上是模板的错,不是用户的:这里直接报出来(同 apps/derive.py)。""" + from app.apps.spec import parse_spec + + return parse_spec(spec).model_dump(mode="json", by_alias=True) + + +# ========================================================================== +# 模板登记之外的几样(示例蓝图、预置、每组关节的说明) +# ========================================================================== + + +@dataclass +class Extras: + #: 一张完整的示例蓝图(测试和启动核对用):实例化、生成关节都填上后要能通过画布校验和发布前检查 + example: Callable[[], dict[str, Any]] + #: 示例蓝图的生成关节怎么填(测试用):{关节 id: 值} + example_fill: Callable[[], dict[str, Any]] + #: 选模板时预置还没填的卡片 + prefill: Callable[[dict[str, Any]], None] | None = None + #: 每组生成关节给模型看的说明:{group: 说明} + briefs: Callable[[dict[str, Any]], dict[str, str]] | None = None + #: 自由形:图是导入的(实例化时从上下文拿),模板不出骨架 + imports_graph: bool = False + #: 卡片内容超出模板能力的地方(bp.template_mismatch 等):[{code, level, path, message}] + problems: Callable[[dict[str, Any]], list[dict[str, Any]]] | None = None + + +EXTRAS: dict[str, Extras] = {} + + +def extend(template_id: str, extras: Extras) -> None: + if template_id in EXTRAS: + raise ValueError(f"模板「{template_id}」的示例和预置重复登记") + EXTRAS[template_id] = extras + + +def user_item(v: Any) -> dict[str, Any]: + """用户填过、确认过的一项(示例蓝图用);没填的记「缺」。""" + return {"value": v, "source": "user", "status": "confirmed" if v is not None else "missing", "why": None} + + +def template_item(v: Any) -> dict[str, Any]: + """模板默认的一项:来源记「模板默认」,状态「待确认」(发布前要人看过,P2)。""" + return {"value": v, "source": "template", "status": "proposed" if v is not None else "missing", "why": None} + + +def template_problems(template_id: str, spec: dict[str, Any]) -> list[dict[str, Any]]: + """模板自己认的问题:卡片内容超出模板能力(只能从一个库查、复用的口径卡接不上……)。""" + extras = EXTRAS.get(template_id) + if extras is None or extras.problems is None: + return [] + return extras.problems(spec) + + +def mismatch(path: str, message: str) -> dict[str, Any]: + return {"code": "bp.template_mismatch", "level": "error", "path": path, "message": message} + + +def prefill(template_id: str, spec: dict[str, Any]) -> None: + """选模板时按模板预置还没填的卡片(原地改)。已经写了的不动。""" + extras = EXTRAS.get(template_id) + if extras is not None and extras.prefill is not None: + extras.prefill(spec) + + +def default_cadence(preset: str = "weekly") -> dict[str, Any]: + out: dict[str, Any] = {"preset": preset, "time": "09:00", "tz": "Asia/Shanghai", "period": DEFAULT_PERIOD[preset]} + if preset == "weekly": + out["weekday"] = 1 + if preset == "monthly": + out["day"] = 1 + return out + + +def fill_cadence(spec: dict[str, Any], preset: str = "weekly") -> None: + if value(spec.get("cadence")) is None: + spec["cadence"] = template_item(default_cadence(preset)) + + +def step(step_id: str, label: str, *, policy: str = "any", due: str | None = "P2D") -> dict[str, Any]: + """预置的一步:处理人留空(要人填),几个人同意、时限按模板默认。""" + return {"id": step_id, "label": template_item(label), "who": template_item(None), + "policy": template_item({"kind": policy}), "due": template_item(due), "on_timeout": template_item(None), + "threshold": template_item(None)} diff --git a/backend/app/blueprints/templates/approval.py b/backend/app/blueprints/templates/approval.py new file mode 100644 index 00000000..3b0b9816 --- /dev/null +++ b/backend/app/blueprints/templates/approval.py @@ -0,0 +1,113 @@ +"""审批流程 approval(§3.3):入口(表单)→ [按金额线分支] → 人工(一级或多级)→ [写回] → 已通过 / 已退回。 + +没有生成关节,全部按卡片确定性地填: +- 表单(填什么)→ 入口节点的字段; +- 每一步(谁来做)→ 一个人工节点:派给谁(岗位)、几个人同意、时限、超时怎么办;写了条件的那一步前面加一个分支, + 条件只许「字段 比较 常量」,不满足的直接跳到下一步; +- 写回(可选)→ 调用工具节点:目标能力、字段对应,要人确认时派给最后一步的岗位。 + +任何一步驳回都到「已退回」。不能做成个人应用:要有人审批。 +""" +from __future__ import annotations + +from typing import Any + +from app.blueprints.templates import Joint, TemplateDef, register +from app.blueprints.templates import _common as c + +ID = "approval" +VERSION = 1 +APPROVED = "approved" +REJECTED = "rejected" +WRITE = "writeback" + + +def skeleton(bp: dict[str, Any]) -> tuple[dict[str, Any], list[Joint]]: + nodes = [c.node(c.START, "input", "发起", fields=c.form_fields(bp))] + joints = [Joint(id="start.fields", kind="fields", node_id=c.START, field="/fields", from_card="/fields", + label="表单")] + steps = bp.get("people") or [] + writeback = c.value((bp.get("writeback") or {}).get("capability")) + chain = c.approval_chain(bp, after=WRITE if writeback else APPROVED, rejected=REJECTED) + nodes += chain.nodes + joints += chain.joints + edges = [c.edge(c.START, chain.head), *chain.edges] + if writeback: + write, write_joints, _ = c.write_node(bp, WRITE, confirm_slot=c.slot_of(steps[-1]) if steps else None) + nodes.append(write) + joints += write_joints + edges.append(c.edge(WRITE, APPROVED)) + nodes.append(c.node(APPROVED, "output", "已通过", fields=[{"name": "结论", "value": "已通过"}, *chain.notes])) + if steps: + nodes.append(c.node(REJECTED, "output", "已退回", fields=[{"name": "结论", "value": "已退回"}, + *[dict(n) for n in chain.notes]])) + return {"nodes": nodes, "edges": edges}, joints + + +def app_skeleton(bp: dict[str, Any], graph: dict[str, Any]) -> dict[str, Any]: + name = c.app_name(bp, "审批") + capability = c.value((bp.get("writeback") or {}).get("capability")) + writes = {WRITE: capability} if capability else {} + spec = c.app_base(bp, graph, use="process", name=name, description=str(c.value(bp.get("purpose")) or ""), + writes=writes) + c.entry_and_pages(spec, bp, graph, label=f"发起{name}", writes=writes) + return c.finish_app(spec) + + +def problems(bp: dict[str, Any]) -> list[dict[str, Any]]: + """写回的字段对应只能取表单字段和常量:审批流程没有指标,也没有核对出来的行。""" + if not c.value((bp.get("writeback") or {}).get("capability")): + return [] + _, bad = c.write_args(c.value(bp["writeback"].get("mapping")) or {}) + return [c.mismatch("/writeback/mapping", f"审批流程写回时只能取表单里的字段或常量,这几个无法取值:{'、'.join(bad)}")] \ + if bad else [] + + +def _prefill(spec: dict[str, Any]) -> None: + if not spec.get("people"): + spec["people"] = [c.step("s1", "审批")] + if not spec.get("fields"): + spec["fields"] = [{"name": "reason", "spec": c.template_item({"type": "string", "title": "事由", + "x-widget": "textarea", "required": True}), + "sensitive": False}] + + +def example() -> dict[str, Any]: + """示例:报销审批。金额线 5000 以上才要财务组全员同意,48 小时没处理完升级给总监;先过直属主管。""" + item = c.user_item + + def field(name: str, spec: dict[str, Any]) -> dict[str, Any]: + return {"name": name, "spec": item(spec), "sensitive": False} + + return { + "format": "agentlab.blueprint/1", "purpose": item("员工报销,主管先批,大额的再过财务"), + "template": {"id": ID, "version": VERSION}, "data": [], "cadence": item(None), + "people": [ + {"id": "lead", "label": item("主管审批"), "who": item([{"kind": "user", "name": "zhang"}]), + "policy": item({"kind": "any"}), "due": item("P2D"), "on_timeout": item({"action": "remind"}), + "threshold": item(None)}, + {"id": "finance", "label": item("财务会签"), "who": item([{"kind": "group", "name": "财务组"}]), + "policy": item({"kind": "all"}), "due": item("PT48H"), + "on_timeout": item({"action": "escalate", "to": [{"kind": "user", "name": "director"}]}), + "threshold": item({"field": "amount", "op": ">", "value": 5000})}, + ], + "fields": [field("amount", {"type": "number", "title": "金额(元)", "minimum": 0.01, "required": True}), + field("reason", {"type": "string", "title": "事由", "x-widget": "textarea", "required": True})], + "writeback": None, + "access": {"use": [{"kind": "group", "name": "全体员工"}], "observe": [], "manage": []}, "asks": [], + } + + +TEMPLATE = register(TemplateDef( + id=ID, version=VERSION, label="审批流程", + description="有人发起、有人审批:一级或多级,几个人同意算通过,超时提醒或升级,通过后可以写回别的系统。", + applies_when="用户要一个申请—审批的流程(报销、请假、采购、合同),有表单、有处理人,可能按金额分级、要会签。", + cards={"purpose": "必填:一句话说清审批什么", + "fields": "必填:申请人要填的字段(名称、类型、必填、上下限、选项)", + "people": "必填:每一步谁处理、几个人同意算通过、时限、超时给谁;某一步只在金额超过某个数时才走,写条件", + "writeback": "可选:通过后写回哪个系统、哪些字段、要不要人确认", + "access": "可选:谁能发起、谁能看全部、谁能管理"}, + personal=None, + skeleton=skeleton, app_skeleton=app_skeleton, schedule=None, tags=["流程", "审批"], +)) +c.extend(ID, c.Extras(example=example, example_fill=dict, prefill=_prefill, problems=problems)) diff --git a/backend/app/blueprints/templates/exception_handling.py b/backend/app/blueprints/templates/exception_handling.py new file mode 100644 index 00000000..968e721f --- /dev/null +++ b/backend/app/blueprints/templates/exception_handling.py @@ -0,0 +1,181 @@ +"""异常处置 exception_handling(§3.3):定时 → 入口(统计期)→ 取数(异常清单)→ 分支(有 / 无)→ 人工(负责人填处置 +说明,清单附在待办上)→ [复核] → 成果。 + +- 生成关节:取异常清单的 SQL(一个库,一条 SQL,每条异常一行); +- 确定性关节:统计期、定时任务、负责人(谁来做的第一步)、复核(第二步,可选)、时限与超时; +- 异常数是清单的行数(口径卡按行数算,不交给模型); +- 应用页:最近一期的印章、异常数、异常清单,派给我的待办;每一期的处置在它自己的实例页看。 + +没写「谁来做」时只看清单(个人应用能用的就是这一部分):入口 → 取数 → 口径卡 → 成果。 +""" +from __future__ import annotations + +from typing import Any + +from app.blueprints.templates import Joint, TemplateDef, register +from app.blueprints.templates import _common as c + +ID = "exception_handling" +VERSION = 1 +PARSE = "parse" +GATE = "gate" +HANDLE = "handle" +REVIEW = "review" +CLEAR = "clear" +REJECTED = "rejected" +#: 负责人填的处置说明 +NOTE_FORM = {"format": "agentlab.form/1", "type": "object", + "properties": {"note": {"type": "string", "title": "处置说明", "x-widget": "textarea"}}, + "required": ["note"], "x-order": ["note"]} + +LIST_SHAPE_PROMPT = ("每条异常一行:列出能认出是哪一条的列(门店、商品、单号、日期……)和判断它异常的那几个数," + "列名用英文小写和下划线;没有异常时返回空结果") + + +def _group(bp: dict[str, Any]) -> c.Group | None: + groups, _ = c.data_groups(bp) + return groups[0] if groups else None + + +def skeleton(bp: dict[str, Any]) -> tuple[dict[str, Any], list[Joint]]: + group = _group(bp) + groups = [group] if group is not None else [] + fetches, joints = c.fetch_nodes(groups) + nodes = [c.node(c.START, "input", "统计期", fields=c.period_fields()), *fetches] + joints.append(Joint(id="start.fields", kind="fields", node_id=c.START, field="/fields", from_card="/cadence", + label="统计期")) + edges = [c.edge(c.START, f["id"]) for f in fetches] + if group is None: + nodes.append(c.node(c.DONE, "output", "成果", fields=[])) + return {"nodes": nodes, "edges": edges}, joints + fetch = group.node_id + # 原样按 JSON 解析调用工具节点的结果(engine/lineage.parsed_tool):分支和异常数按它的行数认 + nodes += [c.node(PARSE, "transform", "异常清单", mode="json", template=f"{{{{ nodes.{fetch} }}}}"), + c.node(c.CALIBER, "metrics", "异常数", caliber=f"{c.app_name(bp, '异常处置')}口径", caliber_version="v1", + metrics=[{"id": "exceptions", "name": "异常数", "unit": "条", + "expression": f"nodes.{PARSE}.row_count"}])] + edges += [c.edge(fetch, PARSE), c.edge(PARSE, c.CALIBER)] + steps = bp.get("people") or [] + fields = [{"name": "异常数(条)", "value": f"{{{{ nodes.{PARSE}.row_count }}}}"}] + if not steps: + nodes.append(c.node(c.DONE, "output", "异常清单", fields=fields)) + edges.append(c.edge(c.CALIBER, c.DONE)) + return {"nodes": nodes, "edges": edges}, joints + nodes.append(c.node(GATE, "branch", "有没有异常", mode="expression", cases=[ + {"key": "hit", "condition": f"nodes.{PARSE}.row_count > 0", "label": "有异常"}])) + edges += [c.edge(c.CALIBER, GATE), c.edge(GATE, HANDLE, "hit"), c.edge(GATE, CLEAR, "default")] + owner = steps[0] + label = str(c.value(owner.get("label")) or "处置") + handle, handle_joints = c.human( + owner, 0, HANDLE, mode="input", form=NOTE_FORM, + title=f"{label}:{{{{ input.period }}}} 有 {{{{ nodes.{PARSE}.row_count }}}} 条异常", + message="本期的异常清单附在下面,处理完填写处置说明", + context={"异常清单": f"{{{{ nodes.{PARSE}.rows | json }}}}"}) + nodes.append(handle) + joints += handle_joints + fields.append({"name": "处置说明", "value": f"{{{{ nodes.{HANDLE}.value }}}}"}) + if len(steps) > 1: + checker = steps[1] + review_label = str(c.value(checker.get("label")) or "复核") + review, review_joints = c.human(checker, 1, REVIEW, title=f"{review_label}:{{{{ input.period }}}} 的异常处置", + message=f"处置说明:{{{{ nodes.{HANDLE}.value }}}}") + nodes += [review, c.node(REJECTED, "output", "复核未通过", fields=[ + *fields, {"name": "复核意见", "value": f"{{{{ nodes.{REVIEW}.note }}}}"}])] + joints += review_joints + edges += [c.edge(HANDLE, REVIEW), c.edge(REVIEW, c.DONE, "approved"), c.edge(REVIEW, REJECTED, "rejected")] + fields = [*fields, {"name": "复核意见", "value": f"{{{{ nodes.{REVIEW}.note }}}}"}] + else: + edges.append(c.edge(HANDLE, c.DONE)) + nodes += [c.node(c.DONE, "output", "已处置", fields=fields), + c.node(CLEAR, "output", "本期没有异常", fields=[{"name": "结论", "value": "本期没有异常"}])] + return {"nodes": nodes, "edges": edges}, joints + + +def app_skeleton(bp: dict[str, Any], graph: dict[str, Any]) -> dict[str, Any]: + from app.apps.derive import VIEW, _results + from app.apps.tree import node_map + + name = c.app_name(bp, "异常处置") + process = bool(bp.get("people")) + spec = c.app_base(bp, graph, use="process" if process else "view", name=name, + description=str(c.value(bp.get("purpose")) or "")) + spec["views"][VIEW] = c.latest_view(c.context(bp)) + home = _results(node_map(graph), VIEW, "home") + if process: + home.append({"id": "my_tasks", "type": "task_list", "props": {"scope": "mine"}}) + spec["views"]["inst"] = {"source": {"kind": "instance"}} + spec["pages"] = [{"id": "home", "title": name, "body": home}] + if process: + spec["pages"].append(c.instance_page(graph)) + return c.finish_app(spec) + + +def schedule(bp: dict[str, Any]) -> dict[str, Any] | None: + return c.schedule_of(bp, c.app_name(bp, "异常处置")) + + +def briefs(bp: dict[str, Any]) -> dict[str, str]: + group = _group(bp) + return c.data_briefs(bp, [group], shape=LIST_SHAPE_PROMPT) if group is not None else {} + + +def problems(bp: dict[str, Any]) -> list[dict[str, Any]]: + groups, out = c.data_groups(bp) + if len(groups) > 1: + out.append(c.mismatch("/data", "异常处置只能从一个库里查异常清单:请把要查的数放在同一个库里,或者拆成几个应用")) + if any(item.get("reuse") for item in bp.get("data") or []): + out.append(c.mismatch("/data", "异常清单要按表查出每一条,不能复用口径卡:请按表对")) + if len(bp.get("people") or []) > 2: + out.append(c.mismatch("/people", "异常处置最多两步:负责人处置,再加一道复核")) + return out + + +def _prefill(spec: dict[str, Any]) -> None: + c.fill_cadence(spec, "daily") + if not spec.get("people"): + spec["people"] = [c.step("owner", "处置", due="P1D")] + + +def example() -> dict[str, Any]: + """示例:每天查一次昨天库存低于安全库存的门店商品,派给门店运营填处置说明,区域经理复核。""" + item = c.user_item + + return { + "format": "agentlab.blueprint/1", "purpose": item("每天把缺货的门店商品找出来,运营处理,区域经理复核"), + "template": {"id": ID, "version": VERSION}, + "data": [{"id": "stockout", "label": item("缺货"), "unit": item("条"), + "table": item({"source": "shop", "table": "stock"}), "measure": item("库存低于安全库存"), + "date": item({"column": "stat_date"}), "filter": item(None), "grain": item("门店 × 商品"), + "reuse": None}], + "cadence": item(c.default_cadence("daily")), + "people": [ + {"id": "owner", "label": item("运营处置"), "who": item([{"kind": "group", "name": "门店运营"}]), + "policy": item({"kind": "any"}), "due": item("P1D"), "on_timeout": item(None), "threshold": item(None)}, + {"id": "check", "label": item("区域复核"), "who": item([{"kind": "slot", "name": "区域经理"}]), + "policy": item({"kind": "any"}), "due": item("P2D"), + "on_timeout": item({"action": "remind", "every": "PT4H"}), "threshold": item(None)}, + ], + "fields": [], "writeback": None, + "access": {"use": [{"kind": "group", "name": "门店运营"}], "observe": [], "manage": []}, "asks": [], + } + + +def example_fill() -> dict[str, Any]: + return {"sql_fetch_shop": ("SELECT store, sku, qty, safety_qty FROM stock" + " WHERE stat_date = '{{ input.period_end }}' AND qty < safety_qty")} + + +TEMPLATE = register(TemplateDef( + id=ID, version=VERSION, label="异常处置", + description="定期查出异常(缺货、超期、对不上的单子),派给负责人填处置说明,可以再加一道复核。", + applies_when="用户要定期找出某类异常并让人处理、留下处置记录;异常从一个库里能查出来。", + cards={"purpose": "必填:一句话说清找什么异常、谁来处理", + "data": "必填:什么算异常(对到一张表,写明判断条件),只能从一个库里查", + "cadence": "必填:多久查一次,统计哪一期", + "people": "可选:第一步是负责人(填处置说明),第二步是复核(可选);不写就只看清单", + "access": "可选:谁能用、谁能看全部、谁能管理"}, + personal="只看清单的那一部分(没有处置和复核)", + skeleton=skeleton, app_skeleton=app_skeleton, schedule=schedule, tags=["流程", "定时", "异常"], +)) +c.extend(ID, c.Extras(example=example, example_fill=example_fill, prefill=_prefill, briefs=briefs, + problems=problems)) diff --git a/backend/app/blueprints/templates/freeform.py b/backend/app/blueprints/templates/freeform.py new file mode 100644 index 00000000..452c948a --- /dev/null +++ b/backend/app/blueprints/templates/freeform.py @@ -0,0 +1,110 @@ +"""自由形 freeform(§3.3):从已有的运行(问数据的一轮回答,经 from-run 提取)或已发布的工作流版本导入,图原样用, +没有关节。蓝图只有目的、谁能看、多久更新三张卡片;要改图只能回画布(搭建者)。 + +图由实例化的上下文给(graph,导入时存在蓝图上)。应用骨架按 apps/derive.py 的派生规则:有人工节点或写入的按流程, +否则按看板;写入节点按能力登记的进程内快照认(和运行时同一个判断,capabilities.registry.writes_externally)。 +""" +from __future__ import annotations + +import copy +from typing import Any + +from app.blueprints.templates import Joint, TemplateDef, register +from app.blueprints.templates import _common as c + +ID = "freeform" +VERSION = 1 + + +def imported(bp: dict[str, Any]) -> dict[str, Any]: + graph = c.context(bp).get("graph") + return copy.deepcopy(graph) if isinstance(graph, dict) else {"nodes": [], "edges": []} + + +def skeleton(bp: dict[str, Any]) -> tuple[dict[str, Any], list[Joint]]: + return imported(bp), [] + + +def _writes(graph: dict[str, Any]) -> dict[str, str]: + from app.apps.tree import node_map + from app.capabilities.registry import cached_view, writes_externally + + out: dict[str, str] = {} + for nid, n in node_map(graph).items(): + tool = str(n["config"].get("tool") or "") + view = cached_view(tool) if n["type"] == "tool" and tool else None + if view is not None and writes_externally(tool, view.get("effect"), view.get("endpoint_id")): + out[nid] = tool + return out + + +def app_skeleton(bp: dict[str, Any], graph: dict[str, Any]) -> dict[str, Any]: + from app.apps.derive import ENTRY, INSTANCE_VIEW, PIN, VIEW, _entries, _results + from app.apps.forms import input_schema + from app.apps.tree import input_fields, node_map + + name = c.app_name(bp, "应用") + nodes = node_map(graph) + writes = _writes(graph) + process = bool(writes) or any(n["type"] == "human" for n in nodes.values()) + spec = c.app_base(bp, graph, use="process" if process else "view", name=name, + description=str(c.value(bp.get("purpose")) or ""), writes=writes) + fields = input_fields(graph) + if fields: + spec["forms"][ENTRY] = input_schema(fields) + names = list(spec["forms"][ENTRY]["properties"]) + spec["entries"].append({"id": ENTRY, "label": f"发起{name}" if process else "按条件运行", "pin": PIN, + "form": {"$ref": f"#/forms/{ENTRY}"}, "map": {n: f"form.{n}" for n in names}}) + spec["views"][INSTANCE_VIEW] = {"source": {"kind": "instance"}} + if not process: + spec["views"][VIEW] = c.latest_view(c.context(bp)) + spec["pages"] = [{"id": "home", "title": name, "body": ([] if process else _results(nodes, VIEW, "home")) + + _entries(spec)}] + if spec["entries"]: + spec["pages"].append(c.instance_page(graph, writes)) + return c.finish_app(spec) + + +def schedule(bp: dict[str, Any]) -> dict[str, Any] | None: + """导入的图入口字段正好是统计期三个字段时按「多久更新」填;别的字段没法替人定,只建任务、不填输入。""" + from app.apps.tree import input_fields + + names = {f["name"] for f in input_fields(imported(bp))} + inputs = None if set(c.PERIOD_FIELDS) <= names else {} + return c.schedule_of(bp, c.app_name(bp, "应用"), inputs=inputs) + + +def example() -> dict[str, Any]: + item = c.user_item + + return {"format": "agentlab.blueprint/1", "purpose": item("把这次问数据的回答做成每周自动出的看板"), + "template": {"id": ID, "version": VERSION}, "data": [], "cadence": item(c.default_cadence("weekly")), + "people": [], "fields": [], "writeback": None, + "access": {"use": [], "observe": [], "manage": []}, "asks": []} + + +def example_graph() -> dict[str, Any]: + """示例导入的图:统计期 → 查库 → 口径卡 → 按指标出具(测试用)。""" + return {"nodes": [ + c.node(c.START, "input", "统计期", fields=c.period_fields()), + c.node("q", "tool", "查订单", tool="db_query__shop", args={ + "sql": "SELECT SUM(amount) AS gmv FROM orders WHERE paid_at BETWEEN '{{ input.period_start }}'" + " AND '{{ input.period_end }}'"}), + c.node(c.CALIBER, "metrics", "口径卡", caliber="周报口径", caliber_version="v1", + metrics=[{"id": "gmv", "name": "销售额", "unit": "元", "expression": "cell(nodes.q, 0, 'gmv')"}]), + c.node(c.DONE, "output", "出具", fields=[{"name": "销售额(元)", "value": "{{ nodes.caliber.metrics[0].value }}"}], + contract={"metrics_from": [c.CALIBER], "required": ["gmv"], "strict": True}), + ], "edges": [c.edge(c.START, "q"), c.edge("q", c.CALIBER), c.edge(c.CALIBER, c.DONE)]} + + +TEMPLATE = register(TemplateDef( + id=ID, version=VERSION, label="自由形", + description="从已有的开始:一次问数据的回答,或者一个已发布的工作流,原样做成应用;改图要回画布。", + applies_when="用户已经有一次满意的问数据回答,或者一个已发布的工作流,想直接做成应用;需求在五个场景之外时也用它。", + cards={"purpose": "必填:一句话说清这个应用做什么", + "cadence": "可选:要不要定期自动出数", + "access": "可选:谁能用、谁能看全部、谁能管理"}, + personal="导入的图满足问数据的规则(只读、没有人工节点和写入)时可以", + skeleton=skeleton, app_skeleton=app_skeleton, schedule=schedule, tags=["导入"], +)) +c.extend(ID, c.Extras(example=example, example_fill=dict, imports_graph=True)) diff --git a/backend/app/blueprints/templates/periodic_board.py b/backend/app/blueprints/templates/periodic_board.py new file mode 100644 index 00000000..a43a3587 --- /dev/null +++ b/backend/app/blueprints/templates/periodic_board.py @@ -0,0 +1,127 @@ +"""周期看板 periodic_board(§3.3):入口(统计期)→ 取数(每个库一个调用工具节点)→ 口径卡 → 成果(指标出具)。 + +- 生成关节:每个取数节点的 SQL、口径卡每个数的指标式(只许 cell() 取格加算术); +- 确定性关节:统计期字段、定时任务(多久更新)、出具契约的必需指标(看哪些数);复用已发布口径卡的项落成 caliber_from; +- 应用页:印章、指标块、复用的口径、趋势、明细表;「按条件查看」是按需视图(参数就是统计期)。 + +个人应用能用全部(只读、没有人工节点和写入)。 +""" +from __future__ import annotations + +from typing import Any + +from app.blueprints.templates import Joint, TemplateDef, register +from app.blueprints.templates import _common as c + +ID = "periodic_board" +VERSION = 1 +#: 按条件查看的按需视图:同样的统计期一小时内用缓存,不重复查库 +ON_DEMAND_TTL_S = 3600 + + +def skeleton(bp: dict[str, Any]) -> tuple[dict[str, Any], list[Joint]]: + groups, _ = c.data_groups(bp) + caliber, metric_joints = c.caliber_node(bp, groups, c.app_name(bp, "周期看板")) + reused = c.reuse_nodes(groups) + fetches, joints = c.fetch_nodes(groups) + nodes = [c.node(c.START, "input", "统计期", fields=c.period_fields()), *fetches] + edges = [c.edge(c.START, f["id"]) for f in fetches] + joints.append(Joint(id="start.fields", kind="fields", node_id=c.START, field="/fields", from_card="/cadence", + label="统计期")) + if caliber is not None: + nodes.append(caliber) + joints += metric_joints + edges += [c.edge(g.node_id, c.CALIBER) for g in groups if g.items] + edges.append(c.edge(c.CALIBER, c.DONE)) + for card, _item, fetch in reused: + nodes.append(card) + edges += [c.edge(fetch, card["id"]), c.edge(card["id"], c.DONE)] + done, done_joints = c.board_output(bp, caliber, reused) + nodes.append(done) + joints += done_joints + return {"nodes": nodes, "edges": edges}, joints + + +def app_skeleton(bp: dict[str, Any], graph: dict[str, Any]) -> dict[str, Any]: + from app.apps.derive import PIN, VIEW, _results + from app.apps.forms import input_schema + from app.apps.tree import input_fields, node_map + + name = c.app_name(bp, "周期看板") + spec = c.app_base(bp, graph, use="view", name=name, description=str(c.value(bp.get("purpose")) or "")) + nodes = node_map(graph) + spec["forms"][c.START] = input_schema(input_fields(graph)) + spec["views"][VIEW] = c.latest_view(c.context(bp)) + spec["views"]["custom"] = {"source": {"kind": "on_demand", "pin": PIN, "params": {"$ref": f"#/forms/{c.START}"}, + "ttl_s": ON_DEMAND_TTL_S}} + spec["pages"] = [ + {"id": "home", "title": name, "body": [*_results(nodes, VIEW, "home"), + *c.reused_section(bp, graph, VIEW, "home"), + *c.series_section(graph, VIEW, "home")]}, + {"id": "custom", "title": "按条件查看", "body": [*_results(nodes, "custom", "custom"), + *c.reused_section(bp, graph, "custom", "custom")]}, + ] + return c.finish_app(spec) + + +def schedule(bp: dict[str, Any]) -> dict[str, Any] | None: + return c.schedule_of(bp, c.app_name(bp, "周期看板")) + + +def briefs(bp: dict[str, Any]) -> dict[str, str]: + groups, _ = c.data_groups(bp) + return c.data_briefs(bp, groups) + + +def _prefill(spec: dict[str, Any]) -> None: + c.fill_cadence(spec, "weekly") + + +def problems(bp: dict[str, Any]) -> list[dict[str, Any]]: + return c.data_groups(bp)[1] + + +def example() -> dict[str, Any]: + """示例:每周一看上周的销售额、订单数和退款率(库 shop 的 orders 表)。""" + item = c.user_item + + def data(item_id: str, label: str, unit: str, measure: str, filter_: str | None = None) -> dict[str, Any]: + return {"id": item_id, "label": item(label), "unit": item(unit), + "table": item({"source": "shop", "table": "orders"}), "measure": item(measure), + "date": item({"column": "paid_at", "rule": "按支付日"}), "filter": item(filter_), + "grain": item("全部门店"), "reuse": None} + + return {"format": "agentlab.blueprint/1", "purpose": item("每周一看上周各门店的销售额、订单数和退款率"), + "template": {"id": ID, "version": VERSION}, + "data": [data("gmv", "销售额", "元", "sum(amount)", "不含已退款"), data("orders", "订单数", "单", "count(*)"), + data("refund_rate", "退款率", "%", "退款单数 / 订单数")], + "cadence": item(c.default_cadence("weekly")), "people": [], "fields": [], "writeback": None, + "access": {"use": [{"kind": "group", "name": "门店"}], "observe": [], "manage": []}, "asks": []} + + +def example_fill() -> dict[str, Any]: + return { + "sql_fetch_shop": ("SELECT SUM(CASE WHEN refunded = 0 THEN amount ELSE 0 END) AS gmv, COUNT(*) AS order_cnt," + " SUM(CASE WHEN refunded = 1 THEN 1 ELSE 0 END) AS refund_cnt FROM orders" + " WHERE paid_at BETWEEN '{{ input.period_start }}' AND '{{ input.period_end }}'"), + "metric_gmv": "cell(nodes.fetch_shop, 0, 'gmv')", + "metric_orders": "cell(nodes.fetch_shop, 0, 'order_cnt')", + "metric_refund_rate": ("round(cell(nodes.fetch_shop, 0, 'refund_cnt')" + " / cell(nodes.fetch_shop, 0, 'order_cnt') * 100, 2)" + " if cell(nodes.fetch_shop, 0, 'order_cnt') else None"), + } + + +TEMPLATE = register(TemplateDef( + id=ID, version=VERSION, label="周期看板", + description="定期出一张看板:每天、每周或每月按同一个口径算几个数,打开就有数,能看趋势、能按条件再查。", + applies_when="用户想定期看几个数(销售额、订单数、退款率这类),按天、周、月更新,不需要人审批、不写回别的系统。", + cards={"purpose": "必填:一句话说清看什么、给谁看", + "data": "必填:每一项对到一张表(或复用已发布的口径卡),写明怎么算、按哪个日期、筛选条件", + "cadence": "必填:每天、每周还是每月,几点,统计哪一期", + "access": "可选:谁能用、谁能看全部、谁能管理"}, + personal="全部可以做成个人应用(只读,自己点刷新)", + skeleton=skeleton, app_skeleton=app_skeleton, schedule=schedule, tags=["看板", "定时"], +)) +c.extend(ID, c.Extras(example=example, example_fill=example_fill, prefill=_prefill, briefs=briefs, + problems=problems)) diff --git a/backend/app/blueprints/templates/reconcile_writeback.py b/backend/app/blueprints/templates/reconcile_writeback.py new file mode 100644 index 00000000..5925570e --- /dev/null +++ b/backend/app/blueprints/templates/reconcile_writeback.py @@ -0,0 +1,202 @@ +"""核对写回 reconcile_writeback(§3.3):定时 → 取数(核对差异:汇总一行 + 差异明细)→ 口径卡(差异的指标)→ 有没有差异 +→ 人工复核(确认要写回)→ 写回 → 成果。 + +- 生成关节:汇总差异的 SQL、差异明细的 SQL、口径卡每个数的指标式(同一组,一起填:两条 SQL 查同一个库); +- 确定性关节:统计期、定时任务、复核人(谁来做的第一步)、写回目标与字段对应(明细整组写 rows,指标写 metric.)、 + 要不要人确认(确认派给复核的岗位); +- 两个成果都按指标出具(差异的指标就是这一期核对的结论)。 + +不能做成个人应用:要人复核、要写回别的系统。 +""" +from __future__ import annotations + +from typing import Any + +from app.blueprints.templates import Joint, TemplateDef, register +from app.blueprints.templates import _common as c + +ID = "reconcile_writeback" +VERSION = 1 +DETAIL = "detail" +PARSE = "parse" +GATE = "gate" +REVIEW = "review" +WRITE = "writeback" +CLEAR = "clear" +REJECTED = "rejected" +#: 差异明细整组的取值链(写回参数写 rows 时用它) +ROWS = f"nodes.{PARSE}.rows" + +DETAIL_BRIEF_PROMPT = ("差异明细节点 {node}(工具 db_query__{source}):再写一条只读 SQL,每条差异一行,列出要写回的那几列" + "(列名和写回的字段对应:{mapping});没有差异时返回空结果。统计期同上。") + + +def _group(bp: dict[str, Any]) -> c.Group | None: + groups, _ = c.data_groups(bp) + return groups[0] if groups else None + + +def skeleton(bp: dict[str, Any]) -> tuple[dict[str, Any], list[Joint]]: + group = _group(bp) + groups = [group] if group is not None else [] + name = c.app_name(bp, "核对写回") + fetches, joints = c.fetch_nodes(groups) + nodes = [c.node(c.START, "input", "统计期", fields=c.period_fields()), *fetches] + joints.append(Joint(id="start.fields", kind="fields", node_id=c.START, field="/fields", from_card="/cadence", + label="统计期")) + edges = [c.edge(c.START, f["id"]) for f in fetches] + caliber, metric_joints = c.caliber_node(bp, groups, name) + if group is None or caliber is None: + nodes.append(c.node(c.DONE, "output", "成果", fields=[])) + return {"nodes": nodes, "edges": edges}, joints + nodes += [caliber, + c.node(DETAIL, "tool", f"差异明细({group.source})", tool=f"db_query__{group.source}", + args={"sql": c.SQL_PLACEHOLDER}), + c.node(PARSE, "transform", "差异明细", mode="json", template=f"{{{{ nodes.{DETAIL} }}}}"), + c.node(GATE, "branch", "有没有差异", mode="expression", cases=[ + {"key": "hit", "condition": f"nodes.{PARSE}.row_count > 0", "label": "有差异"}])] + joints += metric_joints + joints.append(Joint(id=f"sql_{DETAIL}", kind="sql", node_id=DETAIL, field="/args/sql", group=group.node_id, + label=f"差异明细的 SQL({group.source})")) + edges += [c.edge(group.node_id, c.CALIBER), c.edge(c.START, DETAIL), c.edge(DETAIL, PARSE), + c.edge(c.CALIBER, GATE), c.edge(PARSE, GATE), c.edge(GATE, CLEAR, "default")] + steps = bp.get("people") or [] + confirm_slot = None + after_gate = WRITE + if steps: + checker = steps[0] + label = str(c.value(checker.get("label")) or "复核") + review, review_joints = c.human( + checker, 0, REVIEW, title=f"{label}:{{{{ input.period }}}} 有 {{{{ nodes.{PARSE}.row_count }}}} 条差异要写回", + message="差异明细附在下面,确认后写回", context={"差异明细": f"{{{{ {ROWS} | json }}}}"}) + nodes += [review, c.node(REJECTED, "output", "不写回", fields=[ + {"name": "结论", "value": "复核没有通过,没有写回"}, + {"name": "复核意见", "value": f"{{{{ nodes.{REVIEW}.note }}}}"}])] + joints += review_joints + edges += [c.edge(REVIEW, WRITE, "approved"), c.edge(REVIEW, REJECTED, "rejected")] + confirm_slot = c.slot_of(checker) + after_gate = REVIEW + edges.append(c.edge(GATE, after_gate, "hit")) + write, write_joints, _ = c.write_node(bp, WRITE, confirm_slot=confirm_slot, metrics=c.metric_paths(caliber), + rows=ROWS) + nodes.append(write) + joints += write_joints + edges.append(c.edge(WRITE, c.DONE)) + done, done_joints = c.board_output(bp, caliber, [], label="已写回") + clear, _ = c.board_output(bp, caliber, [], node_id=CLEAR, label="没有差异") + nodes += [done, clear] + joints += done_joints + return {"nodes": nodes, "edges": edges}, joints + + +def app_skeleton(bp: dict[str, Any], graph: dict[str, Any]) -> dict[str, Any]: + from app.apps.derive import VIEW, _results + from app.apps.tree import node_map + + name = c.app_name(bp, "核对写回") + capability = c.value((bp.get("writeback") or {}).get("capability")) + writes = {WRITE: capability} if capability and WRITE in node_map(graph) else {} + spec = c.app_base(bp, graph, use="process", name=name, description=str(c.value(bp.get("purpose")) or ""), + writes=writes) + spec["views"][VIEW] = c.latest_view(c.context(bp)) + spec["views"]["inst"] = {"source": {"kind": "instance"}} + spec["pages"] = [ + {"id": "home", "title": name, "body": [*_results(node_map(graph), VIEW, "home"), + {"id": "my_tasks", "type": "task_list", "props": {"scope": "mine"}}]}, + c.instance_page(graph, writes), + ] + return c.finish_app(spec) + + +def schedule(bp: dict[str, Any]) -> dict[str, Any] | None: + return c.schedule_of(bp, c.app_name(bp, "核对写回")) + + +def briefs(bp: dict[str, Any]) -> dict[str, str]: + group = _group(bp) + if group is None: + return {} + out = c.data_briefs(bp, [group]) + mapping = c.value((bp.get("writeback") or {}).get("mapping")) or {} + out[group.node_id] += "\n" + DETAIL_BRIEF_PROMPT.format( + node=DETAIL, source=group.source, mapping="、".join(f"{k} ← {v}" for k, v in mapping.items()) or c.UNKNOWN_PROMPT) + return out + + +def problems(bp: dict[str, Any]) -> list[dict[str, Any]]: + groups, out = c.data_groups(bp) + if len(groups) > 1: + out.append(c.mismatch("/data", "核对写回的两边要在同一个库里,一条 SQL 才对得上:请把要核对的数放在同一个库里")) + if any(item.get("reuse") for item in bp.get("data") or []): + out.append(c.mismatch("/data", "核对差异要按表重新算,不能复用口径卡:请按表对")) + if len(bp.get("people") or []) > 1: + out.append(c.mismatch("/people", "核对写回只有一步复核:请只留一步")) + mapping = c.value((bp.get("writeback") or {}).get("mapping")) or {} + metrics = {item["id"]: "" for item in bp.get("data") or []} + _, bad = c.write_args(mapping, metrics=metrics, rows=ROWS) + if bad: + out.append(c.mismatch("/writeback/mapping", f"写回的字段对应只能取差异明细(rows)、看哪些数里的指标或常量," + f"这几个无法取值:{'、'.join(bad)}")) + return out + + +def _prefill(spec: dict[str, Any]) -> None: + c.fill_cadence(spec, "daily") + if not spec.get("people"): + spec["people"] = [c.step("check", "复核", due="P1D")] + + +def example() -> dict[str, Any]: + """示例:每天核对昨天订单系统和财务系统的金额,差异给财务复核后写回财务系统。""" + item = c.user_item + + def data(item_id: str, label: str, unit: str, measure: str) -> dict[str, Any]: + return {"id": item_id, "label": item(label), "unit": item(unit), + "table": item({"source": "shop", "table": "orders"}), "measure": item(measure), + "date": item({"column": "paid_at"}), "filter": item("和 ledger 表按单号对"), "grain": item("单号"), + "reuse": None} + + return { + "format": "agentlab.blueprint/1", "purpose": item("每天核对订单和财务入账,差异复核后写回财务系统"), + "template": {"id": ID, "version": VERSION}, + "data": [data("diff_count", "差异笔数", "笔", "金额对不上的单数"), + data("diff_amount", "差异金额", "元", "两边金额差的绝对值之和")], + "cadence": item(c.default_cadence("daily")), + "people": [{"id": "check", "label": item("财务复核"), "who": item([{"kind": "group", "name": "财务组"}]), + "policy": item({"kind": "any"}), "due": item("P1D"), "on_timeout": item(None), + "threshold": item(None)}], + "fields": [], + "writeback": {"capability": item("fake_ledger_adjust"), + "mapping": item({"items": "rows", "total": "metric.diff_amount"}), + "confirm": item(True)}, + "access": {"use": [{"kind": "group", "name": "财务组"}], "observe": [], "manage": []}, "asks": [], + } + + +def example_fill() -> dict[str, Any]: + period = "o.paid_at BETWEEN '{{ input.period_start }}' AND '{{ input.period_end }}'" + return { + "sql_fetch_shop": ("SELECT COUNT(*) AS diff_count, SUM(ABS(o.amount - l.amount)) AS diff_amount FROM orders o" + f" JOIN ledger l ON l.order_id = o.id WHERE o.amount <> l.amount AND {period}"), + "sql_detail": ("SELECT o.id AS order_id, o.amount AS amount FROM orders o JOIN ledger l ON l.order_id = o.id" + f" WHERE o.amount <> l.amount AND {period}"), + "metric_diff_count": "cell(nodes.fetch_shop, 0, 'diff_count')", + "metric_diff_amount": "cell(nodes.fetch_shop, 0, 'diff_amount') if cell(nodes.fetch_shop, 0, 'diff_count') else 0", + } + + +TEMPLATE = register(TemplateDef( + id=ID, version=VERSION, label="核对写回", + description="定期核对两边的数,找出对不上的,交给人复核,确认后写回别的系统;每次写入都留生效记录。", + applies_when="用户要定期对账或核对(两张表、两个系统的数对不对得上),找出差异后由人确认,再写回某个系统。", + cards={"purpose": "必填:一句话说清核对什么、对不上怎么办", + "data": "必填:差异的指标(差异笔数、差异金额),对到同一个库里的表", + "cadence": "必填:多久核对一次,统计哪一期", + "people": "必填:谁复核(只有一步)", + "writeback": "必填:写回哪个系统(能力登记里的写入能力)、字段对应(差异明细写 rows)、要不要人确认", + "access": "可选:谁能用、谁能看全部、谁能管理"}, + personal=None, + skeleton=skeleton, app_skeleton=app_skeleton, schedule=schedule, tags=["流程", "定时", "写回"], +)) +c.extend(ID, c.Extras(example=example, example_fill=example_fill, prefill=_prefill, briefs=briefs, + problems=problems)) diff --git a/backend/app/blueprints/templates/records.py b/backend/app/blueprints/templates/records.py new file mode 100644 index 00000000..0e0916ec --- /dev/null +++ b/backend/app/blueprints/templates/records.py @@ -0,0 +1,213 @@ +"""填报登记 records(§3.3、N8):入口(表单)→ [审批] → 平台内置能力 records_append(一次提交落一行)→ 已登记; +另配一张汇总看板(周期看板的骨架,查这个应用的记录表)。 + +两件事在同一张图里,按入口字段 mode 分两条路: +- 填报:应用的入口表单提交(入口映射把 mode 写成 submit)→ [审批] → 写记录表 → 已登记。写入只经调用工具节点和动作 + (生效记录、幂等键),能力允许无人值守,审批写「全部自动放行」; +- 汇总:定时任务按「多久更新」发起(输入模板把 mode 写成 summary)→ 取数(查记录表,生成关节 SQL)→ 口径卡(生成关节 + 指标式)→ 成果(指标出具)。正式运行以服务身份查、看到全部行,所以汇总是全量的(N8:发布摘要写明)。 + +表单字段在入口节点上都不是必填(汇总那条路不带表单),必填由应用的入口表单把关,记录表写入时按列再核一遍。 +记录表的键和登记成的数据源名由实例化的上下文给(records = {table, source},记录表服务建表时定);「看哪些数」里对到 +本应用记录表的项,库名写 @records。 + +不能做成个人应用(personal=None):个人应用只读,这张图的骨架就是往自己的记录表里写,去掉写入只剩一张永远是空的表; +想看自己提交过什么,用正式应用里的「我的记录」。蓝图这边(blueprints/store.records_context)也从不替个人蓝图建记录表。 + +「填什么」里的文件字段进记录表的文件列(存文件引用),提交时文件先绑到这次运行,写下这一行时再绑到这一行 +(records/actions._bind_files),看得到这一行的人能下载。 +""" +from __future__ import annotations + +from typing import Any + +from app.blueprints.templates import Joint, TemplateDef, register +from app.blueprints.templates import _common as c + +ID = "records" +VERSION = 1 +#: 「看哪些数」里指这个应用自己的记录表 +RECORDS_SELF = "@records" +ROUTE = "route" +APPEND = "append" +SUBMITTED = "submitted" +REJECTED = "rejected" +SUMMARY = "summary" +#: 入口字段 mode 的两个值 +MODE_SUBMIT = "submit" +MODE_SUMMARY = "summary" + + +def records_of(bp: dict[str, Any]) -> dict[str, str]: + """这个应用的记录表:{table: 写入时认的表(records_tables 的 id、数据源名或「键.v版本」,records/tables.find_table), + source: 登记成的数据源名},由实例化的上下文给(records/tables.ensure_table 建好之后)。没给时按记录表服务的起名规则 + 猜第一版(键是蓝图 id):只用于还没建表时看骨架,试运行和发布前由调用方给真的。""" + import re + + from app.records.tables import SOURCE_PREFIX + + ctx = c.context(bp) + given = ctx.get("records") if isinstance(ctx.get("records"), dict) else {} + key = str(ctx.get("blueprint_id") or "draft") + source = f"{SOURCE_PREFIX}{re.sub(r'[^a-z0-9]', '', key.lower())[:12] or 'table'}" + return {"table": str(given.get("table") or f"{key}.v1"), "source": str(given.get("source") or source)} + + +def _groups(bp: dict[str, Any]) -> tuple[list[c.Group], list[dict[str, Any]]]: + return c.data_groups(bp, source_map={RECORDS_SELF: records_of(bp)["source"]}, prefix=SUMMARY) + + +def skeleton(bp: dict[str, Any]) -> tuple[dict[str, Any], list[Joint]]: + from app.records import RECORDS_APPEND + + records = records_of(bp) + groups, _ = _groups(bp) + name = c.app_name(bp, "填报登记") + mode = {"name": "mode", "label": "做什么", "enum": [MODE_SUBMIT, MODE_SUMMARY], "default": MODE_SUBMIT, + "description": "填报(submit)或汇总(summary):应用的入口表单填报,定时任务汇总"} + nodes = [c.node(c.START, "input", "填报", fields=[*c.form_fields(bp, required=False), mode, + *[{**f, "required": False} for f in c.period_fields()]]), + c.node(ROUTE, "branch", "填报还是汇总", mode="expression", cases=[ + {"key": "summary", "condition": f"input.mode == '{MODE_SUMMARY}'", "label": "汇总"}])] + joints = [Joint(id="start.fields", kind="fields", node_id=c.START, field="/fields", from_card="/fields", + label="表单与表结构")] + edges = [c.edge(c.START, ROUTE)] + # 填报:[审批] → 写记录表 + chain = c.approval_chain(bp, after=APPEND, rejected=REJECTED) + nodes += chain.nodes + joints += chain.joints + edges += [c.edge(ROUTE, chain.head, "default"), *chain.edges] + values = {f["name"]: c.field_ref(f["name"]) for f in bp.get("fields") or []} + nodes.append(c.node(APPEND, "tool", "写记录表", tool=RECORDS_APPEND, approval="never", + args={"table": records["table"], "values": values})) + joints.append(Joint(id=f"{APPEND}.args", kind="capability", node_id=APPEND, field="/args", from_card="/fields", + label="写记录表:字段对应")) + nodes.append(c.node(SUBMITTED, "output", "已登记", fields=[{"name": "结论", "value": "已登记"}, *chain.notes])) + edges.append(c.edge(APPEND, SUBMITTED)) + if bp.get("people"): + nodes.append(c.node(REJECTED, "output", "已退回", fields=[{"name": "结论", "value": "已退回"}, + *[dict(n) for n in chain.notes]])) + # 汇总:周期看板的骨架,查记录表 + fetches, fetch_joints = c.fetch_nodes(groups) + caliber, metric_joints = c.caliber_node(bp, groups, name) + reused = c.reuse_nodes(groups) + nodes += fetches + joints += fetch_joints + edges += [c.edge(ROUTE, f["id"], "summary") for f in fetches] + if caliber is not None: + nodes.append(caliber) + joints += metric_joints + edges += [c.edge(g.node_id, c.CALIBER) for g in groups if g.items] + edges.append(c.edge(c.CALIBER, c.DONE)) + for card, _item, fetch in reused: + nodes.append(card) + edges += [c.edge(fetch, card["id"]), c.edge(card["id"], c.DONE)] + if fetches: + done, done_joints = c.board_output(bp, caliber, reused, label="汇总") + nodes.append(done) + joints += done_joints + else: + # 还没定看哪些数:汇总那条路直接收尾,照实写还没有汇总 + nodes.append(c.node(c.DONE, "output", "汇总", fields=[{"name": "结论", "value": "还没定汇总看哪些数"}])) + edges.append(c.edge(ROUTE, c.DONE, "summary")) + return {"nodes": nodes, "edges": edges}, joints + + +def app_skeleton(bp: dict[str, Any], graph: dict[str, Any]) -> dict[str, Any]: + from app.apps.derive import VIEW, _results + from app.apps.tree import node_map + from app.records import RECORDS_APPEND + + name = c.app_name(bp, "填报登记") + writes = {APPEND: RECORDS_APPEND} + spec = c.app_base(bp, graph, use="process", name=name, description=str(c.value(bp.get("purpose")) or ""), + writes=writes) + spec["views"][VIEW] = c.latest_view(c.context(bp)) + summary = [comp for comp in _results(node_map(graph), VIEW, "home") if comp.get("type") != "table"] + # 我的记录:按看的人实时过滤(使用者只看自己的,N8 行级可见),不走封存。汇总表格不放:它会把每一行列给所有人 + mine = [{"id": "my_records", "type": "records_list"}] + c.entry_and_pages(spec, bp, graph, label=f"填报{name}", writes=writes, + home_extra=[*mine, *summary, *c.reused_section(bp, graph, VIEW, "home")], + entry_map={"mode": f"'{MODE_SUBMIT}'"}) + return c.finish_app(spec) + + +def schedule(bp: dict[str, Any]) -> dict[str, Any] | None: + if not bp.get("data"): + return None + cadence = c.value(bp.get("cadence")) + return c.schedule_of(bp, c.app_name(bp, "填报登记"), + inputs={**c.period_template(cadence), "mode": MODE_SUMMARY} if cadence else None) + + +def briefs(bp: dict[str, Any]) -> dict[str, str]: + groups, _ = _groups(bp) + return c.data_briefs(bp, groups) + + +def problems(bp: dict[str, Any]) -> list[dict[str, Any]]: + out = _groups(bp)[1] + if bp.get("writeback") and c.value(bp["writeback"].get("capability")): + out.append(c.mismatch("/writeback", "填报登记写进平台自己的记录表,不写回别的系统:请删掉「写回哪里」")) + return out + + +def _prefill(spec: dict[str, Any]) -> None: + c.fill_cadence(spec, "weekly") + + +def example() -> dict[str, Any]: + """示例:门店每天报损,店长审批;汇总看板每周一看上周的报损金额和笔数。""" + item = c.user_item + + def data(item_id: str, label: str, unit: str, measure: str) -> dict[str, Any]: + return {"id": item_id, "label": item(label), "unit": item(unit), + "table": item({"source": RECORDS_SELF, "table": "records"}), "measure": item(measure), + "date": item({"column": "_submitted_at", "rule": "按提交时间"}), "filter": item(None), + "grain": item("全部门店"), "reuse": None} + + return { + "format": "agentlab.blueprint/1", "purpose": item("门店每天报损,店长审批,每周看汇总"), + "template": {"id": ID, "version": VERSION}, + "data": [data("loss_amount", "报损金额", "元", "sum(amount)"), data("loss_count", "报损笔数", "笔", "count(*)")], + "cadence": item(c.default_cadence("weekly")), + "people": [{"id": "manager", "label": item("店长审批"), "who": item([{"kind": "slot", "name": "店长"}]), + "policy": item({"kind": "any"}), "due": item("P1D"), "on_timeout": item(None), + "threshold": item(None)}], + "fields": [ + {"name": "store", "spec": item({"type": "string", "title": "门店", "required": True}), "sensitive": False}, + {"name": "amount", "spec": item({"type": "number", "title": "金额(元)", "minimum": 0, "required": True}), + "sensitive": False}, + {"name": "reason", "spec": item({"type": "string", "title": "原因", "x-widget": "textarea"}), + "sensitive": True}, + ], + "writeback": None, + "access": {"use": [{"kind": "group", "name": "门店"}], "observe": [{"kind": "group", "name": "区域经理"}], + "manage": []}, + "asks": [], + } + + +def example_fill() -> dict[str, Any]: + sql = ("SELECT SUM(amount) AS loss_amount, COUNT(*) AS loss_count FROM records" + " WHERE date(_submitted_at) BETWEEN '{{ input.period_start }}' AND '{{ input.period_end }}'") + node = f"{SUMMARY}_rec_draft" + return {f"sql_{node}": sql, "metric_loss_amount": f"cell(nodes.{node}, 0, 'loss_amount')", + "metric_loss_count": f"cell(nodes.{node}, 0, 'loss_count')"} + + +TEMPLATE = register(TemplateDef( + id=ID, version=VERSION, label="填报登记", + description="大家按同一张表单提交,每次提交存一行(可以先审批),再按周期汇总着看;每个人只看得到自己提交的记录。", + applies_when="用户要收集一类记录(报损、巡店、日报、登记),每次提交一行,之后汇总着看;不需要写回别的系统。", + cards={"purpose": "必填:一句话说清登记什么、谁来填", + "fields": "必填:每次提交填哪些字段(名称、类型、必填、上下限、选项),可以标敏感", + "people": "可选:提交后要谁审批(审批通过才落进记录表)", + "data": "可选:汇总看哪些数(对到本应用的记录表)", + "cadence": "可选:汇总多久更新一次", + "access": "可选:谁能填(只看得到自己的记录)、谁能看全部、谁能管理"}, + personal=None, + skeleton=skeleton, app_skeleton=app_skeleton, schedule=schedule, tags=["流程", "记录", "看板"], +)) +c.extend(ID, c.Extras(example=example, example_fill=example_fill, prefill=_prefill, briefs=briefs, + problems=problems)) diff --git a/backend/app/blueprints/trial.py b/backend/app/blueprints/trial.py index f4406805..23c112bd 100644 --- a/backend/app/blueprints/trial.py +++ b/backend/app/blueprints/trial.py @@ -1,19 +1,358 @@ """试运行(N4、§3.5):跑一次还没发布的图(探索运行,origin_kind=trial),草稿应用对着这次运行解析 (apps/resolve.resolve_page 的 trial 旁路),印章写「试运行」。流程类的人工步骤派给试运行的人自己,写入走测试环境或演练, -调度不对 trial 的待办做超时升级。 +调度不对 trial 的待办做超时升级(process/tasks.py)。 -包 B2 实现。 +- 实例化(materialize):模板按卡片出图、关节、应用草稿、定时任务参数(blueprints/instantiate,纯函数),图和关节存到 + 蓝图上,应用草稿和定时任务参数记进这一次的留痕(blueprint_events 的 instantiate)——发布单建应用时用的就是试运行时看到的 + 那一份(P1:看到的就是发布的)。已经填好的生成关节(蓝图 joints 上存的值,依据没变的才算,instantiate.filled_from)交回 + 模板,改了一张卡片不会把助手填的 SQL、指标式丢掉。「自由形」(从运行、工作流版本导入)没有关节,图原样存。 +- 试运行(start_trial):先实例化,蓝图检查(缺项)、实例化交回的问题有 error 的不试;以发起人的身份发起探索运行,看板类的 + 输入按「多久更新」算出最近一期(同定时任务到点时的取值),用户给的覆盖它;流程类填了示例表单的,和应用入口提交同一条路 + (表单校验、文件核对后绑到这次运行、按入口映射出输入,entry_inputs)。开登录后的使用者(个人蓝图)照问数据的约束: + 图只能用放行的节点和工具,结果遮罩、只读。 +- 预览(preview_page):按这次试运行解析草稿应用的一页。只认这个蓝图自己的试运行。 """ from __future__ import annotations +import copy +import logging +from dataclasses import dataclass, field from typing import Any +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession -async def start_trial(session: Any, blueprint: Any, *, inputs: dict[str, Any] | None, actor: Any) -> str: - """实例化 → 保存图到蓝图 → 发起探索运行,交回 run_id。蓝图状态记 trialed、last_trial_run_id。""" - raise NotImplementedError +from app.api.deps import Principal +from app.db.models import Run +from app.db.models_blueprints import Blueprint, BlueprintEvent + +logger = logging.getLogger(__name__) + +#: 试运行的运行来源(engine/origin.py) +ORIGIN = "trial" +#: 没有关节、图原样导入的模板 +FREEFORM = "freeform" +#: 机器码(接口回 {detail, code};白话在 app/plain.py) +NOT_READY = "trial_not_ready" +NO_GRAPH = "trial_no_graph" +NO_RUN = "trial_no_run" +POLICY = "trial_policy" +FORM = "trial_form" + +NO_GRAPH_TEXT = "蓝图还没有可以运行的图:请先选场景、把卡片补齐" +NOT_READY_TEXT = "蓝图还有没补齐的地方,补齐之后才能用真数试运行" +NO_RUN_TEXT = "这个蓝图还没有试运行过,或者这次运行不是它的试运行" -async def preview_page(session: Any, blueprint: Any, *, page_id: str, run_id: str | None, principal: Any) -> dict[str, Any]: - """按这次试运行解析应用草稿的一页(agentlab.view/1),印章 from=试运行、trial=true。""" - raise NotImplementedError +class TrialRefused(Exception): + """不试运行 / 不预览:status_code 照 HTTP 语义,message 是给人看的一句话,code 是机器码,issues 是挡住它的问题 + (蓝图检查、实例化交回的,带白话)。""" + + def __init__(self, status_code: int, message: str, code: str | None = None, + issues: list[dict[str, Any]] | None = None) -> None: + super().__init__(message) + self.status_code = status_code + self.message = message + self.code = code + self.issues = issues or [] + + +@dataclass +class Materialized: + """实例化的结果(已存到蓝图上):图和哈希、关节状态、应用草稿(钉住项没有版本号)、定时任务参数、问题。""" + + graph: dict[str, Any] + graph_hash: str + joints: dict[str, Any] + app_spec: dict[str, Any] + schedule: dict[str, Any] | None + problems: list[dict[str, Any]] = field(default_factory=list) + + @property + def blocked(self) -> bool: + return any(p.get("level") == "error" for p in self.problems) + + +# -------------------------------------------------------------------------- +# 留痕 +# -------------------------------------------------------------------------- + + +async def record_event(session: AsyncSession, bp: Blueprint, op: str, data: dict[str, Any], *, + principal: Principal | None) -> None: + """蓝图的一条留痕(blueprints/store.record_event,同一个蓝图里 seq 递增),记谁、核实过没有。调用方提交。""" + from app.blueprints.store import record_event as record + + await record(session, bp, op=op, data=data, actor=principal.username if principal else None, + verified=bool(principal and principal.verified)) + + +async def last_event(session: AsyncSession, bp: Blueprint, op: str, **match: Any) -> BlueprintEvent | None: + """这个蓝图最近一条某种留痕;match 给了只要 data 里这几项对得上的。""" + rows = (await session.execute(select(BlueprintEvent).where( + BlueprintEvent.blueprint_id == bp.id, BlueprintEvent.op == op) + .order_by(BlueprintEvent.seq.desc()).limit(50))).scalars() + for row in rows: + data = row.data or {} + if all(data.get(k) == v for k, v in match.items()): + return row + return None + + +# -------------------------------------------------------------------------- +# 实例化 +# -------------------------------------------------------------------------- + + +def template_of(bp: Blueprint) -> str: + """蓝图用的模板:卡片上选的那个(从运行、工作流版本导入的记「自由形」);还没选的是空串。""" + ref = (bp.spec or {}).get("template") + if isinstance(ref, dict) and ref.get("id"): + return str(ref["id"]) + return bp.template_id or "" + + +#: 填报登记的模板 +RECORDS_TEMPLATE = "records" + + +async def materialize(session: AsyncSession, bp: Blueprint, *, principal: Principal | None) -> Materialized: + """按模板实例化,把图、图哈希、关节存到蓝图上,记一条 instantiate 留痕(带应用草稿、定时任务参数),提交。 + 交回的问题是实例化交回的(缺项、待填的关节、骨架改动、画布校验的 error)加上蓝图检查的提醒,带白话;挡不挡由调用方定。 + + 自由形导入的图原样存(不重新排版):它的哈希要和导入的那一版对得上,发布单才按哈希复用那一版,不另存一版。""" + from app.blueprints.instantiate import filled_from, instantiate + from app.blueprints.ops import blueprint_issues + from app.core.artifact_store import graph_hash + from app.plain import with_plain + + from app.blueprints.store import instantiate_context + from app.records.store import RecordsRefused + + template = template_of(bp) + if template == FREEFORM and not (bp.graph or {}).get("nodes"): + raise TrialRefused(409, NO_GRAPH_TEXT, NO_GRAPH) + # 上下文和卡片修改、填关节、发布单同一份(blueprints/store.instantiate_context):填报登记的记录表按「填什么」取或建 + # 起草这边的那一版(草稿不影响线上),图里写「键.v版本」 + try: + ctx = await instantiate_context(session, bp, create_records=True) + except RecordsRefused as e: + await session.rollback() + raise TrialRefused(422, e.message, e.code) from e + filled = filled_from(bp.spec or {}, bp.joints or {}, graph=ctx.get("graph"), records=ctx.get("records")) + result = instantiate(bp.spec or {}, filled=filled, **ctx) + graph = bp.graph if template == FREEFORM else result.graph + if not (graph or {}).get("nodes") and not any(p.get("level") == "error" for p in result.problems): + raise TrialRefused(409, NO_GRAPH_TEXT, NO_GRAPH) + digest = graph_hash(graph or {}) + app_spec = _draft_pins(result.app_spec, bp, digest) + # 实例化交回的是挡路的 error;蓝图检查里的提醒(模板版本旧了之类)另外带上 + warnings = [i for i in blueprint_issues(bp.spec or {}, for_="trial") if i.get("level") != "error"] + problems = [with_plain(p) for p in [*result.problems, *warnings]] + bp.graph, bp.graph_hash, bp.joints = graph, digest, result.joints + bp.updated_by = principal.username if principal else bp.updated_by + await record_event(session, bp, "instantiate", { + "graph_hash": digest, "template": template, "app_spec": app_spec, "schedule": result.schedule, + "joints": result.joints, "problems": problems}, principal=principal) + await session.commit() + await session.refresh(bp) + return Materialized(graph=graph, graph_hash=digest, joints=result.joints, app_spec=app_spec, + schedule=result.schedule, problems=problems) + + +def _draft_pins(app_spec: dict[str, Any], bp: Blueprint, digest: str) -> dict[str, Any]: + """草稿的钉住项:没有版本号、哈希是这张图的;有工作流的写工作流,还没有的写蓝图(apps/spec.Pin 二者写一个)。""" + spec = copy.deepcopy(app_spec) + pins = [] + for pin in spec.get("pins") or []: + pin = {k: v for k, v in pin.items() if k not in ("workflow_id", "blueprint")} + pin.update(version=None, graph_hash=digest, level=None) + pin.update({"workflow_id": bp.workflow_id} if bp.workflow_id else {"blueprint": bp.id}) + pins.append(pin) + spec["pins"] = pins + return spec + + +async def draft_app_spec(session: AsyncSession, bp: Blueprint, graph: dict[str, Any]) -> dict[str, Any]: + """按派生规则从这张图出应用草稿:预览找不到试运行时记下的那一份时用。""" + from app.apps.derive import derive_from_graph + + purpose = ((bp.spec or {}).get("purpose") or {}).get("value") + return await derive_from_graph(session, graph, name=bp.name or "未命名应用", + description=str(purpose) if isinstance(purpose, str) else "", + workflow_id=bp.workflow_id, blueprint_id=None if bp.workflow_id else bp.id) + + +async def app_spec_for(session: AsyncSession, bp: Blueprint, digest: str | None) -> tuple[dict[str, Any] | None, + dict[str, Any] | None]: + """这张图(按哈希认)实例化时记下的 (应用草稿, 定时任务参数);没有实例化过这张图为 (None, None)。""" + event = await last_event(session, bp, "instantiate", graph_hash=digest) if digest else None + if event is None: + return None, None + data = event.data or {} + return data.get("app_spec"), data.get("schedule") + + +# -------------------------------------------------------------------------- +# 试运行 +# -------------------------------------------------------------------------- + + +def trial_inputs(blueprint: Blueprint, inputs: dict[str, Any] | None) -> dict[str, Any]: + """试运行(和个人应用的刷新,blueprints/personal.refresh_inputs)的输入:看板类按「多久更新」算出最近一期 + (blueprints/instantiate.trial_inputs,和定时任务到点时渲染的是同一份),用户给的覆盖它。流程类填了示例表单的 + 不走这里,走 entry_inputs(和应用入口提交同一条路)。""" + from app.blueprints import instantiate + + try: + base = instantiate.trial_inputs(blueprint.spec or {}) + except Exception: # noqa: BLE001 - 卡片还不全、设置不成形(发布单的预检会报)时只用用户给的,缺的输入运行时照实报 + logger.warning("蓝图 %s 算不出试运行的统计期,只用用户给的输入", blueprint.id, exc_info=True) + base = {} + return {**base, **{k: v for k, v in (inputs or {}).items() if v not in (None, "")}} + + +def entry_of_draft(app_spec: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]] | None: + """应用草稿里第一个带表单的入口和它的表单(流程类:「填什么」就是它);看板类没有入口,为 None。""" + from app.apps.tree import resolve_form + + for entry in app_spec.get("entries") or []: + form = resolve_form(app_spec, (entry or {}).get("form")) if isinstance(entry, dict) else None + if isinstance(form, dict) and (form.get("properties") or {}): + return entry, form + return None + + +async def entry_inputs(blueprint: Blueprint, app_spec: dict[str, Any], inputs: dict[str, Any] | None, *, + principal: Principal) -> tuple[dict[str, Any], Any] | None: + """流程类的示例表单:用户填了入口表单里的字段,就按应用入口提交同一条路换成运行输入(apps/entries)——先按表单校验, + 表单里的文件核对是这个人在这张蓝图上传的、还没用过,占住(发起成功绑到这次运行,file_text 读得到),再按入口映射 + 出输入(常量也带上:填报登记的 mode=submit,试运行走的就是填报那条路)。没填表单字段的(看板类、只改统计期的)为 + None,按 trial_inputs。交回 (运行输入, 文件的占位)。""" + from app.apps.entries import map_inputs + from app.apps.forms import validate_form + from app.files import store as files_store + + found = entry_of_draft(app_spec) + if found is None or not inputs: + return None + entry, form = found + if not any(k in (form.get("properties") or {}) and v not in (None, "") for k, v in inputs.items()): + return None + if errors := validate_form(form, inputs): + first = errors[0] + label = ((form.get("properties") or {}).get(first.get("path")) or {}).get("title") or first.get("path") or "" + raise TrialRefused(422, f"示例表单没有通过校验:{label}{':' if label else ''}{first.get('message')}", FORM) + try: + values, claimed = await files_store.claim(form, inputs, principal=principal, + context={"blueprint_id": blueprint.id}) + except files_store.FileRefused as e: + raise TrialRefused(e.status, e.message, e.code) from e + return map_inputs(entry, values, principal), claimed + + +async def start_trial(session: AsyncSession, blueprint: Blueprint, *, inputs: dict[str, Any] | None, + principal: Principal, actor: str | None) -> tuple[Run, Materialized]: + """实例化 → 保存图到蓝图 → 发起探索运行(origin_kind=trial、origin={blueprint_id}),交回 (运行, 实例化结果)。 + 蓝图记 last_trial_run_id,留痕记 trial(带这次用的应用草稿);运行成功结束后蓝图记「试运行过」(settle)。""" + from app.api.deps import restricted + from app.engine.launch import launch_run + + result = await materialize(session, blueprint, principal=principal) + if result.blocked: + raise TrialRefused(409, NOT_READY_TEXT, NOT_READY, [p for p in result.problems if p.get("level") == "error"]) + options = None + memory_scope = None + if restricted(): + # 开登录后的使用者(个人蓝图):和问数据、个人应用同一份约束(auth/chat_policy.py,blueprints/personal.policy_problem) + from app.auth.chat_policy import chat_memory_scope + from app.blueprints.personal import policy_problem + from app.tools.datasource import MASK_RESULTS_OPTION, READ_ONLY_OPTION + + if problem := policy_problem(result.graph): + raise TrialRefused(403, problem, POLICY) + memory_scope = chat_memory_scope(actor) + options = {MASK_RESULTS_OPTION: True, READ_ONLY_OPTION: True} + from app.files import store as files_store + + submitted = await entry_inputs(blueprint, result.app_spec, inputs, principal=principal) + payload, claimed = submitted if submitted is not None else (trial_inputs(blueprint, inputs), None) + try: + run = await launch_run( + session, graph=result.graph, input_payload=payload, run_class="exploratory", + actor=actor, origin_kind=ORIGIN, origin={"blueprint_id": blueprint.id, "graph_hash": result.graph_hash, + "actor_verified": principal.verified, + "auth_mode": principal.mode}, + workflow_name=blueprint.name or None, options=options, memory_scope=memory_scope) + except BaseException: + if claimed is not None: + await files_store.release(claimed) + raise + if claimed is not None: + await files_store.finish(claimed, run.id) + blueprint.last_trial_run_id = run.id + await record_event(session, blueprint, "trial", {"run_id": run.id, "graph_hash": result.graph_hash, + "app_spec": result.app_spec}, principal=principal) + await session.commit() + await session.refresh(blueprint) + return run, result + + +def is_trial_of(run: Run | None, bp: Blueprint) -> bool: + return run is not None and run.origin_kind == ORIGIN and (run.origin or {}).get("blueprint_id") == bp.id + + +async def settle(session: AsyncSession, bp: Blueprint) -> Blueprint: + """最近一次试运行成功结束了、蓝图还记着「起草中」:改记「试运行过」(读蓝图、预览、出发布单时顺带看一眼, + 不在运行收尾时回调蓝图——引擎不认识蓝图)。""" + if bp.status != "drafting" or not bp.last_trial_run_id: + return bp + status = await session.scalar(select(Run.status).where(Run.id == bp.last_trial_run_id)) + if status == "succeeded": + bp.status = "trialed" + await session.commit() + await session.refresh(bp) + return bp + + +# -------------------------------------------------------------------------- +# 预览 +# -------------------------------------------------------------------------- + + +@dataclass +class PreviewApp: + """预览用的「应用」:还没有应用(或者有,但预览的是蓝图上的草稿)。resolve_page 要的几样:id、名字、草稿。""" + + id: str + name: str + draft: dict[str, Any] + published_version: int | None = None + status: str = "active" + + +async def preview_page(session: AsyncSession, blueprint: Blueprint, *, page_id: str | None, run_id: str | None, + principal: Principal) -> dict[str, Any]: + """按这次试运行解析应用草稿的一页(agentlab.view/1),印章 from=试运行、trial=true。run_id 不给就是最近一次。 + 草稿用这次试运行时记下的那一份(之后改了卡片,预览的仍是这次运行对应的样子)。""" + from app.apps.resolve import resolve_page + from app.apps.tree import page_of + + run = await session.get(Run, run_id or blueprint.last_trial_run_id or "") + if not is_trial_of(run, blueprint): + raise TrialRefused(404, NO_RUN_TEXT, NO_RUN) + assert run is not None + await settle(session, blueprint) + event = await last_event(session, blueprint, "trial", run_id=run.id) + spec = (event.data or {}).get("app_spec") if event is not None else None + if not isinstance(spec, dict): + spec = await draft_app_spec(session, blueprint, run.graph or {}) + pages = [p for p in spec.get("pages") or [] if isinstance(p, dict) and p.get("id")] + wanted = page_id or (pages[0]["id"] if pages else "home") + if page_of(spec, wanted) is None: + from app.apps.resolve import ViewRefused + + raise ViewRefused(404, f"应用里没有页面「{wanted}」", "app_page_not_found") + app = PreviewApp(id=blueprint.app_id or blueprint.id, name=blueprint.name, draft=spec) + return await resolve_page(session, app, page_id=wanted, principal=principal, role="manage", draft=True, + trial=run, actor=principal.username) diff --git a/backend/app/capabilities/platform.py b/backend/app/capabilities/platform.py new file mode 100644 index 00000000..eb3fda5a --- /dev/null +++ b/backend/app/capabilities/platform.py @@ -0,0 +1,73 @@ +"""平台内置能力(docs/design/normal-user-apps.md N8、N9):平台自己执行的写入,接进动作的同一条路径。 + +写外部系统的能力由平台执行器按登记的端点发请求(capabilities/endpoints.py);这里的几项不发请求,由平台自己执行, +但生效记录、幂等键、发送确认、结果未知转核实全部沿用 process/actions.py——调用工具节点认得出它们是写入(能力登记里 +效果为 write),走的就是 prepare → (确认)→ send,send 调 registry.endpoint_request,那里按名字转到 execute。 + +| 能力 | 效果 | 治理默认 | 做什么 | +| records_append | 写入 | 允许无人值守、查询能力 records_lookup | 往记录表追加一行(records/actions.py),幂等键就是动作键 | +| records_lookup | 只读 | | 按幂等键查那一行写没写下(结果未知时 actions._lookup 调) | +| table_import_period | 写入 | 要人确认 | 按上传源已有的配方把一个文件导入成一期(files/imports.py) | + +环境:正式运行写真的;探索运行(试运行、个人应用)在 actions.prepare 里就定成演练——这几项没有测试环境,一行都不写。 +治理默认只在登记里第一次出现这一行时写进去,之后管理员改了算管理员的。 +""" +from __future__ import annotations + +from typing import Any + +from app.files import TABLE_IMPORT_PERIOD +from app.records import RECORDS_APPEND, RECORDS_LOOKUP + +#: 平台执行的能力 +PLATFORM_CAPABILITIES = (RECORDS_APPEND, RECORDS_LOOKUP, TABLE_IMPORT_PERIOD) +#: 登记里新出现这一行时写进去的治理字段 +GOVERNANCE_DEFAULTS: dict[str, dict[str, Any]] = { + # 平台自己的表、一次提交只落一行、重放不会重复写:允许无人值守(填报登记不该每条都等人确认) + RECORDS_APPEND: {"unattended_write": True, "lookup": RECORDS_LOOKUP}, + # 换掉一个数据源的数据:要人确认 + TABLE_IMPORT_PERIOD: {"unattended_write": False}, +} +#: 写入能力 → 它的查询能力(平台按幂等键替它查)。治理里只许选这一对,同端点上的只读能力那条规矩管不到平台能力 +LOOKUPS = {RECORDS_APPEND: RECORDS_LOOKUP} + + +def is_platform(name: str | None) -> bool: + return bool(name) and name in PLATFORM_CAPABILITIES + + +def lookup_allowed(name: str, lookup: str) -> bool: + """治理时给平台能力选的查询能力对不对。""" + return LOOKUPS.get(name) == lookup + + +async def execute(session: Any, capability: Any, args: dict[str, Any], *, environment: str, + idem_key: str | None = None, on_behalf: Any = None, run_id: str | None = None, + node_id: str | None = None) -> Any: + """平台能力的执行器,交回和端点请求一样的 EndpointResult:2xx 生效、status 为空且不是 unknown 为确定没有生效 + (error 写原因,actions.send 照实说「没有写入」),404 是查询能力没查到。""" + from app.capabilities.registry import EndpointResult + + name = getattr(capability, "name", None) or str(capability) + if name == RECORDS_APPEND: + from app.records.actions import append_action + + return await append_action(args, idem_key=idem_key, run_id=run_id, on_behalf=on_behalf, + environment=environment) + if name == RECORDS_LOOKUP: + from app.records.actions import lookup_action + + return await lookup_action(args, environment=environment) + if name == TABLE_IMPORT_PERIOD: + from app.files.imports import import_period_action + + return await import_period_action(args, run_id=run_id, on_behalf=on_behalf, environment=environment) + return EndpointResult(status=None, body=None, error=f"「{name}」不是平台能力", environment=environment) + + +def actor_of(on_behalf: Any) -> str | None: + """写记录、签导入记哪个人:身份断言里的 sub(运行的发起人:这件事是替他办的)。""" + if isinstance(on_behalf, dict): + sub = on_behalf.get("sub") + return str(sub) if sub else None + return str(on_behalf) if on_behalf else None diff --git a/backend/app/capabilities/registry.py b/backend/app/capabilities/registry.py index 17928768..45e4314d 100644 --- a/backend/app/capabilities/registry.py +++ b/backend/app/capabilities/registry.py @@ -25,6 +25,8 @@ from typing import Any from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession +from app.capabilities.platform import GOVERNANCE_DEFAULTS + @dataclass(frozen=True) class EndpointResult: @@ -44,6 +46,9 @@ GOVERNED_FIELDS = ("effect", "approval", "unattended_write", "returns_schema", " "credential_mode", "lookup", "endpoint_id") #: 同步时写的字段(source_hash 只按它们算) _SYNCED_FIELDS = ("system", "title", "description", "params_schema", "effect_system") +#: 新插入的行一律带上这几项(平台能力的治理默认会改其中几项):一条 INSERT 插多行时各行的键要一样, +#: 不然后面几行多出来的键会被丢掉 +_FRESH_DEFAULTS = {"unattended_write": False, "lookup": None} #: 登记的进程内快照:同步、治理、端点改动时重算(refresh_cache)。is_platform_query 跑在节点的热路径上、发布检查 #: (engine/lint_capabilities.py)是同步函数,都不能每次查库 @@ -79,9 +84,10 @@ async def _discover(session: AsyncSession) -> dict[str, dict[str, Any]]: found: dict[str, dict[str, Any]] = {} for name, spec in all_specs().items(): + # 平台内置的写入能力(records_append、table_import_period)自己声明效果为 write(capabilities/platform.py) found[name] = {"system": "builtin", "title": name, "description": spec.description, "params_schema": _json_schema(spec.args_schema), - "effect_system": "dynamic" if spec.dangerous or spec.writes_state else "read"} + "effect_system": spec.effect or ("dynamic" if spec.dangerous or spec.writes_state else "read")} for src in (await session.execute(select(DataSource))).scalars(): found[f"{QUERY_PREFIX}{src.name}"] = { @@ -136,8 +142,10 @@ async def sync_all(session: AsyncSession) -> int: digest = _hash({**synced, "endpoint_id": item.get("endpoint_id")}) row = existing.get(name) if row is None: + # 平台能力第一次进登记时带上治理默认(records_append 允许无人值守、查询能力是 records_lookup),之后照管理员改的 fresh.append({"name": name, **synced, "source_hash": digest, "synced_at": now, - "endpoint_id": item.get("endpoint_id")}) + "endpoint_id": item.get("endpoint_id"), **_FRESH_DEFAULTS, + **GOVERNANCE_DEFAULTS.get(name, {})}) elif row.source_hash != digest or row.missing: for key, value in synced.items(): setattr(row, key, value) @@ -239,10 +247,12 @@ def governance_of(capability: Any) -> dict[str, Any]: "lookup": capability.lookup, "credential_mode": capability.credential_mode or "service"} -def _default_governance(item: dict[str, Any]) -> dict[str, Any]: - """还没进登记表的能力(刚建的数据源,登记还没同步到)按同步得出的样子算:没人治理过,版本是新行的 1。""" +def _default_governance(item: dict[str, Any], name: str = "") -> dict[str, Any]: + """还没进登记表的能力(刚建的数据源,登记还没同步到)按同步得出的样子算:没人治理过,版本是新行的 1。 + 平台能力带上它的治理默认(同 sync_all 插入新行时)。""" return {"effect": item["effect_system"], "approval": "inherit", "unattended_write": False, "version": 1, - "endpoint_id": item.get("endpoint_id"), "masked": [], "lookup": None, "credential_mode": "service"} + "endpoint_id": item.get("endpoint_id"), "masked": [], "lookup": None, "credential_mode": "service", + **GOVERNANCE_DEFAULTS.get(name, {})} async def _governed_rows(session: AsyncSession, tool_names: list[str]) -> dict[str, dict[str, Any]]: @@ -257,7 +267,7 @@ async def _governed_rows(session: AsyncSession, tool_names: list[str]) -> dict[s (await session.execute(select(Capability).where(Capability.name.in_(names)))).scalars()} if missing := [n for n in names if n not in out]: found = await _discover(session) - out.update({n: _default_governance(found[n]) for n in missing if n in found}) + out.update({n: _default_governance(found[n], n) for n in missing if n in found}) return out @@ -303,7 +313,12 @@ async def endpoint_request(session: AsyncSession, capability: Any, args: dict[st """平台执行器:按登记的端点发请求(只认登记的 base_url,参数按路径段编码代入),声明了 tabular 的读取落快照。 实现在 capabilities/endpoints.py。tool:按这一行自定义工具拼请求(工具页试运行的草稿),不给按能力名找已保存的。""" from app.capabilities.endpoints import endpoint_request as run + from app.capabilities.platform import execute, is_platform + if tool is None and is_platform(getattr(capability, "name", None)): + # 平台内置能力(记录表、导入一期):平台自己执行,不发请求;生效记录、幂等、确认照旧在动作流程里 + return await execute(session, capability, args, environment=environment, idem_key=idem_key, + on_behalf=on_behalf, run_id=run_id, node_id=node_id) return await run(session, capability, args, environment=environment, idem_key=idem_key, on_behalf=on_behalf, run_id=run_id, node_id=node_id, tool=tool) @@ -380,9 +395,15 @@ async def _check_lookup(session: AsyncSession, name: str, endpoint_id: str | Non (endpoint_request),所以只能是同一个端点上、绑定端点的只读能力:写记忆这类平台自身的写、别的系统上的读取、 MCP 和 Python 工具都查不了这一笔写入。能力页的候选按同一条规矩列。""" from app.capabilities.endpoints import bound_endpoint_ref + from app.capabilities.platform import is_platform, lookup_allowed from app.db.models import Capability, CustomTool ref = str(lookup) + if is_platform(name): + # 平台能力的查询能力也由平台执行,只认登记好的那一对(records_append → records_lookup) + if not lookup_allowed(name, ref): + raise GovernanceError("平台能力的查询能力只能是平台为它准备的那一项") + return finder = await session.get(Capability, ref) tool = (await session.execute(select(CustomTool).where(CustomTool.name == ref))).scalar_one_or_none() if (ref == name or finder is None or finder.missing or effective_effect(finder) != "read" or tool is None diff --git a/backend/app/data/engine.py b/backend/app/data/engine.py index 505294ab..1aac53f9 100644 --- a/backend/app/data/engine.py +++ b/backend/app/data/engine.py @@ -928,8 +928,20 @@ async def run_query( """ limits = limits or QueryLimits(timeout_seconds=query_timeout(source)) kind = (source.kind or "").lower() + if (getattr(source, "origin", None) or "manual") == "records" and not getattr(source, "prelude", None): + # 记录表(docs/design/normal-user-apps.md N8)没经解析就拿来查(数据剖析这类入口):照样走临时视图, + # 底表里的幂等键、被更正的行不露出来 + from app.records.views import default_view + + source = default_view(source) # 按数据源的方言扫:MySQL 的反斜杠转义、PG 的 $$ 字符串,守卫要和数据库读得一样 statement = check(sql, readonly=bool(source.readonly), source_name=source.name, dialect=kind) + if forbidden := tuple(getattr(source, "forbid_schemas", None) or ()): + # 记录表靠连接上的同名临时视图钉版本、分行可见:写了 main.<表> 就绕过了视图(records/views.py) + if hit := guard.schema_reference(statement, forbidden, dialect=kind): + raise SqlRejected(f"「{source.name}」只能按表名查询(如 FROM records),不能在表名前加库名「{hit}.」:" + "这张表只给看这次运行能看的那些行") + prelude: tuple[str, ...] = tuple(getattr(source, "prelude", None) or ()) engine = await engines.get(source) started = time.perf_counter() @@ -938,6 +950,10 @@ async def run_query( return await _run_write(engine, kind, statement, limits, started) async def _read(conn: AsyncConnection) -> tuple[list[str], list[list[Any]], bool, dict[str, str]]: + # 连接上先执行的语句(记录表的同名临时视图)。按驱动原样执行,不经 text():视图里拼着看的人的名字, + # 名字里的冒号不能被当成绑定参数 + for stmt in prelude: + await conn.exec_driver_sql(stmt) cursor = await conn.stream(text(statement)) columns = list(cursor.keys()) collected = RowCollector(limits) diff --git a/backend/app/data/guard.py b/backend/app/data/guard.py index 399ef994..466af990 100644 --- a/backend/app/data/guard.py +++ b/backend/app/data/guard.py @@ -471,3 +471,39 @@ def is_write(sql: str, *, dialect: str | None = None) -> bool: if not statements: return True return any(_write_reason(s, r) is not None for s in statements for r in readings) + + +#: 代码段里的一个词或一个符号(schema_reference 用) +_ATOM = re.compile(r"\w+|\S") + + +def _ident_name(token: _Token) -> str: + """带引号的标识符 → 名字本身("ma""in" → ma"in,[main] → main)。""" + end = len(token.text) - token.close if token.close else len(token.text) + inner = token.text[token.open:end] + quote = token.text[:token.open] + return inner.replace(quote * 2, quote) if quote in ('"', "`") else inner + + +def schema_reference(sql: str, schemas: tuple[str, ...] | list[str], *, dialect: str | None = None) -> str | None: + """SQL 里有没有直接写这些库名加点(main.records、"main"."records"、[main].records……):有就交回写的那个库名。 + + 记录表靠连接上的同名临时视图做钉版本和行级可见(records/store.view_prelude):不带库名的表名先找 temp 库,查到的 + 是视图;写了 main. 就绕过视图看到了底表。所以这一类源(data/engine.run_query 的 forbid_schemas)一律拒。按扫描出的 + 词判断:字符串、注释里的 main. 不算;带引号的写法算。每种读法都扫一遍,任何一种读出来有就算有。""" + wanted = {s.lower() for s in schemas if s} + if not wanted: + return None + for reading in _readings(dialect): + atoms: list[str] = [] + for token in _tokens(sql, reading): + if token.kind == "code": + atoms += [a.lower() for a in _ATOM.findall(token.text)] + elif token.kind == "ident": + atoms.append(_ident_name(token).lower()) + elif token.kind in ("string", "sep"): + atoms.append(token.kind) + for name, nxt in zip(atoms, atoms[1:]): + if name in wanted and nxt == ".": + return name + return None diff --git a/backend/app/data/raw_store.py b/backend/app/data/raw_store.py index 8e18d5db..a6a818d9 100644 --- a/backend/app/data/raw_store.py +++ b/backend/app/data/raw_store.py @@ -65,8 +65,14 @@ def put_raw(raw: bytes) -> tuple[str, Path]: 已有文件的哈希对不上(磁盘损坏、被人改过)时,用这次的字节原子替换掉它:路径本身就是 内容的哈希,这次手里的字节才是这个名字应有的内容。 """ + return put_addressed(raw, raw_root()) + + +def put_addressed(raw: bytes, root: Path) -> tuple[str, Path]: + """按内容哈希存进 root/<前两位>/,只读(0444),返回 (sha256, 路径)。原件存档和上传的文件 + (files/store.py,docs/design/normal-user-apps.md N9)共用这一种写法,见 put_raw。""" sha = hashlib.sha256(raw).hexdigest() - path = raw_path(sha) + path = root / sha[:2] / sha if path.is_file() and sha256_file(path) == sha: return sha, path path.parent.mkdir(parents=True, exist_ok=True) diff --git a/backend/app/data/table_versions.py b/backend/app/data/table_versions.py index c2e2e575..2407d0e3 100644 --- a/backend/app/data/table_versions.py +++ b/backend/app/data/table_versions.py @@ -560,8 +560,11 @@ def reaches_app_files(path: str | None) -> bool: 可写的沙箱根目录,登记模型生成的库是正当用法。 """ data = settings.data_dir + # records、files:记录表和上传文件(docs/design/normal-user-apps.md N8、N9)。记录表由平台登记成只读源、按行级可见查, + # 手工登记过去就绕开了钉版本和行级可见;上传的文件按绑定的运行核对读权限 return _reaches(path, _zone( - [data / "artifacts", data / "sandbox-policies"], [*_app_db_files(), data / ".secret_key"])) + [data / "artifacts", data / "sandbox-policies", data / "records", data / "files"], + [*_app_db_files(), data / ".secret_key"])) def report_to_json(report: Any) -> dict[str, Any]: @@ -2625,7 +2628,8 @@ async def _disable_manual_app_files(session: AsyncSession) -> int: select(DataSource).where( DataSource.kind == "sqlite", or_(DataSource.enabled.is_(True), DataSource.readonly.is_(False)), - or_(DataSource.origin.is_(None), DataSource.origin != "upload"), + # 记录表(origin=records)的文件就在应用的数据目录里,是平台自己登记的只读源,不在此列 + or_(DataSource.origin.is_(None), DataSource.origin.not_in(("upload", "records"))), ) )).scalars()) hit = [row for row in rows if reaches_app_files(row.database)] diff --git a/backend/app/engine/compiler.py b/backend/app/engine/compiler.py index ec3e5dfd..c9c115de 100644 --- a/backend/app/engine/compiler.py +++ b/backend/app/engine/compiler.py @@ -11,6 +11,7 @@ from langgraph.graph import END, START, StateGraph from app.core.errors import describe_exception, raw_detail from app.core.events import EventType from app.engine.context import NodeContext, NodeError, RunContext +from app.engine.expressions import open_template_scope, template_scope from app.engine.nodes import ( challenge, control, dual_check, human, io, knowledge, llm, merge, metrics, multi, report, tools, ) @@ -83,7 +84,9 @@ def _wrap( last_error: Exception | None = None for attempt in range(retries + 1): try: - updates = await runner(state, ctx) + # 模板函数(file_text)要知道在哪次运行、哪个节点:执行期间设好(engine/expressions.template_scope) + with template_scope(await open_template_scope(ctx)): + updates = await runner(state, ctx) elapsed = int((time.perf_counter() - started) * 1000) # 完整输出落工件库。事件里只放截断预览是给画布看的; diff --git a/backend/app/engine/expressions.py b/backend/app/engine/expressions.py index 9cc4364f..68c35138 100644 --- a/backend/app/engine/expressions.py +++ b/backend/app/engine/expressions.py @@ -1,11 +1,16 @@ from __future__ import annotations import ast +import importlib import json import math import operator import re -from typing import Any +from collections.abc import Iterator +from contextlib import contextmanager +from contextvars import ContextVar +from dataclasses import dataclass, field +from typing import Any, Callable # -------------------------------------------------------------------------- # 变量插值: {{ input.query }} / {{ nodes.n1.text }} / {{ vars.items | json }} @@ -70,8 +75,102 @@ def _stringify(value: Any) -> str: return str(value) +# -------------------------------------------------------------------------- +# 模板函数:{{ file_text(input.附件) }} / {{ file_text(input.附件, 8000) }} +# -------------------------------------------------------------------------- + +#: 模板里能调的函数:名字 → 「模块:函数」,用到时才导入(模板引擎不依赖文件存储)。参数是路径(input.附件)、数或 +#: 带引号的文字;函数要知道自己在哪次运行、哪个节点(发事件、核对绑定的文件),从 TEMPLATE_SCOPE 取 +TEMPLATE_FUNCTIONS: dict[str, str] = {"file_text": "app.files.text:file_text"} +#: 模板函数的准备:节点配置里用到这个函数时,执行前先异步做的事(模板渲染是同步的,读库只能放在这里)。 +#: 名字 → 「模块:函数」,函数收 TemplateScope +TEMPLATE_PREPARERS: dict[str, str] = {"file_text": "app.files.text:prepare"} +_CALL = re.compile(r"^([A-Za-z_]\w*)\s*\((.*)\)$", re.S) +_ARG_NUMBER = re.compile(r"^[+-]?\d+(?:\.\d+)?$") + + +@dataclass +class TemplateScope: + """一次节点执行里渲染模板的运行上下文:node 是 NodeContext(运行、节点、发事件),memo 给模板函数记这一次执行里 + 已经做过的事(同一个附件同一个上限只抽一次、只发一条事件)。""" + + node: Any + memo: dict[str, Any] = field(default_factory=dict) + + +TEMPLATE_SCOPE: ContextVar[TemplateScope | None] = ContextVar("agentlab_template_scope", default=None) + + +async def open_template_scope(node: Any) -> TemplateScope: + """一次节点执行的模板上下文:节点配置(连同图级默认)里用到哪个模板函数,就先做它的准备(TEMPLATE_PREPARERS, + 例如读这次运行绑定的文件)。每次执行现做:回复待办时新绑上的文件,恢复之后的这一次执行就看得到。""" + scope = TemplateScope(node) + text = json.dumps([getattr(node, "config", None), getattr(getattr(getattr(node, "run", None), "spec", None), + "defaults", None)], ensure_ascii=False, default=str) + for name, target in TEMPLATE_PREPARERS.items(): + if f"{name}(" in text: + module, _, attr = target.partition(":") + await getattr(importlib.import_module(module), attr)(scope) + return scope + + +@contextmanager +def template_scope(scope: TemplateScope) -> Iterator[TemplateScope]: + """节点执行期间设好模板的运行上下文(engine/compiler.py 包在每次执行外面)。不在节点里渲染时没有它,模板函数 + 照实说「运行时才读取」。""" + token = TEMPLATE_SCOPE.set(scope) + try: + yield scope + finally: + TEMPLATE_SCOPE.reset(token) + + +def template_call(expr: str) -> tuple[str, list[str]] | None: + """`file_text(input.附件, 8000)` → ("file_text", ["input.附件", "8000"]);不是登记过的模板函数为 None。 + 变量检查(engine/variables.py)按它认出函数里引用的路径。""" + m = _CALL.match(expr.strip()) + if not m or m.group(1) not in TEMPLATE_FUNCTIONS: + return None + args = [a.strip() for a in _split_args(m.group(2))] + return m.group(1), [a for a in args if a] + + +def _split_args(text: str) -> list[str]: + """按顶层逗号切参数:引号、括号、方括号里的逗号不算。""" + out: list[str] = [] + depth, quote, start = 0, "", 0 + for i, ch in enumerate(text): + if quote: + if ch == quote: + quote = "" + elif ch in "'\"": + quote = ch + elif ch in "([": + depth += 1 + elif ch in ")]": + depth -= 1 + elif ch == "," and depth == 0: + out.append(text[start:i]) + start = i + 1 + out.append(text[start:]) + return out + + +def _arg_value(arg: str, ctx: dict[str, Any]) -> Any: + if _ARG_NUMBER.match(arg): + return float(arg) if "." in arg else int(arg) + if len(arg) >= 2 and arg[0] == arg[-1] and arg[0] in "'\"": + return arg[1:-1] + return resolve_path(ctx, arg) + + +def _function(name: str) -> Callable[..., Any]: + module, _, attr = TEMPLATE_FUNCTIONS[name].partition(":") + return getattr(importlib.import_module(module), attr) + + def render_template(text: str, ctx: dict[str, Any]) -> str: - """把字符串里的 {{ ... }} 全部替换掉。支持 `路径 | 过滤器` 语法。""" + """把字符串里的 {{ ... }} 全部替换掉。支持 `路径 | 过滤器` 语法,以及登记过的模板函数(TEMPLATE_FUNCTIONS)。""" if not text or "{{" not in text: return text or "" @@ -79,8 +178,13 @@ def render_template(text: str, ctx: dict[str, Any]) -> str: expr = match.group(1).strip() if not expr: return "" + call = template_call(expr.split("|")[0]) if "(" in expr else None parts = [p.strip() for p in expr.split("|")] - value = resolve_path(ctx, parts[0]) + if call is not None: + name, args = call + value = _function(name)(*(_arg_value(a, ctx) for a in args)) + else: + value = resolve_path(ctx, parts[0]) for filt in parts[1:]: fn = _FILTERS.get(filt) if fn: diff --git a/backend/app/engine/inquiry.py b/backend/app/engine/inquiry.py index 99556f11..4941a80e 100644 --- a/backend/app/engine/inquiry.py +++ b/backend/app/engine/inquiry.py @@ -703,7 +703,8 @@ async def _usable_sources(run_id: str, names: Iterable[str], versions: Any) -> d known = used.get(str(name)) if known and str(source_id) not in known: continue - if (origin or "manual") == "upload" and pins is not None and source_id not in pins: + # 记录表(origin=records)同理:没固定过高水位的,建工具时会补固定进运行记录 + if (origin or "manual") in ("upload", "records") and pins is not None and source_id not in pins: continue out[str(name)] = masked_columns(options) return out diff --git a/backend/app/engine/launch.py b/backend/app/engine/launch.py index 27341d4d..4e71dc26 100644 --- a/backend/app/engine/launch.py +++ b/backend/app/engine/launch.py @@ -69,6 +69,7 @@ async def launch_run( app_id: str | None = None, app_version: int | None = None, expect_hash: str | None = None, + workflow_name: str | None = None, ) -> Run: """发起一次运行,返回刚建好的运行记录(执行已经交给 run_manager)。不发起就抛 LaunchRefused;抛别的异常时 运行也没有开始执行。 @@ -83,12 +84,13 @@ async def launch_run( (run_version_unpublished),退役的拒绝(run_version_retired)。 - 用到的能力的治理快照写进 options["capabilities"];能力版本相对发布时有变化只记一条提醒(capability_drift)。 - 参数和 POST /api/runs 的请求体一一对应(input 叫 input_payload);actor 是记在运行上的发起人。 + 参数和 POST /api/runs 的请求体一一对应(input 叫 input_payload);actor 是记在运行上的发起人。workflow_name 是没挂在 + 工作流上的探索运行记在运行上的名字(蓝图的试运行写蓝图名),不给就是「未保存的工作流」;挂在工作流上的用工作流的名字。 schedule_id 是发起它的定时任务,options 是整次运行沿用的选项快照,都原样交给 run_manager.start;图里有双盲复算、 反方审稿节点时 options 另加核查设置的快照(_with_verify_snapshot)。 """ # 没挂在工作流上(画布没保存就发起、问数据当场搭的)。老数据里是「临时图」,前端两种都认 - name = "未保存的工作流" + name = workflow_name or "未保存的工作流" run_version: int | None = None version_hash: str | None = None governed = False diff --git a/backend/app/engine/runner.py b/backend/app/engine/runner.py index fe4b45a4..ef22bd1e 100644 --- a/backend/app/engine/runner.py +++ b/backend/app/engine/runner.py @@ -28,6 +28,7 @@ from app.engine.deadline import segment from app.engine.replay import PROTOCOL, PROTOCOL_KEY, protocol_of from app.engine.schema import GraphSpec, NodeType, loop_steps, topology_of, validate_graph from app.process.actions import ActionPending +from app.records.views import scope_entries from app.tools.datasource import RUN_VERSIONS_KEY logger = logging.getLogger(__name__) @@ -244,6 +245,8 @@ class RunManager: # 看不到这条还没提交的运行,会把刚固定的快照删掉(table_versions.pin_lock) async with pin_lock(): data_versions = await _data_versions(session, spec) + # 记录表这次运行看哪些行:正式运行看全部,别的按发起人的授权(records/views.scope_entries) + await scope_entries(session, data_versions, run_class=run_class, started_by=started_by) run = Run( workflow_id=workflow_id, workflow_name=workflow_name, @@ -1177,8 +1180,13 @@ async def _data_versions(session: Any, spec: GraphSpec) -> dict[str, Any]: 发起时算不到的(继续运行时改了节点配置、没固定版本的子工作流中途被改过、运行中途新建的源) 由数据源工具第一次用到时补上(tools/datasource.py 的 _pin_late,记进运行记录并发一条日志事件)。 没用到任何上传源时返回空 dict 而不是 None:None 留给升级前发起的运行(照旧用当前版本,不补固定)。 + + 记录表(origin=records,docs/design/normal-user-apps.md N8)同样在这里固定高水位:{"seq": 高水位, …} + (records/views.pin_entry)。这次运行看哪些行由发起处另外记上(records/views.scope_entries):按需视图的缓存键 + 只要高水位。 """ from app.db.models import DataSource + from app.records.views import pin_entry names, anything = await _bound_sources(session, spec) if not names and not anything: @@ -1190,7 +1198,15 @@ async def _data_versions(session: Any, spec: GraphSpec) -> dict[str, Any]: if not anything: query = query.where(DataSource.name.in_(sorted(names))) rows = (await session.execute(query)).all() - return {sid: {"snapshot": snap, "name": name} for sid, name, snap in rows} + out: dict[str, Any] = {sid: {"snapshot": snap, "name": name} for sid, name, snap in rows} + records = select(DataSource).where(DataSource.enabled.is_(True), DataSource.origin == "records") \ + .order_by(DataSource.name) + if not anything: + records = records.where(DataSource.name.in_(sorted(names))) + for source in (await session.execute(records)).scalars(): + if (entry := await pin_entry(session, source)) is not None: + out[source.id] = entry + return out async def _bound_sources(session: Any, spec: GraphSpec) -> tuple[set[str], bool]: diff --git a/backend/app/engine/variables.py b/backend/app/engine/variables.py index 8f95a20d..137b4b0a 100644 --- a/backend/app/engine/variables.py +++ b/backend/app/engine/variables.py @@ -182,8 +182,13 @@ def _iter_strings(value: Any, prefix: str = "") -> list[tuple[str, str]]: def _root_of(expr: str) -> tuple[str, str]: - """把 `vars.sales | json` 拆成 ('vars.sales', 'vars')。""" + """把 `vars.sales | json` 拆成 ('vars.sales', 'vars')。模板函数(`file_text(input.附件, 8000)`)按它的第一个 + 参数认:引用的是 input.附件。""" + from app.engine.expressions import template_call + path = expr.split("|")[0].strip() + if "(" in path and (call := template_call(path)) is not None: + path = call[1][0] if call[1] else "" # 去掉下标,vars.rows[0].name → vars.rows.name clean = re.sub(r"\[[^\]]*\]", "", path) root = clean.split(".")[0].strip() diff --git a/backend/app/files/__init__.py b/backend/app/files/__init__.py index ad60c349..dd9b879f 100644 --- a/backend/app/files/__init__.py +++ b/backend/app/files/__init__.py @@ -3,7 +3,8 @@ 读文件:模板函数 file_text(ref);导入:平台内置能力 table_import_period(按上传源已有的配方导入一期,效果写入)。 下载按绑定的运行或记录核对读权限。没绑定的上传 24 小时后清理。 -包 B3 实现。 +模块:store(存放、上传上下文、绑定、读权限、删除、清理)、text(模板函数 file_text)、imports(平台能力 +table_import_period 的执行);接口在 api/files.py。 """ from __future__ import annotations diff --git a/backend/app/files/imports.py b/backend/app/files/imports.py new file mode 100644 index 00000000..6e1d11d4 --- /dev/null +++ b/backend/app/files/imports.py @@ -0,0 +1,90 @@ +"""平台内置能力 table_import_period:把一个上传的文件按数据源已有的配方导入成新的一期(docs/design/normal-user-apps.md N9)。 + +内核就是数据页的「上传新一期」(data/recipe_imports.reupload:原件存档、按当前配方自动试运行,不调模型),试运行通过、 +没有要人勾的确认项、没有要写理由的核对时接着提交(commit_staging)。效果是写入(换掉数据源的当前数据),走动作和确认: +调用工具节点先开确认卡,人确认之后才执行到这里。 + +要人判断的情形不替人做主:试运行没通过、有必勾的确认项(单位变了、表结构变了、统计期要录入……)、有没通过要写理由的 +核对——照实拒绝,说清要去数据页确认哪几项;这次的暂存留着,在数据页的导入里接着做。 + +只认这次运行绑定的文件(提交入口、回复待办时绑上的),不能凭一个文件编号导入别人的文件。 +""" +from __future__ import annotations + +import asyncio +from typing import Any + +from sqlalchemy import select + +from app.db.base import SessionLocal + + +def _result(status: int | None, body: Any = None, *, error: str | None = None, environment: str = "prod") -> Any: + from app.capabilities.registry import EndpointResult + + return EndpointResult(status=status, body=body, error=error, environment=environment) + + +async def import_period_action(args: dict[str, Any], *, run_id: str | None, on_behalf: Any, environment: str) -> Any: + from app.data import recipe_imports, table_versions + from app.data.tabular import UnsupportedTable + from app.db.models import DataSource + from app.db.models_blueprints import StoredFile + from app.files.store import as_ref, read_blob + + ref = as_ref(args.get("file")) + if ref is None and isinstance(args.get("file"), str) and args["file"].strip(): + ref = {"file_id": args["file"].strip()} + if ref is None: + return _result(None, error="没有拿到要导入的文件", environment=environment) + name = str(args.get("source") or "").strip() + signer = _signer(on_behalf) + async with SessionLocal() as session: + row = await session.get(StoredFile, ref["file_id"]) + if row is None or not run_id or row.bound_run_id != run_id: + return _result(None, error="要导入的文件没有随这次运行提交,不能导入", environment=environment) + raw = await asyncio.to_thread(read_blob, row.sha256) + if raw is None: + return _result(None, error="要导入的文件内容不在了,或者和登记的不一致", environment=environment) + source = (await session.execute(select(DataSource).where(DataSource.name == name))).scalar_one_or_none() + if source is None or (source.origin or "manual") != "upload" or not source.current_recipe_id: + return _result(None, error=f"「{name}」不是按配方导入的上传表格,不能按配方导入一期", environment=environment) + try: + staging = await recipe_imports.reupload(session, source, raw=raw, filename=row.name, signed_by=signer) + blocked = _needs_people(staging) + if blocked: + return _result(None, error=f"这一期要在「数据」页由人确认后才能导入:{blocked}。这次导入已经暂存," + f"在数据源「{name}」的导入里接着做", environment=environment) + done = await recipe_imports.commit_staging( + session, staging, trial_id=str((staging.trial or {}).get("trial_id") or ""), confirmations=[], + acceptances=[], signed_by=signer) + except (recipe_imports.ImportRefused, table_versions.StoreUnavailable) as e: + return _result(None, error=getattr(e, "message", None) or str(e), environment=environment) + except UnsupportedTable as e: + return _result(None, error=f"文件读不出表格:{e}", environment=environment) + return _result(200, {"source": name, "file": ref["file_id"], "import_id": done.import_id, + "snapshot_id": done.snapshot_id, "unchanged": done.unchanged, "parts": done.parts}, + environment=environment) + + +def _signer(on_behalf: Any) -> str | None: + """导入记录上签谁:确认这次导入的人;无人值守的(没人确认)签运行的发起人。""" + if isinstance(on_behalf, dict): + return str(on_behalf.get("act") or on_behalf.get("sub") or "") or None + return str(on_behalf) if on_behalf else None + + +def _needs_people(staging: Any) -> str: + """要人判断的地方(试运行没通过、必勾的确认项、要写理由的核对),用一句话列出;没有为空串。""" + trial = staging.trial if isinstance(staging.trial, dict) else {} + if not trial: + return "按当前配方没能试运行(配方有问题或文件读不出)" + if trial.get("status") != "passed": + return "试运行没有通过" + items = [str(i.get("label") or i.get("id")) for i in trial.get("confirm_items") or [] + if isinstance(i, dict) and i.get("required")] + if items: + return "确认 " + ";".join(items[:5]) + (f" 等 {len(items)} 项" if len(items) > 5 else "") + if trial.get("acceptable"): + return "有没通过的核对,需要写明接受的理由" + return "" diff --git a/backend/app/files/store.py b/backend/app/files/store.py new file mode 100644 index 00000000..bd94dcb8 --- /dev/null +++ b/backend/app/files/store.py @@ -0,0 +1,550 @@ +"""文件的存放、上传上下文、绑定、读权限、删除和清理(docs/design/normal-user-apps.md N9、§3.8)。 + +**存放。** 按 sha256 内容寻址:data/files/<前两位>/,只读(0444),和上传表格的原件存档同一种写法 +(data/raw_store.put_addressed)。元数据一行一个上传(files 表):同样的内容传两次是两行、一个文件。 + +**两步。** 先 POST /api/files 拿回引用 {file_id, name, size, sha256, type},再把引用当表单值提交。上传要带上下文: +应用的入口({app_id, entry})、待办({task_id})或蓝图({blueprint_id},试运行、个人应用),只有能用那个入口、能处理 +那条待办、能改那个蓝图的人传得上来。 + +**绑定。** 提交入口(apps/entries.py)、回复待办(process/tasks.py)时核对:引用是提交人自己传的、在这个上下文里传的、 +还没被用过,然后绑到这次运行(一次性)。表单里的引用换成登记的那一份(名字、大小、哈希以登记为准),连同 sha256 +进运行输入、随封存固定。入口要先占住(claim)再发起运行:发起失败放回去,成功了改成运行 id。 + +**读。** 绑到运行的,读得到那次运行的人能下载(auth/access.can_read_run);写进记录表那一行的,看得到那一行的人能下载 +(records/access.py 的行级可见);没绑定的只有上传的人自己。文件不做遮罩。 + +**清理。** 24 小时前上传、还没绑定的删掉(调度循环每小时一次,cleanup_tick)。 +""" +from __future__ import annotations + +import asyncio +import hashlib +import json +import logging +import re +from dataclasses import dataclass, field +from datetime import datetime, timedelta +from pathlib import Path +from typing import Any + +from sqlalchemy import delete, or_, select, text, update +from sqlalchemy.ext.asyncio import AsyncSession + +from app.apps.spec import FILE_REF_KEYS +from app.core.config import settings +from app.db.base import SessionLocal, utcnow +from app.db.models_blueprints import StoredFile +from app.files import ALLOWED_MIME_PREFIXES, UNBOUND_TTL_S + +logger = logging.getLogger(__name__) + +#: 入口提交时先占住文件(发起运行之前),bound_run_id 写成这个前缀加一个随机串;发起成功换成运行 id +CLAIM_PREFIX = "claim:" +#: 上下文里认的几项 +CONTEXT_KEYS = ("app_id", "entry", "task_id", "blueprint_id", "field") +#: 扩展名 → 类型(白名单,files.ALLOWED_MIME_PREFIXES) +EXT_MIME = { + ".pdf": "application/pdf", + ".doc": "application/msword", + ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + ".xls": "application/vnd.ms-excel", + ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + ".csv": "text/csv", + ".txt": "text/plain", + ".png": "image/png", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", +} +#: 类型 → 文件开头应有的字节。对不上就拒:扩展名谁都能改,内容得是它说的那种文件 +_MAGIC = { + "application/pdf": (b"%PDF",), + "image/png": (b"\x89PNG\r\n\x1a\n",), + "image/jpeg": (b"\xff\xd8\xff",), + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": (b"PK\x03\x04",), + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": (b"PK\x03\x04",), + "application/msword": (b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1",), + "application/vnd.ms-excel": (b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1",), +} +_TEXT_TYPES = ("text/csv", "text/plain") +_SHA = re.compile(r"^[0-9a-f]{64}$") +#: 文件名最长存几个字 +NAME_MAX = 300 +#: 文件控件(x-widget: file)的值要是引用这个形状;校验不过时表单错误的 code。 +#: 前端的表单错误 code 联合类型里还没有专门的一项(contract_requests),先用 type +FILE_ERROR_CODE = "type" + + +class FileRefused(Exception): + """上传、绑定、下载、删除不成:status 是 HTTP 状态,code 是问题编号(files.*,白话在 app/plain.py),field 是表单 + 里哪个字段(绑定时有)。message 直接给人看。""" + + def __init__(self, status: int, code: str, message: str, *, field: str | None = None) -> None: + super().__init__(message) + self.status = status + self.code = code + self.message = message + self.field = field + + +# -------------------------------------------------------------------------- +# 存放 +# -------------------------------------------------------------------------- + + +def files_root() -> Path: + """文件的根目录。按调用时的 settings 现算:测试会换数据目录。""" + return settings.data_dir / "files" + + +def blob_path(sha: str) -> Path: + if not _SHA.match(sha or ""): + raise ValueError("文件哈希的格式不对") + return files_root() / sha[:2] / sha + + +def read_blob(sha: str) -> bytes | None: + """取回文件内容并核对哈希:文件不在、内容和哈希对不上都返回 None(不交出被改过的内容)。""" + try: + data = blob_path(sha).read_bytes() + except (OSError, ValueError): + return None + if hashlib.sha256(data).hexdigest() != sha: + logger.warning("文件 %s 的内容和哈希对不上,不交出", sha) + return None + return data + + +def type_of(filename: str, raw: bytes) -> str: + """按扩展名定类型,再核对文件开头的字节。不在白名单、对不上、空文件都抛 FileRefused。""" + ext = Path(filename or "").suffix.lower() + mime = EXT_MIME.get(ext) + if mime is None or not mime.startswith(ALLOWED_MIME_PREFIXES): + allowed = "、".join(sorted({e.lstrip(".").upper() for e in EXT_MIME})) + raise FileRefused(415, "files.type_not_allowed", f"只能上传这些类型的文件:{allowed}") + if not raw: + raise FileRefused(422, "files.empty", "文件是空的") + if mime in _TEXT_TYPES: + head = raw[:65536] + if b"\x00" in head or not _decodes(head): + raise FileRefused(415, "files.content_mismatch", f"「{filename}」不是文字文件,和扩展名对不上") + return mime + if not raw.startswith(_MAGIC.get(mime, (b"",))): + raise FileRefused(415, "files.content_mismatch", f"「{filename}」的内容和扩展名对不上,请确认文件没有改过扩展名") + return mime + + +def _decodes(head: bytes) -> bool: + for encoding in ("utf-8", "gb18030"): + try: + head.decode(encoding) + return True + except UnicodeDecodeError: + # 截在多字节字符中间的那几个字节不算 + try: + head[:-3].decode(encoding) + return True + except UnicodeDecodeError: + continue + return False + + +def ref_of(row: StoredFile) -> dict[str, Any]: + """登记的那一份引用:表单值、运行输入里放的就是它。""" + return {"file_id": row.id, "name": row.name, "size": row.size, "sha256": row.sha256, "type": row.mime} + + +def as_ref(value: Any) -> dict[str, Any] | None: + """表单值 → 引用(字典或 JSON 文字都认);形状不对为 None。""" + if isinstance(value, str): + try: + value = json.loads(value) + except ValueError: + return None + if not isinstance(value, dict) or not set(value) <= set(FILE_REF_KEYS): + return None + if not isinstance(value.get("file_id"), str) or not value["file_id"]: + return None + return value + + +async def save(session: AsyncSession, raw: bytes, filename: str, *, uploaded_by: str | None, + context: dict[str, Any]) -> StoredFile: + """存内容、登记一行。类型按扩展名和内容核对(type_of)。""" + from app.data import raw_store + + name = (Path(filename or "").name or "附件").strip()[:NAME_MAX] + mime = type_of(name, raw) + sha, _ = await asyncio.to_thread(raw_store.put_addressed, raw, files_root()) + row = StoredFile(sha256=sha, name=name, size=len(raw), mime=mime, uploaded_by=uploaded_by, + context={k: v for k, v in context.items() if k in CONTEXT_KEYS}) + session.add(row) + await session.commit() + return row + + +# -------------------------------------------------------------------------- +# 上传的上下文:谁能往哪里传 +# -------------------------------------------------------------------------- + + +def parse_context(raw: Any) -> dict[str, str]: + """POST /api/files 的 context(JSON 文字或对象)→ 只留认得的几项。三种之一都没有的抛 FileRefused。""" + if isinstance(raw, str): + try: + raw = json.loads(raw) if raw.strip() else {} + except ValueError: + raw = None + if not isinstance(raw, dict): + raise FileRefused(422, "files.context_invalid", "上传需要说明是给哪个入口、哪条待办或哪个蓝图用的") + ctx = {k: str(v) for k, v in raw.items() if k in CONTEXT_KEYS and isinstance(v, (str, int)) and str(v).strip()} + if not (("app_id" in ctx and "entry" in ctx) or "task_id" in ctx or "blueprint_id" in ctx): + raise FileRefused(422, "files.context_invalid", "上传需要说明是给哪个入口、哪条待办或哪个蓝图用的") + return ctx + + +async def check_context(session: AsyncSession, principal: Any, ctx: dict[str, str]) -> dict[str, Any] | None: + """这个人能不能往这个上下文传文件:能用那个入口、能处理那条待办、能改那个蓝图。交回那个字段的文件控件设置 + (x-file:accept、max_mb;没说是哪个字段、字段没有设置时为 None),上传时按它再核一遍。""" + if "task_id" in ctx: + return await _task_context(session, principal, ctx) + if "app_id" in ctx: + return await _entry_context(session, principal, ctx) + return await _blueprint_context(session, principal, ctx) + + +_NO_ACCESS = "没有往这里上传文件的权限" + + +async def _entry_context(session: AsyncSession, principal: Any, ctx: dict[str, str]) -> dict[str, Any] | None: + from app.apps.access import app_role, at_least + from app.apps.tree import entry_of, resolve_form + from app.db.models_apps import App, AppVersion + + app = await session.get(App, ctx["app_id"]) + role = await app_role(session, principal, app) if app is not None else None + if app is None or app.status == "archived" or role is None: + raise FileRefused(404, "files.context_invalid", "应用不存在或已归档") + if not at_least(role, "use"): + raise FileRefused(403, "files.forbidden", _NO_ACCESS) + spec = app.draft or {} + if app.published_version: + version = (await session.execute(select(AppVersion).where( + AppVersion.app_id == app.id, AppVersion.version == app.published_version))).scalar_one_or_none() + spec = (version.spec if version is not None else None) or spec + entry = entry_of(spec, ctx["entry"]) + if entry is None: + raise FileRefused(404, "files.context_invalid", f"应用里没有入口「{ctx['entry']}」") + return _field_setting(resolve_form(spec, entry.get("form")), ctx.get("field")) + + +async def _task_context(session: AsyncSession, principal: Any, ctx: dict[str, str]) -> dict[str, Any] | None: + from app.db.models_process import Task, TaskAssignment + from app.process.tasks import handles + + task = await session.get(Task, ctx["task_id"]) + if task is None or task.status != "pending": + raise FileRefused(404, "files.context_invalid", "待办不存在或已经处理完了") + if principal.mode != "off": + rows = list((await session.execute(select(TaskAssignment).where(TaskAssignment.task_id == task.id))).scalars()) + if not handles(rows, principal): + raise FileRefused(403, "files.forbidden", _NO_ACCESS) + return _field_setting(task.form, ctx.get("field")) + + +async def _blueprint_context(session: AsyncSession, principal: Any, ctx: dict[str, str]) -> dict[str, Any] | None: + from app.db.models_blueprints import Blueprint + + bp = await session.get(Blueprint, ctx["blueprint_id"]) + if bp is None: + raise FileRefused(404, "files.context_invalid", "蓝图不存在") + if principal.mode != "off" and not ( + (bp.owner and bp.owner == principal.username) or (bp.scope == "shared" and principal.at_least("builder"))): + raise FileRefused(403, "files.forbidden", _NO_ACCESS) + return None + + +def _field_setting(form: Any, name: str | None) -> dict[str, Any] | None: + props = form.get("properties") if isinstance(form, dict) else None + prop = props.get(name) if isinstance(props, dict) and name else None + if not isinstance(prop, dict): + return None + setting = prop.get("x-file") + return setting if isinstance(setting, dict) else {} + + +def accept_problem(setting: dict[str, Any] | None, *, name: str, mime: str, size: int) -> str | None: + """文件控件设置(x-file:accept 类型或扩展名列表、max_mb)核一个文件:不合返回原因。""" + if not setting: + return None + accept = [str(a).lower() for a in setting.get("accept") or [] if isinstance(a, str)] + if accept: + ext = Path(name).suffix.lower() + if not any(a == mime or a == ext or (a.endswith("/*") and mime.startswith(a[:-1])) for a in accept): + return f"这里只收这些类型的文件:{'、'.join(accept)}" + max_mb = setting.get("max_mb") + if isinstance(max_mb, (int, float)) and not isinstance(max_mb, bool) and size > max_mb * 1024 * 1024: + return f"这里的文件不能超过 {max_mb:g} MB" + return None + + +# -------------------------------------------------------------------------- +# 绑定 +# -------------------------------------------------------------------------- + +#: 还没绑到记录上:JSON 列显式写过 None 的存的是 JSON 的 null,不是 SQL 的 NULL,两种都算 +_NO_RECORD = text("(files.bound_record IS NULL OR files.bound_record = 'null')") + + +def file_fields(form: Any) -> list[str]: + """表单里的文件字段(x-widget: file)。""" + props = form.get("properties") if isinstance(form, dict) else None + if not isinstance(props, dict): + return [] + return [name for name, prop in props.items() if isinstance(prop, dict) and prop.get("x-widget") == "file"] + + +def _context_matches(row: StoredFile, expected: dict[str, str]) -> bool: + got = row.context or {} + return all(str(got.get(k) or "") == v for k, v in expected.items()) + + +def _field_label(form: Any, name: str) -> str: + prop = ((form or {}).get("properties") or {}).get(name) or {} + return str(prop.get("title") or name) + + +async def _check(session: AsyncSession, form: Any, values: dict[str, Any], *, principal: Any, + context: dict[str, str]) -> list[tuple[str, StoredFile]]: + """表单里每个填了的文件字段:引用要对得上一行登记、是提交人自己传的、在这个上下文里传的、还没被用过。 + 交回 [(字段, 那一行)];有一个不对就抛 FileRefused(field 是那个字段)。""" + out: list[tuple[str, StoredFile]] = [] + seen: set[str] = set() + for name in file_fields(form): + value = values.get(name) + if value in (None, ""): + continue + label = _field_label(form, name) + ref = as_ref(value) + if ref is None: + raise FileRefused(422, "files.ref_invalid", f"「{label}」需要先上传文件", field=name) + row = await session.get(StoredFile, ref["file_id"]) + if row is None: + raise FileRefused(422, "files.not_found", f"「{label}」的文件不在了(超过 24 小时没提交会被清理),请重新上传", + field=name) + if row.uploaded_by != getattr(principal, "username", None): + raise FileRefused(422, "files.not_yours", f"「{label}」的文件不是你上传的,请重新上传", field=name) + if ref.get("sha256") not in (None, row.sha256) or row.id in seen: + raise FileRefused(422, "files.ref_invalid", f"「{label}」的文件引用对不上,请重新上传", field=name) + if row.bound_run_id is not None or row.bound_record is not None: + raise FileRefused(409, "files.already_bound", f"「{label}」的文件已经提交过一次,请重新上传", field=name) + if not _context_matches(row, context): + raise FileRefused(422, "files.context_mismatch", f"「{label}」的文件是在别处上传的,请在这里重新上传", + field=name) + seen.add(row.id) + out.append((name, row)) + return out + + +@dataclass +class Claim: + """入口提交时占住的文件:发起运行成功后 finish(绑到运行),失败 release(放回去)。""" + + token: str + ids: list[str] = field(default_factory=list) + + +async def claim(form: Any, values: dict[str, Any], *, principal: Any, context: dict[str, str] + ) -> tuple[dict[str, Any], Claim]: + """核对表单里的文件引用并占住它们(自己的会话、立刻提交,两次并发提交只有一次占得到)。交回换成登记引用的表单值 + 和占位。没有文件字段时什么都不做。""" + from app.db.base import new_id + + token = Claim(token=f"{CLAIM_PREFIX}{new_id()[:20]}") + if not file_fields(form): + return values, token + async with SessionLocal() as session: + checked = await _check(session, form, values, principal=principal, context=context) + out = dict(values) + for name, row in checked: + done = await session.execute(update(StoredFile).where( + StoredFile.id == row.id, StoredFile.bound_run_id.is_(None), _NO_RECORD) + .values(bound_run_id=token.token)) + if done.rowcount != 1: + await session.rollback() + raise FileRefused(409, "files.already_bound", + f"「{_field_label(form, name)}」的文件已经提交过一次,请重新上传", field=name) + token.ids.append(row.id) + out[name] = ref_of(row) + await session.commit() + return out, token + + +async def finish(token: Claim, run_id: str) -> None: + if not token.ids: + return + async with SessionLocal() as session: + await session.execute(update(StoredFile).where(StoredFile.bound_run_id == token.token) + .values(bound_run_id=run_id)) + await session.commit() + + +async def release(token: Claim) -> None: + if not token.ids: + return + async with SessionLocal() as session: + await session.execute(update(StoredFile).where(StoredFile.bound_run_id == token.token) + .values(bound_run_id=None)) + await session.commit() + + +async def bind_in(session: AsyncSession, form: Any, values: dict[str, Any], *, principal: Any, run_id: str, + context: dict[str, str]) -> dict[str, Any]: + """在调用方的会话里把表单里的文件绑到一次已有的运行(回复待办):和回复一起提交。交回换成登记引用的表单值。""" + checked = await _check(session, form, values, principal=principal, context=context) + out = dict(values) + for name, row in checked: + done = await session.execute(update(StoredFile).where( + StoredFile.id == row.id, StoredFile.bound_run_id.is_(None), _NO_RECORD) + .values(bound_run_id=run_id)) + if done.rowcount != 1: + raise FileRefused(409, "files.already_bound", + f"「{_field_label(form, name)}」的文件已经提交过一次,请重新上传", field=name) + out[name] = ref_of(row) + return out + + +async def bound_files(run_id: str) -> dict[str, dict[str, Any]]: + """这次运行绑定的文件:{file_id: 引用}。用到 file_text 的节点执行前读一次(files/text.prepare),只认这些。""" + from app.db.models import Run + + async with SessionLocal() as session: + out = {row.id: ref_of(row) for row in (await session.execute( + select(StoredFile).where(StoredFile.bound_run_id == run_id))).scalars()} + # 入口提交是先占住、发起成功后才改成运行 id(claim → finish):运行开头的节点可能赶在改之前执行。 + # 占着的文件只要出现在这次运行的输入里、是发起人在这个应用里传的,就是这次提交占的那几个 + run = await session.get(Run, run_id) + wanted = [ref["file_id"] for v in ((run.input if run is not None else None) or {}).values() + if (ref := as_ref(v)) is not None and ref["file_id"] not in out] + if wanted and run is not None: + origin = run.origin or {} + for row in (await session.execute(select(StoredFile).where( + StoredFile.id.in_(wanted), StoredFile.bound_run_id.like(f"{CLAIM_PREFIX}%")))).scalars(): + ctx = row.context or {} + same = (ctx.get("app_id") and ctx.get("app_id") == run.app_id) or ( + ctx.get("blueprint_id") and ctx.get("blueprint_id") == origin.get("blueprint_id")) + if row.uploaded_by == run.started_by and same: + out[row.id] = ref_of(row) + return out + + +# -------------------------------------------------------------------------- +# 读权限、删除 +# -------------------------------------------------------------------------- + + +async def readable(session: AsyncSession, principal: Any, row: StoredFile) -> bool: + """能不能下载这个文件:关登录全部放行;上传的人自己;读得到绑定的那次运行;看得到绑定的那一行记录。""" + from app.api.deps import can_read_run + + if principal.mode == "off": + return True + if principal.username and row.uploaded_by == principal.username: + return True + run_id = row.bound_run_id + if run_id and not run_id.startswith(CLAIM_PREFIX) and await can_read_run(principal, run_id): + return True + if isinstance(row.bound_record, dict): + return await _record_visible(session, principal, row.bound_record) + return False + + +async def _record_visible(session: AsyncSession, principal: Any, bound: dict[str, Any]) -> bool: + from app.db.models_blueprints import RecordsTable + from app.records import store as records_store + from app.records.access import scope_of + from app.records.tables import columns_of, path_of + + table = await session.get(RecordsTable, str(bound.get("table_id") or "")) + if table is None: + return False + scope = await scope_of(session, principal, table.app_id) + if scope == "all": + return True + if scope != "mine": + return False + try: + got = await asyncio.to_thread(records_store.row_by_id, path_of(table), columns_of(table), + str(bound.get("row_id") or "")) + except records_store.RecordsRefused: + return False + return got is not None and got.get("_submitted_by") == principal.username + + +async def remove(session: AsyncSession, principal: Any, file_id: str) -> None: + """删一个文件:只能删自己传的、还没绑定的。内容没有别的登记引用时一起删掉。""" + row = await session.get(StoredFile, file_id) + if row is None or row.uploaded_by != getattr(principal, "username", None): + raise FileRefused(404, "files.not_found", "文件不存在,或者不是你上传的") + if row.bound_run_id is not None or row.bound_record is not None: + raise FileRefused(409, "files.bound", "文件已经提交了,不能删除:它是那次运行的证据") + sha = row.sha256 + await session.delete(row) + await session.commit() + await _drop_unreferenced(session, {sha}) + + +async def _drop_unreferenced(session: AsyncSession, shas: set[str]) -> int: + """这些内容没有任何登记引用了就删文件(连同抽出的文字缓存)。返回删了几个。""" + if not shas: + return 0 + used = set((await session.execute(select(StoredFile.sha256).where(StoredFile.sha256.in_(list(shas))))).scalars()) + gone = 0 + for sha in shas - used: + from app.files.text import drop_cache + + try: + blob_path(sha).unlink() + gone += 1 + except FileNotFoundError: + pass + except (OSError, ValueError): + logger.warning("文件 %s 删不掉,下次清理再试", sha, exc_info=True) + drop_cache(sha) + return gone + + +# -------------------------------------------------------------------------- +# 清理 +# -------------------------------------------------------------------------- + +#: 调度循环里多久清理一次(秒) +CLEANUP_EVERY_S = 3600 +_last_cleanup: datetime | None = None + + +async def cleanup(now: datetime | None = None, *, ttl_s: int | None = None) -> int: + """删掉 ttl_s(缺省 24 小时)之前上传、还没绑定的文件(占着却没发起成功的也算),返回删了几行。""" + now = now or utcnow() + cutoff = now - timedelta(seconds=UNBOUND_TTL_S if ttl_s is None else ttl_s) + async with SessionLocal() as session: + stale = list((await session.execute(select(StoredFile.id, StoredFile.sha256).where( + or_(StoredFile.bound_run_id.is_(None), StoredFile.bound_run_id.like(f"{CLAIM_PREFIX}%")), + _NO_RECORD, StoredFile.uploaded_at < cutoff))).all()) + if not stale: + return 0 + await session.execute(delete(StoredFile).where(StoredFile.id.in_([i for i, _ in stale]))) + await session.commit() + await _drop_unreferenced(session, {sha for _, sha in stale}) + logger.info("清理了 %d 个超过时限没有提交的上传文件", len(stale)) + return len(stale) + + +async def cleanup_tick(now: datetime | None = None) -> int: + """调度循环每一拍调;每小时真正清理一次。""" + global _last_cleanup + now = now or utcnow() + if _last_cleanup is not None and (now - _last_cleanup).total_seconds() < CLEANUP_EVERY_S: + return 0 + _last_cleanup = now + return await cleanup(now) diff --git a/backend/app/files/text.py b/backend/app/files/text.py new file mode 100644 index 00000000..2356ae09 --- /dev/null +++ b/backend/app/files/text.py @@ -0,0 +1,174 @@ +"""模板函数 file_text:运行时把附件抽成文字交给 agent 或报告读(docs/design/normal-user-apps.md N9、§3.8)。 + +写法:{{ file_text(input.附件) }},或者带上限 {{ file_text(input.附件, 8000) }}(默认 TEXT_DEFAULT 字,最多 TEXT_MAX)。 + +- 只读这次运行绑定的文件(提交入口、回复待办时绑上的,files/store.bound_files;节点执行前现读,见 prepare): + 引用是输入里带来的,不能凭一个哈希读到别人的文件; +- 抽取沿用知识库上传的那一份(memory/parsing.extract,表格也转成文字);抽出来的全文按内容哈希缓存(上传时就在后台 + 抽一遍,运行时多半直接读缓存); +- 超过上限照实截断,并在文字末尾写明全文多少字、读入了多少;抽不出(图片、旧版 Office、扫描件)照实写进返回的文字, + 不报错、不编; +- 每次抽取记一条运行事件 file.extracted(字数、是否截断),读入的那一段文字按工件存下(进证据)。 + +模板渲染是同步的:缓存没命中时就在这里抽取。文件大小有上传上限(max_upload_mb),上传时已经在后台抽过一遍。 +""" +from __future__ import annotations + +import asyncio +import json +import logging +from pathlib import Path +from typing import Any + +from app.files.store import as_ref, bound_files, files_root, read_blob + +logger = logging.getLogger(__name__) + +#: 默认读入多少字、最多读入多少字 +TEXT_DEFAULT = 20_000 +TEXT_MAX = 200_000 +#: 抽取文字工件的种类 +TEXT_KIND = "file_text" +#: 存工件的后台任务:留着引用,不让它们半路被回收 +_PENDING: set[asyncio.Task[Any]] = set() + + +def _cache_path(sha: str) -> Path: + return files_root() / "_text" / sha[:2] / f"{sha}.json" + + +def drop_cache(sha: str) -> None: + try: + _cache_path(sha).unlink(missing_ok=True) + except (OSError, ValueError): + pass + + +def extract_text(sha: str, name: str, mime: str) -> tuple[str | None, str | None]: + """(全文, 抽不出的原因)。按内容哈希缓存:同一份内容只抽一次。""" + from app.memory.parsing import UnsupportedDocument, extract + + cache = _cache_path(sha) + try: + cached = json.loads(cache.read_text(encoding="utf-8")) + if isinstance(cached, dict): + return cached.get("text"), cached.get("problem") + except (OSError, ValueError): + pass + raw = read_blob(sha) + if raw is None: + return None, "文件不在了或者内容被改动过" + text: str | None = None + problem: str | None = None + if mime.startswith("image/"): + problem = "这是图片,抽不出文字" + else: + try: + text = extract(raw, name, mime, tables=True) + except UnsupportedDocument as e: + problem = str(e) + except Exception as e: # noqa: BLE001 - 解析库的各种异常照实写成抽不出 + logger.warning("附件 %s 抽取文字出错", name, exc_info=True) + problem = f"读取出错:{type(e).__name__}" + if text is not None and not text.strip(): + text, problem = None, "没有抽出文字(可能是扫描件)" + try: + cache.parent.mkdir(parents=True, exist_ok=True) + tmp = cache.with_suffix(".tmp") + tmp.write_text(json.dumps({"text": text, "problem": problem}, ensure_ascii=False), encoding="utf-8") + tmp.replace(cache) + except OSError: + logger.warning("附件 %s 抽出的文字没能缓存", name, exc_info=True) + return text, problem + + +async def warm(sha: str, name: str, mime: str) -> None: + """上传之后在后台先抽一遍,运行时直接读缓存。出错不影响上传。""" + try: + await asyncio.to_thread(extract_text, sha, name, mime) + except Exception: # noqa: BLE001 + logger.warning("附件 %s 的文字预抽取出错", name, exc_info=True) + + +#: TemplateScope.memo 里放这次运行绑定的文件的键 +_BOUND = "bound_files" + + +async def prepare(scope: Any) -> None: + """节点配置里用到 file_text 时,执行前读一次这次运行绑定的文件(engine/expressions.TEMPLATE_PREPARERS)。""" + run_id = getattr(getattr(scope.node, "run", None), "run_id", None) + scope.memo[_BOUND] = await bound_files(run_id) if run_id else {} + + +def _limit(max_chars: Any) -> int: + if isinstance(max_chars, (int, float)) and not isinstance(max_chars, bool) and max_chars > 0: + return int(min(max_chars, TEXT_MAX)) + return TEXT_DEFAULT + + +def file_text(ref: Any, max_chars: Any = None) -> str: + """模板函数本体(engine/expressions.TEMPLATE_FUNCTIONS)。返回给模型读的文字;读不到的照实说为什么。""" + from app.engine.expressions import TEMPLATE_SCOPE + + parsed = as_ref(ref) + if parsed is None: + return "(没有附件)" if ref in (None, "") else "(附件的引用不对,读不到)" + name = str(parsed.get("name") or "附件") + scope = TEMPLATE_SCOPE.get() + node = scope.node if scope is not None else None + if scope is None or node is None or _BOUND not in scope.memo: + return f"(附件「{name}」在运行时才读取)" + meta = scope.memo[_BOUND].get(parsed["file_id"]) + if meta is None: + return f"(附件「{name}」没有随这次运行提交,读不到)" + limit = _limit(max_chars) + memo_key = f"file_text:{meta['file_id']}:{limit}" + if memo_key in scope.memo: + return scope.memo[memo_key] + text, problem = extract_text(meta["sha256"], meta["name"], meta["type"]) + total = len(text or "") + if text is None: + shown = f"(附件「{meta['name']}」抽不出文字:{problem})" + included = "" + elif total > limit: + included = text[:limit] + shown = f"{included}\n……(附件「{meta['name']}」共 {total} 字,这里只读入了前 {limit} 字,其余没有读入)" + else: + included = shown = text + scope.memo[memo_key] = shown + _record(node, meta, included=included, total=total, truncated=text is not None and total > limit, problem=problem) + return shown + + +def _record(node: Any, meta: dict[str, Any], *, included: str, total: int, truncated: bool, + problem: str | None) -> None: + """记一条 file.extracted(字数、是否截断),读入的那一段按工件存。工件 id 就是内容哈希,这里先算出来写进事件, + 落盘和登记交给后台任务(模板渲染是同步的)。""" + from app.core.artifact_store import canonical_json, content_hash, put_json + from app.core.events import EventType + + payload = {"file_id": meta["file_id"], "name": meta["name"], "sha256": meta["sha256"], "text": included, + "total_chars": total, "truncated": truncated, **({"problem": problem} if problem else {})} + artifact = content_hash(canonical_json(payload)) + run_id = getattr(node.run, "run_id", None) + node_id = getattr(getattr(node, "node", None), "id", None) + try: + task = asyncio.get_running_loop().create_task( + put_json(payload, kind=TEXT_KIND, run_id=run_id, node_id=node_id)) + _PENDING.add(task) + task.add_done_callback(_PENDING.discard) + except RuntimeError: # 不在事件循环里(不该出现):工件不存,事件照发 + artifact = None + data = {"file_id": meta["file_id"], "name": meta["name"], "sha256": meta["sha256"], "chars": len(included), + "total_chars": total, "truncated": truncated, "ok": problem is None, "artifact": artifact, + **({"reason": problem} if problem else {})} + event = getattr(EventType, "FILE_EXTRACTED", None) + try: + if event is not None: + node.emit(event, **data) + else: + # 事件类型还没登记(contract_requests):先记成日志事件,code 写明是哪一种 + node.emit(EventType.LOG, level="info", code="file.extracted", + message=f"读入附件「{meta['name']}」{len(included)} 字" + ("(截断)" if truncated else ""), **data) + except Exception: # noqa: BLE001 - 事件只是留痕,读入的文字照样交回 + logger.warning("file.extracted 事件没发出去", exc_info=True) diff --git a/backend/app/look/base.py b/backend/app/look/base.py index bb5d8c8a..4b843595 100644 --- a/backend/app/look/base.py +++ b/backend/app/look/base.py @@ -16,8 +16,8 @@ from __future__ import annotations from dataclasses import dataclass, field from typing import Any, Protocol, TypedDict -#: 这一版实现的对象类型(口径以后再加:账本先做实验,look §3.8) -LOOK_KINDS = ("table", "capability", "workflow_version") +#: 实现的对象类型。口径(caliber)是已发布口径卡上的指标,蓝图助手复用口径时看(look/calibers.py,normal-user-apps N2) +LOOK_KINDS = ("table", "capability", "workflow_version", "caliber") LOOK_LIMIT = 3 # 起草阶段每轮最多查看几次 REPAIR_LOOK_LIMIT = 1 # 自查修正阶段另给几次 diff --git a/backend/app/look/calibers.py b/backend/app/look/calibers.py new file mode 100644 index 00000000..fce2daf4 --- /dev/null +++ b/backend/app/look/calibers.py @@ -0,0 +1,306 @@ +"""查看的对象之一:口径(normal-user-apps N2,补 G10:没有按名字检索的口径库)。蓝图助手看「看哪些数」时,先查数据目录, +再查已发布工作流里的口径卡:对到已有的口径卡时优先复用(实例化成 caliber_from),不重写指标式。 + +只列每个工作流最新的「已发布且未退役」的版本(app/apps/versions,P5 的唯一说法)里的口径卡,本身转抄别处口径卡的 +(caliber_from)不列——源头才能复用(运行时也只认源头,engine/nodes/metrics._pinned_caliber)。 + +复用的是整张卡(caliber_from 固定到那一版的那张卡),卡上每个指标都要算得出来:卡读的每个输入都要是 cell(nodes.X, 0, +'列名')、X 是查库的调用工具节点。新图里那个库的取数节点就叫 X、交出同样的列(blueprints/templates/_common.data_groups)。 +读别的(整形、沙箱、模型写的、按别的行号取)的卡照实说不能复用,请按表重新对。 + +点名写法:source 写工作流名(或 id),name 写指标名(或指标 id);只写 source 列那个工作流的全部指标。 +""" +from __future__ import annotations + +import json +from dataclasses import dataclass +from typing import Any + +from app.look.base import PICK_LIMIT, LookTarget +from app.look.pick import Picker, PickFailed + +# ========================================================================== +# 写给模型的文字 +# ========================================================================== + +OVERVIEW_HEAD_PROMPT = "已发布的口径(要复用已有的指标时用 look,kind 写 caliber):" +OVERVIEW_LINE_PROMPT = "- {workflow} v{version}:{metrics}" +OVERVIEW_MORE_PROMPT = "- …另有 {n} 个工作流" +DETAIL_HEAD_PROMPT = "· {name}(指标 id {metric}{unit}):出自「{workflow}」v{version} 的口径卡「{card}」({caliber})" +DETAIL_EXPR_PROMPT = " 指标式:{expression}" +DETAIL_REUSE_PROMPT = (" 复用写法(「看哪些数」这一项的 reuse 照抄,不要改):{reuse}\n" + " 这张卡读:{inputs}。实例化时那个库的取数节点就叫这个名字、交出这几列,复用才算得出来") +DETAIL_INPUT_PROMPT = "{node}({tool})的列 {columns}" +DETAIL_NOT_REUSABLE_PROMPT = " 不能复用:{reason}。请按表重新对" +BRIEF_PROMPT = "· {name}({workflow} v{version}):字数超过上限,只列名字,要看指标式时点名再 look" +MISSING_PROMPT = "没找到口径:{items}(只能查看已发布且未退役的版本里的口径卡;别拿名字相近的顶替)" +INDEX_LINE_PROMPT = "{workflow}|{card}|{name}({metric})|{unit}" +PICK_WHAT_PROMPT = "口径指标" +PICK_LINE_PROMPT = "每行一个指标:工作流名|口径卡|指标名(指标 id)|单位;source 写工作流名,name 写指标名" + +#: 概览最多列几个工作流、每个工作流最多列几个指标名 +OVERVIEW_WORKFLOWS = 30 +OVERVIEW_METRICS = 8 + +#: 不能复用的原因(写进查看结果,也是蓝图存的时候拒收的说法) +NOT_TOOL_REASON = "这张口径卡的输入不全是查库结果里的格(有整形、代码、模型写的或别的口径卡的数)" +ROW_REASON = "这张口径卡按别的行号取格,模板的取数只出一行" +CHAINED_REASON = "这张口径卡本身也是转抄别处的口径,请复用源头那一张" + + +@dataclass(frozen=True) +class CaliberView: + """一个已发布口径卡上的一个指标。inputs 是整张卡读的取数节点和列(能复用时),reason 是不能复用的原因。""" + + workflow_id: str + workflow_name: str + version: int + level: str + node_id: str + card: str + caliber: str + metric_id: str + name: str + unit: str + expression: str + inputs: tuple[tuple[str, str, tuple[str, ...]], ...] + reason: str | None + + @property + def label(self) -> str: + return f"{self.workflow_name} v{self.version} · {self.name}" + + def reuse(self) -> dict[str, Any] | None: + """「看哪些数」这一项的 reuse(blueprints/ops._reuse 的形状);不能复用为 None。""" + if self.reason is not None: + return None + return {"workflow_id": self.workflow_id, "version": self.version, "node_id": self.node_id, + "metric_id": self.metric_id, + "inputs": [{"node": n, "tool": t, "columns": list(cols)} for n, t, cols in self.inputs]} + + +def card_inputs(graph: dict[str, Any], card_id: str) -> tuple[list[dict[str, Any]], str | None]: + """整张口径卡读的取数节点和列:([{node, tool, columns}], 不能复用的原因)。每个指标式的每个输入都要是 + cell(nodes.X, 0, '列名')、X 是查库的调用工具节点(engine/lineage 认的原始数据,且只取第一行)。""" + from app.apps.tree import node_map + from app.engine.expressions import ExpressionError, cell_parts, leaf_refs, parse_expression + from app.tools.datasource import QUERY_PREFIX + + nodes = node_map(graph) + card = nodes.get(card_id) + if card is None or card["type"] != "metrics": + return [], "指的不是口径卡" + if card["config"].get("caliber_from") not in (None, "", {}): + return [], CHAINED_REASON + found: dict[str, dict[str, Any]] = {} + for metric in card["config"].get("metrics") or []: + try: + tree = parse_expression(str((metric or {}).get("expression") or ""))[0] + except ExpressionError: + return [], NOT_TOOL_REASON + for path in leaf_refs(tree): + parts = cell_parts(path) + if parts is None: + return [], NOT_TOOL_REASON + chain, row, column = parts + node_id = chain[len("nodes."):] if chain.startswith("nodes.") else "" + tool = str((nodes.get(node_id) or {}).get("config", {}).get("tool") or "") + if (nodes.get(node_id) or {}).get("type") != "tool" or not tool.startswith(QUERY_PREFIX): + return [], NOT_TOOL_REASON + if row.strip() != "0": + return [], ROW_REASON + try: + col = json.loads(column.replace("'", '"')) if column[:1] in ("'", '"') else None + except ValueError: + col = None + if not isinstance(col, str): + return [], NOT_TOOL_REASON + entry = found.setdefault(node_id, {"node": node_id, "tool": tool, "columns": []}) + if col not in entry["columns"]: + entry["columns"].append(col) + return list(found.values()), None + + +def views_of(workflow_id: str, workflow_name: str, version: Any) -> list[CaliberView]: + """一个已发布版本里每张口径卡(源头的)的每个指标。""" + from app.apps.tree import node_map + + graph = getattr(version, "graph", None) or {} + out: list[CaliberView] = [] + for nid, node in node_map(graph).items(): + if node["type"] != "metrics" or node["config"].get("caliber_from") not in (None, "", {}): + continue + inputs, reason = card_inputs(graph, nid) + packed = tuple((i["node"], i["tool"], tuple(i["columns"])) for i in inputs) + caliber = f"{node['config'].get('caliber') or node['title']} @ {node['config'].get('caliber_version') or 'v1'}" + for metric in node["config"].get("metrics") or []: + if not isinstance(metric, dict) or not metric.get("id"): + continue + out.append(CaliberView( + workflow_id=workflow_id, workflow_name=workflow_name, version=int(version.version), + level=str(getattr(version, "level", None) or ""), node_id=nid, card=node["title"], caliber=caliber, + metric_id=str(metric["id"]), name=str(metric.get("name") or metric["id"]), + unit=str(metric.get("unit") or ""), expression=str(metric.get("expression") or ""), inputs=packed, + reason=reason)) + return out + + +class CaliberKind: + kind = "caliber" + label = "口径" + + def __init__(self, items: list[CaliberView], *, picker: Picker | None = None) -> None: + self.items = items + self.picker = picker + + @classmethod + async def load(cls, session: Any, *, picker: Picker | None = None) -> CaliberKind: + """读每个工作流最新的已发布且未退役的版本里的口径卡。用调用方的会话,开流之前读好。""" + from sqlalchemy import select + + from app.apps import versions as app_versions + from app.db.models import Workflow + + items: list[CaliberView] = [] + for wf in (await session.execute(select(Workflow).order_by(Workflow.name))).scalars().all(): + latest = await app_versions.latest_published(session, wf.id) + if latest is not None: + items += views_of(wf.id, wf.name, latest) + return cls(items, picker=picker) + + def _workflows(self) -> dict[str, list[CaliberView]]: + out: dict[str, list[CaliberView]] = {} + for item in self.items: + out.setdefault(item.workflow_id, []).append(item) + return out + + def _pool(self, sources: list[str] | None) -> list[CaliberView]: + return [i for i in self.items if not sources or i.workflow_name in sources or i.workflow_id in sources] + + # ---------------------------------------------------------------- 概览、目录 + + async def overview(self) -> list[str]: + flows = self._workflows() + if not flows: + return [] + lines = [OVERVIEW_HEAD_PROMPT] + for items in list(flows.values())[:OVERVIEW_WORKFLOWS]: + names = "、".join(i.name for i in items[:OVERVIEW_METRICS]) + ("…" if len(items) > OVERVIEW_METRICS else "") + lines.append(OVERVIEW_LINE_PROMPT.format(workflow=items[0].workflow_name, version=items[0].version, + metrics=names)) + if len(flows) > OVERVIEW_WORKFLOWS: + lines.append(OVERVIEW_MORE_PROMPT.format(n=len(flows) - OVERVIEW_WORKFLOWS)) + return lines + + async def index(self, sources: list[str] | None) -> str: + return "\n".join(INDEX_LINE_PROMPT.format(workflow=i.workflow_name, card=i.card, name=i.name, + metric=i.metric_id, unit=i.unit or "-") + for i in self._pool(sources)) + + # ---------------------------------------------------------------- 点名、挑选 + + async def resolve(self, targets: list[LookTarget]) -> tuple[list[tuple[CaliberView, str]], list[LookTarget]]: + found: list[tuple[CaliberView, str]] = [] + missing: list[LookTarget] = [] + for t in targets: + source, name = str(t.get("source") or ""), str(t.get("name") or "") + hits = [i for i in self._pool([source] if source else None) if name in (i.name, i.metric_id)] + if not hits: + missing.append(t) + for hit in hits: + if all(i is not hit for i, _ in found): + found.append((hit, "named")) + return found, missing + + async def pick(self, need: str, sources: list[str] | None) -> tuple[list[tuple[CaliberView, str]], str | None]: + pool = self._pool(sources) + if len(pool) <= PICK_LIMIT: + return [(i, "picked") for i in pool], None + if self.picker is None: + return [], "没有可用的挑选模型" + try: + picks = await self.picker.pick(need=need, what=PICK_WHAT_PROMPT, line=PICK_LINE_PROMPT, + index=await self.index(sources)) + except PickFailed as e: + return [], str(e) + out: list[tuple[CaliberView, str]] = [] + for source, name in picks: + for i in pool: + if name in (i.name, i.metric_id) and (not source or source in (i.workflow_name, i.workflow_id)) \ + and all(o is not i for o, _ in out): + out.append((i, "picked")) + if picks and not out: + return [], "挑出的指标不在已发布的口径卡里" + return out[:PICK_LIMIT], None + + def key(self, obj: tuple[CaliberView, str]) -> str: + i = obj[0] + return f"caliber:{i.workflow_id}:{i.version}:{i.node_id}:{i.metric_id}" + + # ---------------------------------------------------------------- 详情 + + async def detail(self, objects: list[tuple[CaliberView, str]], budget: int, *, + missing: list[LookTarget] = ()) -> tuple[str, list[dict[str, Any]]]: + lines: list[str] = [] + used = 0 + for item, _how in objects: + block = [DETAIL_HEAD_PROMPT.format(name=item.name, metric=item.metric_id, + unit=f",单位 {item.unit}" if item.unit else "", + workflow=item.workflow_name, version=item.version, card=item.card, + caliber=item.caliber), + DETAIL_EXPR_PROMPT.format(expression=item.expression)] + reuse = item.reuse() + if reuse is not None: + block.append(DETAIL_REUSE_PROMPT.format( + reuse=json.dumps({k: v for k, v in reuse.items() if k != "inputs"}, ensure_ascii=False), + inputs=";".join(DETAIL_INPUT_PROMPT.format(node=n, tool=t, columns="、".join(cols)) + for n, t, cols in item.inputs))) + else: + block.append(DETAIL_NOT_REUSABLE_PROMPT.format(reason=item.reason)) + text = "\n".join(block) + if used + len(text) > budget: + text = BRIEF_PROMPT.format(name=item.name, workflow=item.workflow_name, version=item.version) + used += len(text) + 1 + lines.append(text) + if missing: + lines.append(MISSING_PROMPT.format(items="、".join( + f"{t.get('source') or ''} {t.get('name') or ''}".strip() for t in missing))) + record = {"kind": "caliber", "named": [i.label for i, how in objects if how == "named"], + "picked": [i.label for i, how in objects if how == "picked"], + "missing": [f"{t.get('source') or ''} {t.get('name') or ''}".strip() for t in missing]} + return "\n".join(lines), [record] + + # ---------------------------------------------------------------- 复用 + + def reuse_for(self, ref: dict[str, Any]) -> tuple[dict[str, Any] | None, str | None]: + """蓝图助手写的 reuse → 按这一轮读好的口径核对并补上 inputs:(完整的 reuse, 不能复用的原因)。""" + for item in self.items: + if (item.workflow_id, item.version, item.node_id, item.metric_id) == ( + ref.get("workflow_id"), ref.get("version"), ref.get("node_id"), ref.get("metric_id")): + return (item.reuse(), None) if item.reason is None else (None, item.reason) + return None, "只能复用已发布且未退役的版本里的口径卡(look 给出的那一版)" + + +async def verify_reuse(session: Any, ref: dict[str, Any]) -> dict[str, Any]: + """蓝图存的时候按库里那一版核对复用的口径卡:已发布且未退役、是源头的口径卡、有这个指标、能复用。交回补上 inputs + 的 reuse;不行抛 BpRefused(bp.data_unmapped)。用户在卡片上选的、助手提的都过这一道。""" + from app.apps import versions as app_versions + from app.blueprints.ops import BpRefused + from app.db.models import Workflow + + workflow = await session.get(Workflow, str(ref.get("workflow_id") or "")) + published = await app_versions.published_versions(session, workflow.id) if workflow is not None else [] + version = next((v for v in published if v.version == ref.get("version")), None) + if workflow is None or version is None: + raise BpRefused("复用的口径卡要出自已发布且未退役的工作流版本,这一版不是(可能已退役或删除)", code="bp.data_unmapped") + hit = next((i for i in views_of(workflow.id, workflow.name, version) + if (i.node_id, i.metric_id) == (ref.get("node_id"), ref.get("metric_id"))), None) + if hit is None: + inputs, reason = card_inputs(version.graph or {}, str(ref.get("node_id") or "")) + raise BpRefused(f"「{workflow.name}」v{version.version} 里没有这个口径指标" + + (f":{reason}" if reason and not inputs else ""), code="bp.data_unmapped") + reuse = hit.reuse() + if reuse is None: + raise BpRefused(f"「{workflow.name}」v{version.version} 的「{hit.name}」不能复用:{hit.reason}。请按表重新对", + code="bp.data_unmapped") + return reuse diff --git a/backend/app/main.py b/backend/app/main.py index 9ebe19bb..827c9311 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -108,6 +108,14 @@ async def lifespan(_: FastAPI) -> AsyncIterator[None]: await _tasks.startup() await _actions.startup() + # 发布单:上次进程没了时还在执行的单改成停下(停在没做完的那一步、写明执行中断),这样能接着做 + from app.blueprints import publish_plan as _plans + + try: + if stopped := await _plans.startup(): + logger.info("%d 份发布单执行中断,已改成停下,可以接着做", stopped) + except Exception: # noqa: BLE001 + logger.exception("发布单的启动整理失败,服务照常启动") from app.sandbox.manager import sandbox_manager as _sbm await _sbm.start_reaper() diff --git a/backend/app/memory/parsing.py b/backend/app/memory/parsing.py index bb05e3b7..9499c604 100644 --- a/backend/app/memory/parsing.py +++ b/backend/app/memory/parsing.py @@ -185,8 +185,11 @@ def _from_html(raw: bytes) -> str: return re.sub(r"\n{3,}", "\n\n", text).strip() -def extract(raw: bytes, filename: str, mime: str = "") -> str: - """文件字节 → 文本。认不出就按 UTF-8 文本试。""" +def extract(raw: bytes, filename: str, mime: str = "", *, tables: bool = False) -> str: + """文件字节 → 文本。认不出就按 UTF-8 文本试。 + + tables:表格也转成文字(CSV、TSV 原样,xlsx 逐个工作表按行列出)。知识库不收表格(见 _TABULAR),不传它; + 运行时把上传的附件交给 agent 读(files/text.py 的 file_text,docs/design/normal-user-apps.md N9)传 True。""" ext = _ext(filename) if ext in _PDF or mime == "application/pdf": return _from_pdf(raw) @@ -196,6 +199,10 @@ def extract(raw: bytes, filename: str, mime: str = "") -> str: return _from_pptx(raw) if ext in _HTML or mime == "text/html": return _from_html(raw) + if tables and ext in (".csv", ".tsv"): + return _from_text_table(raw, filename) + if tables and ext == ".xlsx": + return _from_xlsx(raw, filename) if ext in _TABULAR: raise UnsupportedDocument( f"「{filename}」是表格,知识库不接收表格。请到「数据」页的「表格」中点击「上传表格」导入:" @@ -216,3 +223,40 @@ def extract(raw: bytes, filename: str, mime: str = "") -> str: f"无法读取 {filename or '该文件'}:它不是 UTF-8 文本," f"也不是可识别的 PDF / Word / PowerPoint / HTML。" ) from e + + +def _from_text_table(raw: bytes, filename: str) -> str: + """CSV / TSV 原样当文字。国内导出的 CSV 常是 GBK,UTF-8 解不开就按 GB18030 试。""" + for encoding in ("utf-8-sig", "gb18030"): + try: + return raw.decode(encoding) + except UnicodeDecodeError: + continue + raise UnsupportedDocument(f"无法读取 {filename}:既不是 UTF-8 也不是 GBK 编码的文字") + + +def _from_xlsx(raw: bytes, filename: str) -> str: + """xlsx 逐个工作表按行列出,单元格之间用制表符。只读取值(公式取上次计算的结果),隐藏的工作表也列出、标明隐藏。""" + try: + from openpyxl import load_workbook + except ImportError as e: # pragma: no cover - openpyxl 在核心依赖里 + raise UnsupportedDocument("读取 Excel 需要 openpyxl") from e + try: + book = load_workbook(io.BytesIO(raw), read_only=True, data_only=True) + except Exception as e: # noqa: BLE001 - 解析库的各种异常一律照实说读不开 + raise UnsupportedDocument(f"无法读取 {filename}:{_why(e)}") from e + parts: list[str] = [] + try: + for sheet in book.worksheets: + hidden = "(隐藏)" if getattr(sheet, "sheet_state", "visible") != "visible" else "" + lines = [] + for row in sheet.iter_rows(values_only=True): + cells = ["" if v is None else str(v) for v in row] + while cells and not cells[-1]: + cells.pop() + if cells: + lines.append("\t".join(cells)) + parts.append(f"## 工作表 {sheet.title}{hidden}\n" + "\n".join(lines)) + finally: + book.close() + return "\n\n".join(parts) diff --git a/backend/app/notify/service.py b/backend/app/notify/service.py index 61102048..a836574a 100644 --- a/backend/app/notify/service.py +++ b/backend/app/notify/service.py @@ -27,16 +27,18 @@ from app.notify.core import Message, Outcome, host_of logger = logging.getLogger(__name__) #: 可以订阅的事件 -EVENTS = ("task.opened", "run.finished", "run.failed", "action.unknown") +EVENTS = ("task.opened", "run.finished", "run.failed", "action.unknown", "review.done") EVENT_LABEL = {"task.opened": "有待办派给我", "run.finished": "实例完成", "run.failed": "实例失败", - "action.unknown": "写入结果未知"} + "action.unknown": "写入结果未知", + # 个人应用提交审核之后,搭建者发布了或退回了(docs/design/normal-user-apps.md N7) + "review.done": "我提交审核的应用有结果"} #: 这几种也是「有一条待办要你处理」,按 task.opened 的订阅推 _AS = {"task.reassigned": "task.opened", "task.escalated": "task.opened", "task.reminded": "task.opened"} _TASK_HEAD = {"task.opened": "新的待办", "task.reassigned": "待办已改派给你", "task.escalated": "待办已超时,升级处理", "task.reminded": "待办催办"} _KIND_TEXT = {"approve": "审批", "input": "补充输入", "edit": "编辑稿件", "tool": "工具调用审批", "code": "代码执行审批", "dual_check": "双盲复算裁决", "action_confirm": "确认写入外部系统", "reconcile": "核实写入结果", - "signal": "等外部系统回调"} + "signal": "等外部系统回调", "review": "审核个人应用"} _ENV_TEXT = {"prod": "生产环境", "test": "测试环境", "simulated": "演练"} _background: set[asyncio.Task[Any]] = set() @@ -182,7 +184,8 @@ async def notify_task(task_id: str, event: str, *, users: list[str]) -> int: where = await _where(session, run) pending = list((await session.execute(select(TaskAssignment).where( TaskAssignment.task_id == task_id, TaskAssignment.status == "pending"))).scalars()) - node = _label(run.graph if run else None, task.node_id) + # 不挂在节点上的待办(个人应用的审核)用待办的标题:它按应用名起,不是按运行数据渲染的 + node = _label(run.graph if run else None, task.node_id) if task.node_id else task.title[:80] names = "、".join(dict.fromkeys(a.principal or "任何人" for a in pending)) or "任何人" lines = [("状态", "待处理"), ("种类", _KIND_TEXT.get(task.kind, task.kind)), ("派给", names[:200])] if where: @@ -220,6 +223,25 @@ async def notify_run(run_id: str, event: str) -> int: task_id=None) +async def notify_review(task_id: str, decision: str, *, owner: str, name: str, app_id: str | None) -> int: + """个人应用提交审核有了结果(review.done,N7):通知提交人——他自己订阅了这件事的个人渠道,加上订阅了它的全局渠道。 + 消息里只有应用名和结论,不放应用里的数(P4)。app_id 是链接过去的应用:发布了的是正式应用,退回的是他的个人应用。""" + event = "review.done" + async with SessionLocal() as session: + channels = await _channels(session, event, None, [owner]) + if not channels: + return 0 + base = await _base_url(session) + published = decision == "published" + message = {"event": event, "status": decision, "ok": published, + "title": f"提交审核的「{name[:80]}」{'已发布成正式应用' if published else '被退回'}", + "lines": [("结论", "已发布" if published else "已退回"), ("待办", f"#{task_id[:6]}")], + "links": [("去看看" if published else "查看我的应用", f"{base}/apps/{app_id}")] if base and app_id else [], + "subject": {"task_id": task_id, "app_id": app_id}} + return await _push(channels, message, subject_kind="task", subject_id=task_id, event=event, run_id=None, + task_id=task_id) + + async def notify_action(action_id: str, event: str) -> int: """写入外部系统的结果未知(action.unknown)。有核实待办的链接到待办,没有的(系统按幂等键去查)链接到实例。""" from app.db.models import ActionRecord diff --git a/backend/app/plain.py b/backend/app/plain.py index 8fe10d2c..4aa4b431 100644 --- a/backend/app/plain.py +++ b/backend/app/plain.py @@ -22,9 +22,337 @@ class Plain: action: str = "" +_Y, _A, _M = "you", "assistant", "admin" + #: 问题编号 → 白话。前缀匹配用 PLAIN_PREFIX(如 "subgraph_version_" 一类) -PLAIN: dict[str, Plain] = {} -PLAIN_PREFIX: dict[str, Plain] = {} +PLAIN: dict[str, Plain] = { + # ---------------------------------------------------------------- 出具契约(engine/governance.py) + "contract.not_object": Plain( + "成果的出具规则格式不对", "出具规则读不出来,系统就判不了这份成果能不能正式交出去。", _A, + "交给助手按出具规则的格式重写,或在成果节点上重新设置。"), + "contract.metrics_from_missing": Plain( + "没说指标从哪张口径卡来", "报告里的数对不上任何指标,核对不了出处。", _A, + "在成果节点的出具规则里选上提供指标的口径卡。"), + "contract.metrics_from_invalid": Plain( + "出具规则选的口径卡不存在", "选错了口径卡,核对时找不到指标。", _A, "改选工作流里实际存在的口径卡。"), + "contract.report_from_missing": Plain( + "没说核对哪一份报告", "不指明报告,报告里的数就没人核对。", _A, "在出具规则里选上写报告的那个节点。"), + "contract.report_from_invalid": Plain( + "出具规则选的报告节点不对", "选的不是写报告的节点,或者不在成果的上游,核对会落空。", _A, + "改选成果上游的报告撰写节点。"), + "contract.required_missing": Plain( + "没列出必须有的指标", "不列出必需指标,缺了关键的数也会交出去。", _Y, + "选出这份成果里必须有的指标(哪些缺了就不交出去由你定)。"), + "contract.cells_undeclared": Plain( + "报告直接引用了查询结果的格子,却没声明", "受管级别不认没声明的引用,正式运行时报告会写不出来。", _Y, + "选择允许直接引用查询结果,或者加一张口径卡把数登记成指标。"), + "contract.strict_off": Plain( + "出具规则没开严格模式", "不开的话,说不清出处的数只会让成果降档,不会被拦下。", _A, "打开严格模式。"), + "contract.claims_ignored": Plain( + "「没附依据的结论句」那一项设了也不生效", "受管级别仍会把没附依据的结论句算进缺口,这项设置只会误导人。", _A, + "改成降档或不予出具。"), + # ---------------------------------------------------------------- 受管级门禁(engine/governance.py) + "governed.supervisor": Plain( + "用了由模型临场分工的节点", "分工和轮数在运行时才定,事先没法审核,受管级别不收。", _Y, + "改用配置固定的 Agent 或「模型调用」节点(结构要拆成哪几步由你定)。"), + "governed.subgraph_unpinned": Plain( + "引用的工作流没固定版本", "上游一改,这边的口径跟着变,没人知道。", _Y, "选定一个已发布的版本。"), + "governed.agent_approval_never": Plain( + "Agent 调危险工具不用审批", "受管级别要求危险工具至少经人审批。", _A, "把审批策略改为「仅危险工具需要审批」。"), + "governed.default_approval_never": Plain( + "全图默认不用审批", "跟着全图默认的 Agent 调危险工具时没人把关。", _A, "把全图默认的审批策略改为需要审批。"), + "governed.agent_no_tools": Plain( + "Agent 没配工具", "不调工具的 Agent 只是在写文字,用「模型调用」节点更合适。", _Y, "改用「模型调用」节点,或给它配上工具。"), + "governed.agent_tools_wide": Plain( + "Agent 的工具太多", "授权范围越宽,越难说清它会做什么。", _Y, "只留下完成任务要用的工具。"), + "governed.code_network": Plain( + "代码节点开了联网", "在代码里取的数不留快照,事后查不了出处。", _Y, "把取数改到「调用工具」节点。"), + "governed.no_contract": Plain( + "成果没有出具规则", "没有出具规则,系统判不了这份成果完不完整。", _A, "给成果节点加上出具规则。"), + "governed.metric_untraced": Plain( + "有指标追不到原始数据", "按指标出具时,指标的出处就是全部依据;追不到的那一个,「完整出具」就没有根据。", _A, + "在口径卡里按格取数,或让整形节点原样解析查询结果。"), + "governed.report_from_required": Plain( + "出具规则核对的是叙述,不是报告", "按数值找出处可能对上好几个地方,受管级别要求每个数只有一个出处。", _A, + "把核对对象改为上游的报告撰写节点。"), + "governed.exit_text_source": Plain( + "成果里的文字不是报告写的", "别的节点写的文字说不清出处。", _A, "成果字段改取报告撰写节点的正文。"), + "governed.text_bypass": Plain( + "模型写的文字绕过了报告直接进了成果", "这些文字里的数和表名都没法追溯。", _A, "改由报告撰写节点来写,成果取报告正文。"), + "governed.report_policy": Plain( + "报告的核对规则不够严", "受管级别要求报告用最严的核对规则。", _A, "把报告撰写节点的核对规则调到最严。"), + "governed.judge_budget": Plain( + "模型裁判没设金额上限", "裁判的花费不能沿用默认值,要事先说清。", _Y, "写一个每份报告的裁判金额上限,或明确选择不限。"), + "governed.caliber_compute_input": Plain( + "口径卡的数来自代码计算", "沙箱里算出来的数追溯不了出处。", _Y, + "若这一步是在取数,把它标成取数;若是在计算,把计算挪到口径卡的表达式里(是哪一种由你定)。"), + "governed.caliber_agent_schema": Plain( + "给口径卡供数的 Agent 交的是自由文本", "口径卡读到的数没法核对到查询结果。", _A, + "给 Agent 配上结构化输出,并打开按出处核对字段。"), + "governed.caliber_agent_cite_fields": Plain( + "给口径卡供数的 Agent 没核对字段出处", "口径卡读到的仍是模型给的数。", _A, "打开按出处核对字段。"), + "governed.caliber_model_input": Plain( + "口径卡的数来自「模型调用」节点", "这种节点不调工具,写出的数没有出处。", _A, "改由「调用工具」节点或配好结构化输出的 Agent 取数。"), + # ---------------------------------------------------------------- 写外部系统(engine/lint_capabilities.py) + "action.write_in_agent": Plain( + "Agent 的工具里有会写外部系统的能力", "写入只能放在「调用工具」节点里,先确认再发送、留生效记录。", _Y, + "从 Agent 的工具清单里移除它,改用「调用工具」节点。"), + "action.unattended_write": Plain( + "写入外部系统不经确认,而这项能力不允许无人值守", "没人确认就写进外部系统,出了错没人拦。", _Y, + "把这一步改为需要确认;确实要无人值守的,请管理员在能力登记里放开。"), + "action.prod_missing": Plain( + "写入能力没有生产环境", "正式运行要写的时候无处可发。", _M, "请管理员在「工具 → 端点」里补上生产环境。"), + "action.reconcile_unplanned": Plain( + "写入能力没有登记查询", "写入结果不明时没法自动核实,只能转人工核实。", _M, "请管理员在能力登记里给它指定查询能力。"), + # ---------------------------------------------------------------- 按流程使用(engine/lint_process.py) + "process.wait_mid_agent": Plain( + "Agent 中途可能停下来等审批", "按流程使用时,停在 Agent 中途的断点在系统升级后恢复不了。", _Y, + "把需要审批的调用挪到「调用工具」节点。"), + "process.human_in_subgraph": Plain( + "人工步骤放在了引用的工作流里", "引用的工作流不保存断点,恢复时整段从头再来,可能重复办。", _Y, + "把人工步骤挪到外层工作流。"), + "process.code_network": Plain( + "代码节点联网,可能在写外部系统", "按流程使用时,写外部系统要先留生效记录,结果不明时才能核实。", _Y, + "把对外部系统的写入挪到「调用工具」节点。"), + # ---------------------------------------------------------------- 应用检查(apps/lint.py、apps/resolve.py) + "app.format": Plain( + "应用描述的格式不对", "格式不对的应用发布不了。", _A, "交给助手按应用格式修好。"), + "app.pin_unpublished": Plain( + "应用用的工作流版本还没发布", "应用只能用已发布的版本,正式运行只从已发布的版本发起。", _Y, + "先发布这一版,或换成一个已发布的版本。"), + "app.pin_retired": Plain( + "应用用的工作流版本已退役", "退役的版本不再接受新的正式运行。", _Y, "升级到一个在用的发布版本。"), + "app.pin_hash": Plain( + "应用记下的版本和库里的对不上", "按内容指纹认版本,对不上就说不清运行的是哪张图。", _Y, "重新选择这一版。"), + "app.upgrade_policy": Plain( + "口径变了,还没选以前的数怎么办", "换版本可能改了口径,新旧数放在一起比之前要先说清。", _Y, + "选一种处置:按新口径重算、新旧并列,或注明前后不可比。"), + "app.binding_target_missing": Plain( + "页面上有一块绑的东西不存在", "这一块会显示不出来。", _A, "改绑到存在的视图、指标或节点,或删掉这一块。"), + "app.view_source_empty": Plain( + "这个视图暂时还没有数", "页面会写明还没有数据,等第一次正式运行完成就有了。", _Y, "不用改;想马上有数,发布后运行一次。"), + "app.on_demand_ttl": Plain( + "按需查看的缓存时效没设好", "查活库的视图不设时效,同样的条件会一直给旧结果。", _A, "设一个缓存时效。"), + "app.component_unknown": Plain( + "用了组件目录里没有的组件", "界面画不出来不认识的组件。", _A, "换成组件目录里有的组件。"), + "app.props_invalid": Plain( + "组件的设置不对", "设置不对,这一块可能显示错或显示不出来。", _A, "按组件的说明改设置。"), + "app.text_number": Plain( + "页面的固定文字里写了数字", "写死的数不会随数据更新,也说不清出处。", _A, "改成绑定到指标或查询结果。"), + "app.binding_not_evidenced": Plain( + "成果字段里的数不是报告里的原文", "说不清出处的数不展示。", _A, "改绑报告,或让成果字段逐字取自报告。"), + "app.metric_untraced": Plain( + "页面上的指标追不到原始数据", "这个数点开看不到出处。", _A, "换一个能追到原始数据的指标,或先改口径卡。"), + "app.expr_arith": Plain( + "显示条件里做了计算", "页面层不做算术,数要在工作流里算好。", _A, "把计算挪到口径卡,条件里只做比较。"), + "app.expr_invalid": Plain( + "显示条件写法不对", "条件算不出来时这一块按不显示处理。", _A, "改正条件的写法。"), + "app.expr_root": Plain( + "显示条件用了不认识的名字", "条件算不出来时这一块按不显示处理。", _A, "改用条件里能用的名字。"), + "app.entry_form_mismatch": Plain( + "发起表单和工作流的输入对不上", "填的东西传不到工作流里,或者传错位置。", _A, "让表单字段和工作流的输入一一对应。"), + "app.entry_unmapped_required": Plain( + "工作流必填的输入,发起表单没给", "发起时会因为缺输入而失败。", _A, "在发起表单里加上这一项,或给它一个固定值。"), + "app.slot_unbound": Plain( + "有一步还没指定谁来做", "没人的那一步会派给任何人,审批、升级都会悄悄失效。", _Y, "在「谁来做」里给这一步选人或组。"), + "app.slot_principal_unknown": Plain( + "「谁来做」里选的人或组在名录里对不上", "派给这个名字的待办没有人能处理。", _Y, "从候选中重新选择,或移除。"), + "app.reconciler_unbound": Plain( + "写入结果不明时没人核实", "写外部系统的结果不明时,要有人去外部系统里查。", _Y, "指定负责核实写入结果的人或组。"), + "app.process_unsafe": Plain( + "这个工作流按流程使用不安全", "流程要能停下等人、断了能接着走,这张图有一处做不到。", _Y, + "按问题里说的改工作流,再发布新版本。"), + "app.hook_entry_missing": Plain( + "外部系统发起用的入口不存在", "外部系统发来的请求会被拒收。", _A, "改选存在的入口。"), + "app.notify_channel_missing": Plain( + "订阅的通知渠道不存在", "这条通知发不出去。", _Y, "换一个存在的渠道,或请管理员建好它。"), + "app.acl_empty": Plain( + "还没给任何人用", "开了登录时,除了管理员和搭建者谁都打不开。", _Y, "在「谁能看」里给要用的人或组授权。"), + "app.acl_principal_unknown": Plain( + "授权给的人或组在名录里对不上", "以后建了同名的人会直接拿到这一档权限,或者停用的人重新启用后又能用。", _Y, + "从候选中重新选择,或移除。"), + "app.polish_refused": Plain( + "助手想改的地方超出了它能改的范围", "助手只能改页面的呈现,改数据、改流程要人来。", _Y, "确实要改的,由你在对应的地方改。"), + # ---------------------------------------------------------------- 发布单(blueprints/publish_plan.py) + "plan.not_instantiated": Plain( + "蓝图还没生成工作流", "没有图就没有东西可以发布。", _Y, "先把卡片补齐,用真数试运行一次。"), + "plan.graph_changed": Plain( + "出单之后蓝图又改过", "要发布的已经不是这份发布单看过的那张图。", _Y, "重新出一份发布单。"), + "plan.untrialed": Plain( + "还没用真数试运行过", "没看过真数就发布,可能不是你要的结果。", _Y, "先试运行一次,看过结果再发布。"), + "plan.trial_differs": Plain( + "发布的内容和最近一次试运行不同", "试运行之后又改过,发布的这一版没用真数看过。", _Y, "建议再试运行一次。"), + "plan.admin_required": Plain( + "受管级别只有管理员能发布", "受管级别的工作流按最严的规则出具,发布由管理员签字。", _M, "请管理员来发布,或改按已发布级别发布。"), + "plan.downgrade_admin": Plain( + "这会把受管工作流降为已发布", "降级之后正式运行不再过受管级别的检查,要管理员决定。", _M, "请管理员来发布,或改按受管级别发布。"), + "plan.preflight": Plain( + "发布前检查没通过", "有问题没解决,这时发布会留下半截状态,所以什么都没写。", _Y, "按下面列出的问题逐条处理,再接着做。"), + "plan.workflow_publish": Plain( + "工作流没能发布", "工作流不发布,就不会有正式运行。", _Y, "按问题处理后接着做。"), + "plan.schedule_invalid": Plain( + "定时设置不对", "按这个设置建不了定时任务。", _Y, "回到「多久更新」卡片改好,再接着做。"), + "plan.app_publish": Plain( + "应用没能发布", "工作流已经发布了,应用还没有;使用者暂时看不到它。", _Y, "按问题处理后接着做。"), + "plan.app_archived": Plain( + "这个蓝图对应的应用已归档", "归档的应用不再改草稿、不再发布。", _Y, "如需继续,请新建一个应用。"), + "plan.app_forbidden": Plain( + "你对这个蓝图发布成的应用没有管理权限", "发布单会改这个应用的页面、发布新的一版、替换它的授权,这些要管理权限。", _M, + "请应用的管理者或管理员来发布,或请他们在应用的授权里给你管理权限。"), + "plan.grant_refused": Plain( + "「谁能看」里有人或组在名录里对不上", "授权只能给名录里在用的人和组。", _Y, "回到「谁能看」卡片重新选择。"), + "plan.first_run": Plain( + "第一次运行没能发起", "应用已经发布好了,只是打开时还没有数。", _Y, "稍后在应用里运行一次,或等定时任务出数。"), + "plan.object_missing": Plain( + "前面某一步建好的东西不见了", "接着做之前要确认前面几步的结果还在。", _Y, "重新出一份发布单。"), + "plan.interrupted": Plain( + "执行到一半服务重启了", "这一步可能只做了一半,后面的步骤都没有做。", _Y, + "接着做:已经存好的版本、建好的应用会按原样复用,不会另建一份。"), + "plan.step_failed": Plain( + "这一步出了意外的错", "这一步没做完,后面的步骤都没有做。", _Y, "稍后接着做;一直不行请把错误信息交给管理员。"), +} +# ---------------------------------------------------------------- 个人应用与页面编辑(包 B4:blueprints/personal.py、 +# apps/lint.py 的 _lint_personal / _lint_views / _lint_hidden、api/personal.py) +PLAIN.update({ + "app.view_source_personal": Plain( + "视图的数据来源和应用的类型对不上", "探索运行的结果没经过发布审核,只能给个人应用的拥有者自己看;个人应用又只有" + "探索运行,取别的来源永远是空的。", _Y, + "共享应用的视图改成取正式运行(最近一次出数、按条件查看或本实例);个人应用的视图改回取它自己的刷新结果。"), + "app.hidden_bound": Plain( + "隐藏的这块是唯一显示这组数的地方", "隐藏之后,页面上一处都看不到这组数了。", _Y, + "确实不要了可以删掉它;还要看的话取消隐藏。"), + "personal.policy": Plain( + "个人应用里有使用者不能用的东西", "个人应用只能读数据、整理、撰写,不能审批、不能写入别的系统,也不能执行代码," + "这样它的结果才能只给你自己看。", _Y, "回到蓝图换一种做法;需要审批或写回的,请提交给搭建者做成正式应用。"), + "personal.off": Plain( + "管理员还没有开放个人应用", "个人应用由管理员决定开不开放。", _M, "请管理员在设置里打开,或请搭建者做成应用。"), + "personal.not_trialed": Plain( + "还没有用真数试过", "没看过真数就存,可能不是你要的结果。", _Y, "先试运行一次,看过结果再存成你的应用。"), + "personal.graph_changed": Plain( + "蓝图改过,还没重新存成你的应用", "刷新按存下的那张图运行,改过的蓝图还没生效。", _Y, + "回到蓝图「存成我的应用」,再刷新。"), + "personal.daily_limit": Plain( + "今天的刷新次数用完了", "每人每天能刷新的次数有上限,控制运行的花费。", _M, "明天再试,或请管理员调高上限。"), + "personal.no_run": Plain( + "还没有成功刷新过", "审核的人要看到这个应用用真数出的结果。", _Y, "先刷新一次,成功之后再提交审核。"), + "personal.in_review": Plain( + "已经提交过审核", "同一个应用同时只能有一份在审核。", _Y, "等搭建者发布或退回之后再提交。"), + "personal.review_target": Plain( + "审核要交给搭建者", "只有搭建者能把它做成正式应用。", _Y, "从候选里选一位搭建者,或者交给一个组。"), + "personal.review_forbidden": Plain( + "审核个人应用要搭建者来做", "审核的人要在副本上试运行、发布成正式应用,这些只有搭建者能做。", _M, + "请一位搭建者处理这条审核,或请管理员调整你的角色。"), + "personal.not_personal": Plain( + "这不是个人应用,或者它出自的蓝图已经不在了", "刷新、提交审核只对还能找到蓝图的个人应用。", _Y, + "共享应用请用它自己的刷新;蓝图删了的个人应用可以归档。"), + "personal.not_shareable": Plain( + "个人应用不能发布或授权给别人", "个人应用的结果没经过发布审核,只给拥有者自己看。", _Y, + "想给别人用,请提交审核,由搭建者发布成正式应用。"), +}) +# ---------------------------------------------------------------- 记录表与文件(包 B3:records/、files/、api/files.py、 +# apps/lint.py 的 _lint_records_rows)。records.* 是写记录表被拒的原因,files.* 是上传、提交、下载文件被拒的原因 +PLAIN.update({ + "app.records_rows_exposed": Plain( + "看板上的表格把记录一条条都列出来了", "看板的数是用全部记录算的,这样每个能用应用的人都能看到别人提交的记录。", _Y, + "要看自己提交了什么,请用「记录列表」组件(按看的人过滤);看板上的表格改成汇总。确实要公开给所有人看的可以不改。"), + "records.column_invalid": Plain( + "表单里有字段存不进记录表", "字段名重复、以下划线开头或者类型不认识,记录表建不起来。", _Y, + "回到「填什么」卡片改字段名或类型。"), + "records.column_unknown": Plain( + "要写入的字段记录表里没有", "表单改过,应用还在用改之前的那一版。", _Y, "重新发布应用,让表单和记录表对上。"), + "records.required_missing": Plain( + "必填的字段没有值", "必填的字段空着,这条记录就是不完整的。", _Y, "把必填的字段填上再提交。"), + "records.value_invalid": Plain( + "有字段的值和类型对不上", "比如数字字段填了文字,存进去以后汇总会算错。", _Y, "按字段要求的类型重新填写。"), + "records.supersede_missing": Plain( + "要更正的那条记录找不到", "更正要指向这张表里已有的一条记录。", _Y, "从记录列表里选要更正的那一条。"), + "records.supersede_twice": Plain( + "这条记录已经被更正过了", "同一条记录只能更正一次,后面的修改要改在最新的那一条上。", _Y, "在最新的那一条上更正。"), + "records.table_retired": Plain( + "这一版记录表已经停用", "表单改过之后出了新版本,旧记录照原样保留、只能查看。", _Y, "重新发布应用,写到新版本里。"), + "records.table_foreign": Plain( + "写的记录表不属于这个应用", "正式运行只能写自己应用的记录表,不然别的应用的记录会被混进来、被不该看的人看到。", _Y, + "回到写记录表那一步,改成这个应用自己的记录表,再重新发布。"), + "records.table_missing": Plain( + "记录表的数据文件不见了", "数据文件被移走或删掉,记录写不进去、也查不了。", _M, "请管理员检查数据目录。"), + "records.file_exists": Plain( + "记录表的数据文件已经有数据,不能重建", "为了不覆盖已有的记录,系统拒绝了重建。", _M, "请管理员检查数据目录。"), + "records.action_key_missing": Plain( + "写记录表没有经过动作流程", "只有经过动作流程,同一次提交才保证只写一条。", _A, + "把写入放在「调用工具」节点里,不要放进 Agent。"), + "files.missing": Plain("没有选文件", "", _Y, "选择要上传的文件。"), + "files.empty": Plain("文件是空的", "空文件里没有可用的内容。", _Y, "检查后重新选择文件。"), + "files.type_not_allowed": Plain( + "这种类型的文件不能上传", "只收常见的文档、表格、图片和文字文件,别的类型可能带来风险。", _Y, + "另存为 PDF、Word、Excel、CSV、图片或文字文件再上传。"), + "files.type_not_accepted": Plain( + "这里不收这种文件", "表单的这一项限定了文件类型或大小。", _Y, "按提示换一个文件。"), + "files.content_mismatch": Plain( + "文件内容和扩展名对不上", "改过扩展名的文件,系统没法按它说的类型读。", _Y, "用原始文件重新上传。"), + "files.context_invalid": Plain( + "没说清文件是给哪里用的", "上传要对应一个入口、一条待办或一个蓝图,系统才知道谁能用它。", _A, + "从表单里的文件控件上传。"), + "files.forbidden": Plain( + "没有权限", "只有能用这个入口、处理这条待办、看得到这次运行或这条记录的人,才能上传或下载。", _M, + "请应用的管理者给你授权。"), + "files.ref_invalid": Plain( + "文件没有上传好", "提交的是文件的引用,要先上传、拿到引用。", _Y, "重新上传这个文件再提交。"), + "files.not_found": Plain( + "文件不见了", "上传后 24 小时还没提交的文件会被清理。", _Y, "重新上传再提交。"), + "files.not_yours": Plain( + "这个文件不是你上传的", "只能提交自己上传的文件。", _Y, "自己上传一份再提交。"), + "files.already_bound": Plain( + "这个文件已经提交过一次", "一次上传只能随一次提交进运行,这样每次运行用的是哪份文件说得清。", _Y, + "再提交的话请重新上传。"), + "files.context_mismatch": Plain( + "文件是在别的地方上传的", "文件只能用在上传时说明的那个入口或那条待办上。", _Y, "在这里重新上传。"), + "files.bound": Plain( + "已经提交的文件不能删除", "它是那次运行的证据,删掉就说不清当时用的是什么。", _Y, "不需要处理。"), + "files.content_lost": Plain( + "文件内容不在了或被改动过", "下载到的内容如果和当时登记的不一样,就不能当证据用。", _M, "请管理员检查数据目录。"), +}) +# ---------------------------------------------------------------- 蓝图与模板(包 B1:blueprints/ops.py 的 bp.*、 +# blueprints/instantiate.py、blueprints/generation.py 的 tpl.*) +PLAIN.update({ + "bp.missing": Plain( + "蓝图上还有没填的卡片", "缺了这一项,模板没法生成能运行的工作流。", _Y, "在卡片上补上,或者告诉助手这一项是什么。"), + "bp.unconfirmed": Plain( + "有助手或模板提的项还没确认", "没确认的项是猜的,发布出去就成了正式的口径和规则。", _Y, "逐项看过,对的点确认,不对的直接改。"), + "bp.data_unmapped": Plain( + "有要看的数还没对到表或口径", "对不到数据,就算不出这个数。", _A, + "请助手按数据目录对到表(或复用已发布的口径),对到之后由你确认。"), + "bp.people_unbound": Plain( + "有一步还没定谁来处理", "流程走到这一步就没人接手。", _Y, "在「谁来做」里选人、组或岗位。"), + "bp.template_mismatch": Plain( + "卡片上写的超出了这个场景能做的", "超出的那部分不会生效,做出来的应用和你说的对不上。", _Y, + "按提示删掉或改小,或者换一个场景。"), + "bp.refused": Plain( + "这处修改没有采纳", "改动不符合这张卡片的写法。", _Y, "按提示的写法重新改。"), + "tpl.skeleton_changed": Plain( + "改动超出了模板留出的位置", "模板的结构是锁住的,审批、写入、出具这些地方不能被顺手改掉。", _A, + "只改模板留给助手的取数和指标;结构要变,请换一个场景或回画布。"), + "tpl.joint_unfilled": Plain( + "还有取数或指标没写好", "缺了它,试运行算不出数。", _A, "请助手填上;填不上时补充说明数从哪来、怎么算。"), + "tpl.joint_refused": Plain( + "助手想改模板锁住的地方,没有采纳", "模板锁住的结构不归助手改。", _A, "不需要处理;要改结构请回到卡片或换一个场景。"), + "tpl.metric_expr": Plain( + "指标的算法写得不合规矩", "指标只能从取数结果里按格取数再算,这样每个数都能追到出处。", _A, "请助手按规矩重写这个指标。"), + "tpl.metric_column": Plain( + "指标要用的列,取数的 SQL 里没有", "运行时这个指标会算不出来。", _A, "请助手让取数的 SQL 交出这一列,或改指标。"), + "tpl.sql_rejected": Plain( + "取数的 SQL 不是只读的一条查询", "取数只能读,不能改数据,也只能是一条语句。", _A, "请助手重写成一条只读的查询。"), +}) +PLAIN_PREFIX: dict[str, Plain] = { + # 子工作流、口径卡固定的版本不是「已发布且未退役」的(apps/versions.py) + "subgraph_version_": Plain( + "引用的工作流版本没发布或已退役", "正式运行发起时会被拒绝。", _Y, "在那个工作流里发布新版本,再把这里的引用换过去。"), + "caliber_version_": Plain( + "引用的口径卡版本没发布或已退役", "正式运行发起时会被拒绝。", _Y, "在那个工作流里发布新版本,再把这里的引用换过去。"), +} + +#: 要管理员处理的编号:端点、能力登记归管理员管(受管级发布、降级的权限在发布单里另报 plan.admin_required、 +#: plan.downgrade_admin) +ADMIN_CODES = frozenset(code for code, plain in PLAIN.items() if plain.who == _M) def plain_of(code: str | None) -> Plain | None: @@ -38,9 +366,31 @@ def plain_of(code: str | None) -> Plain | None: return None +def who_of(issue: dict[str, Any]) -> str: + """这条问题归谁处理(you / assistant / admin)。依次看:要管理员的编号;自动修复给的修复种类(fix_kind:choice 要人 + 选,auto、assist 助手能做);应用检查只有人能处理的(api/copilot_gen.APP_HUMAN_ONLY);白话里登记的那一档(应用检查 + 其余的登记成「助手可以修」:助手的自查会修它们);没登记的应用检查算「助手可以修」,别的算「你来定」。""" + from app.api.copilot_gen import APP_HUMAN_ONLY + + code = str(issue.get("code") or "") + if code in ADMIN_CODES: + return _M + kind = issue.get("fix_kind") + if kind == "choice": + return _Y + if kind in ("auto", "assist"): + return _A + if code in APP_HUMAN_ONLY: + return _Y + plain = plain_of(code) + if plain is not None: + return plain.who + return _A if code.startswith("app.") else _Y + + def with_plain(issue: dict[str, Any]) -> dict[str, Any]: - """给一条问题补上 plain = {title, why, who, action};没登记的不补。""" + """给一条问题补上 plain = {title, why, who, action};没登记的不补(照旧显示技术说法)。who 按 who_of 判。""" plain = plain_of(issue.get("code")) if plain is None: return issue - return {**issue, "plain": {"title": plain.title, "why": plain.why, "who": plain.who, "action": plain.action}} + return {**issue, "plain": {"title": plain.title, "why": plain.why, "who": who_of(issue), "action": plain.action}} diff --git a/backend/app/process/actions.py b/backend/app/process/actions.py index c1a21ffb..e75a269e 100644 --- a/backend/app/process/actions.py +++ b/backend/app/process/actions.py @@ -320,10 +320,13 @@ async def send(prep: Prepared, capability: Any, *, run_id: str, node_id: str, ex environment=prep.environment, preview=prep.preview, attempt=prep.attempt) if prep.environment == "simulated": + from app.capabilities.platform import is_platform + receipt = {"simulated": True, "environment": "simulated", "endpoint": prep.endpoint} await _set(action_id, ("pending",), state="simulated", receipt=receipt) emit(EventType.ACTION_SIMULATED, action_id=action_id, capability=name, - message="演练:探索运行里端点没有测试环境,没有发送请求") + message="演练:探索运行里不写平台的记录表和数据源,没有写入" if is_platform(name) + else "演练:探索运行里端点没有测试环境,没有发送请求") return _output(action_id, prep, "simulated", None, receipt) # 先记 sent 再发:发到一半进程没了,重启后看到的是 sent,只能核实,不会当成没发过再发一次 @@ -360,10 +363,15 @@ async def send(prep: Prepared, capability: Any, *, run_id: str, node_id: str, ex emit(EventType.TOOL_END, tool=name, preview=receipt["summary"], artifact=artifact, action_id=action_id) return _output(action_id, prep, "confirmed", status, result.body) if status is None and not result.unknown: - # 连接都没建立、端点配置不对:请求确定没有发出去 + # 连接都没建立、端点配置不对:请求确定没有发出去。平台内置能力(capabilities/platform.py)是平台自己拒收的 + # (记录表的字段对不上、导入要人在数据页确认……),说「没有写入」 + from app.capabilities.platform import is_platform + await _set(action_id, ("sent",), state="failed", error=result.error or "请求没有发出") emit(EventType.ACTION_FAILED, action_id=action_id, capability=name, error=result.error) emit(EventType.TOOL_ERROR, tool=name, error=result.error or "请求没有发出", action_id=action_id) + if is_platform(name): + raise ActionFailed(f"「{name}」没有写入:{result.error or '平台没有执行'}") raise ActionFailed(f"「{name}」没有发送成功:{result.error or '请求没有发出'}") if status is not None and 400 <= status < 500 and status != 429: await _set(action_id, ("sent",), state="failed", response_status=status, diff --git a/backend/app/process/tasks.py b/backend/app/process/tasks.py index d0726872..73dfc046 100644 --- a/backend/app/process/tasks.py +++ b/backend/app/process/tasks.py @@ -11,6 +11,10 @@ - 关登录时谁都能回复(「都算」),回复人记自报的署名。开了登录:派给人的认用户名,派给组的认组,派给「任何人」的要 builder 以上(这类待办来自画布、定时任务,是给搭建者看的),等外部系统的只有管理员能代为处理。 - tick:提醒、升级(加派一份,escalation_level+1,只升一次)、超时驳回。永不自动批准。 +- 蓝图的试运行(origin_kind=trial,docs/design/normal-user-apps.md N4):每一步都派给发起试运行的人自己,按真实设置显示 + 时限,但调度不对它们做提醒、升级、超时驳回——试运行不该把待办推到真实的处理人、上级那里。 +- 个人应用提交审核(kind=review,N7):没有 Approval、不恢复运行,挂在个人应用最近一次成功的刷新上;派给选定的搭建者 + 或组。在待办里只能退回,同意要在共享副本上走发布单,发布完自动记为已发布(blueprints/personal.py)。 """ from __future__ import annotations @@ -133,6 +137,67 @@ async def open_reconcile(session: AsyncSession, action: Any, *, title: str) -> T return task +#: 个人应用提交审核的待办(docs/design/normal-user-apps.md N7)。没有 Approval,按 correlation_key = blueprint:<蓝图 id> +#: 找回提交审核的蓝图 +REVIEW_KIND = "review" + + +async def open_review(session: AsyncSession, *, run: Run, app_id: str, blueprint_id: str, title: str, + to: list[tuple[str, str]]) -> Task: + """个人应用提交审核:开一条 review 待办,派给选定的搭建者或组(组在这一刻展开成成员,同改派),来源记 review。 + + 待办的 run_id 不能为空(带外键,开待办的事件、通知都按运行走):挂在个人应用最近一次成功的刷新上——审核的人要看的 + 也正是这次用真数出的结果。这次运行已经结束,不会被恢复:回复走 _respond_review,不调 run_manager.resume。调用方提交, + 提交后 announce。""" + task = Task(run_id=run.id, node_id=None, app_id=app_id, app_version=None, kind=REVIEW_KIND, title=title[:300], + policy={"kind": "any"}, correlation_key=f"blueprint:{blueprint_id}") + session.add(task) + await session.flush() + targets: list[tuple[str, str, str]] = [] + for kind, name in dict.fromkeys(to): + targets += await _expand(session, task, kind, name, REVIEW_KIND) + for kind, name, source in dict.fromkeys(targets): + session.add(TaskAssignment(task_id=task.id, principal_kind=kind, principal=name, source=source)) + await session.flush() + return task + + +async def review_handler(session: AsyncSession, task: Task, principal: Any) -> bool: + """这个人是不是这条审核待办的处理人(派给他或他的组、没撤回,同 handles):只有他们能取个人蓝图的共享副本。""" + return handles((await _assignments(session, [task.id])).get(task.id, []), principal) + + +async def close_review(session: AsyncSession, blueprint_id: str, principal: Any, outcome: dict[str, Any], *, + require_handler: bool = False) -> str | None: + """审核有了结果(副本发布了、或者退回了):把这个蓝图还在等的审核待办收掉(条件 UPDATE,和别人的回复抢同一行), + 结论写进 outcome。require_handler 为真时只有处理人能收(退回),不是派给他的抛 403。返回待办 id,没有在等的返回 + None。调用方提交。""" + task = await session.scalar(select(Task).where(Task.correlation_key == f"blueprint:{blueprint_id}", + Task.kind == REVIEW_KIND, Task.status == "pending")) + if task is None: + return None + rows = (await _assignments(session, [task.id])).get(task.id, []) + mine = next((a for a in rows if principal is not None and _matches(a, principal)), None) + if require_handler and mine is None: + raise TaskRefused("这条待办没有派给你", status_code=403, code="task_not_assigned") + now = utcnow() + username = getattr(principal, "username", None) + claimed = await session.execute( + update(Task).where(Task.id == task.id, Task.status == "pending") + .values(status="resolved", resolved_by=username, resolved_at=now, outcome=outcome)) + if claimed.rowcount != 1: + return None + if mine is not None: + await session.execute(update(TaskAssignment).where(TaskAssignment.id == mine.id).values( + status="responded", responded_by=username, responded_at=now, + verified=bool(getattr(principal, "verified", False)), + response={"decision": outcome.get("decision"), "note": outcome.get("note") or ""})) + await session.execute(update(TaskAssignment).where(TaskAssignment.task_id == task.id, + TaskAssignment.status == "pending") + .values(status="withdrawn")) + return task.id + + async def _assign(session: AsyncSession, task: Task, run: Run | None, assignee: Any, *, source: str | None = None) -> list[TaskAssignment]: rows = [] @@ -144,11 +209,18 @@ async def _assign(session: AsyncSession, task: Task, run: Run | None, assignee: return rows +#: 蓝图试运行的运行来源(engine/origin.py):待办派给发起人自己、调度不处理时限 +TRIAL_ORIGIN = "trial" + + async def _targets(session: AsyncSession, task: Task, run: Run | None, assignee: Any) -> list[tuple[str, str, str]]: """(principal_kind, principal, source) 列表,去重。""" spec = assignee if isinstance(assignee, dict) else {} kind = spec.get("kind") out: list[tuple[str, str, str]] = [] + if run is not None and run.origin_kind == TRIAL_ORIGIN and kind != "hook": + # 试运行:不管图里派给谁(岗位、组、表达式),都派给发起试运行的人自己,来源记 trial。等外部系统的照旧等外部系统 + return [("user", run.started_by, TRIAL_ORIGIN) if run.started_by else ("anyone", "", TRIAL_ORIGIN)] if kind == "slot": slot = str(spec.get("slot") or "") bound = await _slot_binding(session, run, slot) @@ -408,6 +480,8 @@ async def respond(task_id: str, principal: Any, *, decision: Any, values: dict[s raise TaskRefused("待办不存在,所属的运行可能已被删除", status_code=404) if task.kind == "reconcile": return await _respond_reconcile(session, task, principal, decision, values, note) + if task.kind == REVIEW_KIND: + return await _respond_review(session, task, principal, decision, note) if task.status != "pending": raise TaskRefused(_closed(task.status)) if inquiry_busy(task.run_id): @@ -416,6 +490,7 @@ async def respond(task_id: str, principal: Any, *, decision: Any, values: dict[s rows = (await _assignments(session, [task.id])).get(task.id, []) mine = _pick(task, rows, principal) response, verdict = _engine_response(task, approval, decision, values, note, payload_hash) + response = await _bind_files(session, task, principal, response) now = utcnow() marked = await session.execute( update(TaskAssignment).where(TaskAssignment.id == mine.id, TaskAssignment.status == "pending") @@ -497,6 +572,40 @@ async def _respond_reconcile(session: AsyncSession, task: Task, principal: Any, return {"task": await detail(task_id, principal), "resolved": True, "run": out.get("run")} +async def _bind_files(session: AsyncSession, task: Task, principal: Any, response: Any) -> Any: + """回复里表单的文件(docs/design/normal-user-apps.md N9):核对是这个人在这条待办上传的、还没用过,绑到这次运行, + 和回复一起提交;交给节点的值换成登记的那一份引用。引用不对按表单错误交回,落到那个字段上。""" + from app.files import store as files_store + + value = response.get("value") if isinstance(response, dict) else None + if not isinstance(value, dict) or not files_store.file_fields(task.form): + return response + try: + bound = await files_store.bind_in(session, task.form, value, principal=principal, run_id=task.run_id, + context={"task_id": task.id}) + except files_store.FileRefused as e: + await session.rollback() + raise FormInvalid([{"path": e.field or "", "code": files_store.FILE_ERROR_CODE, "message": e.message}]) from e + return {**response, "value": bound} + + +async def _respond_review(session: AsyncSession, task: Task, principal: Any, decision: Any, + note: str | None) -> dict[str, Any]: + """审核待办(个人应用提交审核)在待办里只能退回:同意要取共享副本、在副本上走发布单,发布单做完自动记为已发布 + (blueprints/personal.review_published)。退回的结论、蓝图状态和通知由 blueprints/personal.reject_review 做。""" + if task.status != "pending": + raise TaskRefused(_closed(task.status)) + if decision != "reject": + raise TaskRefused("审核个人应用不在这里同意:请取一份共享副本,在副本上用真数试一次、走发布单,发布之后这条待办" + "自动记为已发布;不发布请退回", status_code=422, code="task_decision_invalid") + task_id, run_id = task.id, task.run_id + await session.rollback() + from app.blueprints.personal import reject_review + + await reject_review(task_id, principal, note=note) + return {"task": await detail(task_id, principal), "resolved": True, "run": await _run(run_id)} + + async def close_reconcile(session: AsyncSession, action_id: str, principal: Any, outcome: str, note: str | None) -> str | None: """核实之后把这个动作的核实待办收掉(条件 UPDATE,和 tick、别人的回复抢同一行)。返回待办 id,没有返回 None。""" @@ -652,15 +761,17 @@ async def _notify(task_id: str, event: str, users: list[str]) -> int: async def tick(now: datetime | None = None) -> int: - """调度循环每一拍:提醒、升级、超时驳回(永不自动批准)。返回处理的条数。""" + """调度循环每一拍:提醒、升级、超时驳回(永不自动批准)。返回处理的条数。试运行的待办不处理(只显示时限)。""" now = now or utcnow() action = func.json_extract(Task.on_timeout, "$.action") + trial = select(Run.id).where(Run.origin_kind == TRIAL_ORIGIN) async with SessionLocal() as session: - due = list((await session.execute(select(Task.id).where(Task.status == "pending", or_( - and_(Task.remind_at.is_not(None), Task.remind_at <= now), - and_(Task.due_at.is_not(None), Task.due_at <= now, action == "reject"), - and_(Task.due_at.is_not(None), Task.due_at <= now, action == "escalate", Task.escalation_level == 0), - )).order_by(Task.due_at))).scalars()) + due = list((await session.execute(select(Task.id).where( + Task.status == "pending", Task.run_id.not_in(trial), or_( + and_(Task.remind_at.is_not(None), Task.remind_at <= now), + and_(Task.due_at.is_not(None), Task.due_at <= now, action == "reject"), + and_(Task.due_at.is_not(None), Task.due_at <= now, action == "escalate", Task.escalation_level == 0), + )).order_by(Task.due_at))).scalars()) done = 0 for task_id in due: try: @@ -906,7 +1017,7 @@ async def _describe(session: AsyncSession, tasks: list[Task], principal: Any) -> approvals = {a.id: a for a in (await session.execute( select(Approval).where(Approval.id.in_([t.approval_id for t in tasks if t.approval_id])))).scalars()} runs = {r.id: r for r in (await session.execute( - select(Run.id, Run.workflow_name, Run.graph, Run.origin) + select(Run.id, Run.workflow_name, Run.graph, Run.origin, Run.origin_kind) .where(Run.id.in_({t.run_id for t in tasks})))).all()} apps = dict((await session.execute(select(App.id, App.name).where( App.id.in_({t.app_id for t in tasks if t.app_id})))).all()) @@ -917,6 +1028,10 @@ async def _describe(session: AsyncSession, tasks: list[Task], principal: Any) -> payload = dict(approvals[task.approval_id].payload or {}) if task.approval_id in approvals else {} if task.kind == "reconcile": payload = await _reconcile_payload(session, task) + elif task.kind == REVIEW_KIND: + from app.blueprints.personal import review_payload + + payload = await review_payload(session, task) run = runs.get(task.run_id) out.append({ "id": task.id, "approval_id": task.approval_id, "run_id": task.run_id, "node_id": task.node_id, @@ -940,6 +1055,8 @@ async def _describe(session: AsyncSession, tasks: list[Task], principal: Any) -> "created_at": _iso(task.created_at), # 这条待办上出现的人的显示名(派给谁、谁回复、谁处理、升级给谁):界面写显示名,悬停给用户名 "people": {u: names[u] for u in people_of(task, rows) if u in names}, + # 蓝图试运行的待办:派给了发起试运行的人自己,界面上写「以试运行身份同意 / 驳回」 + **({"trial": True} if run is not None and run.origin_kind == TRIAL_ORIGIN else {}), }) return out diff --git a/backend/app/records/__init__.py b/backend/app/records/__init__.py index f8242cbc..723c10f3 100644 --- a/backend/app/records/__init__.py +++ b/backend/app/records/__init__.py @@ -6,7 +6,9 @@ - 钉版本:运行开始时 data_versions 记下高水位 _seq;查询连接上建同名 TEMP VIEW,只露出 _seq ≤ 高水位、没被更正过的行; - 行级可见:同一套临时视图按人过滤(use 只看自己的,observe / manage 看全部);正式运行以服务身份跑、不过滤。 -包 B3 实现。 +模块:store(文件层:建表、加列、追加、高水位、视图语句)、tables(records_tables 与数据源的登记、表版本, +ensure_table)、access(看哪些行)、views(查询时的 RecordsView、data_versions 里的那一项)、actions(平台能力 +records_append / records_lookup 的执行)、listing(记录列表)。 """ from __future__ import annotations diff --git a/backend/app/records/access.py b/backend/app/records/access.py new file mode 100644 index 00000000..fd95a184 --- /dev/null +++ b/backend/app/records/access.py @@ -0,0 +1,72 @@ +"""记录表的行级可见(docs/design/normal-user-apps.md N8、§3.7、§3.12)。 + +谁看得到哪些行,只有三种:all(全部)、mine(只看自己提交的,_submitted_by = 看的人)、none(一行都不给)。 +- 正式运行以服务身份跑,看全部:看板读的是正式运行的封存结果,汇总是全量的(作者的选择,发布摘要里写明); +- 别的运行(问数据、试运行、个人应用的刷新)按发起人和这张表所属应用的授权:use 只看自己的,observe、manage 看全部; +- 记录列表(records_list、GET /api/apps/{id}/records)按看的人,同一套规则; +- 关登录时所有人等同管理员,看全部;管理员看全部。 +过滤在查询连接的临时视图上做(records/store.view_prelude),模型和 SQL 都绕不过去。 +""" +from __future__ import annotations + +from typing import Any + +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +SCOPES = ("all", "mine", "none") + + +def scope_of_role(principal: Any, role: str | None) -> str: + """看的人在应用上拿到的那一档 → 看哪些行。""" + from app.apps.access import at_least + + if principal.mode == "off" or principal.role == "admin": + return "all" + if at_least(role, "observe"): + return "all" + return "mine" if role == "use" else "none" + + +async def scope_of(session: AsyncSession, principal: Any, app_id: str | None) -> str: + """看的人对这张表(所属应用 app_id)看哪些行。还没归到应用的(试运行时按蓝图建的):搭建者看全部,使用者看自己的。""" + from app.apps.access import app_role + from app.db.models_apps import App + + if principal.mode == "off" or principal.role == "admin": + return "all" + if not app_id: + return "all" if principal.at_least("builder") else "mine" + app = await session.get(App, app_id) + if app is None: + return "all" if principal.at_least("builder") else "none" + return scope_of_role(principal, await app_role(session, principal, app)) + + +async def scope_of_run(session: AsyncSession, app_id: str | None, *, run_class: str | None, + started_by: str | None) -> dict[str, Any]: + """一次运行看哪些行,记进 data_versions:{"rows": all|mine|none, "viewer"?: 发起人}。发起时定下,续跑、恢复沿用。""" + from app.api.deps import auth_mode + + if run_class == "formal": + return {"rows": "all"} + mode = auth_mode() + if mode == "off": + return {"rows": "all"} + principal = await _principal(session, started_by, mode) + if principal is None: + return {"rows": "none"} + scope = await scope_of(session, principal, app_id) + return {"rows": scope, **({"viewer": principal.username} if scope == "mine" else {})} + + +async def _principal(session: AsyncSession, username: str | None, mode: str) -> Any | None: + from app.auth.sessions import principal_of + from app.db.models import User + + if not username: + return None + user = (await session.execute(select(User).where(User.username == username))).scalar_one_or_none() + if user is None or user.disabled: + return None + return await principal_of(session, user, mode) diff --git a/backend/app/records/actions.py b/backend/app/records/actions.py new file mode 100644 index 00000000..66bf0f3a --- /dev/null +++ b/backend/app/records/actions.py @@ -0,0 +1,162 @@ +"""records_append / records_lookup 的执行(平台内置能力,capabilities/platform.py)。 + +由 process/actions.send 经 registry.endpoint_request 调到这里:生效记录已经先写好(pending → sent),这里只管写那一行、 +交回回执。幂等键就是动作键:发送用的是「动作键:第几次」,这里只取动作键,同一个动作不论第几次发都只落一行 +(记录表 store.append 按它去重)。写下的行里有文件字段的,把那几个文件绑到这一行(下载按行级可见核对)。 + +写之前核对三样(写进去的东西谁都看得到,不能凭图里写的一个名字就写): +- 正式运行只写自己的记录表:表出自哪个蓝图,就只收那个蓝图发布出来的工作流的运行(没有蓝图的表,收钉着它的应用里的 + 工作流)——不然一张手改过的图就能往别的应用的表里写(records.table_foreign); +- 更正(supersedes)只能更正提交的人看得到的那一行:按行级可见(records/access),使用者只能更正自己提交的; +- 文件只绑这次运行提交时绑上的(StoredFile.bound_run_id 是这次运行):值里随便写一个文件编号,不会把别人的文件挂到 + 这一行上、让看得到这一行的人都能下载。 +""" +from __future__ import annotations + +import asyncio +import json +from typing import Any + +from sqlalchemy import select + +from app.db.base import SessionLocal +from app.records import store + + +def _result(status: int | None, body: Any = None, *, error: str | None = None, environment: str = "prod") -> Any: + from app.capabilities.registry import EndpointResult + + return EndpointResult(status=status, body=body, error=error, environment=environment) + + +def action_key_of(idem_key: str | None) -> str: + """「动作键:第几次」→ 动作键。""" + return str(idem_key or "").rsplit(":", 1)[0] + + +async def append_action(args: dict[str, Any], *, idem_key: str | None, run_id: str | None, on_behalf: Any, + environment: str) -> Any: + from app.capabilities.platform import actor_of + from app.records.tables import columns_of, find_table, path_of, refuse_retired + + values = args.get("values") + if isinstance(values, str): + try: + values = json.loads(values) + except ValueError: + return _result(None, error="要写入的内容需要是一组字段和值(JSON 对象)", environment=environment) + actor = actor_of(on_behalf) + supersedes = str(args.get("supersedes") or "").strip() or None + async with SessionLocal() as session: + table = await find_table(session, str(args.get("table") or "")) + source = None + if table is not None and table.source_id: + from app.db.models import DataSource + + source = await session.get(DataSource, table.source_id) + try: + if table is not None: + refuse_retired(table) + await _check_writer(session, table, run_id) + if supersedes: + await _check_supersedes(session, table, supersedes, actor) + except store.RecordsRefused as e: + return _result(None, error=e.message, environment=environment) + if table is None: + return _result(None, error=f"找不到记录表「{args.get('table')}」,可能已被删除,请重新发布应用", + environment=environment) + try: + columns = columns_of(table) + done = await asyncio.to_thread( + store.append, path_of(table), columns, values, version=table.version, run_id=run_id, + actor=actor, action_key=action_key_of(idem_key), supersedes=supersedes) + except store.RecordsRefused as e: + return _result(None, error=e.message, environment=environment) + if not done.duplicate: + await _bind_files(table, columns, done, run_id) + return _result(200, {"table": table.table_key, "version": table.version, "source": source.name if source else None, + **done.receipt()}, environment=environment) + + +async def _check_writer(session: Any, table: Any, run_id: str | None) -> None: + """正式运行只写自己的记录表:表出自蓝图的,运行的工作流要是那个蓝图发布出来的;没有蓝图的,要是钉着这张表的应用里的 + 工作流。不是正式运行的(探索运行在 actions.prepare 就定成演练,走不到这里)、没有运行的(平台内部直接调)不核对。""" + from app.db.models import Run + from app.db.models_apps import App + from app.db.models_blueprints import Blueprint + + run = await session.get(Run, run_id) if run_id else None + if run is None or run.run_class != "formal": + return + owners: set[str] = set() + if table.blueprint_id: + bp = await session.get(Blueprint, table.blueprint_id) + if bp is not None and bp.workflow_id: + owners.add(bp.workflow_id) + elif table.app_id: + app = await session.get(App, table.app_id) + pins = ((app.draft or {}).get("pins") or []) if app is not None else [] + owners |= {str(p.get("workflow_id")) for p in pins if isinstance(p, dict) and p.get("workflow_id")} + if run.workflow_id not in owners: + raise store.RecordsRefused("records.table_foreign", f"记录表「{table.name}」不属于这个应用:正式运行只能写自己应用的" + "记录表,请检查写记录表那一步选的表") + + +async def _check_supersedes(session: Any, table: Any, row_id: str, actor: str | None) -> None: + """更正只能更正提交的人看得到的那一行(行级可见同记录列表:使用者只看得到自己提交的)。看不到的说「不在这张表里」, + 不说它在不在。""" + from app.records.access import scope_of_run + from app.records.tables import columns_of, path_of + + scope = await scope_of_run(session, table.app_id, run_class=None, started_by=actor) + if scope.get("rows") == "all": + return + row = await asyncio.to_thread(store.row_by_id, path_of(table), columns_of(table), row_id) + if scope.get("rows") != "mine" or row is None or row.get("_submitted_by") != actor: + raise store.RecordsRefused("records.supersede_missing", "要更正的那一行不在这张记录表里") + + +async def _bind_files(table: Any, columns: list[Any], done: Any, run_id: str | None) -> None: + """这一行的文件字段:把文件绑到这一行(StoredFile.bound_record)。下载时读得到这一行的人才能下(files/store.py)。 + 只绑这次运行提交时绑上的文件(bound_run_id 是这次运行):值里写的别的文件编号不认。""" + from app.db.models_blueprints import StoredFile + + ids = [] + for column in columns: + if column.type != "file": + continue + raw = done.values.get(column.name) + try: + ref = json.loads(raw) if isinstance(raw, str) else raw + except ValueError: + continue + if isinstance(ref, dict) and isinstance(ref.get("file_id"), str): + ids.append(ref["file_id"]) + if not ids: + return + async with SessionLocal() as session: + for row in (await session.execute(select(StoredFile).where(StoredFile.id.in_(ids)))).scalars(): + if row.bound_record is None and run_id and row.bound_run_id == run_id: + row.bound_record = {"table_id": table.id, "row_id": done.row_id} + await session.commit() + + +async def lookup_action(args: dict[str, Any], *, environment: str) -> Any: + """结果未知时按幂等键查:找到这次动作的生效记录,从它的预览里取写的是哪张表,再按动作键查那一行。""" + from app.db.models import ActionRecord + from app.records.tables import columns_of, find_table, path_of + + idem = str(args.get("idempotency_key") or "") + async with SessionLocal() as session: + rec = (await session.execute(select(ActionRecord).where(ActionRecord.idem_key == idem))).scalar_one_or_none() + preview = rec.preview if rec is not None and isinstance(rec.preview, dict) else {} + table = await find_table(session, str(preview.get("table") or "")) if preview else None + if table is None: + return _result(404, {"found": False}, environment=environment) + try: + got = await asyncio.to_thread(store.lookup, path_of(table), columns_of(table), action_key_of(idem)) + except store.RecordsRefused as e: + return _result(None, error=e.message, environment=environment) + if got is None: + return _result(404, {"found": False}, environment=environment) + return _result(200, {"table": table.table_key, "version": table.version, **got}, environment=environment) diff --git a/backend/app/records/listing.py b/backend/app/records/listing.py new file mode 100644 index 00000000..08c992ee --- /dev/null +++ b/backend/app/records/listing.py @@ -0,0 +1,107 @@ +"""记录的逐行查看(组件 records_list、GET /api/apps/{id}/records,docs/design/normal-user-apps.md §3.7、§4.7)。 + +每次打开按看的人实时过滤,不走封存(同实例列表):use 只看自己提交的,observe、manage 看全部;关登录时看全部(没填署名、 +又要只看自己的,分不出谁是谁,按全部给,同实例列表)。一张记录表的各版本合在一起列:新版本在前、每个版本里新提交的 +在前;被更正过的行默认不列,history 打开时列出并标 superseded。 + +遮罩:别人提交的行里,数据源设了遮罩的列(「填什么」里标了敏感的,加上管理员在数据页手工加的)换成「已遮罩」——和看板证据 +同一套遮罩列、同一个说法(P4、P5);自己提交的行照原样给(是自己填的)。附件列遮掉之后连文件的引用也不给。 + +返回的形状同 frontend/src/typesBlueprint.ts 的 RecordsPage:{table, version, columns, items, mine_only},另带 next_cursor +(下一页的游标,「版本:序号」,没有下一页为空)和 state(empty:这个应用还没有记录表)。 +""" +from __future__ import annotations + +import asyncio +from typing import Any + +from sqlalchemy.ext.asyncio import AsyncSession + +from app.records import store +from app.records.access import scope_of_role +from app.records.tables import columns_of, path_of, tables_of_app, versions_of + +#: 一页最多几行 +PAGE_MAX = 200 + + +async def _masked(session: AsyncSession, row: Any) -> set[str]: + """这一版登记成的数据源设了遮罩的列(小写)。""" + from app.data.engine import masked_columns + from app.db.models import DataSource + + source = await session.get(DataSource, row.source_id) if row.source_id else None + return {c.lower() for c in masked_columns(source.options if source is not None else None)} + + +def _shown(item: dict[str, Any], version: int, masked: set[str], viewer: str | None) -> dict[str, Any]: + """一行交给看的人的样子:别人提交的行,遮罩列有值的换成「已遮罩」(P4)。""" + from app.api.evidence import MASKED + + out = {**item, "_version": version} + if not masked or (viewer and item.get("_submitted_by") == viewer): + return out + values = item.get("values") or {} + out["values"] = {k: MASKED if k.lower() in masked and v is not None else v for k, v in values.items()} + return out + + +def _cursor(raw: str | None) -> tuple[int, int] | None: + if not raw: + return None + version, _, seq = str(raw).partition(":") + return (int(version), int(seq)) if version.isdigit() and seq.isdigit() else None + + +async def page(session: AsyncSession, app: Any, *, principal: Any, role: str | None, table: str | None = None, + who: str | None = None, cursor: str | None = None, history: bool = False, + limit: int = 50) -> dict[str, Any]: + tables = await tables_of_app(session, app.id) + current = next((t for t in tables if table in (None, "", t.table_key, t.id)), None) + if current is None and table: + # 也认数据源名(rec_…):模板里手上拿着的可能是它 + from app.records.tables import find_table + + found = await find_table(session, table) + current = next((t for t in tables if found is not None and t.table_key == found.table_key), None) + scope = scope_of_role(principal, role) + if who == "mine" and scope == "all": + scope = "mine" + viewer = principal.username + if scope == "mine" and not viewer and principal.mode == "off": + scope = "all" + if current is None: + return {"table": table, "version": 0, "columns": [], "items": [], "mine_only": scope == "mine", + "state": "empty", "next_cursor": None} + limit = max(1, min(int(limit), PAGE_MAX)) + versions = await versions_of(session, current.table_key) + at = _cursor(cursor) + items: list[dict[str, Any]] = [] + more = False + for row in versions: + if at is not None and row.version > at[0]: + continue + before = at[1] if at is not None and row.version == at[0] else None + cols = columns_of(row) + try: + got, more_here = await asyncio.to_thread( + store.rows, path_of(row), cols, scope=scope, viewer=viewer, history=history, before=before, + limit=limit - len(items)) + except store.RecordsRefused: + continue + masked = await _masked(session, row) + items += [_shown(r, row.version, masked, viewer) for r in got] + if len(items) >= limit: + more = more_here or row is not versions[-1] + break + columns: list[dict[str, Any]] = [] + seen: set[str] = set() + for row in versions: + for c in columns_of(row): + if c.name.lower() not in seen: + seen.add(c.name.lower()) + columns.append({"name": c.name, "label": c.label or c.name, "type": c.type}) + last = items[-1] if items else None + return {"table": current.table_key, "version": versions[0].version if versions else current.version, + "columns": columns, "items": items, "mine_only": scope == "mine", + "next_cursor": f"{last['_version']}:{last['_seq']}" if more and last else None} diff --git a/backend/app/records/store.py b/backend/app/records/store.py new file mode 100644 index 00000000..27ff1a67 --- /dev/null +++ b/backend/app/records/store.py @@ -0,0 +1,482 @@ +"""记录表的文件层(docs/design/normal-user-apps.md N8、§3.7):一个表版本一个 SQLite 文件,只许追加。 + +**文件。** data/records/.v.db,里面只有一张业务表 records:系统列(records.SYSTEM_COLUMNS)、 +业务列(「填什么」卡片生成),外加一列不对外的 _action_key(幂等键,唯一)。查询走连接上的同名临时视图 +(view_select),视图不露 _action_key。 + +**写。** 只有 append 一条路:单进程锁(_WRITE_LOCK)里开一个短事务,先按 action_key 查——同一个动作第二次来交回 +第一次写下的那一行,不再写;更正是一次新的追加,带 _supersedes 指向被更正的行,原行不改。_seq 是 SQLite 的 rowid +(INTEGER PRIMARY KEY),只增不减:从不删行,也就不会复用。 + +**读。** 高水位(high_water)是现在最大的 _seq。一次运行在开始时记下它(engine/runner._data_versions),之后这次 +运行查到的都是 _seq ≤ 高水位、在那一刻没被更正过的行:行只追加、不改,所以同一次运行查几遍都是同一份。 + +这里的函数都是同步的(sqlite3 直连、关 DQS),调用方放进线程。表结构的登记、数据源在 records/tables.py。 +""" +from __future__ import annotations + +import json +import math +import os +import re +import sqlite3 +import threading +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +from app.core.config import settings +from app.data.engine import open_checked_sqlite +from app.db.base import new_id +from app.records import SYSTEM_COLUMNS + +#: 文件里那张业务表的名字。看板的 SQL 写 FROM records +TABLE = "records" +#: 不对外的幂等键列:视图不露它,写 main.records 的 SQL 被只读守卫拒掉 +ACTION_KEY_COLUMN = "_action_key" +#: 表单字段类型 → 列类型。多选、文件存 JSON 文字 +COLUMN_TYPES = {"string": "TEXT", "number": "REAL", "integer": "INTEGER", "boolean": "INTEGER", "array": "TEXT", + "file": "TEXT"} +#: 列名最长几个字 +NAME_MAX = 64 + +_KEY = re.compile(r"^[A-Za-z0-9_-]{1,64}$") +#: 列名里不许出现的字符:引号(拼进 SQL 的标识符)、控制字符 +_BAD_NAME = re.compile(r"[\"`\[\]\x00-\x1f\x7f]") +#: 所有写入(建表、加列、追加)共用的锁。写都是几毫秒的短事务,不按表分锁也不会互相拖住 +_WRITE_LOCK = threading.Lock() + + +class RecordsRefused(ValueError): + """这一次写入不收:code 是问题编号(records.*,白话在 app/plain.py),message 直接给人看。""" + + def __init__(self, code: str, message: str) -> None: + super().__init__(message) + self.code = code + self.message = message + + +@dataclass(frozen=True) +class Column: + """一个业务列:名字(就是表单字段名)、中文名、类型(COLUMN_TYPES 的键)、必填、敏感(进数据源的遮罩列)。""" + + name: str + label: str = "" + type: str = "string" + required: bool = False + sensitive: bool = False + + def out(self) -> dict[str, Any]: + return {"name": self.name, "label": self.label or self.name, "type": self.type, "required": self.required, + "sensitive": self.sensitive} + + +def column_problem(name: Any) -> str | None: + """列名合不合规:返回原因,合规返回 None。下划线开头的留给系统列。""" + if not isinstance(name, str) or not name.strip(): + return "字段名不能为空" + if name != name.strip(): + return f"字段名「{name}」前后不能有空格" + if len(name) > NAME_MAX: + return f"字段名「{name[:20]}…」超过 {NAME_MAX} 个字" + if name.startswith("_"): + return f"字段名「{name}」不能以下划线开头:下划线开头的留给系统列" + if _BAD_NAME.search(name): + return f"字段名「{name}」里不能有引号、方括号或控制字符" + return None + + +def parse_columns(raw: Any) -> list[Column]: + """records_tables.columns(或调用方交来的列定义)→ Column。类型不认识的、名字不合规的抛 RecordsRefused。""" + out: list[Column] = [] + seen: set[str] = set() + for item in raw or []: + if not isinstance(item, dict): + raise RecordsRefused("records.column_invalid", "列定义需要是对象") + name = item.get("name") + if problem := column_problem(name): + raise RecordsRefused("records.column_invalid", problem) + if name.lower() in seen: + raise RecordsRefused("records.column_invalid", f"字段名「{name}」重复了") + seen.add(name.lower()) + kind = str(item.get("type") or "string") + if kind not in COLUMN_TYPES: + raise RecordsRefused("records.column_invalid", f"字段「{name}」的类型「{kind}」不能存进记录表") + out.append(Column(name=name, label=str(item.get("label") or name), type=kind, + required=bool(item.get("required")), sensitive=bool(item.get("sensitive")))) + return out + + +# -------------------------------------------------------------------------- +# 路径 +# -------------------------------------------------------------------------- + + +def records_root() -> Path: + """记录表文件的根目录。按调用时的 settings 现算:测试会换数据目录。""" + return settings.data_dir / "records" + + +def table_path(table_key: str, version: int) -> Path: + """data/records/.v.db。键只认字母、数字、下划线、连字符,挡住路径穿越。""" + if not _KEY.match(table_key or ""): + raise ValueError("记录表的键格式不对") + if not isinstance(version, int) or version < 1: + raise ValueError("记录表的版本号需要是正整数") + return records_root() / f"{table_key}.v{version}.db" + + +def _q(name: str) -> str: + return '"' + name.replace('"', '""') + '"' + + +def _lit(value: str) -> str: + """SQL 文字字面量。只用于临时视图里拼看的人的名字:视图定义不能带参数。""" + return "'" + str(value).replace("'", "''") + "'" + + +def _rw(path: Path) -> sqlite3.Connection: + if not path.is_file(): + raise RecordsRefused("records.table_missing", "记录表的数据文件不见了,请联系管理员") + return open_checked_sqlite(str(path), readonly=False) + + +def _ro(path: Path) -> sqlite3.Connection: + if not path.is_file(): + raise RecordsRefused("records.table_missing", "记录表的数据文件不见了,请联系管理员") + return open_checked_sqlite(str(path), readonly=True) + + +# -------------------------------------------------------------------------- +# 建表、加列 +# -------------------------------------------------------------------------- + + +def create_file(path: Path, columns: list[Column]) -> None: + """新建一个表版本的文件。路径上已有文件时:没有任何行(上次建了一半、登记没提交)就重建,有行就拒绝—— + 有数据的文件绝不覆盖。""" + with _WRITE_LOCK: + if path.exists(): + if _row_count(path) > 0: + raise RecordsRefused("records.file_exists", f"记录表文件 {path.name} 已经有数据,不能重建") + path.unlink() + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_name(f".{path.name}.tmp-{new_id()[:12]}") + conn = open_checked_sqlite(str(tmp), readonly=False) + try: + business = "".join(f", {_q(c.name)} {COLUMN_TYPES[c.type]}" for c in columns) + conn.execute( + f"CREATE TABLE {_q(TABLE)} (" + "_seq INTEGER PRIMARY KEY, _id TEXT NOT NULL UNIQUE, _submitted_by TEXT, _submitted_at TEXT NOT NULL, " + "_run_id TEXT, _supersedes TEXT, _schema_version INTEGER NOT NULL, " + f"{ACTION_KEY_COLUMN} TEXT UNIQUE{business})") + conn.execute(f"CREATE INDEX ix_records_supersedes ON {_q(TABLE)} (_supersedes)") + conn.execute(f"CREATE INDEX ix_records_submitted_by ON {_q(TABLE)} (_submitted_by)") + conn.commit() + finally: + conn.close() + os.replace(tmp, path) + + +def add_columns(path: Path, columns: list[Column]) -> None: + """兼容的改动(只加可选字段):在同一个版本上 ALTER TABLE ADD COLUMN。已有的列跳过(重做一次也没事)。""" + if not columns: + return + with _WRITE_LOCK: + conn = _rw(path) + try: + have = {str(r[1]).lower() for r in conn.execute(f"PRAGMA table_info({_q(TABLE)})")} + for c in columns: + if c.name.lower() not in have: + conn.execute(f"ALTER TABLE {_q(TABLE)} ADD COLUMN {_q(c.name)} {COLUMN_TYPES[c.type]}") + conn.commit() + finally: + conn.close() + + +def _row_count(path: Path) -> int: + try: + conn = open_checked_sqlite(str(path), readonly=True) + except sqlite3.Error: + return 0 + try: + return int(conn.execute(f"SELECT count(*) FROM {_q(TABLE)}").fetchone()[0]) + except sqlite3.Error: + return 0 + finally: + conn.close() + + +# -------------------------------------------------------------------------- +# 追加 +# -------------------------------------------------------------------------- + + +def _now() -> str: + return datetime.now(timezone.utc).isoformat() + + +_TYPE_TEXT = {"number": "数", "integer": "整数", "boolean": "是或否", "array": "多选(列表)", "file": "文件"} +_INTEGER = re.compile(r"[+-]?\d+") +_NUMBER = re.compile(r"[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?") + + +def coerce(column: Column, value: Any) -> Any: + """一个值按列类型收好,能存进 SQLite 的样子。模板渲染出来的一律是文字("12.5"、"true"、JSON),在这里收; + 收不成抛 RecordsRefused(records.value_invalid),说清是哪个字段。空值(None、空串)交回 None。""" + if value is None or (isinstance(value, str) and not value.strip() and column.type != "string"): + return None + if isinstance(value, str) and column.type == "string": + return value + bad = RecordsRefused("records.value_invalid", + f"字段「{column.label or column.name}」应为{_TYPE_TEXT.get(column.type, '文字')}," + f"实际是「{str(value)[:80]}」") + if column.type == "string": + if isinstance(value, (dict, list)): + return json.dumps(value, ensure_ascii=False) + return str(value) + if column.type in ("number", "integer"): + number: Any = None + if isinstance(value, (int, float)) and not isinstance(value, bool): + number = value + elif isinstance(value, str): + text = value.strip() + number = int(text) if _INTEGER.fullmatch(text) else float(text) if _NUMBER.fullmatch(text) else None + if number is None or (isinstance(number, float) and not math.isfinite(number)): + raise bad + if column.type == "integer": + if isinstance(number, float) and not number.is_integer(): + raise bad + return int(number) + return number + if column.type == "boolean": + if isinstance(value, bool): + return int(value) + if isinstance(value, str) and value.strip().lower() in ("true", "false"): + return int(value.strip().lower() == "true") + raise bad + # 多选、文件:存 JSON 文字 + parsed = value + if isinstance(value, str): + try: + parsed = json.loads(value) + except ValueError: + raise bad from None + if column.type == "array" and not isinstance(parsed, list): + raise bad + if column.type == "file": + from app.apps.spec import FILE_REF_KEYS + + if not (isinstance(parsed, dict) and isinstance(parsed.get("file_id"), str) + and set(parsed) <= set(FILE_REF_KEYS)): + raise bad + return json.dumps(parsed, ensure_ascii=False, sort_keys=True) + + +@dataclass(frozen=True) +class Appended: + seq: int + row_id: str + submitted_at: str + #: 同一个动作键已经写过:交回的是第一次写下的那一行,这次没有再写 + duplicate: bool + values: dict[str, Any] + + def receipt(self) -> dict[str, Any]: + return {"_seq": self.seq, "_id": self.row_id, "_submitted_at": self.submitted_at, + "duplicate": self.duplicate} + + +def append(path: Path, columns: list[Column], values: Any, *, version: int, run_id: str | None, actor: str | None, + action_key: str, supersedes: str | None = None) -> Appended: + """写一行。同一个 action_key 第二次来交回第一次的那一行(duplicate=True),不再写。 + + values 只认表里的业务列:多出来的字段、必填没填、类型收不成都拒(RecordsRefused),一行都不写。 + supersedes 是被更正的那一行的 _id:它得在这张表里、而且还没被更正过(更正要改最新的那一行)。""" + if not action_key: + raise RecordsRefused("records.action_key_missing", "写记录表需要动作键,只能经调用工具节点写入") + if not isinstance(values, dict): + raise RecordsRefused("records.value_invalid", "要写入的内容需要是一组字段和值") + by_name = {c.name: c for c in columns} + unknown = [k for k in values if k not in by_name] + if unknown: + raise RecordsRefused("records.column_unknown", + f"记录表里没有这些字段:{'、'.join(map(str, unknown[:5]))}。表单改过的话,请重新发布应用") + row = {c.name: coerce(c, values.get(c.name)) for c in columns} + missing = [c.label or c.name for c in columns if c.required and row[c.name] in (None, "")] + if missing: + raise RecordsRefused("records.required_missing", f"必填的字段没有值:{'、'.join(missing)}") + with _WRITE_LOCK: + conn = _rw(path) + try: + conn.execute("BEGIN IMMEDIATE") + done = conn.execute(f"SELECT _seq, _id, _submitted_at FROM {_q(TABLE)} WHERE {ACTION_KEY_COLUMN} = ?", + (action_key,)).fetchone() + if done is not None: + conn.rollback() + return Appended(seq=int(done[0]), row_id=str(done[1]), submitted_at=str(done[2]), duplicate=True, + values=_row_values(path, columns, int(done[0]))) + if supersedes: + target = conn.execute(f"SELECT _seq FROM {_q(TABLE)} WHERE _id = ?", (supersedes,)).fetchone() + if target is None: + raise RecordsRefused("records.supersede_missing", "要更正的那一行不在这张记录表里") + later = conn.execute(f"SELECT 1 FROM {_q(TABLE)} WHERE _supersedes = ? LIMIT 1", + (supersedes,)).fetchone() + if later is not None: + raise RecordsRefused("records.supersede_twice", "这一行已经被更正过了,请在最新的那一行上更正") + row_id, at = new_id(), _now() + names = ["_id", "_submitted_by", "_submitted_at", "_run_id", "_supersedes", "_schema_version", + ACTION_KEY_COLUMN, *row] + params = [row_id, actor, at, run_id, supersedes or None, version, action_key, *row.values()] + cur = conn.execute(f"INSERT INTO {_q(TABLE)} ({', '.join(_q(n) for n in names)}) " + f"VALUES ({', '.join('?' for _ in names)})", params) + seq = int(cur.lastrowid or 0) + conn.commit() + except BaseException: + conn.rollback() + raise + finally: + conn.close() + return Appended(seq=seq, row_id=row_id, submitted_at=at, duplicate=False, values=row) + + +def _row_values(path: Path, columns: list[Column], seq: int) -> dict[str, Any]: + conn = _ro(path) + try: + names = [c.name for c in columns] + got = conn.execute(f"SELECT {', '.join(_q(n) for n in names) or '1'} FROM {_q(TABLE)} WHERE _seq = ?", + (seq,)).fetchone() + return dict(zip(names, got)) if got is not None and names else {} + finally: + conn.close() + + +# -------------------------------------------------------------------------- +# 读 +# -------------------------------------------------------------------------- + + +def high_water(path: Path) -> int: + """现在最大的 _seq;空表为 0。""" + conn = _ro(path) + try: + got = conn.execute(f"SELECT max(_seq) FROM {_q(TABLE)}").fetchone() + return int(got[0] or 0) + finally: + conn.close() + + +def lookup(path: Path, columns: list[Column], action_key: str) -> dict[str, Any] | None: + """按动作键找写下的那一行(查询能力 records_lookup 用):没有为 None。""" + conn = _ro(path) + try: + got = conn.execute(f"SELECT _seq, _id, _submitted_at FROM {_q(TABLE)} WHERE {ACTION_KEY_COLUMN} = ?", + (action_key,)).fetchone() + finally: + conn.close() + if got is None: + return None + return {"_seq": int(got[0]), "_id": str(got[1]), "_submitted_at": str(got[2]), "duplicate": True} + + +def view_select(columns: list[Column], *, high_water: int | None, scope: str, viewer: str | None, + schema: str = "main") -> str: + """临时视图(和看板、记录列表)看到的那一份: + + - _seq ≤ 高水位(None 为不限,现在有的都算); + - 没被更正过:在高水位之内没有一行指向它(_supersedes)。按高水位判,不靠可改的标记——原行永远不改; + - 行级过滤:scope=all 全部,mine 只看 _submitted_by = viewer 的,none 一行都不给。 + + 不露 _action_key。列名照 SYSTEM_COLUMNS + 业务列的顺序。""" + cols = ", ".join(f"r.{_q(n)}" for n in (*SYSTEM_COLUMNS, *(c.name for c in columns))) + src = f"{_q(schema)}.{_q(TABLE)}" + where = [] + if high_water is not None: + seq = int(high_water) + where.append(f"r._seq <= {seq}") + newer = f" AND s._seq <= {seq}" + else: + newer = "" + where.append(f"NOT EXISTS (SELECT 1 FROM {src} AS s WHERE s._supersedes = r._id{newer})") + if scope == "mine": + where.append(f"r._submitted_by = {_lit(viewer)}" if viewer else "0") + elif scope != "all": + where.append("0") + return f"SELECT {cols} FROM {src} AS r WHERE {' AND '.join(where)}" + + +def view_prelude(columns: list[Column], *, high_water: int | None, scope: str, viewer: str | None) -> tuple[str, ...]: + """查询连接上建同名临时视图的两条语句。SQLite 解析不带库名的表名时先找 temp 库,于是 FROM records 查到的就是 + 这份视图;直接写 main.records 的 SQL 由只读守卫拒掉(data/engine.run_query 的 forbid_schemas)。""" + return (f"DROP VIEW IF EXISTS temp.{_q(TABLE)}", + f"CREATE TEMP VIEW {_q(TABLE)} AS " + + view_select(columns, high_water=high_water, scope=scope, viewer=viewer)) + + +def rows(path: Path, columns: list[Column], *, scope: str, viewer: str | None, history: bool = False, + before: int | None = None, limit: int = 50) -> tuple[list[dict[str, Any]], bool]: + """记录列表(records_list、GET /api/apps/{id}/records):现在的数据,按看的人过滤,_seq 倒序。 + + history=False 只给当前有效的行;True 连被更正过的也给,标 superseded。before 是游标(只要 _seq 更小的)。 + 交回 (行, 后面还有没有)。""" + limit = max(1, min(int(limit), 200)) + names = [c.name for c in columns] + src = f"main.{_q(TABLE)}" + where = ["1"] + params: list[Any] = [] + if scope == "mine": + where.append("r._submitted_by = ?") + params.append(viewer) + elif scope != "all": + return [], False + if not history: + where.append(f"NOT EXISTS (SELECT 1 FROM {src} AS s WHERE s._supersedes = r._id)") + if before is not None: + where.append("r._seq < ?") + params.append(int(before)) + cols = ", ".join(f"r.{_q(n)}" for n in (*SYSTEM_COLUMNS, *names)) + sql = (f"SELECT {cols}, EXISTS (SELECT 1 FROM {src} AS s WHERE s._supersedes = r._id) " + f"FROM {src} AS r WHERE {' AND '.join(where)} ORDER BY r._seq DESC LIMIT ?") + conn = _ro(path) + try: + got = conn.execute(sql, [*params, limit + 1]).fetchall() + finally: + conn.close() + out: list[dict[str, Any]] = [] + width = len(SYSTEM_COLUMNS) + for row in got[:limit]: + system = dict(zip(SYSTEM_COLUMNS, row[:width])) + values = {n: _shown(c, v) for n, c, v in zip(names, columns, row[width:width + len(names)])} + out.append({**system, "superseded": bool(row[-1]), "values": values}) + return out, len(got) > limit + + +def row_by_id(path: Path, columns: list[Column], row_id: str) -> dict[str, Any] | None: + """按 _id 取一行(下载附件时核对行级可见用)。""" + names = [c.name for c in columns] + cols = ", ".join(_q(n) for n in (*SYSTEM_COLUMNS, *names)) + conn = _ro(path) + try: + got = conn.execute(f"SELECT {cols} FROM {_q(TABLE)} WHERE _id = ?", (row_id,)).fetchone() + finally: + conn.close() + if got is None: + return None + width = len(SYSTEM_COLUMNS) + return {**dict(zip(SYSTEM_COLUMNS, got[:width])), + "values": {n: _shown(c, v) for n, c, v in zip(names, columns, got[width:])}} + + +def _shown(column: Column, value: Any) -> Any: + """存的样子 → 给界面的样子:是或否交回布尔,多选、文件解开 JSON。""" + if value is None: + return None + if column.type == "boolean": + return bool(value) + if column.type in ("array", "file") and isinstance(value, str): + try: + return json.loads(value) + except ValueError: + return value + return value diff --git a/backend/app/records/tables.py b/backend/app/records/tables.py new file mode 100644 index 00000000..4c8b29ba --- /dev/null +++ b/backend/app/records/tables.py @@ -0,0 +1,409 @@ +"""记录表的登记(docs/design/normal-user-apps.md N8、§3.7):records_tables 一行一个表版本,各自登记成 origin=records 的 +只读数据源,看板照常用 db_query__<名字> 查、数据目录照常起草。 + +**表版本。** 「填什么」卡片变了时按列的变化分档(column_changes): +- 只加可选字段、改中文名、改敏感标记:兼容,在同一个版本上 ADD COLUMN、更新登记; +- 改类型、删字段、加必填字段、可选改必填:不兼容,出新版本(新文件、新数据源、records_tables 再登记一行), + 旧版本标 retired_at、只读保留——旧记录照原样留着,照样查得到,只是不再往里写。 +不兼容的判定沿用按期累积的 INCOMPATIBLE_KINDS(data/recipe_accumulate.py,列类型变了同样是不兼容),再加上记录表 +特有的三种:删字段、加必填字段、可选改必填(旧行在那一列上是空的)。 + +**草稿不影响线上。** 同一个蓝图(或没有蓝图的应用)的各版本共用一个 table_key。蓝图这边(按卡片生成、试运行、 +填关节)用 draft_table:兼容的只补列,不兼容的出下一版,线上应用在写的那一版不停用、照常收提交;发布单发布应用那一步 +用 publish_table 切换——图里写的那一版成为往里写的那一版,别的版本这时才停用。ensure_table 当场切换,只给没有线上应用 +的场合(测试、手工整理)。 +""" +from __future__ import annotations + +import asyncio +import re +from dataclasses import dataclass +from datetime import datetime, timezone +from typing import Any + +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.data.recipe_accumulate import INCOMPATIBLE_KINDS +from app.db.base import utcnow +from app.db.models import DataSource +from app.db.models_blueprints import RecordsTable +from app.records import RECORDS_ORIGIN, SYSTEM_COLUMNS +from app.records import store +from app.records.store import Column, RecordsRefused + +#: 记录表特有的不兼容改动:删字段、加必填字段、可选改必填。和 INCOMPATIBLE_KINDS(类型等)合起来是出新版本的全部情形 +RECORDS_INCOMPATIBLE = (*INCOMPATIBLE_KINDS, "column_removed", "required_added", "required_changed") +#: 数据源名字的前缀。数据源名只能是小写字母开头、字母数字下划线(会成为工具名的一部分) +SOURCE_PREFIX = "rec_" +#: 系统列在表结构里的说明(工具描述、db_schema、数据目录起草看得到) +SYSTEM_NOTES = { + "_seq": "序号:只增不减,一次运行只看得到开始时已有的序号以内的记录", + "_id": "这一行的编号", + "_submitted_by": "提交人", + "_submitted_at": "提交时间(UTC)", + "_run_id": "写入这一行的运行", + "_supersedes": "更正的是哪一行(那一行的编号);更正过的行不再出现在查询里", + "_schema_version": "写入时的表版本", +} +_SQL_TYPE_LABEL = {"string": "TEXT", "number": "REAL", "integer": "INTEGER", "boolean": "INTEGER", "array": "TEXT", + "file": "TEXT"} + + +@dataclass(frozen=True) +class Change: + kind: str + column: str + message: str + + @property + def incompatible(self) -> bool: + return self.kind in RECORDS_INCOMPATIBLE + + +def column_changes(old: list[Column], new: list[Column]) -> list[Change]: + """两份列定义之间的变化,按列名(不分大小写,SQLite 的列名就不分)对上。""" + before = {c.name.lower(): c for c in old} + after = {c.name.lower(): c for c in new} + out: list[Change] = [] + for key, c in before.items(): + if key not in after: + out.append(Change("column_removed", c.name, f"删掉了字段「{c.label or c.name}」")) + for key, c in after.items(): + was = before.get(key) + if was is None: + out.append(Change("required_added" if c.required else "column_added", c.name, + f"加了{'必填' if c.required else '可选'}字段「{c.label or c.name}」")) + continue + if was.name != c.name: + out.append(Change("column_removed", was.name, f"字段「{was.name}」改名为「{c.name}」")) + continue + if was.type != c.type: + out.append(Change("type", c.name, f"字段「{c.label or c.name}」的类型从 {was.type} 改成了 {c.type}")) + if c.required and not was.required: + out.append(Change("required_changed", c.name, f"字段「{c.label or c.name}」从可选改成了必填")) + if was.label != c.label: + out.append(Change("label", c.name, f"字段「{c.name}」的中文名改成了「{c.label}」")) + if was.sensitive != c.sensitive: + out.append(Change("sensitive", c.name, f"字段「{c.label or c.name}」{'标为' if c.sensitive else '不再是'}敏感")) + return out + + +# -------------------------------------------------------------------------- +# 列定义从哪来 +# -------------------------------------------------------------------------- + + +def _form_type(prop: dict[str, Any]) -> str: + if prop.get("x-widget") == "file": + return "file" + kind = prop.get("type") + return kind if kind in ("string", "number", "integer", "boolean", "array") else "string" + + +def columns_from_form(form: dict[str, Any], *, + sensitive: set[str] | frozenset[str] = frozenset()) -> list[dict[str, Any]]: + """入口表单(agentlab.form/1)→ 记录表的列定义。只看得到的展示字段(x-widget: note)不进表。""" + props = form.get("properties") if isinstance(form, dict) else None + if not isinstance(props, dict): + return [] + required = set(form.get("required") or []) + listed = [n for n in form.get("x-order") or [] if n in props] + order = listed + [n for n in props if n not in listed] + out: list[dict[str, Any]] = [] + for name in order: + prop = props.get(name) + if not isinstance(prop, dict) or prop.get("x-widget") == "note": + continue + out.append({"name": name, "label": str(prop.get("title") or name), "type": _form_type(prop), + "required": name in required, "sensitive": name in sensitive}) + return out + + +def columns_from_fields(fields: list[Any]) -> list[dict[str, Any]]: + """蓝图「填什么」卡片(blueprints/spec.FieldItem:{name, spec: {value: 表单属性}, sensitive})→ 列定义。 + 必填写在属性的 required(布尔)上;没写按可选。""" + out: list[dict[str, Any]] = [] + for item in fields or []: + data = item.model_dump() if hasattr(item, "model_dump") else item + if not isinstance(data, dict) or not isinstance(data.get("name"), str): + continue + spec = data.get("spec") + prop = spec.get("value") if isinstance(spec, dict) else None + prop = prop if isinstance(prop, dict) else {} + if prop.get("x-widget") == "note": + continue + out.append({"name": data["name"], "label": str(prop.get("title") or data["name"]), "type": _form_type(prop), + "required": bool(prop.get("required")), "sensitive": bool(data.get("sensitive"))}) + return out + + +# -------------------------------------------------------------------------- +# 登记 +# -------------------------------------------------------------------------- + + +def _owner(owner: Any) -> tuple[str, str | None, str | None, str]: + """(table_key, app_id, blueprint_id, 名字)。应用有蓝图时按蓝图认,这样试运行时建的表发布后接着用。""" + from app.db.models_apps import App + + if isinstance(owner, App): + blueprint_id = getattr(owner, "blueprint_id", None) + return blueprint_id or owner.id, owner.id, blueprint_id, owner.name or "记录" + blueprint_id = getattr(owner, "id", None) + if not blueprint_id: + raise ValueError("记录表要属于一个应用或蓝图") + return blueprint_id, getattr(owner, "app_id", None), blueprint_id, getattr(owner, "name", None) or "记录" + + +def schema_cache_of(columns: list[Column], label: str) -> dict[str, Any]: + """登记到数据源上的表结构,形状同 data/introspect.introspect:工具描述、db_schema、数据目录都按它读。 + 不露 _action_key(查询走的临时视图里也没有它)。""" + cols = [{"name": n, "type": "INTEGER" if n in ("_seq", "_schema_version") else "TEXT", + "nullable": n not in ("_seq", "_id", "_submitted_at", "_schema_version"), "comment": SYSTEM_NOTES[n]} + for n in SYSTEM_COLUMNS] + cols += [{"name": c.name, "type": _SQL_TYPE_LABEL[c.type], "nullable": True, + "comment": c.label if c.label and c.label != c.name else None} for c in columns] + return {"tables": {store.TABLE: {"qualified": store.TABLE, "schema": None, "columns": cols, + "primary_key": ["_seq"], "comment": label, "is_view": False}}, + "truncated": False, "total": 1, "synced_at": datetime.now(timezone.utc).isoformat(), "schema": None} + + +def _description(label: str, version: int) -> str: + return (f"记录表「{label}」{'' if version == 1 else f'(第 {version} 版)'}:平台托管、只许追加的填报记录,表名 records。" + "一次运行只看得到开始时已有的记录;更正过的行只留最新的一行") + + +async def _free_name(session: AsyncSession, base: str) -> str: + name, n = base, 2 + while (await session.execute(select(DataSource.id).where(DataSource.name == name))).first() is not None: + name, n = f"{base}_{n}", n + 1 + return name + + +async def _register(session: AsyncSession, *, key: str, version: int, columns: list[Column], label: str, + app_id: str | None, blueprint_id: str | None) -> RecordsTable: + path = store.table_path(key, version) + await asyncio.to_thread(store.create_file, path, columns) + base = f"{SOURCE_PREFIX}{re.sub(r'[^a-z0-9]', '', key.lower())[:12] or 'table'}" + name = await _free_name(session, base if version == 1 else f"{base}_v{version}") + source = DataSource(name=name, kind="sqlite", database=str(path), readonly=True, origin=RECORDS_ORIGIN, + description=_description(label, version), options=_options(columns), + schema_cache=schema_cache_of(columns, label), schema_synced_at=utcnow()) + session.add(source) + await session.flush() + row = RecordsTable(table_key=key, version=version, name=label, app_id=app_id, blueprint_id=blueprint_id, + source_id=source.id, columns=[c.out() for c in columns]) + session.add(row) + await session.flush() + return row + + +def _options(columns: list[Column]) -> dict[str, Any]: + from app.data.engine import MASK_COLUMNS_OPTION + + masked = [c.name for c in columns if c.sensitive] + return {MASK_COLUMNS_OPTION: masked} if masked else {} + + +async def current_table(session: AsyncSession, table_key: str) -> RecordsTable | None: + """这张记录表现在往里写的那个版本(没退役的最新一版)。""" + return (await session.execute(select(RecordsTable).where( + RecordsTable.table_key == table_key, RecordsTable.retired_at.is_(None)) + .order_by(RecordsTable.version.desc()).limit(1))).scalar_one_or_none() + + +async def versions_of(session: AsyncSession, table_key: str) -> list[RecordsTable]: + """各版本,新的在前(看板跨版本汇总、记录列表合并各版本时用)。""" + return list((await session.execute(select(RecordsTable).where(RecordsTable.table_key == table_key) + .order_by(RecordsTable.version.desc()))).scalars()) + + +async def tables_of_app(session: AsyncSession, app_id: str) -> list[RecordsTable]: + """这个应用的记录表,每张取现在的版本,按登记先后。""" + rows = list((await session.execute(select(RecordsTable).where(RecordsTable.app_id == app_id) + .order_by(RecordsTable.created_at, RecordsTable.version))).scalars()) + latest: dict[str, RecordsTable] = {} + for row in rows: + if row.table_key not in latest or row.version > latest[row.table_key].version: + latest[row.table_key] = row + return list(latest.values()) + + +async def find_table(session: AsyncSession, ref: str) -> RecordsTable | None: + """调用工具节点 args.table 写的那张表:records_tables 的 id、数据源名、或「table_key.v版本」都认。""" + ref = str(ref or "").strip() + if not ref: + return None + row = await session.get(RecordsTable, ref) + if row is not None: + return row + source = (await session.execute(select(DataSource.id).where( + DataSource.name == ref, DataSource.origin == RECORDS_ORIGIN))).scalar_one_or_none() + if source is not None: + return await table_of_source(session, source) + key, dot, version = ref.rpartition(".v") + if dot and version.isdigit(): + return (await session.execute(select(RecordsTable).where( + RecordsTable.table_key == key, RecordsTable.version == int(version)))).scalar_one_or_none() + return None + + +async def table_of_source(session: AsyncSession, source_id: str) -> RecordsTable | None: + return (await session.execute(select(RecordsTable).where(RecordsTable.source_id == source_id))).scalar_one_or_none() + + +async def ensure_table(session: AsyncSession, owner: Any, columns: list[dict[str, Any]]) -> RecordsTable: + """按「填什么」的列定义取(或建)这张记录表现在的版本,当场切换,交回 records_tables 的那一行。 + + - 第一次:建 v1 的文件、登记数据源和 records_tables; + - 兼容的改动:同一版本上 ADD COLUMN,更新登记(中文名、敏感标记只改这次变了的那几列,见 _sync_registration); + - 不兼容的改动:建下一版(新文件、新数据源),旧版本标 retired_at、只读保留。 + owner 是应用(App)或蓝图(Blueprint)。当场切换会让线上在写的那一版停用,所以只给没有线上应用的场合用(管理员手工 + 整理、测试);蓝图那边起草、试运行用 draft_table,发布单发布应用时用 publish_table。只 flush 不提交:和调用方的 + 其余改动一起提交;文件先建好,调用方回滚时留下的空文件下次建同一版本时重建(有数据的文件绝不覆盖)。""" + key, app_id, blueprint_id, label = _owner(owner) + wanted = store.parse_columns(columns) + current = await current_table(session, key) + if current is None: + return await _register(session, key=key, version=1, columns=wanted, label=label, app_id=app_id, + blueprint_id=blueprint_id) + if app_id and current.app_id != app_id: + # 试运行时按蓝图建的表,发布成应用之后归到应用名下(各版本一起) + for row in await versions_of(session, key): + row.app_id = app_id + changes = column_changes(columns_of(current), wanted) + if any(c.incompatible for c in changes): + current.retired_at = utcnow() + current.note = ";".join(c.message for c in changes if c.incompatible) + return await _register(session, key=key, version=await _next_version(session, key), columns=wanted, + label=label, app_id=app_id or current.app_id, + blueprint_id=blueprint_id or current.blueprint_id) + if changes: + await _sync_registration(session, current, wanted, label=label, draft=False) + await session.flush() + return current + + +async def _next_version(session: AsyncSession, key: str) -> int: + """下一个版本号:停用的版本也占着号(文件和 records_tables 的唯一约束都按它)。""" + return max([row.version for row in await versions_of(session, key)] or [0]) + 1 + + +async def _open_versions(session: AsyncSession, key: str) -> list[RecordsTable]: + """没停用的各版本,老的在前。线上应用在写的那一版是最老的那个;比它新的是起草时出的、还没发布的版本。""" + return sorted([row for row in await versions_of(session, key) if row.retired_at is None], key=lambda r: r.version) + + +def _fits(row: RecordsTable, wanted: list[Column]) -> bool: + return not any(c.incompatible for c in column_changes(columns_of(row), wanted)) + + +async def pick_table(session: AsyncSession, key: str, columns: list[dict[str, Any]]) -> RecordsTable | None: + """只读:起草这边(draft_table)会用的那一版——没停用、和「填什么」兼容的版本里最老的那个(线上在写的优先,少出版本)。 + 要出新版本才对得上的(或者还没建过)为 None。""" + wanted = store.parse_columns(columns) + return next((row for row in await _open_versions(session, key) if _fits(row, wanted)), None) + + +async def draft_table(session: AsyncSession, owner: Any, columns: list[dict[str, Any]]) -> RecordsTable: + """起草这边(按卡片生成、试运行、填关节)要的那一版:草稿和试运行不影响线上应用。 + + - 还没建过:建 v1; + - 有一版兼容(pick_table):用它。缺的可选字段在它上面 ADD COLUMN、登记补上这几列(只加不改:线上的图不写这几列, + 写不坏);已有列的中文名、敏感标记等发布时再改(publish_table)——起草时取消一个敏感标记,不该当场让线上的数露出来; + - 都不兼容:出下一版,线上在写的那一版不停用、照常收提交。「停用旧版、切到新版」只在发布单发布应用那一步做。 + 试运行的写入一律演练(capabilities/platform.py),起草时出的版本在发布前一行都不会有。只 flush,调用方提交。""" + key, app_id, blueprint_id, label = _owner(owner) + wanted = store.parse_columns(columns) + row = await pick_table(session, key, columns) + if row is None: + have = await versions_of(session, key) + return await _register(session, key=key, version=await _next_version(session, key), columns=wanted, + label=label, app_id=next((r.app_id for r in have if r.app_id), app_id), + blueprint_id=blueprint_id) + if column_changes(columns_of(row), wanted): + await _sync_registration(session, row, wanted, label=label, draft=True) + await session.flush() + return row + + +async def publish_table(session: AsyncSession, app: Any, ref: str, columns: list[dict[str, Any]]) -> RecordsTable: + """发布单发布应用那一步(应用的新一版已经发布):图里写的那一版(ref,「键.v版本」)成为这张表往里写的那一版。 + + 各版本归到应用名下;别的没停用的版本这时才停用——线上原来在写的那一版(写明换成了第几版),以及起草时出过、最后没用上的 + 版本。登记按「填什么」整理:中文名、敏感标记照卡片改(只改这次变了的那几列,管理员在数据页手工加的遮罩列留着)。 + 只 flush,调用方提交。""" + row = await find_table(session, ref) + if row is None: + raise RecordsRefused("records.table_missing", f"找不到记录表「{ref}」,请重新出一份发布单") + if row.retired_at is not None: + refuse_retired(row) + wanted = store.parse_columns(columns) + changes = column_changes(columns_of(row), wanted) + if any(c.incompatible for c in changes): + raise RecordsRefused("records.column_unknown", f"记录表「{row.name}」第 {row.version} 版和「填什么」对不上了:" + + ";".join(c.message for c in changes if c.incompatible) + + "。请重新试运行、再出一份发布单") + now = utcnow() + for other in await versions_of(session, row.table_key): + other.app_id = app.id + if other.id == row.id or other.retired_at is not None: + continue + other.retired_at = now + other.note = (f"应用发布了新的表单,改写第 {row.version} 版" if other.version < row.version + else "起草时出的版本,发布时没有用上") + if changes: + await _sync_registration(session, row, wanted, label=app.name or row.name, draft=False) + await session.flush() + return row + + +async def _sync_registration(session: AsyncSession, row: RecordsTable, wanted: list[Column], *, label: str, + draft: bool) -> None: + """兼容的改动落到这一版上:缺的列 ADD COLUMN(文件里已有的跳过),登记的列定义、数据源的表结构和遮罩列跟着改。 + + 遮罩列只改这次变了的那几列(新加的敏感列加上;发布时,敏感标记取消的去掉、新标上的加上),别的原样留着——管理员在 + 数据页手工加的遮罩列不会被下一次表单改动抹掉。draft=True 只加不改:已有列的定义、遮罩照旧,只补新列。""" + have = columns_of(row) + known = {h.name.lower() for h in have} + added = [c for c in wanted if c.name.lower() not in known] + await asyncio.to_thread(store.add_columns, store.table_path(row.table_key, row.version), added) + by_name = {w.name.lower(): w for w in wanted} + # 列的顺序:原有的在前(照原来的顺序),新加的在后——和文件里的列序一致。删掉的列(只在不兼容时出现)这里不会有 + kept = [h if draft else by_name.get(h.name.lower(), h) for h in have] + merged = kept + added + row.columns = [c.out() for c in merged] + if not draft: + row.name = label + source = await session.get(DataSource, row.source_id) if row.source_id else None + if source is None: + return + from app.data.engine import MASK_COLUMNS_OPTION + + masked = [str(m) for m in (source.options or {}).get(MASK_COLUMNS_OPTION) or []] + before = {h.name.lower(): h for h in have} + drop = set() if draft else {c.name.lower() for c in merged + if not c.sensitive and before.get(c.name.lower()) is not None + and before[c.name.lower()].sensitive} + add = [c.name for c in (added if draft else merged) if c.sensitive and c.name not in masked] + masked = [m for m in masked if m.lower() not in drop] + add + options = {k: v for k, v in (source.options or {}).items() if k != MASK_COLUMNS_OPTION} + source.options = {**options, **({MASK_COLUMNS_OPTION: masked} if masked else {})} + source.schema_cache = schema_cache_of(merged, row.name) + source.schema_synced_at = utcnow() + + +def columns_of(row: RecordsTable) -> list[Column]: + return store.parse_columns(row.columns) + + +def path_of(row: RecordsTable) -> Any: + return store.table_path(row.table_key, row.version) + + +def refuse_retired(row: RecordsTable) -> None: + if row.retired_at is not None: + raise RecordsRefused("records.table_retired", + f"记录表「{row.name}」的第 {row.version} 版已经停用(表单改过,出了新版本),旧记录只读保留。" + "请重新发布应用,让它写到新版本") diff --git a/backend/app/records/views.py b/backend/app/records/views.py new file mode 100644 index 00000000..66fd9b7b --- /dev/null +++ b/backend/app/records/views.py @@ -0,0 +1,145 @@ +"""记录表的查询视图(docs/design/normal-user-apps.md §3.7「查询连接」)。 + +origin=records 的数据源查询时换成一个 RecordsView(字段和 DataSource 同名,同 table_versions.SourceView 的做法): +带着这次查询的高水位、看哪些行,以及连接上要先执行的两条语句(建同名临时视图)。data/engine.run_query 认这两样: +- prelude:借到连接后、执行查询前依次执行(DROP / CREATE TEMP VIEW records); +- forbid_schemas:SQL 里直接写 main.<表> 的拒掉——不然绕过临时视图就看到了底表(全部行、被更正的行、幂等键)。 + +高水位来自运行的 data_versions(发起时记下,engine/runner._data_versions),不在运行里(工具库试用、数据剖析)的查询 +用现在的数据、看全部(这些入口只有搭建者以上进得来)。 +""" +from __future__ import annotations + +import asyncio +import copy +from dataclasses import dataclass, field +from datetime import datetime +from typing import Any + +from sqlalchemy.ext.asyncio import AsyncSession + +from app.records import RECORDS_ORIGIN, store + +#: data_versions 里记录表那一项的形状:{"name", "origin": "records", "table", "version", "seq", "rows", "viewer"?} +PIN_KEYS = ("name", "origin", "table", "version", "seq", "rows", "viewer") + + +@dataclass +class RecordsView: + """绑定了高水位和行级过滤的记录表数据源。engine / introspect / guard / 工具只读这些字段,和 DataSource 同名。""" + + id: str + name: str + kind: str = "sqlite" + database: str | None = None + options: dict[str, Any] = field(default_factory=dict) + readonly: bool = True + description: str = "" + schema_cache: dict[str, Any] = field(default_factory=dict) + schema_synced_at: datetime | None = None + enabled: bool = True + host: str | None = None + port: int | None = None + username: str | None = None + password: str | None = None + last_check: dict[str, Any] | None = None + origin: str = RECORDS_ORIGIN + current_snapshot_id: str | None = None + #: 记录表不分快照:引擎缓存按源 id 一个,临时视图每次查询现建 + snapshot_id: str | None = None + #: 文件还在追加,不能以 immutable 打开 + immutable: bool = False + expected_sha256: str | None = None + #: 这次查询的高水位(None:现在有的都算) + high_water: int | None = None + #: all / mine / none(records/access.py) + rows: str = "all" + viewer: str | None = None + #: 连接上先执行的语句(建同名临时视图) + prelude: tuple[str, ...] = () + #: SQL 里不许直接写的库名 + forbid_schemas: tuple[str, ...] = ("main",) + + +def bind_view(source: Any, columns: list[store.Column], *, high_water: int | None, rows: str = "all", + viewer: str | None = None) -> RecordsView: + """数据源行 + 高水位 + 行级过滤 → RecordsView。""" + rows = rows if rows in ("all", "mine", "none") else "none" + return RecordsView( + id=source.id, name=source.name, database=source.database, options=dict(source.options or {}), + description=source.description or "", schema_cache=copy.deepcopy(source.schema_cache or {}), + schema_synced_at=getattr(source, "schema_synced_at", None), enabled=bool(source.enabled), + last_check=getattr(source, "last_check", None), high_water=high_water, rows=rows, viewer=viewer, + prelude=store.view_prelude(columns, high_water=high_water, scope=rows, viewer=viewer)) + + +def columns_of_source(source: Any) -> list[store.Column]: + """数据源上登记的表结构里的业务列(不含系统列)。records_tables 的列定义是权威;这里只在拿不到登记时兜底。""" + from app.records import SYSTEM_COLUMNS + + meta = ((getattr(source, "schema_cache", None) or {}).get("tables") or {}).get(store.TABLE) or {} + return [store.Column(name=str(c.get("name")), label=str(c.get("comment") or c.get("name")), + type=_type_of(str(c.get("type") or ""))) + for c in meta.get("columns") or [] if isinstance(c, dict) and c.get("name") not in SYSTEM_COLUMNS] + + +def _type_of(sql_type: str) -> str: + return {"REAL": "number", "INTEGER": "integer"}.get(sql_type.upper(), "string") + + +async def resolve(session: AsyncSession, source: Any, entry: Any = None) -> RecordsView: + """查询时实际该用的视图。entry 是这次运行 data_versions 里这张表的那一项;None 是不在运行里(现在的数据、看全部)。""" + from app.records.tables import columns_of, table_of_source + + table = await table_of_source(session, source.id) + columns = columns_of(table) if table is not None else columns_of_source(source) + if isinstance(entry, dict): + seq = entry.get("seq") + return bind_view(source, columns, high_water=int(seq) if isinstance(seq, int) else 0, + rows=str(entry.get("rows") or "none"), viewer=entry.get("viewer")) + return bind_view(source, columns, high_water=None, rows="all") + + +def default_view(source: Any) -> RecordsView: + """没经解析就拿来查的记录表数据源(数据剖析这类只有搭建者进得来的入口):现在的数据、看全部,照样走临时视图—— + 底表里的幂等键、被更正的行不露出来。列取登记在数据源上的表结构。""" + return bind_view(source, columns_of_source(source), high_water=None, rows="all") + + +async def pin_entry(session: AsyncSession, source: Any, *, run_class: str | None = None, + started_by: str | None = None) -> dict[str, Any] | None: + """发起运行时记进 data_versions 的那一项:高水位,以及(给了运行类别时)这次运行看哪些行。登记不在、文件不在的 + 返回 None(这个源不固定,查询时照实报错)。""" + from app.records.access import scope_of_run + from app.records.tables import path_of, table_of_source + + table = await table_of_source(session, source.id) + if table is None: + return None + try: + seq = await asyncio.to_thread(store.high_water, path_of(table)) + except store.RecordsRefused: + return None + entry: dict[str, Any] = {"name": source.name, "origin": RECORDS_ORIGIN, "table": table.table_key, + "version": table.version, "seq": seq} + if run_class is not None: + entry.update(await scope_of_run(session, table.app_id, run_class=run_class, started_by=started_by)) + return entry + + +async def scope_entries(session: AsyncSession, versions: dict[str, Any] | None, *, run_class: str | None, + started_by: str | None) -> None: + """给 data_versions 里的记录表补上这次运行看哪些行(就地改):正式运行看全部,别的按发起人在应用上的授权。""" + from app.records.access import scope_of_run + from app.records.tables import table_of_source + + for source_id, entry in (versions or {}).items(): + if not isinstance(entry, dict) or entry.get("origin") != RECORDS_ORIGIN: + continue + table = await table_of_source(session, source_id) + entry.update(await scope_of_run(session, table.app_id if table is not None else None, run_class=run_class, + started_by=started_by)) + + +def is_records(source: Any) -> bool: + return (getattr(source, "origin", None) or "manual") == RECORDS_ORIGIN diff --git a/backend/app/scheduler/loop.py b/backend/app/scheduler/loop.py index 4c850231..243f5f97 100644 --- a/backend/app/scheduler/loop.py +++ b/backend/app/scheduler/loop.py @@ -121,11 +121,14 @@ async def tick(now: datetime | None = None) -> None: async def process_due(now: datetime | None = None) -> None: - """流程的一拍(app/process):待办的提醒、升级、超时驳回(永不自动批准);结果未知的写入按退避去查。 + """流程的一拍(app/process):待办的提醒、升级、超时驳回(永不自动批准);结果未知的写入按退避去查; + 上传了却一直没提交的文件过了时限清掉(app/files,每小时一次)。 各自出错只记日志:这一拍出错不该让调度循环停下,下一拍照常再查。""" + from app.files import store as files_store from app.process import actions, tasks - for name, step in (("待办的时限处理", tasks.tick), ("写入结果的查询", actions.tick)): + for name, step in (("待办的时限处理", tasks.tick), ("写入结果的查询", actions.tick), + ("没有提交的上传文件清理", files_store.cleanup_tick)): try: await step(now) except Exception: # noqa: BLE001 diff --git a/backend/app/tools/builtin/__init__.py b/backend/app/tools/builtin/__init__.py index 5f988361..313410d2 100644 --- a/backend/app/tools/builtin/__init__.py +++ b/backend/app/tools/builtin/__init__.py @@ -1,5 +1,5 @@ """导入即注册。新增内置工具时在这里加一行。""" -from app.tools.builtin import code, data, files, knowledge, web # noqa: F401 +from app.tools.builtin import code, data, files, knowledge, platform, web # noqa: F401 -__all__ = ["code", "data", "files", "knowledge", "web"] +__all__ = ["code", "data", "files", "knowledge", "platform", "web"] diff --git a/backend/app/tools/builtin/platform.py b/backend/app/tools/builtin/platform.py new file mode 100644 index 00000000..eddf1531 --- /dev/null +++ b/backend/app/tools/builtin/platform.py @@ -0,0 +1,71 @@ +"""平台内置能力的工具定义(docs/design/normal-user-apps.md N8、N9;执行在 capabilities/platform.py)。 + +这里只登记名字、说明和参数,让它们进能力登记(效果、治理、版本)和画布的工具清单。写入的两项(records_append、 +table_import_period)效果记 write:只能放在调用工具节点里,节点按动作流程执行(先留生效记录、按幂等键写、需要时等人 +确认),不会走到这里的函数——走到了说明绕过了动作流程,照实拒绝。records_lookup 是只读的查询能力。 +""" +from __future__ import annotations + +from typing import Any + +from pydantic import BaseModel, Field + +from app.files import TABLE_IMPORT_PERIOD +from app.records import RECORDS_APPEND, RECORDS_LOOKUP +from app.tools.registry import ToolContext, register + +#: 写入能力被直接调用(没经动作流程)时交回的话 +_ONLY_VIA_ACTION = "「{name}」是写入能力,只能放在「调用工具」节点里,由动作流程写入(留生效记录、按动作键只写一次)" + + +class RecordsAppendArgs(BaseModel): + table: str = Field(description="写哪张记录表:记录表的数据源名(如 rec_ab12cd),或 records_tables 的编号") + values: dict[str, Any] | str = Field(description="这一行各字段的值,键是表单字段名;也可以是一段 JSON 文字") + supersedes: str | None = Field(default=None, description="更正时填被更正那一行的编号(_id);新增一行时不填") + + +@register( + name=RECORDS_APPEND, + category="记录表", + description="往平台托管的记录表追加一行(填报登记)。一次动作只落一行,重放不会重复写;更正是追加一行并指向被更正的行," + "原行不改。只能放在「调用工具」节点里", + args_schema=RecordsAppendArgs, + effect="write", +) +async def records_append(ctx: ToolContext, **kwargs: Any) -> dict[str, Any]: + return {"error": _ONLY_VIA_ACTION.format(name=RECORDS_APPEND)} + + +class RecordsLookupArgs(BaseModel): + idempotency_key: str = Field(description="写入时用的幂等键:动作键加上第几次发送") + + +@register( + name=RECORDS_LOOKUP, + category="记录表", + description="按幂等键查一次记录表写入有没有落下(写入结果未知时,平台用它自动核实)", + args_schema=RecordsLookupArgs, +) +async def records_lookup(ctx: ToolContext, **kwargs: Any) -> dict[str, Any]: + from app.records.actions import lookup_action + + args = RecordsLookupArgs(**kwargs) + result = await lookup_action({"idempotency_key": args.idempotency_key}, environment="prod") + return {"status": result.status, **(result.body if isinstance(result.body, dict) else {})} + + +class TableImportPeriodArgs(BaseModel): + source: str = Field(description="导入到哪个数据源(按配方导入的上传表格,写数据源名)") + file: dict[str, Any] | str = Field(description="要导入的文件:上传后拿到的引用(来自表单的文件字段)") + + +@register( + name=TABLE_IMPORT_PERIOD, + category="数据", + description="把一个上传的文件按数据源已有的配方导入成新的一期(同数据页的「上传新一期」)。会换掉数据源的当前数据," + "只能放在「调用工具」节点里,由人确认后执行", + args_schema=TableImportPeriodArgs, + effect="write", +) +async def table_import_period(ctx: ToolContext, **kwargs: Any) -> dict[str, Any]: + return {"error": _ONLY_VIA_ACTION.format(name=TABLE_IMPORT_PERIOD)} diff --git a/backend/app/tools/datasource.py b/backend/app/tools/datasource.py index f51a4dde..519d9bba 100644 --- a/backend/app/tools/datasource.py +++ b/backend/app/tools/datasource.py @@ -341,6 +341,8 @@ async def _resolve(session: AsyncSession, row: DataSource, ctx: ToolContext) -> pins = ctx.data_versions if isinstance(pins, dict) and row.id not in pins and _pinned_under_name(pins, row.name): raise table_versions.SnapshotMissing(_rebuilt(row.name)) + if (getattr(row, "origin", None) or "manual") == "records": + return await _resolve_records(session, row, ctx), True if (getattr(row, "origin", None) or "manual") != "upload": return row, False if pins is None or pins is Versions.CURRENT: @@ -428,6 +430,66 @@ async def _pin_late(row: DataSource, ctx: ToolContext) -> str: return sid +async def _resolve_records(session: AsyncSession, row: DataSource, ctx: ToolContext) -> Any: + """记录表(docs/design/normal-user-apps.md N8):按这次运行 data_versions 里记下的高水位和行级过滤,换成连接上建 + 同名临时视图的 RecordsView(records/views.py)。和上传表格同一套规矩: + + - 不在运行里(工具库试用,Versions.CURRENT)、升级前发起的运行(None):现在的数据、看全部(只有搭建者进得来); + - 在运行里却没拿到固定的版本(Versions.UNSET):报错,不退回现在的数据; + - 运行里还没固定(发起时没算到):第一次用到时固定当时的高水位和行级过滤,记进运行(_pin_late_records)。""" + from app.records import views as records_views + + pins = ctx.data_versions + if pins is None or pins is Versions.CURRENT: + return await records_views.resolve(session, row) + if not isinstance(pins, dict): + logger.error("记录表 %s 的工具没拿到用哪一版(运行 %s 节点 %s 的 ToolContext.data_versions=%r)", + row.name, ctx.run_id, ctx.node_id, pins) + raise table_versions.SnapshotMissing(_versions_lost(row.name)) + entry = pins.get(row.id) + if not isinstance(entry, dict) or not isinstance(entry.get("seq"), int): + entry = await _pin_late_records(row, ctx) + return await records_views.resolve(session, row, entry) + + +async def _pin_late_records(row: DataSource, ctx: ToolContext) -> dict[str, Any]: + """发起时没固定到的记录表:第一次用到时固定当时的高水位和这次运行看哪些行,记进 runs.data_versions。 + 做法同 _pin_late:锁内认运行记录里已有的,没有才现算;补固定这件事发一条日志事件。""" + from app.db.base import SessionLocal + from app.db.models import Run + from app.records.views import pin_entry + + pins = ctx.data_versions + assert isinstance(pins, dict) + created = False + async with _late_lock(): + entry = pins.get(row.id) + if isinstance(entry, dict) and isinstance(entry.get("seq"), int): + return entry + async with SessionLocal() as session: + run = await session.get(Run, ctx.run_id) if ctx.run_id else None + stored = dict((run.data_versions if run is not None else None) or {}) + entry = stored.get(row.id) + if not (isinstance(entry, dict) and isinstance(entry.get("seq"), int)): + entry = await pin_entry(session, row, run_class=run.run_class if run is not None else "exploratory", + started_by=run.started_by if run is not None else None) + if entry is None: + raise table_versions.SnapshotMissing(f"记录表「{row.name}」的登记或数据文件不在了,请联系管理员") + entry["late"] = True + created = True + if run is not None: + stored[row.id] = entry + run.data_versions = stored + await session.commit() + pins[row.id] = entry + if created: + await _announce(ctx, EventType.LOG, level="info", code=LATE_PIN_CODE, + message=f"记录表「{row.name}」发起时没有固定,本次运行第一次用到它时固定为当时已有的记录," + "之后继续运行、审批恢复都沿用这一份", + source_id=row.id, source=row.name, seq=entry.get("seq"), late=True) + return entry + + async def _announce(ctx: ToolContext, event_type: EventType, **data: Any) -> None: """经 ToolContext.emit 往运行的事件流里发一条事件;没给 emit(不在运行里)就不发。发不出去不影响查询。""" if ctx.emit is None: @@ -611,6 +673,11 @@ def _make_query_tool(source: Any, ctx: ToolContext, *, fixed: bool = False, extra["masked_whole"] = True if version := getattr(source, "snapshot_id", None): extra["data_version"] = version + # 记录表(records/views.py):查的是第几条以内、看的是谁的行。不写进 data_version:那一项是上传表格的快照 + # id,出处链按它找快照文件 + if getattr(source, "origin", None) == "records" and getattr(source, "prelude", None): + extra["records_view"] = {"high_water": getattr(source, "high_water", None), + "rows": getattr(source, "rows", None)} # 工件引用的 meta 记下源和 SQL 里用到的表:数据目录按它数每张表被运行查询过几次 # (catalog.table_usage),不用再逐个读工件内容。meta 不进内容哈希,快照本身一字不变 payload["artifact"] = await put_json( diff --git a/backend/app/tools/registry.py b/backend/app/tools/registry.py index f200be53..59e66d80 100644 --- a/backend/app/tools/registry.py +++ b/backend/app/tools/registry.py @@ -62,6 +62,9 @@ class ToolSpec: # 改平台自身的状态(写记忆):不危险到默认要人确认,但也不是只读——能力登记里不能记成只读(只读的才能正式运行免审批、 # 才能当写入的查询能力),见 capabilities.registry._discover writes_state: bool = False + # 能力登记里的效果,写了就照它登记(平台内置的写入能力记 write:只能放在调用工具节点里,经动作流程执行, + # capabilities/platform.py)。不写的按 dangerous / writes_state 推 + effect: str | None = None def json_schema(self) -> dict[str, Any]: return self.args_schema.model_json_schema() @@ -79,6 +82,7 @@ def register( dangerous: bool = False, needs_context: bool = True, writes_state: bool = False, + effect: str | None = None, ) -> Callable[[ToolFunc], ToolFunc]: def deco(func: ToolFunc) -> ToolFunc: _REGISTRY[name] = ToolSpec( @@ -90,6 +94,7 @@ def register( dangerous=dangerous, needs_context=needs_context, writes_state=writes_state, + effect=effect, ) return func diff --git a/backend/tests/blueprint_samples.py b/backend/tests/blueprint_samples.py new file mode 100644 index 00000000..f0dbd328 --- /dev/null +++ b/backend/tests/blueprint_samples.py @@ -0,0 +1,128 @@ +"""蓝图、试运行、发布单测试共用的样本(docs/design/normal-user-apps.md 包 B2)。数据全是虚构的。 + +- 一个小的 SQLite 数据源(门店订单,金额、支付日),登记成只读数据源; +- 看板图:统计期 → 查订单 → 口径卡 → 按指标出具(不调模型); +- 流程图:发起报销 → 财务会签(岗位 finance,1 小时超时升级给 director)→ 已通过 / 已退回; +- 存工作流并直接落一个发布版本(发布门禁另有测试,这里要的是一个已发布的不可变版本)、等运行结束、改蓝图卡片。 +""" +from __future__ import annotations + +import asyncio +import sqlite3 +import uuid +from pathlib import Path +from typing import Any + +from app.core.artifact_store import graph_hash +from app.db.base import SessionLocal, utcnow +from app.db.models import DataSource, Run, Workflow, WorkflowVersion +from app.db.models_blueprints import Blueprint + +GMV_SQL = ("SELECT ROUND(SUM(amount), 2) AS gmv, COUNT(*) AS orders FROM orders " + "WHERE paid_at BETWEEN '{{ input.period_start }}' AND '{{ input.period_end }}'") +PERIOD = {"period": "2026-W40", "period_start": "2026-09-28", "period_end": "2026-10-04"} + + +def node(nid: str, ntype: str, label: str | None = None, **config: Any) -> dict[str, Any]: + return {"id": nid, "type": ntype, "position": {"x": 0, "y": 0}, "data": {"label": label or nid, "config": config}} + + +def chain(*nodes: dict[str, Any]) -> dict[str, Any]: + return {"nodes": list(nodes), "edges": [{"source": a["id"], "target": b["id"]} for a, b in zip(nodes, nodes[1:])]} + + +def make_source(tmp_path: Path) -> str: + """建库、登记数据源,交回数据源名(每个测试一个,名字不撞)。同步写库文件,登记在调用方的事件循环里做。""" + path = tmp_path / f"shop_{uuid.uuid4().hex[:6]}.db" + with sqlite3.connect(path) as db: + db.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, amount REAL, paid_at TEXT)") + db.executemany("INSERT INTO orders (amount, paid_at) VALUES (?, ?)", + [(120.5, "2026-09-29"), (80.0, "2026-10-01"), (999.0, "2026-10-09")]) + return str(path) + + +async def register_source(path: str) -> str: + name = f"shop_{uuid.uuid4().hex[:6]}" + async with SessionLocal() as session: + session.add(DataSource(name=name, kind="sqlite", database=path, readonly=True, enabled=True)) + await session.commit() + return name + + +def board_graph(source: str) -> dict[str, Any]: + """统计期 → 查订单 → 口径卡 → 按指标出具。""" + return chain( + node("start", "input", "统计期", fields=[ + {"name": "period", "default": PERIOD["period"]}, + {"name": "period_start", "default": PERIOD["period_start"]}, + {"name": "period_end", "default": PERIOD["period_end"]}]), + node("q", "tool", "查订单", tool=f"db_query__{source}", args={"sql": GMV_SQL}), + node("caliber", "metrics", "周销售口径卡", caliber="周销售口径", caliber_version="v1", metrics=[ + {"id": "gmv", "name": "销售额", "unit": "元", "decimals": 2, "expression": "cell(nodes.q, 0, 'gmv')"}]), + node("done", "output", "出具", fields=[{"name": "销售额", "value": "{{ nodes.caliber.metrics[0].value }}"}], + contract={"metrics_from": ["caliber"], "required": ["gmv"], "strict": True}), + ) + + +def expense_graph() -> dict[str, Any]: + nodes = [node("start", "input", "发起报销", fields=[{"name": "applicant"}, {"name": "amount", "type": "number"}]), + node("review", "human", "财务会签", mode="approve", title="报销审批:{{ input.applicant }}", + assignee={"kind": "slot", "slot": "finance"}, policy="all", due="PT1H", + on_timeout={"action": "escalate", "to_slot": "director"}), + node("ok", "output", "已通过", fields=[{"name": "结论", "value": "已通过"}]), + node("no", "output", "已退回", fields=[{"name": "结论", "value": "已退回"}])] + edges = [{"source": "start", "target": "review"}, + {"source": "review", "target": "ok", "sourceHandle": "approved"}, + {"source": "review", "target": "no", "sourceHandle": "rejected"}] + return {"nodes": nodes, "edges": edges} + + +async def published_workflow(graph: dict[str, Any], name: str, *, description: str = "", + level: str = "published") -> str: + """存工作流并把 v1 立为发布版本(直接落库)。交回工作流 id。""" + async with SessionLocal() as session: + wf = Workflow(name=name, description=description, graph=graph, version=1, published_version=1, + status=level) + session.add(wf) + await session.flush() + session.add(WorkflowVersion(workflow_id=wf.id, version=1, graph=graph, graph_hash=graph_hash(graph), + level=level, published_at=utcnow(), published_by="样本")) + await session.commit() + return wf.id + + +async def wait(run_id: str, statuses: tuple[str, ...] = ("succeeded", "failed", "cancelled"), + timeout: float = 30.0) -> Run: + """等运行走到这几种状态之一(终态的还要等封存完)。""" + from app.engine.runner import run_manager + + deadline = asyncio.get_event_loop().time() + timeout + row = None + while asyncio.get_event_loop().time() < deadline: + async with SessionLocal() as session: + row = await session.get(Run, run_id) + if row is not None and row.status in statuses and not run_manager.is_active(run_id) and ( + row.status == "interrupted" or row.manifest_seq is not None): + return row + await asyncio.sleep(0.05) + raise AssertionError(f"运行 {run_id} 没有走到 {statuses}:{row.status if row else None}") + + +def item(value: Any, source: str = "user", status: str = "confirmed") -> dict[str, Any]: + return {"value": value, "source": source, "status": status, "why": None} + + +async def edit_spec(blueprint_id: str, **cards: Any) -> None: + """直接改蓝图的卡片(卡片上的修改另有测试,这里要的是一张填好的蓝图)。""" + async with SessionLocal() as session: + bp = await session.get(Blueprint, blueprint_id) + bp.spec = {**(bp.spec or {}), **cards} + await session.commit() + + +WEEKLY = {"preset": "weekly", "weekday": 1, "time": "09:00", "tz": "Asia/Shanghai", "period": "last_iso_week"} + + +async def blueprint(blueprint_id: str) -> Blueprint: + async with SessionLocal() as session: + return await session.get(Blueprint, blueprint_id) diff --git a/backend/tests/test_app_catalog.py b/backend/tests/test_app_catalog.py index ac5d977e..a2c371ad 100644 --- a/backend/tests/test_app_catalog.py +++ b/backend/tests/test_app_catalog.py @@ -42,3 +42,18 @@ def test_annotations_do_not_change_validation(): assert not list(Draft202012Validator(table).iter_errors({"title": "门店", "sort": "-gmv", "limit": 20})) assert list(Draft202012Validator(table).iter_errors({"limit": 0})) assert list(Draft202012Validator(table).iter_errors({"unknown": 1})) + + +def test_text_props_are_marked_for_page_editing(): + """应用页上直接改的「改文字」(normal-user-apps N6)只改标了 x-text 的属性:给人看的标题、名称、说明。 + 列名、换算这类写给解析器的字符串不标,普通人改了会让组件取不到数。x-text 同样只是注解,不参与校验。""" + marked = {(c["name"], key) for c in COMPONENTS for key, prop in c["props"]["properties"].items() + if prop.get("x-text") is True} + assert {("metric", "label"), ("metric", "unit"), ("text", "markdown"), ("notice", "text"), + ("section", "description"), ("entry_button", "label"), ("form", "submit_label")} <= marked + assert ("metric", "conv") not in marked and ("chart", "x") not in marked + # 只有字符串、不是枚举的才标 + for name, key in marked: + prop = BY_NAME[name]["props"]["properties"][key] + assert prop["type"] == "string" and "enum" not in prop, (name, key) + assert not list(Draft202012Validator(BY_NAME["metric"]["props"]).iter_errors({"label": "销售额", "conv": "万"})) diff --git a/backend/tests/test_app_spec_tools.py b/backend/tests/test_app_spec_tools.py index 4d5a7873..ace89d43 100644 --- a/backend/tests/test_app_spec_tools.py +++ b/backend/tests/test_app_spec_tools.py @@ -16,7 +16,7 @@ from app.apps.access import role_of from app.apps.derive import derive_app from app.apps.describe import describe_version from app.apps.lint import lint_app -from app.apps.ops import apply_app_op +from app.apps.ops import apply_app_op, polish_problem from app.apps.spec import empty_spec, parse_spec from app.core.artifact_store import graph_hash from app.db.base import SessionLocal, utcnow @@ -133,6 +133,26 @@ def test_the_six_operations(): parse_spec(spec) +def test_update_hides_and_unhides_a_component(): + """隐藏(normal-user-apps N6)走 app_update:为真才写进组件,取消隐藏去掉这一项;写别的值拒收、组件不动。 + 应用页上直接改和编辑器的「隐藏」开关、助手润色用的都是这一个操作(前端 edit/appOps 同一套)。""" + spec = empty_spec("看板") + apply_app_op(spec, {"op": "app_page", "page": {"id": "home", "title": "首页"}}) + apply_app_op(spec, {"op": "app_add", "parent": "home", "component": {"id": "tip", "type": "notice", "props": {"text": "说明"}}}) + comp = spec["pages"][0]["body"][0] + assert apply_app_op(spec, {"op": "app_update", "id": "tip", "hidden": True}).changed + assert comp["hidden"] is True + parse_spec(spec) + again = apply_app_op(spec, {"op": "app_update", "id": "tip", "hidden": True}) + assert (again.changed, again.problem) == (False, None) + bad = apply_app_op(spec, {"op": "app_update", "id": "tip", "hidden": "yes"}) + assert bad.problem and comp["hidden"] is True + assert apply_app_op(spec, {"op": "app_update", "id": "tip", "hidden": False}).changed + assert "hidden" not in comp + # 润色可以隐藏:只改呈现 + assert polish_problem(spec, {"op": "app_update", "id": "tip", "hidden": True}) is None + + # -------------------------------------------------------------------------- # 应用检查 # -------------------------------------------------------------------------- diff --git a/backend/tests/test_blueprint_generation.py b/backend/tests/test_blueprint_generation.py new file mode 100644 index 00000000..55ee30d3 --- /dev/null +++ b/backend/tests/test_blueprint_generation.py @@ -0,0 +1,300 @@ +"""蓝图和关节的生成落地(docs/design/normal-user-apps.md N2、N3、§3.4)、蓝图的存与留痕、查看口径(look caliber)。 + +- TemplateApplier 只收 fill_joint,只收这一组里模板声明过的生成关节;改别的位置、别组的关节、用别的操作一律拒绝并照实 + 交回(自查时交回模型一次、交付时列给人看); +- TemplateChecker:没填的、指标式不合规矩(只许 cell() 取格加算术、行号 0、列要在 SQL 里、追得到原始数据)、SQL 过不了 + 只读检查; +- BlueprintApplier:助手的操作来源记 assistant,越界的拒;复用口径卡按读好的口径核对并补上它读的列; +- apply_ops_and_save:每个操作写一条留痕;卡片改了,那一组生成关节标回「待填」;助手这一轮的操作和人改过的卡片冲突时 + 照实交回; +- look caliber:只列最新的已发布且未退役版本里的源头口径卡,给出复用写法;读别的东西的卡照实说不能复用; + verify_reuse 按库里那一版核对。 +""" +from __future__ import annotations + +import copy +import uuid + +import pytest + +from app.blueprints.generation import BlueprintApplier, BlueprintChecker, TemplateApplier, TemplateChecker +from app.blueprints.instantiate import generated_groups, instantiate +from app.blueprints.templates import _common as c +from app.db.base import SessionLocal +import app.db.models # noqa: F401 - 建表前要先登记全部模型(conftest 按 Base.metadata 建) + + +def _board(): + extras = c.EXTRAS["periodic_board"] + inst = instantiate(extras.example()) + group = generated_groups(inst)["fetch_shop"] + return extras, inst, group + + +def test_template_applier_refuses_anything_but_declared_joints(): + extras, inst, group = _board() + graph = copy.deepcopy(inst.graph) + applier = TemplateApplier(graph, inst.joint_defs, group) + ok = applier.apply({"op": "fill_joint", "joint": "metric_gmv", "value": "cell(nodes.fetch_shop, 0, 'gmv')"}) + assert (ok.changed, ok.forward) == (True, True) + assert {n["id"]: n for n in graph["nodes"]}["caliber"]["data"]["config"]["metrics"][0]["expression"] \ + == "cell(nodes.fetch_shop, 0, 'gmv')" + before = copy.deepcopy(graph) + for op, words in ( + ({"op": "fill_joint", "joint": "done.contract", "value": "{}"}, "按卡片确定地填"), + ({"op": "fill_joint", "joint": "nope", "value": "x"}, "没有关节"), + ({"op": "fill_joint", "joint": "sql_fetch_shop", "value": " "}, "非空"), + ({"op": "update_node", "id": "done", "config": {"contract": {}}}, "锁住"), + ({"op": "add_node", "node": {"id": "x", "type": "llm"}}, "锁住"), + ({"op": "bp_set", "path": "/purpose", "value": "x"}, "fill_joint"), + ): + out = applier.apply(op) + assert (out.changed, out.forward) == (False, False) and words in out.problem, op + assert graph == before, "被拒的一处都没落地" + assert [r["joint"] for r in applier.refusals()] == ["done.contract", "nope", "sql_fetch_shop", None, None, None] + assert all(r["code"] == "tpl.joint_refused" for r in applier.refusals()) + + # 别的组的关节也不收 + spec = extras.example() + spec["data"].append({**copy.deepcopy(spec["data"][0]), "id": "visits", "table": c.template_item( + {"source": "crm", "table": "visits"})}) + two = instantiate(spec) + groups = generated_groups(two) + applier = TemplateApplier(copy.deepcopy(two.graph), two.joint_defs, groups["fetch_shop"]) + assert "不在这一组里" in applier.apply({"op": "fill_joint", "joint": "sql_fetch_crm", "value": "SELECT 1"}).problem + + +async def test_template_checker_reports_unfilled_expressions_and_sql(): + extras, inst, group = _board() + applier = TemplateApplier(copy.deepcopy(inst.graph), inst.joint_defs, group) + checker = TemplateChecker(applier, skeleton=inst.skeleton) + applier.apply({"op": "fill_joint", "joint": "nope", "value": "x"}) + first = await checker.issues() + assert {i["code"] for i in first} == {"tpl.joint_refused", "tpl.joint_unfilled"} + assert {i["joint"] for i in first if i["code"] == "tpl.joint_unfilled"} == {j.id for j in group} + assert "tpl.joint_refused" not in {i["code"] for i in await checker.issues()}, "越界的只交回一次" + + fill = extras.example_fill() + for jid, value in fill.items(): + applier.apply({"op": "fill_joint", "joint": jid, "value": value}) + assert await checker.issues() == [] + + for jid, value, code, words in ( + ("metric_gmv", "len(nodes.fetch_shop.rows)", "tpl.metric_expr", "不能用 len"), + ("metric_gmv", "cell(nodes.caliber, 0, 'gmv')", "tpl.metric_expr", "这一组取数"), + ("metric_gmv", "cell(nodes.fetch_shop, 1, 'gmv')", "tpl.metric_expr", "行号写 0"), + ("metric_gmv", "cell(nodes.fetch_shop, 0, 'revenue')", "tpl.metric_column", "找不到"), + ("metric_gmv", "input.period", "tpl.metric_expr", "cell("), + ("metric_gmv", "cell(nodes.fetch_shop, 0, 'gmv') +", "tpl.metric_expr", "写得不对"), + ("sql_fetch_shop", "DELETE FROM orders", "tpl.sql_rejected", "只读"), + ): + fresh = TemplateApplier(copy.deepcopy(inst.graph), inst.joint_defs, group) + for k, v in {**fill, jid: value}.items(): + fresh.apply({"op": "fill_joint", "joint": k, "value": v}) + issues = await TemplateChecker(fresh, skeleton=inst.skeleton).issues() + assert any(i["code"] == code and words in i["message"] for i in issues), (value, issues) + assert "fill_joint" in checker.repair_request(first, "看过的表") + + +def test_blueprint_applier_records_assistant_proposals_and_refusals(): + from app.blueprints.spec import empty_blueprint + + applier = BlueprintApplier(empty_blueprint()) + assert applier.apply({"op": "bp_template", "template": {"id": "periodic_board", "version": 1}}).changed + assert applier.apply({"op": "bp_set", "path": "/purpose", "value": "看销售"}).changed + assert applier.spec["purpose"]["status"] == "proposed" + out = applier.apply({"op": "bp_add", "path": "/access/use", "value": {"kind": "group", "name": "门店"}}) + assert (out.changed, out.forward) == (False, False) and "授权" in out.problem + assert not applier.apply({"op": "add_node", "node": {}}).forward + assert applier.apply({"op": "plan", "summary": "整理"}).forward + assert applier.landed() == ["bp_template", "/purpose"] + assert [r["path"] for r in applier.refusals()] == ["/access/use"] + + +async def test_blueprint_checker_sends_back_refusals_and_mismatches(): + from app.blueprints.spec import empty_blueprint + + applier = BlueprintApplier(empty_blueprint()) + checker = BlueprintChecker(applier) + applier.apply({"op": "bp_template", "template": {"id": "periodic_board", "version": 1}}) + applier.apply({"op": "bp_add", "path": "/people", "value": {"id": "s1", "label": "审批"}}) + applier.apply({"op": "bp_set", "path": "/access/use", "value": []}) + issues = await checker.issues() + assert {i["code"] for i in issues} == {"bp.refused", "bp.template_mismatch"} + # 缺项不交回模型:缺的是只有用户知道的事 + assert "bp.missing" not in {i["code"] for i in issues} + assert "bp_ask" in checker.repair_request(issues, "") + + +async def _blueprint(spec: dict, **extra): + from app.db.models_blueprints import Blueprint + + async with SessionLocal() as session: + row = Blueprint(name="测试蓝图", scope="shared", spec=spec, **extra) + session.add(row) + await session.commit() + return row.id + + +async def test_apply_ops_and_save_writes_events_and_marks_stale_joints(): + from sqlalchemy import select + + from app.blueprints import store + from app.blueprints.ops import BpRefused + from app.db.models_blueprints import Blueprint, BlueprintEvent + + extras = c.EXTRAS["periodic_board"] + spec = extras.example() + inst = instantiate(spec, filled=extras.example_fill()) + bp_id = await _blueprint(spec, template_id="periodic_board", template_version=1, joints=inst.joints) + async with SessionLocal() as session: + row = await session.get(Blueprint, bp_id) + saved = await store.apply_ops_and_save(session, row, [ + {"op": "bp_set", "path": "/purpose", "value": "每周一看上周"}, + {"op": "bp_set", "path": "/data/0/measure", "value": "sum(amount) - sum(refund)"}, + ], "zhang", True, "user") + assert len(saved.applied) == 2 and saved.refused == [] + events = list((await session.execute(select(BlueprintEvent).where(BlueprintEvent.blueprint_id == bp_id) + .order_by(BlueprintEvent.seq))).scalars()) + assert [(e.seq, e.op, e.actor, e.verified) for e in events] == [(1, "bp_set", "zhang", True), + (2, "bp_set", "zhang", True)] + assert events[1].data["before"]["value"] == "sum(amount)" + assert events[1].data["after"]["value"] == "sum(amount) - sum(refund)" + assert events[1].data["source"] == "user" + # 「怎么算」改了:这一组的 SQL 和指标式标回「待填」 + assert row.joints["sql_fetch_shop"]["status"] == "pending" + assert row.joints["done.contract"]["status"] == "filled" + # 卡片上的修改一个被拒就整串不落 + with pytest.raises(BpRefused): + await store.apply_ops_and_save(session, row, [ + {"op": "bp_set", "path": "/purpose", "value": "再改"}, + {"op": "bp_set", "path": "/people/0/policy", "value": "any"}, + ], "zhang", True, "user") + await session.refresh(row) + assert row.spec["purpose"]["value"] == "每周一看上周" + # 助手这一轮的:冲突的照实交回,别的照常落 + saved = await store.apply_ops_and_save(session, row, [ + {"op": "bp_set", "path": "/data/0/label", "value": "成交额"}, + {"op": "bp_set", "path": "/data/9/label", "value": "不存在"}, + ], None, False, "assistant", partial=True) + assert [o["path"] for o in saved.applied] == ["/data/0/label"] + assert "超出了列表的范围" in saved.refused[0]["message"] + out = store.blueprint_out(row) + assert out["spec"]["data"][0]["label"] == {"value": "成交额", "source": "assistant", "status": "proposed", + "why": None} + assert "value" not in out["joints"]["sql_fetch_shop"], "关节只给状态" + codes = {i["code"] for i in out["issues"]} + assert {"bp.unconfirmed", "tpl.joint_unfilled"} <= codes + assert all(i.get("plain") for i in out["issues"] if i["code"].startswith(("bp.", "tpl."))) + await session.delete(row) + await session.commit() + + +# ---------------------------------------------------------------- 查看口径 + + +async def _published_card(graph: dict) -> tuple[str, str]: + from app.db.models import Workflow, WorkflowVersion + + async with SessionLocal() as session: + wf = Workflow(name=f"周销售_{uuid.uuid4().hex[:6]}", graph=graph, status="published", published_version=1) + session.add(wf) + await session.flush() + session.add(WorkflowVersion(workflow_id=wf.id, version=1, graph=graph, graph_hash="h" * 64, level="published")) + await session.commit() + return wf.id, wf.name + + +def _card_graph(expression: str = "cell(nodes.fetch, 0, 'gmv') / cell(nodes.fetch, 0, 'order_cnt')") -> dict: + return {"nodes": [ + c.node("start", "input", "入口"), + c.node("fetch", "tool", "取数", tool="db_query__shop", args={"sql": "SELECT 1 AS gmv, 2 AS order_cnt"}), + c.node("kpi", "metrics", "周报口径卡", caliber="周报口径", caliber_version="v2", metrics=[ + {"id": "gmv", "name": "销售额", "unit": "元", "expression": "cell(nodes.fetch, 0, 'gmv')"}, + {"id": "aov", "name": "客单价", "unit": "元", "expression": expression}]), + ], "edges": [c.edge("start", "fetch"), c.edge("fetch", "kpi")]} + + +async def test_look_caliber_lists_published_cards_and_how_to_reuse(): + from app.db.models import Workflow + from app.look.base import LookBudget + from app.look.calibers import CaliberKind + from app.look.service import LookService + + wf_id, wf_name = await _published_card(_card_graph()) + bad_id, bad_name = await _published_card(_card_graph("vars.x * 2")) + try: + async with SessionLocal() as session: + kind = await CaliberKind.load(session) + mine = [i for i in kind.items if i.workflow_id == wf_id] + assert [(i.metric_id, i.name, i.version) for i in mine] == [("gmv", "销售额", 1), ("aov", "客单价", 1)] + assert mine[1].reuse() == {"workflow_id": wf_id, "version": 1, "node_id": "kpi", "metric_id": "aov", + "inputs": [{"node": "fetch", "tool": "db_query__shop", "columns": ["gmv", "order_cnt"]}]} + assert any(wf_name in line for line in await kind.overview()) + looks = LookService([kind]) + result = await looks.look({"op": "look", "need": "客单价", "targets": [ + {"kind": "caliber", "source": wf_name, "name": "客单价"}, {"kind": "caliber", "name": "不存在的指标"}]}, + LookBudget()) + assert result.record["objects"][0]["kind"] == "caliber" + assert result.record["objects"][0]["named"] == [f"{wf_name} v1 · 客单价"] + assert "复用写法" in result.text and '"metric_id": "aov"' in result.text and "fetch(db_query__shop)" in result.text + assert "没找到口径" in result.text + # 读别的东西的卡:照实说不能复用 + bad = [i for i in kind.items if i.workflow_id == bad_id] + assert bad and all(i.reuse() is None for i in bad) + result = await looks.look({"op": "look", "need": "x", "targets": [{"kind": "caliber", "source": bad_name}]}, + LookBudget()) + assert "不能复用" in result.text + # 蓝图助手按读好的口径核对复用、补上读的列 + reuse, reason = kind.reuse_for({"workflow_id": wf_id, "version": 1, "node_id": "kpi", "metric_id": "aov"}) + assert reason is None and reuse["inputs"][0]["columns"] == ["gmv", "order_cnt"] + assert kind.reuse_for({"workflow_id": wf_id, "version": 7, "node_id": "kpi", "metric_id": "aov"})[0] is None + finally: + async with SessionLocal() as session: + for wid in (wf_id, bad_id): + await session.delete(await session.get(Workflow, wid)) + await session.commit() + + +async def test_saving_a_reuse_checks_the_published_version(): + from app.blueprints import store + from app.blueprints.ops import BpRefused + from app.blueprints.spec import empty_blueprint + from app.db.models import Workflow, WorkflowVersion + from app.db.models_blueprints import Blueprint + + wf_id, _ = await _published_card(_card_graph()) + spec = empty_blueprint() + spec["data"] = [{"id": "aov", "label": c.template_item("客单价"), "unit": c.template_item(None), + "table": c.template_item(None), "measure": c.template_item(None), "date": c.template_item(None), + "filter": c.template_item(None), "grain": c.template_item(None), "reuse": None}] + bp_id = await _blueprint(spec) + try: + async with SessionLocal() as session: + row = await session.get(Blueprint, bp_id) + ref = {"workflow_id": wf_id, "version": 1, "node_id": "kpi", "metric_id": "aov"} + await store.apply_ops_and_save(session, row, [{"op": "bp_set", "path": "/data/0/reuse", "value": ref}], + "zhang", True, "user") + assert row.spec["data"][0]["reuse"]["inputs"] == [ + {"node": "fetch", "tool": "db_query__shop", "columns": ["gmv", "order_cnt"]}] + # 退役了的版本不能复用 + version = (await session.execute(WorkflowVersion.__table__.select().where( + WorkflowVersion.workflow_id == wf_id))).first() + assert version is not None + from sqlalchemy import update + + from app.db.base import utcnow + + await session.execute(update(WorkflowVersion).where(WorkflowVersion.workflow_id == wf_id) + .values(retired_at=utcnow())) + await session.commit() + with pytest.raises(BpRefused) as e: + await store.apply_ops_and_save(session, row, [{"op": "bp_set", "path": "/data/0/reuse", "value": ref}], + "zhang", True, "user") + assert e.value.code == "bp.data_unmapped" + await session.delete(row) + await session.commit() + finally: + async with SessionLocal() as session: + await session.delete(await session.get(Workflow, wf_id)) + await session.commit() diff --git a/backend/tests/test_blueprint_ops.py b/backend/tests/test_blueprint_ops.py new file mode 100644 index 00000000..51faa862 --- /dev/null +++ b/backend/tests/test_blueprint_ops.py @@ -0,0 +1,238 @@ +"""蓝图的 bp_* 操作和卡片白名单(docs/design/normal-user-apps.md N2、§3.2、§3.13 bp.*)。 + +守的是: +- 每一项带来源和状态:用户写的「已确认」、助手写的「待确认」、写空的「缺」;确认只能由用户来做,值和来源不变; +- 各卡片的白名单:几个人同意只能是 any / all / quorum(quorum 要写人数);时限只收能换算成 ISO 8601 时长的说法; + 金额线只许「字段 比较 常量」;写回只能选能力登记里的写入能力;字段对应只能取表单字段、指标、核对的行或常量; + 「谁能看」只收用户的;反问只能助手问、用户答; +- bp_template 按模板预置还没填的卡片(来源「模板默认」); +- 不改入参;不合规的抛 BpRefused,带 bp.* 机器码; +- blueprint_issues:缺项、没对到数据、没人处理、超出模板能力、发布前没确认的项。 +""" +from __future__ import annotations + +import copy + +import pytest + +from app.blueprints.ops import BpRefused, apply_bp_op, blueprint_issues, duration_of +from app.blueprints.spec import empty_blueprint + + +def board() -> dict: + spec = apply_bp_op(empty_blueprint(), {"op": "bp_template", "template": {"id": "periodic_board", "version": 1}}, + source="user") + return spec + + +def refused(spec: dict, op: dict, *, source: str = "assistant") -> BpRefused: + with pytest.raises(BpRefused) as e: + apply_bp_op(spec, op, source=source) + return e.value + + +def test_items_carry_source_and_status_and_input_is_not_mutated(): + spec = empty_blueprint() + before = copy.deepcopy(spec) + out = apply_bp_op(spec, {"op": "bp_set", "path": "/purpose", "value": " 每周看销售额 "}, source="assistant") + assert spec == before + assert out["purpose"] == {"value": "每周看销售额", "source": "assistant", "status": "proposed", "why": None} + out = apply_bp_op(out, {"op": "bp_set", "path": "/purpose/why", "value": "用户第一句话说的"}, source="assistant") + assert out["purpose"]["why"] == "用户第一句话说的" + # 确认只能由用户来做:值和来源不变,只是状态变成已确认 + assert "确认只能由你来做" in refused(out, {"op": "bp_set", "path": "/purpose/status", "value": "confirmed"}).message + confirmed = apply_bp_op(out, {"op": "bp_set", "path": "/purpose/status", "value": "confirmed"}, source="user") + assert confirmed["purpose"] == {**out["purpose"], "status": "confirmed"} + # 用户直接改:已确认,来源记用户;写空:缺 + mine = apply_bp_op(out, {"op": "bp_set", "path": "/purpose", "value": "每天看"}, source="user") + assert (mine["purpose"]["source"], mine["purpose"]["status"]) == ("user", "confirmed") + cleared = apply_bp_op(mine, {"op": "bp_remove", "path": "/purpose"}, source="user") + assert (cleared["purpose"]["value"], cleared["purpose"]["status"]) == (None, "missing") + assert "没有值" in refused(cleared, {"op": "bp_set", "path": "/purpose/status", "value": "confirmed"}, + source="user").message + + +def test_template_prefills_with_template_source(): + spec = board() + assert spec["template"] == {"id": "periodic_board", "version": 1} + assert spec["cadence"]["source"] == "template" and spec["cadence"]["status"] == "proposed" + assert spec["cadence"]["value"]["preset"] == "weekly" + approval = apply_bp_op(empty_blueprint(), {"op": "bp_template", "template": {"id": "approval", "version": 1}}, + source="assistant") + assert approval["people"][0]["policy"]["value"] == {"kind": "any"} + assert approval["people"][0]["who"]["status"] == "missing", "处理人要人来填,模板不替人定" + # 已经写了的不动 + mine = apply_bp_op(empty_blueprint(), {"op": "bp_set", "path": "/cadence", "value": { + "preset": "daily", "time": "08:30", "tz": "Asia/Shanghai"}}, source="user") + again = apply_bp_op(mine, {"op": "bp_template", "template": {"id": "periodic_board", "version": 1}}, source="user") + assert again["cadence"]["value"]["time"] == "08:30" + e = refused(empty_blueprint(), {"op": "bp_template", "template": {"id": "nope", "version": 1}}) + assert e.code == "bp.template_mismatch" + assert "第 1 版" in refused(empty_blueprint(), {"op": "bp_template", "template": {"id": "approval", "version": 9}}).message + + +def test_data_items_and_reuse_shape(): + spec = apply_bp_op(board(), {"op": "bp_add", "path": "/data", "value": { + "id": "gmv", "label": "销售额", "unit": "元", "table": {"source": "shop", "table": "orders"}, + "date": {"column": "paid_at", "rule": "按支付日"}}}, source="assistant") + item = spec["data"][0] + assert item["table"]["value"] == {"source": "shop", "table": "orders"} and item["table"]["status"] == "proposed" + assert item["measure"]["status"] == "missing" + assert "已经有 id" in refused(spec, {"op": "bp_add", "path": "/data", "value": {"id": "gmv"}}).message + assert "小写字母" in refused(spec, {"op": "bp_add", "path": "/data", "value": {"id": "GMV!"}}).message + assert "不能写这些" in refused(spec, {"op": "bp_add", "path": "/data", "value": {"id": "x", "sql": "select"}}).message + assert "数据源和表名" in refused(spec, {"op": "bp_set", "path": "/data/0/table", "value": {"source": "shop"}}).message + reuse = {"workflow_id": "wf", "version": 3, "node_id": "kpi", "metric_id": "gmv"} + spec = apply_bp_op(spec, {"op": "bp_set", "path": "/data/0/reuse", "value": reuse}, source="user") + assert spec["data"][0]["reuse"] == reuse + assert "版本号" in refused(spec, {"op": "bp_set", "path": "/data/0/reuse", "value": {**reuse, "version": "v3"}}).message + spec = apply_bp_op(spec, {"op": "bp_remove", "path": "/data/0/reuse"}, source="user") + assert spec["data"][0]["reuse"] is None + # 插到某个位置、删一项 + spec = apply_bp_op(spec, {"op": "bp_add", "path": "/data/0", "value": {"id": "orders", "label": "订单数"}}, + source="user") + assert [d["id"] for d in spec["data"]] == ["orders", "gmv"] + spec = apply_bp_op(spec, {"op": "bp_remove", "path": "/data/1"}, source="user") + assert [d["id"] for d in spec["data"]] == ["orders"] + assert "超出了列表的范围" in refused(spec, {"op": "bp_remove", "path": "/data/5"}).message + + +def test_cadence_whitelist(): + spec = empty_blueprint() + ok = apply_bp_op(spec, {"op": "bp_set", "path": "/cadence", "value": { + "preset": "monthly", "day": 1, "time": "07:00", "tz": "asia/shanghai", "period": "last_month"}}, source="user") + assert ok["cadence"]["value"]["tz"] == "Asia/Shanghai" + for bad, words in (({"preset": "hourly", "time": "09:00", "tz": "Asia/Shanghai"}, "每天、每周或每月"), + ({"preset": "weekly", "time": "09:00", "tz": "Asia/Shanghai"}, "周几"), + ({"preset": "monthly", "day": 31, "time": "09:00", "tz": "Asia/Shanghai"}, "28"), + ({"preset": "daily", "time": "9点", "tz": "Asia/Shanghai"}, "24 小时制"), + ({"preset": "daily", "time": "09:00", "tz": "火星"}, "时区"), + ({"preset": "daily", "time": "09:00", "tz": "UTC", "period": "last_year"}, "哪一期")): + assert words in refused(spec, {"op": "bp_set", "path": "/cadence", "value": bad}).message, bad + + +def test_people_whitelist(): + spec = apply_bp_op(empty_blueprint(), {"op": "bp_add", "path": "/fields", "value": { + "name": "amount", "spec": {"type": "number", "title": "金额", "required": True}}}, source="user") + spec = apply_bp_op(spec, {"op": "bp_add", "path": "/people", "value": { + "id": "finance", "label": "财务", "who": [{"kind": "group", "name": "财务组"}], "policy": "all", "due": "48 小时", + "on_timeout": {"action": "escalate", "to": [{"kind": "user", "name": "director"}]}, + "threshold": {"field": "amount", "op": ">", "value": 5000}}}, source="assistant") + step = spec["people"][0] + assert step["policy"]["value"] == {"kind": "all"} + assert step["due"]["value"] == "PT48H" + assert step["on_timeout"]["value"]["to"] == [{"kind": "user", "name": "director"}] + # 几个人同意:只能是 any / all / quorum,quorum 要写人数 + assert apply_bp_op(spec, {"op": "bp_set", "path": "/people/0/policy", "value": {"kind": "quorum", "m": 2}}, + source="user")["people"][0]["policy"]["value"] == {"kind": "quorum", "m": 2} + for bad in ({"kind": "majority"}, {"kind": "quorum"}, {"kind": "any", "m": 2}, {"kind": "quorum", "m": 0}): + assert "同意" in refused(spec, {"op": "bp_set", "path": "/people/0/policy", "value": bad}).message, bad + # 时限:能换算成 ISO 8601 时长的才收 + assert [duration_of(v) for v in ("2 天", "1周", "30 分钟", "P2D", "pt4h", "3 个工作日", "明天")] == \ + ["P2D", "P1W", "PT30M", "P2D", "PT4H", None, None] + assert "时长" in refused(spec, {"op": "bp_set", "path": "/people/0/due", "value": "3 个工作日"}).message + # 超时:只能提醒、升级、驳回,升级要写给谁;没有「自动同意」 + assert "升级给谁" in refused(spec, {"op": "bp_set", "path": "/people/0/on_timeout", + "value": {"action": "escalate"}}).message + assert "不会自动同意" in refused(spec, {"op": "bp_set", "path": "/people/0/on_timeout", + "value": {"action": "approve"}}).message + # 金额线:只许「字段 比较 常量」 + for bad, words in (({"field": "amount * 2", "op": ">", "value": 1}, "字段名"), + ({"field": "amount", "op": "in", "value": 1}, "比较"), + ({"field": "amount", "op": ">", "value": {"x": 1}}, "不能写算式"), + ({"field": "amount", "op": ">", "value": "5000"}, "文字只能比较相等"), + ({"field": "kind", "op": "==", "value": "差旅"}, "不在「填什么」里"), + ({"field": "amount", "op": ">", "value": 1, "and": "x"}, "字段 比较 常量")): + assert words in refused(spec, {"op": "bp_set", "path": "/people/0/threshold", "value": bad}).message, bad + # 处理人:岗位不和别的混着写,发起人不和别的混着写 + assert "岗位" in refused(spec, {"op": "bp_set", "path": "/people/0/who", "value": [ + {"kind": "slot", "name": "财务"}, {"kind": "user", "name": "zhang"}]}).message + assert "种类" in refused(spec, {"op": "bp_set", "path": "/people/0/who", "value": [{"kind": "role", "name": "x"}]}).message + + +def test_fields_follow_the_form_rules(): + spec = apply_bp_op(empty_blueprint(), {"op": "bp_add", "path": "/fields", "value": { + "name": "kind", "spec": {"type": "string", "title": "类别", "enum": ["a", "b"], "x-enum-labels": ["甲", "乙"]}}}, + source="assistant") + assert spec["fields"][0]["spec"]["status"] == "proposed" + assert "正则" in refused(spec, {"op": "bp_set", "path": "/fields/0/spec", + "value": {"type": "string", "pattern": "^a"}}).message + assert "统计期" in refused(spec, {"op": "bp_add", "path": "/fields", "value": {"name": "period_start"}}).message + assert "已经有一个" in refused(spec, {"op": "bp_add", "path": "/fields", "value": {"name": "kind"}}).message + assert "必填" in refused(spec, {"op": "bp_set", "path": "/fields/0/spec", + "value": {"type": "string", "required": "yes"}}).message + renamed = apply_bp_op(spec, {"op": "bp_set", "path": "/fields/0/name", "value": "类别"}, source="user") + assert renamed["fields"][0]["name"] == "类别" + assert apply_bp_op(spec, {"op": "bp_set", "path": "/fields/0/sensitive", "value": True}, + source="user")["fields"][0]["sensitive"] is True + + +def test_writeback_only_takes_write_capabilities(monkeypatch): + from app.capabilities import registry + + monkeypatch.setitem(registry._view, "bp_test_erp_post", {"effect": "write", "endpoint_id": "e1", "missing": False}) + monkeypatch.setitem(registry._view, "bp_test_erp_get", {"effect": "read", "endpoint_id": "e1", "missing": False}) + spec = apply_bp_op(empty_blueprint(), {"op": "bp_set", "path": "/writeback", "value": { + "capability": "bp_test_erp_post", "mapping": {"amount": "form.amount", "kind": "'报销'", "n": 1, "all": "rows"}, + "confirm": True}}, source="assistant") + assert spec["writeback"]["capability"]["value"] == "bp_test_erp_post" + assert spec["writeback"]["mapping"]["status"] == "proposed" + assert "不是写入能力" in refused(spec, {"op": "bp_set", "path": "/writeback/capability", + "value": "bp_test_erp_get"}).message + assert "能力登记里没有" in refused(spec, {"op": "bp_set", "path": "/writeback/capability", + "value": "bp_test_nope"}).message + assert "取值只能是" in refused(spec, {"op": "bp_set", "path": "/writeback/mapping", + "value": {"amount": "input.amount + 1"}}).message + assert "是或否" in refused(spec, {"op": "bp_set", "path": "/writeback/confirm", "value": "yes"}).message + assert apply_bp_op(spec, {"op": "bp_remove", "path": "/writeback"}, source="user")["writeback"] is None + + +def test_access_is_for_people_and_asks_go_one_way(): + spec = empty_blueprint() + e = refused(spec, {"op": "bp_add", "path": "/access/use", "value": {"kind": "group", "name": "门店"}}) + assert "授权是人的决定" in e.message + spec = apply_bp_op(spec, {"op": "bp_add", "path": "/access/use", "value": {"kind": "group", "name": "门店"}}, + source="user") + assert spec["access"]["use"] == [{"kind": "group", "name": "门店"}] + assert "已经在这一档" in refused(spec, {"op": "bp_add", "path": "/access/use", + "value": {"kind": "group", "name": "门店"}}, source="user").message + assert "人或组" in refused(spec, {"op": "bp_add", "path": "/access/observe", + "value": {"kind": "slot", "name": "财务"}}, source="user").message + spec = apply_bp_op(spec, {"op": "bp_ask", "question": "销售额按下单日还是支付日算?", "options": ["按下单日", "按支付日"], + "path": "/data/0/date"}, source="assistant") + assert spec["asks"][0] == {"id": "q1", "question": "销售额按下单日还是支付日算?", "options": ["按下单日", "按支付日"], + "path": "/data/0/date", "answer": None} + assert "直接回答" in refused(spec, {"op": "bp_ask", "question": "?"}, source="user").message + assert "由你来回答" in refused(spec, {"op": "bp_set", "path": "/asks/0/answer", "value": "按支付日"}).message + spec = apply_bp_op(spec, {"op": "bp_set", "path": "/asks/0/answer", "value": "按支付日"}, source="user") + assert spec["asks"][0]["answer"] == "按支付日" + assert "bp_template" in refused(spec, {"op": "bp_set", "path": "/template", "value": {}}).message + assert "路径" in refused(spec, {"op": "bp_set", "path": "purpose", "value": "x"}).message + assert "只能用这几种操作" in refused(spec, {"op": "add_node"}).message + + +def test_blueprint_issues(): + assert [i["code"] for i in blueprint_issues(empty_blueprint(), for_="trial")] == ["bp.missing"] + spec = board() + codes = {(i["code"], i["path"]) for i in blueprint_issues(spec, for_="trial")} + assert ("bp.missing", "/purpose") in codes and ("bp.missing", "/data") in codes + spec = apply_bp_op(spec, {"op": "bp_set", "path": "/purpose", "value": "看销售"}, source="assistant") + spec = apply_bp_op(spec, {"op": "bp_add", "path": "/data", "value": {"id": "gmv", "label": "销售额"}}, + source="assistant") + trial = blueprint_issues(spec, for_="trial") + assert [(i["code"], i["path"]) for i in trial] == [("bp.data_unmapped", "/data/0/table")] + # 发布:助手和模板提的、还没确认的都要确认 + publish = {(i["code"], i["path"]) for i in blueprint_issues(spec, for_="publish")} + assert {("bp.unconfirmed", "/purpose"), ("bp.unconfirmed", "/cadence"), ("bp.unconfirmed", "/data/0/label")} <= publish + # 模板用不到的卡片:照实说不会生效 + spec = apply_bp_op(spec, {"op": "bp_add", "path": "/people", "value": {"id": "s1", "label": "审批"}}, source="user") + assert ("bp.template_mismatch", "/people") in {(i["code"], i["path"]) for i in blueprint_issues(spec, for_="trial")} + # 审批:处理人没定,试运行只提醒(派给试运行的人自己),发布要挡 + approval = apply_bp_op(empty_blueprint(), {"op": "bp_template", "template": {"id": "approval", "version": 1}}, + source="user") + trial = {i["code"]: i["level"] for i in blueprint_issues(approval, for_="trial") if i["code"] == "bp.people_unbound"} + publish = {i["code"]: i["level"] for i in blueprint_issues(approval, for_="publish") if i["code"] == "bp.people_unbound"} + assert trial == {"bp.people_unbound": "warning"} and publish == {"bp.people_unbound": "error"} + # 个人应用:模板不支持、或者有审批步骤的都不行 + personal = {i["code"] for i in blueprint_issues(approval, for_="personal")} + assert "bp.template_mismatch" in personal diff --git a/backend/tests/test_blueprint_starts.py b/backend/tests/test_blueprint_starts.py new file mode 100644 index 00000000..2ce0994f --- /dev/null +++ b/backend/tests/test_blueprint_starts.py @@ -0,0 +1,242 @@ +"""蓝图的四个起点和权限(docs/design/normal-user-apps.md N1、§3.10,包 B2 的 api/blueprints.py)。 + +- conversation:空蓝图,另建一段蓝图对话(kind=blueprint); +- template:按模板预置卡片(选模板走 bp_template);不认识的模板 422; +- run:问数据的一轮回答,按「提取成工作流」同一个规则取出执行路径(api/copilot.extract_run_path),不建工作流,模板记 + 「自由形」,问题记成「目的」的提议;没成功结束的运行 409;/copilot/from-run 照旧能提取成工作流; +- workflow_version:已发布的版本原样导入,蓝图挂在那个工作流上;没发布过的 409; +- 权限:开了登录,使用者不能建共享蓝图;开关关着不能建个人蓝图;开着能建,别人看不到(404)。 +""" +from __future__ import annotations + +import uuid + +import pytest +from httpx import ASGITransport, AsyncClient +from sqlalchemy import func, select + +from app.db.base import SessionLocal +from app.db.models import Conversation, Setting, Workflow +from app.engine.runner import run_manager +from app.main import app +from tests import blueprint_samples as s +from tests.fakes import auth_env + + +@pytest.fixture(autouse=True) +async def engine_up(): + await run_manager.setup() + yield + await run_manager.shutdown() + + +@pytest.fixture +async def client(): + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c: + yield c + + +async def _succeeded_run(graph: dict, inputs: dict, *, actor: str = "analyst") -> str: + run = await run_manager.start(graph=graph, input_payload=inputs, started_by=actor, run_class="exploratory", + origin_kind="chat") + row = await s.wait(run.id) + assert row.status == "succeeded", row.error + return run.id + + +async def _workflows() -> int: + async with SessionLocal() as session: + return int(await session.scalar(select(func.count(Workflow.id))) or 0) + + +async def test_conversation_start_opens_an_empty_blueprint_with_its_own_conversation(client): + r = await client.post("/api/blueprints", json={"source": {"kind": "conversation"}, "scope": "shared", + "name": "门店周报"}) + assert r.status_code == 201, r.text + bp = r.json() + assert bp["scope"] == "shared" and bp["status"] == "drafting" and bp["name"] == "门店周报" + assert bp["spec"]["format"] == "agentlab.blueprint/1" and bp["spec"]["template"] is None + assert bp["source"] == {"kind": "conversation"} and bp["graph_hash"] is None + async with SessionLocal() as session: + conv = await session.get(Conversation, bp["conversation_id"]) + assert conv is not None and conv.kind == "blueprint" and "门店周报" in conv.title + # 还没选场景:蓝图检查照实说,带白话 + missing = [i for i in bp["issues"] if i["code"] == "bp.missing" and i["path"] == "/template"] + assert missing and missing[0]["level"] == "error" + + r = await client.get(f"/api/blueprints/{bp['id']}") + assert r.status_code == 200 and r.json()["id"] == bp["id"] + assert bp["id"] in {b["id"] for b in (await client.get("/api/blueprints")).json()["items"]} + + +async def test_template_start_presets_the_cards(client): + r = await client.post("/api/blueprints", json={"source": {"kind": "template", "id": "periodic_board"}, + "scope": "shared"}) + assert r.status_code == 201, r.text + bp = r.json() + assert bp["spec"]["template"] == {"id": "periodic_board", "version": 1} + assert bp["template_id"] == "periodic_board" and bp["template_version"] == 1 + assert bp["source"] == {"kind": "template", "id": "periodic_board"} + # 周期看板预置了「多久更新」:模板默认、待确认 + assert bp["spec"]["cadence"]["source"] == "template" and bp["spec"]["cadence"]["value"]["preset"] == "weekly" + + r = await client.post("/api/blueprints", json={"source": {"kind": "template"}, "template": "no_such", + "scope": "shared"}) + assert r.status_code == 422 and r.json()["code"] == "blueprint_source_invalid" + + +async def test_run_start_extracts_the_path_without_making_a_workflow(client, tmp_path): + source = await s.register_source(s.make_source(tmp_path)) + run_id = await _succeeded_run(s.board_graph(source), {**s.PERIOD, "question": "上周销售额多少"}) + before = await _workflows() + r = await client.post("/api/blueprints", json={"source": {"kind": "run", "id": run_id}, "scope": "shared"}) + assert r.status_code == 201, r.text + bp = r.json() + assert bp["spec"]["template"] == {"id": "freeform", "version": 1} and bp["source"] == {"kind": "run", "id": run_id} + assert bp["spec"]["purpose"]["value"] == "上周销售额多少" and bp["spec"]["purpose"]["status"] == "proposed" + assert bp["graph_hash"] and bp["workflow_id"] is None + # 图存在蓝图上,不建工作流(发布单保存版本时才建) + assert await _workflows() == before + row = await s.blueprint(bp["id"]) + assert {n["id"] for n in row.graph["nodes"]} == {"start", "q", "caliber", "done"} + # 输入参数化:这次运行的输入变成入口字段的默认值(同 /copilot/from-run) + fields = next(n for n in row.graph["nodes"] if n["id"] == "start")["data"]["config"]["fields"] + assert {"name": "period_start", "default": s.PERIOD["period_start"]} in fields + + # 「提取成工作流」走的是同一个提取规则,照旧建工作流 + r = await client.post("/api/copilot/from-run", json={"run_id": run_id, "name": "提取"}) + assert r.status_code == 200, r.text + assert r.json()["nodes"] == 4 and await _workflows() == before + 1 + + # 没成功结束的运行提取不了 + failed = await run_manager.start(graph=s.chain(s.node("x", "tool", tool="no_such_tool")), input_payload={}, + started_by="analyst", run_class="exploratory", origin_kind="chat") + await s.wait(failed.id) + r = await client.post("/api/blueprints", json={"source": {"kind": "run", "id": failed.id}, "scope": "shared"}) + assert r.status_code in (400, 409) and "提取" in r.json()["detail"] + + +async def test_workflow_version_start_imports_the_published_graph(client, tmp_path): + from app.core.artifact_store import graph_hash + + source = await s.register_source(s.make_source(tmp_path)) + graph = s.board_graph(source) + wf_id = await s.published_workflow(graph, f"周报-{uuid.uuid4().hex[:4]}", description="每周看上周销售额") + r = await client.post("/api/blueprints", json={"source": {"kind": "workflow_version", "id": wf_id, "version": 1}, + "scope": "shared"}) + assert r.status_code == 201, r.text + bp = r.json() + assert bp["workflow_id"] == wf_id and bp["graph_hash"] == graph_hash(graph) + assert bp["source"] == {"kind": "workflow_version", "id": wf_id, "version": 1} + assert bp["spec"]["template"]["id"] == "freeform" and bp["spec"]["purpose"]["value"] == "每周看上周销售额" + + # 没发布过的版本不能当起点 + async with SessionLocal() as session: + from app.db.models import WorkflowVersion + + wf = await session.get(Workflow, wf_id) + wf.version = 2 + session.add(WorkflowVersion(workflow_id=wf_id, version=2, graph=graph, graph_hash=graph_hash(graph))) + await session.commit() + r = await client.post("/api/blueprints", json={"source": {"kind": "workflow_version", "id": wf_id, "version": 2}, + "scope": "shared"}) + assert r.status_code == 409 and r.json()["code"] == "blueprint_source_invalid" + + +@pytest.fixture +async def login(): + await auth_env.reset() + try: + yield + finally: + await auth_env.reset() + async with SessionLocal() as session: + row = await session.get(Setting, "apps") + if row is not None: + await session.delete(row) + await session.commit() + + +async def _switch(on: bool) -> None: + async with SessionLocal() as session: + row = await session.get(Setting, "apps") + if row is None: + session.add(Setting(key="apps", value={"user_personal_apps": on})) + else: + row.value = {**(row.value or {}), "user_personal_apps": on} + await session.commit() + + +async def test_who_can_start_what(login): + await auth_env.turn_on_local() + u = uuid.uuid4().hex[:6] + await auth_env.make_user(f"lee{u}", "user") + await auth_env.make_user(f"ma{u}", "user") + await auth_env.make_user(f"zhao{u}", "builder") + user = await auth_env.login(f"lee{u}") + conversation = {"source": {"kind": "conversation"}} + + # 使用者不能建共享蓝图;开关关着也不能建个人蓝图 + r = await user.post("/api/blueprints", json={**conversation, "scope": "shared"}) + assert r.status_code == 403 + r = await user.post("/api/blueprints", json={**conversation, "scope": "personal"}) + assert r.status_code == 403 and r.json()["code"] == "personal.off" + + # 开关开着:使用者能建个人蓝图,拥有者是他自己;别人当它不存在 + await _switch(True) + r = await user.post("/api/blueprints", json={**conversation, "scope": "personal"}) + assert r.status_code == 201, r.text + mine = r.json() + assert mine["owner"] == f"lee{u}" and mine["scope"] == "personal" + assert (await user.get(f"/api/blueprints/{mine['id']}")).status_code == 200 + other = await auth_env.login(f"ma{u}") + assert (await other.get(f"/api/blueprints/{mine['id']}")).status_code == 404 + assert mine["id"] not in {b["id"] for b in (await other.get("/api/blueprints")).json()["items"]} + # 使用者不能从已发布的工作流开始(工作流是搭建者的东西) + r = await user.post("/api/blueprints", json={"source": {"kind": "workflow_version", "id": "x"}, + "scope": "personal"}) + assert r.status_code == 403 + + # 搭建者能建共享蓝图,看得到共享蓝图,看不到别人的个人蓝图 + builder = await auth_env.login(f"zhao{u}") + r = await builder.post("/api/blueprints", json={**conversation, "scope": "shared"}) + assert r.status_code == 201, r.text + listed = {b["id"] for b in (await builder.get("/api/blueprints")).json()["items"]} + assert r.json()["id"] in listed and mine["id"] not in listed + # 使用者看不到共享蓝图 + assert (await user.get(f"/api/blueprints/{r.json()['id']}")).status_code == 403 + + +async def test_patch_applies_card_ops_as_the_user(client): + bp = (await client.post("/api/blueprints", json={"source": {"kind": "template", "id": "periodic_board"}, + "scope": "shared"})).json() + r = await client.patch(f"/api/blueprints/{bp['id']}", json={ + "name": "门店周报", "ops": [{"op": "bp_set", "path": "/purpose", "value": "每周一看上周各门店的销售额"}]}) + assert r.status_code == 200, r.text + out = r.json() + assert out["name"] == "门店周报" + assert out["spec"]["purpose"] == {"value": "每周一看上周各门店的销售额", "source": "user", "status": "confirmed", + "why": None} + # 越界的操作整批不落,照实说 + r = await client.patch(f"/api/blueprints/{bp['id']}", json={ + "ops": [{"op": "bp_set", "path": "/purpose", "value": "改了"}, {"op": "bp_set", "path": "/nope", "value": 1}]}) + assert r.status_code == 422 and r.json()["code"].startswith("bp.") + assert (await client.get(f"/api/blueprints/{bp['id']}")).json()["spec"]["purpose"]["value"] == "每周一看上周各门店的销售额" + + +async def test_renaming_a_blueprint_leaves_a_trace(client): + """改名也留痕(P2):名字进工作流、应用的名字和口径卡的标题,谁什么时候从什么改成什么都记下;名字没变不记。""" + from app.db.models_blueprints import BlueprintEvent + + bp = (await client.post("/api/blueprints", json={"source": {"kind": "template", "id": "periodic_board"}, + "scope": "shared", "name": "门店周报"})).json() + who = {"X-Actor": "builder1"} + r = await client.patch(f"/api/blueprints/{bp['id']}", json={"name": "门店周报(新)"}, headers=who) + assert r.status_code == 200 and r.json()["name"] == "门店周报(新)" + assert (await client.patch(f"/api/blueprints/{bp['id']}", json={"name": "门店周报(新)"}, + headers=who)).status_code == 200 + async with SessionLocal() as session: + events = list((await session.execute(select(BlueprintEvent).where( + BlueprintEvent.blueprint_id == bp["id"], BlueprintEvent.op == "rename"))).scalars()) + assert len(events) == 1 and (events[0].data["before"], events[0].data["after"]) == ("门店周报", "门店周报(新)") + assert events[0].actor == "builder1" diff --git a/backend/tests/test_blueprint_template_run.py b/backend/tests/test_blueprint_template_run.py new file mode 100644 index 00000000..ccd2a6ad --- /dev/null +++ b/backend/tests/test_blueprint_template_run.py @@ -0,0 +1,73 @@ +"""场景模板实例化出来的图真的能运行(docs/design/normal-user-apps.md §3.3「实例化 + 检查 + 运行」):周期看板按示例蓝图 +实例化、生成关节填上之后,在一个小库上跑一次,口径卡用 cell() 取到格,成果按指标完整出具。库和数字都是编的。 +""" +from __future__ import annotations + +import asyncio +import sqlite3 +import uuid + +import pytest + +from app.blueprints.instantiate import instantiate +from app.blueprints.templates import _common as c +from app.data.engine import engines +from app.db.base import SessionLocal +from app.db.models import DataSource, Run +from app.engine.runner import run_manager + + +@pytest.fixture(autouse=True) +async def engine_up(): + await run_manager.setup() + yield + await run_manager.shutdown() + + +@pytest.fixture +async def shop(tmp_path): + path = tmp_path / "shop.db" + with sqlite3.connect(path) as db: + db.executescript("CREATE TABLE orders (id INTEGER PRIMARY KEY, amount REAL, paid_at TEXT, refunded INTEGER);") + db.executemany("INSERT INTO orders VALUES (?, ?, ?, ?)", [ + (1, 100.0, "2026-10-05", 0), (2, 300.0, "2026-10-08", 1), (3, 600.0, "2026-10-11", 0), + (4, 999.0, "2026-10-12", 0)]) # 统计期外 + name = f"bprun_{uuid.uuid4().hex[:6]}" + async with SessionLocal() as session: + row = DataSource(name=name, kind="sqlite", database=str(path), readonly=True, enabled=True) + session.add(row) + await session.commit() + source_id = row.id + yield name + async with SessionLocal() as session: + await session.delete(await session.get(DataSource, source_id)) + await session.commit() + await engines.invalidate(source_id) + + +async def test_the_board_template_runs_and_issues_by_metrics(shop): + from app.blueprints.templates._common import safe_id + + extras = c.EXTRAS["periodic_board"] + spec = extras.example() + for item in spec["data"]: + item["table"]["value"]["source"] = shop + node = f"fetch_{safe_id(shop)}" + fill = {k.replace("fetch_shop", node): v.replace("fetch_shop", node) for k, v in extras.example_fill().items()} + inst = instantiate(spec, filled=fill) + assert inst.problems == [] + run = await run_manager.start(graph=inst.graph, input_payload={ + "period": "2026-W41", "period_start": "2026-10-05", "period_end": "2026-10-11"}) + for _ in range(400): + await asyncio.sleep(0.05) + async with SessionLocal() as session: + row = await session.get(Run, run.id) + if row.status in ("succeeded", "failed") and row.manifest_seq is not None: + break + assert row.status == "succeeded", row.error + output = row.output or {} + issuance = output["_issuance"] + assert (issuance["tier"], issuance["mode"]) == ("formal", "metrics"), issuance + # 销售额不含已退款的那一单;订单数、退款率按全部订单 + assert output["销售额(元)"] == "700.0" and output["订单数(单)"] == "3" + assert output["退款率(%)"] == "33.33" diff --git a/backend/tests/test_blueprint_templates.py b/backend/tests/test_blueprint_templates.py new file mode 100644 index 00000000..5fb69a71 --- /dev/null +++ b/backend/tests/test_blueprint_templates.py @@ -0,0 +1,252 @@ +"""场景模板与实例化(docs/design/normal-user-apps.md N3、§3.3、§3.4)。 + +每个模板用一张完整的示例蓝图实例化: +- 生成关节没填时:画布校验(engine/schema.validate_graph)过得了,关节标「待填」,问题里是 tpl.joint_unfilled(P3); +- 骨架比对没有差异;生成关节都填上之后,发布前检查(governance.publish_issues,已发布级)没有 error; +- 应用草稿合 agentlab.app/1 的形状,固定版本还没有版本号;定时任务、岗位绑定按卡片来。 + +另外守:骨架比对认得出关节以外的改动;卡片改了,那一组生成关节的依据变了,之前填的就不算数;模板登记齐全。 +""" +from __future__ import annotations + +import copy + +import pytest + +from app.blueprints.instantiate import filled_from, generated_groups, instantiate, registry_problems, skeleton_changes +from app.blueprints.templates import GENERATED_JOINT_KINDS, TEMPLATE_IDS, get_template +from app.blueprints.templates import _common as c +from app.engine.governance import publish_issues +from app.engine.schema import GraphSpec, validate_graph + + +def _graph_for(template_id: str): + if c.EXTRAS[template_id].imports_graph: + from app.blueprints.templates.freeform import example_graph + + return example_graph() + return None + + +def test_registry_is_complete(): + assert registry_problems() == [] + assert all(get_template(t) is not None for t in TEMPLATE_IDS) + for t in TEMPLATE_IDS: + template = get_template(t) + assert template.applies_when and template.cards and template.skeleton + assert all(note.startswith(("必填", "可选")) for note in template.cards.values()), t + + +@pytest.mark.parametrize("template_id", TEMPLATE_IDS) +def test_every_template_instantiates_validates_and_publishes(template_id): + extras = c.EXTRAS[template_id] + example = extras.example() + graph = _graph_for(template_id) + + pending = instantiate(example, graph=graph, workflow_id="wf_1", schedule_id="sch_1") + assert not [i for i in validate_graph(GraphSpec.model_validate(pending.graph)).issues if i.level == "error"] + generated = [j for j in pending.joint_defs if j.kind in GENERATED_JOINT_KINDS] + assert {p["joint"] for p in pending.problems if p["code"] == "tpl.joint_unfilled"} == {j.id for j in generated} + assert all(pending.joints[j.id]["status"] == "pending" for j in generated) + assert skeleton_changes(pending.skeleton, pending.graph, pending.joint_defs) == [] + + full = instantiate(example, filled=extras.example_fill(), graph=graph, workflow_id="wf_1", schedule_id="sch_1") + assert full.problems == [], full.problems + assert all(state["status"] == "filled" for state in full.joints.values()) + assert set(extras.example_fill()) == {j.id for j in generated}, "示例把每个生成关节都填上了" + assert skeleton_changes(full.skeleton, full.graph, full.joint_defs) == [] + errors = [(i.code, i.message) for i in publish_issues(GraphSpec.model_validate(full.graph), level="published") + if i.level == "error"] + assert errors == [] + # 应用草稿:固定在这个工作流上,还没有版本号(发布单发布工作流之后换成那一版) + pin = full.app_spec["pins"][0] + assert pin["workflow_id"] == "wf_1" and pin["version"] is None + from app.core.artifact_store import graph_hash + + assert pin["graph_hash"] == graph_hash(full.graph) + assert full.app_spec["pages"] and full.app_spec["pages"][0]["id"] == "home" + # 同一张蓝图实例化两次,图一模一样(图哈希、试运行对齐都靠它) + assert instantiate(example, filled=extras.example_fill(), graph=graph, workflow_id="wf_1", + schedule_id="sch_1").graph == full.graph + + +def test_board_details(): + extras = c.EXTRAS["periodic_board"] + inst = instantiate(extras.example(), filled=extras.example_fill(), schedule_id="sch_1", blueprint_id="bp_1") + nodes = {n["id"]: n for n in inst.graph["nodes"]} + assert nodes["fetch_shop"]["data"]["config"]["tool"] == "db_query__shop" + contract = nodes["done"]["data"]["config"]["contract"] + assert contract == {"metrics_from": ["caliber"], "required": ["gmv", "orders", "refund_rate"], "strict": True} + from app.engine.governance import board_only + + assert board_only(contract, GraphSpec.model_validate(inst.graph), "done"), "按指标出具" + assert inst.schedule["cron"] == "0 9 * * 1" and inst.schedule["enabled"] is False + assert inst.schedule["input_template"]["period_start"] == "{{ schedule.last_week_start }}" + # 没有工作流时固定在蓝图上;首页看定时任务出的数,按条件查看是按需视图 + assert inst.app_spec["pins"][0]["blueprint"] == "bp_1" + assert inst.app_spec["views"]["latest"]["source"] == {"kind": "latest_sealed", "pin": "main", "from": "schedule:sch_1", + "params": None, "ttl_s": None, "auto": False} + assert inst.app_spec["views"]["custom"]["source"]["kind"] == "on_demand" + home = [comp["type"] for comp in inst.app_spec["pages"][0]["body"]] + assert home[0] == "stamp" and "section" in home and "table" in home + groups = generated_groups(inst) + assert list(groups) == ["fetch_shop"] + assert "'{{ input.period_start }}'" in inst.briefs["fetch_shop"] and "销售额" in inst.briefs["fetch_shop"] + + +def test_board_with_reused_caliber_and_two_sources(): + spec = c.EXTRAS["periodic_board"].example() + spec["data"].append({"id": "visits", "label": {"value": "访客数", "source": "user", "status": "confirmed", "why": None}, + "unit": {"value": "人", "source": "user", "status": "confirmed", "why": None}, + "table": {"value": {"source": "crm", "table": "visits"}, "source": "user", + "status": "confirmed", "why": None}, + "measure": {"value": "count(distinct uid)", "source": "user", "status": "confirmed", "why": None}, + "date": {"value": None, "source": "user", "status": "missing", "why": None}, + "filter": {"value": None, "source": "user", "status": "missing", "why": None}, + "grain": {"value": None, "source": "user", "status": "missing", "why": None}, "reuse": None}) + spec["data"].append({**copy.deepcopy(spec["data"][0]), "id": "aov", "table": { + "value": None, "source": "user", "status": "missing", "why": None}, + "reuse": {"workflow_id": "wf_old", "version": 2, "node_id": "kpi", "metric_id": "aov", + "inputs": [{"node": "fetch", "tool": "db_query__shop", "columns": ["gmv", "order_cnt"]}]}}) + inst = instantiate(spec) + groups = generated_groups(inst) + # 复用的口径卡读原工作流的 fetch:新图里 shop 的取数节点就叫 fetch,本地算 shop 上的数也在这一组 + assert sorted(groups) == ["fetch", "fetch_crm"] + assert {j.id for j in groups["fetch"]} == {"sql_fetch", "metric_gmv", "metric_orders", "metric_refund_rate"} + nodes = {n["id"]: n for n in inst.graph["nodes"]} + assert nodes["reuse_aov"]["data"]["config"]["caliber_from"] == {"workflow_id": "wf_old", "workflow_version": 2, + "node_id": "kpi"} + assert "aov" in nodes["done"]["data"]["config"]["contract"]["required"] + assert "gmv、order_cnt" in inst.briefs["fetch"] + assert any(comp["id"] == "home_reused" for comp in inst.app_spec["pages"][0]["body"]) + # 复用的口径卡没核对过读哪些列:照实说对不上 + spec["data"][-1]["reuse"].pop("inputs") + assert any(p["code"] == "bp.data_unmapped" for p in instantiate(spec).problems) + + +def test_approval_details(): + inst = instantiate(c.EXTRAS["approval"].example()) + nodes = {n["id"]: n for n in inst.graph["nodes"]} + finance = nodes["review_finance"]["data"]["config"] + assert finance["assignee"] == {"kind": "slot", "slot": "finance"} and finance["policy"] == "all" + assert finance["due"] == "PT48H" and finance["on_timeout"] == {"action": "escalate", "to_slot": "finance_up"} + assert nodes["gate_finance"]["data"]["config"]["cases"][0]["condition"] == "input.amount > 5000" + edges = {(e["source"], e["target"], e.get("sourceHandle")) for e in inst.graph["edges"]} + # 金额线以下的直接跳过财务会签 + assert ("gate_finance", "approved", "default") in edges and ("gate_finance", "review_finance", "hit") in edges + assert ("review_lead", "rejected", "rejected") in edges + assert inst.bindings == {"slots": {"lead": [{"kind": "user", "name": "zhang"}], + "finance": [{"kind": "group", "name": "财务组"}], + "finance_up": [{"kind": "user", "name": "director"}]}} + assert set(inst.app_spec["slots"]) == {"lead", "finance", "finance_up"} + assert inst.app_spec["forms"]["start"]["required"] == ["amount", "reason"] + assert inst.app_spec["entries"][0]["map"] == {"amount": "form.amount", "reason": "form.reason"} + assert inst.schedule is None + # 确定性关节按卡片换:改了金额线,分支跟着变;骨架比对只许关节位置不同 + other = c.EXTRAS["approval"].example() + other["people"][1]["threshold"]["value"]["value"] = 8000 + changed = instantiate(other) + assert {n["id"]: n for n in changed.graph["nodes"]}["gate_finance"]["data"]["config"]["cases"][0]["condition"] \ + == "input.amount > 8000" + + +def test_approval_writeback_confirms_with_last_step(monkeypatch): + spec = c.EXTRAS["approval"].example() + item = c.template_item + spec["writeback"] = {"capability": item("erp_reimburse"), "mapping": item({"amount": "form.amount", "kind": "'报销'"}), + "confirm": item(True)} + inst = instantiate(spec) + write = {n["id"]: n for n in inst.graph["nodes"]}["writeback"]["data"]["config"] + assert write == {"tool": "erp_reimburse", "args": {"amount": "{{ input.amount }}", "kind": "报销"}, + "approval": "always", "assignee": {"kind": "slot", "slot": "finance"}} + edges = {(e["source"], e["target"], e.get("sourceHandle")) for e in inst.graph["edges"]} + assert ("review_finance", "writeback", "approved") in edges and ("writeback", "approved", None) in edges + # 写入能力没登记查询:要有人核实结果未知的写入 + assert "reconciler" in inst.app_spec["slots"] + spec["writeback"]["mapping"] = item({"amount": "metric.total"}) + assert any(p["code"] == "bp.template_mismatch" for p in instantiate(spec).problems) + + +def test_records_routes_submit_and_summary(): + from app.records import RECORDS_APPEND + + extras = c.EXTRAS["records"] + inst = instantiate(extras.example(), records={"table": "loss", "source": "records_loss"}, blueprint_id="bp_9") + nodes = {n["id"]: n for n in inst.graph["nodes"]} + append = nodes["append"]["data"]["config"] + assert append["tool"] == RECORDS_APPEND and append["approval"] == "never" + assert append["args"] == {"table": "loss", "values": {"store": "{{ input.store }}", "amount": "{{ input.amount }}", + "reason": "{{ input.reason }}"}} + assert nodes["summary_records_loss"]["data"]["config"]["tool"] == "db_query__records_loss" + # 入口节点上表单字段都不是必填(汇总那条路不带表单),必填由应用的入口表单把关 + fields = {f["name"]: f for f in nodes["start"]["data"]["config"]["fields"]} + assert not any(f.get("required") for f in fields.values()) + assert inst.app_spec["forms"]["start"]["required"] == ["store", "amount"] + assert inst.app_spec["entries"][0]["map"]["mode"] == "'submit'" + assert inst.schedule["input_template"]["mode"] == "summary" + assert inst.app_spec["pages"][0]["body"][0]["type"] == "records_list" + # 汇总看板不放逐行表格(会把每个人的记录列给所有人) + assert "table" not in [comp["type"] for comp in inst.app_spec["pages"][0]["body"]] + + +def test_exception_and_reconcile_details(): + inst = instantiate(c.EXTRAS["exception_handling"].example()) + nodes = {n["id"]: n for n in inst.graph["nodes"]} + assert nodes["handle"]["data"]["config"]["mode"] == "input" + assert nodes["handle"]["data"]["config"]["assignee"] == {"kind": "slot", "slot": "owner"} + assert nodes["review"]["data"]["config"]["assignee"] == {"kind": "slot", "slot": "区域经理"} + assert nodes["gate"]["data"]["config"]["cases"][0]["condition"] == "nodes.parse.row_count > 0" + # 只看清单(个人应用能用的那一部分):没有人工节点 + spec = c.EXTRAS["exception_handling"].example() + spec["people"] = [] + assert not [n for n in instantiate(spec).graph["nodes"] if n["type"] == "human"] + + inst = instantiate(c.EXTRAS["reconcile_writeback"].example()) + write = {n["id"]: n for n in inst.graph["nodes"]}["writeback"]["data"]["config"] + assert write["args"] == {"items": "{{ nodes.parse.rows | compact }}", "total": "{{ nodes.caliber.metrics[1].value }}"} + assert write["assignee"] == {"kind": "slot", "slot": "check"} + assert [j.id for j in generated_groups(inst)["fetch_shop"]] == \ + ["sql_fetch_shop", "metric_diff_count", "metric_diff_amount", "sql_detail"] + + +def test_skeleton_changes_catch_anything_but_joints(): + extras = c.EXTRAS["periodic_board"] + inst = instantiate(extras.example(), filled=extras.example_fill()) + joints = inst.joint_defs + graph = copy.deepcopy(inst.graph) + nodes = {n["id"]: n for n in graph["nodes"]} + nodes["fetch_shop"]["data"]["config"]["args"]["sql"] = "SELECT 1 AS gmv" # 关节位置:不算 + assert skeleton_changes(inst.skeleton, graph, joints) == [] + nodes["fetch_shop"]["data"]["config"]["tool"] = "db_query__other" + nodes["done"]["data"]["config"]["contract"]["strict"] = False # 出具契约是确定性关节:模型改了也算越界 + graph["nodes"].append(c.node("extra", "llm", "多出来的")) + graph["edges"] = [e for e in graph["edges"] if e["target"] != "done"] + messages = [p["message"] for p in skeleton_changes(inst.skeleton, graph, joints)] + assert any("tool" in m for m in messages) and any("多出了节点" in m for m in messages) + assert any("删除了连线" in m for m in messages) + assert all(p["code"] == "tpl.skeleton_changed" for p in skeleton_changes(inst.skeleton, graph, joints)) + + +def test_filled_values_go_stale_when_the_cards_change(): + extras = c.EXTRAS["periodic_board"] + spec = extras.example() + inst = instantiate(spec, filled=extras.example_fill()) + joints = inst.joints + assert filled_from(spec, joints) == extras.example_fill() + # 改了「怎么算」:这一组的说明变了,之前填的 SQL 和指标式都不算数 + spec["data"][0]["measure"]["value"] = "sum(amount) - sum(refund)" + assert filled_from(spec, joints) == {} + # 只改目的:说明没变,照旧算数 + spec = extras.example() + spec["purpose"]["value"] = "换个说法" + assert filled_from(spec, joints) == extras.example_fill() + + +def test_trial_inputs_follow_the_cadence(): + from datetime import datetime, timezone + + from app.blueprints.instantiate import trial_inputs + + inputs = trial_inputs(c.EXTRAS["periodic_board"].example(), at=datetime(2026, 10, 15, 3, tzinfo=timezone.utc)) + assert inputs == {"period": "2026-W41", "period_start": "2026-10-05", "period_end": "2026-10-11"} + assert trial_inputs(c.EXTRAS["approval"].example()) == {} diff --git a/backend/tests/test_blueprint_trial.py b/backend/tests/test_blueprint_trial.py new file mode 100644 index 00000000..1b08217a --- /dev/null +++ b/backend/tests/test_blueprint_trial.py @@ -0,0 +1,350 @@ +"""用真数试运行(docs/design/normal-user-apps.md N4、§3.5,包 B2 的 blueprints/trial.py 和 apps/resolve.py 的 trial 旁路)。 + +- 试运行是探索运行,来源记 trial(origin 里是蓝图 id),蓝图记下这次运行;成功结束后蓝图记「试运行过」; +- 预览:草稿应用对着这次运行解析——视图来源一律是这次运行(kind=trial),印章的来源写「试运行」、trial=true、说明里写 + 「这不是正式结果」;入口按钮点不了、说清为什么; +- 趋势在试运行里只有一个点:照实写「没有趋势」,不报错;按草稿预览一个还没有版本号的钉住项,趋势也不报错; +- 流程类:人工步骤派给试运行的人自己(来源 trial),会签、升级的岗位都不派;到了时限调度也不升级;预览里待办写明是 + 试运行,试运行的人能处理、同意之后流程走完; +- 缺项挡试运行:409,带问题和白话; +- 从一张图派生(apps/derive.derive_from_graph):钉住项没有版本号、哈希是这张图的。 +""" +from __future__ import annotations + +import uuid +from datetime import timedelta + +import pytest +from httpx import ASGITransport, AsyncClient +from sqlalchemy import select + +from app.api.deps import Principal +from app.apps.resolve import TRIAL_FROM, TRIAL_NOTE, TRIAL_SERIES, UNPUBLISHED_EMPTY +from app.core.artifact_store import graph_hash +from app.db.base import SessionLocal, utcnow +from app.db.models import Run, Task, TaskAssignment +from app.engine.runner import run_manager +from app.main import app +from tests import blueprint_samples as s + +ACTOR = {"X-Actor": "tester"} + + +@pytest.fixture(autouse=True) +async def engine_up(): + await run_manager.setup() + yield + await run_manager.shutdown() + + +@pytest.fixture +async def client(): + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test", headers=ACTOR) as c: + yield c + + +def walk(tree): + for n in tree: + yield n + yield from walk(n.get("children") or []) + + +def find(vm, ctype): + return [n for n in walk(vm["tree"]) if n["type"] == ctype] + + +async def _board_blueprint(client, tmp_path) -> dict: + source = await s.register_source(s.make_source(tmp_path)) + wf_id = await s.published_workflow(s.board_graph(source), f"周报-{uuid.uuid4().hex[:4]}", + description="每周看上周销售额") + r = await client.post("/api/blueprints", json={"source": {"kind": "workflow_version", "id": wf_id}, + "scope": "shared"}) + assert r.status_code == 201, r.text + bp = r.json() + await s.edit_spec(bp["id"], purpose=s.item("每周看上周销售额"), cadence=s.item(s.WEEKLY)) + return bp + + +async def test_trial_runs_the_unpublished_graph_and_previews_with_a_trial_stamp(client, tmp_path): + bp = await _board_blueprint(client, tmp_path) + r = await client.post(f"/api/blueprints/{bp['id']}/trial", json={"inputs": s.PERIOD}) + assert r.status_code == 200, r.text + run_id = r.json()["run_id"] + assert r.json()["blueprint"]["last_trial_run_id"] == run_id + run = await s.wait(run_id) + assert run.status == "succeeded", run.error + assert run.run_class == "exploratory" and run.origin_kind == "trial" + assert run.origin["blueprint_id"] == bp["id"] and run.started_by == "tester" + # 自由形导入的图原样跑(哈希和导入的那一版一样),名字记蓝图名 + assert graph_hash(run.graph) == bp["graph_hash"] and run.workflow_name == bp["name"] + assert run.input["period_start"] == s.PERIOD["period_start"] + + r = await client.get(f"/api/blueprints/{bp['id']}/preview") + assert r.status_code == 200, r.text + vm = r.json() + assert vm["trial"]["run_id"] == run_id and vm["app"]["needs_upgrade"] is False + assert all(src["kind"] == "trial" and src["run_id"] == run_id for src in vm["sources"].values()) + stamp = find(vm, "stamp")[0]["data"]["stamp"] + assert stamp["from"] == TRIAL_FROM and stamp["trial"] is True and TRIAL_NOTE in stamp["notes"] + assert stamp["pin"] == bp["name"] + metric = find(vm, "metric")[0]["data"] + assert metric["state"] == "ok" and metric["text"] and metric["evidence"]["run_id"] == run_id + assert not vm["problems"] + # 成功结束了:蓝图记「试运行过」 + assert (await client.get(f"/api/blueprints/{bp['id']}")).json()["status"] == "trialed" + + # 不是这个蓝图的试运行不给预览 + other = await run_manager.start(graph=s.chain(s.node("a", "input")), input_payload={}, started_by="x", + run_class="exploratory", origin_kind="canvas") + r = await client.get(f"/api/blueprints/{bp['id']}/preview", params={"run": other.id}) + assert r.status_code == 404 and r.json()["code"] == "trial_no_run" + + +async def test_trial_series_has_one_point_and_a_draft_without_version_does_not_break(tmp_path): + """趋势:试运行只有一个点,写「没有趋势」;按草稿预览没有版本号的钉住项,趋势是空态(以前 int(None) 报错)。""" + from app.apps.resolve import resolve_page + from app.blueprints.trial import PreviewApp + + source = await s.register_source(s.make_source(tmp_path)) + graph = s.board_graph(source) + run = await run_manager.start(graph=graph, input_payload=s.PERIOD, started_by="tester", run_class="exploratory", + origin_kind="trial", origin={"blueprint_id": "bp-x"}) + run = await s.wait(run.id) + spec = {"format": "agentlab.app/1", "name": "周报", + "pins": [{"alias": "main", "blueprint": "bp-x", "version": None, "graph_hash": graph_hash(graph)}], + "views": {"latest": {"source": {"kind": "latest_sealed", "pin": "main", "from": "formal"}}}, + "pages": [{"id": "home", "title": "周报", "body": [ + {"id": "trend", "type": "line_chart", "bind": {"view": "latest", "series": "caliber.gmv"}}, + {"id": "go", "type": "entry_button", "props": {"entry": "start"}}]}]} + principal = Principal(username="tester", role="admin") + preview = PreviewApp(id="bp-x", name="周报", draft=spec) + async with SessionLocal() as session: + vm = await resolve_page(session, preview, page_id="home", principal=principal, role="manage", draft=True, + trial=run) + plain = await resolve_page(session, preview, page_id="home", principal=principal, role="manage", draft=True) + trend = next(n for n in vm["tree"] if n["id"] == "trend")["data"] + assert trend["state"] == "ok" and trend["note"] == TRIAL_SERIES + assert len(trend["series"]) == 1 and len(trend["series"][0]["points"]) == 1 + assert trend["series"][0]["points"][0]["run_id"] == run.id and trend["series"][0]["points"][0]["value"] is not None + button = next(n for n in vm["tree"] if n["id"] == "go")["data"] + assert button["disabled"] is True and "试运行" in button["reason"] + assert not vm["problems"] + # 不是试运行、只是按草稿预览:没有版本号就没有正式运行可看,照实说「还没有发布」,不进 problems + trend = next(n for n in plain["tree"] if n["id"] == "trend")["data"] + assert trend["state"] == "empty" and trend["message"] == UNPUBLISHED_EMPTY + assert not [p for p in plain["problems"] if p["code"] == "view.resolve_failed"] + + +async def test_process_trial_assigns_every_step_to_the_trial_runner_and_never_escalates(client): + from app.process import tasks + + wf_id = await s.published_workflow(s.expense_graph(), f"报销-{uuid.uuid4().hex[:4]}", description="报销审批") + r = await client.post("/api/blueprints", json={"source": {"kind": "workflow_version", "id": wf_id}, + "scope": "shared"}) + bp = r.json() + await s.edit_spec(bp["id"], purpose=s.item("报销审批")) + r = await client.post(f"/api/blueprints/{bp['id']}/trial", json={"inputs": {"applicant": "钱七", "amount": 1280}}) + assert r.status_code == 200, r.text + run_id = r.json()["run_id"] + await s.wait(run_id, ("interrupted",)) + async with SessionLocal() as session: + task = (await session.execute(select(Task).where(Task.run_id == run_id))).scalars().one() + rows = list((await session.execute(select(TaskAssignment).where(TaskAssignment.task_id == task.id))) + .scalars()) + # 图里派给岗位 finance(会签、没有绑定):试运行一律派给发起试运行的人自己 + assert [(a.principal_kind, a.principal, a.source) for a in rows] == [("user", "tester", "trial")] + assert task.due_at is not None and task.on_timeout["action"] == "escalate" + + # 时限到了:调度不升级试运行的待办(同一个库里别的测试的待办照常处理,只看这一条) + await tasks.tick(utcnow() + timedelta(hours=2)) + async with SessionLocal() as session: + task = await session.get(Task, task.id) + count = len(list((await session.execute(select(TaskAssignment).where( + TaskAssignment.task_id == task.id))).scalars())) + assert task.escalation_level == 0 and task.status == "pending" and count == 1 + + # 预览实例页:流程组件对着这次试运行,待办写明是试运行,试运行的人能处理 + r = await client.get(f"/api/blueprints/{bp['id']}/preview", params={"page": "instance"}) + assert r.status_code == 200, r.text + vm = r.json() + form = next(n for n in walk(vm["tree"]) if n["type"] == "task_form")["data"] + assert form["trial"] is True and form["handler"] is True and form["task"]["id"] == task.id + timeline = find(vm, "instance_timeline")[0]["data"] + assert timeline["state"] == "ok" and timeline["status_text"] == "等待审批" + # 首页的「我发起的」列的就是这次试运行 + home = (await client.get(f"/api/blueprints/{bp['id']}/preview", params={"page": "home"})).json() + assert [i["run_id"] for i in find(home, "instance_list")[0]["data"]["items"]] == [run_id] + # 「派给我的待办」列的是这次试运行的待办(试运行的待办不属于任何应用) + from app.apps.resolve import resolve_page + from app.blueprints.trial import PreviewApp + + spec = {"format": "agentlab.app/1", "name": "报销", "pages": [{"id": "home", "title": "报销", "body": [ + {"id": "mine", "type": "task_list", "props": {"scope": "mine"}}]}]} + async with SessionLocal() as session: + run = await session.get(Run, run_id) + vm = await resolve_page(session, PreviewApp(id=bp["id"], name="报销", draft=spec), page_id="home", + principal=Principal(username="tester", role="admin"), role="manage", draft=True, + trial=run) + assert [i["id"] for i in vm["tree"][0]["data"]["items"]] == [task.id] + # 待办箱里同样写明是试运行 + detail = await tasks.detail(task.id, Principal(username="tester", role="admin")) + assert detail["trial"] is True + + # 以试运行身份同意:流程走完 + await tasks.respond(task.id, Principal(username="tester", role="admin"), decision="approve") + run = await s.wait(run_id) + assert run.status == "succeeded" + assert (await client.get(f"/api/blueprints/{bp['id']}")).json()["status"] == "trialed" + + +async def test_missing_cards_block_the_trial_with_plain_reasons(client): + r = await client.post("/api/blueprints", json={"source": {"kind": "conversation"}, "scope": "shared"}) + bp = r.json() + r = await client.post(f"/api/blueprints/{bp['id']}/trial", json={}) + assert r.status_code == 409, r.text + body = r.json() + assert body["code"] == "trial_not_ready" and body["issues"] + first = body["issues"][0] + assert first["code"] == "bp.missing" and first["plain"]["title"] + async with SessionLocal() as session: + trials = (await session.execute(select(Run.origin).where(Run.origin_kind == "trial"))).scalars().all() + assert not [o for o in trials if (o or {}).get("blueprint_id") == bp["id"]] + + +async def test_derive_from_graph_pins_the_graph_hash_without_a_version(tmp_path): + from app.apps.derive import derive_from_graph + + source = await s.register_source(s.make_source(tmp_path)) + graph = s.board_graph(source) + async with SessionLocal() as session: + spec = await derive_from_graph(session, graph, name="周报", blueprint_id="bp-1") + with_wf = await derive_from_graph(session, graph, name="周报", workflow_id="wf-1", schedule_id="sch-1") + pin = spec["pins"][0] + assert pin["version"] is None and pin["graph_hash"] == graph_hash(graph) and pin["blueprint"] == "bp-1" + assert pin["workflow_id"] is None and pin["use"] == "view" + assert spec["views"]["latest"]["source"]["from"] == "formal" + assert any(c["type"] == "stamp" for c in spec["pages"][0]["body"]) + assert with_wf["pins"][0]["workflow_id"] == "wf-1" and with_wf["pins"][0].get("blueprint") is None + assert with_wf["views"]["latest"]["source"]["from"] == "schedule:sch-1" + + +@pytest.fixture +async def login(): + from app.db.models import Setting + from tests.fakes import auth_env + + await auth_env.reset() + async with SessionLocal() as session: + row = await session.get(Setting, "apps") + if row is None: + session.add(Setting(key="apps", value={"user_personal_apps": True})) + else: + row.value = {**(row.value or {}), "user_personal_apps": True} + await session.commit() + try: + yield auth_env + finally: + await auth_env.reset() + async with SessionLocal() as session: + row = await session.get(Setting, "apps") + if row is not None: + await session.delete(row) + await session.commit() + + +async def test_a_users_trial_follows_the_chat_rules(login, tmp_path): + """使用者试运行自己的个人蓝图:和问数据同一份约束——结果遮罩、只读、记忆是他自己的;图里有使用者不能用的节点不试。""" + from app.tools.datasource import MASK_RESULTS_OPTION, READ_ONLY_OPTION + + await login.turn_on_local() + u = uuid.uuid4().hex[:6] + await login.make_user(f"lee{u}", "user") + user = await login.login(f"lee{u}") + + async def personal(graph: dict) -> dict: + run = await run_manager.start(graph=graph, input_payload={**s.PERIOD, "question": "看看订单"}, + started_by=f"lee{u}", run_class="exploratory", origin_kind="chat") + assert (await s.wait(run.id)).status == "succeeded" + r = await user.post("/api/blueprints", json={"source": {"kind": "run", "id": run.id}, "scope": "personal"}) + assert r.status_code == 201, r.text + bp = r.json() + await s.edit_spec(bp["id"], purpose=s.item("看看订单")) + return bp + + bp = await personal(s.chain(s.node("start", "input", fields=[{"name": "question"}]), + s.node("done", "output", fields=[{"name": "问题", "value": "{{ input.question }}"}]))) + r = await user.post(f"/api/blueprints/{bp['id']}/trial", json={}) + assert r.status_code == 200, r.text + run = await s.wait(r.json()["run_id"]) + assert run.options[MASK_RESULTS_OPTION] is True and run.options[READ_ONLY_OPTION] is True + assert run.memory_scope == f"chat:lee{u}" + + source = await s.register_source(s.make_source(tmp_path)) + bp = await personal(s.board_graph(source)) + r = await user.post(f"/api/blueprints/{bp['id']}/trial", json={}) + assert r.status_code == 403 and r.json()["code"] == "trial_policy" and "个人应用" in r.json()["detail"], r.text + + +async def test_a_template_blueprint_trials_with_the_latest_period_and_keeps_its_filled_joints(client, tmp_path): + """按模板(周期看板):生成关节填好的蓝图实例化、试运行。不给输入时按「多久更新」算出最近一期(每周看上周); + 重新实例化(改了别的卡片)不会把填好的 SQL、指标式丢掉;印章写试运行。""" + from datetime import date, timedelta as days + + from app.blueprints.instantiate import instantiate + from app.blueprints.templates.periodic_board import example + from app.db.models_blueprints import Blueprint + + source = await s.register_source(s.make_source(tmp_path)) + bp = (await client.post("/api/blueprints", json={"source": {"kind": "template", "id": "periodic_board"}, + "scope": "shared", "name": "门店周报"})).json() + spec = example() + spec["data"] = [{**spec["data"][0], "table": s.item({"source": source, "table": "orders"}), + "filter": s.item("全部"), "date": s.item({"column": "paid_at", "rule": "按支付日"})}] + probe = instantiate(spec, name="门店周报", blueprint_id=bp["id"]) + fills = {j.id: ("SELECT ROUND(SUM(amount), 2) AS gmv FROM orders WHERE paid_at BETWEEN " + "'{{ input.period_start }}' AND '{{ input.period_end }}'" if j.kind == "sql" + else f"cell(nodes.{j.group}, 0, 'gmv')") + for j in probe.joint_defs if j.kind in ("sql", "metric_expr")} + filled = instantiate(spec, filled=fills, name="门店周报", blueprint_id=bp["id"]) + assert not [p for p in filled.problems if p["level"] == "error"], filled.problems + async with SessionLocal() as session: + row = await session.get(Blueprint, bp["id"]) + row.spec, row.joints = spec, filled.joints + await session.commit() + + r = await client.post(f"/api/blueprints/{bp['id']}/trial", json={}) + assert r.status_code == 200, r.text + run = await s.wait(r.json()["run_id"]) + assert run.status == "succeeded", run.error + start = date.fromisoformat(run.input["period_start"]) + end = date.fromisoformat(run.input["period_end"]) + assert start.isoweekday() == 1 and end - start == days(days=6) and "-W" in run.input["period"] + sql = next(n for n in run.graph["nodes"] if n["type"] == "tool")["data"]["config"]["args"]["sql"] + assert sql.startswith("SELECT ROUND(SUM(amount), 2)") + row = await s.blueprint(bp["id"]) + assert all(st["status"] == "filled" for st in row.joints.values()) + + vm = (await client.get(f"/api/blueprints/{bp['id']}/preview")).json() + stamp = find(vm, "stamp")[0]["data"]["stamp"] + assert stamp["from"] == TRIAL_FROM and stamp["trial"] is True + # 周期看板有趋势:试运行只有一个点,照实说没有趋势 + trends = [n["data"] for n in walk(vm["tree"]) if (n.get("data") or {}).get("note") == TRIAL_SERIES] + assert trends and len(trends[0]["series"][0]["points"]) == 1 + + +def test_a_period_that_cannot_be_worked_out_is_logged_not_swallowed(monkeypatch, caplog): + """算不出统计期(卡片还不全、上下文缺了)时试运行只用用户给的输入——照实记一条日志,不悄悄吞掉。""" + import logging + from types import SimpleNamespace + + from app.blueprints import instantiate + from app.blueprints.trial import trial_inputs + + def broken(spec): + raise KeyError("records") + + monkeypatch.setattr(instantiate, "trial_inputs", broken) + with caplog.at_level(logging.WARNING, logger="app.blueprints.trial"): + out = trial_inputs(SimpleNamespace(id="bp-x", spec={}), {"period": "2026-W41", "empty": ""}) + assert out == {"period": "2026-W41"} + assert any("bp-x" in r.getMessage() and r.exc_info for r in caplog.records) diff --git a/backend/tests/test_copilot_blueprint_stream.py b/backend/tests/test_copilot_blueprint_stream.py new file mode 100644 index 00000000..3c44731e --- /dev/null +++ b/backend/tests/test_copilot_blueprint_stream.py @@ -0,0 +1,452 @@ +"""蓝图助手和填关节的流式接口(docs/design/normal-user-apps.md §2.2、§2.3、§2.11)。模型一律用剧本,不调真接口。 + +守的是: +- blueprint-stream:bp_* 操作落到蓝图上(来源记助手、状态「待确认」),越界的不转发、交付时照实列出;bp_ask 让这一轮就此 + 结束,反问记进蓝图、对话这一轮记成反问(meta.asked),下一轮用户的话记成回答、进历史;每个操作写一条留痕; + 对话是 kind=blueprint;个人应用没开放时个人蓝图 403; +- fill-joints-stream:不同组并行填(两组同时在调模型),事件带 group;一组出错不挡别的组,等别的组做完再按顺序重试一次; + 检查过不了的组留占位、标「待填」并写明原因;填上的关节和图存回蓝图,每个关节写一条留痕。 +""" +from __future__ import annotations + +import asyncio +import json +import sqlite3 +import uuid + +import pytest +from httpx import ASGITransport, AsyncClient +from langchain_core.messages import AIMessageChunk +from sqlalchemy import select + +from app.data.introspect import introspect +from app.db.base import SessionLocal +from app.db.models import Conversation, ConversationTurn, DataSource +from app.db.models_blueprints import Blueprint, BlueprintEvent +from app.main import app +from tests.fixtures.sources import drop_source + + +@pytest.fixture +async def client(): + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c: + yield c + + +async def _source(tmp_path, name: str, ddl: str) -> DataSource: + path = tmp_path / f"{name}.db" + db = sqlite3.connect(path) + db.executescript(ddl) + db.commit() + db.close() + async with SessionLocal() as session: + row = DataSource(name=name, kind="sqlite", database=str(path), description="测试库") + session.add(row) + await session.commit() + row.schema_cache = await introspect(row) + await session.commit() + await session.refresh(row) + session.expunge(row) + return row + + +@pytest.fixture +async def sources(tmp_path): + shop = await _source(tmp_path, f"bpshop_{uuid.uuid4().hex[:6]}", + "CREATE TABLE orders (id INTEGER PRIMARY KEY, amount REAL, paid_at TEXT, refunded INTEGER);") + crm = await _source(tmp_path, f"bpcrm_{uuid.uuid4().hex[:6]}", + "CREATE TABLE visits (id INTEGER PRIMARY KEY, uid TEXT, visited_at TEXT);") + yield shop, crm + await drop_source(shop.id) + await drop_source(crm.id) + + +class Scripted: + """按请求吐操作流:route(messages, n) 交回这一次要吐的操作(或抛错)。记下同时在调的最多有几个(并行的证据)。""" + + def __init__(self, route) -> None: + self.route = route + self.calls: list[list] = [] + self.active = 0 + self.peak = 0 + + async def astream(self, messages): + self.calls.append(list(messages)) + n = len(self.calls) + self.active += 1 + self.peak = max(self.peak, self.active) + try: + await asyncio.sleep(0.05) + lines = self.route(messages, n) + for line in lines: + yield AIMessageChunk(content=json.dumps(line, ensure_ascii=False) + "\n") + finally: + self.active -= 1 + + +def _use(monkeypatch, model) -> None: + import app.api.copilot as copilot + + async def _model(*_a, **_k): + return model, "mock-fast" + + monkeypatch.setattr(copilot, "get_chat_model", _model) + + +async def _events(client, monkeypatch, model, path: str, body: dict) -> list[dict]: + _use(monkeypatch, model) + out: list[dict] = [] + async with client.stream("POST", path, json=body) as r: + assert r.status_code == 200, await r.aread() + async for line in r.aiter_lines(): + if line.startswith("data: "): + out.append(json.loads(line[6:])) + return out + + +def _ops(events: list[dict]) -> list[str]: + return [e["op"] for e in events if e["op"] not in ("thinking", "heartbeat", "model")] + + +async def _blueprint(**fields) -> str: + from app.blueprints.spec import empty_blueprint + + async with SessionLocal() as session: + row = Blueprint(name=fields.pop("name", "测试蓝图"), spec=fields.pop("spec", empty_blueprint()), **fields) + session.add(row) + await session.commit() + return row.id + + +async def _cleanup(bp_id: str) -> None: + async with SessionLocal() as session: + row = await session.get(Blueprint, bp_id) + if row is not None: + if row.conversation_id: + conv = await session.get(Conversation, row.conversation_id) + if conv is not None: + await session.delete(conv) + await session.delete(row) + await session.commit() + + +# ---------------------------------------------------------------- 蓝图对话 + + +async def test_blueprint_stream_proposes_asks_and_records(client, monkeypatch, sources): + shop, _ = sources + + def route(messages, n): + if n == 1: + return [{"op": "plan", "summary": "整理成周期看板"}, + {"op": "bp_template", "template": {"id": "periodic_board", "version": 1}}, + {"op": "bp_set", "path": "/purpose", "value": "每周看门店销售额"}, + {"op": "bp_add", "path": "/data", "value": { + "id": "gmv", "label": "销售额", "unit": "元", "table": {"source": shop.name, "table": "orders"}, + "measure": "sum(amount)"}}, + {"op": "bp_set", "path": "/data/0/table/why", "value": "orders 表有金额和支付日期"}, + {"op": "bp_add", "path": "/access/use", "value": {"kind": "group", "name": "门店"}}, + {"op": "bp_ask", "question": "销售额按下单日还是支付日算?", "options": ["按下单日", "按支付日"], + "path": "/data/0/date"}, + {"op": "bp_set", "path": "/purpose", "value": "问了之后的不算"}] + return [{"op": "plan", "summary": "按支付日"}, + {"op": "bp_set", "path": "/data/0/date", "value": {"column": "paid_at", "rule": "按支付日"}}, + {"op": "done", "explanation": "销售额按支付日算"}] + + model = Scripted(route) + bp_id = await _blueprint() + try: + events = await _events(client, monkeypatch, model, "/api/copilot/blueprint-stream", + {"blueprint_id": bp_id, "instruction": "每周一看上周各门店的销售额"}) + assert _ops(events) == ["plan", "bp_template", "bp_set", "bp_add", "bp_set", "bp_ask", "check", "final"], \ + _ops(events) + final = events[-1] + spec = final["blueprint"]["spec"] + assert spec["template"] == {"id": "periodic_board", "version": 1} + assert spec["purpose"] == {"value": "每周看门店销售额", "source": "assistant", "status": "proposed", "why": None} + assert spec["data"][0]["table"]["why"] == "orders 表有金额和支付日期" + assert spec["access"]["use"] == [], "授权助手不替人填" + assert spec["asks"][0]["question"] == "销售额按下单日还是支付日算?" and spec["asks"][0]["answer"] is None + assert final["asked"] == {"question": "销售额按下单日还是支付日算?", "options": ["按下单日", "按支付日"]} + assert [i["path"] for i in final["issues"]] == ["/access/use"] + assert any(i["code"] == "bp.data_unmapped" or i["code"] == "bp.unconfirmed" for i in final["blueprint"]["issues"]) + system, human = model.calls[0][0][1], model.calls[0][1][1] + assert "periodic_board" in system and "适用于" in system and "bp_ask" in system + assert "每周一看上周各门店的销售额" in human + + async with SessionLocal() as session: + row = await session.get(Blueprint, bp_id) + conv = await session.get(Conversation, row.conversation_id) + assert conv.kind == "blueprint" + turn = (await session.execute(select(ConversationTurn).where( + ConversationTurn.conversation_id == conv.id))).scalars().one() + assert turn.status == "done" and turn.meta["asked"]["question"] == "销售额按下单日还是支付日算?" + ops = [e.op for e in (await session.execute(select(BlueprintEvent).where( + BlueprintEvent.blueprint_id == bp_id).order_by(BlueprintEvent.seq))).scalars()] + assert ops == ["bp_template", "bp_set", "bp_add", "bp_set", "bp_ask"] + + # 下一轮:用户的话记成上一轮反问的回答,问题和回答都在历史里 + events = await _events(client, monkeypatch, model, "/api/copilot/blueprint-stream", + {"blueprint_id": bp_id, "instruction": "按支付日"}) + assert _ops(events) == ["plan", "bp_set", "done", "check", "final"], _ops(events) + spec = events[-1]["blueprint"]["spec"] + assert spec["asks"][0]["answer"] == "按支付日" + assert spec["data"][0]["date"]["value"] == {"column": "paid_at", "rule": "按支付日"} + human = model.calls[-1][1][1] + assert "销售额按下单日还是支付日算?" in human and "按支付日" in human + async with SessionLocal() as session: + events_db = list((await session.execute(select(BlueprintEvent).where( + BlueprintEvent.blueprint_id == bp_id).order_by(BlueprintEvent.seq))).scalars()) + answer = next(e for e in events_db if e.data.get("path") == "/asks/0/answer") + assert answer.data["source"] == "user" + assert events_db[-1].data["path"] == "/data/0/date" and events_db[-1].data["source"] == "assistant" + turns = list((await session.execute(select(ConversationTurn).order_by(ConversationTurn.seq).where( + ConversationTurn.conversation_id == (await session.get(Blueprint, bp_id)).conversation_id))).scalars()) + assert [t.question for t in turns] == ["每周一看上周各门店的销售额", "按支付日"] + assert turns[1].answer == "销售额按支付日算" + finally: + await _cleanup(bp_id) + + +async def test_personal_blueprints_need_the_switch(client, monkeypatch): + bp_id = await _blueprint(scope="personal", owner="someone") + try: + _use(monkeypatch, Scripted(lambda m, n: [{"op": "done"}])) + r = await client.post("/api/copilot/blueprint-stream", json={"blueprint_id": bp_id, "instruction": "看看"}) + assert r.status_code == 403 and "个人应用" in r.json()["detail"] + r = await client.post("/api/copilot/fill-joints-stream", json={"blueprint_id": bp_id}) + assert r.status_code == 403 + r = await client.post("/api/copilot/blueprint-stream", json={"blueprint_id": "nope", "instruction": "看看"}) + assert r.status_code == 404 + finally: + await _cleanup(bp_id) + + +# ---------------------------------------------------------------- 填关节 + + +def _board_spec(shop: str, crm: str) -> dict: + from app.blueprints.templates import _common as c + + spec = c.EXTRAS["periodic_board"].example() + for item in spec["data"]: + item["table"]["value"] = {"source": shop, "table": "orders"} + spec["data"] = spec["data"][:2] + spec["data"].append({**json.loads(json.dumps(spec["data"][0])), "id": "visitors", + "label": c.template_item("访客数"), "unit": c.template_item("人"), + "table": c.template_item({"source": crm, "table": "visits"}), + "measure": c.template_item("count(distinct uid)"), + "date": c.template_item({"column": "visited_at"})}) + return spec + + +def _fills(shop_node: str, crm_node: str) -> dict: + return { + shop_node: [{"op": "plan", "summary": "写取数"}, + {"op": "fill_joint", "joint": f"sql_{shop_node}", "value": + "SELECT SUM(amount) AS gmv, COUNT(*) AS order_cnt FROM orders" + " WHERE paid_at BETWEEN '{{ input.period_start }}' AND '{{ input.period_end }}'"}, + {"op": "fill_joint", "joint": "metric_gmv", "value": f"cell(nodes.{shop_node}, 0, 'gmv')"}, + {"op": "fill_joint", "joint": "metric_orders", "value": f"cell(nodes.{shop_node}, 0, 'order_cnt')"}, + {"op": "update_node", "id": "done", "config": {"contract": {}}}, + {"op": "done", "explanation": "按支付日"}], + crm_node: [{"op": "plan", "summary": "写访客"}, + {"op": "fill_joint", "joint": f"sql_{crm_node}", "value": + "SELECT COUNT(DISTINCT uid) AS visitors FROM visits" + " WHERE visited_at BETWEEN '{{ input.period_start }}' AND '{{ input.period_end }}'"}, + {"op": "fill_joint", "joint": "metric_visitors", "value": f"cell(nodes.{crm_node}, 0, 'visitors')"}, + {"op": "done", "explanation": "访客按去重算"}], + } + + +async def test_fill_joints_runs_groups_in_parallel_and_retries_a_failed_one(client, monkeypatch, sources): + from app.blueprints.templates._common import safe_id + + shop, crm = sources + shop_node, crm_node = f"fetch_{safe_id(shop.name)}", f"fetch_{safe_id(crm.name)}" + fills = _fills(shop_node, crm_node) + failed_once: list[int] = [] + + def route(messages, n): + human = messages[1][1] + if "这是你刚填的关节" in human: + # 自查交回来的只有那条越界的操作:知道了,不再改 + return [{"op": "done"}] + group = shop_node if f"sql_{shop_node}" in human else crm_node + if group == crm_node and not failed_once: + failed_once.append(n) + raise RuntimeError("模型服务限流了") + return fills[group] + + model = Scripted(route) + bp_id = await _blueprint(spec=_board_spec(shop.name, crm.name), template_id="periodic_board", template_version=1) + try: + events = await _events(client, monkeypatch, model, "/api/copilot/fill-joints-stream", {"blueprint_id": bp_id}) + assert model.peak >= 2, "两组同时在调模型" + groups = [(e["group"], e["status"]) for e in events if e["op"] == "group"] + assert (shop_node, "started") in groups and (crm_node, "retrying") in groups + assert groups[-1] == (crm_node, "filled") and (shop_node, "filled") in groups + looks = [e for e in events if e["op"] == "look"] + assert {e["group"] for e in looks} == {shop_node, crm_node} and all(e["by"] == "system" for e in looks) + assert all("group" in e for e in events if e["op"] in ("fill_joint", "plan", "check")) + final = events[-1] + assert final["op"] == "final", final + assert final["groups"][shop_node]["status"] == "filled" and final["groups"][crm_node]["status"] == "filled" + # 越界的那一条没有采纳,照实列出 + assert [r["code"] for r in final["groups"][shop_node]["refusals"]] == ["tpl.joint_refused"] + joints = final["blueprint"]["joints"] + assert all(state["status"] == "filled" for state in joints.values()), joints + assert final["problems"] == [] + async with SessionLocal() as session: + row = await session.get(Blueprint, bp_id) + nodes = {n["id"]: n for n in row.graph["nodes"]} + assert "SUM(amount)" in nodes[shop_node]["data"]["config"]["args"]["sql"] + assert nodes["done"]["data"]["config"]["contract"]["required"] == ["gmv", "orders", "visitors"] + from app.core.artifact_store import graph_hash + + assert row.graph_hash == graph_hash(row.graph) + assert row.joints["metric_gmv"]["value"] == f"cell(nodes.{shop_node}, 0, 'gmv')" + fills_db = [e.data for e in (await session.execute(select(BlueprintEvent).where( + BlueprintEvent.blueprint_id == bp_id, BlueprintEvent.op == "fill_joint"))).scalars()] + assert {d["joint"] for d in fills_db} == {f"sql_{shop_node}", "metric_gmv", "metric_orders", + f"sql_{crm_node}", "metric_visitors"} + + # 再请求一次:都填上了,没有要填的组,直接交付 + events = await _events(client, monkeypatch, model, "/api/copilot/fill-joints-stream", {"blueprint_id": bp_id}) + assert _ops(events) == ["final"] + finally: + await _cleanup(bp_id) + + +async def test_a_group_that_fails_its_checks_keeps_placeholders(client, monkeypatch, sources): + from app.blueprints.templates._common import SQL_PLACEHOLDER, safe_id + + shop, crm = sources + shop_node, crm_node = f"fetch_{safe_id(shop.name)}", f"fetch_{safe_id(crm.name)}" + fills = _fills(shop_node, crm_node) + bad = [{"op": "fill_joint", "joint": f"sql_{crm_node}", "value": "SELECT COUNT(*) AS n FROM visits"}, + {"op": "fill_joint", "joint": "metric_visitors", "value": f"cell(nodes.{crm_node}, 0, 'visitors')"}, + {"op": "done"}] + + def route(messages, n): + human = messages[1][1] + if f"sql_{shop_node}" in human: + return fills[shop_node] + return bad + + model = Scripted(route) + bp_id = await _blueprint(spec=_board_spec(shop.name, crm.name), template_id="periodic_board", template_version=1) + try: + events = await _events(client, monkeypatch, model, "/api/copilot/fill-joints-stream", {"blueprint_id": bp_id}) + final = events[-1] + assert final["groups"][crm_node]["status"] == "failed" and final["groups"][shop_node]["status"] == "filled" + # 自查交回去改了两轮,还是对不上,照实报 + repairs = [e for e in events if e["op"] == "check" and e.get("group") == crm_node and e["status"] == "repairing"] + assert len(repairs) == 2 and repairs[0]["issues"][0]["code"] == "tpl.metric_column" + joints = final["blueprint"]["joints"] + assert joints["metric_gmv"]["status"] == "filled" + assert joints["metric_visitors"]["status"] == "pending" and "没通过检查" in joints["metric_visitors"]["note"] + assert {p["code"] for p in final["problems"]} == {"tpl.joint_unfilled"} + assert all(p.get("plain") for p in final["problems"]) + async with SessionLocal() as session: + row = await session.get(Blueprint, bp_id) + nodes = {n["id"]: n for n in row.graph["nodes"]} + assert nodes[crm_node]["data"]["config"]["args"]["sql"] == SQL_PLACEHOLDER + assert "SUM(amount)" in nodes[shop_node]["data"]["config"]["args"]["sql"] + # 只重填失败的那一组 + model.route = lambda messages, n: fills[crm_node] + events = await _events(client, monkeypatch, model, "/api/copilot/fill-joints-stream", + {"blueprint_id": bp_id, "groups": [crm_node]}) + assert {e["group"] for e in events if e["op"] == "group"} == {crm_node} + assert all(state["status"] == "filled" for state in events[-1]["blueprint"]["joints"].values()) + r = await client.post("/api/copilot/fill-joints-stream", json={"blueprint_id": bp_id, "groups": ["nope"]}) + assert r.status_code == 400 + finally: + await _cleanup(bp_id) + + +async def test_templates_api(client): + r = await client.get("/api/templates") + assert r.status_code == 200 + items = r.json()["items"] + assert [i["id"] for i in items] == ["periodic_board", "approval", "exception_handling", "records", + "reconcile_writeback", "freeform"] + board = items[0] + assert board["label"] == "周期看板" and board["personal"] and board["cards"][0]["card"] == "purpose" + assert next(i for i in items if i["id"] == "approval")["personal"] is None + + +async def test_records_fill_uses_the_records_table(client, monkeypatch): + """填报登记:填关节前按「填什么」建好记录表(和试运行同一个入口),汇总的 SQL 查这张表登记成的数据源;写入节点固定在 + 这一个表版本上(「键.v版本」)。""" + import re + + from app.blueprints.templates import _common as c + from app.db.models_blueprints import RecordsTable + + def route(messages, n): + human = messages[1][1] + if "这是你刚填的关节" in human: + return [{"op": "done"}] + node = re.search(r"sql_(summary_\w+)", human).group(1) + return [{"op": "fill_joint", "joint": f"sql_{node}", "value": + "SELECT SUM(amount) AS loss_amount, COUNT(*) AS loss_count FROM records" + " WHERE date(_submitted_at) BETWEEN '{{ input.period_start }}' AND '{{ input.period_end }}'"}, + {"op": "fill_joint", "joint": "metric_loss_amount", "value": f"cell(nodes.{node}, 0, 'loss_amount')"}, + {"op": "fill_joint", "joint": "metric_loss_count", "value": f"cell(nodes.{node}, 0, 'loss_count')"}, + {"op": "done"}] + + bp_id = await _blueprint(spec=c.EXTRAS["records"].example(), template_id="records", template_version=1) + try: + events = await _events(client, monkeypatch, Scripted(route), "/api/copilot/fill-joints-stream", + {"blueprint_id": bp_id}) + final = events[-1] + assert final["op"] == "final", final + assert all(state["status"] == "filled" for state in final["blueprint"]["joints"].values()), final + async with SessionLocal() as session: + table = (await session.execute(select(RecordsTable).where(RecordsTable.table_key == bp_id))).scalars().one() + source = await session.get(DataSource, table.source_id) + nodes = {n["id"]: n for n in (await session.get(Blueprint, bp_id)).graph["nodes"]} + assert nodes["append"]["data"]["config"]["args"]["table"] == f"{bp_id}.v1" + summary = next(n for nid, n in nodes.items() if nid.startswith("summary_")) + assert summary["data"]["config"]["tool"] == f"db_query__{source.name}" + source_id, source_name = source.id, source.name + await session.delete(table) + await session.commit() + await drop_source(source_id) + assert source_name + finally: + await _cleanup(bp_id) + + +async def test_personal_blueprints_only_see_personal_templates(client, monkeypatch): + """开了个人应用之后,个人蓝图的助手只列能做成个人应用的场景,能力只列只读的。""" + from app.api.settings import APPS_GROUP + from app.db.models import Setting + + async with SessionLocal() as session: + row = await session.get(Setting, APPS_GROUP) + before = dict(row.value) if row is not None else None + if row is None: + session.add(Setting(key=APPS_GROUP, value={"user_personal_apps": True})) + else: + row.value = {**row.value, "user_personal_apps": True} + await session.commit() + bp_id = await _blueprint(scope="personal", owner="someone") + model = Scripted(lambda m, n: [{"op": "bp_set", "path": "/purpose", "value": "给自己看的周报"}, {"op": "done"}]) + try: + events = await _events(client, monkeypatch, model, "/api/copilot/blueprint-stream", + {"blueprint_id": bp_id, "instruction": "我想每周看看自己门店的销售额"}) + assert events[-1]["op"] == "final", events[-1] + system = model.calls[0][0][1] + assert "个人应用" in system and "periodic_board v1" in system + assert "approval v1" not in system and "reconcile_writeback v1" not in system + finally: + await _cleanup(bp_id) + async with SessionLocal() as session: + row = await session.get(Setting, APPS_GROUP) + if before is None: + await session.delete(row) + else: + row.value = before + await session.commit() diff --git a/backend/tests/test_copilot_look.py b/backend/tests/test_copilot_look.py index 719535cb..86ade6a8 100644 --- a/backend/tests/test_copilot_look.py +++ b/backend/tests/test_copilot_look.py @@ -268,10 +268,16 @@ async def test_ask_ends_the_round(client, monkeypatch, shop): final = events[-1] assert final["op"] == "final" and final["autorun"] is False assert {n["id"] for n in final["graph"]["nodes"]} == {"start", "q"} + # 改了图又问了:问题跟着 final 交付,前端记进这一轮 + assert final["asked"] == {"question": ask["question"], "options": []} - # 什么都还没改就问:问题转出去,这一轮就结束 + # 什么都还没改就问:问题转出去,这一轮就结束。照样发一条 final 收尾(带问题、图原样、不运行),前端据此把这一轮 + # 记成「助手反问」,不会一直停在「进行中」 events = await _events(client, monkeypatch, Turns([ask]), {"instruction": "订单金额"}) - assert _ops(events) == ["ask"] + assert _ops(events) == ["ask", "final"] + final = events[-1] + assert final["asked"]["question"] == ask["question"] and final["autorun"] is False + assert final["graph"] == {"nodes": [], "edges": []} and final["issues"] == [] # 非流式的 /generate:问题放在说明里,原图照旧 r = await client.post("/api/copilot/generate", json={"instruction": "订单金额"}) assert r.status_code == 200, r.text diff --git a/backend/tests/test_files.py b/backend/tests/test_files.py new file mode 100644 index 00000000..b4aa6e5e --- /dev/null +++ b/backend/tests/test_files.py @@ -0,0 +1,420 @@ +"""文件(docs/design/normal-user-apps.md N9、§3.8)。 + +- 上传:按内容寻址存、只读;类型按扩展名的白名单、再核对文件开头;要带上下文(入口、待办、蓝图),字段限定了类型的照办; +- 绑定:提交入口时核对是自己在这个入口传的、还没用过,绑到这次运行,表单值换成登记的引用;重复使用、用别人的被拒; + 回复待办时同样绑到运行; +- 下载:上传的人、读得到绑定那次运行的人能下;别人 403;没提交的别人连在不在都不知道; +- 删除:只能删自己的、还没提交的;清理:24 小时前上传、没提交的删掉; +- file_text:运行里只读绑定的文件,超过上限照实截断,记 file.extracted; +- table_import_period:按配方导入一期,要人确认的地方不替人做主。 + +夹具里的人名、门店名是假名。 +""" +from __future__ import annotations + +import asyncio +import dataclasses +import json +import uuid +from datetime import timedelta +from urllib.parse import quote + +import pytest +from httpx import ASGITransport, AsyncClient +from sqlalchemy import select + +from app.api.deps import Principal +from app.core.artifact_store import graph_hash +from app.core.config import settings +from app.db.base import SessionLocal, utcnow +from app.db.models import Run, RunEvent, Workflow, WorkflowVersion +from app.db.models_apps import AppGrant +from app.db.models_blueprints import StoredFile +from app.engine.runner import run_manager +from app.files import store + +TEXT = "门店本周报损:一店 3 件,二店 5 件。原因多为过期。" * 3 +FILE_FIELD = {"type": "object", "x-widget": "file", "title": "附件", "x-file": {"accept": [".txt", ".csv"]}} + + +@pytest.fixture(autouse=True) +def data_dir(monkeypatch, tmp_path): + data = tmp_path / "data" + (data / "uploads").mkdir(parents=True) + monkeypatch.setattr(settings, "data_dir", data) + yield data + + +@pytest.fixture +async def engine_up(data_dir): + await run_manager.setup() + yield + await run_manager.shutdown() + + +@pytest.fixture +async def client(engine_up): + from app.main import app + + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c: + yield c + + +def node(nid, ntype, **config): + return {"id": nid, "type": ntype, "position": {"x": 0, "y": 0}, "data": {"label": nid, "config": config}} + + +def chain(*nodes): + return {"nodes": list(nodes), "edges": [{"source": a["id"], "target": b["id"]} for a, b in zip(nodes, nodes[1:])]} + + +async def wait(run_id: str, statuses=("interrupted", "failed", "succeeded"), timeout=30.0) -> Run: + deadline = asyncio.get_event_loop().time() + timeout + while asyncio.get_event_loop().time() < deadline: + async with SessionLocal() as session: + row = await session.get(Run, run_id) + if row and row.status in statuses and not run_manager.is_active(row.id): + return row + await asyncio.sleep(0.05) + raise AssertionError(f"运行 {run_id} 没有进入 {statuses}") + + +def actor(name: str) -> dict[str, str]: + return {"X-Actor": quote(name)} + + +GRAPH = chain(node("start", "input", fields=[{"name": "doc", "type": "file"}, {"name": "note"}]), + node("out", "output", fields=[{"name": "text", "value": "{{ file_text(input.doc, 12) }}"}, + {"name": "ref", "value": "{{ input.doc.sha256 }}"}])) + + +async def published_app(client) -> str: + """一个已发布的应用:入口「报损」带文件字段,成果读附件的前 12 个字。""" + async with SessionLocal() as session: + wf = Workflow(name=f"报损-{uuid.uuid4().hex[:6]}", graph=GRAPH, status="published", published_version=1) + session.add(wf) + await session.flush() + session.add(WorkflowVersion(workflow_id=wf.id, version=1, graph=GRAPH, graph_hash=graph_hash(GRAPH), + level="published", published_at=utcnow())) + await session.commit() + wf_id = wf.id + spec = {"format": "agentlab.app/1", "name": "报损", + "pins": [{"alias": "main", "workflow_id": wf_id, "version": 1, "graph_hash": graph_hash(GRAPH), + "use": "entry"}], + "entries": [{"id": "report", "label": "报损", "pin": "main", "form": {"$ref": "#/forms/report"}, + "map": {"doc": "form.doc", "note": "form.note"}}], + "forms": {"report": {"type": "object", "required": ["doc"], + "properties": {"doc": FILE_FIELD, "note": {"type": "string", "title": "说明"}}}}, + "pages": [{"id": "home", "title": "首页", "body": [ + {"id": "new", "type": "entry_button", "props": {"entry": "report"}}]}]} + res = await client.post("/api/apps", json={"name": "报损", "spec": spec}, headers=actor("建立人")) + assert res.status_code == 201, res.text + app_id = res.json()["id"] + published = (await client.post(f"/api/apps/{app_id}/publish", json={})).json() + assert published["ok"], published + return app_id + + +async def upload(client, app_id: str, name: str, content: bytes, who: str = "amy", **ctx): + context = {"app_id": app_id, "entry": "report", "field": "doc", **ctx} + return await client.post("/api/files", files={"file": (name, content, "application/octet-stream")}, + data={"context": json.dumps(context)}, headers=actor(who)) + + +async def row_of(file_id: str) -> StoredFile | None: + async with SessionLocal() as session: + return await session.get(StoredFile, file_id) + + +# -------------------------------------------------------------------------- +# 上传 +# -------------------------------------------------------------------------- + + +async def test_upload_checks_context_type_and_content(client): + app_id = await published_app(client) + res = await upload(client, app_id, "报损.txt", TEXT.encode()) + assert res.status_code == 201, res.text + ref = res.json() + assert set(ref) == {"file_id", "name", "size", "sha256", "type"} and ref["type"] == "text/plain" + path = store.blob_path(ref["sha256"]) + assert path.read_bytes() == TEXT.encode() and (path.stat().st_mode & 0o777) == 0o444 + row = await row_of(ref["file_id"]) + assert row.uploaded_by == "amy" and row.context == {"app_id": app_id, "entry": "report", "field": "doc"} + + cases = [ + (await upload(client, app_id, "假的.pdf", b"not a pdf"), 415, "files.content_mismatch"), + (await upload(client, app_id, "程序.exe", b"MZ\x00"), 415, "files.type_not_allowed"), + (await upload(client, app_id, "合同.pdf", b"%PDF-1.4 x"), 415, "files.type_not_accepted"), + (await upload(client, app_id, "空.txt", b""), 422, "files.empty"), + (await upload(client, app_id, "报损.txt", b"x", entry="ghost"), 404, "files.context_invalid"), + (await client.post("/api/files", files={"file": ("a.txt", b"x", "text/plain")}, data={"context": "{}"}), + 422, "files.context_invalid"), + ] + for res, status, code in cases: + assert (res.status_code, res.json().get("code")) == (status, code), res.text + # 没有字段限定的地方(不说是哪个字段)照白名单收 PDF + pdf = await upload(client, app_id, "合同.pdf", b"%PDF-1.4 x", field="") + assert pdf.status_code == 201 and pdf.json()["type"] == "application/pdf" + + +# -------------------------------------------------------------------------- +# 提交入口:绑定、重复使用、别人的、file_text +# -------------------------------------------------------------------------- + + +async def test_entry_binds_the_file_once_and_file_text_reads_it(client): + app_id = await published_app(client) + ref = (await upload(client, app_id, "报损.txt", TEXT.encode())).json() + res = await client.post(f"/api/apps/{app_id}/entries/report", json={"values": {"doc": ref, "note": "本周"}}, + headers=actor("amy")) + assert res.status_code == 201, res.text + run_id = res.json()["run_id"] + done = await wait(run_id, ("succeeded", "failed")) + assert done.status == "succeeded", done.error + assert (await row_of(ref["file_id"])).bound_run_id == run_id + assert done.input["doc"] == ref, "运行输入里是登记的那一份引用(连同 sha256)" + text = done.output["text"] + assert text.startswith(TEXT[:12]) and f"共 {len(TEXT)} 字" in text and "只读入了前 12 字" in text + async with SessionLocal() as session: + events = list((await session.execute(select(RunEvent).where(RunEvent.run_id == run_id))).scalars()) + extracted = [e.data for e in events if e.type == "file.extracted" or e.data.get("code") == "file.extracted"] + assert len(extracted) == 1 + assert extracted[0]["truncated"] is True and extracted[0]["chars"] == 12 + assert extracted[0]["total_chars"] == len(TEXT) and extracted[0]["artifact"] + + again = await client.post(f"/api/apps/{app_id}/entries/report", json={"values": {"doc": ref}}, + headers=actor("amy")) + assert again.status_code == 422 + assert again.json()["errors"][0]["path"] == "doc" and "已经提交过" in again.json()["errors"][0]["message"] + + bobs = (await upload(client, app_id, "别人的.txt", "二店报损".encode(), who="bob")).json() + stolen = await client.post(f"/api/apps/{app_id}/entries/report", json={"values": {"doc": bobs}}, + headers=actor("amy")) + assert stolen.status_code == 422 and "不是你上传的" in stolen.json()["errors"][0]["message"] + assert (await row_of(bobs["file_id"])).bound_run_id is None, "被拒的提交不占文件" + forged = await client.post(f"/api/apps/{app_id}/entries/report", + json={"values": {"doc": {**bobs, "file_id": "x"}}}, headers=actor("bob")) + assert forged.status_code == 422 + + +async def test_file_text_only_reads_files_bound_to_the_run(engine_up): + """输入里塞一个没绑到这次运行的引用:读不到,照实说。""" + async with SessionLocal() as session: + row = await store.save(session, "机密".encode(), "机密.txt", uploaded_by="bob", context={"blueprint_id": "b"}) + ref = store.ref_of(row) + run = await run_manager.start(graph=GRAPH, input_payload={"doc": ref}, run_class="exploratory") + done = await wait(run.id, ("succeeded", "failed")) + assert done.output["text"] == "(附件「机密.txt」没有随这次运行提交,读不到)" + + +async def test_task_reply_binds_the_file_to_the_run(client): + from app.db.models import Task + from app.process import tasks + + form = {"format": "agentlab.form/1", "type": "object", "required": ["doc"], "properties": {"doc": FILE_FIELD}} + graph = chain(node("start", "input"), node("fill", "human", mode="input", title="补附件", form=form), + node("out", "output", fields=[{"name": "text", "value": "{{ file_text(nodes.fill.value.doc) }}"}])) + run = await run_manager.start(graph=graph, input_payload={}) + assert (await wait(run.id)).status == "interrupted" + async with SessionLocal() as session: + task = (await session.execute(select(Task).where(Task.run_id == run.id))).scalars().one() + ref = (await client.post("/api/files", files={"file": ("说明.txt", "二店冷柜坏了".encode(), "text/plain")}, + data={"context": json.dumps({"task_id": task.id, "field": "doc"})}, + headers=actor("amy"))).json() + amy = Principal(username="amy", role="admin", mode="off") + other = (await client.post("/api/files", files={"file": ("x.txt", b"x", "text/plain")}, + data={"context": json.dumps({"task_id": task.id})}, headers=actor("bob"))).json() + with pytest.raises(tasks.FormInvalid) as refused: + await tasks.respond(task.id, amy, decision="submit", values={"doc": other}) + assert refused.value.errors[0]["path"] == "doc" + out = await tasks.respond(task.id, amy, decision="submit", values={"doc": ref}) + assert out["resolved"] is True + done = await wait(run.id, ("succeeded", "failed")) + assert done.status == "succeeded", done.error + assert done.output["text"] == "二店冷柜坏了" + assert (await row_of(ref["file_id"])).bound_run_id == run.id + + +# -------------------------------------------------------------------------- +# 下载、删除、清理 +# -------------------------------------------------------------------------- + + +async def test_download_follows_the_run_and_delete_only_unbound(client, monkeypatch): + from app.api import files as files_api + + app_id = await published_app(client) + suffix = uuid.uuid4().hex[:6] + amy, cat, dan = f"amy{suffix}", f"cat{suffix}", f"dan{suffix}" + ref = (await upload(client, app_id, "报损.txt", TEXT.encode(), who=amy)).json() + res = await client.post(f"/api/apps/{app_id}/entries/report", json={"values": {"doc": ref}}, headers=actor(amy)) + await wait(res.json()["run_id"], ("succeeded", "failed")) + async with SessionLocal() as session: + session.add(AppGrant(app_id=app_id, principal_kind="user", principal=cat, role="observe")) + await session.commit() + + def as_(name: str) -> None: + monkeypatch.setattr(files_api, "current_principal", + lambda: Principal(username=name, role="user", verified=True, mode="local")) + + as_(amy) + got = await client.get(f"/api/files/{ref['file_id']}") + assert got.status_code == 200 and got.content == TEXT.encode() + assert "attachment" in got.headers["content-disposition"] + as_(cat) + assert (await client.get(f"/api/files/{ref['file_id']}")).status_code == 200, "能看全部实例的人读得到这次运行" + as_(dan) + denied = await client.get(f"/api/files/{ref['file_id']}") + assert denied.status_code == 403 and denied.json()["code"] == "files.forbidden" + + # 删除:提交过的不能删;没提交的只有自己能删,别人连在不在都不知道 + off = Principal(username=None, role="admin", mode="off") + monkeypatch.setattr(files_api, "current_principal", lambda: off) + assert (await client.delete(f"/api/files/{ref['file_id']}", headers=actor(amy))).status_code == 409 + loose = (await upload(client, app_id, "草稿.txt", "草稿".encode(), who=amy)).json() + as_(dan) + assert (await client.get(f"/api/files/{loose['file_id']}")).status_code == 404 + monkeypatch.setattr(files_api, "current_principal", lambda: off) + assert (await client.delete(f"/api/files/{loose['file_id']}", headers=actor(dan))).status_code == 404 + assert (await client.delete(f"/api/files/{loose['file_id']}", headers=actor(amy))).status_code == 204 + assert await row_of(loose["file_id"]) is None and not store.blob_path(loose["sha256"]).exists() + + +async def test_cleanup_removes_old_unbound_uploads(engine_up): + async with SessionLocal() as session: + old = await store.save(session, b"old " + uuid.uuid4().hex.encode(), "old.txt", uploaded_by="amy", + context={"blueprint_id": "b"}) + fresh = await store.save(session, b"new " + uuid.uuid4().hex.encode(), "new.txt", uploaded_by="amy", + context={"blueprint_id": "b"}) + kept = await store.save(session, b"kept " + uuid.uuid4().hex.encode(), "kept.txt", uploaded_by="amy", + context={"blueprint_id": "b"}) + claimed = await store.save(session, b"claim " + uuid.uuid4().hex.encode(), "c.txt", uploaded_by="amy", + context={"blueprint_id": "b"}) + long_ago = utcnow() - timedelta(hours=25) + old.uploaded_at = kept.uploaded_at = claimed.uploaded_at = long_ago + kept.bound_run_id = "some-run" + claimed.bound_run_id = f"{store.CLAIM_PREFIX}stale" + await session.commit() + ids = {r.id: r.sha256 for r in (old, fresh, kept, claimed)} + removed = await store.cleanup() + assert removed >= 2 + assert await row_of(old.id) is None and not store.blob_path(ids[old.id]).exists() + assert await row_of(claimed.id) is None, "占着却没发起成功的,过了时限同样清掉" + assert await row_of(fresh.id) is not None and await row_of(kept.id) is not None + assert store.blob_path(ids[kept.id]).exists() + + +# -------------------------------------------------------------------------- +# table_import_period:按配方导入一期 +# -------------------------------------------------------------------------- + + +async def test_import_period_uses_the_recipe_and_leaves_decisions_to_people(client, monkeypatch): + from app.data import raw_store, recipe_imports + from app.db.models import DataSource + from app.files.imports import import_period_action + from tests.test_recipe_imports import FakeState, fake_pipeline, raw_bytes, recipe_source + + pipe = fake_pipeline(FakeState()) + monkeypatch.setattr(recipe_imports, "pipeline", lambda: pipe) + done = await recipe_source(client) + name, before = done["source"]["name"], done["snapshot_id"] + run_id = uuid.uuid4().hex + + async def bound_file(raw: bytes, *, run: str | None = run_id) -> dict: + sha, _ = raw_store.put_addressed(raw, store.files_root()) + async with SessionLocal() as session: + row = StoredFile(sha256=sha, name="月报导出_2026-09-01_2026-09-30.xlsx", size=len(raw), + mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + uploaded_by="amy", context={"app_id": "a", "entry": "e"}, bound_run_id=run) + session.add(row) + await session.commit() + return store.ref_of(row) + + # 假管线每次都要人勾「导入模式」:不替人勾,照实拒绝,暂存留着 + blocked = await import_period_action({"source": name, "file": await bound_file(raw_bytes())}, run_id=run_id, + on_behalf={"sub": "amy", "act": "cat"}, environment="prod") + assert blocked.status is None and "要在「数据」页由人确认" in blocked.error and "导入模式" in blocked.error + # 没有要人判断的地方:按配方导入成新的一期 + monkeypatch.setattr(recipe_imports, "pipeline", lambda: dataclasses.replace(pipe, confirm_items=lambda ctx: [])) + ok = await import_period_action({"source": name, "file": await bound_file(raw_bytes())}, run_id=run_id, + on_behalf={"sub": "amy", "act": "cat"}, environment="prod") + assert ok.status == 200, ok.error + async with SessionLocal() as session: + source = (await session.execute(select(DataSource).where(DataSource.name == name))).scalar_one() + assert source.current_snapshot_id == ok.body["snapshot_id"] != before + # 没随这次运行提交的文件、不是按配方导入的源:拒绝 + other = await import_period_action({"source": name, "file": await bound_file(raw_bytes(), run="x")}, + run_id=run_id, on_behalf=None, environment="prod") + assert other.status is None and "没有随这次运行提交" in other.error + wrong = await import_period_action({"source": "no_such_source", "file": await bound_file(raw_bytes())}, + run_id=run_id, on_behalf=None, environment="prod") + assert wrong.status is None and "不是按配方导入" in wrong.error + + +def test_form_file_widget_rules(): + from app.apps.forms import input_schema, validate_form, validate_form_schema + + form = {"type": "object", "required": ["doc"], "properties": {"doc": FILE_FIELD}} + assert validate_form_schema(form) == [] + assert any("只有文件控件能用" in p for p in validate_form_schema( + {"type": "object", "properties": {"x": {"type": "object"}}})) + assert any("文件控件,类型只能是对象" in p for p in validate_form_schema( + {"type": "object", "properties": {"x": {"type": "string", "x-widget": "file"}}})) + assert any("文件的限制" in p or "不是文件控件" in p for p in validate_form_schema( + {"type": "object", "properties": {"x": {"type": "string", "x-file": {}}}})) + ref = {"file_id": "f", "name": "a.txt", "size": 3, "sha256": "0" * 64, "type": "text/plain"} + assert validate_form(form, {"doc": ref}) == [] + assert validate_form(form, {})[0]["code"] == "required" + assert validate_form(form, {"doc": "a.txt"})[0]["message"] == "「附件」需要先上传文件" + wrong = validate_form(form, {"doc": {**ref, "name": "a.pdf", "type": "application/pdf"}}) + assert wrong and "只收这些类型" in wrong[0]["message"] + schema = input_schema([{"name": "doc", "type": "file", "required": True, "accept": [".pdf"], "max_mb": 5}]) + assert schema["properties"]["doc"] == {"type": "object", "x-widget": "file", "title": "doc", + "x-file": {"accept": [".pdf"], "max_mb": 5}} + assert schema["required"] == ["doc"] and validate_form_schema(schema) == [] + + +# -------------------------------------------------------------------------- +# 试运行的示例表单带附件(复核 M9、L9) +# -------------------------------------------------------------------------- + + +async def test_a_trial_with_an_attachment_binds_the_file_to_the_trial_run(client): + """流程类试运行填了示例表单:和应用入口提交同一条路——文件核对是这个人在这张蓝图上传的、还没用过,绑到这次试运行, + 表单值换成登记的引用;填报登记的「填什么」可以有文件字段(记录表的文件列存引用)。别处上传的文件不收。""" + from tests import blueprint_samples as s + + bp = (await client.post("/api/blueprints", json={"source": {"kind": "template", "id": "records"}, "scope": "shared", + "name": "报损附件"}, headers=actor("amy"))).json() + await s.edit_spec(bp["id"], purpose=s.item("门店报损,附照片"), people=[], data=[], fields=[ + {"name": "store", "spec": s.item({"type": "string", "title": "门店", "required": True}), "sensitive": False}, + {"name": "doc", "spec": s.item({k: v for k, v in FILE_FIELD.items() if k != "x-file"}), "sensitive": False}]) + got = (await client.get(f"/api/blueprints/{bp['id']}", headers=actor("amy"))).json() + assert not [i for i in got["issues"] if i["code"] == "bp.template_mismatch"], "填报登记收文件字段" + + up = await client.post("/api/files", files={"file": ("报损.txt", TEXT.encode(), "text/plain")}, + data={"context": json.dumps({"blueprint_id": bp["id"], "field": "doc"})}, headers=actor("amy")) + assert up.status_code == 201, up.text + ref = up.json() + r = await client.post(f"/api/blueprints/{bp['id']}/trial", json={"inputs": {"store": "一店", "doc": ref}}, + headers=actor("amy")) + assert r.status_code == 200, r.text + run = await wait(r.json()["run_id"], ("succeeded", "failed")) + assert run.status == "succeeded", run.error + assert run.input["doc"]["file_id"] == ref["file_id"] and run.input["doc"]["sha256"] == ref["sha256"] + assert run.input["mode"] == "submit" + assert (await row_of(ref["file_id"])).bound_run_id == run.id, "绑到这次试运行" + + # 同一个文件再提交一次:已经用过了 + again = await client.post(f"/api/blueprints/{bp['id']}/trial", json={"inputs": {"store": "一店", "doc": ref}}, + headers=actor("amy")) + assert again.status_code == 409 and again.json()["code"] == "files.already_bound", again.text + # 别人的文件:不收 + other = await client.post("/api/files", files={"file": ("别人.txt", TEXT.encode(), "text/plain")}, + data={"context": json.dumps({"blueprint_id": bp["id"], "field": "doc"})}, + headers=actor("bob")) + bad = await client.post(f"/api/blueprints/{bp['id']}/trial", json={"inputs": {"store": "一店", "doc": other.json()}}, + headers=actor("amy")) + assert bad.status_code == 422 and bad.json()["code"] == "files.not_yours", bad.text diff --git a/backend/tests/test_personal_apps.py b/backend/tests/test_personal_apps.py new file mode 100644 index 00000000..d9e130ab --- /dev/null +++ b/backend/tests/test_personal_apps.py @@ -0,0 +1,832 @@ +"""个人应用(docs/design/normal-user-apps.md N6 的服务端部分、N7、§3.9)。 + +- 开关:apps.user_personal_apps 默认关;关着时使用者存个人应用、刷新、提交审核一律 403(说人话),搭建者及以上不受它管; +- 存:图要满足使用者的约束(同问数据的白名单:没有人工节点、不写入),要先试运行过,卡片有错的不存(问题带白话); + 建出来的是 scope=personal、owner=拥有者的应用,固定的是蓝图(带图哈希),视图只取探索运行;再存一次是同一个应用; +- 刷新:以拥有者的身份发起探索运行(origin_kind=personal_app),强加 MASK_RESULTS / READ_ONLY,按人计每日上限(和按需 + 视图共用设置项),交回剩余次数;正在刷新的接上那一次;输入按实例化时记下的定时任务输入模板算; +- 只有拥有者看得见;管理员只看得到它存在、能归档,看不到内容;拥有者能读自己的刷新,别人不能;个人应用不能发布、授权; +- 提交审核:要先成功刷新一次,只能交给搭建者;开一条 review 待办;派给的搭建者取得共享副本(copied_from),原个人应用 + 不动;在待办里只能退回;副本发布后待办记为已发布,提交人收到通知; +- 解析:exploratory 来源取最近一次成功封存的刷新,印章写「探索 · 未经发布审核」;趋势按每次刷新排;共享应用里写了 + exploratory 的照实报错;隐藏的组件不下发,按草稿解析时带着 hidden; +- 页面编辑的候选:按固定版本列出能加的数据卡片,已经在页面上的不列,交回的组件能直接 app_add; +- 三条新检查:app.view_source_personal、app.hidden_bound、personal.policy,都有白话。 +""" +from __future__ import annotations + +import asyncio +import copy +import uuid +from datetime import timedelta + +import pytest +from httpx import ASGITransport, AsyncClient +from sqlalchemy import delete, func, select + +from app.api.deps import Principal +from app.api.settings import APPS_GROUP +from app.core.artifact_store import graph_hash +from app.db.base import SessionLocal, utcnow +from app.db.models import Run, Setting, Workflow, WorkflowVersion +from app.db.models_apps import App +from app.db.models_blueprints import Blueprint, BlueprintEvent +from app.db.models_process import Task, TaskAssignment +from app.engine.runner import run_manager +from tests.fakes import auth_env + +# -------------------------------------------------------------------------- +# 准备 +# -------------------------------------------------------------------------- + + +def node(nid, ntype, label=None, **config): + return {"id": nid, "type": ntype, "position": {"x": 0, "y": 0}, "data": {"label": label or nid, "config": config}} + + +def chain(*nodes): + return {"nodes": list(nodes), "edges": [{"source": a["id"], "target": b["id"]} for a, b in zip(nodes, nodes[1:])]} + + +#: 只读数据、整理的看板:入口(统计周,有默认值)→ 数据整形 → 口径卡 → 成果。不调模型,跑得快 +KPI = chain( + node("start", "input", "开始", fields=[{"name": "week", "default": "2026-W41"}]), + node("fetch", "transform", "取数", mode="expression", expression="{'gmv': 4321.5}", assign_to="kpi"), + node("card", "metrics", "口径卡", caliber="周报口径", caliber_version="v1", + metrics=[{"id": "gmv", "name": "销售额", "unit": "元", "expression": "vars.kpi.gmv"}]), + node("out", "output", "成果", fields=[{"name": "r", "value": "{{ nodes.card.text }}"}])) + +HUMAN = chain(node("start", "input", "开始"), node("ok", "human", "主管审批", mode="approve"), + node("out", "output", "成果")) +WRITE = chain(node("start", "input", "开始"), node("w", "tool", "写回系统", tool="http_request"), + node("out", "output", "成果")) + + +def item(value): + return {"value": value, "source": "user", "status": "confirmed"} + + +async def blueprint(owner: str | None, graph: dict | None = None, *, trialed: bool = True, purpose: str | None = "每周看销售额", + name: str = "我的周报", scope: str = "personal") -> str: + graph = copy.deepcopy(KPI if graph is None else graph) + spec = {"format": "agentlab.blueprint/1", "template": {"id": "freeform", "version": 1}, + "purpose": item(purpose) if purpose else {"value": None, "source": "assistant", "status": "missing"}} + async with SessionLocal() as session: + row = Blueprint(name=name, owner=owner, scope=scope, status="trialed" if trialed else "drafting", spec=spec, + template_id="freeform", template_version=1, source={"kind": "run"}, graph=graph, + graph_hash=graph_hash(graph), last_trial_run_id="trial-run" if trialed else None) + session.add(row) + await session.commit() + return row.id + + +async def switch(on: bool, limit: int = 200) -> None: + async with SessionLocal() as session: + row = await session.get(Setting, APPS_GROUP) + value = {"on_demand_daily_limit": limit, "user_personal_apps": on} + if row is None: + session.add(Setting(key=APPS_GROUP, value=value)) + else: + row.value = value + await session.commit() + + +async def people() -> tuple[AsyncClient, dict[str, AsyncClient]]: + """开账号密码登录:管理员 root,使用者 uma、ula,搭建者 bob、bea。""" + root = await auth_env.turn_on_local() + for name, role in (("uma", "user"), ("ula", "user"), ("bob", "builder"), ("bea", "builder")): + await auth_env.make_user(name, role) + return root, {n: await auth_env.login(n) for n in ("uma", "ula", "bob", "bea")} + + +async def saved(client: AsyncClient, blueprint_id: str) -> str: + r = await client.post(f"/api/blueprints/{blueprint_id}/save-personal") + assert r.status_code == 200, r.text + return r.json()["app_id"] + + +async def wait(run_id: str) -> Run: + row = None + for _ in range(600): + async with SessionLocal() as session: + row = await session.get(Run, run_id) + if row.status in ("succeeded", "failed", "cancelled") and row.manifest_seq is not None: + return row + await asyncio.sleep(0.03) + raise AssertionError(f"运行 {run_id} 没有结束:{row.status if row else None}") + + +async def refreshed(client: AsyncClient, app_id: str) -> Run: + r = await client.post(f"/api/apps/{app_id}/refresh") + assert r.status_code == 200, r.text + run = await wait(r.json()["run_id"]) + assert run.status == "succeeded", run.error + return run + + +def walk(tree): + for n in tree: + yield n + yield from walk(n.get("children") or []) + + +@pytest.fixture(autouse=True) +async def env(): + await auth_env.reset() + await run_manager.setup() + async with SessionLocal() as session: + await session.execute(delete(Setting).where(Setting.key == APPS_GROUP)) + # 每日上限按人计、按当天的刷新数:前面的测试留下的刷新不算进来 + await session.execute(delete(Run).where(Run.origin_kind == "personal_app")) + await session.commit() + yield + await run_manager.shutdown() + from app.notify.service import drain + + await drain() + async with SessionLocal() as session: + await session.execute(delete(Setting).where(Setting.key == APPS_GROUP)) + await session.commit() + await auth_env.reset() + + +# -------------------------------------------------------------------------- +# 开关 +# -------------------------------------------------------------------------- + + +async def test_the_switch_gates_users_but_not_builders(): + _, c = await people() + uma_bp = await blueprint("uma") + r = await c["uma"].post(f"/api/blueprints/{uma_bp}/save-personal") + assert r.status_code == 403 and r.json()["code"] == "personal.off", r.text + assert "使用者可以建个人应用" in r.json()["detail"] and "user_personal_apps" not in r.json()["detail"] + assert (await c["uma"].get("/api/apps")).json()["can_create"] == {"shared": False, "personal": False} + + # 搭建者不受开关管(§3.12) + assert (await c["bob"].get("/api/apps")).json()["can_create"] == {"shared": True, "personal": True} + await saved(c["bob"], await blueprint("bob")) + + await switch(True) + assert (await c["uma"].get("/api/apps")).json()["can_create"] == {"shared": False, "personal": True} + app_id = await saved(c["uma"], uma_bp) + + await switch(False) + assert (await c["uma"].post(f"/api/apps/{app_id}/refresh")).json()["code"] == "personal.off" + r = await c["uma"].post(f"/api/apps/{app_id}/submit-review", json={"to": [{"kind": "user", "name": "bob"}]}) + assert r.status_code == 403 and r.json()["code"] == "personal.off" + + +# -------------------------------------------------------------------------- +# 存成个人应用 +# -------------------------------------------------------------------------- + + +async def test_saving_checks_the_user_constraints_and_builds_a_personal_app(): + _, c = await people() + await switch(True) + uma = c["uma"] + + r = await uma.post(f"/api/blueprints/{await blueprint('uma', HUMAN)}/save-personal") + assert r.status_code == 403 and r.json()["code"] == "personal.policy", r.text + assert "使用者在个人应用中不能使用" in r.json()["detail"] and "「主管审批」" in r.json()["detail"] + r = await uma.post(f"/api/blueprints/{await blueprint('uma', WRITE)}/save-personal") + assert r.status_code == 403 and "「写回系统」" in r.json()["detail"], "写入(调用工具节点)一样不许" + + r = await uma.post(f"/api/blueprints/{await blueprint('uma', trialed=False)}/save-personal") + assert r.status_code == 409 and r.json()["code"] == "personal.not_trialed" + r = await uma.post(f"/api/blueprints/{await blueprint('uma', purpose=None)}/save-personal") + assert r.status_code == 422 and r.json()["code"] == "bp.missing", r.text + assert r.json()["issues"][0]["path"] == "/purpose" and r.json()["issues"][0]["plain"]["title"] + + bp = await blueprint("uma") + assert (await c["ula"].post(f"/api/blueprints/{bp}/save-personal")).status_code == 404, "别人的蓝图当它不存在" + r = await uma.post(f"/api/blueprints/{bp}/save-personal") + assert r.status_code == 200, r.text + app_id = r.json()["app_id"] + assert r.json()["blueprint"]["status"] == "personal" and r.json()["blueprint"]["app_id"] == app_id + + detail = (await uma.get(f"/api/apps/{app_id}")).json() + assert (detail["scope"], detail["owner"], detail["blueprint_id"], detail["my_role"]) == ("personal", "uma", bp, + "manage") + assert detail["published_version"] is None and detail["published"] is None + draft = detail["draft"] + assert [(p["blueprint"], p["graph_hash"], p["workflow_id"], p["version"]) for p in draft["pins"]] == [ + (bp, graph_hash(KPI), None, None)] + assert {v["source"]["kind"] for v in draft["views"].values()} == {"exploratory"} + assert draft["entries"] == [] and draft["hooks"] == [] and draft["slots"] == {} + types = {n["type"] for page in draft["pages"] for n in walk(page["body"])} + assert "metric" in types and not types & {"entry_button", "instance_list", "instance_header"} + assert detail["personal"]["remaining_today"] == 200 and detail["personal"]["graph_changed"] is False + + # 再存一次:同一个应用,页面上改过的留着 + draft["pages"][0]["title"] = "我改过的标题" + assert (await uma.patch(f"/api/apps/{app_id}", json={"draft": draft})).status_code == 200 + again = await uma.post(f"/api/blueprints/{bp}/save-personal") + assert again.json()["app_id"] == app_id + assert (await uma.get(f"/api/apps/{app_id}")).json()["draft"]["pages"][0]["title"] == "我改过的标题" + async with SessionLocal() as session: + ops = list((await session.execute(select(BlueprintEvent.op).where(BlueprintEvent.blueprint_id == bp) + .order_by(BlueprintEvent.seq))).scalars()) + assert ops == ["save_personal", "save_personal"] + + +async def test_after_the_blueprint_changes_refresh_waits_for_a_new_save(): + _, c = await people() + await switch(True) + bp = await blueprint("uma") + app_id = await saved(c["uma"], bp) + draft = (await c["uma"].get(f"/api/apps/{app_id}")).json()["draft"] + draft["pages"][0]["title"] = "我改过的标题" + assert (await c["uma"].patch(f"/api/apps/{app_id}", json={"draft": draft})).status_code == 200 + + # 改了取数(节点还在,绑定都找得到):没重新存之前不刷新;重新存之后页面上改过的留着 + changed = copy.deepcopy(KPI) + changed["nodes"][1]["data"]["config"]["expression"] = "{'gmv': 99.0}" + async with SessionLocal() as session: + row = await session.get(Blueprint, bp) + row.graph, row.graph_hash = changed, graph_hash(changed) + await session.commit() + assert (await c["uma"].get(f"/api/apps/{app_id}")).json()["personal"]["graph_changed"] is True + r = await c["uma"].post(f"/api/apps/{app_id}/refresh") + assert r.status_code == 409 and r.json()["code"] == "personal.graph_changed" + await saved(c["uma"], bp) + detail = (await c["uma"].get(f"/api/apps/{app_id}")).json() + assert detail["draft"]["pins"][0]["graph_hash"] == graph_hash(changed) and detail["personal"]["graph_changed"] is False + assert detail["draft"]["pages"][0]["title"] == "我改过的标题" + run = await refreshed(c["uma"], app_id) + assert run.origin["graph_hash"] == graph_hash(changed) + + # 口径卡换了(原来的绑定找不到了):按新图重新派生,页面上不挂找不到数的块 + renamed = copy.deepcopy(changed) + renamed["nodes"][2]["id"] = "card2" + renamed["edges"] = [{"source": "fetch", "target": "card2"} if e["target"] == "card" else + {"source": "card2", "target": "out"} if e["source"] == "card" else e for e in renamed["edges"]] + async with SessionLocal() as session: + row = await session.get(Blueprint, bp) + row.graph, row.graph_hash = renamed, graph_hash(renamed) + await session.commit() + await saved(c["uma"], bp) + draft = (await c["uma"].get(f"/api/apps/{app_id}")).json()["draft"] + metrics = [n["bind"]["metric"] for page in draft["pages"] for n in walk(page["body"]) if n["type"] == "metric"] + assert metrics == ["card2.gmv"] + + +async def test_the_live_draft_only_takes_presentation_changes(): + _, c = await people() + await switch(True) + app_id = await saved(c["uma"], await blueprint("uma")) + draft = (await c["uma"].get(f"/api/apps/{app_id}")).json()["draft"] + + moved = copy.deepcopy(draft) + moved["pins"][0]["graph_hash"] = "0" * 64 + r = await c["uma"].patch(f"/api/apps/{app_id}", json={"draft": moved}) + assert r.status_code == 422 and "回到蓝图" in r.json()["detail"] + formal = copy.deepcopy(draft) + next(iter(formal["views"].values()))["source"] = {"kind": "latest_sealed", "pin": "main"} + assert (await c["uma"].patch(f"/api/apps/{app_id}", json={"draft": formal})).status_code == 422 + entry = {**copy.deepcopy(draft), "entries": [{"id": "go", "label": "发起", "pin": "main", "form": {}}]} + r = await c["uma"].patch(f"/api/apps/{app_id}", json={"draft": entry}) + assert r.status_code == 422 and "入口" in r.json()["detail"] + + # 个人应用不能分享,也没有发布 + r = await c["uma"].put(f"/api/apps/{app_id}/grants", json={"items": [ + {"principal_kind": "user", "principal": "ula", "role": "use"}]}) + assert r.status_code == 409 and r.json()["code"] == "personal.not_shareable" + r = await c["uma"].post(f"/api/apps/{app_id}/publish", json={}) + assert r.status_code == 409 and r.json()["code"] == "personal.not_shareable" + + +# -------------------------------------------------------------------------- +# 刷新 +# -------------------------------------------------------------------------- + + +async def test_refresh_is_masked_read_only_and_limited_per_person(): + from app.tools.datasource import MASK_RESULTS_OPTION, READ_ONLY_OPTION + + _, c = await people() + await switch(True, limit=2) + app_id = await saved(c["uma"], await blueprint("uma")) + r = await c["uma"].post(f"/api/apps/{app_id}/refresh") + assert r.status_code == 200 and r.json()["remaining"] == 1, r.text + run = await wait(r.json()["run_id"]) + assert (run.status, run.run_class, run.origin_kind, run.started_by, run.app_id) == ( + "succeeded", "exploratory", "personal_app", "uma", app_id) + assert run.options[MASK_RESULTS_OPTION] is True and run.options[READ_ONLY_OPTION] is True + assert run.memory_scope == "chat:uma", "记忆固定为拥有者自己的范围(同问数据)" + assert run.origin["graph_hash"] == graph_hash(KPI) and run.workflow_name == "我的周报" + + second = await c["uma"].post(f"/api/apps/{app_id}/refresh") + assert second.json()["remaining"] == 0 + await wait(second.json()["run_id"]) + third = await c["uma"].post(f"/api/apps/{app_id}/refresh") + assert third.status_code == 429 and third.json()["code"] == "personal.daily_limit", third.text + assert (await c["uma"].get(f"/api/apps/{app_id}")).json()["personal"]["remaining_today"] == 0 + + # 按人计:uma 用完了不影响 ula + other = await saved(c["ula"], await blueprint("ula")) + r = await c["ula"].post(f"/api/apps/{other}/refresh") + assert r.status_code == 200 and r.json()["remaining"] == 1 + await wait(r.json()["run_id"]) + + +async def test_a_refresh_in_flight_is_joined_and_inputs_follow_the_trial_rule(monkeypatch): + import app.blueprints.instantiate as instantiate + + _, c = await people() + await switch(True) + bp = await blueprint("uma") + app_id = await saved(c["uma"], bp) + async with SessionLocal() as session: + active = Run(workflow_name="我的周报", graph=KPI, status="running", origin_kind="personal_app", + origin={"graph_hash": graph_hash(KPI)}, app_id=app_id, started_by="uma") + session.add(active) + await session.commit() + active_id = active.id + left = (await c["uma"].get(f"/api/apps/{app_id}")).json()["personal"]["remaining_today"] + assert left == 199, "正在运行的那一次算今天的一次" + r = await c["uma"].post(f"/api/apps/{app_id}/refresh") + assert r.json() == {"run_id": active_id, "remaining": left}, "正在刷新:接上那一次,不另花一次" + async with SessionLocal() as session: + (await session.get(Run, active_id)).status = "cancelled" + await session.commit() + + # 输入和试运行同一个规则:按「多久更新」算出最近一期(blueprints/instantiate.trial_inputs) + seen = [] + + def latest_period(spec, **_): + seen.append(spec.get("purpose", {}).get("value")) + return {"week": "2026-W40"} + + monkeypatch.setattr(instantiate, "trial_inputs", latest_period) + r = await c["uma"].post(f"/api/apps/{app_id}/refresh") + run = await wait(r.json()["run_id"]) + assert run.input == {"week": "2026-W40"} and seen == ["每周看销售额"] + + +# -------------------------------------------------------------------------- +# 谁看得见 +# -------------------------------------------------------------------------- + + +async def test_only_the_owner_sees_a_personal_app(): + from app.auth import run_readable + + _, c = await people() + await switch(True) + app_id = await saved(c["uma"], await blueprint("uma")) + run = await refreshed(c["uma"], app_id) + for who in ("ula", "bob"): + assert (await c[who].get(f"/api/apps/{app_id}")).status_code == 404, who + assert (await c[who].get(f"/api/apps/{app_id}/pages/home")).status_code == 404, who + assert (await c[who].post(f"/api/apps/{app_id}/refresh")).status_code == 404, who + assert (await c[who].post(f"/api/apps/{app_id}/archive")).status_code == 404, who + assert app_id not in [a["id"] for a in (await c[who].get("/api/apps")).json()["items"]], who + mine = (await c["uma"].get("/api/apps?scope=personal")).json()["items"] + assert {a["scope"] for a in mine} == {"personal"} and {a["owner"] for a in mine} == {"uma"} + assert next(a["my_role"] for a in mine if a["id"] == app_id) == "manage" + assert app_id not in [a["id"] for a in (await c["uma"].get("/api/apps?scope=shared")).json()["items"]] + + def who(name: str) -> Principal: + return Principal(username=name, role="user", verified=True, mode="local") + + assert await run_readable(who("uma"), run.id) + assert not await run_readable(who("ula"), run.id), "别人读不了个人应用的刷新" + assert (await c["uma"].get(f"/api/runs/{run.id}/evidence")).status_code == 200 + assert (await c["ula"].get(f"/api/runs/{run.id}/evidence")).status_code == 403 + + +async def test_an_admin_sees_that_it_exists_and_can_archive_it_but_not_its_content(): + root, c = await people() + await switch(True) + app_id = await saved(c["uma"], await blueprint("uma")) + await refreshed(c["uma"], app_id) + for path in (f"/api/apps/{app_id}", f"/api/apps/{app_id}/pages/home", f"/api/apps/{app_id}/pages/home?draft=1", + f"/api/apps/{app_id}/candidates", f"/api/apps/{app_id}/versions"): + assert (await root.get(path)).status_code == 404, path + listed = next(a for a in (await root.get("/api/apps")).json()["items"] if a["id"] == app_id) + assert (listed["owner"], listed["scope"], listed["my_role"], listed["description"], listed["name"]) == ( + "uma", "personal", None, "", "我的周报") + r = await root.post(f"/api/apps/{app_id}/archive") + assert r.status_code == 200 and r.json()["status"] == "archived", r.text + assert "draft" not in r.json() and "personal" not in r.json() + r = await c["uma"].post(f"/api/apps/{app_id}/refresh") + assert r.status_code == 409 and "已归档" in r.json()["detail"] + + +# -------------------------------------------------------------------------- +# 提交审核、共享副本 +# -------------------------------------------------------------------------- + + +async def _user_id(name: str) -> str: + from app.db.models import User + + async with SessionLocal() as session: + return await session.scalar(select(User.id).where(User.username == name)) + + +async def test_review_gives_the_builder_a_shared_copy_and_leaves_the_original(monkeypatch): + import app.notify as notify + from app.blueprints.personal import review_published + from app.core.crypto import encrypt + from app.db.models_process import NotifyChannel + from app.notify.core import Outcome + from app.notify.service import drain + + _, c = await people() + await switch(True) + bp = await blueprint("uma") + app_id = await saved(c["uma"], bp) + to_bob = {"to": [{"kind": "user", "name": "bob"}], "note": "请帮我做成正式的周报"} + r = await c["uma"].post(f"/api/apps/{app_id}/submit-review", json=to_bob) + assert r.status_code == 409 and r.json()["code"] == "personal.no_run", "先成功刷新一次" + run = await refreshed(c["uma"], app_id) + r = await c["uma"].post(f"/api/apps/{app_id}/submit-review", json={"to": [{"kind": "user", "name": "ula"}]}) + assert r.status_code == 422 and r.json()["code"] == "personal.review_target", "只能交给搭建者" + r = await c["uma"].post(f"/api/apps/{app_id}/submit-review", json=to_bob) + assert r.status_code == 200, r.text + task_id = r.json()["task_id"] + again = await c["uma"].post(f"/api/apps/{app_id}/submit-review", json=to_bob) + assert again.status_code == 409 and again.json()["code"] == "personal.in_review" + + async with SessionLocal() as session: + task = await session.get(Task, task_id) + assert (task.kind, task.run_id, task.app_id, task.status) == ("review", run.id, app_id, "pending") + rows = list((await session.execute(select(TaskAssignment).where(TaskAssignment.task_id == task_id))).scalars()) + assert [(a.principal_kind, a.principal, a.source) for a in rows] == [("user", "bob", "review")] + assert (await session.get(Blueprint, bp)).status == "in_review" + before = copy.deepcopy((await session.get(App, app_id)).draft) + inbox = (await c["bob"].get("/api/tasks")).json()["items"] + mine = next(t for t in inbox if t["id"] == task_id) + assert mine["payload"]["kind"] == "review" and mine["payload"]["submitted_by"] == "uma" + assert mine["payload"]["note"] == "请帮我做成正式的周报" and mine["can_respond"] + + assert (await c["bea"].post(f"/api/blueprints/{bp}/copy")).status_code == 404, "没派给她的搭建者取不到" + assert (await c["uma"].post(f"/api/blueprints/{bp}/copy")).status_code == 403 + r = await c["bob"].post(f"/api/blueprints/{bp}/copy") + assert r.status_code == 201, r.text + dup = r.json() + assert (dup["copied_from"], dup["scope"], dup["owner"], dup["status"]) == (bp, "shared", "bob", "drafting") + assert dup["graph_hash"] == graph_hash(KPI) and dup["spec"]["purpose"]["value"] == "每周看销售额" + assert (await c["bob"].post(f"/api/blueprints/{bp}/copy")).json()["id"] == dup["id"], "再取是同一份" + async with SessionLocal() as session: + original = await session.get(Blueprint, bp) + assert original.status == "in_review" and original.scope == "personal" and original.graph == KPI + assert (await session.get(App, app_id)).draft == before, "原个人应用不动" + assert any(cp["id"] == dup["id"] for cp in (await c["bob"].get(f"/api/tasks/{task_id}")).json()["payload"]["copies"]) + + # 在待办里不能同意:要在副本上走发布单 + r = await c["bob"].post(f"/api/tasks/{task_id}/respond", json={"decision": "approve"}) + assert r.status_code == 422 and "共享副本" in r.json()["detail"], r.text + + # 发布单做完:待办记为已发布,提交人收到通知(他自己订阅了的个人渠道) + sent = [] + + async def fake_send(channel, message): + sent.append((channel.name, message)) + return Outcome(True, 200, 1, None) + + monkeypatch.setattr(notify, "send", fake_send) + async with SessionLocal() as session: + session.add(NotifyChannel(name="uma 的手机", scope="user", owner_id=await _user_id("uma"), + url=encrypt("https://example.com/hook"), events=["review.done"])) + await session.commit() + copy_row = await session.get(Blueprint, dup["id"]) + bob = Principal(username="bob", role="builder", verified=True, mode="local") + assert await review_published(session, copy_row, app_id="formal-app", principal=bob) == task_id + await drain() + assert [(name, m["title"]) for name, m in sent] == [("uma 的手机", "提交审核的「我的周报」已发布成正式应用")] + async with SessionLocal() as session: + task = await session.get(Task, task_id) + assert task.status == "resolved" and task.outcome["decision"] == "published" + assert task.outcome["app_id"] == "formal-app" and task.resolved_by == "bob" + assert (await session.get(Blueprint, bp)).status == "personal" + review = (await c["uma"].get(f"/api/apps/{app_id}")).json()["personal"]["review"] + assert (review["decision"], review["app_id"], review["status"]) == ("published", "formal-app", "resolved") + + +async def test_the_reviewer_can_send_it_back(): + from app.db.models import Group, GroupMember + + _, c = await people() + await switch(True) + async with SessionLocal() as session: + group = Group(name="搭建者组") + session.add(group) + await session.flush() + session.add(GroupMember(group_id=group.id, user_id=await _user_id("bob"))) + await session.commit() + bp = await blueprint("uma") + app_id = await saved(c["uma"], bp) + await refreshed(c["uma"], app_id) + r = await c["uma"].post(f"/api/apps/{app_id}/submit-review", json={"to": [{"kind": "group", "name": "搭建者组"}]}) + assert r.status_code == 200, r.text + task_id = r.json()["task_id"] + assert (await c["bea"].post(f"/api/tasks/{task_id}/respond", json={"decision": "reject"})).status_code == 403 + r = await c["bob"].post(f"/api/tasks/{task_id}/respond", json={"decision": "reject", "note": "口径要先和财务对一下"}) + assert r.status_code == 200 and r.json()["resolved"], r.text + review = (await c["uma"].get(f"/api/apps/{app_id}")).json()["personal"] + assert review["blueprint_status"] == "personal" + assert (review["review"]["decision"], review["review"]["note"]) == ("reject", "口径要先和财务对一下") + assert (await c["uma"].post(f"/api/apps/{app_id}/submit-review", json={ + "to": [{"kind": "user", "name": "bob"}]})).status_code == 200, "退回之后可以再提交" + + +# -------------------------------------------------------------------------- +# 解析:探索来源、印章、隐藏 +# -------------------------------------------------------------------------- + + +async def test_the_page_reads_the_latest_refresh_and_stamps_it_as_exploratory(): + _, c = await people() + await switch(True) + app_id = await saved(c["uma"], await blueprint("uma")) + page = (await c["uma"].get(f"/api/apps/{app_id}/pages/home")).json() + view = next(iter(page["sources"])) + assert page["sources"][view]["kind"] == "exploratory" and page["sources"][view]["state"] == "empty" + assert "刷新" in page["sources"][view]["message"] and page["problems"] == [] + assert page["app"]["needs_upgrade"] is False + + first = await refreshed(c["uma"], app_id) + page = (await c["uma"].get(f"/api/apps/{app_id}/pages/home")).json() + source = page["sources"][view] + assert (source["state"], source["run_id"]) == ("ok", first.id) + assert source["stamp"]["from"] == "探索 · 未经发布审核" and source["stamp"]["pin"] == "我的周报" + metric = next(n for n in walk(page["tree"]) if n["type"] == "metric") + assert metric["data"]["state"] == "ok" and metric["data"]["evidence"]["run_id"] == first.id + + # 趋势按每次刷新排(页面上加一块趋势是改呈现,可以直接改) + draft = (await c["uma"].get(f"/api/apps/{app_id}")).json()["draft"] + draft["pages"][0]["body"].append({"id": "trend", "type": "series", "bind": {"view": view, "series": "card.gmv"}}) + assert (await c["uma"].patch(f"/api/apps/{app_id}", json={"draft": draft})).status_code == 200 + second = await refreshed(c["uma"], app_id) + page = (await c["uma"].get(f"/api/apps/{app_id}/pages/home")).json() + trend = next(n for n in walk(page["tree"]) if n["id"] == "trend")["data"] + assert [p["run_id"] for p in trend["series"][0]["points"]] == [first.id, second.id] + assert trend["series"][0]["label"] == "每次刷新" and trend["state"] == "ok" + + # 最近一次刷新没成功:给上一次的结果,并写明 + async with SessionLocal() as session: + session.add(Run(workflow_name="我的周报", graph=KPI, status="failed", origin_kind="personal_app", + origin={"graph_hash": graph_hash(KPI)}, app_id=app_id, started_by="uma", + finished_at=utcnow() + timedelta(seconds=1))) + await session.commit() + source = (await c["uma"].get(f"/api/apps/{app_id}/pages/home")).json()["sources"][view] + assert source["run_id"] == second.id and "没有成功" in source["message"] + assert any("没有成功" in note for note in source["stamp"]["notes"]) + + +async def test_hidden_components_are_not_sent_but_the_editor_sees_them(): + _, c = await people() + await switch(True) + app_id = await saved(c["uma"], await blueprint("uma")) + await refreshed(c["uma"], app_id) + draft = (await c["uma"].get(f"/api/apps/{app_id}")).json()["draft"] + section = next(n for n in draft["pages"][0]["body"] if n["type"] == "section") + section["hidden"] = True + assert (await c["uma"].patch(f"/api/apps/{app_id}", json={"draft": draft})).status_code == 200 + page = (await c["uma"].get(f"/api/apps/{app_id}/pages/home")).json() + ids = {n["id"] for n in walk(page["tree"])} + assert section["id"] not in ids and not any(n["type"] == "metric" for n in walk(page["tree"])), "里面的也不下发" + editor = (await c["uma"].get(f"/api/apps/{app_id}/pages/home?draft=1")).json() + shown = next(n for n in walk(editor["tree"]) if n["id"] == section["id"]) + assert shown["hidden"] is True and any(n["type"] == "metric" for n in walk(shown["children"])) + + +async def test_hidden_components_are_skipped_in_shared_apps_too(): + """关登录:共享应用里隐藏了的组件同样不下发;只被它绑定的视图不取运行。""" + wf, hash_ = await _workflow(KPI) + spec = {"format": "agentlab.app/1", "name": "周报", + "pins": [{"alias": "main", "workflow_id": wf, "version": 1, "graph_hash": hash_, "use": "view"}], + "views": {"latest": {"source": {"kind": "latest_sealed", "pin": "main"}}, + "ask": {"source": {"kind": "on_demand", "pin": "main", "auto": True, "ttl_s": 60}}}, + "pages": [{"id": "home", "title": "首页", "body": [ + {"id": "stamp", "type": "stamp", "bind": {"view": "latest"}}, + {"id": "gone", "type": "metric", "hidden": True, "bind": {"view": "ask", "metric": "card.gmv"}}]}]} + async with _client() as client: + app_id = (await client.post("/api/apps", json={"name": "周报", "spec": spec})).json()["id"] + out = (await client.post(f"/api/apps/{app_id}/publish", json={})).json() + assert out["ok"], out + assert "app.hidden_bound" in {i["code"] for i in out["issues"]} + page = (await client.get(f"/api/apps/{app_id}/pages/home")).json() + assert [n["id"] for n in page["tree"]] == ["stamp"] and set(page["sources"]) == {"latest"}, \ + "按需视图只被隐藏的组件绑定:不取数、不自动发起" + async with SessionLocal() as session: + assert await session.scalar(select(Run.id).where(Run.app_id == app_id)) is None + + +# -------------------------------------------------------------------------- +# 页面编辑的候选 +# -------------------------------------------------------------------------- + + +def _client() -> AsyncClient: + from app.main import app + + return AsyncClient(transport=ASGITransport(app=app), base_url="http://test") + + +async def _workflow(graph: dict) -> tuple[str, str]: + async with SessionLocal() as session: + wf = Workflow(name=f"周报-{uuid.uuid4().hex[:6]}", graph=graph, status="published", published_version=1, + version=1) + session.add(wf) + await session.flush() + session.add(WorkflowVersion(workflow_id=wf.id, version=1, graph=graph, graph_hash=graph_hash(graph), + level="published", published_at=utcnow())) + await session.commit() + return wf.id, graph_hash(graph) + + +BOARD = chain( + node("start", "input", "开始", fields=[{"name": "week", "default": "2026-W41"}]), + node("q", "tool", "查订单", tool="db_query__shop", args={"sql": "SELECT SUM(amount) AS gmv FROM orders"}), + node("card", "metrics", "核心指标", caliber="周报口径", caliber_version="v1", + metrics=[{"id": "gmv", "name": "销售额", "unit": "元", "expression": "cell(nodes.q, 0, 'gmv')"}, + {"id": "orders", "name": "订单数", "expression": "cell(nodes.q, 0, 'gmv')"}]), + node("rep", "report", "周报"), + node("out", "output", "成果")) + + +async def test_candidates_list_what_can_be_added_from_the_pinned_version(): + from app.apps.lint import lint_app + from app.apps.ops import apply_app_op + + wf, _ = await _workflow(BOARD) + async with _client() as client: + spec = (await client.post("/api/apps/derive", json={"workflow_id": wf, "version": 1})).json()["spec"] + # 去掉派生出来的表格和一个指标:它们就该出现在候选里 + home = spec["pages"][0]["body"] + spec["pages"][0]["body"] = [n for n in home if n["type"] != "table"] + cols = next(n for n in walk(spec["pages"][0]["body"]) if n["type"] == "columns") + cols["children"] = [m for m in cols["children"] if m["bind"]["metric"] != "card.orders"] + app_id = (await client.post("/api/apps", json={"name": "周报", "spec": spec})).json()["id"] + items = (await client.get(f"/api/apps/{app_id}/candidates")).json()["items"] + got = {(i["kind"], i["label"], i["group"]) for i in items} + assert got == {("metric", "订单数", "核心指标"), ("series", "销售额的趋势", "核心指标"), + ("series", "订单数的趋势", "核心指标"), ("table", "查订单", "查订单")}, got + assert not any(i["kind"] == "report" for i in items), "报告块已经在页面上" + for cand in items: + draft = copy.deepcopy(spec) + assert apply_app_op(draft, {"op": "app_add", "parent": "home", "component": cand["component"]}).changed + async with SessionLocal() as session: + errors = [i for i in await lint_app(session, draft, {}) if i["level"] == "error"] + assert errors == [], (cand, errors) + + +async def test_candidates_need_manage_and_work_for_personal_apps(): + _, c = await people() + await switch(True) + app_id = await saved(c["uma"], await blueprint("uma")) + items = (await c["uma"].get(f"/api/apps/{app_id}/candidates")).json()["items"] + assert [(i["kind"], i["component"]["bind"]["series"]) for i in items] == [("series", "card.gmv")] + assert (await c["ula"].get(f"/api/apps/{app_id}/candidates")).status_code == 404 + + wf, _ = await _workflow(BOARD) + spec = (await c["bob"].post("/api/apps/derive", json={"workflow_id": wf, "version": 1})).json()["spec"] + shared = (await c["bob"].post("/api/apps", json={"name": "周报", "spec": spec})).json()["id"] + r = await c["bob"].put(f"/api/apps/{shared}/grants", json={"items": [ + {"principal_kind": "user", "principal": "ula", "role": "use"}]}) + assert r.status_code == 200, r.text + r = await c["ula"].get(f"/api/apps/{shared}/candidates") + assert r.status_code == 403, "只有使用权限的人不能改页面" + + +# -------------------------------------------------------------------------- +# 三条新检查 +# -------------------------------------------------------------------------- + + +async def test_the_three_new_checks_and_their_plain_wording(): + from app.apps.lint import lint_app + from app.plain import plain_of, with_plain + + def personal(bp_id: str, graph: dict, **extra) -> dict: + return {"format": "agentlab.app/1", "name": "我的", + "pins": [{"alias": "main", "blueprint": bp_id, "graph_hash": graph_hash(graph), "use": "view"}], + "views": {"v": {"source": {"kind": "exploratory", "pin": "main"}}}, + "pages": [{"id": "home", "title": "首页", "body": [{"id": "s", "type": "stamp", "bind": {"view": "v"}}]}], + **extra} + + def codes(issues, level=None): + return {i["code"] for i in issues if level is None or i["level"] == level} + + wf, hash_ = await _workflow(KPI) + shared = {"format": "agentlab.app/1", "name": "周报", + "pins": [{"alias": "main", "workflow_id": wf, "version": 1, "graph_hash": hash_}], + "views": {"v": {"source": {"kind": "exploratory", "pin": "main"}}}, + "pages": [{"id": "home", "title": "首页", "body": [{"id": "s", "type": "stamp", "bind": {"view": "v"}}]}]} + ok_bp = await blueprint("uma") + human_bp = await blueprint("uma", HUMAN) + async with SessionLocal() as session: + assert "app.view_source_personal" in codes(await lint_app(session, shared, {}), "error"), "共享应用不能取探索运行" + assert codes(await lint_app(session, personal(ok_bp, KPI), {}, scope="personal"), "error") == set() + formal = personal(ok_bp, KPI) + formal["views"]["v"]["source"] = {"kind": "latest_sealed", "pin": "main"} + assert "app.view_source_personal" in codes(await lint_app(session, formal, {}, scope="personal"), "error") + assert "app.pin_unpublished" in codes(await lint_app(session, personal(ok_bp, KPI), {}), "error"), \ + "共享应用不能固定蓝图" + + issues = await lint_app(session, personal(human_bp, HUMAN), {}, scope="personal") + policy = [i for i in issues if i["code"] == "personal.policy"] + assert policy and policy[0]["level"] == "error" and "「主管审批」" in policy[0]["message"] + with_entry = personal(ok_bp, KPI, entries=[{"id": "go", "label": "发起", "pin": "main", "form": {}}]) + assert any("入口" in i["message"] for i in await lint_app(session, with_entry, {}, scope="personal") + if i["code"] == "personal.policy") + + hidden = personal(ok_bp, KPI) + hidden["pages"][0]["body"][0]["hidden"] = True + bound = [i for i in await lint_app(session, hidden, {}, scope="personal") if i["code"] == "app.hidden_bound"] + assert [(i["level"], i["path"]) for i in bound] == [("warning", "pages[0].body[0].hidden")] + inside = personal(ok_bp, KPI) + inside["pages"][0]["body"] = [{"id": "box", "type": "section", "hidden": True, + "children": [{"id": "s", "type": "stamp", "bind": {"view": "v"}}]}] + assert "app.hidden_bound" in codes(await lint_app(session, inside, {}, scope="personal"), "warning"), \ + "放在隐藏的布局组件里也算" + twice = personal(ok_bp, KPI) + twice["pages"][0]["body"].append({"id": "s2", "type": "stamp", "bind": {"view": "v"}, "hidden": False}) + twice["pages"][0]["body"][0]["hidden"] = True + assert "app.hidden_bound" not in codes(await lint_app(session, twice, {}, scope="personal")) + + for code in ("app.view_source_personal", "app.hidden_bound", "personal.policy"): + assert plain_of(code) is not None, code + assert with_plain({"code": code})["plain"]["who"] == "you", code + + +# -------------------------------------------------------------------------- +# 复核修复:蓝图对话、审核待办补收、个人蓝图不建记录表、认人接口带开关 +# -------------------------------------------------------------------------- + + +async def test_a_users_blueprint_conversation_follows_the_blueprint(): + """使用者没开问数据也读得到自己蓝图的对话(按蓝图判,不走问数据的路由);别人的个人蓝图的对话,搭建者也读不到、 + 列表里也不列。认人接口带上个人应用的开关,新建应用的入口按它给。""" + _, c = await people() + assert (await c["uma"].get("/api/auth/me")).json()["user_personal_apps"] is False + await switch(True) + assert (await c["uma"].get("/api/auth/me")).json()["user_personal_apps"] is True + r = await c["uma"].post("/api/blueprints", json={"source": {"kind": "conversation"}, "scope": "personal", + "name": "我的退款周报"}) + assert r.status_code == 201, r.text + bp = r.json() + got = await c["uma"].get(f"/api/blueprints/{bp['id']}/conversation") + assert got.status_code == 200 and got.json()["id"] == bp["conversation_id"], got.text + assert (await c["uma"].get(f"/api/conversations/{bp['conversation_id']}")).status_code == 403, "问数据没开" + assert (await c["bob"].get(f"/api/conversations/{bp['conversation_id']}")).status_code == 404 + assert (await c["bob"].get(f"/api/blueprints/{bp['id']}/conversation")).status_code == 404 + listed = (await c["bob"].get("/api/conversations", params={"kind": "blueprint"})).json() + assert bp["conversation_id"] not in {x["id"] for x in listed} + + +async def test_a_review_left_open_by_a_failed_close_is_settled_when_someone_looks(monkeypatch): + """副本已经发布、原蓝图的审核待办却还挂着(发布单做完时没能结束它):拥有者打开个人应用时补上,记为已发布、处理人是 + 发布那份副本的人,原蓝图回到「个人应用」。""" + _, c = await people() + await switch(True) + bp = await blueprint("uma") + app_id = await saved(c["uma"], bp) + await refreshed(c["uma"], app_id) + r = await c["uma"].post(f"/api/apps/{app_id}/submit-review", json={"to": [{"kind": "user", "name": "bob"}]}) + task_id = r.json()["task_id"] + dup = (await c["bob"].post(f"/api/blueprints/{bp}/copy")).json() + async with SessionLocal() as session: + copy_row = await session.get(Blueprint, dup["id"]) + copy_row.status, copy_row.app_id = "published", "formal-app" + await session.commit() + assert (await session.get(Task, task_id)).status == "pending" + state = (await c["uma"].get(f"/api/apps/{app_id}")).json()["personal"] + assert state["blueprint_status"] == "personal" + assert (state["review"]["decision"], state["review"]["app_id"]) == ("published", "formal-app") + async with SessionLocal() as session: + task = await session.get(Task, task_id) + assert task.status == "resolved" and task.resolved_by == "bob" + from app.notify.service import drain + + await drain() + + +async def test_a_personal_blueprint_never_creates_a_records_table(): + """填报登记不能做成个人应用(只读,建了表也没人写):个人蓝图检查报 bp.template_mismatch;实例化、填关节这些地方也不替 + 个人蓝图建记录表、登记全局数据源。""" + from app.blueprints.ops import blueprint_issues + from app.blueprints.store import instantiate_context + from app.blueprints.templates._common import EXTRAS + from app.db.models import DataSource + from app.db.models_blueprints import RecordsTable + + spec = EXTRAS["records"].example() + assert any(i["code"] == "bp.template_mismatch" and i["path"] == "/template" + for i in blueprint_issues(spec, for_="personal")) + async with SessionLocal() as session: + row = Blueprint(name="我的报损", owner="uma", scope="personal", status="drafting", spec=spec, + template_id="records", template_version=1, source={"kind": "template"}) + session.add(row) + await session.flush() + sources = int(await session.scalar(select(func.count(DataSource.id))) or 0) + ctx = await instantiate_context(session, row, create_records=True) + await session.commit() + assert "records" not in ctx + assert not (await session.execute(select(RecordsTable).where(RecordsTable.table_key == row.id))).first() + assert int(await session.scalar(select(func.count(DataSource.id))) or 0) == sources diff --git a/backend/tests/test_plain_layer.py b/backend/tests/test_plain_layer.py new file mode 100644 index 00000000..5c5357c6 --- /dev/null +++ b/backend/tests/test_plain_layer.py @@ -0,0 +1,151 @@ +"""白话层(docs/design/normal-user-apps.md N10,app/plain.py)和反问收尾的服务端部分(N11、G6)。 + +- 覆盖:代码里出现的问题编号(工作流发布门禁 contract.* / governed.* / action.* / process.*、子工作流和口径卡固定的版本、 + 应用检查 app.*、蓝图 bp.*、模板 tpl.*、个人应用 personal.*、发布单 plan.*)都要有白话。B1、B3、B4 新增的编号由各包 + 自己补;这里扫的是代码里实际出现的全部编号,报出没有白话的那几个; +- 谁来改(who):要管理员的编号 → admin;自动修复给的是 choice → you,auto / assist → assistant;应用检查只有人能处理的 + (APP_HUMAN_ONLY)→ you,其余 → assistant。白话里登记的那一档和这条规则一致(一种说法,P5); +- 文案:白话里不写「钉住」、不裸写配置键名(check-copy 同一套规则在 scripts/check-copy.mjs 里扫); +- 反问收尾:只问不改的一轮记进历史时,下一轮的上下文写「助手反问了什么」,不写「没有结果」;只问了一句的那一轮记的 + 空图不算「上一轮的图」。 +""" +from __future__ import annotations + +import re +from pathlib import Path + +import pytest + +from app.db import models # noqa: F401 - 建表要先登记全部模型(conftest 按 Base.metadata 建表) +from app.plain import ADMIN_CODES, PLAIN, PLAIN_PREFIX, plain_of, who_of, with_plain + +APP = Path(__file__).resolve().parent.parent / "app" +#: 白话层要覆盖的编号前缀 +PREFIXES = ("contract", "governed", "action", "process", "app", "bp", "tpl", "personal", "plan") +_CODE = r"((?:%s)\.[a-z_]+)" % "|".join(PREFIXES) +#: 问题编号在代码里出现的几种写法:code="x"、"code": "x"、out.error("x"、add("x"、flag 的元组写法、 +#: 异常类的默认编号、模块级常量(PERSONAL_OFF = "personal.off") +PATTERNS = [ + re.compile(r'\bcode\s*=\s*"%s"(?!\s*,\s*")' % _CODE), + re.compile(r'"code"\s*:\s*"%s"' % _CODE), + re.compile(r'\.(?:error|warning|info)\(\s*"%s"' % _CODE), + re.compile(r'\badd\(\s*"%s"' % _CODE), + re.compile(r'\bcode\s*=\s*"[^"]*",\s*"%s"' % _CODE), + re.compile(r'\bcode\s*:\s*str\s*=\s*"%s"' % _CODE), + re.compile(r'^[A-Z][A-Z0-9_]*\s*(?::\s*\w+\s*)?=\s*"%s"' % _CODE, re.M), + re.compile(r'Refused\([^)]*?"%s"\s*\)' % _CODE), +] +#: 不是问题编号的同名写法:运行事件的种类(core/events.py 的 action.sent 一类) +SKIP_FILES = {APP / "core" / "events.py"} + + +def codes_in_code() -> dict[str, str]: + """代码里出现的问题编号 → 第一次出现在哪个文件。""" + out: dict[str, str] = {} + for path in sorted(APP.rglob("*.py")): + if path in SKIP_FILES: + continue + text = path.read_text(encoding="utf-8") + for pattern in PATTERNS: + for code in pattern.findall(text): + out.setdefault(code, str(path.relative_to(APP))) + return out + + +def test_the_scan_finds_codes_in_every_family(): + found = codes_in_code() + for code in ("contract.required_missing", "contract.report_from_invalid", "governed.metric_untraced", + "action.prod_missing", "process.human_in_subgraph", "app.text_number", "app.acl_empty", + "app.polish_refused", "plan.graph_changed", "plan.preflight", "bp.refused"): + assert code in found, code + # 事件种类不是问题编号 + assert "action.sent" not in found + + +def test_every_problem_code_in_the_code_has_a_plain_wording(): + missing = {code: where for code, where in codes_in_code().items() if plain_of(code) is None} + assert not missing, "这些问题编号还没有白话(app/plain.py):" + ";".join( + f"{code}({where})" for code, where in sorted(missing.items())) + + +def test_subgraph_and_caliber_version_codes_have_plain_wording(): + from app.apps.versions import CALIBER_RETIRED, CALIBER_UNPUBLISHED, SUBGRAPH_RETIRED, SUBGRAPH_UNPUBLISHED + + for code in (SUBGRAPH_UNPUBLISHED, SUBGRAPH_RETIRED, CALIBER_UNPUBLISHED, CALIBER_RETIRED): + assert plain_of(code) is not None, code + + +#: 工作流发布门禁、应用检查、发布单的白话(包 B2 写的):一句话、为什么要紧、怎么办三样都要有 +FULL = ("contract.", "governed.", "action.", "process.", "app.", "plan.", "subgraph_version_", "caliber_version_") + + +def test_every_plain_wording_is_complete_and_follows_the_copy_rules(): + keys = ("report_from", "metrics_from", "caliber_from", "on_timeout", "assignee", "upgrade_policy", + "evidence_role", "output_schema", "cite_fields") + for code, plain in [*PLAIN.items(), *PLAIN_PREFIX.items()]: + assert plain.title and plain.action, code + assert plain.why or not code.startswith(FULL), code + assert plain.who in ("you", "assistant", "admin"), code + text = plain.title + plain.why + plain.action + assert "钉" not in text and "跑" not in text, code + assert not any(k in text for k in keys), code + # 中文句子用全角标点 + assert not re.search(r"[一-鿿][,;:?!]|[,;:?!][一-鿿]", text), code + + +def test_who_follows_one_rule(): + from app.api.copilot_gen import APP_HUMAN_ONLY + + # 应用检查(apps/lint.py 报的)在白话里登记的那一档:只有人能处理的「你来定」,其余「助手可以修」(助手的自查修它们) + lint = {code for code, where in codes_in_code().items() if where == "apps/lint.py"} + for code in lint: + assert PLAIN[code].who == ("you" if code in APP_HUMAN_ONLY else "assistant"), code + assert who_of({"code": "app.slot_unbound"}) == "you" + assert who_of({"code": "app.text_number"}) == "assistant" + # 自动修复给的种类:要人选的你来定,能自动修、能交给助手的助手可以修 + assert who_of({"code": "contract.required_missing", "fix_kind": "choice"}) == "you" + assert who_of({"code": "governed.subgraph_unpinned", "fix_kind": "auto"}) == "assistant" + assert who_of({"code": "governed.supervisor", "fix_kind": "assist"}) == "assistant" + # 要管理员的:端点、能力登记、受管级和降级的发布 + assert {"action.prod_missing", "action.reconcile_unplanned", "plan.admin_required", "plan.downgrade_admin"} \ + <= ADMIN_CODES + assert who_of({"code": "action.prod_missing", "fix_kind": "assist"}) == "admin" + # 没登记白话的:照旧显示技术说法(不补 plain) + issue = {"code": "no.such_code", "message": "x"} + assert with_plain(issue) is issue + out = with_plain({"code": "subgraph_version_retired", "message": "x"}) + assert out["plain"]["title"] and out["plain"]["who"] == "you" + + +@pytest.fixture +async def conversation(): + from app.db.base import SessionLocal + from app.db.models import Conversation, ConversationTurn + + async with SessionLocal() as session: + conv = Conversation(title="反问") + session.add(conv) + await session.flush() + session.add(ConversationTurn(conversation_id=conv.id, seq=1, question="订单金额", answer="", status="done", + graph={"nodes": [], "edges": []}, + meta={"asked": {"question": "按下单时间还是付款时间算?", + "options": ["下单时间", "付款时间"]}})) + # 问数据页的写法:meta.asked 只记 true,问题写在这一轮的答案里 + session.add(ConversationTurn(conversation_id=conv.id, seq=2, question="付款时间", status="done", + answer="要不要去掉已退款的订单?", meta={"asked": True})) + await session.commit() + return conv.id + + +async def test_history_says_what_the_assistant_asked(conversation): + from app.api.copilot import _history_section, _previous_graph + from app.db.base import SessionLocal + + async with SessionLocal() as session: + text = await _history_section(session, conversation) + previous = await _previous_graph(session, conversation) + assert "助手反问" in text and "按下单时间还是付款时间算?" in text and "下单时间、付款时间" in text + assert "(助手反问,等用户回答:要不要去掉已退款的订单?)" in text + assert "(没有结果)" not in text + # 只问了一句的那一轮记的是空图:不算「上一轮的图」 + assert previous is None and "上一轮用的工作流" not in text diff --git a/backend/tests/test_publish_plan.py b/backend/tests/test_publish_plan.py new file mode 100644 index 00000000..c1a30a48 --- /dev/null +++ b/backend/tests/test_publish_plan.py @@ -0,0 +1,653 @@ +"""一次确认发布:发布单(docs/design/normal-user-apps.md N5、§3.6,包 B2 的 blueprints/publish_plan.py)。 + +- 顺利走完:出单只读(什么都没建)、九步依次做完——存版本(工作流记下出自哪个蓝图)、预检、发布工作流、建定时任务 + (先停用)、建应用(钉住项换成发布的那一版、视图绑定时任务)、发布应用、启用定时任务、授权、跑第一次(按定时任务触发), + 每步留痕、审计写 publish_plan.*,蓝图记「已发布」; +- 预检挡住时什么都没写:连工作流版本都不存,没有定时任务、没有应用; +- 流程类岗位没绑人:预检报 app.slot_unbound,白话写「你来定」; +- 中途失败后接着做:停在那一步、写明原因(工作流已发布,应用还没有);接着做从那一步开始,已完成的按 id 核对、不重做; + 前面建的东西不见了,接着做停下、不另建一份; +- 受管级要管理员:搭建者出单时问题里写「要找管理员」,执行 403; +- 图变了拒绝执行(plan.graph_changed);发布的图和最近一次试运行的不同,照实提醒(plan.trial_differs,不拦)。 +""" +from __future__ import annotations + +import uuid + +import pytest +from httpx import ASGITransport, AsyncClient +from sqlalchemy import func, select + +from app.db.base import SessionLocal +from app.db.models import AppGrant, AuditEvent, Run, Schedule, Workflow, WorkflowVersion +from app.db.models_apps import App, AppVersion +from app.db.models_blueprints import Blueprint +from app.engine.runner import run_manager +from app.main import app +from tests import blueprint_samples as s +from tests.fakes import auth_env + +ACTOR = {"X-Actor": "builder1"} + + +@pytest.fixture(autouse=True) +async def engine_up(): + await run_manager.setup() + yield + await run_manager.shutdown() + + +@pytest.fixture +async def client(): + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test", headers=ACTOR) as c: + yield c + + +async def _count(model) -> int: + async with SessionLocal() as session: + return int(await session.scalar(select(func.count()).select_from(model)) or 0) + + +async def _board_from_run(client, tmp_path, *, access: dict | None = None, cadence: dict | None = None, + trial: bool = True) -> dict: + """问数据的一轮回答(看板图)→ 蓝图(自由形)→ 卡片填好 →(试运行)。""" + source = await s.register_source(s.make_source(tmp_path)) + run = await run_manager.start(graph=s.board_graph(source), input_payload=s.PERIOD, started_by="builder1", + run_class="exploratory", origin_kind="chat") + assert (await s.wait(run.id)).status == "succeeded" + r = await client.post("/api/blueprints", json={"source": {"kind": "run", "id": run.id}, "scope": "shared", + "name": f"门店周报-{uuid.uuid4().hex[:4]}"}) + assert r.status_code == 201, r.text + bp = r.json() + await s.edit_spec(bp["id"], purpose=s.item("每周一看上周销售额"), cadence=s.item(cadence or s.WEEKLY), + access=access or {"use": [{"kind": "user", "name": "zhang"}, {"kind": "group", "name": "门店"}], + "observe": [], "manage": []}) + if trial: + r = await client.post(f"/api/blueprints/{bp['id']}/trial", json={"inputs": s.PERIOD}) + assert r.status_code == 200, r.text + assert (await s.wait(r.json()["run_id"])).status == "succeeded" + else: + r = await client.post(f"/api/blueprints/{bp['id']}/instantiate") + assert r.status_code == 200, r.text + return (await client.get(f"/api/blueprints/{bp['id']}")).json() + + +def _steps(plan: dict) -> dict: + return {st["kind"]: st for st in plan["steps"]} + + +async def test_a_plan_runs_all_nine_steps(client, tmp_path): + bp = await _board_from_run(client, tmp_path) + workflows, schedules, apps = await _count(Workflow), await _count(Schedule), await _count(App) + + r = await client.post(f"/api/blueprints/{bp['id']}/publish-plan", json={"level": "published"}) + assert r.status_code == 200, r.text + plan = r.json() + assert plan["ok"] is True and plan["status"] == "planned", plan["problems"] + assert [st["kind"] for st in plan["steps"]] == ["save_version", "preflight", "publish_workflow", "create_schedule", + "create_app", "publish_app", "enable_schedule", "grant", + "first_run"] + assert all(st["status"] == "pending" for st in plan["steps"]) + assert plan["options"]["first_run"] is True and plan["graph_hash"] == bp["graph_hash"] + summary = {x["step"]: x["text"] for x in plan["summary"]} + assert "每周一 09:00" in summary["create_schedule"] and "zhang" in summary["grant"] and "门店(组)" in summary["grant"] + assert not [p for p in plan["problems"] if p["level"] == "error"] + # 出单只读:什么都没建 + assert (await _count(Workflow), await _count(Schedule), await _count(App)) == (workflows, schedules, apps) + + r = await client.post(f"/api/publish-plans/{plan['id']}/run") + assert r.status_code == 200, r.text + done = r.json() + assert done["status"] == "done", done["steps"] + steps = _steps(done) + assert all(st["status"] == "done" for st in steps.values()) + + row = await s.blueprint(bp["id"]) + assert row.status == "published" and row.workflow_id and row.app_id + async with SessionLocal() as session: + wf = await session.get(Workflow, row.workflow_id) + version = (await session.execute(select(WorkflowVersion).where( + WorkflowVersion.workflow_id == wf.id))).scalars().one() + schedule = await session.get(Schedule, steps["create_schedule"]["result"]["schedule_id"]) + application = await session.get(App, row.app_id) + published = (await session.execute(select(AppVersion).where( + AppVersion.app_id == application.id))).scalars().one() + grants = {(g.principal_kind, g.principal, g.role) for g in (await session.execute( + select(AppGrant).where(AppGrant.app_id == application.id))).scalars()} + audits = [a.action for a in (await session.execute(select(AuditEvent).where( + AuditEvent.subject_id == plan["id"]).order_by(AuditEvent.at))).scalars()] + # 存版本:工作流记下出自哪个蓝图、哪个模板、哪次运行;发布的就是蓝图的那张图 + assert wf.origin["blueprint_id"] == bp["id"] and wf.origin["template"] == "freeform@1" and wf.origin["run_id"] + assert wf.published_version == 1 and version.level == "published" and version.graph_hash == bp["graph_hash"] + # 定时任务:正式运行、跑这个工作流,应用发布后启用 + assert schedule.workflow_id == wf.id and schedule.run_class == "formal" and schedule.enabled is True + assert set(schedule.input_template) == {"period", "period_start", "period_end"} + # 应用:出自这个蓝图,引用发布的那一版,看板视图只看定时任务出的数 + assert application.blueprint_id == bp["id"] and application.published_version == 1 + pin = published.pins[0] + assert (pin["workflow_id"], pin["version"], pin["graph_hash"]) == (wf.id, 1, bp["graph_hash"]) + assert published.spec["views"]["latest"]["source"]["from"] == f"schedule:{schedule.id}" + assert grants == {("user", "zhang", "use"), ("group", "门店", "use")} + assert audits[0] == "publish_plan.plan" and audits[1] == "publish_plan.start" + assert audits.count("publish_plan.step") == 9 and audits[-1] == "publish_plan.done" + + # 跑第一次:按定时任务触发,应用一打开就有数 + first = await s.wait(steps["first_run"]["result"]["run_id"]) + assert first.status == "succeeded" and first.schedule_id == schedule.id and first.run_class == "formal" + r = await client.get(f"/api/apps/{application.id}/pages/home") + assert r.status_code == 200, r.text + stamp = next(n for n in r.json()["tree"] if n["type"] == "stamp")["data"]["stamp"] + assert stamp["from"].startswith("定时任务") + + # 做完了的单不能再执行 + r = await client.post(f"/api/publish-plans/{plan['id']}/run") + assert r.status_code == 409 and r.json()["code"] == "plan_state" + + +async def test_preflight_blocks_and_nothing_is_written(client, tmp_path): + bp = await _board_from_run(client, tmp_path, cadence={**s.WEEKLY, "tz": "Mars/Olympus"}, trial=False) + workflows, schedules, apps = await _count(Workflow), await _count(Schedule), await _count(App) + plan = (await client.post(f"/api/blueprints/{bp['id']}/publish-plan", json={"level": "published"})).json() + assert plan["ok"] is False + codes = {p["code"]: p for p in plan["problems"]} + assert codes["plan.schedule_invalid"]["level"] == "error" and codes["plan.schedule_invalid"]["plain"]["title"] + # 没试运行过:照实提醒,不拦 + assert codes["plan.untrialed"]["level"] == "warning" + + r = await client.post(f"/api/publish-plans/{plan['id']}/run") + assert r.status_code == 200, r.text + stopped = r.json() + steps = _steps(stopped) + assert stopped["status"] == "stopped" and stopped["ok"] is False + assert steps["preflight"]["status"] == "failed" and steps["preflight"]["error_code"] == "plan.preflight" + assert "什么都没写" in steps["preflight"]["message"] + assert all(st["status"] in ("pending", "skipped") for k, st in steps.items() if k != "preflight") + # 什么都没写:连工作流版本都没存,没有定时任务、没有应用 + assert (await _count(Workflow), await _count(Schedule), await _count(App)) == (workflows, schedules, apps) + assert (await s.blueprint(bp["id"])).workflow_id is None + + +async def test_a_process_with_an_unbound_step_stops_at_preflight(client): + wf_id = await s.published_workflow(s.expense_graph(), f"报销-{uuid.uuid4().hex[:4]}", description="报销审批") + bp = (await client.post("/api/blueprints", json={"source": {"kind": "workflow_version", "id": wf_id}, + "scope": "shared"})).json() + await s.edit_spec(bp["id"], purpose=s.item("报销审批")) + assert (await client.post(f"/api/blueprints/{bp['id']}/instantiate")).status_code == 200 + plan = (await client.post(f"/api/blueprints/{bp['id']}/publish-plan", json={"level": "published"})).json() + assert plan["ok"] is False + unbound = [p for p in plan["problems"] if p["code"] == "app.slot_unbound"] + assert unbound and unbound[0]["plain"]["who"] == "you" and "谁来做" in unbound[0]["plain"]["action"] + # 流程类不跑第一次;已发布的那一版按哈希复用,不另存 + assert plan["options"]["first_run"] is False + summary = {x["step"]: x["text"] for x in plan["summary"]} + assert "沿用" in summary["save_version"] and "流程类" in summary["first_run"] + + +async def test_a_failed_step_stops_and_resume_does_not_redo_what_is_done(client, tmp_path, monkeypatch): + from app.blueprints import publish_plan as plans + + bp = await _board_from_run(client, tmp_path) + original = plans._STEPS["publish_app"] + calls = {"n": 0} + + async def flaky(session, ctx): + calls["n"] += 1 + if calls["n"] == 1: + raise plans.StepFailed(plans.APP_PUBLISH, "工作流已经发布,应用没有通过检查、还没有发布;使用者暂时看不到它") + return await original(session, ctx) + + monkeypatch.setitem(plans._STEPS, "publish_app", flaky) + plan = (await client.post(f"/api/blueprints/{bp['id']}/publish-plan", json={"level": "published"})).json() + stopped = (await client.post(f"/api/publish-plans/{plan['id']}/run")).json() + steps = _steps(stopped) + assert stopped["status"] == "stopped" + assert [k for k, st in steps.items() if st["status"] == "done"] == [ + "save_version", "preflight", "publish_workflow", "create_schedule", "create_app"] + assert steps["publish_app"]["status"] == "failed" and steps["publish_app"]["error_code"] == "plan.app_publish" + assert steps["publish_app"]["message"].startswith("工作流已经发布") + # 中途停下的状态无害:定时任务停用着、应用停在草稿、没授权 + async with SessionLocal() as session: + schedule = await session.get(Schedule, steps["create_schedule"]["result"]["schedule_id"]) + application = await session.get(App, steps["create_app"]["result"]["app_id"]) + grants = (await session.execute(select(AppGrant).where(AppGrant.app_id == application.id))).scalars().all() + assert schedule.enabled is False and schedule.next_run_at is None + assert application.published_version is None and not grants + # 停下的单不能「执行」,要「接着做」 + r = await client.post(f"/api/publish-plans/{plan['id']}/run") + assert r.status_code == 409 and r.json()["code"] == "plan_state" + + versions, schedules, apps = await _count(WorkflowVersion), await _count(Schedule), await _count(App) + r = await client.post(f"/api/publish-plans/{plan['id']}/resume") + assert r.status_code == 200, r.text + done = r.json() + assert done["status"] == "done", done["steps"] + again = _steps(done) + # 已完成的按 id 核对、不重做:同一个工作流版本、同一个定时任务、同一个应用 + for kind in ("save_version", "create_schedule", "create_app"): + assert again[kind]["result"] == steps[kind]["result"] + assert (await _count(WorkflowVersion), await _count(Schedule), await _count(App)) == (versions, schedules, apps) + async with SessionLocal() as session: + schedule = await session.get(Schedule, steps["create_schedule"]["result"]["schedule_id"]) + application = await session.get(App, steps["create_app"]["result"]["app_id"]) + assert schedule.enabled is True and application.published_version == 1 + await s.wait(again["first_run"]["result"]["run_id"]) + + +async def test_resume_stops_when_something_done_is_gone(client, tmp_path, monkeypatch): + from app.blueprints import publish_plan as plans + + bp = await _board_from_run(client, tmp_path) + + async def broken(session, ctx): + raise plans.StepFailed(plans.APP_PUBLISH, "工作流已经发布,应用还没有") + + monkeypatch.setitem(plans._STEPS, "publish_app", broken) + plan = (await client.post(f"/api/blueprints/{bp['id']}/publish-plan", json={"level": "published"})).json() + stopped = (await client.post(f"/api/publish-plans/{plan['id']}/run")).json() + schedule_id = _steps(stopped)["create_schedule"]["result"]["schedule_id"] + async with SessionLocal() as session: + await session.delete(await session.get(Schedule, schedule_id)) + await session.commit() + schedules = await _count(Schedule) + again = (await client.post(f"/api/publish-plans/{plan['id']}/resume")).json() + steps = _steps(again) + assert again["status"] == "stopped" + assert steps["create_schedule"]["status"] == "failed" + assert steps["create_schedule"]["error_code"] == "plan.object_missing" + # 不另建一份;这份单不能再接着做,要重新出单 + assert await _count(Schedule) == schedules + r = await client.post(f"/api/publish-plans/{plan['id']}/resume") + assert r.status_code == 409 and r.json()["code"] == "plan.object_missing" + + +async def test_a_changed_graph_refuses_to_run(client, tmp_path): + bp = await _board_from_run(client, tmp_path) + plan = (await client.post(f"/api/blueprints/{bp['id']}/publish-plan", json={"level": "published"})).json() + # 出单之后改了图(卡片改了、重新实例化) + async with SessionLocal() as session: + row = await session.get(Blueprint, bp["id"]) + graph = {**row.graph, "nodes": [{**n, "data": {**n["data"], "label": "改过的"}} if n["id"] == "done" else n + for n in row.graph["nodes"]]} + row.graph = graph + await session.commit() + assert (await client.post(f"/api/blueprints/{bp['id']}/instantiate")).status_code == 200 + r = await client.post(f"/api/publish-plans/{plan['id']}/run") + assert r.status_code == 409 and r.json()["code"] == "plan.graph_changed" + assert (await s.blueprint(bp["id"])).workflow_id is None + + # 重新出单:发布的图和最近一次试运行的不同,照实提醒(不拦) + plan = (await client.post(f"/api/blueprints/{bp['id']}/publish-plan", json={"level": "published"})).json() + differs = [p for p in plan["problems"] if p["code"] == "plan.trial_differs"] + assert differs and differs[0]["level"] == "warning" and plan["ok"] is True + + +@pytest.fixture +async def login(): + await auth_env.reset() + try: + yield + finally: + await auth_env.reset() + + +async def test_governed_plans_need_an_admin(login, tmp_path): + admin = await auth_env.turn_on_local() + u = uuid.uuid4().hex[:6] + await auth_env.make_user(f"zhao{u}", "builder") + builder = await auth_env.login(f"zhao{u}") + source = await s.register_source(s.make_source(tmp_path)) + wf_id = await s.published_workflow(s.board_graph(source), f"周报-{u}", description="每周看上周销售额") + bp = (await builder.post("/api/blueprints", json={"source": {"kind": "workflow_version", "id": wf_id}, + "scope": "shared"})).json() + await s.edit_spec(bp["id"], purpose=s.item("每周看上周销售额")) + assert (await builder.post(f"/api/blueprints/{bp['id']}/instantiate")).status_code == 200 + + plan = (await builder.post(f"/api/blueprints/{bp['id']}/publish-plan", json={"level": "governed"})).json() + admin_only = [p for p in plan["problems"] if p["code"] == "plan.admin_required"] + assert plan["ok"] is False and admin_only and admin_only[0]["plain"]["who"] == "admin" + r = await builder.post(f"/api/publish-plans/{plan['id']}/run") + assert r.status_code == 403 and r.json()["code"] == "admin_only" + # 管理员出的受管级单子不报这一条 + plan = (await admin.post(f"/api/blueprints/{bp['id']}/publish-plan", json={"level": "governed"})).json() + assert not [p for p in plan["problems"] if p["code"] == "plan.admin_required"] + # 使用者看不到发布单 + await auth_env.make_user(f"lee{u}", "user") + user = await auth_env.login(f"lee{u}") + assert (await user.get(f"/api/publish-plans/{plan['id']}")).status_code == 403 + + +async def test_runs_launched_by_a_plan_are_formal_and_from_the_published_version(client, tmp_path): + """看板没有定时任务时,跑第一次从发布的那一版发起正式运行(来源 launcher)。""" + bp = await _board_from_run(client, tmp_path) + await s.edit_spec(bp["id"], cadence=s.item(None, status="missing")) + assert (await client.post(f"/api/blueprints/{bp['id']}/instantiate")).status_code == 200 + plan = (await client.post(f"/api/blueprints/{bp['id']}/publish-plan", json={"level": "published"})).json() + steps = _steps(plan) + assert steps["create_schedule"]["status"] == "skipped" and steps["enable_schedule"]["status"] == "skipped" + done = (await client.post(f"/api/publish-plans/{plan['id']}/run")).json() + assert done["status"] == "done", done["steps"] + run = await s.wait(_steps(done)["first_run"]["result"]["run_id"]) + async with SessionLocal() as session: + row = await session.get(Run, run.id) + assert row.run_class == "formal" and row.version == 1 and row.origin_kind == "launcher" + + +async def test_a_published_review_copy_closes_the_review(client, tmp_path, monkeypatch): + """审核副本(个人应用提交审核,搭建者在副本上走发布单)做完之后,原蓝图的审核待办记为已发布(blueprints/personal.py)。""" + from app.blueprints import personal + + bp = await _board_from_run(client, tmp_path) + async with SessionLocal() as session: + row = await session.get(Blueprint, bp["id"]) + row.copied_from = "original-bp" + await session.commit() + seen = [] + + async def published(session, blueprint, *, app_id, principal): + seen.append((blueprint.id, app_id, principal.username)) + return "task-1" + + monkeypatch.setattr(personal, "review_published", published) + plan = (await client.post(f"/api/blueprints/{bp['id']}/publish-plan", json={"level": "published", + "first_run": False})).json() + done = (await client.post(f"/api/publish-plans/{plan['id']}/run")).json() + assert done["status"] == "done" and _steps(done)["first_run"]["status"] == "skipped" + assert seen == [(bp["id"], _steps(done)["create_app"]["result"]["app_id"], "builder1")] + + +async def test_publishing_again_upgrades_the_same_app_and_keeps_its_schedule(client, tmp_path): + """已经发布过的蓝图改了取数再发一版(N6 改取数回到蓝图):同一个工作流存新版本、同一个应用升版(口径变了要处置)、 + 沿用原来的定时任务(按蓝图更新时间),不另建一份。""" + bp = await _board_from_run(client, tmp_path) + first = (await client.post(f"/api/blueprints/{bp['id']}/publish-plan", json={"level": "published", + "first_run": False})).json() + first = (await client.post(f"/api/publish-plans/{first['id']}/run")).json() + assert first["status"] == "done", first["steps"] + schedule_id = _steps(first)["create_schedule"]["result"]["schedule_id"] + app_id = _steps(first)["create_app"]["result"]["app_id"] + + # 改取数:销售额去掉 999 的那一单;改「多久更新」:每周二 + async with SessionLocal() as session: + row = await session.get(Blueprint, bp["id"]) + nodes = [] + for n in row.graph["nodes"]: + if n["id"] == "q": + config = {**n["data"]["config"], "args": {"sql": s.GMV_SQL + " AND amount < 900"}} + n = {**n, "data": {**n["data"], "config": config}} + nodes.append(n) + row.graph = {**row.graph, "nodes": nodes} + row.spec = {**row.spec, "cadence": s.item({**s.WEEKLY, "weekday": 2})} + await session.commit() + r = await client.post(f"/api/blueprints/{bp['id']}/trial", json={"inputs": s.PERIOD}) + assert (await s.wait(r.json()["run_id"])).status == "succeeded" + + # 口径变了,没选处置:停在预检,你来定 + plan = (await client.post(f"/api/blueprints/{bp['id']}/publish-plan", json={"level": "published", + "first_run": False})).json() + upgrade = [p for p in plan["problems"] if p["code"] == "app.upgrade_policy"] + assert plan["ok"] is False and upgrade and upgrade[0]["plain"]["who"] == "you" + summary = {x["step"]: x["text"] for x in plan["summary"]} + assert "沿用应用正在用的定时任务" in summary["create_schedule"] and "每周二" in summary["create_schedule"] + assert summary["create_app"].startswith("更新应用") + + plan = (await client.post(f"/api/blueprints/{bp['id']}/publish-plan", json={ + "level": "published", "first_run": False, "dispositions": {"main": "recompute"}})).json() + assert plan["ok"] is True, plan["problems"] + done = (await client.post(f"/api/publish-plans/{plan['id']}/run")).json() + assert done["status"] == "done", done["steps"] + steps = _steps(done) + assert steps["create_schedule"]["result"] == {"schedule_id": schedule_id, "enabled": True, "reused": True} + assert steps["create_app"]["result"] == {"app_id": app_id, "created": False} + async with SessionLocal() as session: + row = await session.get(Blueprint, bp["id"]) + wf = await session.get(Workflow, row.workflow_id) + schedule = await session.get(Schedule, schedule_id) + count = int(await session.scalar(select(func.count(Schedule.id)).where(Schedule.workflow_id == wf.id)) or 0) + version = (await session.execute(select(AppVersion).where( + AppVersion.app_id == app_id, AppVersion.version == 2))).scalar_one() + assert wf.published_version == 2 and count == 1 + assert schedule.cron.endswith(" 2") and schedule.enabled is True + assert version.pins[0]["version"] == 2 and version.dispositions == {"main": "recompute"} + assert version.spec["views"]["latest"]["source"]["from"] == f"schedule:{schedule_id}" + + +async def test_problems_are_split_into_three_kinds(client): + """预检的问题带白话和归谁处理(摘要按它分三栏):岗位没绑人是「你来定」。""" + wf_id = await s.published_workflow(s.expense_graph(), f"报销-{uuid.uuid4().hex[:4]}", description="报销审批") + bp = (await client.post("/api/blueprints", json={"source": {"kind": "workflow_version", "id": wf_id}, + "scope": "shared"})).json() + await s.edit_spec(bp["id"], purpose=s.item("报销审批")) + assert (await client.post(f"/api/blueprints/{bp['id']}/instantiate")).status_code == 200 + plan = (await client.post(f"/api/blueprints/{bp['id']}/publish-plan", json={"level": "published"})).json() + assert all(p["who"] in ("you", "assistant", "admin") for p in plan["problems"]) + assert {p["source"] for p in plan["problems"]} <= {"blueprint", "plan", "workflow", "schedule", "app", "grants"} + unbound = next(p for p in plan["problems"] if p["code"] == "app.slot_unbound") + assert unbound["who"] == "you" and unbound["source"] == "app" + + +# -------------------------------------------------------------------------- +# 复核修复:各包接缝上的几件事 +# -------------------------------------------------------------------------- + + +async def _approval_blueprint(client) -> str: + """审批流程模板的蓝图:只有一步主管审批(处理人写了具体的人,岗位按卡片绑上),没有写回。""" + from app.blueprints.templates._common import EXTRAS + + bp = (await client.post("/api/blueprints", json={"source": {"kind": "template", "id": "approval"}, "scope": "shared", + "name": f"报销-{uuid.uuid4().hex[:4]}"})).json() + spec = EXTRAS["approval"].example() + spec["people"] = spec["people"][:1] + spec["access"] = {"use": [{"kind": "user", "name": "zhang"}], "observe": [], "manage": []} + await s.edit_spec(bp["id"], **spec) + return bp["id"] + + +def _human(graph: dict) -> dict: + return next(n for n in graph["nodes"] if n["type"] == "human")["data"]["config"] + + +async def test_cards_changed_after_the_trial_are_what_gets_published(client): + """试运行(实例化)之后改了「谁来做」的时限:图变了,出单时按卡片重新实例化,发布的是新图;和最近一次试运行不同照实 + 提醒。出单之后再改卡片(这次图哈希不一定变),执行时按卡片内容的指纹认出来,拒绝执行。""" + bp_id = await _approval_blueprint(client) + assert (await client.post(f"/api/blueprints/{bp_id}/instantiate")).status_code == 200 + before = await s.blueprint(bp_id) + assert _human(before.graph)["due"] == "P2D" + + r = await client.patch(f"/api/blueprints/{bp_id}", json={"ops": [ + {"op": "bp_set", "path": "/people/0/due", "value": "P1D"}]}) + assert r.status_code == 200, r.text + assert (await s.blueprint(bp_id)).graph_hash == before.graph_hash, "卡片上的修改只刷新关节,不重算图" + + plan = (await client.post(f"/api/blueprints/{bp_id}/publish-plan", json={"level": "published"})).json() + assert plan["ok"] is True, plan["problems"] + now = await s.blueprint(bp_id) + assert plan["graph_hash"] == now.graph_hash != before.graph_hash and _human(now.graph)["due"] == "P1D" + assert plan["options"]["spec_hash"] + + # 出单之后又改了卡片(换处理人只改岗位绑定、不改图):执行前按卡片内容的指纹认出来 + r = await client.patch(f"/api/blueprints/{bp_id}", json={"ops": [ + {"op": "bp_set", "path": "/people/0/who", "value": [{"kind": "user", "name": "li"}]}]}) + assert r.status_code == 200, r.text + assert (await s.blueprint(bp_id)).graph_hash == now.graph_hash + r = await client.post(f"/api/publish-plans/{plan['id']}/run") + assert r.status_code == 409 and r.json()["code"] == "plan.graph_changed" + + plan = (await client.post(f"/api/blueprints/{bp_id}/publish-plan", json={"level": "published"})).json() + done = (await client.post(f"/api/publish-plans/{plan['id']}/run")).json() + assert done["status"] == "done", done["steps"] + async with SessionLocal() as session: + row = await session.get(Blueprint, bp_id) + version = (await session.execute(select(WorkflowVersion).where( + WorkflowVersion.workflow_id == row.workflow_id))).scalars().one() + application = await session.get(App, row.app_id) + published = (await session.execute(select(AppVersion).where(AppVersion.app_id == application.id))).scalars().one() + assert _human(version.graph)["due"] == "P1D", "发布的是卡片上写的时限" + assert published.bindings["slots"]["lead"] == [{"kind": "user", "name": "li"}], "发布的是卡片上写的处理人" + + +async def test_a_plan_cannot_take_over_an_app_the_builder_cannot_manage(login, tmp_path): + """蓝图已经发布成应用:只有对那个应用有管理权限的人能出单、执行(发布单会改它的草稿、发布它、整份替换授权)。 + 只能查看的搭建者出单时预检报 plan.app_forbidden(要找管理员),执行 403;应用的授权没被改。""" + await auth_env.turn_on_local() + u = uuid.uuid4().hex[:6] + await auth_env.make_user(f"zhao{u}", "builder") + await auth_env.make_user(f"qian{u}", "builder") + owner = await auth_env.login(f"zhao{u}") + other = await auth_env.login(f"qian{u}") + source = await s.register_source(s.make_source(tmp_path)) + wf_id = await s.published_workflow(s.board_graph(source), f"周报-{u}", description="每周看上周销售额") + bp = (await owner.post("/api/blueprints", json={"source": {"kind": "workflow_version", "id": wf_id}, + "scope": "shared"})).json() + await s.edit_spec(bp["id"], purpose=s.item("每周看上周销售额"), + access={"use": [{"kind": "user", "name": f"zhao{u}"}], "observe": [], "manage": []}) + plan = (await owner.post(f"/api/blueprints/{bp['id']}/publish-plan", json={"level": "published", + "first_run": False})).json() + assert not [p for p in plan["problems"] if p["code"] == "plan.app_forbidden"] + done = (await owner.post(f"/api/publish-plans/{plan['id']}/run")).json() + assert done["status"] == "done", done["steps"] + app_id = (await s.blueprint(bp["id"])).app_id + + # 另一个搭建者把自己写进「谁能看」的管理,想借发布单拿到管理权 + await s.edit_spec(bp["id"], access={"use": [], "observe": [], "manage": [{"kind": "user", "name": f"qian{u}"}]}) + plan = (await other.post(f"/api/blueprints/{bp['id']}/publish-plan", json={"level": "published", + "first_run": False})).json() + forbidden = [p for p in plan["problems"] if p["code"] == "plan.app_forbidden"] + assert plan["ok"] is False and forbidden and forbidden[0]["who"] == "admin" and forbidden[0]["plain"]["title"] + r = await other.post(f"/api/publish-plans/{plan['id']}/run") + assert r.status_code == 403 and r.json()["code"] == "plan.app_forbidden", r.text + async with SessionLocal() as session: + grants = {(g.principal, g.role) for g in (await session.execute( + select(AppGrant).where(AppGrant.app_id == app_id))).scalars()} + assert grants == {(f"zhao{u}", "use")}, "授权没被改" + + +async def test_plans_left_running_by_a_dead_process_are_stopped_at_startup(client, tmp_path): + """执行到一半进程没了:单子停在「正在执行」,谁也接不着。启动时改成停下,停在没做完的那一步、写明执行中断,就能接着做。""" + from app.blueprints import publish_plan as plans + from app.db.models_blueprints import PublishPlan + + bp = await _board_from_run(client, tmp_path) + plan = (await client.post(f"/api/blueprints/{bp['id']}/publish-plan", json={"level": "published", + "first_run": False})).json() + async with SessionLocal() as session: + row = await session.get(PublishPlan, plan["id"]) + steps = [dict(st) for st in row.steps] + steps[0].update(status="done", result={"workflow_id": "x"}) + row.steps, row.status = steps, "running" + await session.commit() + assert await plans.startup() >= 1 + got = (await client.get(f"/api/publish-plans/{plan['id']}")).json() + stopped = _steps(got) + assert got["status"] == "stopped" and stopped["save_version"]["status"] == "done" + assert stopped["preflight"]["status"] == "failed" and stopped["preflight"]["error_code"] == "plan.interrupted" + assert "重启" in stopped["preflight"]["message"] + from app.plain import plain_of + + assert plain_of("plan.interrupted") is not None + + +# ---------------------------------------------------------------- 填报登记:试运行 → 发布单 → 入口提交 + + +RECORD_FIELDS = [ + {"name": "store", "spec": s.item({"type": "string", "title": "门店", "required": True}), "sensitive": False}, + {"name": "amount", "spec": s.item({"type": "number", "title": "金额", "required": True}), "sensitive": False}, + {"name": "reason", "spec": s.item({"type": "string", "title": "原因"}), "sensitive": True}, +] + + +async def _records_blueprint(client) -> str: + bp = (await client.post("/api/blueprints", json={"source": {"kind": "template", "id": "records"}, "scope": "shared", + "name": f"报损-{uuid.uuid4().hex[:4]}"})).json() + await s.edit_spec(bp["id"], purpose=s.item("门店报损登记"), fields=RECORD_FIELDS, people=[], data=[], + cadence=s.item(s.WEEKLY), + access={"use": [{"kind": "user", "name": "amy"}, {"kind": "user", "name": "bob"}], + "observe": [], "manage": []}) + return bp["id"] + + +def _append_table(graph: dict) -> str: + return next(n for n in graph["nodes"] if n["type"] == "tool")["data"]["config"]["args"]["table"] + + +async def _publish(client, bp_id: str) -> dict: + plan = (await client.post(f"/api/blueprints/{bp_id}/publish-plan", json={"level": "published"})).json() + if any(p["code"] == "app.upgrade_policy" for p in plan["problems"]): + plan = (await client.post(f"/api/blueprints/{bp_id}/publish-plan", json={ + "level": "published", "dispositions": {"main": "incomparable"}})).json() + assert plan["ok"] is True, plan["problems"] + done = (await client.post(f"/api/publish-plans/{plan['id']}/run")).json() + assert done["status"] == "done", done["steps"] + return done + + +async def _submit(client, app_id: str, values: dict, who: str) -> Run: + r = await client.post(f"/api/apps/{app_id}/entries/start", json={"values": values}, headers={"X-Actor": who}) + assert r.status_code == 201, r.text + run = await s.wait(r.json()["run_id"]) + assert run.status == "succeeded", run.error + return run + + +async def test_records_blueprint_trials_publishes_and_submissions_land_in_the_table(client): + """填报登记走一遍:试运行(示例表单走填报那条路,写入演练)→ 发布单 → 入口提交,记录表里有那一行。图里写的记录表是 + 「键.v版本」(和填关节、卡片修改同一种写法),正式运行写得进去。 + + 之后在蓝图上不兼容地改表单(金额改成文字)再试运行:起草时出第 2 版,线上应用固定在第 1 版、照常收提交;发布之后才 + 切到第 2 版、第 1 版停用。记录列表里别人提交的行,敏感列写「已遮罩」。""" + from app.db.models_blueprints import RecordsTable + from app.records import store + from app.records.tables import path_of + + from app.capabilities.registry import sync_all + + async with SessionLocal() as session: + # 平台能力 records_append 登记进能力表(启动时同步的那一次):带查询能力,应用不用绑核实岗位 + await sync_all(session) + bp_id = await _records_blueprint(client) + r = await client.post(f"/api/blueprints/{bp_id}/trial", json={"inputs": {"store": "一店", "amount": 3}}) + assert r.status_code == 200, r.text + trial = await s.wait(r.json()["run_id"]) + assert trial.status == "succeeded", trial.error + assert trial.input["mode"] == "submit" and trial.input["store"] == "一店", "填了示例表单:试的是填报那条路" + row = await s.blueprint(bp_id) + assert _append_table(row.graph) == f"{bp_id}.v1" + + await _publish(client, bp_id) + app_id = (await s.blueprint(bp_id)).app_id + await _submit(client, app_id, {"store": "一店", "amount": 12.5, "reason": "过期"}, "amy") + await _submit(client, app_id, {"store": "二店", "amount": 3, "reason": "破损"}, "bob") + async with SessionLocal() as session: + v1 = (await session.execute(select(RecordsTable).where(RecordsTable.table_key == bp_id))).scalars().one() + assert v1.app_id == app_id and v1.retired_at is None + assert store.high_water(path_of(v1)) == 2, "试运行一行都没写,两次提交各一行" + + # 记录列表:别人提交的行,敏感列写「已遮罩」;自己的照原样 + page = (await client.get(f"/api/apps/{app_id}/records", headers={"X-Actor": "amy"})).json() + by = {r["_submitted_by"]: r["values"] for r in page["items"]} + assert by["amy"]["reason"] == "过期" and by["bob"]["reason"] == "已遮罩" and by["bob"]["store"] == "二店" + + # 草稿上不兼容地改表单、试运行:出第 2 版,线上那一版不停用 + fields = [RECORD_FIELDS[0], {**RECORD_FIELDS[1], "spec": s.item({"type": "string", "title": "金额"})}, RECORD_FIELDS[2]] + await s.edit_spec(bp_id, fields=fields) + r = await client.post(f"/api/blueprints/{bp_id}/trial", json={"inputs": {"store": "三店", "amount": "三元"}}) + assert (await s.wait(r.json()["run_id"])).status == "succeeded" + assert _append_table((await s.blueprint(bp_id)).graph) == f"{bp_id}.v2" + async with SessionLocal() as session: + versions = list((await session.execute(select(RecordsTable).where(RecordsTable.table_key == bp_id) + .order_by(RecordsTable.version))).scalars()) + assert [(v.version, v.retired_at is None) for v in versions] == [(1, True), (2, True)] + await _submit(client, app_id, {"store": "一店", "amount": 7, "reason": "过期"}, "amy") + assert store.high_water(path_of(versions[0])) == 3, "线上应用照常写第 1 版" + + # 发布之后才切换:第 1 版停用(写明换成了第 2 版),新的提交写进第 2 版 + done = await _publish(client, bp_id) + assert {st["kind"]: st for st in done["steps"]}["publish_app"]["result"]["records"] == [f"{bp_id}.v2"] + async with SessionLocal() as session: + versions = list((await session.execute(select(RecordsTable).where(RecordsTable.table_key == bp_id) + .order_by(RecordsTable.version))).scalars()) + assert versions[0].retired_at is not None and "第 2 版" in versions[0].note and versions[1].retired_at is None + await _submit(client, app_id, {"store": "四店", "amount": "五元"}, "amy") + assert store.high_water(path_of(versions[1])) == 1 and store.high_water(path_of(versions[0])) == 3 diff --git a/backend/tests/test_records.py b/backend/tests/test_records.py new file mode 100644 index 00000000..b82ac801 --- /dev/null +++ b/backend/tests/test_records.py @@ -0,0 +1,672 @@ +"""记录表(docs/design/normal-user-apps.md N8、§3.7)。 + +- 追加:按动作键幂等,同一个动作第二次来交回第一次写下的那一行;更正是新的一行带 _supersedes,原行不改; +- 高水位:运行开始时记下最大的 _seq,同一次运行查两遍结果一样,期间有新提交也不变; +- 行级可见:use 只看自己提交的,observe 看全部;正式运行看全部;查询里直接写 main.<表> 被只读守卫拒掉,幂等键列不露; +- 表版本:只加可选字段在同一版本上加列;改类型、删字段、加必填字段出新版本,旧版本只读保留; +- records_append 走动作:生效记录、无人值守、重放不重复写;结果未知时按幂等键查到、核实为已生效、不重发; + 探索运行演练,一行都不写; +- records_list(GET /api/apps/{id}/records)按看的人实时过滤;看板表格逐行列出记录表时应用检查给警告。 + +夹具:门店报损的假数据,人名是假名。 +""" +from __future__ import annotations + +import asyncio +import json +import uuid +from datetime import timedelta +from types import SimpleNamespace + +import pytest +from httpx import ASGITransport, AsyncClient +from sqlalchemy import select + +from app.core.config import settings +from app.data.engine import run_query +from app.data.guard import SqlRejected, schema_reference +from app.db.base import SessionLocal, utcnow +from app.db.models import ActionRecord, DataSource, Run, RunEvent, User +from app.db.models_apps import App, AppGrant +from app.db.models_blueprints import RecordsTable +from app.engine.runner import run_manager +from app.records import RECORDS_APPEND, RECORDS_LOOKUP, store +from app.records.tables import columns_of, ensure_table, path_of +from app.records.views import resolve + +COLUMNS = [ + {"name": "门店", "label": "门店", "type": "string", "required": True}, + {"name": "数量", "label": "报损数量", "type": "integer", "required": True}, + {"name": "原因", "label": "原因", "type": "string"}, +] +COUNT = "SELECT count(*) AS n FROM records" + + +@pytest.fixture(autouse=True) +def data_dir(monkeypatch, tmp_path): + data = tmp_path / "data" + (data / "uploads").mkdir(parents=True) + monkeypatch.setattr(settings, "data_dir", data) + yield data + + +@pytest.fixture +async def engine_up(data_dir): + await run_manager.setup() + yield + await run_manager.shutdown() + + +@pytest.fixture +async def client(): + from app.main import app + + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c: + yield c + + +def node(nid, ntype, **config): + return {"id": nid, "type": ntype, "position": {"x": 0, "y": 0}, "data": {"label": nid, "config": config}} + + +def chain(*nodes): + return {"nodes": list(nodes), "edges": [{"source": a["id"], "target": b["id"]} for a, b in zip(nodes, nodes[1:])]} + + +async def wait(run_id: str, statuses=("interrupted", "failed", "succeeded"), timeout=30.0) -> Run: + deadline = asyncio.get_event_loop().time() + timeout + while asyncio.get_event_loop().time() < deadline: + async with SessionLocal() as session: + row = await session.get(Run, run_id) + if row and row.status in statuses and not run_manager.is_active(row.id): + return row + await asyncio.sleep(0.05) + raise AssertionError(f"运行 {run_id} 没有进入 {statuses}") + + +async def make_app(name: str = "门店报损", *, grants: dict[str, str] | None = None) -> App: + async with SessionLocal() as session: + app = App(name=name, created_by="建立人") + session.add(app) + await session.flush() + for who, role in (grants or {}).items(): + session.add(AppGrant(app_id=app.id, principal_kind="user", principal=who, role=role)) + await session.commit() + return app + + +async def make_table(owner, columns=COLUMNS) -> RecordsTable: + async with SessionLocal() as session: + row = await ensure_table(session, owner, columns) + await session.commit() + return row + + +async def source_of(table: RecordsTable) -> DataSource: + async with SessionLocal() as session: + return await session.get(DataSource, table.source_id) + + +def add(table: RecordsTable, values: dict, *, by: str = "amy", key: str | None = None, supersedes: str | None = None): + return store.append(path_of(table), columns_of(table), values, version=table.version, run_id=None, actor=by, + action_key=key or uuid.uuid4().hex, supersedes=supersedes) + + +def rows_of(result) -> list: + return result.rows + + +# -------------------------------------------------------------------------- +# 追加、幂等、更正 +# -------------------------------------------------------------------------- + + +async def test_append_is_idempotent_and_corrections_keep_the_original(): + table = await make_table(await make_app()) + first = add(table, {"门店": "一店", "数量": "3"}, key="k1") + again = add(table, {"门店": "一店", "数量": "99"}, key="k1") + assert not first.duplicate and again.duplicate + assert (again.seq, again.row_id) == (first.seq, first.row_id), "同一个动作键只落一行,交回第一次的那一行" + assert store.high_water(path_of(table)) == first.seq == 1 + assert first.values["数量"] == 3, "模板渲染出来的文字按列类型收成整数" + + fixed = add(table, {"门店": "一店", "数量": 4, "原因": "过期"}, key="k2", supersedes=first.row_id) + cols = columns_of(table) + current, _ = store.rows(path_of(table), cols, scope="all", viewer=None) + assert [r["_id"] for r in current] == [fixed.row_id], "更正过的行不再出现在当前有效的行里" + history, _ = store.rows(path_of(table), cols, scope="all", viewer=None, history=True) + assert [(r["_id"], r["superseded"]) for r in history] == [(fixed.row_id, False), (first.row_id, True)] + original = next(r for r in history if r["_id"] == first.row_id) + assert original["values"]["数量"] == 3 and original["_supersedes"] is None, "原行一个字都不改" + assert next(r for r in history if r["_id"] == fixed.row_id)["_supersedes"] == first.row_id + + for values, supersedes, code in [ + ({"门店": "一店", "数量": 1}, first.row_id, "records.supersede_twice"), + ({"门店": "一店", "数量": 1}, "nope", "records.supersede_missing"), + ({"门店": "一店", "数量": 1, "颜色": "红"}, None, "records.column_unknown"), + ({"门店": "一店"}, None, "records.required_missing"), + ({"门店": "一店", "数量": "三"}, None, "records.value_invalid"), + ({"门店": "一店", "数量": "1.5"}, None, "records.value_invalid"), + ]: + with pytest.raises(store.RecordsRefused) as refused: + add(table, values, supersedes=supersedes) + assert refused.value.code == code, values + assert store.high_water(path_of(table)) == 2, "被拒的写入一行都没落" + + +# -------------------------------------------------------------------------- +# 查询:临时视图、只读守卫 +# -------------------------------------------------------------------------- + + +async def test_queries_go_through_the_temp_view_and_main_is_refused(): + table = await make_table(await make_app()) + first = add(table, {"门店": "一店", "数量": 2}) + add(table, {"门店": "一店", "数量": 5}, supersedes=first.row_id) + add(table, {"门店": "二店", "数量": 1}, by="bob") + source = await source_of(table) + assert source.origin == "records" and source.readonly + async with SessionLocal() as session: + view = await resolve(session, source, {"seq": 3, "rows": "all"}) + total = await run_query(view, 'SELECT sum("数量") AS s, count(*) AS n FROM records') + assert total.rows == [[6, 2]], "被更正的那一行不算" + for sql in ("SELECT * FROM main.records", 'SELECT * FROM "main"."records"', "SELECT * FROM [main].records", + "SELECT * FROM main . records", "SELECT a.* FROM records a JOIN MAIN.records b ON a._id = b._id"): + with pytest.raises(SqlRejected) as refused: + await run_query(view, sql) + assert "main." in str(refused.value), sql + with pytest.raises(Exception) as hidden: + await run_query(view, "SELECT _action_key FROM records") + assert "_action_key" in str(hidden.value), "幂等键列不在视图里" + # 没经解析、直接拿数据源行查(数据剖析这类入口):照样走视图 + plain = await run_query(source, COUNT) + assert plain.rows == [[2]] + with pytest.raises(SqlRejected): + await run_query(source, "SELECT count(*) FROM main.records") + + +def test_schema_reference_ignores_strings_and_identifiers_that_merely_contain_main(): + assert schema_reference("SELECT * FROM main.records", ("main",)) == "main" + assert schema_reference("SELECT 'main.records' AS x FROM records", ("main",)) is None + assert schema_reference('SELECT "main.records" FROM records', ("main",)) is None + assert schema_reference("SELECT domain.x FROM records AS domain", ("main",)) is None + assert schema_reference("SELECT 1 /* main.records */ FROM records", ("main",)) is None + + +# -------------------------------------------------------------------------- +# 高水位:同一次运行查两遍一样 +# -------------------------------------------------------------------------- + + +async def test_a_run_sees_the_same_rows_twice_even_when_new_ones_arrive(engine_up): + table = await make_table(await make_app()) + add(table, {"门店": "一店", "数量": 1}) + add(table, {"门店": "二店", "数量": 2}, by="bob") + source = await source_of(table) + tool = f"db_query__{source.name}" + graph = chain(node("start", "input"), node("t1", "tool", tool=tool, args={"sql": COUNT}), + node("gate", "human", mode="approve", title="看一眼"), + node("t2", "tool", tool=tool, args={"sql": COUNT}), + node("out", "output", fields=[{"name": "t1", "value": "{{ nodes.t1 }}"}, + {"name": "t2", "value": "{{ nodes.t2 }}"}])) + run = await run_manager.start(graph=graph, input_payload={}, run_class="formal") + assert (await wait(run.id)).status == "interrupted" + add(table, {"门店": "三店", "数量": 3}, by="cat") + add(table, {"门店": "四店", "数量": 4}) + await run_manager.resume(run.id, {"approved": True}) + done = await wait(run.id, ("succeeded", "failed")) + assert done.status == "succeeded", done.error + assert json.loads(done.output["t1"])["rows"] == [[2]] + assert json.loads(done.output["t2"])["rows"] == [[2]], "审批期间新来的两条没有混进这次运行" + entry = done.data_versions[source.id] + assert entry["seq"] == 2 and entry["rows"] == "all" and entry["origin"] == "records" + async with SessionLocal() as session: + started = list((await session.execute(select(RunEvent).where( + RunEvent.run_id == run.id, RunEvent.type == "run.started").order_by(RunEvent.seq))).scalars()) + assert all(e.data["data_versions"][source.id]["seq"] == 2 for e in started), "封存的发起事件里记着高水位" + # 新的一次运行看得到新来的 + once = chain(node("start", "input"), node("t", "tool", tool=tool, args={"sql": COUNT}), + node("out", "output", fields=[{"name": "t", "value": "{{ nodes.t }}"}])) + again = await run_manager.start(graph=once, input_payload={}, run_class="formal") + assert json.loads((await wait(again.id, ("succeeded", "failed"))).output["t"])["rows"] == [[4]] + + +# -------------------------------------------------------------------------- +# 行级可见 +# -------------------------------------------------------------------------- + + +async def _users(*names_roles): + async with SessionLocal() as session: + for name, role in names_roles: + if (await session.execute(select(User).where(User.username == name))).scalar_one_or_none() is None: + session.add(User(username=name, display_name=name, role=role)) + await session.commit() + + +async def test_exploratory_runs_see_rows_by_the_starters_grant(engine_up, monkeypatch): + import app.api.deps as deps + + suffix = uuid.uuid4().hex[:6] + amy, bob, cat = f"amy{suffix}", f"bob{suffix}", f"cat{suffix}" + await _users((amy, "user"), (bob, "user"), (cat, "user")) + app = await make_app(grants={amy: "use", bob: "use", cat: "observe"}) + table = await make_table(app) + add(table, {"门店": "一店", "数量": 1}, by=amy) + add(table, {"门店": "一店", "数量": 2}, by=amy) + add(table, {"门店": "二店", "数量": 5}, by=bob) + source = await source_of(table) + monkeypatch.setattr(deps, "auth_mode", lambda: "local") + graph = chain(node("start", "input"), node("t", "tool", tool=f"db_query__{source.name}", + args={"sql": 'SELECT count(*) AS n, sum("数量") AS s FROM records'}), + node("out", "output", fields=[{"name": "t", "value": "{{ nodes.t }}"}])) + + async def seen(who: str, run_class: str = "exploratory") -> list: + run = await run_manager.start(graph=graph, input_payload={}, started_by=who, run_class=run_class) + done = await wait(run.id, ("succeeded", "failed")) + assert done.status == "succeeded", done.error + return json.loads(done.output["t"])["rows"][0] + + assert await seen(amy) == [2, 3], "use 只看自己提交的" + assert await seen(bob) == [1, 5] + assert await seen(cat) == [3, 8], "observe 看全部" + assert await seen(f"zed{suffix}") == [0, None], "没有授权的一行都看不到" + assert await seen(amy, "formal") == [3, 8], "正式运行以服务身份跑,看全部" + + +async def test_records_list_filters_by_viewer(client, monkeypatch): + from app.api import personal + from app.api.deps import Principal + + app = await make_app(grants={"amy": "use", "cat": "observe"}) + table = await make_table(app) + a1 = add(table, {"门店": "一店", "数量": 1}, by="amy") + add(table, {"门店": "二店", "数量": 2}, by="bob") + fixed = add(table, {"门店": "一店", "数量": 3}, by="amy", supersedes=a1.row_id) + + def as_(name: str) -> None: + monkeypatch.setattr(personal, "current_principal", + lambda: Principal(username=name, role="user", verified=True, mode="local")) + + as_("amy") + mine = (await client.get(f"/api/apps/{app.id}/records")).json() + assert mine["mine_only"] is True and [r["_id"] for r in mine["items"]] == [fixed.row_id] + assert mine["items"][0]["values"] == {"门店": "一店", "数量": 3, "原因": None} + assert [c["name"] for c in mine["columns"]] == ["门店", "数量", "原因"] and mine["table"] == table.table_key + history = (await client.get(f"/api/apps/{app.id}/records", params={"history": "true"})).json() + assert [(r["_id"], r["superseded"]) for r in history["items"]] == [(fixed.row_id, False), (a1.row_id, True)] + as_("cat") + everyone = (await client.get(f"/api/apps/{app.id}/records")).json() + assert everyone["mine_only"] is False and len(everyone["items"]) == 2 + paged = (await client.get(f"/api/apps/{app.id}/records", params={"limit": 1})).json() + assert len(paged["items"]) == 1 and paged["next_cursor"] + rest = (await client.get(f"/api/apps/{app.id}/records", + params={"limit": 1, "cursor": paged["next_cursor"]})).json() + assert rest["items"][0]["_id"] != paged["items"][0]["_id"] + as_("dan") + assert (await client.get(f"/api/apps/{app.id}/records")).status_code == 404, "没有授权的人不知道应用在不在" + + +# -------------------------------------------------------------------------- +# 表版本 +# -------------------------------------------------------------------------- + + +async def test_compatible_changes_add_columns_incompatible_ones_make_a_new_version(): + app = await make_app() + v1 = await make_table(app) + old = add(v1, {"门店": "一店", "数量": 1}) + # 加一个可选字段:同一版本加列 + same = await make_table(app, [*COLUMNS, {"name": "照片", "label": "照片", "type": "file"}]) + assert same.id == v1.id and same.version == 1 + assert [c["name"] for c in same.columns] == ["门店", "数量", "原因", "照片"] + add(same, {"门店": "二店", "数量": 2, "照片": {"file_id": "f1", "name": "a.png", "size": 1, "sha256": "0" * 64, + "type": "image/png"}}) + source = await source_of(same) + assert "照片" in [c["name"] for c in source.schema_cache["tables"]["records"]["columns"]] + # 标敏感:进数据源的遮罩列,不出新版本 + masked = await make_table(app, [*COLUMNS[:2], {**COLUMNS[2], "sensitive": True}, + {"name": "照片", "label": "照片", "type": "file"}]) + assert masked.version == 1 and (await source_of(masked)).options["mask_columns"] == ["原因"] + + # 改类型:出新版本,旧版本只读保留 + v2 = await make_table(app, [COLUMNS[0], {**COLUMNS[1], "type": "string"}]) + assert v2.version == 2 and v2.table_key == v1.table_key and v2.source_id != v1.source_id + async with SessionLocal() as session: + versions = list((await session.execute(select(RecordsTable).where( + RecordsTable.table_key == v1.table_key).order_by(RecordsTable.version))).scalars()) + assert [v.version for v in versions] == [1, 2] + assert versions[0].retired_at is not None and "类型" in versions[0].note and versions[1].retired_at is None + assert store.high_water(path_of(versions[0])) == 2, "旧版本的记录照原样留着" + assert (await run_query(await source_of(versions[0]), COUNT)).rows == [[2]], "旧版本照样查得到" + # 删字段、加必填字段、可选改必填:都出新版本 + v3 = await make_table(app, [COLUMNS[0]]) + v4 = await make_table(app, [COLUMNS[0], {"name": "店长", "type": "string", "required": True}]) + v5 = await make_table(app, [COLUMNS[0], {"name": "店长", "type": "string", "required": True}, + {"name": "备注", "type": "string"}]) + v6 = await make_table(app, [COLUMNS[0], {"name": "店长", "type": "string", "required": True}, + {"name": "备注", "type": "string", "required": True}]) + assert [v3.version, v4.version, v5.version, v6.version] == [3, 4, 4, 5] + + # 往停用的版本写:拒绝 + from app.records.actions import append_action + + refused = await append_action({"table": versions[0].id, "values": {"门店": "一店", "数量": 1}}, idem_key="x:1", + run_id=None, on_behalf=None, environment="prod") + assert refused.status is None and "停用" in refused.error and old.seq == 1 + + +# -------------------------------------------------------------------------- +# records_append 走动作 +# -------------------------------------------------------------------------- + + +async def _sync() -> None: + from app.capabilities.registry import sync_all + + async with SessionLocal() as session: + await sync_all(session) + + +def append_graph(table_ref: str) -> dict: + return chain(node("start", "input", fields=[{"name": "store"}, {"name": "qty"}]), + node("w", "tool", tool=RECORDS_APPEND, approval="never", + args={"table": table_ref, "values": {"门店": "{{ input.store }}", "数量": "{{ input.qty }}"}}), + node("out", "output", fields=[{"name": "id", "value": "{{ nodes.w.receipt._id }}"}])) + + +async def writer_of(app: App, graph: dict) -> str: + """应用里钉着的那个工作流(正式运行只写自己应用的记录表:表没有蓝图时认应用钉着的工作流)。交回工作流 id。""" + from app.db.models import Workflow + + async with SessionLocal() as session: + wf = Workflow(name=f"报损-{uuid.uuid4().hex[:6]}", graph=graph, status="published") + session.add(wf) + await session.flush() + row = await session.get(App, app.id) + row.draft = {"pins": [{"alias": "main", "workflow_id": wf.id, "version": 1, "graph_hash": "x"}]} + await session.commit() + return wf.id + + +async def test_records_append_is_a_governed_write_that_writes_once(engine_up): + from app.capabilities.platform import execute + from app.capabilities.registry import get_capability + + app = await make_app() + table = await make_table(app) + source = await source_of(table) + workflow_id = await writer_of(app, append_graph(source.name)) + await _sync() + async with SessionLocal() as session: + cap = await get_capability(session, RECORDS_APPEND) + finder = await get_capability(session, RECORDS_LOOKUP) + assert cap.effect_system == "write" and cap.unattended_write and cap.lookup == RECORDS_LOOKUP + assert finder.effect_system == "read" + + run = await run_manager.start(graph=append_graph(source.name), input_payload={"store": "一店", "qty": "7"}, + run_class="formal", started_by="amy", workflow_id=workflow_id) + done = await wait(run.id, ("succeeded", "failed", "interrupted")) + assert done.status == "succeeded", done.error + async with SessionLocal() as session: + [rec] = list((await session.execute(select(ActionRecord).where(ActionRecord.run_id == run.id))).scalars()) + assert rec.state == "confirmed" and rec.environment == "prod" and rec.capability == RECORDS_APPEND + [row], _ = store.rows(path_of(table), columns_of(table), scope="all", viewer=None) + assert row["values"] == {"门店": "一店", "数量": 7, "原因": None} + assert row["_submitted_by"] == "amy" and row["_run_id"] == run.id and done.output["id"] == row["_id"] + + # 重放(同一个动作键,第几次发都一样):交回第一次的那一行,不再写 + for idem in (rec.idem_key, f"{rec.action_key}:2"): + again = await execute(None, cap, {"table": source.name, "values": {"门店": "一店", "数量": 7}}, + environment="prod", idem_key=idem, on_behalf={"sub": "amy"}, run_id=run.id) + assert again.status == 200 and again.body["duplicate"] is True and again.body["_id"] == row["_id"] + assert store.high_water(path_of(table)) == 1 + + # 探索运行:演练,一行都不写 + trial = await run_manager.start(graph=append_graph(source.name), input_payload={"store": "二店", "qty": "1"}, + run_class="exploratory", started_by="amy") + assert (await wait(trial.id, ("succeeded", "failed"))).status == "succeeded" + async with SessionLocal() as session: + [sim] = list((await session.execute(select(ActionRecord).where(ActionRecord.run_id == trial.id))).scalars()) + assert sim.state == "simulated" and store.high_water(path_of(table)) == 1 + + +async def test_unknown_result_is_found_by_the_lookup_and_not_written_again(engine_up, monkeypatch): + """写下了、回执没拿到(进程在写完之后出了错):结果未知、运行挂起;查询能力按幂等键查到那一行,核实为已生效, + 接着跑时节点交回存下的回执,记录表里还是一行。""" + from app.process import actions + from app.records import actions as records_actions + + app = await make_app() + table = await make_table(app) + source = await source_of(table) + workflow_id = await writer_of(app, append_graph(source.name)) + await _sync() + real = records_actions.append_action + + async def crash_after_write(*args, **kwargs): + await real(*args, **kwargs) + raise RuntimeError("写完之后连接断了") + + monkeypatch.setattr(records_actions, "append_action", crash_after_write) + run = await run_manager.start(graph=append_graph(source.name), input_payload={"store": "一店", "qty": "2"}, + run_class="formal", started_by="amy", workflow_id=workflow_id) + assert (await wait(run.id)).status == "interrupted" + async with SessionLocal() as session: + [rec] = list((await session.execute(select(ActionRecord).where(ActionRecord.run_id == run.id))).scalars()) + assert rec.state == "unknown" and store.high_water(path_of(table)) == 1 + monkeypatch.setattr(records_actions, "append_action", real) + for _ in range(100): + async with SessionLocal() as session: + if (await session.get(ActionRecord, rec.id)).next_lookup_at is not None: + break + await asyncio.sleep(0.05) + assert await actions.tick(utcnow() + timedelta(minutes=5)) == 1 + done = await wait(run.id, ("succeeded", "failed")) + assert done.status == "succeeded", done.error + async with SessionLocal() as session: + rec = await session.get(ActionRecord, rec.id) + assert rec.state == "confirmed" and rec.resolution["how"] == "lookup" + assert store.high_water(path_of(table)) == 1, "核实之后接着跑,没有再写一行" + + +# -------------------------------------------------------------------------- +# 应用检查:看板表格逐行列出记录表 +# -------------------------------------------------------------------------- + + +async def test_dashboard_table_listing_record_rows_is_warned(): + from app.apps.lint import _Issues, _lint_records_rows + + table = await make_table(await make_app()) + source = await source_of(table) + + def spec_with(sql: str) -> tuple[dict, dict]: + graph = chain(node("start", "input"), + node("q", "tool", tool=f"db_query__{source.name}", args={"sql": sql})) + spec = {"views": {"v": {"source": {"kind": "latest_sealed", "pin": "main"}}}, + "pages": [{"id": "home", "body": [{"id": "rows", "type": "table", + "bind": {"view": "v", "query": {"node": "q"}}}]}]} + return spec, {"main": SimpleNamespace(graph=graph, row=object(), blueprint=None)} + + async def codes(sql: str) -> list[str]: + spec, pins = spec_with(sql) + out = _Issues() + async with SessionLocal() as session: + await _lint_records_rows(session, spec, pins, out) + return [i["code"] for i in out.items] + + assert await codes("SELECT * FROM records") == ["app.records_rows_exposed"] + assert await codes('SELECT "门店", "数量" FROM records WHERE "数量" > 1') == ["app.records_rows_exposed"] + assert await codes('SELECT "门店", sum("数量") AS n FROM records GROUP BY "门店"') == [] + assert await codes("SELECT count(*) FROM records") == [] + + +# -------------------------------------------------------------------------- +# 数据源:平台维护,数据目录照常起草 +# -------------------------------------------------------------------------- + + +async def test_records_source_is_managed_by_the_platform(client): + from app.data import catalog, table_versions + + table = await make_table(await make_app()) + source = await source_of(table) + add(table, {"门店": "一店", "数量": 1}) + # 启动整理不把它当成「指向应用自己数据文件的手工源」停掉 + async with SessionLocal() as session: + await table_versions._disable_manual_app_files(session) + assert (await source_of(table)).enabled is True + # 连接字段改不了、删不掉、不用重新探查;测连接照常 + patched = await client.patch(f"/api/datasources/{source.id}", json={"database": "/tmp/x.db"}) + assert patched.status_code == 422 and "记录表" in patched.json()["detail"] + assert (await client.patch(f"/api/datasources/{source.id}", json={"description": "门店报损"})).status_code == 200 + assert (await client.delete(f"/api/datasources/{source.id}")).status_code == 409 + assert (await client.post(f"/api/datasources/{source.id}/introspect")).status_code == 409 + assert (await client.post(f"/api/datasources/{source.id}/test")).json()["ok"] is True + # 手工源不许登记到记录表的文件上 + sneaky = await client.post("/api/datasources", json={"name": f"m_{uuid.uuid4().hex[:8]}", "kind": "sqlite", + "database": str(path_of(table))}) + assert sneaky.status_code == 422 + # 数据目录照常起草:表、系统列的说明都在 + async with SessionLocal() as session: + report = await catalog.draft_catalog(session, await session.get(DataSource, source.id), tables=["records"]) + await session.commit() + entries = await catalog.read_catalog(session, source.id) + assert [t.table for t in report.tables] == ["records"] and "records" in entries + + +def test_stamp_writes_the_high_water_for_records(): + from app.apps.resolve import _version_text + + assert _version_text({"name": "rec_abc", "origin": "records", "seq": 12, "rows": "all"}) == "rec_abc 截至第 12 条" + assert _version_text({"name": "sales", "snapshot": "0123456789abcdef"}) == "sales 01234567" + + +# -------------------------------------------------------------------------- +# 复核修复:草稿不影响线上、遮罩列不被抹掉、写入的三道核对 +# -------------------------------------------------------------------------- + + +async def test_drafting_never_retires_the_live_version_and_publishing_switches(): + """起草(draft_table):兼容的只补列,不兼容的出下一版、线上那一版不停用;只读的 pick_table 认同一版。发布 + (publish_table)才切换:图里写的那一版成为往里写的,别的没停用的这时停用,登记按卡片整理。""" + from app.records.tables import draft_table, pick_table, publish_table + + owner = SimpleNamespace(id=uuid.uuid4().hex, app_id=None, name="门店报损") + async with SessionLocal() as session: + v1 = await draft_table(session, owner, COLUMNS) + await session.commit() + add(v1, {"门店": "一店", "数量": 1}) + async with SessionLocal() as session: + # 兼容(加可选字段):同一版补列 + noted = [*COLUMNS, {"name": "备注", "type": "string"}] + same = await draft_table(session, owner, noted) + # 不兼容(数量改成文字):出第 2 版,第 1 版照常收 + changed = [COLUMNS[0], {**COLUMNS[1], "type": "string"}, COLUMNS[2]] + v2 = await draft_table(session, owner, changed) + assert (await pick_table(session, owner.id, changed)).id == v2.id + assert (await pick_table(session, owner.id, noted)).id == v1.id, "线上那一版还兼容的,起草优先用它" + await session.commit() + assert same.id == v1.id and v2.version == 2 + async with SessionLocal() as session: + v1 = await session.get(RecordsTable, v1.id) + assert v1.retired_at is None and "备注" in [c["name"] for c in v1.columns] + add(v1, {"门店": "二店", "数量": 2, "备注": "照常写"}) + + app = await make_app() + async with SessionLocal() as session: + live = await publish_table(session, await session.get(App, app.id), f"{owner.id}.v2", changed) + await session.commit() + async with SessionLocal() as session: + rows = list((await session.execute(select(RecordsTable).where(RecordsTable.table_key == owner.id) + .order_by(RecordsTable.version))).scalars()) + assert live.version == 2 and [r.app_id for r in rows] == [app.id, app.id] + assert rows[0].retired_at is not None and "第 2 版" in rows[0].note and rows[1].retired_at is None + assert store.high_water(path_of(rows[0])) == 2, "旧记录照原样留着" + + +async def test_a_compatible_change_keeps_masks_added_by_hand(): + """兼容的表单改动只改这次变了的那几列的遮罩:管理员在数据页手工加的遮罩列(这里是提交人)留着;取消敏感标记的去掉。""" + from app.data.engine import MASK_COLUMNS_OPTION + + app = await make_app() + table = await make_table(app, [*COLUMNS[:2], {**COLUMNS[2], "sensitive": True}]) + async with SessionLocal() as session: + source = await session.get(DataSource, table.source_id) + source.options = {MASK_COLUMNS_OPTION: ["原因", "_submitted_by"]} + await session.commit() + await make_table(app, [*COLUMNS[:2], {**COLUMNS[2], "sensitive": True}, {"name": "电话", "type": "string", + "sensitive": True}]) + assert (await source_of(table)).options[MASK_COLUMNS_OPTION] == ["原因", "_submitted_by", "电话"] + await make_table(app, [*COLUMNS[:2], COLUMNS[2], {"name": "电话", "type": "string", "sensitive": True}]) + assert (await source_of(table)).options[MASK_COLUMNS_OPTION] == ["_submitted_by", "电话"] + + +async def test_formal_runs_only_write_their_own_tables_and_only_bind_their_own_files(): + """正式运行只写自己应用的记录表(别的工作流的运行写不进来,records.table_foreign);写下的行只绑这次运行提交时 + 绑上的文件——值里随手写一个别的文件编号不会被挂到这一行上。""" + from app.db.models import Workflow + from app.db.models_blueprints import StoredFile + from app.records.actions import append_action + + app = await make_app() + table = await make_table(app, [*COLUMNS, {"name": "照片", "label": "照片", "type": "file"}]) + async with SessionLocal() as session: + mine = Workflow(name=f"报损-{uuid.uuid4().hex[:6]}", graph={"nodes": [], "edges": []}, status="published") + other = Workflow(name=f"别的-{uuid.uuid4().hex[:6]}", graph={"nodes": [], "edges": []}, status="published") + session.add_all([mine, other]) + await session.flush() + row = await session.get(App, app.id) + row.draft = {"pins": [{"alias": "main", "workflow_id": mine.id, "version": 1, "graph_hash": "x"}]} + runs = [Run(graph={"nodes": [], "edges": []}, input={}, status="running", run_class="formal", workflow_id=w.id) + for w in (mine, other)] + session.add_all(runs) + await session.flush() + files = [StoredFile(sha256="ab" * 32, name=f"{n}.png", size=1, mime="image/png", uploaded_by="amy", + bound_run_id=bound) for n, bound in (("本次", runs[0].id), ("别人的", None))] + session.add_all(files) + await session.commit() + run_ids, file_ids = [r.id for r in runs], [f.id for f in files] + + def ref(file_id: str) -> dict: + return {"file_id": file_id, "name": "a.png", "size": 1, "sha256": "ab" * 32, "type": "image/png"} + + refused = await append_action({"table": table.id, "values": {"门店": "一店", "数量": 1}}, idem_key="k:1", + run_id=run_ids[1], on_behalf={"sub": "amy"}, environment="prod") + assert refused.status is None and "不属于这个应用" in refused.error + ok = await append_action({"table": table.id, "values": {"门店": "一店", "数量": 1, "照片": ref(file_ids[0])}}, + idem_key="k2:1", run_id=run_ids[0], on_behalf={"sub": "amy"}, environment="prod") + stray = await append_action({"table": table.id, "values": {"门店": "一店", "数量": 2, "照片": ref(file_ids[1])}}, + idem_key="k3:1", run_id=run_ids[0], on_behalf={"sub": "amy"}, environment="prod") + assert ok.status == 200 and stray.status == 200 + assert store.high_water(path_of(table)) == 2, "别的工作流的那一次一行都没写" + async with SessionLocal() as session: + bound, loose = [await session.get(StoredFile, i) for i in file_ids] + assert bound.bound_record == {"table_id": table.id, "row_id": ok.body["_id"]} + assert loose.bound_record is None, "不是这次运行提交时绑上的文件不挂到这一行" + + +async def test_a_correction_only_reaches_rows_the_submitter_can_see(monkeypatch): + """更正只能更正看得到的那一行:使用者(use)只能更正自己提交的,别人提交的当它不在;查看全部的人都能更正。""" + from app.records import access + from app.records.actions import append_action + + app = await make_app(grants={"amy": "use", "cat": "observe"}) + table = await make_table(app) + bob_row = add(table, {"门店": "二店", "数量": 2}, by="bob") + amy_row = add(table, {"门店": "一店", "数量": 1}, by="amy") + + async def scope(session, app_id, *, run_class, started_by): + return {"amy": {"rows": "mine", "viewer": "amy"}, "cat": {"rows": "all"}}.get(started_by, {"rows": "none"}) + + monkeypatch.setattr(access, "scope_of_run", scope) + + async def fix(who: str, row_id: str, key: str): + return await append_action({"table": table.id, "values": {"门店": "一店", "数量": 9}, "supersedes": row_id}, + idem_key=f"{key}:1", run_id=None, on_behalf={"sub": who}, environment="prod") + + assert "不在这张记录表里" in (await fix("amy", bob_row.row_id, "a1")).error + assert (await fix("amy", amy_row.row_id, "a2")).status == 200 + assert (await fix("cat", bob_row.row_id, "c1")).status == 200 + assert "不在这张记录表里" in (await fix("dan", amy_row.row_id, "d1")).error diff --git a/backend/tests/test_settings_apps_auth.py b/backend/tests/test_settings_apps_auth.py index 113604f2..a139641c 100644 --- a/backend/tests/test_settings_apps_auth.py +++ b/backend/tests/test_settings_apps_auth.py @@ -1,6 +1,8 @@ -"""设置接口的两处改动:应用一组(按需视图的每日上限,D-j)登记进默认设置;登录设置不经 /api/settings 读写(D-l)。 +"""设置接口的两处改动:应用一组(按需视图的每日上限,D-j;使用者能不能建个人应用,normal-user-apps N7)登记进默认设置; +登录设置不经 /api/settings 读写(D-l)。 - apps.on_demand_daily_limit 默认 200,只收 0 到 100,000 的整数,写错 422、一项都不落库; +- apps.user_personal_apps 默认关,只收开或关; - auth 这一组(OIDC 客户端密钥、管理员映射)GET 不给,PUT 带着也不写——只经 /api/auth/settings 改; - 改设置只给管理员(开登录时搭建者只读)。 """ @@ -31,14 +33,16 @@ async def clean(): async def test_daily_limit_is_a_registered_setting_with_default_200(): async with auth_env.client() as c: body = (await c.get("/api/settings")).json() - assert body[APPS_GROUP] == {"on_demand_daily_limit": 200} + assert body[APPS_GROUP] == {"on_demand_daily_limit": 200, "user_personal_apps": False} put = await c.put("/api/settings", json={"values": {APPS_GROUP: {"on_demand_daily_limit": 30}}}) assert put.status_code == 200, put.text - assert put.json()[APPS_GROUP] == {"on_demand_daily_limit": 30} - assert (await c.get("/api/settings")).json()[APPS_GROUP] == {"on_demand_daily_limit": 30} + assert put.json()[APPS_GROUP] == {"on_demand_daily_limit": 30, "user_personal_apps": False} + assert (await c.get("/api/settings")).json()[APPS_GROUP] == {"on_demand_daily_limit": 30, + "user_personal_apps": False} async with SessionLocal() as session: - assert await apps_settings(session) == {"on_demand_daily_limit": 30} - assert apps_values({"on_demand_daily_limit": "坏的"}) == {"on_demand_daily_limit": 200}, "存坏了的按默认" + assert await apps_settings(session) == {"on_demand_daily_limit": 30, "user_personal_apps": False} + assert apps_values({"on_demand_daily_limit": "坏的", "user_personal_apps": "开"}) == { + "on_demand_daily_limit": 200, "user_personal_apps": False}, "存坏了的按默认" @pytest.mark.parametrize("value, fragment", [ @@ -47,6 +51,8 @@ async def test_daily_limit_is_a_registered_setting_with_default_200(): ({"on_demand_daily_limit": 1.5}, "按需视图每日上限"), ({"on_demand_daily_limit": 100_001}, "100,000"), ({"ttl": 3}, "不支持「ttl」"), + ({"user_personal_apps": "yes"}, "使用者可以建个人应用"), + ({"user_personal_apps": 1}, "只能是开或关"), ("200", "需要是一个对象"), ]) async def test_bad_daily_limits_are_refused(value, fragment): @@ -74,6 +80,9 @@ async def test_auth_settings_are_not_read_or_written_here(): await auth_env.make_user("bob", "builder") bob = await auth_env.login("bob") - assert (await bob.get("/api/settings")).json()[APPS_GROUP] == {"on_demand_daily_limit": 200} + assert (await bob.get("/api/settings")).json()[APPS_GROUP] == {"on_demand_daily_limit": 200, + "user_personal_apps": False} assert (await bob.put("/api/settings", json={"values": {APPS_GROUP: {"on_demand_daily_limit": 1}}}) ).status_code == 403, "设置页的应用一组只有管理员能改" + assert (await bob.put("/api/settings", json={"values": {APPS_GROUP: {"user_personal_apps": True}}}) + ).status_code == 403, "个人应用的开关同样只有管理员能改"