astrbot_plugin_imagestudio/审计/findings/C3-测试与仓库卫生.md

40 KiB

C3 · 测试质量 + 仓库卫生 + 配置

审计范围(实际读过 / 实际执行统计的文件):

  • 测试:tests/(45 个文件 11559 行,逐一统计;完整通读 tests/test_profile_delete_route.py、tests/test_generation_task_display.py、tests/test_advanced_style_consensus_route.py、tests/test_resource_access_service.py、tests/test_material_vision_input.py、tests/test_image_provider_timeout.py、tests/test_worker_service.py(150-230)、tests/test_advanced_style_set_workflow.py(1-80))
  • 前端测试:frontend/tests/*.mjs(8 个,通读 ui-theme-contract.test.mjs、workflow-model-route.test.mjs、workflow-cross-review-wiring.test.mjs、production-data-boundary.test.mjs)
  • 配置:config.yaml、_conf_schema.json、metadata.yaml、requirements.txt、.gitignore、main.py:110-175、core/config_service.py、frontend/package.json、DEVELOPMENT.md
  • 源码对照:backend/services/(68 个 service,31016 行)、backend/routes/(34 个模块)、backend/route_registry.py(166 个 endpoint)
  • 仓库卫生:git ls-files / git log --all / .tmp/ / .tmp_pytest_* / release/ / web/ / pages/imagestudio/ 全量文件与体积统计
  • 未审计(按规则排除):.tmp/ 内部源码副本、node_modules/、__pycache__/、release/ 内的源码、web/assets/ 与 pages/imagestudio/assets/ 的构建产物内容

摘要

测试层面:263 个后端用例可全量收集通过,核心工作流(round/queue/cross-review/advanced material)覆盖扎实,但 166 个 endpoint 中只有 33 个(19.9%)被测试触及,34 个路由模块有 24 个从未出现在测试里,68 个 service 有 23 个(4579 行)零覆盖,其中包含 integration_token_service(外部插件 token 鉴权)、chat_command_guard_service(聊天访问控制)、deletion_safety_service 三个安全相关模块。8 个前端"测试"里有 7 个是对 .vue / .css 源文本做正则匹配,不执行任何组件逻辑;35638 行 Vue 代码实质零行为测试。仓库没有 conftest.py、没有 pytest.ini/pyproject.toml,导致 pytest tests/ 直接 ModuleNotFoundError 崩溃收集,只有 python -m pytest 能跑;21 个测试文件各自重复内联同一套 SQLite Database 夹具。

仓库卫生是本维度最严重的问题。工作树里躺着 8228 个未跟踪垃圾文件 / 2.57 GB(.tmp 6303 文件 2129 MB + 20 个根级 .tmp_pytest_* 1925 文件 507 MB)。.gitignore 确实挡住了它们,但没挡住 release/(20 个 zip,37 MB 已入库)和 web/ pages/imagestudio/ 的构建产物(38 个哈希文件已入库);230 次提交里 86 次(37%)在改构建产物,历史上累计 439 个哈希命名的死 blob,.git 已膨胀到 51 MB。

最致命的一条是密钥泄漏:.env.imagestudio_codex_handoff.yaml 含 2 个真实 OpenAI 兼容 API key、PostgreSQL 明文密码、AstrBot 管理员 JWT 与明文管理员密码,虽然被 .gitignore 忽略未入库,但它已经被复制进 8 个 deploy-* 打包目录,并被打进 19 个 .tar.gz/.tar 部署包(其中 nas-deploy-worktree-20260724.tar 546 MB,还顺带打进了 3000+ 个 pytest 临时文件),这些包脚本会 scp 到 NAS。

配置层面:config.yaml 含 54 个私有区乱码字符(GBK/UTF-8 双重解码损坏),metadata.yaml 的 short_desc、CHANGELOG.md(649 处)同样损坏;_conf_schema.json 只暴露 64 个键,整个 prompt_governance(NSFW 自动分流、内容审核 failure_policy、日志留存天数)和 chat_access.adult_*_allowlist 成人内容白名单完全没有配置项,AstrBot 管理员无法在面板里配置这些安全开关。

发现

[P0-致命] 真实 API Key / DB 密码 / 管理员 JWT 被打进 19 个部署包并推送到 NAS

  • 位置:.env.imagestudio_codex_handoff.yaml:26、:45、:58、:65、:66;打包证据见 .tmp/deploy-1.0.35/.env.imagestudio_codex_handoff.yaml 等 8 个目录

  • 问题:该文件保存了可直接使用的生产/测试凭据。.gitignore 的 .env* 规则确实生效(git ls-files 确认 0 条匹配,git log --all --diff-filter=A 确认从未入库),但打包脚本用的是"整目录复制"而不是 git archive,于是把它一起带进了部署产物:

    # git ls-files 确认未入库
    $ git ls-files | grep -i env
    (空)
    
    # 但 8 个 deploy 暂存目录都含有它
    .tmp\deploy-1.0.35\.env.imagestudio_codex_handoff.yaml              3506 B
    .tmp\deploy-clean-1.0.35\.env.imagestudio_codex_handoff.yaml        3506 B
    .tmp\deploy-clean-1.0.36\.env.imagestudio_codex_handoff.yaml        3506 B
    .tmp\deploy-clean-1.0.37\.env.imagestudio_codex_handoff.yaml        3506 B
    .tmp\deploy-stage-1.0.38-20260720-092843\.env...yaml                3506 B
    .tmp\deploy-stage-1.0.39-20260720-095704\.env...yaml                3506 B
    .tmp\deploy-stage-1.0.40-20260720-100538\.env...yaml                3506 B
    .tmp\deploy-stage-1.0.41-20260720-101338\.env...yaml                3506 B
    
    # 19 个归档内含该文件(tar -tf 逐个验证)
    astrbot_plugin_imagestudio-1.0.35.tar.gz / 1.0.36 / 1.0.37
    astrbot_plugin_imagestudio-1.0.38~1.0.41-*.tar.gz
    astrbot_plugin_imagestudio-1.0.64.tar.gz / 1.0.65 / 1.0.67-* / 1.0.68-*
    imagestudio-1.0.66-deploy-20260724-224910.tar.gz
    imagestudio-material-*-20260724.tar.gz  (5 个)
    nas-deploy-worktree-20260724.tar / nas-deploy-worktree-20260724-clean.tar
    

    归档里的实际条目路径:

    $ tar -tf .tmp/astrbot_plugin_imagestudio-1.0.35.tar.gz | grep env
    astrbot_plugin_imagestudio/.env.imagestudio_codex_handoff.yaml
    $ tar -tf .tmp/astrbot_plugin_imagestudio-1.0.41-20260720-101338.tar.gz | grep env
    ./.env.imagestudio_codex_handoff.yaml
    

    文件内的凭据类型(不复述完整值):

    model_sites.site_a.api_key_plaintext: "sk-3af1f9dd7ffd25ff...(64 hex)"   # weilai.chat
    model_sites.site_b.api_key_plaintext: "sk-B6KqCtlccQ2MU5O3z2X2...(48)"   # botcf.com
    postgresql.host/port/user/password:   <PG_HOST:内网IP:已脱敏>:25008 / <PG_USER:已脱敏> / 明文密码
    astrbot.admin_token_plaintext:        "eyJhbGciOiJIUzI1NiI..." (HS256 JWT, exp=1783872299)
    astrbot.admin_username / admin_password_plaintext:  明文管理员账号密码
    

    讽刺的是文件末尾还写着 rules.redact_secrets: true。

  • 影响:任何拿到部署包的人(NAS 上的其他用户、备份、误传到公开仓库/Issue 附件)可以:① 直接盗刷两个模型站点的额度;② 连上 <PG_HOST:内网IP:已脱敏>:25008 的 PostgreSQL 读写业务库;③ 用 JWT 与管理员密码接管 AstrBot 实例(该实例还托管本插件的全部 166 个 API)。JWT exp=1783872299 换算约 2026-07-12 过期,但 admin_password_plaintext 永不过期,可随时重签。deploy_remote.sh / upload_via_ssh.py 表明这些包已经上传到 NAS。

  • 修复建议:

    1. 立刻轮换全部 5 类凭据:weilai.chat 与 botcf.com 的 API key 作废重发;PG 用户 <PG_USER:已脱敏> 改密;AstrBot 管理员改密并使 JWT 失效(改 secret)。
    2. 删除全部含泄漏的归档与 staging 目录:
      Remove-Item -Recurse -Force .tmp\deploy-1.0.35, .tmp\deploy-clean-1.0.3?, .tmp\deploy-stage-1.0.4?-*
      Get-ChildItem .tmp -File | Where-Object { $_.Name -match '\.(tar|tar\.gz|zip|b64)$' } | Remove-Item -Force
      
      并到 NAS 上删除已上传的同名包。
    3. 打包改为 git archive,从源头杜绝未跟踪文件进包:
      git archive --format=tar.gz --prefix=astrbot_plugin_imagestudio/ -o dist/plugin-$(git describe --always).tar.gz HEAD
      
      并在打包脚本末尾加断言:tar -tf "$OUT" | grep -qE '(^|/)\.env' && { echo "SECRET LEAK"; exit 1; }
    4. 凭据本身改为环境变量注入(_conf_schema.json 里已经有 *_api_key_env_var 字段,说明设计上本就支持),文件里只留 env var 名。

[P1-严重] pytest tests/ 直接崩溃:无 conftest.py、无 pytest 配置,测试只能用 python -m pytest 跑

  • 位置:仓库根(缺 conftest.py / pytest.ini / pyproject.toml / setup.cfg / tox.ini,find . -name conftest.py 全仓库 0 命中)

  • 问题:45 个测试文件全部用 from backend... / from adapters... 这类以仓库根为起点的绝对导入,但没有任何机制把仓库根加进 sys.path。只有 python -m pytest(-m 会把 CWD 插到 sys.path[0])才能工作:

    $ python -m pytest tests/test_profile_delete_route.py -q
    1 passed in 0.14s
    
    $ pytest tests/test_profile_delete_route.py -q
    tests\test_profile_delete_route.py:3: in <module>
        from adapters.astrbot_adapter import resolve_route
    E   ModuleNotFoundError: No module named 'adapters'
    =========================== short test summary ===========================
    ERROR tests/test_profile_delete_route.py
    !!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!
    
  • 影响:任何 CI 模板、IDE 测试运行器(PyCharm/VSCode 默认调 pytest)、tox、pre-commit 都会在收集阶段全军覆没,且报的是 ModuleNotFoundError 这种指向不明的错。新贡献者按直觉敲 pytest 会得到"这个仓库的测试是坏的"的结论。同时缺少配置文件也意味着没有 --strict-markers、没有超时保护、没有覆盖率门槛。

  • 修复建议:新建 pyproject.toml(或最小化的 pytest.ini):

    [tool.pytest.ini_options]
    pythonpath = ["."]
    testpaths = ["tests"]
    addopts = "-q --strict-markers"
    filterwarnings = ["error::DeprecationWarning"]
    

    pythonpath 需要 pytest >= 7.0;若要兼容更旧版本,再加一个仓库根 conftest.py:

    import sys, pathlib
    sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
    

[P1-严重] 166 个 endpoint 只有 33 个被测试触及,24/31 路由模块零覆盖(含鉴权与文件服务)

  • 位置:backend/route_registry.py(ROUTES 共 166 条)对照 tests/*.py
  • 问题:用 RouteSpec.endpoint 字面量与 handler 模块名对 45 个测试文件做全文匹配:
    total endpoints: 166   referenced in tests: 33   (19.9%)
    route modules:    31   referenced:          7    (22.6%)
    
    untested modules:
      api_discovery_routes  asset_routes      branch_routes     contract_routes
      cost_routes           dashboard_routes  data_backup_routes event_routes
      history_routes        image_routes      integration_routes job_routes
      log_routes            material_routes   media_routes      model_runtime_routes
      prompt_routes         round_routes      settings_routes   storage_routes
      ui_routes             wardrobe_routes   web_routes        workflow_routes
    
    被测的 7 个是 advanced_material_routes、generation_cross_review_routes、node_material_routes、node_routes、profile_card_routes、profile_routes、review_routes。
  • 影响:storage_routes(签名 URL / 文件下发,直接决定"前端永远不能看到本地绝对路径"这条安全约束能否守住)、integration_routes(外部插件集成入口)、settings_routes(写配置)、media_routes、data_backup_routes(导出全量数据)这几个高风险模块,任何一次重构后的权限回归都不会被测试拦住。round_routes(工作流轮次的公开入口)虽然 service 层有 1055 行测试,但路由层的参数校验/权限装饰完全裸奔。
  • 修复建议:不必给 166 个 endpoint 逐个写用例,优先补两层:
    1. 注册表级契约测试(成本极低,一次覆盖 166 条):断言每条 RouteSpec 的 handler 可 import、可调用、permission 非空且属于合法枚举;断言 assert_unique_routes() 通过。
      from backend.route_registry import ROUTES, assert_unique_routes
      def test_every_route_handler_resolves_and_declares_permission():
          assert_unique_routes()
          for spec in ROUTES:
              mod, fn = spec.handler.rsplit(".", 1)
              assert callable(getattr(importlib.import_module(mod), fn)), spec.endpoint
              assert spec.permission in {"read", "write", "admin"}, spec.endpoint
      
    2. 对 storage_routes / integration_routes / settings_routes / data_backup_routes 补越权用例,复用 tests/test_resource_access_service.py:96 已有的 owner-chain 参数化模式。

[P1-严重] 23 个 service(4579 行)零测试,其中 3 个是安全边界模块

  • 位置:backend/services/(68 个 service / 31016 行)对照 tests/*.py 全文
  • 问题:以下 service 名在整个 tests/ 目录中一次都没出现过:
    material_binding_schema_service.py    408 行
    asset_import_service.py               406
    prompt_plan_schema_service.py         379
    model_provider_bootstrap.py           375
    node_injection_template_service.py    366
    branch_lineage_service.py             356   ← 注意 tests/test_workflow_branch_lineage.py 存在
    api_discovery_service.py              351
    history_service.py                    314
    log_service.py                        300
    workflow_progression_service.py       240   ← tests/test_character_workflow_progression.py 存在
    integration_token_service.py          202   ← 外部插件 token 鉴权
    integration_service.py                171
    dashboard_service.py                  117
    chat_command_guard_service.py         101   ← 聊天侧访问控制
    chat_session_service.py                86
    web_hosting_service.py                 84
    deletion_safety_service.py             75   ← 删除前的安全检查
    reference_binding_mapper.py             69
    event_stream_service.py                 50
    chat_media_import_service.py            47
    ui_service.py                           37
    contract_service.py                     30
    media_index_service.py                  15
    ------------------------------------------------
    合计                                  4579 行 / 23 个模块(占 service 总数 33.8%)
    
    特别值得注意的是 branch_lineage_service 和 workflow_progression_service:存在同名测试文件(test_workflow_branch_lineage.py 332 行、test_character_workflow_progression.py 248 行),但它们测的是别的模块,真正的 service 一行没碰——这种"看起来有测试"的假象比明摆着没测试更危险。
  • 影响:integration_token_service(202 行 token 签发/校验)零测试 = 外部插件鉴权逻辑没有任何回归保护;chat_command_guard_service(101 行)零测试 = chat_access 白名单/限流的绕过不会被发现;deletion_safety_service(75 行)零测试 = 误删保护失效时静默。
  • 修复建议:按风险排序补三个模块即可覆盖大部分暴露面:
    1. integration_token_service:签发→校验→过期→篡改签名→重放,5 个用例。
    2. chat_command_guard_service:白名单命中/未命中、成人白名单、并发上限、日限额,4 个用例(可直接复用 tests/test_chat_workflow_round_commands.py 的 fixture)。
    3. deletion_safety_service:有引用时拒删、级联引用、强制删除路径,3 个用例。 同时把 test_workflow_branch_lineage.py / test_character_workflow_progression.py 与真实 service 接上,或改名以免误导。

[P1-严重] 前端 8 个测试里 7 个是"源码正则匹配",35638 行 Vue 零行为测试

  • 位置:frontend/tests/(8 个 .mjs),典型代表 frontend/tests/production-data-boundary.test.mjs:33-38、frontend/tests/workflow-cross-review-wiring.test.mjs:19-33

  • 问题:grep -l readFile frontend/tests/*.mjs 命中 7/8 个文件。这些"测试"把 .vue / .css 当纯文本读进来做正则断言,从不实例化组件:

    // frontend/tests/production-data-boundary.test.mjs:33
    assert.match(app, /const profilePageItems = computed<CharacterProfile\[\]>\(\(\) => backendProfiles\.value\)/)
    assert.match(app, /const imageGenerationImages[\s\S]*localGenerationImages\.value\.filter\(isAuthenticGenerationImage\)/)
    
    // frontend/tests/workflow-cross-review-wiring.test.mjs:19
    assert.equal((app.match(/<WorkflowGenerationReviewDialog\b/g) ?? []).length, 1)
    assert.match(app, /loadWorkflowRounds\(result\.round\.node_id, true\)/)
    assert.match(dialog, /model_routes: \[\.\.\.reviewModelRoutes\.value\]/)
    

    唯一真正 import 被测模块的是 frontend/tests/workflow-model-route.test.mjs(导入 workflow-model-route.ts 与 workflow-lock-state.ts 两个纯函数模块)。frontend/package.json:11-12 也证实没有任何组件测试运行器——test:contracts 就是 node --test tests/*.test.mjs,依赖树里没有 vitest / @vue/test-utils / jsdom。

  • 影响:① 假阴性——把 computed<CharacterProfile[]> 换成等价的 computed(() => ...) 会让测试红,但功能完全正常;把变量重命名、格式化工具重排一次空格,整批测试崩。② 假阳性——组件在运行时抛异常、props 契约破裂、事件不触发,这些测试全部照过。26 个用例 356 ms 跑完就是因为它们只是在做字符串匹配。③ 35638 行 Vue(36 个 .vue 文件)实际测试覆盖率为 0。

  • 修复建议:

    1. 引入 vitest + @vue/test-utils + jsdom(放进 devDependencies),把 workflow-cross-review-wiring / advanced-material-upload / production-data-boundary 这三个"接线测试"改写成挂载组件、mock endpoints、断言实际发出的请求与渲染结果。
    2. 把纯逻辑(isAuthenticGenerationImage、候选池筛选、时间戳归一化)从 App.vue 抽到 .ts 模块,按 workflow-model-route.test.mjs 的模式做真单测——这是目前唯一正确的样板。
    3. ui-theme-contract.test.mjs 这类"CSS token 必须存在"的检查保留即可,它本来就是文本契约,但要从"测试"改名为 lint(如挪到 scripts/lint-tokens.mjs 并接进 npm run lint),避免和真测试混在一起虚增数字。

[P1-严重] release/ 20 个 zip(37 MB)与前端构建产物已入库,.git 膨胀到 51 MB、37% 的提交在改产物

  • 位置:.gitignore(缺 release/、web/assets/、pages/imagestudio/assets/ 规则);release/astrbot_plugin_imagestudio-1.0.0.zip … 1.0.31.zip

  • 问题:量化结果:

    git ls-files 总数                     455
    ├─ release/*.zip                       20 个,37.02 MB(单个最大 4.23 MB)
    ├─ web/*                               19 个(18 个哈希命名构建产物 + index.html)
    └─ pages/imagestudio/*                 19 个(同上)
    → 二进制/构建产物占已跟踪文件 12.7%
    
    .git 目录                              51 MB
    提交总数                               230
    触及 web/ 或 pages/ 的提交              86  (37.4%)
    历史上出现过的 web/pages 文件路径       439  ← 当前只剩 38 个
    → 约 401 个哈希命名的死 blob 永久留在历史里
    

    且当前工作树里 13 个旧产物已删、13 个新产物未跟踪(git status 里 D pages/imagestudio/assets/index-Dp4kkpJ0.js / ?? pages/imagestudio/assets/index-3MfZqRFA.js),每次 npm run build 都会因为 Vite 的 content-hash 生成一批全新文件名,历史只增不减。

    另外 release/astrbot_plugin_imagestudio-1.0.0.zip ~ 1.0.6.zip 每个 4.2 MB,里面装的是运行期数据:

    data/temp/provider_probe_B_image2_generation.json   1.76 MB  (真实模型响应,含 b64 图片)
    data/temp/provider_probe_B_image2_generation.png    1.32 MB
    data/temp/s81_provider_runtime_b.png                0.76 MB
    data/db/imagestudio.db                              0.29 MB  (真实 SQLite 库)
    

    这与 DEVELOPMENT.md 自己写的"测试可使用临时目录,且不能把真实运行数据加入发布包"直接冲突。

  • 影响:① 每个 clone 强制拉 51 MB,其中 ~45 MB 是没人会用的历史产物;② 37% 的提交 diff 被机器生成的 minified JS 淹没,git log -p、git bisect、code review 全部失效;③ 早期 release zip 里的 imagestudio.db 与 provider probe 响应是真实数据,永久留在版本库历史中无法用 git rm 撤销。

  • 修复建议:

    1. .gitignore 补丁:
      # 发布产物:用 Git Release/附件分发,不入库
      release/
      
      # 前端构建产物(哈希命名,每次 build 都变)
      web/assets/
      pages/imagestudio/assets/
      
      注意 web/index.html 与 pages/imagestudio/index.html 需要保留(AstrBot 靠它发现插件页面),所以只忽略 assets/ 子目录。若决定连 index.html 也不入库,则需要在安装文档里加"必须先 npm run build"的前置步骤。
    2. 停止跟踪但保留本地文件:
      git rm -r --cached release web/assets pages/imagestudio/assets
      git commit -m "chore: stop tracking release archives and frontend build output"
      
    3. 若要真正瘦身 .git,需要改写历史(会让所有 clone 失效,需团队同步):
      # 需先安装 git-filter-repo
      git filter-repo --path release --path web/assets --path pages/imagestudio/assets --invert-paths
      
      不改写历史时,至少跑一次 git gc --aggressive --prune=now 回收部分空间。
    4. DEVELOPMENT.md 里"生产构建必须同时提交 pages/imagestudio/ 的最新插件页面产物"这句要一并改掉,否则规则和 .gitignore 打架。

[P1-严重] _conf_schema.json 缺失 prompt_governance 与成人内容白名单,AstrBot 面板无法配置内容安全开关

  • 位置:_conf_schema.json(共 64 个键)对照 config.yaml:96-140 与 main.py:110-175 的映射表

  • 问题:main.py 的 _CONFIG_KEY_MAP 逐条把 config.yaml 路径映射到 schema 键,schema 里没有的键在 AstrBot 面板中就不存在,也就无法被管理员配置或持久化。实测缺口:

    config.yaml 配置项 schema 键 状态
    prompt_governance.translation.*(6 项) — 全缺
    prompt_governance.moderation.llm_review_enabled / failure_policy — 全缺
    prompt_governance.routing.safe_route / nsfw_route / adult_auto_route_enabled / entrypoints.* — 全缺
    prompt_governance.image_moderation.* — 全缺
    prompt_governance.retention.*(4 项,含 redact_sensitive_logs) — 全缺
    chat_access.adult_group_allowlist — 缺(普通 group_allowlist 有)
    chat_access.adult_user_allowlist — 缺(普通 user_allowlist 有)
    security.integration_token_set / allowed_integration_plugins — 全缺
    features.quick_profile / workspace / material_library / wardrobe / api_discovery — 缺(只有 private_companion_integration)
    advanced_materials.recognition_concurrency — 缺
    storage.images_path / thumbnails_path / materials_path / styles_path / archives_path / temp_path — 缺(只有 advanced_materials_path)
    recognition_prompts.* — 全缺

    而这些键在业务代码里是真的被读的:

    # backend/services/chat_workflow_service.py:1175
    adult_users = _id_set(access.get("adult_user_allowlist"))
    adult_groups = _id_set(access.get("adult_group_allowlist"))
    # backend/services/advanced_material_service.py:1309
    adult_users = {str(value).strip() for value in access.get("adult_user_allowlist", []) if str(value).strip()}
    

    backend/services/settings_service.py:184-185 甚至在插件自己的设置页里渲染了这两个字段,说明产品意图上它们是可配置的——只是 AstrBot 侧的通道断了。

  • 影响:在 AstrBot 真实部署下,管理员只能靠手改插件目录里的 config.yaml 来打开 NSFW 分流、内容审核、成人白名单和日志脱敏;而插件更新会覆盖 config.yaml,配置静默回退到默认值——adult_auto_route_enabled: false、llm_review_enabled: false、adult_*_allowlist: []。也就是说内容安全开关在生产环境实际上不可用、且升级即丢失。

  • 修复建议:

    1. 在 _conf_schema.json 补齐这些键(至少 prompt_governance.moderation.*、prompt_governance.routing.*、chat_access.adult_*_allowlist、prompt_governance.retention.redact_sensitive_logs),并在 main.py:_CONFIG_KEY_MAP 加对应映射。
    2. 加一条防漂移测试,让 schema 与映射表永远同步:
      def test_config_key_map_and_schema_stay_in_sync():
          schema = json.loads(Path("_conf_schema.json").read_text(encoding="utf-8"))
          mapped = set(main._CONFIG_KEY_MAP.values())
          assert mapped - set(schema) == set(), "映射到不存在的 schema 键"
          assert set(schema) - mapped == set(), "schema 键未接入 config.yaml"
      
      这条测试当前应当是通过的(两边都是 64 个),所以还需要第二条:断言 config.yaml 中所有安全相关叶子路径都出现在 _CONFIG_KEY_MAP 的 key 里。
    3. postgresql_password 在 schema 里是 "type": "string",AstrBot 面板会明文回显。若 AstrBot 支持 "type": "password" 或 "secret": true,应改用;否则至少在 description 里引导用户填 dsn 并把密码放环境变量。

[P2-中等] config.yaml / metadata.yaml / CHANGELOG.md 存在编码损坏(私有区乱码),且 config.yaml 是已入库文件

  • 位置:config.yaml:15(以及全文 54 处)、metadata.yaml:5、CHANGELOG.md(649 处)

  • 问题:三个文件本身是合法 UTF-8,但内容是中文被 GBK 误解码后再存成 UTF-8 的产物,包含 Unicode 私有使用区字符(U+E000–U+F8FF),已不可逆还原:

    $ python - <<'PY'
    print(repr(open('config.yaml',encoding='utf-8').read().splitlines()[14]))
    PY
    '  # default_model 鏄?ImageStudio 璺敱鍚嶏紱route_name 鐣欑┖鏃跺鐢ㄥ畠銆?'
    

    原文应为「default_model 是 ImageStudio 路由名;route_name 留空时也用它。」

    全仓库扫描(跳过 web/ pages/ release/ frontend/):

    config.yaml       私有区字符 54 个
    CHANGELOG.md      私有区字符 649 个
    metadata.yaml     私有区字符 1 个   ← short_desc
    受影响的已跟踪文件:3
    

    metadata.yaml:5 的 short_desc 是 AstrBot 插件市场直接展示的字段:

    short_desc: AstrBot 鍐呯殑瑙掕壊璧勪骇銆佸伐浣滄祦涓庡浘鐗囩敓鎴愮鐞嗗伐浣滃彴銆?
    

    值得注意的是同一个 config.yaml 里新写的注释是正常的(config.yaml:57 「留空时沿用进阶素材识别路由」可读),说明损坏是某次工具链(很可能是 Windows 上的 PowerShell 重定向或 Set-Content 默认 ANSI 编码)一次性造成的,之后新增行没受影响。

  • 影响:① AstrBot 插件市场/管理面板会展示乱码描述,直接影响用户第一印象;② config.yaml 里 54 处注释是解释各字段语义的唯一文档(vision 段那 3 行注释解释了"Vision 模型必须单独填写,不能假定生图模型具备视觉理解能力"这种关键约束),现在完全不可读,运维只能靠猜;③ 后续任何人用编辑器打开这些文件再保存,损坏会继续扩散。

  • 修复建议:

    1. 手工重写这三个文件的中文内容(config.yaml 54 处、metadata.yaml 1 处优先;CHANGELOG.md 649 处可从 git 历史或 Release notes 恢复)。
    2. 在 DEVELOPMENT.md 的 Windows 章节明确:写文件一律 Out-File -Encoding utf8 / Set-Content -Encoding utf8,禁止裸 > 重定向。
    3. 加一条 CI/测试守卫防止复发:
      def test_no_mojibake_in_tracked_text_files():
          for name in ("config.yaml", "metadata.yaml", "_conf_schema.json", "README.md"):
              text = Path(name).read_text(encoding="utf-8")
              bad = [c for c in text if "" <= c <= ""]
              assert not bad, f"{name} 含 {len(bad)} 个私有区字符,疑似编码损坏"
      

[P2-中等] 工作树 8228 个未跟踪垃圾文件 / 2.57 GB,其中 .tmp 单目录 2.1 GB

  • 位置:.tmp/、根目录 20 个 .tmp_pytest_*/

  • 问题:.gitignore 里 .tmp/ 与 .tmp_pytest*/ 规则是生效的(git ls-files | grep '^\.tmp' 返回 0),所以不是入库问题,而是纯粹的磁盘/工作流污染。量化:

    目录 文件数 体积
    .tmp/ 6303 2129.08 MB
    .tmp_pytest_full_1022 231 68.03 MB
    .tmp_pytest_full_1030 232 67.94 MB
    .tmp_pytest_full_1031 232 67.93 MB
    .tmp_pytest_full_1022_final 231 67.92 MB
    .tmp_pytest_full_1030_x 232 67.92 MB
    .tmp_pytest_full 223 55.76 MB
    .tmp_pytest_route_refs 103 18.40 MB
    .tmp_pytest_auto_round 124 17.36 MB
    .tmp_pytest_style_set / _2 52 / 52 16.09 / 16.09 MB
    其余 10 个 .tmp_pytest_* 89 46.81 MB
    .tmp_pytest_* 小计 1925 507.25 MB
    合计 8228 2636 MB

    .tmp/ 内部有 8 个整仓库快照(deploy-1.0.35 2180 文件 496 MB、deploy-clean-1.0.35/36/37 各 390 文件 8.5 MB、4 个 deploy-stage-1.0.38~41)、22 个部署归档、~60 个一次性 patch/fix 脚本(fix_age_failures.py、fix_soft_asserts.py、patch_soft_anatomy_tests.py、patch_tests_age2.py …)、40+ 个 pytest 输出目录,以及若干真实生成图片(nas_eval_20260720/ 13 个 jpg/png 9.67 MB、latest_style_audit/ 含一个真实 imagestudio.db)。

    deploy-1.0.35 之所以是 496 MB,是因为它把根目录的 .tmp_pytest_* 一起复制进去了:

    $ Get-ChildItem .tmp/deploy-1.0.35 | Select -First 8
    .tmp_pytest_advanced  .tmp_pytest_advanced2  .tmp_pytest_config
    .tmp_pytest_full      .tmp_pytest_full_1022  .tmp_pytest_full_1022_final
    .tmp_pytest_full_1030 .tmp_pytest_full_1030_x
    

    这个错误直接导致 nas-deploy-worktree-20260724.tar 达到 546 MB(正常插件包约 8 MB,膨胀 68 倍),其二级目录分布:

    601 .tmp_pytest_full_1031      601 .tmp_pytest_full_1030_x    601 .tmp_pytest_full_1030
    599 .tmp_pytest_full_1022_final 599 .tmp_pytest_full_1022     583 .tmp_pytest_full
    365 backend                     305 .tmp_pytest_route_refs    176 tests
    

    即 3000+ 个 pytest 临时文件被 scp 到了 NAS。

  • 影响:① 2.6 GB 拖慢 IDE 索引、ripgrep、防病毒扫描与备份;② 更实际的伤害是打包脚本"整目录复制"时会把它们卷进部署包(546 MB 的 tar 已经发生),部署耗时与 NAS 空间双重浪费;③ .tmp/ 里的 60 多个 fix_*.py / patch_*.py 脚本表明有大量一次性修补动作发生在版本控制之外,这些修改无法追溯。

  • 修复建议:

    1. 清理(先确认 git status 干净):
      # 保守:先看要删什么
      Get-ChildItem . -Directory -Force -Filter '.tmp_pytest*' | Select Name, @{n='MB';e={[math]::Round((Get-ChildItem $_ -Recurse -File -Force | Measure-Object Length -Sum).Sum/1MB,2)}}
      
      # 执行
      Get-ChildItem . -Directory -Force -Filter '.tmp_pytest*' | Remove-Item -Recurse -Force
      Remove-Item -Recurse -Force .tmp
      Remove-Item -Recurse -Force .pytest_cache
      Get-ChildItem . -Directory -Recurse -Force -Filter '__pycache__' | Where-Object { $_.FullName -notmatch 'node_modules' } | Remove-Item -Recurse -Force
      
    2. 统一 pytest 临时目录出口,避免再散落到根:在 pyproject.toml 里固定 addopts = "--basetemp=.pytest_tmp",.gitignore 里 .pytest_tmp*/ 规则已存在。
    3. 打包脚本改用 git archive(见 P0 条),从根本上不再依赖"复制工作树"。

[P2-中等] 21 个测试文件各自重复内联同一套 SQLite Database 夹具,无任何共享 fixture

  • 位置:tests/test_resource_access_service.py:15-77(典型)以及其余 20 个文件的同构代码
  • 问题:grep -l "DatabaseSettings(" tests/*.py 命中 21 个文件,每一个都手写同一段初始化:
    # tests/test_resource_access_service.py:15
    def _fixture(tmp_path):
        database = Database(
            DatabaseSettings(
                backend="sqlite",
                sqlite=SqliteSettings(path=str(tmp_path / "resource-access.sqlite3")),
            )
        )
        database.initialize()
        profiles = ProfileRepository(database)
        workflows = WorkflowRepository(database)
        images = ImageRepository(database)
        jobs = JobRepository(database)
        profiles.create({...})
        workflows.create_workflow({...})
        workflows.create_node({...})
        ...
    
    同样地,_StaticConfigService(把 7 个 storage 路径指到 tmp 目录的桩类)在 tests/test_advanced_material_workflow.py 与 tests/test_advanced_style_set_workflow.py:61-75 里各写了一份完全相同的实现;RequestContext(...) 构造在 3 个文件里各自重复。仓库没有 conftest.py,所以没有任何共享位置。
  • 影响:新增一个 repository 或改一次 DatabaseSettings 签名要动 21 个文件;各文件的种子数据略有差异,导致"同一个 bug 在 A 测试里能复现、B 里不能"这类难查的不一致;也是 11559 行测试代码里相当一部分体积的来源。
  • 修复建议:新建 tests/conftest.py(顺带解决 P1 的 sys.path 问题):
    import sys, pathlib, pytest
    sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
    
    from core.config_service import ImageStudioConfig, StorageConfig
    from core.identity import RequestContext
    from database.db_helper import Database, DatabaseSettings, SqliteSettings
    
    @pytest.fixture
    def sqlite_db(tmp_path):
        db = Database(DatabaseSettings(backend="sqlite",
                                       sqlite=SqliteSettings(path=str(tmp_path / "test.sqlite3"))))
        db.initialize()
        yield db
    
    @pytest.fixture
    def storage_config(tmp_path):
        return ImageStudioConfig(storage=StorageConfig(**{
            f"{k}_path": str(tmp_path / k) for k in
            ("images", "thumbnails", "materials", "advanced_materials", "styles", "archives", "temp")
        }))
    
    @pytest.fixture
    def ctx():
        def _make(user_id="user-a", *perms):
            return RequestContext(username=user_id, user_id=user_id, platform="qq",
                                  is_authenticated=True, permissions=frozenset(perms))
        return _make
    
    然后分批把 21 个文件的 _fixture 改成注入。

[P2-中等] tests/test_material_vision_input.py 无条件 import Pillow,而 Pillow 被明确定义为可选依赖

  • 位置:tests/test_material_vision_input.py:6;requirements.txt:1-2
  • 问题:requirements.txt 全文只有注释、零条实际依赖(grep -vE "^\s*#|^\s*$" requirements.txt | wc -l = 0),且第一段就写明:
    # 帮助/状态图片卡片会在运行环境已有 Pillow 时启用;未安装时自动回退文字。
    # 为保持插件默认零依赖,不在这里强制安装 Pillow。
    
    业务代码确实遵守了这个约定(engines/image_provider.py:231-235、backend/services/api_discovery_service.py:320-324 都是 try: import httpx / except ImportError: 的软导入)。但测试没有:
    # tests/test_material_vision_input.py:6
    from PIL import Image
    
    模块级硬导入,没有 pytest.importorskip("PIL") 也没有 @pytest.mark.skipif。仓库里也没有 requirements-dev.txt 声明测试期依赖。
  • 影响:在任何按照 requirements.txt(零依赖)搭起来的干净环境里,python -m pytest tests/ 会在收集阶段报 ModuleNotFoundError: No module named 'PIL',整个 263 个用例的套件一起挂掉,而不是跳过这 2 个。这跟 P1 的 pytest 崩溃叠加,等于测试套件在标准环境下有两处一碰就碎。
  • 修复建议:
    1. 改成 Image = pytest.importorskip("PIL").Image(或文件顶部 pytest.importorskip("PIL")),让缺 Pillow 时只跳过这 2 个用例。
    2. 新建 requirements-dev.txt 显式声明测试期依赖并钉版本:
      pytest>=8.0,<9
      Pillow>=10.0,<12
      
      requirements.txt 保持零依赖不变(这个设计本身是对的)。

[P3-轻微] 前端把 vite/typescript/vue-tsc 放进 dependencies,devDependencies 为空

  • 位置:frontend/package.json:15-23
  • 问题:
    "dependencies": {
      "@vitejs/plugin-vue": "^5.2.0",
      "pinia": "^2.3.0",
      "typescript": "^5.7.0",
      "vite": "^6.0.0",
      "vue": "^3.5.0",
      "vue-router": "^4.5.0",
      "vue-tsc": "^2.2.0"
    },
    "devDependencies": {}
    
    vite、typescript、vue-tsc、@vitejs/plugin-vue 是纯构建期工具,运行期打包产物里一行都不会出现。
  • 影响:npm ci --omit=dev 无法瘦身;依赖审计(npm audit)会把构建工具的漏洞算作生产依赖漏洞,噪音掩盖真实风险。影响有限(private: true 且不发布 npm 包),但会误导任何自动化供应链扫描。
  • 修复建议:
    "dependencies": { "pinia": "^2.3.0", "vue": "^3.5.0", "vue-router": "^4.5.0" },
    "devDependencies": {
      "@vitejs/plugin-vue": "^5.2.0", "typescript": "^5.7.0",
      "vite": "^6.0.0", "vue-tsc": "^2.2.0"
    }
    

[P3-轻微] 无 CI,且 DEVELOPMENT.md 的"验证"流程根本不跑测试

  • 位置:DEVELOPMENT.md「## 验证」章节;仓库无 .github/、无 Makefile、无任何 workflow 文件
  • 问题:文档给出的唯一验证命令是:
    python -m compileall adapters backend core database engines scripts tests main.py
    cd frontend
    npm.cmd run typecheck
    npm.cmd run build:plugin
    npm.cmd run build:web
    
    compileall 只做语法编译,不执行任何一个测试;263 个后端用例和 26 个前端用例都不在流程里。而且 scripts 目录根本不存在:
    $ python -m compileall -q adapters backend core database engines scripts tests main.py
    Can't list 'scripts'
    exit=0        ← 目录缺失,但退出码仍是 0,静默通过
    
    git ls-files | grep -iE '\.github|workflow' 无任何命中,确认零 CI。
  • 影响:测试写了 11559 行却不在任何门禁上,全靠开发者自觉手跑;compileall 对缺失目录返回 0 意味着这个"验证"连自身的完整性都保证不了。230 次提交里没有一次被自动检查拦截过。
  • 修复建议:
    1. 修正 DEVELOPMENT.md,把验证改成(先落实 P1 的 pytest 配置):
      python -m pytest -q
      cd frontend
      npm.cmd run typecheck
      npm.cmd run test:contracts
      npm.cmd run build:plugin
      
      并删掉不存在的 scripts。
    2. 加最小 CI(.github/workflows/ci.yml 或对应 Forgejo Actions),矩阵只跑 python -m pytest -q + npm run typecheck + npm run test:contracts 即可,20 秒内出结果。

[P3-轻微] 4 份根目录设计文档已随版本严重过期,且 tests/test_prompt_expansion_stage_guard.py 未入库

  • 位置:imagestudio_api_contract_v3_ui_adjusted.md、imagestudio_codex_hermes_dev_flow_v3.md、imagestudio_full_plugin_dev_doc_v3_ui_adjusted.md、imagestudio_ui_navigation_queue_s130.md;tests/test_prompt_expansion_stage_guard.py

  • 问题:4 份文档写于 2026-07-04 ~ 07-06(imagestudio_full_plugin_dev_doc_v3_ui_adjusted.md 31 KB),文件名带 v3,而 metadata.yaml 当前版本已是 1.0.72,中间隔了 70 个版本、约 230 次提交。它们与 docs/ 下 20 多份带日期的审计/队列文档并存,但没有任何"已归档/已作废"标记。

    另外 git status --porcelain 显示 ?? tests/test_prompt_expansion_stage_guard.py —— 一个 60 行、2 个用例的测试文件写完了但从未提交,同时 backend/services/prompt_expansion_service.py 处于 M 修改状态。

  • 影响:新人从根目录看到 4 份体量最大的 .md 会误以为它们是当前契约(imagestudio_api_contract_v3_ui_adjusted.md 描述的 API 与现在 166 个 endpoint 的实际形态大概率已经对不上)。未入库的测试文件意味着这次改动的回归保护随时可能被 git clean 抹掉。

  • 修复建议:

    1. git mv imagestudio_*.md docs/archive/,并在每份开头加一行 > 已归档:本文档对应 v3 设计阶段(2026-07),当前实现以 docs/ 下最新日期文档与 backend/route_registry.py 为准。
    2. 立刻提交 tests/test_prompt_expansion_stage_guard.py(与它守护的 backend/services/prompt_expansion_service.py 改动同一个 commit)。