Compare commits

..

7 Commits

Author SHA1 Message Date
姚章浩 64b32c2da6 feat(settings): 数据源配置默认只列 PP 资料 + 「可加入的来源」
build / build (push) Successful in 53s
主人要求:AList 已由钉盘文件替代、钉钉知识库改为按当前账号发现 ⇒ 这两类不再出现在
数据源配置里,只保留 PP 资料与「可加入的来源」(按当前钉钉账号列出可访问的知识库与钉盘空间)。

实现(非破坏、可逆):
- 新增纯函数 splitSourceConnections(connections, showLegacy):把 alist 与 dingtalk 归为
  legacy,默认只返回 PP/手工等其余来源;showLegacy=true 时原样返回(顺序不变、一条不少)。
- 「数据源配置」新增一行折叠开关「显示 AList/钉钉知识库来源(N)」:默认收起,只显示
  PP 资料(+手动导入);展开后这 N 个来源照旧可改刷新周期、启停、看修订历史。
  **没有删除任何来源,也没有动它们的调度与目录快照。**
- 区块文案说明登记路径:新来源只从「可加入的来源」勾选登记(钉盘文件已替代 AList)。
- 测试:splitSourceConnections 直测(默认折起 a/d、展开 a/b/c/d)+ SSR 断言默认视图只含 PP、
  折叠项不在默认视图(原断言的 dingtalk 卡片标记改为折叠后的期望)。

验证:make verify 15/15;SystemSettings 用例 7/7。
2026-10-14 12:01:47 +08:00
姚章浩 b7f7e4f121 fix(deploy): 上线前校验 .env 键值形状(两行粘成一行的坏值不再能上线)
build / build (push) Successful in 1m1s
事故复盘(2026-10-14,测试实例 p1 整体不可用约 6 分钟):
- 我用 `rstrip("\n") + 新行` 往 `.env` 追加 `VERSION_HISTORY_LINK_ORIGIN`,而 `.env` 最后一行
  当时没有结尾换行 ⇒ 两行**粘成一行**:
  `VERSION_HISTORY_GITEA_BASE_URL=http://192.168.50.223:3000VERSION_HISTORY_LINK_ORIGIN=https://gitea.zheromiku.top`
- 配置校验按设计拒绝这个非法 origin ⇒ `cmd/api`/`cmd/worker` 启动即退出 ⇒ 容器 crash-loop
  (fail-closed 是对的,但代价是平台起不来)。

修复:
- `scripts/deploy-api-web.sh` 新增 **1a 步护栏**:上线前解析 `.env`,只要某行的值里又出现 `KEY=`
  (两行粘连)或键名不合法 ⇒ 打印 `ENV_VALUE_LOOKS_MERGED` 并**拒绝部署**(不动线上);
- `internal/appconfig` 在校验失败时补线索:值里含 `=` ⇒ 提示"`.env` 里两行可能粘成了一行";
- 回归用例 `TestLoadRejectsMergedVersionHistoryEnvValue`(粘行必拒 + 线索文案 + 合法值仍放行)。

验证:护栏对"粘行样例/键名非法"退出码 1、对"正常样例/当前真实 .env"退出码 0;Go 用例通过;
make verify 15/15。线上已修 `.env` 并重启 api+worker(healthy),重新同步后页面链接已全部走公网 origin。
2026-10-14 11:17:35 +08:00
姚章浩 4cb5110845 fix(version-history): 页面链接改走公网 origin(抓取仍走内网)+ tag 补链接
build / build (push) Successful in 1m1s
现象(主人反馈):点「查看提交」打开是空白页。原因:链接用的是**抓取用的内网地址**
(`http://192.168.50.223:3000/...`),内网外的浏览器到不了;而公网地址
`https://gitea.zheromiku.top/...` 实测 200。另外 tag 证据里**根本没有 url**,
页面渲染出空 `href`,点下去像"没反应"。

修复:

- 新增 `VERSION_HISTORY_LINK_ORIGIN`(页面链接 origin,公网;留空 = 与抓取 origin 相同):
  抓取仍匿名走内网白名单地址,**给人点的链接**用公网 origin 拼 —— 两者本就不该共用一个地址;
  校验必须是干净的 http(s) 绝对地址。
- tag 证据补 `url`(`<link origin>/<repo>/src/tag/<name>`),并在前端**没有链接就不渲染**该按钮。
- 测试:客户端(LinkOrigin 生效 / 未配时退回 / 非法拒绝)、规则(tag 链接写入证据 / 无基址不编链接)、
  前端(有链接才渲染「查看 tag」)。

验证:make verify 15/15;真实链路重同步后库里 commit_url = `https://gitea.zheromiku.top/...`(200)、
release_tags 带 url。
2026-10-14 11:06:13 +08:00
姚章浩 90db243a68 fix(web): 旧 index.html 的哈希资源回退到「上一版构建」,页面不再空白/裸奔
build / build (push) Successful in 56s
现象(主人反馈:页面**偶尔**变成"只有文字没样式"):旧入口 index.html 引用的是上一版的
`index-CddbQIqQ.js` / `index-DLg1Y9tN.css`,而新镜像里只剩当次构建的两个文件
⇒ JS 404 白屏、CSS 404 只有文字没样式。触发条件是"短时间内多次重建 web + CDN/浏览器还拿着旧入口"。

修复(三层,各管一段):

1. **入口不缓存**(上一笔已做):`index.html` → `no-cache, must-revalidate`,CDN/浏览器每次回源校验;
2. **旧哈希资源仍可取**(本笔):`/assets/` 未命中时先回退到只读挂载的
   `deploy/legacy-assets/assets`(**上一版构建**的资源),再 404 ⇒ 还持有旧入口的客户端
   不会因为一个文件 404 而白屏/裸奔;该目录由 `scripts/deploy-api-web.sh` 在**每次重建前**
   从"正在运行的那个镜像"里落盘(`LEGACY_ASSETS=` 会打在部署日志里),并加进 .gitignore;
3. **未命中不再回退成 HTML**:避免浏览器把 index.html 当 JS 执行报一堆语法错误。

验证:旧入口的两个引用 `assets/index-CddbQIqQ.js`、`assets/index-DLg1Y9tN.css` 现在都是 200
(旧客户端可用);当前入口的 `assets/index-Dbnd-DW-.js`、`assets/index-Bgkt4A1i.css` 也是 200;
不存在的文件名仍明确 404;`nginx -t` 通过;本机 8088 与公网入口 kg.zheromiku.top 一致;make verify 15/15。
2026-10-14 10:58:01 +08:00
姚章浩 062a3b3cb6 fix(web): index.html 不再被 CDN/浏览器缓存(否则页面停在旧构建上)
build / build (push) Successful in 55s
现象:p1 已上线新构建(容器内 bundle 是新的),但主人通过公网入口 kg.zheromiku.top 看到的
仍是旧界面(左侧菜单只有 4 项、没有「版本记录」)。实测:

- 公网入口 `/` 引用 `index-CddbQIqQ.js`(10-10 的旧包),而本机 8088 已引用 `index-Dbnd-DW-.js`;
- 带上缓存破坏参数再取同一个公网地址 ⇒ 立刻拿到新包;响应头有 `EO-Cache-Status`/`EO-LOG-UUID`
  ⇒ 中间是腾讯云 EdgeOne,把**旧 index.html** 缓存住了(浏览器同理:index.html 无缓存头时按启发式缓存)。
- 根因:`deploy/nginx.conf` 里对 `index.html` **完全没设缓存头**。

修复(只动静态入口的缓存语义,不改任何业务逻辑):

- `index.html`(含 SPA 深链回退):`Cache-Control: no-cache, must-revalidate` ⇒ 每次回源校验,
  CDN/浏览器不会再把入口钉在旧构建上;
- `/assets/`(带内容哈希):`public, max-age=31536000, immutable` 长缓存,换版本必然换文件名;
- `/assets/` 未命中明确 `404`,不再回退成 `index.html`(否则浏览器把 HTML 当 JS 执行,报一堆语法错误)。

验证:本机 8088 与公网入口 `kg.zheromiku.top` 的 index.html 都只发一条 `no-cache, must-revalidate`,
且公网入口已引用新包 `index-Dbnd-DW-.js`(其中含「版本记录」);`nginx -t` 通过;旧哈希资源 404、
SPA 深链仍 200。CHANGELOG 补 Fixed 条目。

⚠️ 本次是"新功能看起来没上线"的真实原因,已记入 deploy/nginx.conf 注释,避免复发。
2026-10-14 10:38:44 +08:00
姚章浩 4d43a9386a fix(version-history): tag 之前的提交不再被编号 + 部署脚本注入构建身份
build / build (push) Successful in 1m5s
真实数据发现(本机 p1 实例第一次同步后核对):
- **缺陷**:tag `v0.1.0` 之前的 20 个提交,提交内 CHANGELOG 顶部**也已经**是 0.1.0(旧分支遗留条目),
  而它们的祖先集合被那个**更晚才打**的 tag 全覆盖 ⇒ 按提交数算得 0 ⇒ 被错标成「0.1.0 开发版」。
  它们的正确判定是「历史提交」:那个 tag 是后来才打的,当时还没有发布基线。
- **修复**:基线 tag 必须是该提交的**祖先(或就是该提交)**,否则不给号;新增原因码
  `release_tag_created_later`(页面文案:'该版本是在更晚的提交上发布的 —— 这个提交当时还没有 tag')。
  回归用例两条:`TestDeriveVersionsDoesNotNumberCommitsThatPredateTheTag`、
  `TestDeriveVersionsSideBranchWithoutTagStaysHistorical`(不含 tag 的侧分支同样不给号)。
- **部署脚本注入构建身份**:`scripts/deploy-api-web.sh` 原先不传 `-ldflags -X`,产物 `CommitSHA=unknown`
  ⇒ 页面只能显示"当前运行版本未知"(契约上诚实,但没用)。现在按 `scripts/version.py --identity`
  (唯一来源,与 Makefile/CI 同规则)注入 VERSION/RELEASE_VERSION/BUILD_KIND/COMMITS_SINCE_RELEASE/
  COMMIT_SHA/BUILD_TIME;取不到身份**拒绝继续**(宁可不上线,也不上线一个认不出自己的产物),
  并在收尾核对注入的 SHA 真的进了产物。
- compose.yaml:把 VERSION_HISTORY_* 五项接进应用环境(api/worker 共享锚点),留空即未接线。

验证:真实仓库复验(114 条对账一致)⇒ 正式 1 / 开发 4 / 历史 109(原来错的 19 条现在都是
`release_tag_created_later`);p1 实例重新同步后当前快照分布一致,带号的记录只剩 1 正式 + 4 开发
(含真实存在的「同号不同 SHA」:950c1b4 与 3a1d32d 都是 0.1.1,各占一行);
make verify 15/15 success;前端 18 用例 + typecheck 通过。
2026-10-14 10:00:27 +08:00
姚章浩 0974d8dfa2 feat(version-history): 「版本记录」页 —— 追踪远端 main 全部提交(只读 + 管理员手动同步)
build / build (push) Successful in 57s
按已确认的契约实现(口径见 docs/VERSION_HISTORY.md):

- **版本号口径(只给有证据的)**:注释 tag + tag 指向该提交 + 该提交内 CHANGELOG 顶部三者一致 ⇒ 正式版本;
  tag 之后的提交按 `<主>.<次>.<自该 tag 的提交数>` 显示开发号(与 scripts/version.py **同规则**);
  证据不足 ⇒ 「历史提交 · 短SHA」+ 原因码,**不补造版本号**。完整 SHA 是唯一身份、版本号不是唯一键
  (tag 之后两条并行分支各自的第 1 个提交都算 0.1.1 ⇒ 两条都保留,用短 SHA 区分)。
- **迁移 000046**:version_history_commits(提交记录,主键 repo_key+commit_sha)+ version_history_sync_runs
  (同步状态)。快照 = 一次同步:抓完并与 X-Total-Count 对账通过才切换;失败不切换快照、不清空历史、
  last_success_at 不动(页面显示"上次同步失败(原因)· 仍展示上次成功数据");「同步成功」≠「历史完整」。
- **只读客户端(匿名,不使用任何凭据)**:白名单 origin + 固定仓库、拒绝任意 URL 与跨主机重定向、
  响应上限 5MB / 超时 15s、仅 5xx/429 退避重试(最多 3 次);逐页抓到短页为止;每次全量扫 tag
  ⇒ 旧提交后补的 tag 会更新既有记录(不新增第二行)。
- **接口**(三个都登记进 api/openapi.yaml):GET /api/v1/build-info(viewer)、
  GET /api/v1/version-history(viewer;游标绑定快照,过期返回 409 cursor_expired;不返回伪造 total)、
  POST /api/v1/version-history/sync(admin;并发同步复用同一作业,靠 IdempotencyKey)。
- **「当前运行」只认精确匹配**:产物注入的完整 SHA 命中某条记录才标该条;开发构建显式标注"开发构建";
  没有可用标识 ⇒ "当前运行版本未知";**不拿最新 main / 最新 tag 顶替**,CI 成功不等于已部署。
- **前端**:一级菜单第 5 项(版本记录)+ 时间线页面(全部/正式/开发/历史四段筛选、正文展开、
  加载更多、760px 单列无横向溢出、提交正文与变更记录按纯文本渲染);无打 tag / 发布 / 部署入口。

新增配置(留空即未接线,页面降级):VERSION_HISTORY_GITEA_BASE_URL / _REPO / _ALLOWED_ORIGINS /
_HTTP_TIMEOUT / _MAX_PAGES。

验证:`make verify` 15/15 success(tests-go 578 通过 / 0 失败;tests-web 209 通过 / 0 失败);
新增 Go 用例 30(版本口径与图遍历 12、客户端守卫 6、同步编排 5、接口 7);前端新增 18(组件 10 + 客户端 8);
真实仓库匿名快照拉取(`VERSION_HISTORY_LIVE_BASE_URL=… go test -run TestLiveSyncAgainstRealRepository`):
抓到 113 条与 X-Total-Count 一致、v0.1.0 是注释 tag 且目标与 `git rev-parse v0.1.0^{commit}` 一致、
开发号逐个等于 `git rev-list --count v0.1.0..<sha>`(正式 1 / 开发 22 / 历史 90)。
2026-10-13 19:40:19 +08:00
44 changed files with 9310 additions and 941 deletions
+12
View File
@@ -28,3 +28,15 @@ TEST_WEKNORA_POLL_MAX=60s
TEST_WEKNORA_STALLED_AFTER=30m
TEST_WEKNORA_MAX_UPLOAD_BYTES=52428800
TEST_ACCEPTANCE_POLICY_VERSION=structural-v1
# 「版本记录」页:**匿名只读**远端仓库的提交与 tag(**不使用任何凭据**)。
# 留空即"未接线"(页面降级展示、同步按钮不可用)。只允许下面批准的 origin 与固定仓库,
# 不接受任何调用方传入的 URL;`VERSION_HISTORY_REPO` 必须是 owner/name。
VERSION_HISTORY_GITEA_BASE_URL=
VERSION_HISTORY_REPO=Weknora/knowledge-governance
VERSION_HISTORY_ALLOWED_ORIGINS=
# 页面上的「查看提交 / 查看 tag」链接用哪个 origin —— 抓取可以走内网,但链接必须能被
# **点它的人**打开(否则点开是空白)。留空 = 与上面的抓取地址相同。
VERSION_HISTORY_LINK_ORIGIN=https://gitea.zheromiku.top
VERSION_HISTORY_HTTP_TIMEOUT=15s
VERSION_HISTORY_MAX_PAGES=200
+2
View File
@@ -43,3 +43,5 @@ backups/
.ci-remote-tags
.ci-commits-count
.ci-preview-url
# 上一版构建的静态资源(部署脚本落盘、只读挂载的运行时目录,不进 git)
deploy/legacy-assets/
+27
View File
@@ -1,5 +1,32 @@
# Changelog
## [Unreleased]
### Added
- **「版本记录」页**(一级菜单第 5 项):只读时间线追踪**远端 main 可达的全部提交**(含合并提交与已并入 main 的侧分支提交),按提交时间倒序显示标题/正文、`[正式版本] / [开发版本] / [历史提交]` 徽标、短 SHA、提交内变更记录与 `[查看提交]`/`[查看 tag]`;支持「全部 / 正式 / 开发 / 历史」筛选与游标翻页,窄屏单列。
- 新增只读接口 `GET /api/v1/build-info`(当前运行产物的构建身份)、`GET /api/v1/version-history`(快照游标分页,不返回伪造的 total)、`POST /api/v1/version-history/sync`(仅管理员手动同步,并发同步复用同一作业)。
- 新增迁移 `000046_version_history`(提交记录 + 同步状态):`commit_sha` 是唯一身份,**版本号不是唯一键** —— 两个提交算出同一个开发号时各占一行,用 SHA 区分。
- 「当前运行」只认运行产物注入的**完整 SHA 精确匹配**:匹配到就标该条;开发构建显式标注"开发构建";拿不到标识就显示"当前运行版本未知",**不拿最新 main 或最新 tag 顶替**;CI 成功不等于已部署。
### Changed
- 「系统设置 → 数据源配置」默认只列 PP 资料与「可加入的来源」:AList 来源(已由钉盘文件替代)与静态登记的钉钉知识库来源(改为按当前钉钉账号发现)**不再默认列出**,收进「显示 AList/钉钉知识库来源(N)」折叠开关 —— **来源一个都没删**,展开后照旧可改刷新周期与启停,「来源与目录」里的内容不变。手动导入来源(本地手工验收)不在这次范围内,照旧显示。
### Fixed
- 前端入口与静态资源的缓存语义("新功能看起来没上线"与"页面偶尔裸奔/空白"的根因):
- `index.html` 此前**没有缓存头**,CDN/浏览器按启发式缓存它 ⇒ 页面会一直停在旧构建上(实测被腾讯云 EdgeOne 卡住:源站已是新包,公网入口仍发旧包)。现在 `index.html` 每次回源校验(`no-cache, must-revalidate`);
- 带内容哈希的 `/assets/` 长缓存(`immutable`),但**未命中时先回退到"上一版构建的资源"目录、再 404**(`deploy/legacy-assets` 由部署脚本在每次重建前落盘并只读挂载):CDN/浏览器仍持有旧 `index.html` 时,它引用的旧 JS/CSS 依旧能取到 ⇒ 不会出现"JS 404 白屏"或"CSS 404 只有文字没样式";
- 明确 404 时不再回退成 `index.html`(否则浏览器把 HTML 当 JS 执行,报一堆语法错误)。
- **上线前护栏 + 事故复盘**:`scripts/deploy-api-web.sh` 现在先校验 `.env` 的键值形状(值里再出现 `KEY=` 或键名不合法 ⇒ **拒绝上线**),配置校验失败时也会给出"两行粘成一行"的线索。事故:`.env` 最后一行没有结尾换行、又被追加新键 ⇒ 两行粘成一行 ⇒ `VERSION_HISTORY_GITEA_BASE_URL` 变成非法值 ⇒ api/worker 按设计拒绝启动、崩溃重启(平台整体不可用)。已修数据、加护栏、加回归用例。
- 「版本记录」页的链接改为**抓取与链接分离**:抓取仍走配置的(内网)地址,页面上的「查看提交 / 查看 tag」用 `VERSION_HISTORY_LINK_ORIGIN`(公网 origin)拼 —— 原先两者共用内网地址,内网外的浏览器点开是空白;另外 tag 记录原先不带链接(空 `href` 点下去没反应),现在补上链接、没有链接就不渲染该按钮。
### Security
- 版本记录同步**匿名只读**远端仓库(**不使用任何凭据**),来源限配置里批准的 origin 与固定仓库:拒绝任意 URL、拒绝跨主机重定向,单个响应设大小上限与超时、5xx/429 才有退避重试。
- 提交正文与变更记录一律按**纯文本**渲染(不产生 HTML/脚本注入面);页面不含打 tag / 发布 / 部署入口;同步动作仅管理员可用,服务端再次判角色。
> **版本号的唯一来源就是本文件顶部那条已发布版本。** 不放 `VERSION` 文件、不把版本写进源码常量。
>
> **正式版本**用**注释 tag** `vX.Y.Z`(由人批准后创建):CI 只**核验**「tag 的版本 == 它指到那个提交里的
+100
View File
@@ -44,6 +44,106 @@
}
],
"paths": {
"/api/v1/build-info": {
"get": {
"tags": [
"Runtime"
],
"operationId": "getBuildInfo",
"summary": "读取当前运行产物的构建身份(正式版本/构建类型/完整提交 SHA);拿不到注入就明确返回不可用",
"responses": {
"200": {
"$ref": "#/components/responses/Envelope"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"500": {
"$ref": "#/components/responses/InternalError"
}
}
}
},
"/api/v1/version-history": {
"get": {
"tags": [
"Runtime"
],
"operationId": "listVersionHistory",
"summary": "按快照游标分页列出远端 main 可达的提交、版本号证据与「当前运行」判据",
"parameters": [
{
"name": "kind",
"in": "query",
"required": false,
"schema": {
"type": "string",
"enum": [
"all",
"release",
"development",
"historical"
]
}
},
{
"name": "limit",
"in": "query",
"required": false,
"schema": {
"type": "integer",
"minimum": 1,
"maximum": 100
}
},
{
"name": "cursor",
"in": "query",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"$ref": "#/components/responses/Envelope"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"409": {
"description": "游标指向的记录快照已被清理,需要刷新后重新加载"
},
"500": {
"$ref": "#/components/responses/InternalError"
}
}
}
},
"/api/v1/version-history/sync": {
"post": {
"tags": [
"Runtime"
],
"operationId": "syncVersionHistory",
"summary": "手动同步一次版本记录(仅管理员;并发同步复用同一个作业)",
"responses": {
"200": {
"$ref": "#/components/responses/Envelope"
},
"202": {
"description": "已入队同步任务"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"500": {
"$ref": "#/components/responses/InternalError"
}
}
}
},
"/api/v1/backup-schedule": {
"get": {
"tags": [
+9 -2
View File
@@ -120,6 +120,11 @@ func run(ctx context.Context, getenv func(string) string) error {
TestAllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
ProductionAllowDockerHTTP: config.ProductionWeKnoraAllowDockerHTTP,
})
// 「版本记录」:只读查询面在 API 侧接线;真正的抓取在 worker 侧(未配置来源即未接线)。
versionHistoryStore, versionHistoryRepo := httpapi.VersionHistoryStore(nil), ""
if config.VersionHistoryGiteaBaseURL != "" {
versionHistoryStore, versionHistoryRepo = postgresstore.NewStore(pool), config.VersionHistoryRepo
}
handler, err := httpapi.NewHandler(httpapi.Config{
Store: postgresstore.NewStore(pool),
Monitor: monitorProvider,
@@ -137,8 +142,10 @@ func run(ctx context.Context, getenv func(string) string) error {
ProductionReleaseAuthorizerRef: config.ProductionReleaseAuthorizerRef,
ProductionReleaseAuthorizationToken: releaseAuthorizationToken,
// 数据源发现(系统设置 → 数据源配置):用与 worker 同一份 dws 状态做只读列举。
DingtalkSources: dingtalkSourceLister{},
BackupSchedule: postgresstore.NewStore(pool),
DingtalkSources: dingtalkSourceLister{},
BackupSchedule: postgresstore.NewStore(pool),
VersionHistory: versionHistoryStore,
VersionHistoryRepo: versionHistoryRepo,
BackupHost: backuphost.New(backuphost.Config{
SSHConfig: config.BackupHostSSHConfig,
Target: config.BackupHostTarget,
+38
View File
@@ -2,6 +2,7 @@ package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
@@ -16,6 +17,7 @@ import (
"knowledge-governance/internal/jobs"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/platform/weknora"
"knowledge-governance/internal/versionhistory"
artifactfetch "knowledge-governance/internal/workflows/artifactfetch"
catalogrefresh "knowledge-governance/internal/workflows/catalogrefresh"
"knowledge-governance/internal/workflows/sourcescan"
@@ -110,6 +112,42 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
return nil, fmt.Errorf("create artifact fetch handler: %w", err)
}
handlers["artifact.fetch"] = artifactHandler.Handle
if config.VersionHistoryGiteaBaseURL != "" {
// 「版本记录」同步:匿名只读远端仓库的提交/tag,写本库快照。未配置来源就不注册,
// 界面上的同步按钮也会显示"未接线",不会入队一个没人处理的作业。
client, err := versionhistory.NewGiteaClient(versionhistory.GiteaConfig{
BaseURL: config.VersionHistoryGiteaBaseURL,
AllowedBaseURLs: config.VersionHistoryAllowedOrigins,
LinkOrigin: config.VersionHistoryLinkOrigin,
Repo: config.VersionHistoryRepo,
Timeout: config.VersionHistoryHTTPTimeout,
})
if err != nil {
return nil, fmt.Errorf("create version history client: %w", err)
}
syncer, err := versionhistory.NewSyncer(versionhistory.SyncerConfig{Source: client, Store: store,
RepoKey: config.VersionHistoryRepo, MaxPages: config.VersionHistoryMaxPages})
if err != nil {
return nil, fmt.Errorf("create version history syncer: %w", err)
}
handlers[versionhistory.JobType] = func(ctx context.Context, job jobs.Job) error {
triggeredBy := ""
var payload struct {
TriggeredBy string `json:"triggered_by"`
}
if err := json.Unmarshal(job.Payload, &payload); err == nil {
triggeredBy = payload.TriggeredBy
}
run, err := syncer.Sync(ctx, job.ID, triggeredBy)
if err != nil {
log.Printf("version history sync failed job=%s run=%d code=%s: %v", job.ID, run.ID, run.ErrorCode, err)
return err
}
log.Printf("version history sync completed job=%s run=%d fetched=%d expected=%v complete=%v",
job.ID, run.ID, run.FetchedCount, run.ExpectedCount, run.Complete)
return nil
}
}
if config.PPScanEnabled {
scanner, err := sourcescan.NewFilePPScanner(sourcescan.FilePPScannerConfig{
AllowedRoot: config.PPScanAllowedRoot,
+13
View File
@@ -40,6 +40,15 @@ services:
MINERU_BASE_URL: "${MINERU_BASE_URL:-}"
TEST_INTERNAL_WEKNORA_KB_ID: "${TEST_INTERNAL_WEKNORA_KB_ID:-1b52c140-2e18-4676-afc5-4c7d8d190a8c}"
TEST_EXTERNAL_WEKNORA_KB_ID: "${TEST_EXTERNAL_WEKNORA_KB_ID:-fd7db6aa-763a-46f1-84d2-ecc7c952a5ea}"
# 「版本记录」页:**匿名只读**远端仓库的提交与 tag(不使用任何凭据)。
# 留空 = 未接线(页面降级、同步入口不可用);来源只允许下面批准的 origin 与固定仓库。
VERSION_HISTORY_GITEA_BASE_URL: "${VERSION_HISTORY_GITEA_BASE_URL:-}"
VERSION_HISTORY_REPO: "${VERSION_HISTORY_REPO:-Weknora/knowledge-governance}"
VERSION_HISTORY_ALLOWED_ORIGINS: "${VERSION_HISTORY_ALLOWED_ORIGINS:-}"
# 页面链接用的 origin(给内网外的浏览器点开);留空 = 与抓取 origin 相同。
VERSION_HISTORY_LINK_ORIGIN: "${VERSION_HISTORY_LINK_ORIGIN:-}"
VERSION_HISTORY_HTTP_TIMEOUT: "${VERSION_HISTORY_HTTP_TIMEOUT:-15s}"
VERSION_HISTORY_MAX_PAGES: "${VERSION_HISTORY_MAX_PAGES:-200}"
# P10 readiness probe reads the routing KB with the same scoped key.
TEST_WEKNORA_API_KEY_FILE: /run/secrets/test_weknora_api_key
TEST_WEKNORA_ALLOW_DOCKER_HTTP: "${TEST_WEKNORA_ALLOW_DOCKER_HTTP:-false}"
@@ -204,6 +213,10 @@ services:
api:
condition: service_healthy
read_only: true
volumes:
# 上一版构建的静态资源(只读,由部署脚本落盘):CDN/浏览器可能还持有旧 index.html,
# 让它的旧哈希引用不至于 404 —— 否则页面会空白或"只有文字没样式"。
- ./deploy/legacy-assets:/usr/share/nginx/legacy:ro
tmpfs:
- /tmp
- /var/cache/nginx
+25
View File
@@ -25,7 +25,32 @@ server {
proxy_set_header Host $host;
}
# 带内容哈希的构建产物:可以长期缓存(换版本必然换文件名);旧哈希文件已被新构建替换
# ⇒ 明确 404,不要回退成 index.html(否则浏览器把 HTML 当 JS 执行,报一堆语法错误)。
location /assets/ {
expires 1y;
add_header Cache-Control "public, max-age=31536000, immutable";
# 当前构建里没有再找**上一版构建**的资源:CDN/浏览器可能还持有旧 index.html,
# 它引用的旧哈希文件若直接 404,页面就会空白或"裸奔"(只有文字没样式)。
# 旧目录由部署脚本在每次重建前落盘(deploy/legacy-assets,只读挂载)。
try_files $uri @legacy;
}
location @legacy {
root /usr/share/nginx/legacy;
try_files $uri =404;
}
# ⚠️ index.html(含 SPA 深链回退)**必须每次回源校验**:它引用的是带哈希的 JS 文件名,
# 一旦被 CDN/浏览器缓存住,页面就一直停在旧构建上(看着像"新功能没上线")。
# 2026-10-14 实测被腾讯云 EdgeOne 缓存卡住过一次:源站已是新包,公网入口仍发旧包。
location = /index.html {
# 只发一条 Cache-Control(`expires -1` 会再发一条,CDN 读到哪条说不准)。
add_header Cache-Control "no-cache, must-revalidate" always;
}
location / {
try_files $uri $uri/ /index.html;
add_header Cache-Control "no-cache, must-revalidate" always;
}
}
+80
View File
@@ -0,0 +1,80 @@
# 版本记录(全部 main 提交时间线)
「版本记录」是平台一级菜单的只读页面:追踪**远端 main 可达的每一个提交**(含合并提交与已并入 main
的侧分支提交),按提交时间倒序展示,并标注它对应哪一版、有没有正式 tag、是不是当前正在跑的那份产物。
## 一、版本号口径(只给有证据的号)
| 判定 | 条件(全部可机器核验) | 页面显示 |
|---|---|---|
| **正式版本** | ① 有 tag `vX.Y.Z` 指向该提交;② 该 tag 是**注释 tag**(Gitea `/git/refs/tags` 的 `object.type == "tag"`);③ 该提交内 `CHANGELOG.md` 顶部版本 == `X.Y.Z` | `0.1.0` + `[正式版本]`,正文取该提交内的变更记录 |
| **开发版本** | 该提交内 CHANGELOG 顶部有版本号,且存在 `v<该版本>` tag、能算出「自该 tag 以来的提交数」n | `<主>.<次>.<n>` + `[开发版本]`(与 `scripts/version.py` **同规则**:n=0 时等于版本号本身) |
| **历史提交** | 证据不足(轻量 tag / tag 与提交内记录不一致 / 找不到基线 / 提交图不完整) | `历史提交 · <短SHA>` + 具体原因,**不补造版本号** |
- **完整 SHA 是唯一身份**,版本号不是唯一键:两个提交算出同一个号(例如 tag 之后两个并行分支各自第 1 个提交都是 `0.1.1`)时**两条都保留**,用短 SHA 区分。
- 提交数按提交图算(等价 `git rev-list --count <tag>..<sha>`),**不执行历史提交里的任何脚本**;提交图不完整(检出被截断)时拒绝给号,原因码 `shallow_or_incomplete_graph`。
## 二、数据与同步
- 两张表(迁移 `000046_version_history`):`version_history_commits`(提交记录,主键 `repo_key + commit_sha`)、`version_history_sync_runs`(同步状态)。
- **快照 = 一次同步**(`snapshot_id = sync_runs.id`):抓取期间旧快照继续对外可见;抓完并**与 `X-Total-Count` 对账通过**后才成为事实。失败**不切换快照**、不清空历史,`last_success_at` 保持不动 ⇒ 页面显示"上次同步失败(原因)· 仍展示上次成功的数据(时间)"。
- **同步成功 ≠ 历史完整**:`complete=false` 时页面显示"部分历史(N/M)"。
- 抓取方式:`GET /repos/{owner}/{repo}/commits?limit=50&page=N` 逐页到短页为止(本仓 113 条 = 3 页);**每次同步都全量扫 tag**,因此"旧提交后补的 tag"会更新到既有记录(不新增第二行)。
- 游标绑定快照(`base64(snapshot_id|committed_at|sha)`),排序 `committed_at DESC, commit_sha DESC` ⇒ 翻页确定性、不重不漏;游标指向的快照被清理后返回 `409 cursor_expired`,页面提示刷新。
- 只保留最近 **3** 个成功快照供游标使用(`VersionHistoryKeptSnapshots`)。
## 三、当前运行(只认精确匹配)
- `GET /api/v1/build-info` 回运行产物由 `-ldflags -X` 注入的身份:`release_version / build_kind / commit_sha(完整 40 位)/ display_version / built_at / identity_available`。
- 页面判据:完整 SHA **精确命中**某条记录 ⇒ 标该条;`build_kind=development` 且命中不了 ⇒ 顶部显示"开发构建 `<号>`(短SHA)",**不标任何条目**;没有可用标识 ⇒ "当前运行版本未知"。
- **绝不**用"最新 main"或"最新 tag"顶替当前运行;**CI 成功不等于已部署**。
## 四、配置(匿名只读,不使用凭据)
```text
VERSION_HISTORY_GITEA_BASE_URL=http://192.168.50.223:3000 # 留空 = 未接线(页面降级,同步按钮不可用)
VERSION_HISTORY_REPO=Weknora/knowledge-governance # 固定 owner/name
VERSION_HISTORY_ALLOWED_ORIGINS= # 逗号分隔白名单;留空 = 只允许上面那个 origin
VERSION_HISTORY_HTTP_TIMEOUT=15s
VERSION_HISTORY_MAX_PAGES=200
```
安全边界:来源必须落在白名单 origin 与固定仓库内(**拒绝任意 URL**)、拒绝跨主机重定向、单响应大小上限 5MB、
超时 15s、仅 5xx/429 退避重试(最多 3 次);**请求不携带任何凭据**;提交正文与变更记录一律按**纯文本**渲染。
## 五、接口与权限
| 接口 | 最小角色 | 说明 |
|---|---|---|
| `GET /api/v1/build-info` | viewer | 当前运行产物的构建身份(只回身份字段) |
| `GET /api/v1/version-history` | viewer | 游标分页列表;带 `sync` 状态与 `current_running` 判定 |
| `POST /api/v1/version-history/sync` | **admin** | 手动同步一次;并发同步**复用同一个作业**(`IdempotencyKey`) |
三个接口都登记在 `api/openapi.yaml`(契约测试会核对)。
## 六、同步触发
初版只有**管理员手动同步**(页面上「同步记录」按钮,仅管理员可见);**不默认新增定时调度**。
## 七、验证
```bash
# 单元与规则(含分页去重、对账失败、不可达保留旧快照、后补 tag 升级、同号不同 SHA)
go test ./internal/versionhistory/ ./internal/governance/ ./internal/httpapi/ -count=1
# 真实仓库交叉核对(**匿名**;未设变量即按设计跳过,理由在 scripts/test-scope.json)
VERSION_HISTORY_LIVE_BASE_URL=http://192.168.50.223:3000 \
go test ./internal/versionhistory/ -run TestLiveSyncAgainstRealRepository -count=1 -v
# 全量门禁
make verify
```
真实仓库交叉核对会断言:抓到条数 == `X-Total-Count`、SHA 不重复、`vX.Y.Z` 是注释 tag 且目标与
`git rev-parse vX.Y.Z^{commit}` 一致、开发号与本地 `git rev-list --count vX.Y.Z..<sha>` 逐个相等。
## 八、不做什么
- 不提供打 tag / 发布 / 部署入口;同步不改远端任何东西(只读 GET)。
- 不用最新 tag 给历史提交重新编号,不给证据不足的提交编版本号。
- 不把「软件版本」与「知识发布批次」混在一起(发布批次在「发布管理」)。
@@ -0,0 +1,450 @@
# DobotAI 2.0 知识运营报表数据链路分析
> 调查日期:2026-10-14(Asia/Shanghai)
> 阶段:只读现状调查与架构建议,未实施开发。
> 结论等级:**线上已核实**=本轮 DWS 真实响应;**源码已核实**=本地实现/迁移证据;**待确认**=生产部署或数据不可访问,不能用源码代替线上事实。
> 本文不含员工原始记录、问答原文、密码或 Token。
## 0. 摘要与调查边界
### 0.1 核心结论
1. **现有数据不是一条统一链路。** 至少有 DobotAI Go 后端问答/规则覆盖判定、钉钉 AI 表格标签、Python 离线统计三套实现;目前不能把它们的“覆盖/正确”视为同一指标。
2. DWS 核实 `w0nYx0a` 为 **问题流水表 (2.0)**,`jQ6oevs` 为 **问题流水表**。截至本轮聚合,分别为 **2,121 / 13,275 条**;两表日期重叠,不能简单拼接后当作去重后的总使用量。
3. **2.0 表覆盖、正确性、产品、部门、区域填值数均为 0。** 因而仅依赖这张表,当前不能生成可信的质量与维度周报。后端源码另有 `coverage_decisions`,但生产数据完整率尚未核实。
4. 后端覆盖器是**确定性规则**,不是 LLM 正确性评测;引用存在不等于回答正确。源码未发现对应的 AI 正确性评估存储/服务。
5. 现有流水统计脚本正确率为“正确=是 /(正确=是+否)”,**不要求该行已覆盖**;与用户本轮期望口径不同。
6. 推荐先确认生产源、评估来源与分母,再新增一个轻量统计模块;报表 API 和邮件均复用它。**不重建问答日志,不把监控任务成功率当作回答正确率。**
### 0.2 已检查范围与限制
| 范围 | 检查方式 | 证据级别 / 限制 |
|---|---|---|
| 两张指定 AI 表格 | DWS `table get`、`field get`、`record stats`、`record group-stats` | 线上已核实;不全量读取问答,不导出员工记录 |
| `/home/zheromiku/dobotai-platform` | Go 源码、数据库迁移、HTTP 路由、导出流程 | 源码已核实;HEAD `0fc73c415245073a7a94aa9afb1fe35ca9c1fb3e`,工作区有已有未提交改动,HEAD 不代表线上版本 |
| `/home/zheromiku/knowledge-governance` | API、监控、工作流及目录结构 | 源码已核实;HEAD `b7f7e4f12101569db5bb76af9d836043eefc342b`,工作区有已有未提交改动 |
| `/home/zheromiku/knowledge-adapter-service` | 检索模型、API、日志实现 | 源码已核实;未检查 live 检索/问答系统 |
| `/home/zheromiku/DOBOTAI/{weekly_report,kb_ops,knowledge_ai_report}` | 现有 Python 统计、清洗和映射代码 | 源码已核实;没有运行会写 Excel/日志的流水线 |
| 后端 live PostgreSQL | 尝试使用本地既有连接配置,只读连接 | **连接失败,未能执行任何查询**;不能确认 live 表、迁移、行数及版本 |
| 运行服务版本 | 本地候选服务 `/version` 只读探测 | 未成功取得 DobotAI 版本响应;生产地址、部署 SHA 待确认 |
| 表格重复事件 | DWS PostgreSQL 聚合探测 | 返回 `Invalid PostgreSQL query`;**未得到重复率,不能宣称已完成去重核验** |
DWS 大请求曾出现下游 `code: 800`,拆成单字段聚合后成功。覆盖分组响应没有提供可解释的选项值,改按 `field get` 取得的稳定 option ID 分别计数,避免猜测分组对应关系。所有下述主要计数的响应数据版本均为 **23215**;这是表格数据版本,**不是评估器版本**。
## 1. 当前系统架构与数据流
### 1.1 问答后端:源码链路
```text
钉钉消息(群聊须 @) / POST /v1/qa
→ 身份与会话解析、Agent 绑定
→ BeginTurn:channel_actors / channel_conversations / messages / turns
→ WeKnora Agent Chat:生成答案与引用
→ FinishTurn:更新 turns,保存出站 messages
├→ 成功轮次 observer:coverage.Service
│ → coverage_decisions
│ → 若未覆盖,同时创建 support_cases
├→ 钉钉实际送达:单独记录 messages 送达状态
└→ 可选 question_table_exports outbox
→ 异步写入 AI 表格基础问答和人员快照
→ 本地记录 external_record_id
```
证据:`DP/internal/store/postgres/store.go:50–129,196–283`;`DP/internal/qa/service.go:166–177,285–298`;`DP/cmd/dobotai/main.go:84–95,188–203`。
**边界:**`turns.status=succeeded` 表示答案生成成功,不等同于用户成功收到答案。覆盖评估保存失败不会把成功问答改为失败,故成功轮次可能没有覆盖记录;成功请求重放提前返回,不自动补评估。
### 1.2 表格和离线报表:已核实链路与断点
```text
AI 表格:问题、答案、人员、时间 + 覆盖/正确/产品等标签
→ 本地 Excel / 离线流水与问题主表
→ 人员部门映射(08) → 部门区域映射(09)
→ 月区域使用统计(10) / 知识指标统计(12)
→ Excel 汇总
```
- 后端 `internal/questiontable/row.go:40–41` 明确**省略** `是否覆盖/是否正确/产品分类/问题类型/根因分析` 五个 select 字段;导出 SQL 也未读取 `coverage_decisions`。
- 两张表有评估字段,不代表已查明谁填写、何时填写、是否由 AI 自动评估;完整字段读取未返回 AI 配置证据。
- Base 工作流列表返回 3 个工作流、`runningCount=0`。这只说明本次列表中没有运行中的 Base 工作流,**不能排除外部自动化、定时脚本或人工评估**。
- 本轮未核实“线上 AI 表格 → 本地 Excel”的自动同步和执行调度,也未核实当前正式周报调用哪份脚本。
### 1.3 知识治理和检索适配的边界
知识治理当前负责知识源、解析、发布及监控;Adapter 提供检索,不生成最终答案。现有监控 API 的 `success_rate` 来源是 `jobs` 的 completed/failed,**不是回答正确率**。
证据:`KG/internal/monitoring/metrics.go:25–44,73–86`;`KG/internal/monitoring/real.go:109–181`;`KA/src/knowledge_adapter/app.py:131–160`、`models.py:27–33`。
## 2. 实际数据表、字段及关联关系
### 2.1 线上 AI 表格
共同 Base:`KGZLxjv9VG37o9N6IYvYGBl9V6EDybno`。
| 表 | tableId | viewId | 本轮记录数 | 提问时间最小值 — 最大值 |
|---|---|---|---:|---|
| 问题流水表 (2.0) | `w0nYx0a` | `Qr19nXJ` | 2,121 | 2026-09-12 19:43:30 — 2026-10-14 11:45:30 +08:00 |
| 问题流水表(旧表) | `jQ6oevs` | `TE2xi1m` | 13,275 | 2026-04-01 03:02:00 — 2026-10-14 11:44:23 +08:00 |
以上是 `COUNT` 聚合的记录数,**不是有效提问数或去重问题数**。两个 URL 的版本归属以真实表名为证据,不根据链接排列顺序推断。
| 字段名 | fieldId | 类型 | 用途 / 关联 |
|---|---|---|---|
| 中文问题 | `ZaMZF6j` | text | 中文文本,不能拿其非空作为所有语言的有效问题条件 |
| 原始问题 | `bETcL3r` | text | 原始提问 |
| AI答案 | `Y4cpmxU` | text | 答案正文 |
| 提问时间 | `SCug9My` | date | 时间筛选;字段 formatter 为 `YYYY-MM-DD HH:mm:ss` |
| 提问人 | `S2XA1uZ` | user | 人员实体;跨系统 ID 关系待确认 |
| 流程触发人员信息 | `JgY2f1z` | text | 触发身份,文本格式不可假定始终为结构化 JSON |
| 语言 | `DNIV3mQ` | text | 后端导出以 Han/Latin 字符启发式判断,不是语言模型识别 |
| 部门 | `eBc6a6b` | text | 部门名称,不是部门外键 |
| 区域 | `fPNLeVW` | text | 区域名称 |
| 是否覆盖 | `QMn9UoU` | singleSelect | `是 / 否 / 否但不计入` |
| 是否正确 | `H3gtTuv` | singleSelect | `是 / 否 / 待确认` |
| 产品分类 | `nFvv8OR` | singleSelect | 产品标签;其中 DobotStudio Pro 是产品选项,不是渠道证据 |
| 问题类型 | `UMqUPAG` | singleSelect | 问题业务分类 |
| 根因分析 | `lnF7gF9` | singleSelect | 知识缺失/过期/检索不到等标签 |
| 父记录 | 2.0:`C7kZIHz`;旧表:`qgyb5Df` | unidirectionalLink | 两字段 config 都指向 `w0nYx0a`,且允许 multiple;不能当作已建立的 1.0→2.0 迁移去重关系 |
**同一行存问答和评估标签**,没有本轮可见的独立评估表外键,也没有 `turn_id`、渠道、评估状态、评估时间、评估器版本业务列。DWS 有记录历史读取能力,但“单元格变更历史”不能直接等价于有状态、有版本的评估执行流水。
#### 线上标签和维度填值情况
| 计数项 | 2.0 | 旧表 | 解释 |
|---|---:|---:|---|
| 记录数 | 2,121 | 13,275 | 原始行数 |
| 提问时间有值 | 2,121 | 13,275 | 已可做日期筛选 |
| AI答案有值 | 2,121 | 13,256 | 有值不等于正确或成功送达 |
| 覆盖标签有值 | 0 | 13,205 | 有值不等于评估完成 |
| 覆盖=是 | 0 | 8,627 | 按 option ID 筛选 |
| 覆盖=否 | 0 | 4,481 | 按 option ID 筛选 |
| 覆盖=否但不计入 | 0 | 97 | 不计入的实际原因/标准待确认 |
| 覆盖为空 | 2,121 | 70 | 用记录数减已知三个选项数量计算 |
| 正确性有值 | 0 | 13,035 | 包括“待确认” |
| 正确性=待确认 | 0 | 4,791 | 不能当作正确性评估已完成 |
| 覆盖与正确性同时有值 | 0 | 12,965 | 仅为标签填值交集,不是正式完成量 |
| 覆盖=是且正确=是 | 0 | 7,887 | 未排除测试人员、去重或筛有效问题 |
| 部门有值 | 0 | 10,814 | 缺失会影响部门分析 |
| 区域有值 | 0 | 8,556 | 缺失会影响区域分析 |
| 产品分类有值 | 0 | 12,969 | 缺失或“未知”仍需区分 |
DWS 对提问人字段的 `DISTINCT` 返回 2.0 为 153、旧表为 418;这是**该人员字段的不同值计数**,尚未确认一行单人约束、ID 域及跨渠道合并,不发布为正式活跃人数。
日期过滤实测:`2026-10-05 ≤ 提问时间 < 2026-10-12`,2.0 为 **465 行**,旧表为 **80 行**。这证明已有时间范围查询能力,但不是“每周有效提问量”。
### 2.2 后端关系模型:迁移与写入代码证据,live 待确认
以下是真实源码中的表/列,不是猜测表名;但本轮 live DB 未连通,**不能宣称已核实生产表结构**。
| 实际表名 | 关键字段 | 用途 / 关联 | 证据 |
|---|---|---|---|
| `turns` | `id, tenant_key, channel, external_message_id, session_key, weknora_session_id, weknora_request_id, question, answer, references_json, status, created_at, updated_at, request_message_id, answer_message_id, agent_id, media_json` | 一个问答轮次;唯一 `(tenant_key,channel,external_message_id)` | DP 迁移 000001:16–35;000002;000003:77–84 |
| `messages` | `id, tenant_key, channel, conversation_id, actor_id, correlation_id, direction, role, message_type, text_content, status, provider_created_at, created_at` | 入站/出站/内部消息;不要混合计为问题 | DP 迁移 000003:39–64 |
| `messages` 人员/送达扩展 | `actor_name_snapshot, department_snapshot, region_snapshot, trigger_person_snapshot, actor_union_id_snapshot, delivered_at, delivery_method, provider_message_id, failure_code` | 提问时人员维度与独立送达状态 | DP 迁移 000003/000004/000009/000010 |
| `coverage_decisions` | `id,tenant_key,channel,turn_id,evaluator_version,verdict,reason_code,reference_count,top_score,created_at,updated_at` | 覆盖决策;`turn_id → turns.id`,唯一 `(tenant_key,channel,turn_id)` | DP 迁移 000007:4–27 |
| `support_cases` | `id,tenant_key,channel,turn_id,coverage_decision_id,status`;通知及 FAQ 导出字段 | 未覆盖支持单;不是正确性评估结果 | DP 迁移 000007:29–49;000011 |
| `channel_actors` | `id,tenant_key,channel,external_actor_id,actor_type,display_name` | 渠道内人员;唯一 `(tenant_key,channel,external_actor_id)` | DP 迁移 000003:8–18 |
| `channel_conversations` | `id,tenant_key,channel,external_conversation_id,conversation_type` | 对话;群聊对话不等于个人 | DP 迁移 000003:23–34 |
| `session_mappings` | `session_key,tenant_key,channel,agent_id,conversation_type,external_subject_id,weknora_session_id` | 外部会话与 WeKnora 会话映射 | DP 迁移 000001:1–14;000008 |
| `directory_profiles` | `tenant_key,staff_id,union_id,name,nickname,job_title,department_ids,department_name,main_department_name,region,employment_status,source,synced_at,updated_at` | 当前通讯录,主键 `(tenant_key,staff_id)` | DP 迁移 000009:1–20 |
| `question_table_exports` | `id,tenant_key,channel,turn_id,status,attempts,last_attempt_at,next_attempt_at,exported_at,failure_code,external_record_id` | 表格同步 outbox;远端记录 ID 可用于对照,但当前表没有可见反向 turn ID | DP 迁移 000010:11–40 |
| `answer_feedback` | `answer_message_id,turn_id,actor_id,value,reason_code,source,created_at,updated_at` | 用户点赞/点踩当前状态,不能等价为 AI 正确性评估 | DP 迁移 000005:6–19 |
建议调查/聚合连接顺序:`turns → request_message_id → messages → actor_id → channel_actors`;覆盖决策按 `turn_id` 加租户/渠道校验关联,避免跨租户。目录按渠道身份与 `staff_id/union_id` 解析,**不能统一按姓名 JOIN**。来自回调的 `external_actor_id` 可能有回退 ID,不应假定总是 staff ID。
### 2.3 评估状态、时间、版本与重新评估
| 问题 | 已有实现 | 边界 |
|---|---|---|
| 是否有评估状态 | `turns.status` 是问答状态;`coverage_decisions` 有最终 verdict,但没有独立 pending/running/failed 评估状态列 | 无决策只能视为缺评估,无法区分等待/失败/未接入 |
| 是否有评估时间 | 覆盖决策 `created_at/updated_at` 为 DB 写入时间 | 不是独立的 AI 评估任务开始/完成时间;表格没有对应业务列 |
| 是否有评估器版本 | 源码 `EvaluatorVersion="v3"`,写入 `evaluator_version` | 迁移默认 `v1`;线上版本分布待确认;版本不是 LLM 型号 |
| 是否保存多次评估 | 覆盖唯一键不含版本;冲突仅 `DO UPDATE SET id=coverage_decisions.id` | 保留原有决策,不取“最新一次”;没有多版本历史 |
| AI 正确性版本/时间 | 表格只见标签;后端未找到该评估模型 | 实际 AI 批处理/人工标注系统待定位 |
证据:`DP/internal/coverage/types.go:33–50`;`DP/internal/store/postgres/coverage.go:33–55`。
### 2.4 已有 API 与服务
| 实际 API / 服务 | 当前用途 | 是否可直接提供目标周报 |
|---|---|---|
| `POST /v1/qa` | 发起问答,接收 channel 等基础参数;不接收部门/区域/union ID,也未调用目录补全 | 否,且本轮未调用该写接口 |
| `GET /v1/admin/audit/turns`;`GET /v1/admin/audit/turns/{id}` | 可选管理审计;列表筛选只允许 limit/cursor/channel/status | 否,无日期区间聚合、coverage JOIN 或质量统计 |
| `coverage.Service.EvaluateAndPersist` | 成功轮次覆盖评估和保存 | 可复用已有决策,不是统计服务 |
| `questiontable.Dispatcher` | outbox 异步表格插入 | 是同步服务,不是评估和统计服务 |
| DWS `record stats/group-stats` | 表格服务端计数、筛选、分组、去重聚合 | 可复用数据读取能力;仍需统一业务口径 |
| `GET /api/v1/monitor/overview`;`GET /api/v1/monitor/metrics` | 知识治理资源/入库/任务监控 | 不可替代问答运营指标 |
| `POST /retrieval` | Adapter 外部知识检索,返回片段/score/元数据 | 不保存此处所需最终答案正确性 |
证据:DP `internal/httpapi/server.go:86–92,130–165`;KG `internal/httpapi/server.go:322–342`;KA `src/knowledge_adapter/app.py:131–160`。
### 2.5 钉钉、Studio Pro、Wiki 入口如何区分
- 后端已有 `turns.channel`、`messages.channel`、`channel_actors.channel`,可作为现有入口维度基础。
- 钉钉 handler 已实现;HTTP `/v1/qa` 允许调用方传 channel。**未查明线上 Studio Pro/Wiki 是否经过该接口、传入什么 channel,不能编造渠道枚举。**
- 表格没有显式入口字段;旧/新表名表达版本,不表达全部业务入口。
- “产品分类=DobotStudio Pro”描述问题涉及产品,不表示用户从 Studio Pro 发起。
- 知识治理的 `internal/external` 是知识可见范围,文档中 PG/ES/OSS 是发布运输通道,不能替代问答业务入口。
- Wiki 资料检索/页面访问与 Wiki 问答必须分开定义,不能把知识访问数直接加入提问量。
## 3. 现有覆盖率、正确率计算逻辑
### 3.1 后端单次覆盖判断:不是统计覆盖率
当前 `coverage.Evaluator` 只接受 `succeeded`:
1. 答案命中明确无答案措辞,或同时出现“检索缺口+联系人工”措辞 → `uncovered_explicit_no_answer`。
2. 未命中上述规则,且引用数量为 0 → `uncovered_no_references`。
3. 有引用 → `covered_has_references`。
记录最高引用 score,但**没有分数阈值**,也不核对答案事实是否正确。该规则无法等价于表格 AI 对知识覆盖与回答正确性的评估。
证据:`DP/internal/coverage/evaluator.go:12–38,62–119,131–138`。
### 3.2 离线脚本实际口径
| 代码入口 | 实际公式 / 样本 | 与本轮目标差异 |
|---|---|---|
| `WR/scripts/12_calc_kb_metrics.py:153–179`;KB 同名脚本 | 严格覆盖率=覆盖“是” /(覆盖“是”+“否”);另算含部分覆盖率 | 空值、待确认、不计入、非法标签不进分母;没有统一有效问题判定 |
| 同上正确率 | 正确“是” /(正确“是”+“否”),独立统计正确列 | **没有先限定覆盖=是**;待确认不进分母 |
| `KB/scripts/06_calc_metrics.py:139–159` | 主表覆盖=(是+部分覆盖)/全部输入行;正确率=是/(是+否) | 主表是归并问题,非事件频次;空值等仍进覆盖分母 |
| `KR/backup/calculate_metrics.py:182–211` | 先筛 `is_real_question=True`,覆盖总和 / 非空 question 数 | 另一套“真实问题”口径;实际正式入口待确认 |
`12_calc_kb_metrics.py` 先排除代码内置的测试/指定人员名单,再算指标;人员列缺失则不排除。本文不公开名单。它没有时间过滤、事件去重、非空问题检查;分母为 0 时返回 `0.0`,容易把“没有评估样本”显示成“表现为零”。
证据:`WR/scripts/12_calc_kb_metrics.py:128–146,282–308`。
### 3.3 有效问题、未评估、多次评估与历史变化
| 调查点 | 真实现状 |
|---|---|
| 有效问题如何判定 | 没有一套所有入口共用定义;主表、流水脚本、旧清洗分别采用不同过滤。`KB/scripts/01_import_raw.py:82–110,180–193` 按说明类关键词过滤,规则可能误排业务问题;旧清洗还按答案排除词过滤 |
| 未完成评估 | 流水指标脚本不把空值/待确认计入对应分母;正确性“待确认”不是完成。后端成功但无决策的轮次无专门评估状态 |
| 多次评估取哪一次 | 后端保留首次成功持久化决策,不覆盖原判定;表格/Excel 统计读取当前单元格,不查询历史最新完成任务 |
| 历史是否变化 | 离线重跑使用当前标签、映射和人员名单;修改标签/通讯录/区域规则或文件会改变过去统计。后端规则决策不会仅因升级版本自动改写,但后续补评估或统计过滤调整仍会影响历史结果 |
| 时间范围 | AI 表格已实测可以;后端审计列表没有时间参数;12脚本本身没有时间过滤,10脚本支持自然月 |
| 产品/部门/区域 | 字段基础存在;当前10脚本有区域月使用统计,未发现目标产品×部门×区域质量聚合服务。2.0 的这些字段实际为空 |
**流水线时间错位:**`WR/scripts/12_run_08_09_10_pipeline.py:154–180` 把 `--month` 传给区域统计,知识指标读取完整输入,故同次产物可能混合“某月使用”与“全量质量”。
### 3.4 月使用与技术人员至少5次
- 当前 `WR/scripts/10_calc_region_usage_metrics.py:286–342,418–448` 按指定自然月;未指定时取数据中最大可解析日期所在月。区域总次数是流水行数,使用人数是人员文本 `nunique()`,不是统一稳定 ID。
- 通讯录人员分母按 ID/姓名回退去重,再按区域展开;并未严格筛选技术人员、纳入范围和在职状态。多区域可能重复计数,汇总与人员明细身份口径也不同。
- 旧 `KR/backup/calculate_metrics.py:214–290` 有“真实问题+内部技术支持+纳入范围+在职+周期≥5”的实现;`KR/backup/usage/region_usage.py:135–195` 则按 user ID,但在职/有效问题筛选不同。
- **可以复用旧算法思路,不能称为当前已上线的统一≥5次指标。** 技术人员范围、人员 ID 唯一性、计次单位与离职处理均待确认。
### 3.5 重复计数风险
| 风险来源 | 已有保护 | 仍存在的风险 |
|---|---|---|
| 回调重复 | 后端 external_message_id 复合唯一键;成功请求返回原结果 | 新 ID 重发同内容是不同事件,不应按相同文本盲目去重 |
| 多轮对话 | 后端一个 turn 一个问答轮次 | 一个会话多个 turn;若把会话、message、turn混合汇总会重复;默认群聊共享会话不是一个用户 |
| 覆盖重评 | 一个 turn 一份持久化覆盖决策 | 不是多版本评估历史;新的 uncovered 输入可能创建支持单,但指向原有 covered 决策,需单独处理重评一致性 |
| 表格同步重试 | 本地 outbox 一个 turn 唯一 | 远端插入后本地 MarkExported 失败可重试插入,未证明远端 exactly-once |
| 旧数据导入 | 01脚本 SHA1(对话人\|规范时间\|原始问题),保留首条/跳过历史 ID | 不是官方消息 ID;时间缺失或规范化冲突会错误合并;12统计入口自身不去重 |
| 1.0 / 2.0 合并 | 有两张表和父记录字段 | 日期重叠但无可证实迁移键;本轮 SQL 重复探测失败,重复量待确认 |
| 通讯录及区域映射 | 已有离线别名/区域规则 | 重名保留首条、多区域 explode、目录规则分叉,可能放大或错归属 |
证据:DP `internal/store/postgres/coverage.go:33–55`;`internal/questiontable/dispatcher.go:168–185`;KB `scripts/01_import_raw.py:180–230`;WR `scripts/10_calc_region_usage_metrics.py:336–375`。
## 4. 报表指标可用性清单
分级针对**当前完整业务指标**,不把“有字段”当作“已有可信接口”。原始计数已支持的部分单独注明;所有后端数据实际填值仍待 live 核实。
| 目标指标 | 分级 | 现有可复用基础 | 必须补齐 / 验证 |
|---|---|---|---|
| 每周有效提问数量 | **部分支持,需要补充字段或逻辑** | 表格日期计数已支持,可直接查原始周行数;后端 turn 唯一键 | 有效问题、测试排除、失败是否纳入、双表去重和入口范围 |
| 知识覆盖率 | **部分支持,需要补充字段或逻辑** | 后端规则决策;旧表覆盖标签;离线覆盖公式 | 选择权威覆盖源、统一分母;2.0表标签为空,不能出质量结论 |
| 回答正确率 | **部分支持,需要补充字段或逻辑** | 旧表正确性标签、脚本 | 核实 AI 评估写入源及版本;限定已覆盖交集;2.0无正确性标签 |
| 有效解答率 | **部分支持,需要补充字段或逻辑** | 旧表可筛覆盖=是且正确=是,已实测交集计数 | 没有找到正式有效解答率实现;需同一有效样本分母与缺评估处理 |
| 与上周对比 | **部分支持,需要补充字段或逻辑** | 日期范围已支持,两期可查原始计数 | 统一两期口径与 as-of;没有核实不可变历史统计快照 |
| 活跃用户数量 | **部分支持,需要补充字段或逻辑** | 人员字段 DISTINCT、后端 actors/union ID | 稳定 ID、单人行、跨入口合并、机器人/测试排除;字段不同值不是可靠人数 |
| 按部门、区域、产品统计 | **部分支持,需要补充字段或逻辑** | 旧表标签、人员快照、目录和区域脚本 | 2.0全部为空;补关联与未知桶;产品分类不是渠道 |
| 月使用次数≥5的技术人员数量 | **部分支持,需要补充字段或逻辑** | 历史 backup 有≥5次逻辑;目录有职位/任职字段 | 当前入口未实现该指标;统一技术人员名单、有效事件与稳定ID、自然月 |
| 未覆盖问题 Top N | **部分支持,需要补充字段或逻辑** | 旧表覆盖=否,后端 uncovered/support_cases | 选择按事件还是归并问题;归并键、排序、授权与脱敏;未找到正式排名API |
| AI 评估完成率 | **部分支持,需要补充字段或逻辑** | 当前标签非空/待确认可统计;后端决策存在性 | 非空不等于完成,规则覆盖不等于AI评估;执行状态、应评样本、正确性终态定义待补 |
| 自动邮件周报(交付能力) | **暂不支持,需要开发** | 可复用统一统计结果;DWS 有 mail 服务但不代表项目已有邮件周报 | 本轮未找到项目邮件周报任务、投递去重、失败重试与发送审计实现 |
**当前可以直接查询的内容:**原始记录量、时间范围行数、标签分布、字段填值量和字段 DISTINCT。这些查询能力已经实测,不等价于完整目标指标已验收。
## 5. 当前的数据缺口和技术风险
### 5.1 P0:先澄清,避免做出“看起来正确”的错误周报
1. **生产证据缺口:**live DB 不可达,部署 SHA 未取得;需提供只读访问或由运维导出脱敏 schema/聚合。不能拿本地迁移证明生产已具备全部字段。
2. **评估来源不明:**用户描述的“AI 自动覆盖与正确性评估”尚未定位到实际执行代码;表格字段配置未证明其自动化机制,后端现有覆盖器不是 AI 评测。
3. **2.0标签断点:**质量、产品、部门和区域字段无填值。先查真实数据是否在别处,避免重新建设已有评估器。
4. **无统一分母:**归并问题主表、流水事件、规则成功问答、旧真实问题过滤不一致。
5. **双表版本不是入口:**同时写入/迁移关系未知,直接相加有重复风险。
### 5.2 P1:实现前要纳入验收
- 状态缺失:后端成功问答可缺覆盖评估,表格“待确认”无法区分进行中/人工待审/失败。
- 评估更新:后端首次决策幂等与“取最新评估”目标不兼容;不能静默变更现有策略。
- 用户反馈不等于正确性:点踩理由 incorrect 是用户反馈,不是统一 AI 评估标注。
- 维度漂移:提问时快照与当前目录应分开;按当前部门重算历史会变动。
- 人员去重:不同渠道 external ID、staff ID、union ID 不等价;姓名只能作低可信回退。
- 产品归类:后端未见相应字段,旧脚本同名问题回退可能跨产品误配。
- 区域规则分叉:weekly_report 与 kb_ops 的09/10已有不同别名规则,不应复制两套继续演化。
- 时间口径:提问时间、系统入站时间、评估写入时间不同;周窗口必须选定一种,评估完成作为另一个 as-of。
- 分母为零:现有脚本输出零,新的正式报表宜输出 null/not_available,并给缺失原因,不能暗示正确率为0%。
- 性能与权限:避免每周全量读入问答正文;服务端聚合、固定窗口、只读凭据、超时及租户校验优先。
- 邮件数据泄露:默认仅汇总;Top N需脱敏、权限和明确授权,不嵌入员工个人明细。
## 6. 最小改造方案及预估工作量(建议,未实施)
### 6.1 推荐方案 / 备选方案 / 不推荐
| 方案 | 内容 | 评价 |
|---|---|---|
| **推荐** | 在现有知识治理后端增加一个轻量运营统计模块;读现有问答/目录/评估源,统一归一化与计算;API及邮件共享结果 | 一个开发者可维护,不增微服务,不重建日志;先以 live 权威源核实为前提 |
| **备选** | 表格作为权威源时,先用 DWS 聚合/窄字段读取生成可复核统计,再接入同一模块 | 出数快,但目前2.0标签缺失,评估追踪/远端去重仍弱;不能据此承诺全指标可用 |
| **不推荐** | 新建问答日志系统、另做邮件专用公式、长期全量导出大表、拿检索score/监控成功率冒充正确率 | 重复建设、口径漂移、隐私与维护成本高 |
若生产问答库不可安全跨库读取,可将同一统计模块部署到已有 DobotAI 服务并通过只读聚合接口供治理平台消费。**二选一落地,不先创建两个同义统计实现。**
### 6.2 模块边界与复用点
| 模块(建议) | 输入 / 输出 | 边界与复用 |
|---|---|---|
| 只读来源适配 | 原问答记录、当前评估、人员快照 → 归一化事件 | 复用 turns/messages/coverage_decisions;正确性先定位原系统,禁止新增替代评测器;旧表仅作明确授权历史源 |
| 口径与统计 | 同一范围内事件+已批准规则 → 总量、分子分母、维度、两期对比、缺失诊断 | 复用12脚本标签规范化/异常计数和10脚本区域规则;**不直接沿用有冲突的分母/姓名去重** |
| V1只读API | 授权过滤 → 统一统计结果 | 复用治理HTTP、鉴权、日志;不复用 monitor 的任务成功率 |
| 周报快照/渲染 | 同一统计结果 → 报表摘要/邮件内容 | 复用现有持久任务设施(jobs),但先核实扩展点;快照持久化位置需批准后设计 |
| 邮件投递 | 已批准收件范围+快照 → 发送/失败审计 | 不在发送环节重新计算;定时、重试、投递幂等单独处理 |
后续涉及页面/UI时,**先移交 prototype Agent** 做数据缺失、口径说明、筛选及对比状态原型;原型确认后才进入正式开发。本轮没有启动 prototype、coder、tester或CI/CD任务。
### 6.3 归一化数据模型草案(DTO,不是新增数据库表)
| 建议字段 | 来源与规则 |
|---|---|
| `source / source_record_id` | 后端 turn ID 或表格record ID+表ID,保持来源命名空间 |
| `tenant / channel / occurred_at` | 优先现有租户/渠道/选定提问时间;未知渠道不得伪造 |
| `person_key / identity_quality` | 来源稳定ID及映射置信等级;报告不返回原始人员ID |
| `department / region / product` | 快照/标签,缺失进入unknown;产品由现有分类来源提供 |
| `is_valid / exclusion_reason` | 用户确认的统一规则;与是否已评估分开 |
| `coverage_value / coverage_source / coverage_version` | 后端规则和表格AI标签必须标注来源,不能无说明混合 |
| `correctness_value / correctness_source` | 原正确性评估;unknown/pending与incorrect分开 |
| `evaluation_state / evaluated_at` | 有证据才填写;不能把问答成功时间当评估完成时间 |
没有证据的状态/版本保持 unknown,报表附质量诊断。若需要正式评估历史,优先评估已有原系统能力,再决定是否加小型关联/快照存储;**本轮不提供DDL,不变更数据库**。
### 6.4 指标口径草案(待用户确认,不是现状)
设同一范围内:`V`=有效事件数;`C`=有效且已覆盖事件数;`R`=有效且已覆盖且回答正确事件数。
- 期望覆盖率=`C/V`;正确率=`R/C`;有效解答率=`R/V`。
- 同时返回未评估、正确性待确认、评估失败/未知、测试排除等数量;是否将未评估有效事件保留在V和已覆盖待正确性评估事件保留在C,**须明确确认**。不能把暂缺标签暗中视为“否”。
- 若另提供“已评估样本表现”,必须使用不同指标名与分母说明,不冒充上述业务覆盖率。
- 周范围推荐 Asia/Shanghai 周一00:00起、下周一00:00止,半开区间;月≥5按自然月及有效事件数计算。
- 计次单位推荐问答turn;会话、答案消息和重复回调不额外计次。正常多轮各turn是否算一次由业务确认。
- 比较两周时同一rule_version与as-of策略;可冻结已发布结果并提供明确重算版本,不能悄然修改已发送邮件的历史值。
### 6.5 V1 API草案(新建议,尚不存在)
建议仅新增一个端点:`GET /api/v1/operations/report`,参数 `start/end/timezone`、可选 `channel/department/region/product`、`compare=previous_period`、`top_n`。最终路由名称待仓库规范确认。
响应逻辑字段:
- `period, timezone, generated_at, as_of, rule_version, sources, source_versions`。
- `counts`:原始量、有效量、已覆盖量、已覆盖且正确量、各类未评估/排除量。
- `metrics`:每项 value/numerator/denominator/status,缺证据时not_available,不用假零。
- `comparison`:上期计数及指标;率差用百分点,量变化可用百分比;上期分母为零时显式不可比。
- `dimensions`:已授权维度聚合与unknown桶;避免多区域展开使总计膨胀。
- `top_uncovered`:脱敏题目/归并标识/次数;默认不输出员工信息,权限不足不返回明细。
- `data_quality`:缺标签、身份未匹配、维度缺失、重复待查、来源/评估版本差异。
自动邮件调用**同一内部统计入口**,使用其结果快照渲染,不另外写SQL或复刻公式。发送幂等建议由“周期+规则/快照版本+收件组”组成;未知投递结果不能盲目重发。
### 6.6 安全、日志、部署与CI/CD影响
- 数据源使用只读身份,设置查询超时,禁止写入、DDL或将秘密放入Git;报告和邮件仅输出授权范围聚合。
- 复用治理鉴权与租户边界;报表访问、导出和邮件投递留审计,日志只含周期、规则版、计数、耗时、稳定失败码。
- 默认不引入新微服务、消息队列或独立运行栈;新增统计模块随现有API部署,邮件复用已核实后的任务框架。
- 后续CI增加纯统计契约测试:空样本、待确认、重复事件、多轮、双表来源、跨租户、跨区域、零分母、两期版本一致性。
- 本轮未改变工作流、Runner、生产部署和数据库。后续数据库/索引/调度变更均需单独批准与回滚方案。
### 6.7 工作量估计
以下为架构估算,不是实测工时或已批准开发排期;单位为单人工作日,不含UI正式实现、重新建设AI评估器及历史数据大规模回填。
| 后续工作 | 预估 | 前提 / 验收 |
|---|---:|---|
| 生产只读核验与口径确认 | 1天 | 取得真实schema、部署SHA、渠道枚举、评估来源和填值聚合 |
| 只读来源适配+统一统计核心 | 2–3天 | 对拍固定范围的分子分母、异常/未知桶、去重规则 |
| V1接口+对比+基础维度/Top N | 1–2天 | API和独立核对结果一致,无未授权个人明细 |
| 周报快照/调度/邮件复用 | 1–2天 | 同一快照与API数值一致;批准测试收件人;失败重试不重复发送 |
| 回归与验收证据整理 | 1–2天 | 边界测试、固定范围对拍、性能和权限记录完整 |
**基础范围估计合计6–10工作日**。若正确性原系统不可接入、缺turn↔record映射或要回填2.0维度/历史评估,需调查后另估,不能承诺上述时间覆盖所有缺口。
### 6.8 Gitea Issue规划(草案,未创建,不建DEV任务)
| 标题 / 类型 | 交付与验收标准 | 依赖 |
|---|---|---|
| `[ARCH] 核实生产问答与评估数据源` | 脱敏live schema、部署SHA、实际渠道值、成功turn与缺决策量、评估版本分布;明确AI正确性来源;全部只读 | 只读访问/运维证据 |
| `[DECISION] 确认有效问题和三个质量指标口径` | 批准V/C/R、测试排除、未评估处理、turn计次、时区窗口、技术人员范围与历史重算规则 | 来源核验 |
| `[ARCH] 运营统计模块与V1接口契约` | 单一计算入口、来源映射、API草案、unknown/不可用状态、对拍及权限验收标准 | 口径确认 |
| `[ARCH] 邮件周报复用与投递幂等设计` | 同一快照供API/邮件使用;收件权限、重试、未知投递处理与审计方案 | V1契约 |
| `[UI] 运营报表V1原型交接prototype` | 筛选、两期对比、缺失数据提示、指标分母/来源说明;用户批准原型,不写正式UI业务代码 | 口径和契约 |
## 7. 需要用户确认的问题
1. **生产部署在哪里?** 本地 DobotAI 连接配置对应DB不可达,请提供生产项目路径/只读访问方式,或让运维输出无个人信息的schema与聚合;不要在聊天发送密码或Token。
2. **AI自动评估由什么执行?** 是钉钉AI字段、外部工作流、离线批处理还是另一系统?请给执行代码/配置所在位置及其结果目标表;现有后端v3规则不是该正确性评估。
3. **哪份评估是权威?** 表格覆盖标签与后端规则决策是否刻意分别保留?若不一致,以哪份为正式周报口径?
4. **两个流水表的关系?** 为什么时间同时延伸到本轮当天?是否双写、试点/正式用户分流或历史迁移?是否有现有消息ID/turn ID映射文件或表?
5. **有效提问范围?** 是否排除测试人员、无效/范围外问题、纯寒暄、失败问答、图片问题和设置指令?内置排除名单是否仍有效?
6. **未评估与待确认如何进入分母?** 正式业务率与已评估样本率是否同时展示?零样本是否显示“暂无可用评估”,而不是0%?
7. **入口范围和人员定义?** Studio Pro/Wiki是否问答入口、实际渠道值是什么?“技术人员”是技术支持岗位还是更大名单?≥5次是否按有效turn和自然月?
8. **历史归属与发布策略?** 按提问时部门/区域还是当前通讯录?周报冻结还是自动随评估更新重算?周窗口是否采用周一至周一、北京时间?
9. **Top N语义与邮件权限?** 排名按重复提问频次还是每条未覆盖事件?哪些人员能看脱敏问题?收件人范围、发送日/时间和重发策略是什么?
10. **正式离线报表入口是哪份?** weekly_report、kb_ops还是knowledge_ai_report旧流程?确认后保留一套权威规则,避免三份实现互相冲突。
## 附录:证据定位与复核方式
路径缩写:DP=`/home/zheromiku/dobotai-platform`;KG=`/home/zheromiku/knowledge-governance`;KA=`/home/zheromiku/knowledge-adapter-service`;WR=`/home/zheromiku/DOBOTAI/weekly_report`;KB=`/home/zheromiku/DOBOTAI/kb_ops`;KR=`/home/zheromiku/DOBOTAI/knowledge_ai_report`。迁移简称均在DP `db/migrations/`,例如000007对应 `000007_coverage_decisions.up.sql`。
### A. DWS只读命令示例
```sh
# 明确限定两表,读取字段/视图目录
dws aitable table get --base-id KGZLxjv9VG37o9N6IYvYGBl9V6EDybno --table-ids w0nYx0a,jQ6oevs
# 完整表头;按字段展开配置前先确认ID
dws aitable field get --base-id KGZLxjv9VG37o9N6IYvYGBl9V6EDybno --table-id w0nYx0a
# COUNT统计匹配记录,不加limit避免仅统计子集
dws aitable record stats --base-id KGZLxjv9VG37o9N6IYvYGBl9V6EDybno --table-id w0nYx0a --stats '[{"fieldId":"ZaMZF6j","statsType":"COUNT"}]'
```
实际标签筛选使用field get取得的option ID:覆盖“是”=`MPfK0hpGNX`,“否”=`rZT6tj41Je`,“否但不计入”=`1IJOik1qP8`;正确“是”=`p1jnsxEU3R`,“待确认”=`VGER9DlTkn`。日期范围使用 `not_before` 与 `before`,而非通用数值比较运算符。
本轮字段/聚合JSON保存在调查用scratch目录下 `dobotai-investigation/`;其中 `sanitized-summary.json` 含聚合摘要,不含原始问答或人员记录。失败响应未伪造成结果。
### B. 关键源码索引
| 文件 | 用途 |
|---|---|
| DP `internal/core/types.go:39–56,91–122` | 请求和turn模型 |
| DP `internal/store/postgres/store.go:50–129,196–283` | 问答/消息事务写入,送达分离 |
| DP `internal/qa/service.go:166–177,285–298` | 重放、成功评估observer、错误边界 |
| DP `internal/coverage/{types,evaluator,service}.go` | 覆盖版本、规则及持久化服务 |
| DP `internal/store/postgres/coverage.go:33–55` | 决策幂等和支持单关联 |
| DP `internal/questiontable/row.go:36–87` | 实际表格字段映射、select省略 |
| DP `internal/store/postgres/question_table_exports.go:80–98` | 导出数据来源,未关联评估 |
| DP `internal/questiontable/dispatcher.go:168–185` | 远端写入后标记本地,重复窗口 |
| DP `internal/httpapi/server.go:86–92,130–188` | 现有问答/审计API契约 |
| DP `internal/channels/dingtalk/handler.go:189–265` | 入口、人员补全和请求 |
| DP `internal/directory/resolver.go:35–64` | 通讯录缓存与故障回退 |
| WR `scripts/12_calc_kb_metrics.py:128–179,282–308` | 当前流水统计样本与真实公式 |
| WR `scripts/12_run_08_09_10_pipeline.py:154–180` | 月份只传区域统计的时间错位 |
| WR `scripts/10_calc_region_usage_metrics.py:286–342,345–448` | 自然月、区域展开、人数与次数统计 |
| KB `scripts/06_calc_metrics.py:139–159` | 问题主表不同分母 |
| KB `scripts/01_import_raw.py:82–110,180–230` | 清洗/事件哈希去重 |
| KR `backup/calculate_metrics.py:182–290` | 旧真实问题与技术人员≥5逻辑 |
| KR `backup/usage/region_usage.py:135–195` | 另一份按ID的月≥5逻辑 |
| KG `internal/monitoring/{real,metrics}.go` | 知识运行监控,不是问答质量统计 |
| KA `src/knowledge_adapter/{app,models,observability}.py` | 外部检索、请求边界及脱敏日志 |
**下一步门槛:先确认数据源与口径,再批准实现;本报告不代表已批准开发、数据回填、结构变更或邮件发送。**
+77 -4
View File
@@ -61,6 +61,17 @@ type Config struct {
BackupHostTarget string
BackupHostScriptDir string
BackupHostRoot string
// 版本记录(「版本记录」页):**匿名只读**远端仓库的提交与 tag。来源留空即"未接线"
// (页面降级展示,接口返回可用性=false)。只允许配置里批准的 origin 与仓库,
// 不接受任何调用方传入的 URL;本功能**不使用凭据**。
VersionHistoryGiteaBaseURL string
VersionHistoryRepo string
VersionHistoryAllowedOrigins []string
// VersionHistoryLinkOrigin 是**页面链接**用的 origin(给内网外的浏览器点开),
// 留空即与抓取 origin 相同。只用于拼展示链接,不参与任何请求。
VersionHistoryLinkOrigin string
VersionHistoryHTTPTimeout time.Duration
VersionHistoryMaxPages int
}
func Load(getenv func(string) string) (Config, error) {
@@ -98,10 +109,16 @@ func Load(getenv func(string) string) (Config, error) {
TestAcceptancePolicyVersion: valueOrDefault(getenv("TEST_ACCEPTANCE_POLICY_VERSION"), "structural-v1"),
TestAutoReviewPolicy: valueOrDefault(getenv("TEST_AUTO_REVIEW_POLICY"), string(governance.AutoReviewInternal)),
// 整库逻辑备份的目标主机:三项同时给出才接线(脚本目录/备份根有默认值)。
BackupHostSSHConfig: strings.TrimSpace(getenv("BACKUP_HOST_SSH_CONFIG")),
BackupHostTarget: strings.TrimSpace(getenv("BACKUP_HOST_TARGET")),
BackupHostScriptDir: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_SCRIPT_DIR")), "/opt/weknora-test"),
BackupHostRoot: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_ROOT")), "/srv/kb-backups"),
BackupHostSSHConfig: strings.TrimSpace(getenv("BACKUP_HOST_SSH_CONFIG")),
BackupHostTarget: strings.TrimSpace(getenv("BACKUP_HOST_TARGET")),
BackupHostScriptDir: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_SCRIPT_DIR")), "/opt/weknora-test"),
BackupHostRoot: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_ROOT")), "/srv/kb-backups"),
VersionHistoryGiteaBaseURL: strings.TrimSpace(getenv("VERSION_HISTORY_GITEA_BASE_URL")),
VersionHistoryRepo: valueOrDefault(strings.TrimSpace(getenv("VERSION_HISTORY_REPO")), "Weknora/knowledge-governance"),
VersionHistoryAllowedOrigins: splitOrigins(getenv("VERSION_HISTORY_ALLOWED_ORIGINS")),
VersionHistoryLinkOrigin: strings.TrimSpace(getenv("VERSION_HISTORY_LINK_ORIGIN")),
VersionHistoryHTTPTimeout: 15 * time.Second,
VersionHistoryMaxPages: valueOrDefaultInt(getenv("VERSION_HISTORY_MAX_PAGES"), 200),
}
if config.DatabaseURL == "" {
return Config{}, errors.New("DATABASE_URL is required")
@@ -183,6 +200,32 @@ func Load(getenv func(string) string) (Config, error) {
if config.WorkerLivenessStaleAfter, err = durationOrDefault(getenv("WORKER_LIVENESS_STALE_AFTER"), config.WorkerLivenessStaleAfter); err != nil {
return Config{}, fmt.Errorf("WORKER_LIVENESS_STALE_AFTER: %w", err)
}
if config.VersionHistoryHTTPTimeout, err = durationOrDefault(getenv("VERSION_HISTORY_HTTP_TIMEOUT"), config.VersionHistoryHTTPTimeout); err != nil {
return Config{}, fmt.Errorf("VERSION_HISTORY_HTTP_TIMEOUT: %w", err)
}
// 版本记录来源:给了 origin 就必须是干净的 http(s) origin;白名单留空则默认只许自己。
if config.VersionHistoryGiteaBaseURL != "" {
if err := validateHTTPBaseURL(config.VersionHistoryGiteaBaseURL); err != nil {
return Config{}, fmt.Errorf("VERSION_HISTORY_GITEA_BASE_URL: %w%s", err,
envHint(config.VersionHistoryGiteaBaseURL))
}
if len(config.VersionHistoryAllowedOrigins) == 0 {
config.VersionHistoryAllowedOrigins = []string{config.VersionHistoryGiteaBaseURL}
}
for _, origin := range config.VersionHistoryAllowedOrigins {
if err := validateHTTPBaseURL(origin); err != nil {
return Config{}, fmt.Errorf("VERSION_HISTORY_ALLOWED_ORIGINS: %w", err)
}
}
if strings.Count(config.VersionHistoryRepo, "/") != 1 {
return Config{}, errors.New("VERSION_HISTORY_REPO 必须是 owner/name 形式")
}
if config.VersionHistoryLinkOrigin != "" {
if err := validateHTTPBaseURL(config.VersionHistoryLinkOrigin); err != nil {
return Config{}, fmt.Errorf("VERSION_HISTORY_LINK_ORIGIN: %w", err)
}
}
}
if config.TestWeKnoraHTTPTimeout, err = durationOrDefault(getenv("TEST_WEKNORA_HTTP_TIMEOUT"), config.TestWeKnoraHTTPTimeout); err != nil {
return Config{}, fmt.Errorf("TEST_WEKNORA_HTTP_TIMEOUT: %w", err)
}
@@ -279,6 +322,36 @@ func validateHTTPBaseURL(value string) error {
return nil
}
// envHint 给"值明显不像一个地址"的情况补一句线索:最常见的成因是 `.env` 里两行粘在一起
// (新键被追加到没有结尾换行的上一行后面)—— 值里就会出现第二个 `KEY=`。
func envHint(value string) string {
if strings.Contains(value, "=") {
return "(值里出现了 `=`:`.env` 里两行可能粘成了一行,改成一行一值再上线)"
}
return ""
}
// splitOrigins 解析逗号分隔的 origin 白名单(空项丢弃)。
func splitOrigins(value string) []string {
parts := strings.Split(value, ",")
origins := make([]string, 0, len(parts))
for _, part := range parts {
if trimmed := strings.TrimSpace(part); trimmed != "" {
origins = append(origins, trimmed)
}
}
return origins
}
// valueOrDefaultInt 解析正整数(非法/缺省都退回默认值)。
func valueOrDefaultInt(value string, fallback int) int {
parsed, err := strconv.Atoi(strings.TrimSpace(value))
if err != nil || parsed <= 0 {
return fallback
}
return parsed
}
func valueOrDefault(value, fallback string) string {
if value == "" {
return fallback
+32
View File
@@ -1,6 +1,7 @@
package appconfig
import (
"strings"
"testing"
"time"
)
@@ -290,3 +291,34 @@ func TestProductionWeKnoraEndpointIsConfigurableAndFailsClosed(t *testing.T) {
t.Fatalf("production endpoint must default to unconfigured: %#v", unset)
}
}
// 回归用例(2026-10-14 线上事故):`.env` 两行粘成一行时,base URL 会变成
// "http://host:3000VERSION_HISTORY_LINK_ORIGIN=…" —— 必须被拒,并给出线索文案,
// 而不是让 api/worker 带着坏值崩溃重启(或者更糟:静默按坏值跑起来)。
func TestLoadRejectsMergedVersionHistoryEnvValue(t *testing.T) {
values := map[string]string{
"DATABASE_URL": "postgres://example",
"VERSION_HISTORY_GITEA_BASE_URL": "http://192.168.50.223:3000VERSION_HISTORY_LINK_ORIGIN=https://gitea.example",
}
_, err := Load(func(key string) string { return values[key] })
if err == nil {
t.Fatal("粘在一起的值必须被拒绝")
}
if !strings.Contains(err.Error(), "粘成了一行") {
t.Fatalf("错误里应给出线索(.env 粘行):%v", err)
}
// 正常值仍然放行,且链接 origin 可为空(退回抓取 origin)
good := map[string]string{
"DATABASE_URL": "postgres://example",
"VERSION_HISTORY_GITEA_BASE_URL": "http://192.168.50.223:3000",
"VERSION_HISTORY_LINK_ORIGIN": "https://gitea.example",
}
config, err := Load(func(key string) string { return good[key] })
if err != nil {
t.Fatalf("合法配置不该被拒:%v", err)
}
if config.VersionHistoryLinkOrigin != "https://gitea.example" || len(config.VersionHistoryAllowedOrigins) != 1 {
t.Fatalf("配置解析不对:%+v", config)
}
}
+271
View File
@@ -0,0 +1,271 @@
package governance
import (
"fmt"
"regexp"
"sort"
"strconv"
"strings"
"time"
)
// 版本记录(「版本记录」页)的领域类型与**版本号口径**。
//
// 口径(主人 2026-10-13 定:只给有证据的版本号):
// - 正式版本:存在**注释 tag** `vX.Y.Z` 指向该提交,且该提交内 CHANGELOG 顶部版本 == X.Y.Z;
// - 开发版本:该提交位于某个正式 tag 之后,且能算出「自该 tag 以来的提交数」⇒ `<主>.<次>.<n>`;
// - 历史提交:证据不足 ⇒ 不下发数字版本号,只给原因(**不补造**)。
//
// 不变量:**完整 SHA 是唯一身份**,版本号不是唯一键;两个提交算出同一个号时两条都保留。
const (
VersionStateVerified = "verified"
VersionStateUnknown = "unknown"
RecordKindRelease = "release"
RecordKindDevelopment = "development"
RecordKindHistorical = "historical"
// 原因码:页面据此显示「版本号未能核验」的具体理由。
ReasonAnnotatedTagMatch = "annotated_tag_and_changelog_top_match"
ReasonLightweightTag = "lightweight_tag"
ReasonChangelogTopMissing = "no_changelog_top"
ReasonChangelogMismatch = "changelog_top_mismatch"
ReasonNoReleaseTag = "no_release_tag_for_commit"
ReasonNoBaseline = "no_baseline"
// ReasonIncompleteGraph:提交图不完整(检出被截断)⇒ 提交数算不准 ⇒ 宁可不给号。
ReasonIncompleteGraph = "shallow_or_incomplete_graph"
// ReasonTagCreatedLater:该版本号对应的 tag 是在**更晚的提交**上打的(不在这个提交的历史里)
// ⇒ 这个提交当时还没有发布基线,不能拿"后来才有的 tag"给它编号。
ReasonTagCreatedLater = "release_tag_created_later"
)
// versionHistorySemver 只认三段十进制、无前导零(与 scripts/check_changelog.py 同口径)。
var versionHistorySemver = regexp.MustCompile(`^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$`)
// releasedHeading 匹配 CHANGELOG 里的已发布版本标题 `## [x.y.z] - …`。
var releasedHeading = regexp.MustCompile(`(?m)^##\s*\[(\d+\.\d+\.\d+)\]\s*$|^##\s*\[(\d+\.\d+\.\d+)\]\s*-`)
// VersionTagEvidence 是一个指向某提交的 tag 及其可核验属性。
type VersionTagEvidence struct {
Name string `json:"name"`
TagSHA string `json:"sha,omitempty"`
Annotated bool `json:"annotated"`
URL string `json:"url,omitempty"`
}
// VersionEvidence 是版本号判定的完整依据(进库的 jsonb,也直接给页面看)。
type VersionEvidence struct {
State string `json:"state"`
Reason string `json:"reason"`
Tags []VersionTagEvidence `json:"tags,omitempty"`
ChangelogTop string `json:"changelog_top,omitempty"`
BaseTag string `json:"base_tag,omitempty"`
CommitsSinceBase *int `json:"commits_since_base,omitempty"`
}
// VersionHistoryCommit 是一条提交记录(版本记录页的列表项)。
type VersionHistoryCommit struct {
RepoKey string
CommitSHA string
Parents []string
CommittedAt time.Time
AuthorDisplay string
Subject string
Body string
VersionLabel string
VersionState string
RecordKind string
ReleaseTags []VersionTagEvidence
ReleaseNotes string
CommitURL string
VersionEvidence VersionEvidence
SnapshotID int64
}
// VersionHistorySyncRun 是一次同步的状态(「同步成功」≠「历史完整」)。
type VersionHistorySyncRun struct {
ID int64
JobID string
Status string
SourceHeadSHA string
StartedAt time.Time
FinishedAt time.Time
LastSuccessAt time.Time
Complete bool
FetchedCount int
ExpectedCount *int
ErrorCode string
ActiveSnapshotID int64
TriggeredBy string
}
// CurrentRunningIdentity 是「当前运行」的判据结果:只认精确匹配,**不猜**。
type CurrentRunningIdentity struct {
State string `json:"state"` // matched | development | unknown
CommitSHA string `json:"commit_sha,omitempty"`
DisplayVersion string `json:"display_version,omitempty"`
MatchedCommitSHA string `json:"matched_commit_sha,omitempty"`
}
// VersionHistoryPage 是列表接口的返回体。
type VersionHistoryPage struct {
Items []VersionHistoryCommit
NextCursor string
HasMore bool
Sync VersionHistorySyncRun
CurrentRunning CurrentRunningIdentity
}
// SemverValid 判断是否为合规三段的正式版本号。
func SemverValid(value string) bool { return versionHistorySemver.MatchString(value) }
// CompareSemver 按主/次/修订比较;任一非法 ⇒ 0(调用方应先校验)。
func CompareSemver(left, right string) int {
lp, ok := semverParts(left)
if !ok {
return 0
}
rp, ok := semverParts(right)
if !ok {
return 0
}
for i := 0; i < 3; i++ {
if lp[i] != rp[i] {
if lp[i] < rp[i] {
return -1
}
return 1
}
}
return 0
}
func semverParts(value string) ([3]int, bool) {
var out [3]int
if !versionHistorySemver.MatchString(value) {
return out, false
}
for i, part := range strings.Split(value, ".") {
n, err := strconv.Atoi(part)
if err != nil {
return out, false
}
out[i] = n
}
return out, true
}
// DecideVersion 按证据判定一个提交的版本号口径。
//
// changelogTop 是该提交内 CHANGELOG 的顶部已发布版本(读不到就空);
// tagsAtCommit 是所有指向该提交的 tag(含注释标记);baseTag/commitsSinceBase
// 来自提交图遍历(最近的正式 tag 与该 tag 以来的提交数),没有就传空/nil。
func DecideVersion(changelogTop string, tagsAtCommit []VersionTagEvidence, baseTag string, commitsSinceBase *int) (label, state, kind string, evidence VersionEvidence) {
evidence = VersionEvidence{State: VersionStateUnknown, Reason: ReasonNoReleaseTag,
Tags: tagsAtCommit, ChangelogTop: changelogTop, BaseTag: baseTag, CommitsSinceBase: commitsSinceBase}
// ① 正式版本:注释 tag + 版本名合法 + 提交内 CHANGELOG 顶部一致。
annotated := make([]VersionTagEvidence, 0, len(tagsAtCommit))
semverTags := make([]VersionTagEvidence, 0, len(tagsAtCommit))
for _, tag := range tagsAtCommit {
if tag.Annotated {
annotated = append(annotated, tag)
}
if SemverValid(strings.TrimPrefix(tag.Name, "v")) {
semverTags = append(semverTags, tag)
}
}
sort.Slice(semverTags, func(i, j int) bool { return semverTags[i].Name < semverTags[j].Name })
for _, tag := range annotated {
version := strings.TrimPrefix(tag.Name, "v")
if !SemverValid(version) {
continue
}
if changelogTop != "" && changelogTop != version {
continue // 该 tag 不合规(版本与提交内记录不一致)⇒ 继续找别的
}
if changelogTop == "" {
evidence.Reason = ReasonChangelogTopMissing
continue
}
return version, VersionStateVerified, RecordKindRelease, VersionEvidence{
State: VersionStateVerified, Reason: ReasonAnnotatedTagMatch, Tags: tagsAtCommit,
ChangelogTop: changelogTop, BaseTag: "v" + version, CommitsSinceBase: commitsSinceBase}
}
// ② 开发版本:基线 tag 存在且能算出「自该 tag 以来的提交数」。
// 口径与 scripts/version.py **完全一致**:基线 = `v<提交内 CHANGELOG 顶部版本>`,
// 号 = `<主>.<次>.<n>`(n=0 时正好等于该版本号本身);两个提交算出同一个号时两条都保留。
if SemverValid(changelogTop) && baseTag != "" && commitsSinceBase != nil && *commitsSinceBase >= 0 {
parts, _ := semverParts(changelogTop)
label := fmt.Sprintf("%d.%d.%d", parts[0], parts[1], *commitsSinceBase)
return label, VersionStateVerified, RecordKindDevelopment, VersionEvidence{
State: VersionStateVerified, Reason: "counted_commits_since_base_tag", Tags: tagsAtCommit,
ChangelogTop: changelogTop, BaseTag: baseTag, CommitsSinceBase: commitsSinceBase}
}
// ③ 历史提交:证据不足 ⇒ 不给号,只给原因(不补造)。
annotatedSemver := 0
for _, tag := range annotated {
if SemverValid(strings.TrimPrefix(tag.Name, "v")) {
annotatedSemver++
}
}
switch {
case len(semverTags) > 0 && annotatedSemver == 0:
evidence.Reason = ReasonLightweightTag
case changelogTop == "":
evidence.Reason = ReasonChangelogTopMissing
case annotatedSemver > 0:
evidence.Reason = ReasonChangelogMismatch
case baseTag == "":
evidence.Reason = ReasonNoBaseline
default:
evidence.Reason = ReasonNoReleaseTag
}
return "", VersionStateUnknown, RecordKindHistorical, evidence
}
// ExtractReleaseNotes 从提交内的 CHANGELOG 文本里取某个已发布版本的整段正文。
//
// 边界口径与 scripts/check_changelog.py 一致:**任意二级标题都是边界**(否则
// `## 能力基线(未发布)` 这类标题会把后文算进上一节)。
func ExtractReleaseNotes(changelog, version string) string {
if changelog == "" || !SemverValid(version) {
return ""
}
lines := strings.Split(changelog, "\n")
start := -1
for i, line := range lines {
if m := releasedHeading.FindStringSubmatch(strings.TrimSpace(line)); m != nil {
if m[1] == version || m[2] == version {
start = i
break
}
}
}
if start < 0 {
return ""
}
var body []string
for _, line := range lines[start+1:] {
if strings.HasPrefix(line, "## ") {
break
}
body = append(body, line)
}
return strings.TrimSpace(strings.Join(body, "\n"))
}
// ChangelogTopVersion 取 CHANGELOG 顶部的已发布版本;没有 ⇒ 空串。
func ChangelogTopVersion(changelog string) string {
for _, line := range strings.Split(changelog, "\n") {
if m := releasedHeading.FindStringSubmatch(strings.TrimSpace(line)); m != nil {
if m[1] != "" {
return m[1]
}
return m[2]
}
}
return ""
}
+101
View File
@@ -0,0 +1,101 @@
package governance
import "testing"
func tag(name string, annotated bool) VersionTagEvidence {
return VersionTagEvidence{Name: name, TagSHA: "tag-" + name, Annotated: annotated}
}
func intPtr(value int) *int { return &value }
func TestDecideVersionReleaseRequiresAnnotatedTagAndChangelogTop(t *testing.T) {
cases := []struct {
name string
changelogTop string
tags []VersionTagEvidence
wantLabel string
wantKind string
wantReason string
}{
{"注释 tag + 顶部一致 ⇒ 正式版本", "0.1.0", []VersionTagEvidence{tag("v0.1.0", true)},
"0.1.0", RecordKindRelease, ReasonAnnotatedTagMatch},
{"轻量 tag 指向该提交 ⇒ 不算正式版本", "0.1.0", []VersionTagEvidence{tag("v0.1.0", false)},
"", RecordKindHistorical, ReasonLightweightTag},
{"有版本但无 tag ⇒ 不算正式版本", "0.1.0", nil, "", RecordKindHistorical, ReasonNoBaseline},
{"注释 tag 与提交内顶部不一致 ⇒ 不算正式版本", "0.1.1", []VersionTagEvidence{tag("v0.1.0", true)},
"", RecordKindHistorical, ReasonChangelogMismatch},
{"非三段版本名的 tag ⇒ 不算正式版本", "0.1.0", []VersionTagEvidence{tag("v0.1", true)},
"", RecordKindHistorical, ReasonNoBaseline},
}
for _, tc := range cases {
label, state, kind, evidence := DecideVersion(tc.changelogTop, tc.tags, "", nil)
if label != tc.wantLabel || kind != tc.wantKind {
t.Fatalf("%s:label=%q kind=%q,期望 %q/%q(reason=%s)", tc.name, label, kind, tc.wantLabel, tc.wantKind, evidence.Reason)
}
if evidence.Reason != tc.wantReason {
t.Fatalf("%s:reason=%q,期望 %q", tc.name, evidence.Reason, tc.wantReason)
}
if tc.wantKind == RecordKindHistorical && state != VersionStateUnknown {
t.Fatalf("%s:历史提交必须是 unknown,得到 %q", tc.name, state)
}
}
}
func TestDecideVersionDevelopmentUsesBaseTagCount(t *testing.T) {
label, state, kind, evidence := DecideVersion("0.1.0", nil, "v0.1.0", intPtr(12))
if label != "0.1.12" || kind != RecordKindDevelopment || state != VersionStateVerified {
t.Fatalf("开发号计算错:%q/%q/%q", label, kind, state)
}
if evidence.BaseTag != "v0.1.0" || evidence.CommitsSinceBase == nil || *evidence.CommitsSinceBase != 12 {
t.Fatalf("依据不完整:%+v", evidence)
}
// 恰在发布提交上(0 个提交)⇒ 号就是该版本号
label, _, kind, _ = DecideVersion("0.1.0", nil, "v0.1.0", intPtr(0))
if label != "0.1.0" || kind != RecordKindDevelopment {
t.Fatalf("0 个提交时应等于版本号本身,得到 %q/%q", label, kind)
}
// 图不完整 ⇒ 不给号
label, _, kind, _ = DecideVersion("0.1.0", nil, "", nil)
if label != "" || kind != RecordKindHistorical {
t.Fatalf("无基线时必须不下发号,得到 %q/%q", label, kind)
}
}
func TestDecideVersionKeepsSameNumberForDifferentCommits(t *testing.T) {
// 两个提交算出同一个号:判定层不合并、不去重(唯一身份是 SHA)
first, _, _, _ := DecideVersion("0.1.0", nil, "v0.1.0", intPtr(3))
second, _, _, _ := DecideVersion("0.1.0", nil, "v0.1.0", intPtr(3))
if first != second || first != "0.1.3" {
t.Fatalf("同号应各自保留:%q / %q", first, second)
}
}
func TestChangelogTopAndReleaseNotes(t *testing.T) {
changelog := "# Changelog\n\n## [Unreleased]\n\n### Added\n\n- 新\n\n" +
"## [0.2.0] - 2026-10-13\n\n### Changed\n\n- **破坏性**:接口下线\n\n" +
"## [0.1.0] - 2026-10-01\n\n### Added\n\n- 旧\n"
if top := ChangelogTopVersion(changelog); top != "0.2.0" {
t.Fatalf("顶部版本 = %q,期望 0.2.0", top)
}
notes := ExtractReleaseNotes(changelog, "0.2.0")
if notes != "### Changed\n\n- **破坏性**:接口下线" {
t.Fatalf("0.2.0 段落 = %q", notes)
}
if ExtractReleaseNotes(changelog, "9.9.9") != "" {
t.Fatal("不存在的版本必须返回空,不许猜")
}
// 不带方括号的二级标题也是边界(与 check_changelog 同口径)
boundary := "# Changelog\n\n## [0.1.0] - 2026-10-01\n\n### Added\n\n- 甲\n\n## 能力基线(未发布)\n\n- 乙\n"
if notes := ExtractReleaseNotes(boundary, "0.1.0"); notes != "### Added\n\n- 甲" {
t.Fatalf("边界算错:%q", notes)
}
}
func TestSemverHelpers(t *testing.T) {
if !SemverValid("0.1.0") || SemverValid("01.1.0") || SemverValid("0.1") || SemverValid("v0.1.0") {
t.Fatal("三段无前导零校验不对")
}
if CompareSemver("0.10.0", "0.9.0") != 1 || CompareSemver("1.0.0", "1.0.0") != 0 || CompareSemver("0.1.0", "0.2.0") != -1 {
t.Fatal("版本比较不对")
}
}
+5
View File
@@ -139,6 +139,11 @@ func classifyRole(method, path string) string {
if strings.HasPrefix(path, "/api/v1/backup-schedule") && method != http.MethodGet {
return roleAdmin
}
// 版本记录的同步会拉起一次对远端仓库的抓取(消耗网络与数据库写入),
// 与"谁能改生产绑定"同级:读任何角色可看,同步只能管理员。
if strings.HasPrefix(path, "/api/v1/version-history") && method != http.MethodGet {
return roleAdmin
}
// Everything else that mutates (review, batch, seal, confirm, start, retry,
// route visibility, disable) is engineer work; viewers cannot POST at all.
return roleEngineer
+16
View File
@@ -111,6 +111,10 @@ type Config struct {
// enumerates the production-side bases the operator can bind.
// BackupSchedule 是「系统设置 → 存储与备份」的计划存储;BackupHost 负责在目标库
// 所在主机上读回/下发计划并触发一次整库备份(未接线时页面降级展示)。
// VersionHistory 是「版本记录」页的只读查询面;VersionHistoryRepo 是固定的仓库标识
// (owner/name)。两者都给才接线,否则页面降级为"未接线"(不报 500)。
VersionHistory VersionHistoryStore
VersionHistoryRepo string
BackupSchedule BackupScheduleStore
BackupHost BackupHost
BackupRuns *BackupRunTracker
@@ -318,6 +322,18 @@ func NewHandler(config Config) (http.Handler, error) {
mux.HandleFunc("GET /api/v1/monitor/overview", func(w http.ResponseWriter, r *http.Request) {
monitorOverview(w, r, config.Monitor)
})
// 「版本记录」:当前运行的构建身份(只读,与监控同级可见)
mux.HandleFunc("GET /api/v1/build-info", func(w http.ResponseWriter, r *http.Request) {
buildInfo(w, r)
})
// 全部 main 提交时间线(读本库缓存,不直接打 Gitea)
mux.HandleFunc("GET /api/v1/version-history", func(w http.ResponseWriter, r *http.Request) {
versionHistoryList(w, r, config)
})
// 手动同步一次(仅管理员;并发同步合并成同一个作业)
mux.HandleFunc("POST /api/v1/version-history/sync", func(w http.ResponseWriter, r *http.Request) {
versionHistorySync(w, r, config)
})
mux.HandleFunc("GET /api/v1/monitor/knowledge-bases/{id}/files", func(w http.ResponseWriter, r *http.Request) {
monitorFiles(w, r, config.Monitor)
})
+16 -10
View File
@@ -1489,16 +1489,19 @@ func TestHandlerRejectsCatalogMutationsWithoutOperationID(t *testing.T) {
}
type fakeJobStore struct {
createSettingsConnectionID string
createSettingsDraft postgresstore.SourceSettingsDraft
createSettingsOperationID string
createSettingsErr error
createSettingsReplayed bool
activateSettingsConnectionID string
activateSettingsRevisionID string
activateSettingsOperationID string
activateSettingsReplayed bool
activateSettingsErr error
createSettingsConnectionID string
createSettingsDraft postgresstore.SourceSettingsDraft
createSettingsOperationID string
createSettingsErr error
createSettingsReplayed bool
activateSettingsConnectionID string
activateSettingsRevisionID string
activateSettingsOperationID string
activateSettingsReplayed bool
activateSettingsErr error
// enqueueEchoRequestedID:幂等"首次入队"语义 —— 返回调用方请求的那个 id
// (默认 false 时返回 enqueueResult,即"复用已有任务"的路径)。
enqueueEchoRequestedID bool
listSettingsConnectionID string
listSettingsErr error
settingsRevisions []governance.SourceConnectionRevision
@@ -1867,6 +1870,9 @@ func (s *fakeJobStore) ActivateUISettingsWithOperation(_ context.Context, revisi
func (s *fakeJobStore) Enqueue(_ context.Context, request jobs.EnqueueRequest, _ time.Time) (*jobs.Job, error) {
s.enqueued = request
if s.enqueueEchoRequestedID {
return &jobs.Job{ID: request.ID, Type: request.Type, State: jobs.StatePending}, nil
}
return s.enqueueResult, nil
}
+257
View File
@@ -0,0 +1,257 @@
package httpapi
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/version"
"knowledge-governance/internal/versionhistory"
)
// 「版本记录」页的服务面:**只读查询** + 管理员手动同步。
//
// 设计口径(见 docs/RELEASE_RUNBOOK.md 与 internal/governance/version_history.go):
// - 列表只读本库缓存(Gitea 不可达也能看),游标绑定快照 ⇒ 翻页不重不漏;
// - 同步只有一个入口,且只允许管理员触发;并发同步合并成同一个作业;
// - 「当前运行」只认构建产物注入的**完整 SHA 精确匹配**,拿不到就显示未知。
// 版本记录的作业类型(worker 侧注册同名 handler;值来自 versionhistory,避免两处写死)。
const VersionHistoryJobType = versionhistory.JobType
const (
versionHistoryDefaultPageSize = 30
versionHistoryMaxPageSize = 100
)
// VersionHistoryStore 是版本记录页需要的只读查询面(由 postgres.Store 实现)。
type VersionHistoryStore interface {
ActiveVersionHistorySnapshot(ctx context.Context, repoKey string) (int64, error)
LoadVersionHistoryPage(ctx context.Context, repoKey, kind, cursor string, limit int) (
[]governance.VersionHistoryCommit, string, bool, int64, error)
LoadVersionHistorySyncState(ctx context.Context, repoKey string) (governance.VersionHistorySyncRun, error)
VersionHistorySyncInFlight(ctx context.Context, repoKey string, now time.Time) (bool, error)
}
type versionHistoryTag struct {
Name string `json:"name"`
URL string `json:"url"`
}
type versionHistoryItem struct {
CommitSHA string `json:"commit_sha"`
ShortSHA string `json:"short_sha"`
Parents []string `json:"parents"`
CommittedAt string `json:"committed_at"`
AuthorDisplay string `json:"author_display"`
Subject string `json:"subject"`
Body string `json:"body"`
RecordKind string `json:"record_kind"`
VersionLabel string `json:"version_label"`
VersionState string `json:"version_state"`
ReleaseTags []versionHistoryTag `json:"release_tags"`
ReleaseNotes string `json:"release_notes"`
CommitURL string `json:"commit_url"`
VersionReason string `json:"version_reason"`
CurrentRunning bool `json:"is_current_running"`
}
type versionHistorySyncState struct {
Available bool `json:"available"`
Status string `json:"status"`
Complete bool `json:"complete"`
LastSuccessAt string `json:"last_success_at"`
FetchedCount int `json:"fetched_count"`
ExpectedCount *int `json:"expected_count"`
ErrorCode string `json:"error_code"`
SourceHeadSHA string `json:"source_head_sha"`
ActiveSnapshotID int64 `json:"active_snapshot_id"`
Repo string `json:"repo"`
}
type versionHistoryCurrentRunning struct {
State string `json:"state"`
CommitSHA string `json:"commit_sha"`
DisplayVersion string `json:"display_version"`
MatchedCommitSHA string `json:"matched_commit_sha"`
}
type versionHistoryResponse struct {
Items []versionHistoryItem `json:"items"`
NextCursor string `json:"next_cursor"`
HasMore bool `json:"has_more"`
Sync versionHistorySyncState `json:"sync"`
CurrentRunning versionHistoryCurrentRunning `json:"current_running"`
}
func versionHistoryError(w http.ResponseWriter, status int, code, message string) {
writeJSON(w, status, map[string]string{"error": message, "code": code})
}
// currentRunning 判定「当前运行」:只在完整 SHA 精确命中时标记,否则明确说未知。
func currentRunning(items []governance.VersionHistoryCommit) (versionHistoryCurrentRunning, string) {
info := version.Snapshot()
if !info.IdentityAvailable || info.CommitSHA == nil {
return versionHistoryCurrentRunning{State: "unknown",
DisplayVersion: info.DisplayVersion}, ""
}
sha := *info.CommitSHA
for _, item := range items {
if item.CommitSHA == sha {
return versionHistoryCurrentRunning{State: "matched", CommitSHA: sha,
DisplayVersion: info.DisplayVersion, MatchedCommitSHA: sha}, sha
}
}
state := "unknown"
if info.BuildKind == "development" {
state = "development"
}
// 开发构建:产物带完整 SHA,但它不在已同步的提交里 ⇒ 说明"当前运行"与页面记录不重合
return versionHistoryCurrentRunning{State: state, CommitSHA: sha,
DisplayVersion: info.DisplayVersion}, ""
}
func versionHistoryList(w http.ResponseWriter, r *http.Request, config Config) {
if config.VersionHistory == nil || config.VersionHistoryRepo == "" {
writeJSON(w, http.StatusOK, versionHistoryResponse{Items: []versionHistoryItem{},
Sync: versionHistorySyncState{Available: false},
CurrentRunning: func() versionHistoryCurrentRunning {
running, _ := currentRunning(nil)
return running
}()})
return
}
kind := strings.TrimSpace(r.URL.Query().Get("kind"))
if kind == "" {
kind = "all"
}
limit := versionHistoryDefaultPageSize
if raw := strings.TrimSpace(r.URL.Query().Get("limit")); raw != "" {
parsed, err := strconv.Atoi(raw)
if err != nil || parsed <= 0 || parsed > versionHistoryMaxPageSize {
versionHistoryError(w, http.StatusBadRequest, "invalid_limit",
fmt.Sprintf("limit 必须是 1..%d 的整数", versionHistoryMaxPageSize))
return
}
limit = parsed
}
cursor := strings.TrimSpace(r.URL.Query().Get("cursor"))
items, nextCursor, hasMore, _, err := config.VersionHistory.LoadVersionHistoryPage(
r.Context(), config.VersionHistoryRepo, kind, cursor, limit)
if err != nil {
if errors.Is(err, postgresstore.ErrVersionHistoryCursorExpired) {
versionHistoryError(w, http.StatusConflict, "cursor_expired",
"这次翻页依据的记录快照已被清理,请刷新页面重新加载")
return
}
versionHistoryError(w, http.StatusInternalServerError, "version_history_unavailable", "读取版本记录失败")
return
}
if items == nil {
items = []governance.VersionHistoryCommit{}
}
state, err := config.VersionHistory.LoadVersionHistorySyncState(r.Context(), config.VersionHistoryRepo)
if err != nil {
versionHistoryError(w, http.StatusInternalServerError, "version_history_unavailable", "读取同步状态失败")
return
}
running, matchedSHA := currentRunning(items)
payload := versionHistoryResponse{
Items: make([]versionHistoryItem, 0, len(items)),
NextCursor: nextCursor, HasMore: hasMore, CurrentRunning: running,
Sync: versionHistorySyncState{Available: true, Status: state.Status, Complete: state.Complete,
LastSuccessAt: versionHistoryTime(state.LastSuccessAt), FetchedCount: state.FetchedCount,
ExpectedCount: state.ExpectedCount, ErrorCode: state.ErrorCode,
SourceHeadSHA: state.SourceHeadSHA, ActiveSnapshotID: state.ActiveSnapshotID,
Repo: config.VersionHistoryRepo},
}
for _, item := range items {
record := versionHistoryItem{
CommitSHA: item.CommitSHA, ShortSHA: shortSHA(item.CommitSHA), Parents: item.Parents,
CommittedAt: versionHistoryTime(item.CommittedAt), AuthorDisplay: item.AuthorDisplay,
Subject: item.Subject, Body: item.Body, RecordKind: item.RecordKind,
VersionLabel: item.VersionLabel, VersionState: item.VersionState,
ReleaseNotes: item.ReleaseNotes, CommitURL: item.CommitURL,
VersionReason: item.VersionEvidence.Reason,
ReleaseTags: make([]versionHistoryTag, 0, len(item.ReleaseTags)),
CurrentRunning: matchedSHA != "" && item.CommitSHA == matchedSHA,
}
for _, tag := range item.ReleaseTags {
record.ReleaseTags = append(record.ReleaseTags, versionHistoryTag{Name: tag.Name, URL: tag.URL})
}
payload.Items = append(payload.Items, record)
}
writeJSON(w, http.StatusOK, payload)
}
func versionHistorySync(w http.ResponseWriter, r *http.Request, config Config) {
if config.VersionHistory == nil || config.VersionHistoryRepo == "" {
versionHistoryError(w, http.StatusServiceUnavailable, "version_history_unavailable",
"版本记录未接线:没有配置只读的仓库来源")
return
}
now := config.Now().UTC()
inFlight, err := config.VersionHistory.VersionHistorySyncInFlight(r.Context(), config.VersionHistoryRepo, now)
if err != nil {
versionHistoryError(w, http.StatusInternalServerError, "version_history_unavailable", "查询同步状态失败")
return
}
if inFlight {
state, err := config.VersionHistory.LoadVersionHistorySyncState(r.Context(), config.VersionHistoryRepo)
if err != nil {
versionHistoryError(w, http.StatusInternalServerError, "version_history_unavailable", "查询同步状态失败")
return
}
// 已经在跑:不重复入队,明确告诉调用方复用现有任务
writeJSON(w, http.StatusOK, map[string]any{"job_id": state.JobID, "sync_run_id": state.ID,
"status": state.Status, "reused": true})
return
}
triggeredBy := ""
if identity, ok := sessionFrom(r.Context()); ok {
triggeredBy = identity.Username
}
payload, err := json.Marshal(map[string]string{"repo_key": config.VersionHistoryRepo, "triggered_by": triggeredBy})
if err != nil {
versionHistoryError(w, http.StatusInternalServerError, "version_history_unavailable", "构造同步任务失败")
return
}
requestedID := fmt.Sprintf("version-history-sync-%d", now.UnixNano())
job, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{ID: requestedID,
Type: VersionHistoryJobType, Payload: payload, AvailableAt: now, MaxAttempts: 3,
IdempotencyKey: "version-history.sync:" + config.VersionHistoryRepo}, now)
if err != nil || job == nil {
versionHistoryError(w, http.StatusInternalServerError, "version_history_unavailable", "入队同步任务失败")
return
}
writeJSON(w, http.StatusAccepted, map[string]any{"job_id": job.ID, "status": job.State,
"reused": job.ID != requestedID})
}
// buildInfo:当前运行产物的构建身份(只读;与监控接口同级可见)。
func buildInfo(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, version.Snapshot())
}
func versionHistoryTime(value time.Time) string {
if value.IsZero() {
return ""
}
return value.UTC().Format(time.RFC3339)
}
func shortSHA(sha string) string {
if len(sha) > 12 {
return sha[:12]
}
return sha
}
+286
View File
@@ -0,0 +1,286 @@
package httpapi
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/version"
)
type fakeVersionHistoryStore struct {
items []governance.VersionHistoryCommit
nextCursor string
hasMore bool
snapshot int64
pageErr error
state governance.VersionHistorySyncRun
stateErr error
inFlight bool
inFlightErr error
lastKind string
lastCursor string
lastLimit int
}
func (f *fakeVersionHistoryStore) ActiveVersionHistorySnapshot(context.Context, string) (int64, error) {
return f.snapshot, nil
}
func (f *fakeVersionHistoryStore) LoadVersionHistoryPage(_ context.Context, _, kind, cursor string, limit int) (
[]governance.VersionHistoryCommit, string, bool, int64, error) {
f.lastKind, f.lastCursor, f.lastLimit = kind, cursor, limit
if f.pageErr != nil {
return nil, "", false, f.snapshot, f.pageErr
}
return f.items, f.nextCursor, f.hasMore, f.snapshot, nil
}
func (f *fakeVersionHistoryStore) LoadVersionHistorySyncState(context.Context, string) (governance.VersionHistorySyncRun, error) {
return f.state, f.stateErr
}
func (f *fakeVersionHistoryStore) VersionHistorySyncInFlight(context.Context, string, time.Time) (bool, error) {
return f.inFlight, f.inFlightErr
}
func decodeVersionHistoryBody(t *testing.T, recorder *httptest.ResponseRecorder) map[string]any {
t.Helper()
var payload map[string]any
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
t.Fatalf("响应不是 JSON:%v(%s)", err, recorder.Body.String())
}
return payload
}
// 注入的完整 SHA 决定「当前运行」;不注入就只能是未知 —— 绝不拿最新版本顶替。
func withInjectedIdentity(t *testing.T, sha, kind string) {
t.Helper()
previousSHA, previousKind, previousRelease := version.CommitSHA, version.BuildKind, version.ReleaseVersion
version.CommitSHA, version.BuildKind, version.ReleaseVersion = sha, kind, "0.1.0"
t.Cleanup(func() {
version.CommitSHA, version.BuildKind, version.ReleaseVersion = previousSHA, previousKind, previousRelease
})
}
func TestBuildInfoReportsIdentityAvailability(t *testing.T) {
sha := strings.Repeat("a", 40)
withInjectedIdentity(t, sha, "development")
recorder := httptest.NewRecorder()
buildInfo(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/build-info", nil))
if recorder.Code != http.StatusOK {
t.Fatalf("状态码 = %d", recorder.Code)
}
payload := decodeVersionHistoryBody(t, recorder)
if payload["identity_available"] != true || payload["commit_sha"] != sha {
t.Fatalf("完整注入时应给出身份:%v", payload)
}
if payload["build_kind"] != "development" {
t.Fatalf("构建类型 = %v", payload["build_kind"])
}
withInjectedIdentity(t, "unknown", "release")
recorder = httptest.NewRecorder()
buildInfo(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/build-info", nil))
payload = decodeVersionHistoryBody(t, recorder)
if payload["identity_available"] != false || payload["commit_sha"] != nil || payload["display_version"] != "dev" {
t.Fatalf("身份不可用时必须明确说未知:%v", payload)
}
}
func TestVersionHistoryListUnconfiguredStaysReadable(t *testing.T) {
withInjectedIdentity(t, "unknown", "development")
recorder := httptest.NewRecorder()
versionHistoryList(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/version-history", nil), Config{})
if recorder.Code != http.StatusOK {
t.Fatalf("未接线也必须 200(页面降级展示):%d", recorder.Code)
}
payload := decodeVersionHistoryBody(t, recorder)
sync, _ := payload["sync"].(map[string]any)
if sync["available"] != false {
t.Fatalf("未接线时 sync.available 必须为 false:%v", sync)
}
items, _ := payload["items"].([]any)
if len(items) != 0 {
t.Fatalf("未接线时不该有记录:%v", items)
}
running, _ := payload["current_running"].(map[string]any)
if running["state"] != "unknown" {
t.Fatalf("拿不到身份必须显示未知:%v", running)
}
}
func TestVersionHistoryListMarksOnlyExactMatchAndKeepsSameNumberApart(t *testing.T) {
sha := strings.Repeat("b", 40)
other := strings.Repeat("c", 40)
withInjectedIdentity(t, sha, "development")
store := &fakeVersionHistoryStore{snapshot: 7, hasMore: true, nextCursor: "cursor-1",
items: []governance.VersionHistoryCommit{
{CommitSHA: sha, CommittedAt: time.Date(2026, 10, 13, 10, 0, 0, 0, time.UTC),
Subject: "feat: 当前运行的这条", RecordKind: governance.RecordKindDevelopment,
VersionLabel: "0.1.3", VersionState: governance.VersionStateVerified,
VersionEvidence: governance.VersionEvidence{Reason: "counted_commits_since_base_tag"}},
{CommitSHA: other, CommittedAt: time.Date(2026, 10, 13, 9, 0, 0, 0, time.UTC),
Subject: "feat: 同号的另一条", RecordKind: governance.RecordKindDevelopment,
VersionLabel: "0.1.3", VersionState: governance.VersionStateVerified},
}}
config := Config{VersionHistory: store, VersionHistoryRepo: "WeknorA/knowledge-governance"}
recorder := httptest.NewRecorder()
versionHistoryList(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/version-history?kind=development&limit=2", nil), config)
if recorder.Code != http.StatusOK {
t.Fatalf("状态码 = %d", recorder.Code)
}
if store.lastKind != "development" || store.lastLimit != 2 {
t.Fatalf("查询参数没透传:kind=%s limit=%d", store.lastKind, store.lastLimit)
}
payload := decodeVersionHistoryBody(t, recorder)
items, _ := payload["items"].([]any)
if len(items) != 2 {
t.Fatalf("记录数 = %d", len(items))
}
flagged := 0
for _, raw := range items {
item, _ := raw.(map[string]any)
if item["is_current_running"] == true {
flagged++
if item["commit_sha"] != sha {
t.Fatalf("只允许精确匹配的那条被标记:%v", item)
}
}
// 同号不同 SHA:两条都在,且都带自己的短 SHA
if item["version_label"] != "0.1.3" || item["short_sha"] == "" {
t.Fatalf("同号的记录应各自保留并以短 SHA 区分:%v", item)
}
}
if flagged != 1 {
t.Fatalf("被标记为当前运行的条数 = %d", flagged)
}
if payload["has_more"] != true || payload["next_cursor"] != "cursor-1" {
t.Fatalf("分页游标没透传:%v", payload)
}
running, _ := payload["current_running"].(map[string]any)
if running["state"] != "matched" || running["matched_commit_sha"] != sha {
t.Fatalf("当前运行判定不对:%v", running)
}
}
func TestVersionHistoryListDevelopmentBuildNotInRecordsIsNotMarked(t *testing.T) {
withInjectedIdentity(t, strings.Repeat("d", 40), "development")
store := &fakeVersionHistoryStore{snapshot: 3, items: []governance.VersionHistoryCommit{
{CommitSHA: strings.Repeat("e", 40), VersionLabel: "0.1.5", RecordKind: governance.RecordKindDevelopment}}}
config := Config{VersionHistory: store, VersionHistoryRepo: "o/r"}
recorder := httptest.NewRecorder()
versionHistoryList(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/version-history", nil), config)
payload := decodeVersionHistoryBody(t, recorder)
items, _ := payload["items"].([]any)
for _, raw := range items {
item, _ := raw.(map[string]any)
if item["is_current_running"] == true {
t.Fatalf("产物 SHA 不在记录里就不得标记任何条目:%v", item)
}
}
running, _ := payload["current_running"].(map[string]any)
if running["state"] != "development" || running["commit_sha"] == "" {
t.Fatalf("开发构建要显式标为开发构建,而不是标成某条记录:%v", running)
}
}
func TestVersionHistoryListRejectsBadLimitAndExpiredCursor(t *testing.T) {
withInjectedIdentity(t, "unknown", "development")
store := &fakeVersionHistoryStore{snapshot: 5}
config := Config{VersionHistory: store, VersionHistoryRepo: "o/r"}
recorder := httptest.NewRecorder()
versionHistoryList(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/version-history?limit=999", nil), config)
if recorder.Code != http.StatusBadRequest {
t.Fatalf("limit 越界应 400,得到 %d", recorder.Code)
}
if code := decodeVersionHistoryBody(t, recorder)["code"]; code != "invalid_limit" {
t.Fatalf("错误码 = %v", code)
}
store.pageErr = postgresstore.ErrVersionHistoryCursorExpired
recorder = httptest.NewRecorder()
versionHistoryList(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/version-history?cursor=stale", nil), config)
if recorder.Code != http.StatusConflict {
t.Fatalf("游标过期应 409,得到 %d", recorder.Code)
}
if code := decodeVersionHistoryBody(t, recorder)["code"]; code != "cursor_expired" {
t.Fatalf("错误码 = %v", code)
}
}
func TestVersionHistorySyncRequiresAdminAndEnqueuesOnce(t *testing.T) {
// 角色:读任何角色可看,同步只能管理员
if got := classifyRole(http.MethodGet, "/api/v1/version-history"); got != roleViewer {
t.Fatalf("GET 的最小角色 = %q", got)
}
if got := classifyRole(http.MethodPost, "/api/v1/version-history/sync"); got != roleAdmin {
t.Fatalf("同步的最小角色 = %q,必须是 %q", got, roleAdmin)
}
now := time.Date(2026, 10, 13, 12, 0, 0, 0, time.UTC)
queue := &fakeJobStore{enqueueEchoRequestedID: true}
store := &fakeVersionHistoryStore{snapshot: 9}
config := Config{Store: queue, VersionHistory: store, VersionHistoryRepo: "Weknora/knowledge-governance",
Now: func() time.Time { return now }}
recorder := httptest.NewRecorder()
versionHistorySync(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/version-history/sync", nil), config)
if recorder.Code != http.StatusAccepted {
t.Fatalf("首次同步应 202,得到 %d(%s)", recorder.Code, recorder.Body.String())
}
if queue.enqueued.Type != VersionHistoryJobType || queue.enqueued.IdempotencyKey != "version-history.sync:Weknora/knowledge-governance" {
t.Fatalf("入队参数不对:%+v", queue.enqueued)
}
if queue.enqueued.MaxAttempts != 3 || queue.enqueued.AvailableAt != now {
t.Fatalf("入队参数不对:%+v", queue.enqueued)
}
payload := decodeVersionHistoryBody(t, recorder)
if payload["reused"] != false {
t.Fatalf("首次不该标成复用:%v", payload)
}
// 已经在跑:不重复入队,明确返回已有任务
store.inFlight = true
store.state = governance.VersionHistorySyncRun{ID: 11, JobID: "job-running", Status: "running"}
queue.enqueued = jobs.EnqueueRequest{}
recorder = httptest.NewRecorder()
versionHistorySync(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/version-history/sync", nil), config)
if recorder.Code != http.StatusOK {
t.Fatalf("并发同步应 200 + 复用已有任务,得到 %d", recorder.Code)
}
payload = decodeVersionHistoryBody(t, recorder)
if payload["reused"] != true || payload["job_id"] != "job-running" {
t.Fatalf("应复用已有任务:%v", payload)
}
if queue.enqueued.Type != "" {
t.Fatalf("已在跑时不得再次入队:%+v", queue.enqueued)
}
}
func TestVersionHistorySyncUnavailableWhenNotWired(t *testing.T) {
recorder := httptest.NewRecorder()
versionHistorySync(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/version-history/sync", nil), Config{})
if recorder.Code != http.StatusServiceUnavailable {
t.Fatalf("未接线应 503,得到 %d", recorder.Code)
}
if code := decodeVersionHistoryBody(t, recorder)["code"]; code != "version_history_unavailable" {
t.Fatalf("错误码 = %v", code)
}
// 未接线时页面仍然可读(只是没有记录)
store := &fakeVersionHistoryStore{stateErr: errors.New("boom")}
recorder = httptest.NewRecorder()
config := Config{VersionHistory: store, VersionHistoryRepo: "o/r"}
versionHistoryList(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/version-history", nil), config)
if recorder.Code != http.StatusInternalServerError {
t.Fatalf("查询异常应 500,得到 %d", recorder.Code)
}
}
@@ -0,0 +1,4 @@
DROP INDEX IF EXISTS version_history_sync_runs_recent_idx;
DROP INDEX IF EXISTS version_history_commits_page_idx;
DROP TABLE IF EXISTS version_history_sync_runs;
DROP TABLE IF EXISTS version_history_commits;
@@ -0,0 +1,56 @@
-- 「版本记录」页的数据:**远端 main 可达的每一个提交**(含合并提交与已并入 main 的侧分支提交),
-- 以及每次同步的状态。
--
-- 口径(见 docs/RELEASE_RUNBOOK.md 与 internal/governance/version_history.go):
-- * commit_sha(完整 40 位)是**唯一身份**;version_label **不是唯一键** —— 两个提交算出同一个
-- 开发号时各占一行,用 SHA 区分。
-- * 证据不足一律 version_state='unknown' + record_kind='historical',**不补造版本号**。
-- * 快照 = 一次同步(snapshot_id = version_history_sync_runs.id);对外只服务**最近一次成功**的快照
-- ⇒ 抓取过程中旧数据继续可读,新快照抓完并计数对账通过后才成为事实。
CREATE TABLE version_history_commits (
repo_key TEXT NOT NULL,
commit_sha CHAR(40) NOT NULL,
parents TEXT[] NOT NULL DEFAULT '{}',
committed_at TIMESTAMPTZ NOT NULL,
author_display TEXT NOT NULL DEFAULT '',
subject TEXT NOT NULL DEFAULT '',
body TEXT NOT NULL DEFAULT '',
version_label TEXT,
version_state TEXT NOT NULL,
record_kind TEXT NOT NULL,
release_tags JSONB NOT NULL DEFAULT '[]'::JSONB,
release_notes TEXT NOT NULL DEFAULT '',
commit_url TEXT NOT NULL DEFAULT '',
version_evidence JSONB NOT NULL DEFAULT '{}'::JSONB,
snapshot_id BIGINT NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (repo_key, commit_sha),
CONSTRAINT version_history_commits_kind CHECK (record_kind IN ('release', 'development', 'historical')),
CONSTRAINT version_history_commits_state CHECK (version_state IN ('verified', 'unknown')),
CONSTRAINT version_history_commits_sha CHECK (commit_sha ~ '^[0-9a-f]{40}$')
);
-- 分页排序 (committed_at DESC, commit_sha DESC) 的覆盖索引:游标翻页不重不漏。
CREATE INDEX version_history_commits_page_idx
ON version_history_commits (repo_key, snapshot_id, committed_at DESC, commit_sha DESC);
CREATE TABLE version_history_sync_runs (
id BIGSERIAL PRIMARY KEY,
repo_key TEXT NOT NULL,
job_id TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL,
source_head_sha TEXT NOT NULL DEFAULT '',
started_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
finished_at TIMESTAMPTZ,
last_success_at TIMESTAMPTZ,
complete BOOLEAN NOT NULL DEFAULT FALSE,
fetched_count INTEGER NOT NULL DEFAULT 0,
expected_count INTEGER,
error_code TEXT NOT NULL DEFAULT '',
triggered_by TEXT NOT NULL DEFAULT '',
CONSTRAINT version_history_sync_runs_status
CHECK (status IN ('pending', 'running', 'completed', 'failed', 'cancelled'))
);
CREATE INDEX version_history_sync_runs_recent_idx
ON version_history_sync_runs (repo_key, id DESC);
+12 -2
View File
@@ -11,8 +11,8 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
if err != nil {
t.Fatalf("loadMigrations() error = %v", err)
}
if len(migrations) != 45 {
t.Fatalf("migration count = %d, want 45", len(migrations))
if len(migrations) != 46 {
t.Fatalf("migration count = %d, want 46", len(migrations))
}
if migrations[0].Version != 1 || !strings.Contains(migrations[0].UpSQL, "CREATE TABLE IF NOT EXISTS jobs") {
t.Fatalf("migration 1 = %#v", migrations[0])
@@ -115,6 +115,16 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
if migrations[44].Version != 45 || !strings.Contains(migrations[44].UpSQL, "CREATE TABLE backup_schedule") {
t.Fatalf("migration 45 = %#v", migrations[44])
}
// 000046:「版本记录」的提交记录与同步状态;唯一身份是完整 commit_sha,
// 版本号不是唯一键;证据不足只落 historical(不许编版本号)。
if migrations[45].Version != 46 || !strings.Contains(migrations[45].UpSQL, "CREATE TABLE version_history_commits") ||
!strings.Contains(migrations[45].UpSQL, "CREATE TABLE version_history_sync_runs") ||
!strings.Contains(migrations[45].UpSQL, "'release', 'development', 'historical'") {
t.Fatalf("migration 46 = %#v", migrations[45])
}
if !strings.Contains(migrations[45].DownSQL, "DROP TABLE IF EXISTS version_history_commits") {
t.Fatalf("migration 46 down = %#v", migrations[45].DownSQL)
}
}
func TestProcessingConfirmationMigrationSeparatesPlanningFromUpload(t *testing.T) {
@@ -0,0 +1,315 @@
package postgres
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/jackc/pgx/v5"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/versionhistory"
)
// 「版本记录」的持久化:提交记录 + 同步状态(migration 000046)。
//
// 事实口径(与 internal/governance、internal/versionhistory 一致):
// - commit_sha 是唯一身份;同一提交再次同步只更新自己那一行(后补 tag 靠这条生效);
// - 对外只服务**最近一次成功**的快照(snapshot_id = sync_runs.id);
// - 失败不切换快照、不清空历史。
const (
// VersionHistoryKeptSnapshots:保留最近几个成功快照供游标使用,更旧的清理。
VersionHistoryKeptSnapshots = 3
// VersionHistoryInFlightWindow:超过这个时长的 running 视为"陈旧"(进程被杀留下的),
// 不再挡住新的同步请求。
VersionHistoryInFlightWindow = 30 * time.Minute
versionHistoryDefaultLimit = 30
versionHistoryMaxLimit = 100
)
// ErrVersionHistoryCursorExpired:游标指向的快照已被清理 ⇒ 调用方返回 409 让页面刷新。
var ErrVersionHistoryCursorExpired = errors.New("version history cursor expired")
// BeginVersionHistorySync 开一次同步(status=running),返回 run id(同时就是快照 id)。
func (s *Store) BeginVersionHistorySync(ctx context.Context, repoKey, jobID, triggeredBy string, now time.Time) (int64, error) {
var id int64
err := s.db.QueryRow(ctx, `
INSERT INTO version_history_sync_runs (repo_key, job_id, status, started_at, triggered_by)
VALUES ($1, $2, 'running', $3, $4)
RETURNING id`, repoKey, jobID, now.UTC(), triggeredBy).Scan(&id)
if err != nil {
return 0, fmt.Errorf("开启版本记录同步:%w", err)
}
return id, nil
}
// VersionHistorySyncInFlight 是否有在跑的同步(陈旧 running 不算)。
func (s *Store) VersionHistorySyncInFlight(ctx context.Context, repoKey string, now time.Time) (bool, error) {
var exists bool
err := s.db.QueryRow(ctx, `
SELECT EXISTS (
SELECT 1 FROM version_history_sync_runs
WHERE repo_key = $1 AND status IN ('pending', 'running') AND started_at > $2)`,
repoKey, now.UTC().Add(-VersionHistoryInFlightWindow)).Scan(&exists)
if err != nil {
return false, fmt.Errorf("查询版本记录同步状态:%w", err)
}
return exists, nil
}
// SaveVersionHistorySnapshot 写入本次快照的全部提交记录(同一提交只更新自己那一行),
// 并清理过旧的快照(**不动本次快照**)。
func (s *Store) SaveVersionHistorySnapshot(ctx context.Context, snapshotID int64, repoKey string,
records []governance.VersionHistoryCommit, expectedCount int, complete bool, now time.Time) error {
// expectedCount/complete 由 FinishVersionHistorySync 落库(这里只写记录行)。
_, _ = expectedCount, complete
tx, err := s.db.Begin(ctx)
if err != nil {
return fmt.Errorf("写版本记录快照:%w", err)
}
defer func() { _ = tx.Rollback(ctx) }()
for _, record := range records {
parents := record.Parents
if parents == nil {
parents = []string{}
}
tags, err := json.Marshal(record.ReleaseTags)
if err != nil {
return fmt.Errorf("序列化 tag 证据:%w", err)
}
evidence, err := json.Marshal(record.VersionEvidence)
if err != nil {
return fmt.Errorf("序列化版本依据:%w", err)
}
var label *string
if record.VersionLabel != "" {
value := record.VersionLabel
label = &value
}
if _, err := tx.Exec(ctx, `
INSERT INTO version_history_commits (repo_key, commit_sha, parents, committed_at, author_display,
subject, body, version_label, version_state, record_kind, release_tags, release_notes,
commit_url, version_evidence, snapshot_id, updated_at)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16)
ON CONFLICT (repo_key, commit_sha) DO UPDATE SET
parents = EXCLUDED.parents, committed_at = EXCLUDED.committed_at,
author_display = EXCLUDED.author_display, subject = EXCLUDED.subject, body = EXCLUDED.body,
version_label = EXCLUDED.version_label, version_state = EXCLUDED.version_state,
record_kind = EXCLUDED.record_kind, release_tags = EXCLUDED.release_tags,
release_notes = EXCLUDED.release_notes, commit_url = EXCLUDED.commit_url,
version_evidence = EXCLUDED.version_evidence, snapshot_id = EXCLUDED.snapshot_id,
updated_at = EXCLUDED.updated_at`,
repoKey, record.CommitSHA, parents, record.CommittedAt.UTC(), record.AuthorDisplay,
record.Subject, record.Body, label, record.VersionState, record.RecordKind,
tags, record.ReleaseNotes, record.CommitURL, evidence, snapshotID, now.UTC()); err != nil {
return fmt.Errorf("写入版本记录 %s:%w", record.CommitSHA, err)
}
}
if _, err := tx.Exec(ctx, `
DELETE FROM version_history_commits
WHERE repo_key = $1 AND snapshot_id <> $2 AND snapshot_id NOT IN (
SELECT id FROM version_history_sync_runs
WHERE repo_key = $1 AND status = 'completed' ORDER BY id DESC LIMIT $3)`,
repoKey, snapshotID, VersionHistoryKeptSnapshots); err != nil {
return fmt.Errorf("清理过旧版本记录快照:%w", err)
}
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("提交版本记录快照:%w", err)
}
return nil
}
// FinishVersionHistorySync 标记同步成功(此时本次快照成为对外服务的事实)。
func (s *Store) FinishVersionHistorySync(ctx context.Context, runID int64, outcome versionhistory.SyncOutcome, now time.Time) error {
command, err := s.db.Exec(ctx, `
UPDATE version_history_sync_runs
SET status = 'completed', finished_at = $2, last_success_at = $2, complete = $3,
fetched_count = $4, expected_count = $5, source_head_sha = $6
WHERE id = $1`,
runID, now.UTC(), outcome.Complete, outcome.FetchedCount, outcome.ExpectedCount, outcome.SourceHeadSHA)
if err != nil {
return fmt.Errorf("完成版本记录同步:%w", err)
}
if command.RowsAffected() != 1 {
return fmt.Errorf("完成版本记录同步:run %d 不存在", runID)
}
return nil
}
// FailVersionHistorySync 标记同步失败并落错误码(**不切换对外快照**)。
func (s *Store) FailVersionHistorySync(ctx context.Context, runID int64, errorCode string, now time.Time) error {
_, err := s.db.Exec(ctx, `
UPDATE version_history_sync_runs
SET status = 'failed', finished_at = $2, error_code = $3
WHERE id = $1`, runID, now.UTC(), errorCode)
if err != nil {
return fmt.Errorf("标记版本记录同步失败:%w", err)
}
return nil
}
// ActiveVersionHistorySnapshot 返回对外快照(最近一次成功同步);没有 ⇒ 0。
func (s *Store) ActiveVersionHistorySnapshot(ctx context.Context, repoKey string) (int64, error) {
var id int64
err := s.db.QueryRow(ctx, `
SELECT id FROM version_history_sync_runs
WHERE repo_key = $1 AND status = 'completed' ORDER BY id DESC LIMIT 1`, repoKey).Scan(&id)
if errors.Is(err, pgx.ErrNoRows) {
return 0, nil
}
if err != nil {
return 0, fmt.Errorf("查询版本记录快照:%w", err)
}
return id, nil
}
// LoadVersionHistorySyncState 读同步状态:最新一次 run(任何终态)+ 最近一次成功时间。
func (s *Store) LoadVersionHistorySyncState(ctx context.Context, repoKey string) (governance.VersionHistorySyncRun, error) {
var run governance.VersionHistorySyncRun
var expected *int
err := s.db.QueryRow(ctx, `
SELECT id, job_id, status, source_head_sha, started_at, finished_at, complete,
fetched_count, expected_count, error_code, triggered_by
FROM version_history_sync_runs WHERE repo_key = $1 ORDER BY id DESC LIMIT 1`, repoKey).
Scan(&run.ID, &run.JobID, &run.Status, &run.SourceHeadSHA, &run.StartedAt, &run.FinishedAt,
&run.Complete, &run.FetchedCount, &expected, &run.ErrorCode, &run.TriggeredBy)
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
return governance.VersionHistorySyncRun{}, fmt.Errorf("查询同步状态:%w", err)
}
if errors.Is(err, pgx.ErrNoRows) {
return governance.VersionHistorySyncRun{}, nil
}
run.ExpectedCount = expected
if snapshot, err := s.ActiveVersionHistorySnapshot(ctx, repoKey); err != nil {
return governance.VersionHistorySyncRun{}, err
} else {
run.ActiveSnapshotID = snapshot
}
var lastSuccess *time.Time
if err := s.db.QueryRow(ctx, `
SELECT last_success_at FROM version_history_sync_runs
WHERE repo_key = $1 AND status = 'completed' ORDER BY id DESC LIMIT 1`, repoKey).
Scan(&lastSuccess); err == nil && lastSuccess != nil {
run.LastSuccessAt = *lastSuccess
}
return run, nil
}
// VersionHistoryCursorBetween 偏移一页:绑定快照 + (committed_at, commit_sha) 组合游标。
func encodeVersionHistoryCursor(snapshotID int64, committedAt time.Time, sha string) string {
raw := fmt.Sprintf("%d|%s|%s", snapshotID, committedAt.UTC().Format(time.RFC3339Nano), sha)
return base64.RawURLEncoding.EncodeToString([]byte(raw))
}
func decodeVersionHistoryCursor(cursor string) (int64, time.Time, string, error) {
decoded, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil {
return 0, time.Time{}, "", fmt.Errorf("游标不是合法编码")
}
parts := strings.Split(string(decoded), "|")
if len(parts) != 3 {
return 0, time.Time{}, "", fmt.Errorf("游标结构不对")
}
var snapshotID int64
if _, err := fmt.Sscanf(parts[0], "%d", &snapshotID); err != nil || snapshotID <= 0 {
return 0, time.Time{}, "", fmt.Errorf("游标缺少快照")
}
committedAt, err := time.Parse(time.RFC3339Nano, parts[1])
if err != nil {
return 0, time.Time{}, "", fmt.Errorf("游标的提交时间不对")
}
if len(parts[2]) != 40 {
return 0, time.Time{}, "", fmt.Errorf("游标的提交标识不对")
}
return snapshotID, committedAt.UTC(), parts[2], nil
}
// LoadVersionHistoryPage 按游标读一页(只读当前快照;跨快照游标直接拒绝)。
func (s *Store) LoadVersionHistoryPage(ctx context.Context, repoKey, kind, cursor string, limit int) (
items []governance.VersionHistoryCommit, nextCursor string, hasMore bool, snapshotID int64, err error) {
if limit <= 0 {
limit = versionHistoryDefaultLimit
}
if limit > versionHistoryMaxLimit {
limit = versionHistoryMaxLimit
}
switch kind {
case "", "all", governance.RecordKindRelease, governance.RecordKindDevelopment, governance.RecordKindHistorical:
default:
return nil, "", false, 0, fmt.Errorf("未知的记录类型 %q", kind)
}
if kind == "" {
kind = "all"
}
active, err := s.ActiveVersionHistorySnapshot(ctx, repoKey)
if err != nil {
return nil, "", false, 0, err
}
var (
cursorAt *time.Time
cursorSHA *string
)
if cursor != "" {
cursorSnapshot, committedAt, sha, decodeErr := decodeVersionHistoryCursor(cursor)
if decodeErr != nil {
return nil, "", false, 0, fmt.Errorf("%w:%s", ErrVersionHistoryCursorExpired, decodeErr)
}
if cursorSnapshot != active {
return nil, "", false, active, ErrVersionHistoryCursorExpired
}
cursorAt, cursorSHA = &committedAt, &sha
}
if active == 0 {
return []governance.VersionHistoryCommit{}, "", false, 0, nil
}
rows, err := s.db.Query(ctx, `
SELECT commit_sha, parents, committed_at, author_display, subject, body, version_label,
version_state, record_kind, release_tags, release_notes, commit_url, version_evidence, snapshot_id
FROM version_history_commits
WHERE repo_key = $1 AND snapshot_id = $2 AND ($3 = 'all' OR record_kind = $3)
AND ($4::TIMESTAMPTZ IS NULL OR (committed_at, commit_sha) < ($4, $5))
ORDER BY committed_at DESC, commit_sha DESC
LIMIT $6`, repoKey, active, kind, cursorAt, cursorSHA, limit+1)
if err != nil {
return nil, "", false, active, fmt.Errorf("读取版本记录:%w", err)
}
defer rows.Close()
for rows.Next() {
var (
record governance.VersionHistoryCommit
label *string
tagsRaw []byte
evidRaw []byte
)
if err := rows.Scan(&record.CommitSHA, &record.Parents, &record.CommittedAt, &record.AuthorDisplay,
&record.Subject, &record.Body, &label, &record.VersionState, &record.RecordKind,
&tagsRaw, &record.ReleaseNotes, &record.CommitURL, &evidRaw, &record.SnapshotID); err != nil {
return nil, "", false, active, fmt.Errorf("解析版本记录:%w", err)
}
record.RepoKey = repoKey
if label != nil {
record.VersionLabel = *label
}
if len(tagsRaw) > 0 {
_ = json.Unmarshal(tagsRaw, &record.ReleaseTags)
}
if len(evidRaw) > 0 {
_ = json.Unmarshal(evidRaw, &record.VersionEvidence)
}
items = append(items, record)
}
if err := rows.Err(); err != nil {
return nil, "", false, active, fmt.Errorf("读取版本记录:%w", err)
}
if len(items) > limit {
items = items[:limit]
hasMore = true
last := items[len(items)-1]
nextCursor = encodeVersionHistoryCursor(active, last.CommittedAt, last.CommitSHA)
}
return items, nextCursor, hasMore, active, nil
}
+35
View File
@@ -0,0 +1,35 @@
package version
// 构建身份(「版本记录」页的"当前运行"判据)。**只回身份字段**:不含主机、配置或任何凭据。
//
// 关键点:只有注入进来的 **完整 40 位 SHA** 才算可用身份 —— 页面据此做精确匹配;
// 拿不到就明确返回 identity_available=false,由页面显示"当前运行版本未知",**绝不猜**。
type BuildInfo struct {
ReleaseVersion string `json:"release_version"`
BuildKind string `json:"build_kind"`
CommitSHA *string `json:"commit_sha"`
DisplayVersion string `json:"display_version"`
BuiltAt string `json:"built_at"`
IdentityAvailable bool `json:"identity_available"`
}
// Snapshot 读当前运行产物的构建身份。
func Snapshot() BuildInfo {
info := BuildInfo{ReleaseVersion: ReleaseVersion, BuildKind: BuildKind, BuiltAt: BuildTime}
if IsRelease() {
info.BuildKind = "release"
} else {
info.BuildKind = "development"
}
if fullSHA.MatchString(CommitSHA) {
sha := CommitSHA
info.CommitSHA = &sha
info.DisplayVersion = DisplayVersion()
info.IdentityAvailable = true
return info
}
// 身份不可用:明确说"未知",不回上一正式版本号,也不假装是某个提交
info.DisplayVersion = "dev"
info.IdentityAvailable = false
return info
}
+355
View File
@@ -0,0 +1,355 @@
package versionhistory
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
// GiteaConfig 是只读客户端的配置。**只用匿名请求**:本客户端不会携带任何凭据,
// 也不接受调用方传入任意 URL —— base 必须在白名单里,仓库只允许配置的那一个。
type GiteaConfig struct {
BaseURL string
AllowedBaseURLs []string
// LinkOrigin 是**给人看的链接**用的 origin(例如公网 https://gitea.example)。
// 抓取用内网地址、点链接的人在内网外 —— 两者必须能分开,否则页面上的链接打不开。
// 留空则与 BaseURL 相同。它只用于拼展示链接,不参与任何请求。
LinkOrigin string
Repo string
HTTPClient *http.Client
Timeout time.Duration
MaxResponseBytes int64
MaxRetries int
Sleep func(time.Duration)
PageSize int
}
// GiteaClient 只读地访问 Gitea 的提交、tag 与仓库内文件。
type GiteaClient struct {
baseURL *url.URL
linkOrigin string
repo string
client *http.Client
maxBytes int64
maxRetries int
sleep func(time.Duration)
pageSize int
}
const (
giteaDefaultTimeout = 15 * time.Second
giteaDefaultMaxBytes = 5 << 20 // 单个响应上限 5MB
giteaDefaultRetries = 3
giteaDefaultPageSize = 50 // Gitea 的 commits/tags 上限就是 50
giteaCommitURLSuffix = "/commit/"
)
// NewGiteaClient 校验并构造客户端。校验失败一律返回错误(宁可不接线)。
func NewGiteaClient(config GiteaConfig) (*GiteaClient, error) {
base, err := url.Parse(strings.TrimSpace(config.BaseURL))
if err != nil || base.Host == "" || (base.Scheme != "http" && base.Scheme != "https") {
return nil, errors.New("版本记录:Gitea base URL 非法(必须是 http(s) 绝对地址)")
}
allowed := false
for _, candidate := range config.AllowedBaseURLs {
parsed, perr := url.Parse(strings.TrimSpace(candidate))
if perr == nil && parsed.Host != "" && parsed.Scheme == base.Scheme && parsed.Host == base.Host {
allowed = true
break
}
}
if !allowed {
return nil, fmt.Errorf("版本记录:Gitea base URL %q 不在白名单里(拒绝任意 URL 请求)", config.BaseURL)
}
repo := strings.Trim(strings.TrimSpace(config.Repo), "/")
if strings.Count(repo, "/") != 1 || strings.ContainsAny(repo, " \t?#") {
return nil, errors.New("版本记录:仓库必须是 owner/name 形式")
}
maxBytes := config.MaxResponseBytes
if maxBytes <= 0 {
maxBytes = giteaDefaultMaxBytes
}
timeout := config.Timeout
if timeout <= 0 {
timeout = giteaDefaultTimeout
}
retries := config.MaxRetries
if retries <= 0 {
retries = giteaDefaultRetries
}
pageSize := config.PageSize
if pageSize <= 0 || pageSize > giteaDefaultPageSize {
pageSize = giteaDefaultPageSize
}
client := config.HTTPClient
if client == nil {
client = &http.Client{Timeout: timeout}
}
// 只允许回到同一个 host:重定向到别处一律拒绝(防 SSRF)。
sameHost := *client
sameHost.CheckRedirect = func(req *http.Request, via []*http.Request) error {
if req.URL.Scheme != base.Scheme || req.URL.Host != base.Host {
return newGiteaError(KindRedirect, 0, "版本记录:拒绝重定向到其它主机", nil)
}
return nil
}
sleep := config.Sleep
if sleep == nil {
sleep = time.Sleep
}
linkOrigin := strings.TrimRight(strings.TrimSpace(config.LinkOrigin), "/")
if linkOrigin == "" {
linkOrigin = strings.TrimRight(base.String(), "/")
} else if parsed, perr := url.Parse(linkOrigin); perr != nil || parsed.Host == "" ||
(parsed.Scheme != "http" && parsed.Scheme != "https") {
return nil, fmt.Errorf("版本记录:链接 origin %q 非法(必须是 http(s) 绝对地址)", config.LinkOrigin)
}
return &GiteaClient{baseURL: base, linkOrigin: linkOrigin, repo: repo, client: &sameHost,
maxBytes: maxBytes, maxRetries: retries, sleep: sleep, pageSize: pageSize}, nil
}
// PageSize 是抓取页大小(外层据此做完整性对账)。
func (c *GiteaClient) PageSize() int { return c.pageSize }
// CommitURLBase 给记录页拼提交链接用(**给人看的** origin + 固定仓库,不接受外部传入)。
// 抓取走内网、链接走公网 —— 两者分开,页面上的链接才点得开。
func (c *GiteaClient) CommitURLBase() string {
return c.linkOrigin + "/" + c.repo + giteaCommitURLSuffix
}
// TagURLBase 给记录页拼 tag 链接用(`<link origin>/<repo>/src/tag/`)。
func (c *GiteaClient) TagURLBase() string {
return c.linkOrigin + "/" + c.repo + "/src/tag/"
}
func (c *GiteaClient) apiURL(path string, query url.Values) string {
target := *c.baseURL
target.Path = strings.TrimRight(c.baseURL.Path, "/") + "/api/v1/repos/" + c.repo + path
target.RawQuery = query.Encode()
return target.String()
}
// get 发一次匿名 GET(**不设 Authorization 头**),带超时、响应上限与退避重试。
func (c *GiteaClient) get(ctx context.Context, rawURL string) ([]byte, http.Header, error) {
var lastErr error
for attempt := 0; attempt <= c.maxRetries; attempt++ {
if attempt > 0 {
c.sleep(time.Duration(attempt) * 500 * time.Millisecond)
}
request, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
return nil, nil, newGiteaError(KindParse, 0, "版本记录:构造请求失败", err)
}
request.Header.Set("Accept", "application/json")
response, err := c.client.Do(request)
if err != nil {
lastErr = newGiteaError(KindUnreachable, 0, "版本记录:Gitea 不可达", err)
continue
}
body, readErr := io.ReadAll(io.LimitReader(response.Body, c.maxBytes+1))
closeErr := response.Body.Close()
if readErr != nil {
lastErr = newGiteaError(KindUnreachable, 0, "版本记录:读取响应失败", readErr)
continue
}
if closeErr != nil {
lastErr = newGiteaError(KindUnreachable, 0, "版本记录:关闭响应失败", closeErr)
continue
}
if int64(len(body)) > c.maxBytes {
return nil, nil, newGiteaError(KindTooLarge, response.StatusCode,
fmt.Sprintf("版本记录:响应超过 %d 字节上限(已丢弃)", c.maxBytes), nil)
}
switch {
case response.StatusCode == http.StatusOK:
return body, response.Header, nil
case response.StatusCode == http.StatusNotFound:
return nil, response.Header, errGiteaNotFound
case response.StatusCode == http.StatusTooManyRequests || response.StatusCode >= 500:
lastErr = newGiteaError(KindStatus, response.StatusCode, "版本记录:Gitea 返回可重试错误", nil)
continue
default:
return nil, response.Header, newGiteaError(KindStatus, response.StatusCode, "版本记录:Gitea 返回错误", nil)
}
}
if lastErr == nil {
lastErr = newGiteaError(KindUnreachable, 0, "版本记录:Gitea 请求失败", nil)
}
return nil, nil, lastErr
}
var errGiteaNotFound = newGiteaError(KindNotFound, http.StatusNotFound, "版本记录:Gitea 上没有该对象", nil)
// ListCommits 读一页提交;同时返回 X-Total-Count(用于完整性对账,不做假 total)。
func (c *GiteaClient) ListCommits(ctx context.Context, page, limit int) ([]RawCommit, int, error) {
if limit <= 0 || limit > giteaDefaultPageSize {
limit = giteaDefaultPageSize
}
query := url.Values{}
query.Set("limit", fmt.Sprintf("%d", limit))
query.Set("page", fmt.Sprintf("%d", page))
query.Set("stat", "false")
query.Set("verification", "false")
body, header, err := c.get(ctx, c.apiURL("/commits", query))
if err != nil {
return nil, 0, err
}
var payload []struct {
SHA string `json:"sha"`
Parents []struct {
SHA string `json:"sha"`
} `json:"parents"`
Created string `json:"created"`
Commit struct {
Message string `json:"message"`
Author struct {
Name string `json:"name"`
Date string `json:"date"`
} `json:"author"`
Committer struct {
Name string `json:"name"`
Date string `json:"date"`
} `json:"committer"`
} `json:"commit"`
}
if err := json.Unmarshal(body, &payload); err != nil {
return nil, 0, newGiteaError(KindParse, 0, "版本记录:提交响应无法解析", err)
}
total := 0
if raw := header.Get("X-Total-Count"); raw != "" {
if _, err := fmt.Sscanf(raw, "%d", &total); err != nil {
total = 0
}
}
commits := make([]RawCommit, 0, len(payload))
for _, item := range payload {
if !fullSHA.MatchString(item.SHA) {
continue
}
parents := make([]string, 0, len(item.Parents))
for _, parent := range item.Parents {
parents = append(parents, parent.SHA)
}
subject, body := splitMessage(item.Commit.Message)
when := parseGiteaTime(item.Commit.Committer.Date)
if when.IsZero() {
when = parseGiteaTime(item.Commit.Author.Date)
}
if when.IsZero() {
when = parseGiteaTime(item.Created)
}
author := item.Commit.Author.Name
if author == "" {
author = item.Commit.Committer.Name
}
commits = append(commits, RawCommit{SHA: item.SHA, Parents: parents, CommittedAt: when,
AuthorDisplay: author, Subject: subject, Body: body})
}
return commits, total, nil
}
// BranchHeadSHA 读分支 HEAD 的完整 SHA(同步记录里的 source_head_sha 用它)。
func (c *GiteaClient) BranchHeadSHA(ctx context.Context, branch string) (string, error) {
if strings.ContainsAny(branch, " /?#") || branch == "" {
return "", newGiteaError(KindParse, 0, "版本记录:分支名非法", nil)
}
body, _, err := c.get(ctx, c.apiURL("/branches/"+branch, url.Values{}))
if err != nil {
return "", err
}
var payload struct {
Commit struct {
ID string `json:"id"`
} `json:"commit"`
}
if err := json.Unmarshal(body, &payload); err != nil {
return "", newGiteaError(KindParse, 0, "版本记录:分支响应无法解析", err)
}
if !fullSHA.MatchString(payload.Commit.ID) {
return "", newGiteaError(KindParse, 0, "版本记录:分支 HEAD 不是完整 SHA", nil)
}
return payload.Commit.ID, nil
}
// ListTags 读全部 tag,并逐个核验它是不是**注释 tag** 以及它指向哪个提交。
// 轻量 tag(object.type == "commit")不会被当作正式版本的证据。
func (c *GiteaClient) ListTags(ctx context.Context) ([]RawTag, error) {
type ref struct {
Ref string `json:"ref"`
Object struct {
Type string `json:"type"`
SHA string `json:"sha"`
} `json:"object"`
}
refs := make([]ref, 0)
for page := 1; page <= 40; page++ {
query := url.Values{}
query.Set("limit", "50")
query.Set("page", fmt.Sprintf("%d", page))
body, _, err := c.get(ctx, c.apiURL("/git/refs/tags", query))
if err != nil {
return nil, err
}
var pageRefs []ref
if err := json.Unmarshal(body, &pageRefs); err != nil {
return nil, newGiteaError(KindParse, 0, "版本记录:tag 列表无法解析", err)
}
refs = append(refs, pageRefs...)
// 短页 = 最后一页(也防住"服务端忽略 page 参数"导致的死循环)
if len(pageRefs) < 50 {
break
}
}
tags := make([]RawTag, 0, len(refs))
for _, item := range refs {
name := strings.TrimPrefix(item.Ref, "refs/tags/")
if name == "" {
continue
}
tag := RawTag{Name: name, TargetSHA: item.Object.SHA}
if item.Object.Type == "tag" {
tag.Annotated = true
tag.TagSHA = item.Object.SHA
// 注释 tag:解引用到真正的提交(tag 对象里的 object.sha)
body, _, err := c.get(ctx, c.apiURL("/git/tags/"+item.Object.SHA, url.Values{}))
if err != nil {
return nil, err
}
var annotated struct {
Object struct {
SHA string `json:"sha"`
} `json:"object"`
}
if err := json.Unmarshal(body, &annotated); err != nil {
return nil, newGiteaError(KindParse, 0, "版本记录:注释 tag 无法解析", err)
}
if !fullSHA.MatchString(annotated.Object.SHA) {
continue
}
tag.TargetSHA = annotated.Object.SHA
}
tags = append(tags, tag)
}
return tags, nil
}
// ReadFile 读某个提交内的文件(用于取该提交的 CHANGELOG.md)。
func (c *GiteaClient) ReadFile(ctx context.Context, sha, path string) (string, error) {
if !fullSHA.MatchString(sha) {
return "", newGiteaError(KindParse, 0, "版本记录:提交必须是完整 40 位 SHA", nil)
}
if strings.Contains(path, "..") || strings.HasPrefix(path, "/") {
return "", newGiteaError(KindParse, 0, "版本记录:文件路径非法", nil)
}
body, _, err := c.get(ctx, c.apiURL("/raw/"+path, url.Values{"ref": []string{sha}}))
if err != nil {
return "", err
}
return string(body), nil
}
+243
View File
@@ -0,0 +1,243 @@
package versionhistory
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
const (
shaA = "1111111111111111111111111111111111111111"
shaB = "2222222222222222222222222222222222222222"
shaT = "3333333333333333333333333333333333333333" // 注释 tag 对象
)
func fakeGitea(t *testing.T, handler http.HandlerFunc) *httptest.Server {
t.Helper()
server := httptest.NewServer(handler)
t.Cleanup(server.Close)
return server
}
func validConfig(base string) GiteaConfig {
return GiteaConfig{BaseURL: base, AllowedBaseURLs: []string{base}, Repo: "Weknora/knowledge-governance",
Sleep: func(time.Duration) {}, MaxRetries: 2, PageSize: 50}
}
func TestGiteaClientUsesSeparateLinkOriginForHumanLinks(t *testing.T) {
// 抓取走内网、链接走公网:页面上的链接必须用公网 origin,否则点开是空白。
config := validConfig("http://192.168.50.223:3000")
config.LinkOrigin = "https://gitea.zheromiku.top/"
client, err := NewGiteaClient(config)
if err != nil {
t.Fatalf("构造客户端失败:%v", err)
}
if got := client.CommitURLBase(); got != "https://gitea.zheromiku.top/Weknora/knowledge-governance/commit/" {
t.Fatalf("提交链接基址 = %q(必须用公网 origin)", got)
}
if got := client.TagURLBase(); got != "https://gitea.zheromiku.top/Weknora/knowledge-governance/src/tag/" {
t.Fatalf("tag 链接基址 = %q", got)
}
// 不配 LinkOrigin ⇒ 退回抓取 origin(内网场景仍然一致)
fallback, err := NewGiteaClient(validConfig("http://192.168.50.223:3000"))
if err != nil {
t.Fatalf("构造客户端失败:%v", err)
}
if !strings.HasPrefix(fallback.CommitURLBase(), "http://192.168.50.223:3000/") {
t.Fatalf("未配 LinkOrigin 时应退回抓取 origin:%q", fallback.CommitURLBase())
}
bad := validConfig("http://192.168.50.223:3000")
bad.LinkOrigin = "ftp://nope"
if _, err := NewGiteaClient(bad); err == nil {
t.Fatal("非 http(s) 的链接 origin 必须拒绝")
}
}
func TestGiteaClientRejectsNonWhitelistedOriginAndBadRepo(t *testing.T) {
if _, err := NewGiteaClient(GiteaConfig{BaseURL: "http://evil.example.com",
AllowedBaseURLs: []string{"http://192.168.50.223:3000"}, Repo: "a/b"}); err == nil {
t.Fatal("白名单外的 origin 必须拒绝")
}
if _, err := NewGiteaClient(GiteaConfig{BaseURL: "ftp://host", AllowedBaseURLs: []string{"ftp://host"},
Repo: "a/b"}); err == nil {
t.Fatal("非 http(s) 必须拒绝")
}
if _, err := NewGiteaClient(GiteaConfig{BaseURL: "http://host", AllowedBaseURLs: []string{"http://host"},
Repo: "a/b/c"}); err == nil {
t.Fatal("仓库必须是 owner/name")
}
if _, err := NewGiteaClient(GiteaConfig{BaseURL: "http://host", AllowedBaseURLs: []string{"http://host"},
Repo: "a/b?x=1"}); err == nil {
t.Fatal("仓库名带查询串必须拒绝")
}
}
func TestGiteaClientListCommitsParsesFieldsAndSendsNoCredentials(t *testing.T) {
var sawAuth string
server := fakeGitea(t, func(w http.ResponseWriter, r *http.Request) {
sawAuth = r.Header.Get("Authorization")
if got := r.URL.Path; got != "/api/v1/repos/Weknora/knowledge-governance/commits" {
t.Errorf("路径 = %s", got)
}
if r.URL.Query().Get("limit") != "50" || r.URL.Query().Get("page") != "1" {
t.Errorf("分页参数 = %s", r.URL.RawQuery)
}
w.Header().Set("X-Total-Count", "111")
fmt.Fprintf(w, `[{"sha":%q,"parents":[{"sha":%q}],"created":"2026-10-13T09:12:00Z",
"commit":{"message":"feat: 标题\n\n正文一行\n第二行","author":{"name":"姚章浩","date":"2026-10-13T09:11:00Z"},
"committer":{"name":"姚章浩","date":"2026-10-13T09:12:00Z"}}}]`, shaB, shaA)
})
client, err := NewGiteaClient(validConfig(server.URL))
if err != nil {
t.Fatalf("构造客户端失败:%v", err)
}
commits, total, err := client.ListCommits(context.Background(), 1, 50)
if err != nil {
t.Fatalf("ListCommits:%v", err)
}
if sawAuth != "" {
t.Fatalf("匿名只读不得携带任何凭据,实际带了 Authorization=%q", sawAuth)
}
if total != 111 || len(commits) != 1 {
t.Fatalf("total=%d len=%d", total, len(commits))
}
got := commits[0]
if got.SHA != shaB || len(got.Parents) != 1 || got.Parents[0] != shaA {
t.Fatalf("提交字段解析错:%+v", got)
}
if got.Subject != "feat: 标题" || got.Body != "正文一行\n第二行" {
t.Fatalf("标题/正文拆分错:%q / %q", got.Subject, got.Body)
}
if !got.CommittedAt.Equal(time.Date(2026, 10, 13, 9, 12, 0, 0, time.UTC)) {
t.Fatalf("提交时间解析错:%s", got.CommittedAt)
}
if !strings.HasSuffix(client.CommitURLBase(), "/Weknora/knowledge-governance/commit/") {
t.Fatalf("提交链接基址错:%s", client.CommitURLBase())
}
}
func TestGiteaClientRetriesTransientFailuresThenGivesUp(t *testing.T) {
attempts := 0
server := fakeGitea(t, func(w http.ResponseWriter, r *http.Request) {
attempts++
if attempts < 3 {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("X-Total-Count", "0")
fmt.Fprint(w, "[]")
})
client, err := NewGiteaClient(validConfig(server.URL))
if err != nil {
t.Fatalf("构造客户端失败:%v", err)
}
if _, _, err := client.ListCommits(context.Background(), 1, 50); err != nil {
t.Fatalf("5xx 应退避重试后成功:%v", err)
}
if attempts != 3 {
t.Fatalf("重试次数 = %d,期望 3", attempts)
}
alwaysFail := fakeGitea(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
})
client2, err := NewGiteaClient(validConfig(alwaysFail.URL))
if err != nil {
t.Fatalf("构造客户端失败:%v", err)
}
if _, _, err := client2.ListCommits(context.Background(), 1, 50); err == nil {
t.Fatal("持续 5xx 必须报错,不能返回空数据")
}
}
func TestGiteaClientRejectsOversizedResponseAndCrossHostRedirect(t *testing.T) {
big := fakeGitea(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Total-Count", "1")
fmt.Fprintf(w, "[{\"sha\":%q,\"commit\":{\"message\":%q}}]", shaA, strings.Repeat("x", 4096))
})
config := validConfig(big.URL)
config.MaxResponseBytes = 512
client, err := NewGiteaClient(config)
if err != nil {
t.Fatalf("构造客户端失败:%v", err)
}
if _, _, err := client.ListCommits(context.Background(), 1, 50); err == nil {
t.Fatal("超过响应上限必须报错(丢弃)")
}
elsewhere := fakeGitea(t, func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "[]") })
redirector := fakeGitea(t, func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, elsewhere.URL+"/api/v1/repos/Weknora/knowledge-governance/commits", http.StatusFound)
})
client2, err := NewGiteaClient(validConfig(redirector.URL))
if err != nil {
t.Fatalf("构造客户端失败:%v", err)
}
if _, _, err := client2.ListCommits(context.Background(), 1, 50); err == nil {
t.Fatal("跨主机重定向必须拒绝")
}
}
func TestGiteaClientListTagsDetectsAnnotatedAndLightweight(t *testing.T) {
server := fakeGitea(t, func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/api/v1/repos/Weknora/knowledge-governance/git/refs/tags":
fmt.Fprintf(w, `[{"ref":"refs/tags/v0.1.0","object":{"type":"tag","sha":%q}},
{"ref":"refs/tags/light","object":{"type":"commit","sha":%q}}]`, shaT, shaA)
case r.URL.Path == "/api/v1/repos/Weknora/knowledge-governance/git/tags/"+shaT:
fmt.Fprintf(w, `{"tag":"v0.1.0","object":{"type":"commit","sha":%q}}`, shaB)
default:
t.Errorf("未预期的路径 %s", r.URL.Path)
w.WriteHeader(http.StatusNotFound)
}
})
client, err := NewGiteaClient(validConfig(server.URL))
if err != nil {
t.Fatalf("构造客户端失败:%v", err)
}
tags, err := client.ListTags(context.Background())
if err != nil {
t.Fatalf("ListTags:%v", err)
}
if len(tags) != 2 {
t.Fatalf("tag 数 = %d", len(tags))
}
annotated := tags[0]
if annotated.Name != "v0.1.0" || !annotated.Annotated || annotated.TagSHA != shaT || annotated.TargetSHA != shaB {
t.Fatalf("注释 tag 应解引用到提交:%+v", annotated)
}
lightweight := tags[1]
if lightweight.Annotated || lightweight.TargetSHA != shaA {
t.Fatalf("轻量 tag 不能被当成注释 tag:%+v", lightweight)
}
}
func TestGiteaClientReadFileGuards(t *testing.T) {
server := fakeGitea(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("ref") != shaA {
t.Errorf("ref = %s", r.URL.Query().Get("ref"))
}
fmt.Fprint(w, "# Changelog\n")
})
client, err := NewGiteaClient(validConfig(server.URL))
if err != nil {
t.Fatalf("构造客户端失败:%v", err)
}
text, err := client.ReadFile(context.Background(), shaA, "CHANGELOG.md")
if err != nil || !strings.Contains(text, "Changelog") {
t.Fatalf("读文件失败:%v / %q", err, text)
}
if _, err := client.ReadFile(context.Background(), "abc", "CHANGELOG.md"); err == nil {
t.Fatal("短 SHA 必须拒绝")
}
if _, err := client.ReadFile(context.Background(), shaA, "../../etc/passwd"); err == nil {
t.Fatal("路径穿越必须拒绝")
}
if _, err := client.ReadFile(context.Background(), shaA, "/etc/passwd"); err == nil {
t.Fatal("绝对路径必须拒绝")
}
}
+36
View File
@@ -0,0 +1,36 @@
package versionhistory
import (
"regexp"
"strings"
"time"
)
// fullSHA:只认完整 40 位小写十六进制 —— 版本记录的唯一身份。
var fullSHA = regexp.MustCompile(`^[0-9a-f]{40}$`)
// splitMessage 把提交信息拆成标题(首行)与正文(其余);不编造摘要。
func splitMessage(message string) (subject, body string) {
message = strings.ReplaceAll(message, "\r\n", "\n")
trimmed := strings.TrimRight(message, "\n")
if strings.TrimSpace(trimmed) == "" {
return "", ""
}
if index := strings.Index(trimmed, "\n"); index >= 0 {
return strings.TrimSpace(trimmed[:index]), strings.TrimSpace(trimmed[index+1:])
}
return strings.TrimSpace(trimmed), ""
}
// parseGiteaTime 解析 Gitea 的时间字段;解析不了返回零值(调用方按"时间未知"处理)。
func parseGiteaTime(value string) time.Time {
if strings.TrimSpace(value) == "" {
return time.Time{}
}
for _, layout := range []string{time.RFC3339Nano, time.RFC3339, "2006-01-02T15:04:05Z0700"} {
if parsed, err := time.Parse(layout, value); err == nil {
return parsed.UTC()
}
}
return time.Time{}
}
+168
View File
@@ -0,0 +1,168 @@
package versionhistory
import (
"context"
"os"
"os/exec"
"strings"
"testing"
"time"
)
// 真实仓库的只读同步用例:**匿名抓取**内部可达的 Gitea,并把算出的版本号与本地 git 交叉核对
// (`git rev-list --count v0.1.0..<sha>`)—— 两套实现(Go 图遍历 vs git)必须给出同一个号。
//
// 未设 VERSION_HISTORY_LIVE_BASE_URL 即按设计 SKIP(已在 scripts/test-scope.json 声明理由);
// 本用例**不读任何凭据**、只读远端仓库,不写任何东西。
func TestLiveSyncAgainstRealRepository(t *testing.T) {
base := strings.TrimSpace(os.Getenv("VERSION_HISTORY_LIVE_BASE_URL"))
if base == "" {
t.Skip("VERSION_HISTORY_LIVE_BASE_URL 未设置:跳过真实仓库的只读同步用例")
}
if _, err := exec.LookPath("git"); err != nil {
t.Skip("本地没有 git:无法与 git 交叉核对")
}
repo := strings.TrimSpace(os.Getenv("VERSION_HISTORY_LIVE_REPO"))
if repo == "" {
repo = "Weknora/knowledge-governance"
}
client, err := NewGiteaClient(GiteaConfig{BaseURL: base, AllowedBaseURLs: []string{base}, Repo: repo})
if err != nil {
t.Fatalf("构造只读客户端:%v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
defer cancel()
commits, total := []RawCommit{}, 0
for page := 1; page <= 10; page++ {
pageCommits, pageTotal, err := client.ListCommits(ctx, page, 50)
if err != nil {
t.Fatalf("第 %d 页抓取失败:%v", page, err)
}
if pageTotal > 0 {
total = pageTotal
}
commits = append(commits, pageCommits...)
if len(pageCommits) < 50 {
break
}
}
seen := map[string]bool{}
for _, commit := range commits {
if seen[commit.SHA] {
t.Fatalf("分页出现重复提交 %s", commit.SHA)
}
seen[commit.SHA] = true
}
if total == 0 || len(commits) != total {
t.Fatalf("分页与 X-Total-Count 不一致:抓到 %d,远端宣称 %d", len(commits), total)
}
tags, err := client.ListTags(ctx)
if err != nil {
t.Fatalf("读 tag:%v", err)
}
// 与本地 git 交叉核对:注释 tag 指向的提交必须与 `git rev-parse` 一致
var releaseTag RawTag
foundRelease := false
for _, tag := range tags {
if tag.Name == "v0.1.0" {
releaseTag, foundRelease = tag, true
}
}
if !foundRelease || !releaseTag.Annotated {
t.Fatalf("真实仓库里应有注释 tag v0.1.0,实际:%+v", tags)
}
if local := localGit(t, "rev-parse", "v0.1.0^{commit}"); local != releaseTag.TargetSHA {
t.Fatalf("tag 目标与本地 git 不一致:接口 %s,本地 %s", releaseTag.TargetSHA, local)
}
derived := DeriveVersions(DeriveInput{RepoKey: repo, CommitURLBase: client.CommitURLBase(),
Commits: commits, Tags: tags,
Changelog: func(sha string) (string, error) { return client.ReadFile(ctx, sha, "CHANGELOG.md") }})
if !derived.GraphComplete {
t.Fatalf("真实仓库的提交图应当完整,缺父提交 %v", derived.MissingParents)
}
releases, development, historical := 0, 0, 0
for _, record := range derived.Records {
switch record.RecordKind {
case "release":
releases++
if record.CommitSHA == releaseTag.TargetSHA {
if record.VersionLabel != "0.1.0" || record.ReleaseNotes == "" {
t.Fatalf("正式版本记录不完整:%+v", record)
}
}
case "development":
development++
case "historical":
historical++
if record.VersionLabel != "" {
t.Fatalf("历史提交不许有版本号:%+v", record)
}
}
}
if releases != 1 {
t.Fatalf("正式版本条数 = %d,期望 1(只有 v0.1.0)", releases)
}
// 交叉核对开发号:Go 的图遍历 vs 本地 git 的 rev-list --count
checked := 0
for _, record := range derived.Records {
if record.RecordKind != "development" || checked >= 8 {
continue
}
if _, err := exec.Command("git", "cat-file", "-e", record.CommitSHA).Output(); err != nil {
continue // 本地没有这个提交(远端有新提交)⇒ 跳过交叉核对
}
count := localGit(t, "rev-list", "--count", "v0.1.0.."+record.CommitSHA)
want := "0.1." + count
if record.VersionLabel != want {
t.Fatalf("提交 %s 的号 = %q,git 算出来是 %q", record.CommitSHA[:12], record.VersionLabel, want)
}
checked++
}
if checked == 0 {
t.Fatal("没有交叉核对任何开发号 —— 证据不足")
}
head := derived.Records[0]
t.Logf("真实仓库 %s:远端 main 可达 %d 条提交(对账一致)|正式 %d|开发 %d|历史 %d|tag %d 个(注释 %v 个)",
repo, len(commits), releases, development, historical, len(tags), countAnnotated(tags))
for index, record := range derived.Records {
if index >= 6 {
break
}
label := record.VersionLabel
if label == "" {
label = "历史提交 · " + record.CommitSHA[:12]
}
t.Logf(" %s|%s|%s|%s", label, record.CommitSHA[:12], record.RecordKind, record.Subject)
}
if head.VersionLabel == "" && head.RecordKind != "historical" {
t.Fatalf("HEAD 记录异常:%+v", head)
}
if want := "0.1." + localGit(t, "rev-list", "--count", "v0.1.0.."+head.CommitSHA); head.VersionLabel != want {
t.Fatalf("HEAD 的号 = %q,git 算出来是 %q", head.VersionLabel, want)
}
}
func countAnnotated(tags []RawTag) int {
annotated := 0
for _, tag := range tags {
if tag.Annotated {
annotated++
}
}
return annotated
}
func localGit(t *testing.T, args ...string) string {
t.Helper()
output, err := exec.Command("git", args...).Output()
if err != nil {
t.Fatalf("本地 git %s 失败:%v", strings.Join(args, " "), err)
}
return strings.TrimSpace(string(output))
}
+208
View File
@@ -0,0 +1,208 @@
// Package versionhistory 把「远端 main 可达的提交」+「tag 证据」+「提交内 CHANGELOG」
// 换算成版本记录页要的提交记录。
//
// 它**只读、纯计算**:不发网络请求、不写库、不执行任何历史提交里的脚本。版本号口径
// 委托给 internal/governance.DecideVersion,提交数按提交图算(等价 `git rev-list --count <tag>..<sha>`),
// 与 scripts/version.py 同规则 —— 两处算出的号必须一致。
package versionhistory
import (
"sort"
"time"
"knowledge-governance/internal/governance"
)
// RawCommit 是一条从 Gitea 读回的提交(只保留展示与判版本所需的字段)。
type RawCommit struct {
SHA string
Parents []string
CommittedAt time.Time
AuthorDisplay string
Subject string
Body string
}
// RawTag 是一个 tag 及其可核验属性;Annotated=false 表示轻量 tag(不算正式版本的证据)。
type RawTag struct {
Name string
TagSHA string
TargetSHA string
Annotated bool
}
// ChangelogSource 读「某个提交内的 CHANGELOG.md」;读不到返回错误(调用方按"无记录"处理)。
type ChangelogSource func(sha string) (string, error)
// DeriveInput 是一次换算的全部输入。
type DeriveInput struct {
RepoKey string
CommitURLBase string // 形如 "<origin>/<owner>/<repo>/commit/",由配置拼好,不接受外部传入
TagURLBase string // 形如 "<origin>/<owner>/<repo>/src/tag/";空则不下发 tag 链接
Commits []RawCommit
Tags []RawTag
Changelog ChangelogSource
SnapshotID int64
}
// DeriveResult 是换算结果。
type DeriveResult struct {
Records []governance.VersionHistoryCommit
GraphComplete bool
MissingParents []string
}
// DeriveVersions 逐提交判定版本号(含合并提交与侧分支提交;不展示任何未推送的本地提交,
// 因为输入本身就是远端 main 可达集合)。
func DeriveVersions(in DeriveInput) DeriveResult {
bySHA := make(map[string]RawCommit, len(in.Commits))
for _, commit := range in.Commits {
bySHA[commit.SHA] = commit
}
missing := map[string]bool{}
ancestors := make(map[string]map[string]struct{}, len(in.Commits))
var walk func(sha string) map[string]struct{}
walk = func(sha string) map[string]struct{} {
if set, ok := ancestors[sha]; ok {
return set
}
set := map[string]struct{}{sha: {}}
ancestors[sha] = set // 先占位,DAG 不会有环
commit, ok := bySHA[sha]
if !ok {
return set
}
for _, parent := range commit.Parents {
if _, known := bySHA[parent]; !known {
missing[parent] = true
continue
}
for item := range walk(parent) {
set[item] = struct{}{}
}
}
return set
}
for _, commit := range in.Commits {
walk(commit.SHA)
}
tagsByTarget := map[string][]RawTag{}
tagByName := map[string]RawTag{}
for _, tag := range in.Tags {
tagsByTarget[tag.TargetSHA] = append(tagsByTarget[tag.TargetSHA], tag)
if _, exists := tagByName[tag.Name]; !exists {
tagByName[tag.Name] = tag
}
}
changelogCache := map[string]string{}
readChangelog := func(sha string) string {
if text, ok := changelogCache[sha]; ok {
return text
}
text := ""
if in.Changelog != nil {
if loaded, err := in.Changelog(sha); err == nil {
text = loaded
}
}
changelogCache[sha] = text
return text
}
graphComplete := len(missing) == 0
result := DeriveResult{GraphComplete: graphComplete}
for sha := range missing {
result.MissingParents = append(result.MissingParents, sha)
}
sort.Strings(result.MissingParents)
records := make([]governance.VersionHistoryCommit, 0, len(in.Commits))
for _, commit := range in.Commits {
changelog := readChangelog(commit.SHA)
top := governance.ChangelogTopVersion(changelog)
baseTagName := ""
var sinceBase *int
tagCreatedLater := false
if governance.SemverValid(top) {
candidate := "v" + top
if base, exists := tagByName[candidate]; exists {
own, ownKnown := ancestors[commit.SHA]
_, tagIsAncestor := own[base.TargetSHA]
switch {
case !graphComplete:
// tag 存在但图不完整 ⇒ 不给号(宁可没号,也不报错号)
baseTagName = candidate
case !ownKnown:
// 连自己的祖先都给不出 ⇒ 不给号
case !tagIsAncestor:
// **该 tag 是更晚才打在这个提交之后的**:这个提交当时还没有发布基线。
// (提交数在这里算会得到 0 —— 因为它的祖先全被那个更晚的 tag 覆盖 —— 拿它编号是错的。)
tagCreatedLater = true
default:
baseSet := ancestors[base.TargetSHA]
count := 0
for item := range own {
if _, inBase := baseSet[item]; !inBase {
count++
}
}
baseTagName = candidate
sinceBase = &count
}
}
}
evidenceTags := make([]governance.VersionTagEvidence, 0, len(tagsByTarget[commit.SHA]))
for _, tag := range tagsByTarget[commit.SHA] {
url := ""
if in.TagURLBase != "" {
url = in.TagURLBase + tag.Name
}
evidenceTags = append(evidenceTags, governance.VersionTagEvidence{
Name: tag.Name, TagSHA: tag.TagSHA, Annotated: tag.Annotated, URL: url})
}
sort.Slice(evidenceTags, func(i, j int) bool { return evidenceTags[i].Name < evidenceTags[j].Name })
label, state, kind, evidence := governance.DecideVersion(top, evidenceTags, baseTagName, sinceBase)
switch {
case label != "":
case !graphComplete:
evidence.Reason = governance.ReasonIncompleteGraph
case tagCreatedLater:
evidence.Reason = governance.ReasonTagCreatedLater
}
record := governance.VersionHistoryCommit{
RepoKey: in.RepoKey,
CommitSHA: commit.SHA,
Parents: commit.Parents,
CommittedAt: commit.CommittedAt,
AuthorDisplay: commit.AuthorDisplay,
Subject: commit.Subject,
Body: commit.Body,
VersionLabel: label,
VersionState: state,
RecordKind: kind,
ReleaseTags: evidenceTags,
CommitURL: in.CommitURLBase + commit.SHA,
VersionEvidence: evidence,
SnapshotID: in.SnapshotID,
}
if kind == governance.RecordKindRelease {
record.ReleaseNotes = governance.ExtractReleaseNotes(changelog, label)
}
records = append(records, record)
}
// 最新在上;同一提交时间用 SHA 兜底 ⇒ 排序确定,分页不重不漏。
sort.SliceStable(records, func(i, j int) bool {
if !records[i].CommittedAt.Equal(records[j].CommittedAt) {
return records[i].CommittedAt.After(records[j].CommittedAt)
}
return records[i].CommitSHA > records[j].CommitSHA
})
result.Records = records
return result
}
+262
View File
@@ -0,0 +1,262 @@
package versionhistory
import (
"testing"
"time"
"knowledge-governance/internal/governance"
)
func at(minute int) time.Time {
return time.Date(2026, 10, 13, 10, minute, 0, 0, time.UTC)
}
func commit(sha string, parents []string, minute int) RawCommit {
return RawCommit{SHA: sha, Parents: parents, CommittedAt: at(minute),
AuthorDisplay: "姚章浩", Subject: "feat: " + sha, Body: "body " + sha}
}
func changelogWith(top string) string {
if top == "" {
return "# Changelog\n\n## [Unreleased]\n\n### Added\n\n- 早期提交,还没有已发布版本\n"
}
return "# Changelog\n\n## [Unreleased]\n\n### Added\n\n- 新\n\n" +
"## [" + top + "] - 2026-10-01\n\n### Added\n\n- 首次发布\n"
}
func readerFor(topBySHA map[string]string) ChangelogSource {
return func(sha string) (string, error) { return changelogWith(topBySHA[sha]), nil }
}
func find(t *testing.T, records []governance.VersionHistoryCommit, sha string) governance.VersionHistoryCommit {
t.Helper()
for _, record := range records {
if record.CommitSHA == sha {
return record
}
}
t.Fatalf("记录里没有提交 %s", sha)
return governance.VersionHistoryCommit{}
}
func TestDeriveVersionsLinearHistoryWithAnnotatedTag(t *testing.T) {
commits := []RawCommit{
commit("A", nil, 1), commit("B", []string{"A"}, 2),
commit("C", []string{"B"}, 3), commit("D", []string{"C"}, 4),
}
tags := []RawTag{{Name: "v0.1.0", TagSHA: "tagobj", TargetSHA: "A", Annotated: true}}
top := map[string]string{"A": "0.1.0", "B": "0.1.0", "C": "0.1.0", "D": "0.1.0"}
result := DeriveVersions(DeriveInput{RepoKey: "Weknora/knowledge-governance",
CommitURLBase: "http://gitea/commit/", Commits: commits, Tags: tags, Changelog: readerFor(top)})
if !result.GraphComplete {
t.Fatal("线性历史应判为图完整")
}
if len(result.Records) != 4 {
t.Fatalf("记录数 = %d,期望 4", len(result.Records))
}
// 最新在上
if result.Records[0].CommitSHA != "D" || result.Records[3].CommitSHA != "A" {
t.Fatalf("排序不对:%s…%s", result.Records[0].CommitSHA, result.Records[3].CommitSHA)
}
for sha, want := range map[string]string{"A": "0.1.0", "B": "0.1.1", "C": "0.1.2", "D": "0.1.3"} {
record := find(t, result.Records, sha)
if record.VersionLabel != want {
t.Fatalf("%s 的号 = %q,期望 %q(原因 %s)", sha, record.VersionLabel, want, record.VersionEvidence.Reason)
}
if record.CommitURL != "http://gitea/commit/"+sha {
t.Fatalf("%s 的提交链接 = %q", sha, record.CommitURL)
}
}
release := find(t, result.Records, "A")
if release.RecordKind != governance.RecordKindRelease || release.VersionState != governance.VersionStateVerified {
t.Fatalf("tag 指向的提交应是正式版本:%+v", release)
}
if release.ReleaseNotes == "" || len(release.ReleaseTags) != 1 {
t.Fatalf("正式版本必须带 tag 与提交内 CHANGELOG 正文:%+v", release)
}
development := find(t, result.Records, "B")
if development.RecordKind != governance.RecordKindDevelopment || development.ReleaseNotes != "" {
t.Fatalf("开发提交不该带发布正文:%+v", development)
}
}
func TestDeriveVersionsKeepsMergeAndSideBranchCommitsAndSameNumberDifferentSHA(t *testing.T) {
commits := []RawCommit{
commit("A", nil, 1), commit("B", []string{"A"}, 2), commit("C", []string{"A"}, 3),
commit("M", []string{"B", "C"}, 4), commit("D", []string{"M"}, 5),
}
tags := []RawTag{{Name: "v0.1.0", TargetSHA: "A", Annotated: true}}
top := map[string]string{"A": "0.1.0", "B": "0.1.0", "C": "0.1.0", "M": "0.1.0", "D": "0.1.0"}
result := DeriveVersions(DeriveInput{RepoKey: "repo", Commits: commits, Tags: tags, Changelog: readerFor(top)})
for _, sha := range []string{"B", "C", "M", "D"} {
if record := find(t, result.Records, sha); record.VersionLabel == "" {
t.Fatalf("合并/侧分支提交 %s 必须能查到:%+v", sha, record)
}
}
if merge := find(t, result.Records, "M"); len(merge.Parents) != 2 || merge.VersionLabel != "0.1.3" {
t.Fatalf("合并提交应保留双父并按图算号:%+v", merge)
}
if side := find(t, result.Records, "C"); side.VersionLabel != "0.1.1" {
t.Fatalf("侧分支提交按同一基线算:%+v", side)
}
// 同号不同 SHA:B 与 C 都是 0.1.1,两条都要在(唯一身份是 SHA)
same := 0
for _, record := range result.Records {
if record.VersionLabel == "0.1.1" {
same++
}
}
if same != 2 {
t.Fatalf("同号不同 SHA 应保留两条,实际 %d", same)
}
if find(t, result.Records, "B").CommitSHA == find(t, result.Records, "C").CommitSHA {
t.Fatal("同号两条必须靠 SHA 区分")
}
}
func TestDeriveVersionsIncompleteGraphNeverInventsNumbers(t *testing.T) {
// 只拿到 B、C,父提交 A 不在集合里(等价浅克隆/检出截断)
commits := []RawCommit{commit("B", []string{"A"}, 2), commit("C", []string{"B"}, 3)}
tags := []RawTag{{Name: "v0.1.0", TargetSHA: "A", Annotated: true}}
top := map[string]string{"B": "0.1.0", "C": "0.1.0"}
result := DeriveVersions(DeriveInput{RepoKey: "repo", Commits: commits, Tags: tags, Changelog: readerFor(top)})
if result.GraphComplete {
t.Fatal("缺父提交必须判为图不完整")
}
if len(result.MissingParents) != 1 || result.MissingParents[0] != "A" {
t.Fatalf("缺失父提交 = %v", result.MissingParents)
}
for _, record := range result.Records {
if record.VersionLabel != "" {
t.Fatalf("图不完整时不许给号:%+v", record)
}
if record.VersionEvidence.Reason != governance.ReasonIncompleteGraph {
t.Fatalf("原因码应为 %s,得到 %s", governance.ReasonIncompleteGraph, record.VersionEvidence.Reason)
}
if record.RecordKind != governance.RecordKindHistorical {
t.Fatalf("应为历史提交:%+v", record)
}
}
}
func TestDeriveVersionsLightweightTagIsNotARelease(t *testing.T) {
commits := []RawCommit{commit("A", nil, 1)}
tags := []RawTag{{Name: "v0.1.0", TargetSHA: "A", Annotated: false}} // 轻量 tag
result := DeriveVersions(DeriveInput{RepoKey: "repo", Commits: commits, Tags: tags,
Changelog: readerFor(map[string]string{"A": "0.1.0"})})
record := find(t, result.Records, "A")
if record.RecordKind == governance.RecordKindRelease {
t.Fatalf("轻量 tag 不得标成正式版本:%+v", record)
}
if len(record.ReleaseTags) != 1 || record.ReleaseTags[0].Annotated {
t.Fatalf("tag 证据要原样保留:%+v", record.ReleaseTags)
}
}
func TestDeriveVersionsPicksUpTagAddedAfterwards(t *testing.T) {
commits := []RawCommit{commit("A", nil, 1), commit("B", []string{"A"}, 2)}
changelog := readerFor(map[string]string{"A": "0.1.0", "B": "0.1.0"})
before := DeriveVersions(DeriveInput{RepoKey: "repo", Commits: commits, Changelog: changelog})
if find(t, before.Records, "B").RecordKind != governance.RecordKindHistorical {
t.Fatalf("还没有 tag 时 B 只能是历史提交:%+v", find(t, before.Records, "B"))
}
// 旧提交后补的注释 tag:再算一次就该升级成正式版本相关记录(不新增第二行)
after := DeriveVersions(DeriveInput{RepoKey: "repo", Commits: commits, Changelog: changelog,
Tags: []RawTag{{Name: "v0.1.0", TargetSHA: "A", Annotated: true}}})
if find(t, after.Records, "A").RecordKind != governance.RecordKindRelease {
t.Fatalf("后补的注释 tag 必须让 A 变成正式版本:%+v", find(t, after.Records, "A"))
}
if len(after.Records) != len(before.Records) {
t.Fatalf("后补 tag 不得新增记录:%d → %d", len(before.Records), len(after.Records))
}
if find(t, after.Records, "B").VersionLabel != "0.1.1" {
t.Fatalf("B 应拿到开发号:%+v", find(t, after.Records, "B"))
}
}
func TestDeriveVersionsFillsTagLinksForHumans(t *testing.T) {
commits := []RawCommit{commit("A", nil, 1)}
tags := []RawTag{{Name: "v0.1.0", TargetSHA: "A", Annotated: true}}
derived := DeriveVersions(DeriveInput{RepoKey: "repo", Commits: commits, Tags: tags,
CommitURLBase: "https://gitea.example/o/r/commit/",
TagURLBase: "https://gitea.example/o/r/src/tag/",
Changelog: readerFor(map[string]string{"A": "0.1.0"})})
record := find(t, derived.Records, "A")
if len(record.ReleaseTags) != 1 || record.ReleaseTags[0].URL != "https://gitea.example/o/r/src/tag/v0.1.0" {
t.Fatalf("tag 必须带可点的链接:%+v", record.ReleaseTags)
}
// 不给 TagURLBase ⇒ 不下发链接(页面据此不渲染空的 tag 链接)
bare := DeriveVersions(DeriveInput{RepoKey: "repo", Commits: commits, Tags: tags,
Changelog: readerFor(map[string]string{"A": "0.1.0"})})
if url := find(t, bare.Records, "A").ReleaseTags[0].URL; url != "" {
t.Fatalf("没有基址时不该编链接:%q", url)
}
}
func TestDeriveVersionsSortsDeterministicallyForPaging(t *testing.T) {
sameTime := at(9)
commits := []RawCommit{
{SHA: "aaa", CommittedAt: sameTime}, {SHA: "bbb", CommittedAt: sameTime},
{SHA: "ccc", CommittedAt: sameTime}, {SHA: "ddd", CommittedAt: sameTime},
}
result := DeriveVersions(DeriveInput{RepoKey: "repo", Commits: commits})
order := []string{result.Records[0].CommitSHA, result.Records[1].CommitSHA,
result.Records[2].CommitSHA, result.Records[3].CommitSHA}
want := []string{"ddd", "ccc", "bbb", "aaa"}
for i := range want {
if order[i] != want[i] {
t.Fatalf("同一提交时间的排序必须确定:%v", order)
}
}
}
// 回归用例(真实数据发现):tag **更晚**才在链尾打上时,tag 之前那些「提交内 CHANGELOG 顶部
// 已经写着 0.1.0」的提交**不能**被算成 0.1.0 开发版 —— 它们的祖先集合全被那个更晚的 tag 覆盖,
// 按提交数会得到 0。正确结果:历史提交 + 原因 release_tag_created_later。
func TestDeriveVersionsDoesNotNumberCommitsThatPredateTheTag(t *testing.T) {
commits := []RawCommit{
commit("A", nil, 1), commit("B", []string{"A"}, 2),
commit("C", []string{"B"}, 3), commit("D", []string{"C"}, 4),
}
// tag 打在 C 上;A、B 的 CHANGELOG 顶部**也已经**是 0.1.0(旧分支遗留的条目)
tags := []RawTag{{Name: "v0.1.0", TargetSHA: "C", Annotated: true}}
top := map[string]string{"A": "0.1.0", "B": "0.1.0", "C": "0.1.0", "D": "0.1.0"}
result := DeriveVersions(DeriveInput{RepoKey: "repo", Commits: commits, Tags: tags, Changelog: readerFor(top)})
for _, sha := range []string{"A", "B"} {
record := find(t, result.Records, sha)
if record.VersionLabel != "" || record.RecordKind != governance.RecordKindHistorical {
t.Fatalf("tag 之前的提交 %s 不许编号:%+v", sha, record)
}
if record.VersionEvidence.Reason != governance.ReasonTagCreatedLater {
t.Fatalf("提交 %s 的原因码 = %q,期望 %q", sha, record.VersionEvidence.Reason, governance.ReasonTagCreatedLater)
}
}
if release := find(t, result.Records, "C"); release.RecordKind != governance.RecordKindRelease || release.VersionLabel != "0.1.0" {
t.Fatalf("tag 指向的提交才是正式版本:%+v", release)
}
if after := find(t, result.Records, "D"); after.VersionLabel != "0.1.1" {
t.Fatalf("tag 之后的提交才是开发号:%+v", after)
}
}
// 侧分支(不含 tag 的那条线)同样不给号。
func TestDeriveVersionsSideBranchWithoutTagStaysHistorical(t *testing.T) {
commits := []RawCommit{
commit("A", nil, 1), commit("B", []string{"A"}, 2), commit("T", []string{"B"}, 3),
commit("S", []string{"A"}, 4), // 从 A 分出去、不含 tag 的侧分支
commit("M", []string{"T", "S"}, 5), // 合并回主干
}
tags := []RawTag{{Name: "v0.1.0", TargetSHA: "T", Annotated: true}}
top := map[string]string{"A": "0.1.0", "B": "0.1.0", "T": "0.1.0", "S": "0.1.0", "M": "0.1.0"}
result := DeriveVersions(DeriveInput{RepoKey: "repo", Commits: commits, Tags: tags, Changelog: readerFor(top)})
if side := find(t, result.Records, "S"); side.VersionLabel != "" {
t.Fatalf("不含 tag 的侧分支提交不许编号:%+v", side)
}
if merge := find(t, result.Records, "M"); merge.VersionLabel != "0.1.2" {
t.Fatalf("合并提交含 tag 祖先 ⇒ 按图算号:%+v", merge)
}
}
+282
View File
@@ -0,0 +1,282 @@
package versionhistory
import (
"context"
"errors"
"fmt"
"sort"
"strings"
"time"
"knowledge-governance/internal/governance"
)
// 同步作业的错误码:页面与同步记录直接展示,**不暴露内部细节**。
const (
ErrorCodeUnreachable = "gitea_unreachable"
ErrorCodeStatus = "gitea_status"
ErrorCodeTooLarge = "gitea_response_too_large"
ErrorCodeNotFound = "gitea_not_found"
ErrorCodeParse = "gitea_parse"
ErrorCodeRedirect = "gitea_redirect"
ErrorCodeCountMismatch = "count_mismatch"
ErrorCodeIncompletePages = "incomplete_history"
ErrorCodeUnexpected = "unexpected"
)
// ErrorKind 是客户端错误的机器可读类别(同步器据此给 error_code,不去猜字符串)。
type ErrorKind string
const (
KindUnreachable ErrorKind = "unreachable"
KindStatus ErrorKind = "status"
KindTooLarge ErrorKind = "too_large"
KindNotFound ErrorKind = "not_found"
KindParse ErrorKind = "parse"
KindRedirect ErrorKind = "redirect"
)
// GiteaError 携带类别与 HTTP 状态码。
type GiteaError struct {
Kind ErrorKind
Status int
Message string
Wrapped error
}
func (e *GiteaError) Error() string {
if e.Status > 0 {
return fmt.Sprintf("%s(HTTP %d)", e.Message, e.Status)
}
return e.Message
}
func (e *GiteaError) Unwrap() error { return e.Wrapped }
func newGiteaError(kind ErrorKind, status int, message string, wrapped error) *GiteaError {
return &GiteaError{Kind: kind, Status: status, Message: message, Wrapped: wrapped}
}
// errorCode 把任意错误翻成同步错误码;未识别的错误归为 unexpected(不静默吞掉)。
func errorCode(err error) string {
var gitea *GiteaError
if errors.As(err, &gitea) {
switch gitea.Kind {
case KindUnreachable:
return ErrorCodeUnreachable
case KindStatus:
if gitea.Status > 0 {
return fmt.Sprintf("%s_%d", ErrorCodeStatus, gitea.Status)
}
return ErrorCodeStatus
case KindTooLarge:
return ErrorCodeTooLarge
case KindNotFound:
return ErrorCodeNotFound
case KindParse:
return ErrorCodeParse
case KindRedirect:
return ErrorCodeRedirect
}
}
var typed interface{ ErrorCode() string }
if errors.As(err, &typed) {
return typed.ErrorCode()
}
return ErrorCodeUnexpected
}
// codeError 让同步器自己的失败也带机器可读码。
type codeError struct {
code string
message string
}
func (e codeError) Error() string { return e.message }
func (e codeError) ErrorCode() string { return e.code }
// JobType 是同步作业的类型名:HTTP 侧入队与 worker 侧注册必须用同一个值。
const JobType = "versionhistory.sync"
// Source 是版本记录同步需要的只读数据源。
type Source interface {
PageSize() int
CommitURLBase() string
ListCommits(ctx context.Context, page, limit int) ([]RawCommit, int, error)
ListTags(ctx context.Context) ([]RawTag, error)
// TagURLBase 是 tag 链接的基址(给人看的 origin,可能与抓取 origin 不同)。
TagURLBase() string
ReadFile(ctx context.Context, sha, path string) (string, error)
// BranchHeadSHA 读分支 HEAD;读不到不算致命(退回"提交列表里最新的那条")。
BranchHeadSHA(ctx context.Context, branch string) (string, error)
}
// SyncStore 是同步器需要的持久化能力。
type SyncStore interface {
BeginVersionHistorySync(ctx context.Context, repoKey, jobID, triggeredBy string, now time.Time) (int64, error)
SaveVersionHistorySnapshot(ctx context.Context, snapshotID int64, repoKey string,
records []governance.VersionHistoryCommit, expected int, complete bool, now time.Time) error
FinishVersionHistorySync(ctx context.Context, runID int64, outcome SyncOutcome, now time.Time) error
FailVersionHistorySync(ctx context.Context, runID int64, errorCode string, now time.Time) error
}
// SyncOutcome 是一次成功同步的结果(「同步成功」与「历史完整」分开表达)。
type SyncOutcome struct {
SourceHeadSHA string
FetchedCount int
ExpectedCount int
Complete bool
}
// SyncerConfig 装配同步器。
type SyncerConfig struct {
Source Source
Store SyncStore
RepoKey string
Changelog string // 提交内的变更记录文件路径,默认 CHANGELOG.md
Now func() time.Time
MaxPages int
}
// Syncer 抓取远端 main 可达的全部提交并换算版本记录。
type Syncer struct {
source Source
store SyncStore
repoKey string
changelog string
now func() time.Time
maxPages int
}
const syncerDefaultMaxPages = 200
// NewSyncer 校验依赖;缺一即拒绝装配(不允许"半接线"跑起来)。
func NewSyncer(config SyncerConfig) (*Syncer, error) {
if config.Source == nil || config.Store == nil {
return nil, errors.New("版本记录同步器:数据源与存储都必需")
}
if strings.TrimSpace(config.RepoKey) == "" {
return nil, errors.New("版本记录同步器:仓库标识必需")
}
changelog := config.Changelog
if changelog == "" {
changelog = "CHANGELOG.md"
}
now := config.Now
if now == nil {
now = time.Now
}
maxPages := config.MaxPages
if maxPages <= 0 {
maxPages = syncerDefaultMaxPages
}
return &Syncer{source: config.Source, store: config.Store, repoKey: config.RepoKey,
changelog: changelog, now: now, maxPages: maxPages}, nil
}
// Sync 跑一次同步。任何失败都会把这次 run 标成 failed 并带上错误码;
// **失败绝不切换对外快照**,页面继续看上一次成功的数据。
func (s *Syncer) Sync(ctx context.Context, jobID, triggeredBy string) (governance.VersionHistorySyncRun, error) {
now := s.now().UTC()
runID, err := s.store.BeginVersionHistorySync(ctx, s.repoKey, jobID, triggeredBy, now)
if err != nil {
return governance.VersionHistorySyncRun{}, fmt.Errorf("版本记录:开始同步失败:%w", err)
}
fail := func(cause error) (governance.VersionHistorySyncRun, error) {
code := errorCode(cause)
if markErr := s.store.FailVersionHistorySync(ctx, runID, code, s.now().UTC()); markErr != nil {
return governance.VersionHistorySyncRun{}, fmt.Errorf("版本记录:标记同步失败时又出错:%w", markErr)
}
return governance.VersionHistorySyncRun{ID: runID, Status: "failed", ErrorCode: code},
fmt.Errorf("版本记录:同步失败(%s):%w", code, cause)
}
commits, total, err := s.fetchAllCommits(ctx)
if err != nil {
return fail(err)
}
if total > 0 && len(commits) != total {
return fail(codeError{code: ErrorCodeCountMismatch,
message: fmt.Sprintf("版本记录:提交数与远端宣称不一致(抓到 %d,远端 X-Total-Count=%d)", len(commits), total)})
}
tags, err := s.source.ListTags(ctx)
if err != nil {
return fail(err)
}
derived := DeriveVersions(DeriveInput{RepoKey: s.repoKey, CommitURLBase: s.source.CommitURLBase(),
TagURLBase: s.source.TagURLBase(),
Commits: commits, Tags: tags, SnapshotID: runID,
Changelog: func(sha string) (string, error) {
return s.source.ReadFile(ctx, sha, s.changelog)
}})
if err := s.store.SaveVersionHistorySnapshot(ctx, runID, s.repoKey, derived.Records, total, true, s.now().UTC()); err != nil {
return fail(err)
}
sourceHead := ""
if head, err := s.source.BranchHeadSHA(ctx, "main"); err == nil {
sourceHead = head
} else {
sourceHead = headSHA(commits) // 读分支失败不致命:退回提交列表最新一条
}
outcome := SyncOutcome{SourceHeadSHA: sourceHead, FetchedCount: len(commits),
ExpectedCount: total, Complete: derived.GraphComplete && (total == 0 || len(commits) == total)}
if err := s.store.FinishVersionHistorySync(ctx, runID, outcome, s.now().UTC()); err != nil {
return fail(err)
}
return governance.VersionHistorySyncRun{ID: runID, Status: "completed", SourceHeadSHA: outcome.SourceHeadSHA,
FetchedCount: outcome.FetchedCount, ExpectedCount: &total, Complete: outcome.Complete,
LastSuccessAt: s.now().UTC(), StartedAt: now}, nil
}
// fetchAllCommits 逐页抓取并按 SHA 去重;短页即终止(也防住服务端忽略 page 参数)。
func (s *Syncer) fetchAllCommits(ctx context.Context) ([]RawCommit, int, error) {
pageSize := s.source.PageSize()
if pageSize <= 0 {
pageSize = giteaDefaultPageSize
}
seen := map[string]bool{}
commits := make([]RawCommit, 0, pageSize)
total := 0
for page := 1; page <= s.maxPages; page++ {
pageCommits, pageTotal, err := s.source.ListCommits(ctx, page, pageSize)
if err != nil {
return nil, 0, err
}
if pageTotal > 0 {
total = pageTotal
}
for _, commit := range pageCommits {
if seen[commit.SHA] {
continue
}
seen[commit.SHA] = true
commits = append(commits, commit)
}
if len(pageCommits) < pageSize {
return commits, total, nil
}
if total > 0 && len(commits) >= total {
return commits, total, nil
}
}
return nil, 0, codeError{code: ErrorCodeIncompletePages,
message: fmt.Sprintf("版本记录:分页超过 %d 页仍未取完(疑似服务端分页异常)", s.maxPages)}
}
// headSHA 取远端 main 的 HEAD(提交列表按时间倒序,最新一条即 HEAD;取不到就空)。
func headSHA(commits []RawCommit) string {
sorted := make([]RawCommit, len(commits))
copy(sorted, commits)
sort.Slice(sorted, func(i, j int) bool {
if !sorted[i].CommittedAt.Equal(sorted[j].CommittedAt) {
return sorted[i].CommittedAt.After(sorted[j].CommittedAt)
}
return sorted[i].SHA > sorted[j].SHA
})
if len(sorted) == 0 {
return ""
}
return sorted[0].SHA
}
+255
View File
@@ -0,0 +1,255 @@
package versionhistory
import (
"context"
"fmt"
"strings"
"testing"
"time"
"knowledge-governance/internal/governance"
)
type fakeSource struct {
commits []RawCommit
total int
pageSize int
tags []RawTag
changelog map[string]string
head string
headErr error
commitsErr error
listCalls int
}
func (f *fakeSource) PageSize() int { return f.pageSize }
func (f *fakeSource) CommitURLBase() string {
return "http://gitea.test/Weknora/knowledge-governance/commit/"
}
func (f *fakeSource) TagURLBase() string {
return "http://gitea.test/Weknora/knowledge-governance/src/tag/"
}
func (f *fakeSource) ListCommits(_ context.Context, page, limit int) ([]RawCommit, int, error) {
f.listCalls++
if f.commitsErr != nil {
return nil, 0, f.commitsErr
}
start := (page - 1) * limit
if start >= len(f.commits) {
return nil, f.total, nil
}
end := start + limit
if end > len(f.commits) {
end = len(f.commits)
}
return f.commits[start:end], f.total, nil
}
func (f *fakeSource) ListTags(context.Context) ([]RawTag, error) { return f.tags, nil }
func (f *fakeSource) ReadFile(_ context.Context, sha, _ string) (string, error) {
if text, ok := f.changelog[sha]; ok {
return text, nil
}
return "", fmt.Errorf("no changelog for %s", sha)
}
func (f *fakeSource) BranchHeadSHA(context.Context, string) (string, error) {
if f.headErr != nil {
return "", f.headErr
}
return f.head, nil
}
type savedSnapshot struct {
snapshotID int64
records []governance.VersionHistoryCommit
expected int
complete bool
}
type fakeStore struct {
beginCalls int
beginErr error
saved []savedSnapshot
finished []SyncOutcome
failed []string
activeSnapshot int64
lastSuccess time.Time
saveErr error
}
func (f *fakeStore) BeginVersionHistorySync(_ context.Context, _, _, _ string, _ time.Time) (int64, error) {
f.beginCalls++
if f.beginErr != nil {
return 0, f.beginErr
}
return int64(f.beginCalls), nil
}
func (f *fakeStore) SaveVersionHistorySnapshot(_ context.Context, snapshotID int64, _ string,
records []governance.VersionHistoryCommit, expected int, complete bool, _ time.Time) error {
if f.saveErr != nil {
return f.saveErr
}
f.saved = append(f.saved, savedSnapshot{snapshotID: snapshotID, records: records,
expected: expected, complete: complete})
if complete {
f.activeSnapshot = snapshotID
}
return nil
}
func (f *fakeStore) FinishVersionHistorySync(_ context.Context, _ int64, outcome SyncOutcome, now time.Time) error {
f.finished = append(f.finished, outcome)
f.lastSuccess = now
return nil
}
func (f *fakeStore) FailVersionHistorySync(_ context.Context, _ int64, code string, _ time.Time) error {
f.failed = append(f.failed, code)
return nil
}
func linearCommits(count int) []RawCommit {
commits := make([]RawCommit, 0, count)
for index := 0; index < count; index++ {
sha := fmt.Sprintf("%040x", index+1)
parents := []string{}
if index > 0 {
parents = append(parents, fmt.Sprintf("%040x", index))
}
commits = append(commits, RawCommit{SHA: sha, Parents: parents,
CommittedAt: time.Date(2026, 10, 13, 9, 0, 0, 0, time.UTC).Add(time.Duration(index) * time.Minute),
AuthorDisplay: "姚章浩", Subject: fmt.Sprintf("feat: 第 %d 条", index)})
}
return commits
}
func newTestSyncer(t *testing.T, source Source, store SyncStore) *Syncer {
t.Helper()
syncer, err := NewSyncer(SyncerConfig{Source: source, Store: store, RepoKey: "Weknora/knowledge-governance",
Now: func() time.Time { return time.Date(2026, 10, 13, 12, 0, 0, 0, time.UTC) }})
if err != nil {
t.Fatalf("装配同步器:%v", err)
}
return syncer
}
func TestSyncPullsEveryPageAndReconcilesTotal(t *testing.T) {
commits := linearCommits(111)
source := &fakeSource{commits: commits, total: 111, pageSize: 50, head: commits[110].SHA,
changelog: map[string]string{}}
store := &fakeStore{}
run, err := newTestSyncer(t, source, store).Sync(context.Background(), "job-1", "admin")
if err != nil {
t.Fatalf("同步失败:%v", err)
}
if source.listCalls != 3 {
t.Fatalf("应抓 3 页,实际 %d 次", source.listCalls)
}
if len(store.saved) != 1 || len(store.saved[0].records) != 111 {
t.Fatalf("落库记录数 = %d", len(store.saved[0].records))
}
seen := map[string]bool{}
for _, record := range store.saved[0].records {
if seen[record.CommitSHA] {
t.Fatalf("落库出现重复提交 %s", record.CommitSHA)
}
seen[record.CommitSHA] = true
}
if !run.Complete || run.FetchedCount != 111 || run.SourceHeadSHA != commits[110].SHA {
t.Fatalf("同步结果不完整:%+v", run)
}
if store.activeSnapshot != 1 || len(store.finished) != 1 || len(store.failed) != 0 {
t.Fatalf("快照切换/完成记录不对:%+v", store)
}
}
func TestSyncFailsLoudlyWhenCountDoesNotMatch(t *testing.T) {
commits := linearCommits(100) // 远端宣称 121,实际只给 100
source := &fakeSource{commits: commits, total: 121, pageSize: 50, head: commits[99].SHA}
store := &fakeStore{activeSnapshot: 7}
_, err := newTestSyncer(t, source, store).Sync(context.Background(), "job-2", "admin")
if err == nil {
t.Fatal("数量不一致必须报错,不能宣称完整")
}
if len(store.failed) != 1 || store.failed[0] != ErrorCodeCountMismatch {
t.Fatalf("错误码 = %v,期望 %s", store.failed, ErrorCodeCountMismatch)
}
if len(store.saved) != 0 || store.activeSnapshot != 7 {
t.Fatalf("失败时不得写快照、不得切换对外快照:%+v", store)
}
}
func TestSyncKeepsPreviousSnapshotWhenGiteaIsUnreachable(t *testing.T) {
source := &fakeSource{pageSize: 50, commitsErr: newGiteaError(KindUnreachable, 0, "不可达", nil)}
store := &fakeStore{activeSnapshot: 3, lastSuccess: time.Date(2026, 10, 12, 0, 0, 0, 0, time.UTC)}
_, err := newTestSyncer(t, source, store).Sync(context.Background(), "job-3", "admin")
if err == nil {
t.Fatal("不可达必须报错")
}
if len(store.failed) != 1 || store.failed[0] != ErrorCodeUnreachable {
t.Fatalf("错误码 = %v", store.failed)
}
if store.activeSnapshot != 3 || !store.lastSuccess.Equal(time.Date(2026, 10, 12, 0, 0, 0, 0, time.UTC)) {
t.Fatalf("失败不得动既有快照与最后成功时间:%+v", store)
}
}
func TestSyncIsIdempotentAndPicksUpTagsAddedAfterwards(t *testing.T) {
commits := linearCommits(3)
changelog := map[string]string{}
for _, commit := range commits {
changelog[commit.SHA] = "# Changelog\n\n## [Unreleased]\n\n### Added\n\n- 新\n\n## [0.1.0] - 2026-10-01\n\n### Added\n\n- 首次发布\n"
}
source := &fakeSource{commits: commits, total: 3, pageSize: 50, head: commits[2].SHA, changelog: changelog}
store := &fakeStore{}
syncer := newTestSyncer(t, source, store)
if _, err := syncer.Sync(context.Background(), "job-4", "admin"); err != nil {
t.Fatalf("首次同步:%v", err)
}
first := store.saved[0].records
if len(first) != 3 {
t.Fatalf("记录数 = %d", len(first))
}
// 还没有 tag ⇒ 全都是历史提交(不给号)
for _, record := range first {
if record.VersionLabel != "" || record.RecordKind != governance.RecordKindHistorical {
t.Fatalf("无 tag 时不应给号:%+v", record)
}
}
// 旧提交后补一个注释 tag ⇒ 再同步不新增记录,只把 A 升级成正式版本,B/C 拿到开发号
source.tags = []RawTag{{Name: "v0.1.0", TagSHA: strings.Repeat("a", 40), TargetSHA: commits[0].SHA, Annotated: true}}
if _, err := syncer.Sync(context.Background(), "job-5", "admin"); err != nil {
t.Fatalf("二次同步:%v", err)
}
second := store.saved[1].records
if len(second) != len(first) {
t.Fatalf("后补 tag 不得新增记录:%d → %d", len(first), len(second))
}
bySHA := map[string]governance.VersionHistoryCommit{}
for _, record := range second {
bySHA[record.CommitSHA] = record
}
if got := bySHA[commits[0].SHA]; got.RecordKind != governance.RecordKindRelease || got.VersionLabel != "0.1.0" {
t.Fatalf("tag 指向的提交应升级为正式版本:%+v", got)
}
if got := bySHA[commits[1].SHA]; got.VersionLabel != "0.1.1" || got.RecordKind != governance.RecordKindDevelopment {
t.Fatalf("tag 之后的提交应拿到开发号:%+v", got)
}
if got := bySHA[commits[2].SHA]; got.VersionLabel != "0.1.2" {
t.Fatalf("第二个提交应是 0.1.2:%+v", got)
}
}
func TestSyncerRequiresDependencies(t *testing.T) {
if _, err := NewSyncer(SyncerConfig{RepoKey: "a/b"}); err == nil {
t.Fatal("缺数据源/存储必须拒绝装配")
}
if _, err := NewSyncer(SyncerConfig{Source: &fakeSource{}, Store: &fakeStore{}}); err == nil {
t.Fatal("缺仓库标识必须拒绝装配")
}
}
+77 -1
View File
@@ -9,8 +9,77 @@ echo "=== 1. 打回滚标签 ($TS)"
docker tag knowledge-governance-p1-api:latest "knowledge-governance-p1-api:rollback-$TS" || exit 1
docker tag knowledge-governance-p1-web:latest "knowledge-governance-p1-web:rollback-$TS" || exit 1
echo "=== 1a. 上线前校验 .env 的键值形状(一行一值)"
# 2026-10-14 实测事故:`.env` 最后一行没有结尾换行、又被追加新键 ⇒ 两行粘成一行
# ⇒ VERSION_HISTORY_GITEA_BASE_URL 变成 "http://host:3000VERSION_HISTORY_LINK_ORIGIN=…"
# ⇒ 配置校验按设计拒绝启动 ⇒ api/worker 崩溃重启(平台整体不可用)。
# 这里在**上线前**用形状判定拦住:值里再出现 `KEY=` 或键名不合法,直接拒绝部署。
if [ -f .env ]; then
python3 - <<'ENVCHECK' || exit 1
import pathlib
import re
import sys
problems = []
for number, raw in enumerate(pathlib.Path(".env").read_text(encoding="utf-8").splitlines(), 1):
line = raw.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", key.strip()):
problems.append((number, line, "键名不合法"))
elif re.search(r"[A-Z][A-Z0-9_]{3,}=", value):
# 不能用 \b:粘行处是 "…:3000VERSION_HISTORY_…",数字紧邻字母,没有词边界。
problems.append((number, line, "值里又出现 KEY=(两行粘在一起)"))
if problems:
print("ENV_VALUE_LOOKS_MERGED(.env 有坏值,拒绝上线)")
for number, line, why in problems:
print(f" line {number}: {why}: {line[:120]}")
sys.exit(1)
print(" .env 键值形状 OK")
ENVCHECK
fi
echo "=== 1b. 构建身份(构建期注入:页面「当前运行」只认产物里的完整 SHA 精确匹配)"
# 唯一来源是 scripts/version.py --identity(与 Makefile、CI 同一份规则):不注入 ⇒ 页面只能显示"未知"。
IDENTITY_ARGS=()
while IFS= read -r line; do IDENTITY_ARGS+=("$line"); done < <(python3 scripts/version.py --identity 2>/dev/null | python3 -c '
import json, sys
try:
d = json.load(sys.stdin)
except Exception:
sys.exit(0)
release = d.get("release_version") or ""
count = d.get("commits_since_release")
print("--build-arg=VERSION=" + (release or "dev"))
print("--build-arg=RELEASE_VERSION=" + release)
print("--build-arg=BUILD_KIND=" + (d.get("build_kind") or "development"))
print("--build-arg=COMMITS_SINCE_RELEASE=" + ("" if count is None else str(count)))
print("--build-arg=COMMIT_SHA=" + (d.get("commit_sha") or "unknown"))
print("--build-arg=BUILD_TIME=" + (d.get("built_at") or "unknown"))
')
if [ "${#IDENTITY_ARGS[@]}" -lt 6 ]; then
echo "IDENTITY_UNAVAILABLE"
echo " 取不到构建身份(scripts/version.py --identity 失败)⇒ 拒绝继续:"
echo " 否则构建出来的产物无法被「版本记录」页识别成「当前运行」,只会显示未知。"
exit 1
fi
printf ' %s\n' "${IDENTITY_ARGS[@]}"
echo "=== 1c. 保留上一版构建的静态资源(CDN/浏览器可能还持有旧 index.html)"
# 只保留**当前正在跑的那一版**:旧 index.html 的旧哈希引用仍能取到文件,
# 页面不会因为某个 JS/CSS 404 而空白或"裸奔"。目录只读挂载进 web 容器。
LEGACY_DIR="deploy/legacy-assets"
PREV_WEB_IMAGE=$(docker inspect -f '{{.Image}}' knowledge-governance-p1-web-1 2>/dev/null || true)
mkdir -p "$LEGACY_DIR/assets" && chmod 777 "$LEGACY_DIR" "$LEGACY_DIR/assets"
if [ -n "$PREV_WEB_IMAGE" ]; then
docker run --rm --user 0 --entrypoint sh -v "$PWD/$LEGACY_DIR:/out" "$PREV_WEB_IMAGE" \
-c 'cp -a /usr/share/nginx/html/assets/. /out/assets/ 2>/dev/null || true' >/dev/null 2>&1 || true
echo " LEGACY_ASSETS=$(ls -1 "$LEGACY_DIR/assets" 2>/dev/null | tr '\n' ' ')"
fi
echo "=== 2. 构建 api"
docker build --network host "${PROXY_ARGS[@]}" -f Dockerfile -t knowledge-governance-p1-api:latest . || { echo "API_BUILD_FAILED"; exit 1; }
docker build --network host "${PROXY_ARGS[@]}" "${IDENTITY_ARGS[@]}" -f Dockerfile -t knowledge-governance-p1-api:latest . || { echo "API_BUILD_FAILED"; exit 1; }
echo "=== 3. 构建 web"
docker build --network host "${PROXY_ARGS[@]}" -f Dockerfile.web -t knowledge-governance-p1-web:latest . || { echo "WEB_BUILD_FAILED"; exit 1; }
@@ -47,4 +116,11 @@ echo "=== 7b. 生产门禁状态(重建后必须与预期一致)"
docker exec knowledge-governance-p1-api-1 sh -lc 'for v in PRODUCTION_RELEASE_REQUESTS_ENABLED PRODUCTION_BACKUP_RESTORE_VERIFIED; do eval "val=\$$v"; echo "$v=${val:-<empty>}"; done'
echo "=== 8. 新包"
docker exec knowledge-governance-p1-web-1 sh -lc 'grep -o "index-[A-Za-z0-9_-]*\.js" /usr/share/nginx/html/index.html | head -1'
echo "=== 9. 构建身份是否真的进了产物(页面据此判「当前运行」)"
INJECTED=$(printf '%s\n' "${IDENTITY_ARGS[@]}" | sed -n 's/^--build-arg=COMMIT_SHA=//p')
if docker exec knowledge-governance-p1-api-1 sh -lc "strings /app/api | grep -q '$INJECTED'"; then
echo "INJECTED_COMMIT_SHA=$INJECTED(已进 api 产物)"
else
echo "INJECTION_MISSING(产物里没有 $INJECTED —— 页面会显示当前运行未知)"
fi
echo "DONE"
+5
View File
@@ -53,6 +53,11 @@
"package": "knowledge-governance/internal/version",
"test": "TestReleaseBuildRequiresEvidence",
"reason": "构建身份未注入时按设计 SKIP(本地跑全量测试不该被迫先构建);**它的强制点在 contracts 项**:那里带 -ldflags 跑它并断言真的 PASS、且出现 SKIP 就判红"
},
{
"package": "knowledge-governance/internal/versionhistory",
"test": "TestLiveSyncAgainstRealRepository",
"reason": "真实仓库的只读同步用例需要内部可达的 Gitea(**匿名**,不读凭据);无环境即跳过(补验路径:设 VERSION_HISTORY_LIVE_BASE_URL 后单跑这条)"
}
]
}
+2057 -632
View File
File diff suppressed because it is too large Load Diff
+616 -98
View File
@@ -1,108 +1,626 @@
import { renderToStaticMarkup } from 'react-dom/server'
import { describe,expect,it,vi } from 'vitest'
import { SystemSettingsView, visibleSaveMessage } from './SystemSettings'
import { describe, expect, it, vi } from 'vitest'
import { SystemSettingsView, splitSourceConnections, visibleSaveMessage } from './SystemSettings'
import { AuthContext } from './auth'
import type { MonitorOverview } from './monitor'
import type { CatalogSource } from './sourceCatalog'
import type { UISettings } from './uiSettings'
import type { SourceConnectionListItem } from './sourceConnections'
const monitor:MonitorOverview={mode:'simulation',simulated:true,observed_at:'2026-09-08T12:00:00Z',host:{cpu_percent:42,memory_used_bytes:1,memory_total_bytes:2,disk_used_bytes:1,disk_total_bytes:2,gpu_state:'unknown',gpu_detail:'未接入真实GPU监控',simulated:true},services:[{key:'mineru',name:'MinerU',state:'healthy',detail:'模拟',latency_ms:1,observed_at:'2026-09-08T12:00:00Z',simulated:true}],knowledge_bases:[],health:[{key:'mineru',name:'MinerU',liveness:'up',readiness:'blocked',reason:'服务可达但容量已满(429),暂时不可接单',latency_ms:30,observed_at:'2026-09-08T12:00:00Z',last_success_at:'2026-09-08T11:59:00Z',consecutive_failures:2,configured:true,applicable:true}]}
const sources:CatalogSource[]=[{connection_id:'ding-1',source_type:'dingtalk',name:'公司级技术支持知识库',root_node_id:'root-1',folder_count:1079,file_count:3444,observed_at:'2026-09-09T09:30:32Z',snapshot_only:true,snapshot_status:'ready',last_refresh_duration_ms:0}]
const connections:SourceConnectionListItem[]=[{id:'conn-ding',source_type:'dingtalk',name:'公司级技术支持知识库',enabled:true,schedule_configured:true,health_status:'healthy',item_count:3444,updated_at:'2026-09-09T09:30:32Z',next_refresh_at:'2026-09-12T10:00:00Z'},{id:'conn-man',source_type:'manual',name:'本地手工验收',enabled:false,schedule_configured:false,health_status:'unknown',item_count:5,updated_at:'2026-09-09T09:30:32Z',next_refresh_at:null}]
const settings:UISettings={id:'settings-default',state:'active',document_refresh_seconds:15,resource_refresh_seconds:30,stalled_after_seconds:1800,finalizing_after_seconds:7200,ingestion_concurrency:2,test_weknora_base_url:'',production_weknora_base_url:'',production_tenant_id:'',production_knowledge_base_id:'',updated_by:'system:migration',created_at:'2026-09-10T08:00:00Z',activated_at:'2026-09-10T08:00:00Z',retired_at:null,error_code:''}
const authValue=(role:'admin'|'engineer')=>({identity:{id:`${role}-1`,username:role,display_name:role,role,must_change_password:false},ready:true,login:async()=>null,logout:async()=>{},changePassword:async()=>null,signedOut:0,notifySignedOut:()=>{}})
describe('SystemSettingsView service configuration',()=>{
it('lets an administrator edit exactly the four service fields in the web console',()=>{
const configured:UISettings={...settings,test_weknora_base_url:'https://weknora.test.example',production_weknora_base_url:'https://weknora.prod.example',production_tenant_id:'10000',production_knowledge_base_id:'kb-abc123'}
const view=(role:'admin'|'engineer')=>renderToStaticMarkup(<AuthContext.Provider value={authValue(role)}><SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={configured} productionEnabled={false} routingCapabilities={{internal_enabled:true,external_enabled:true}} loading={false} saving={false} error={null} saveMessage={null} onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} initialSection="services" /></AuthContext.Provider>)
const adminHtml=view('admin')
for(const text of ['测试地址','生产地址','生产 ID','知识库 ID','保存并启用服务配置','https://weknora.test.example','https://weknora.prod.example','10000','kb-abc123','四项留空即表示未配置'])expect(adminHtml).toContain(text)
expect(adminHtml).not.toContain('仅管理员可修改')
// 界面只剩这四项:依赖探活矩阵与对内/对外绑定下拉不再出现在服务配置页。
for(const removed of ['MinerU','Embedding','Redis / MQ','PostgreSQL','测试知识库映射'])expect(adminHtml).not.toContain(removed)
const engineerHtml=view('engineer')
expect(engineerHtml).toContain('仅管理员可修改')
expect(engineerHtml).not.toContain('保存并启用服务配置')
})
const monitor: MonitorOverview = {
mode: 'simulation',
simulated: true,
observed_at: '2026-09-08T12:00:00Z',
host: {
cpu_percent: 42,
memory_used_bytes: 1,
memory_total_bytes: 2,
disk_used_bytes: 1,
disk_total_bytes: 2,
gpu_state: 'unknown',
gpu_detail: '未接入真实GPU监控',
simulated: true,
},
services: [
{
key: 'mineru',
name: 'MinerU',
state: 'healthy',
detail: '模拟',
latency_ms: 1,
observed_at: '2026-09-08T12:00:00Z',
simulated: true,
},
],
knowledge_bases: [],
health: [
{
key: 'mineru',
name: 'MinerU',
liveness: 'up',
readiness: 'blocked',
reason: '服务可达但容量已满(429),暂时不可接单',
latency_ms: 30,
observed_at: '2026-09-08T12:00:00Z',
last_success_at: '2026-09-08T11:59:00Z',
consecutive_failures: 2,
configured: true,
applicable: true,
},
],
}
const sources: CatalogSource[] = [
{
connection_id: 'ding-1',
source_type: 'dingtalk',
name: '公司级技术支持知识库',
root_node_id: 'root-1',
folder_count: 1079,
file_count: 3444,
observed_at: '2026-09-09T09:30:32Z',
snapshot_only: true,
snapshot_status: 'ready',
last_refresh_duration_ms: 0,
},
]
const connections: SourceConnectionListItem[] = [
{
id: 'conn-ding',
source_type: 'dingtalk',
name: '公司级技术支持知识库',
enabled: true,
schedule_configured: true,
health_status: 'healthy',
item_count: 3444,
updated_at: '2026-09-09T09:30:32Z',
next_refresh_at: '2026-09-12T10:00:00Z',
},
{
id: 'conn-man',
source_type: 'manual',
name: '本地手工验收',
enabled: false,
schedule_configured: false,
health_status: 'unknown',
item_count: 5,
updated_at: '2026-09-09T09:30:32Z',
next_refresh_at: null,
},
]
const settings: UISettings = {
id: 'settings-default',
state: 'active',
document_refresh_seconds: 15,
resource_refresh_seconds: 30,
stalled_after_seconds: 1800,
finalizing_after_seconds: 7200,
ingestion_concurrency: 2,
test_weknora_base_url: '',
production_weknora_base_url: '',
production_tenant_id: '',
production_knowledge_base_id: '',
updated_by: 'system:migration',
created_at: '2026-09-10T08:00:00Z',
activated_at: '2026-09-10T08:00:00Z',
retired_at: null,
error_code: '',
}
const authValue = (role: 'admin' | 'engineer') => ({
identity: { id: `${role}-1`, username: role, display_name: role, role, must_change_password: false },
ready: true,
login: async () => null,
logout: async () => {},
changePassword: async () => null,
signedOut: 0,
notifySignedOut: () => {},
})
describe('SystemSettingsView',()=>{
it('separates document-engineer settings from locked administrator and production controls',()=>{
const html=renderToStaticMarkup(<SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={settings} productionEnabled={false} routingCapabilities={{internal_enabled:true,external_enabled:true}} loading={false} saving={false} error={null} saveMessage="刷新与告警参数已验证并启用:文档15秒、资源30秒、停滞30分钟、finalizing 2小时" onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} />)
for(const text of ['系统设置','数据源配置','服务配置','存储与备份','刷新策略','设置服务已启用','当前活动版本','公司级技术支持知识库','钉钉知识库','认证方式','端点与凭据','文档工程师可调整','管理员设置已锁定'])expect(html).toContain(text)
// 需求(2026-10-10):数据源配置不再做文件格式筛选(格式由目录级标注决定)。
for(const removed of ['文件格式筛选','未勾选的一律不取件','保存保留格式','恢复继承上级规则'])expect(html).not.toContain(removed)
// 需求(2026-10-10):新增入口只剩「可加入的来源」勾选,粘贴链接的按钮已下线。
for(const removed of ['+ 新增钉钉知识库','新增钉钉知识库'])expect(html).not.toContain(removed)
const servicesHtml=renderToStaticMarkup(<SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={settings} productionEnabled={false} routingCapabilities={{internal_enabled:true,external_enabled:true}} loading={false} saving={false} error={null} saveMessage={null} onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} initialSection="services" />)
for(const text of ['测试 WeKnora','生产 WeKnora','测试地址','生产地址','生产 ID','知识库 ID'])expect(servicesHtml).toContain(text)
const storageHtml=renderToStaticMarkup(<SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={settings} productionEnabled={false} routingCapabilities={{internal_enabled:true,external_enabled:true}} loading={false} saving={false} error={null} saveMessage={null} onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} initialSection="storage" />)
// 存储与备份分区已换成真实功能(整库逻辑备份的定时计划),静态占位文案不再存在。
expect(storageHtml).toContain('存储与备份')
expect(storageHtml).toContain('正在读取备份计划…')
expect(storageHtml).not.toContain('仅保存凭据引用,不可回读')
const refreshHtml=renderToStaticMarkup(<SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={settings} productionEnabled={false} routingCapabilities={{internal_enabled:true,external_enabled:true}} loading={false} saving={false} error={null} saveMessage="刷新与告警参数已验证并启用:文档15秒、资源30秒、停滞30分钟、finalizing 2小时" onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} initialSection="refresh" />)
for(const text of ['刷新与告警参数已验证并启用','停滞30分钟','finalizing 2小时','文档状态刷新间隔','15秒','解析停滞判定','30分钟','保存并应用刷新与告警参数'])expect(refreshHtml).toContain(text)
expect(visibleSaveMessage('已保存',true)).toBeNull();expect(visibleSaveMessage('已保存',false)).toBe('已保存')
expect(html).not.toContain('本地模拟');expect(html).not.toContain('保存模拟设置')
for(const forbidden of ['DATABASE_URL','RELEASE_CONFIG_FILE','API Key明文','secret_ref'])expect(html).not.toContain(forbidden)
// 两个环境卡仍由真实探测驱动(依赖矩阵搬到总览页,本页不再渲染)。
expect(servicesHtml).toContain('解析队列 对内 已配置 · 对外 已配置')
expect(servicesHtml).not.toContain('PostgreSQL')
expect(servicesHtml).toContain('端点探测:暂无真实探测结果')
// V1: left-nav section controls, per-source schedule editing, danger modal & history affordances.
expect(html).toContain('settings-nav')
expect(html).toContain('下次自动刷新')
expect(html).toContain('仅手动刷新')
expect(html).toContain('查看修订历史')
expect(html).toContain('保存并启用调度')
expect(html).toContain('停用来源')
expect(html).toContain('本地手工导入来源不支持定时刷新')
// dead buttons removed
expect(html).not.toContain('添加内容源')
expect(html).not.toContain('管理员编辑')
})
it('lets an administrator bind the internal/external import knowledge bases from 系统设置',()=>{
// 组件一直在(RoutingBindingsSection),但从未挂到任何页面 —— 导入目标库只能靠
// 部署 env 钉死,换库必须重建容器。
const view=(section:'sources'|'bindings'|'production-bindings')=>renderToStaticMarkup(<AuthContext.Provider value={authValue('admin')}><SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={settings} productionEnabled={false} routingCapabilities={{internal_enabled:true,external_enabled:true}} loading={false} saving={false} error={null} saveMessage={null} onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} initialSection={section} /></AuthContext.Provider>)
expect(view('sources')).toContain('测试知识库绑定')
expect(view('sources')).toContain('生产知识库绑定')
const bound=view('bindings')
expect(bound).toContain('id="settings-routing-bindings"')
expect(bound).toContain('分发到对应的测试 WeKnora 知识库')
// 未读到绑定数据时(SSR 不跑 effect)面板也要如实存在,而不是空白。
expect(bound).toContain('读取中…')
// 发布目标(源库 → 目标库)是独立分区,与测试端收件库分开。
const target=view('production-bindings')
expect(target).toContain('id="settings-production-bindings"')
expect(target).toContain('新发布的对内 / 对外内容按这里的绑定写入生产 WeKnora 的对应知识库')
describe('SystemSettingsView service configuration', () => {
it('lets an administrator edit exactly the four service fields in the web console', () => {
const configured: UISettings = {
...settings,
test_weknora_base_url: 'https://weknora.test.example',
production_weknora_base_url: 'https://weknora.prod.example',
production_tenant_id: '10000',
production_knowledge_base_id: 'kb-abc123',
}
const view = (role: 'admin' | 'engineer') =>
renderToStaticMarkup(
<AuthContext.Provider value={authValue(role)}>
<SystemSettingsView
sources={sources}
connections={connections}
monitor={monitor}
settings={configured}
productionEnabled={false}
routingCapabilities={{ internal_enabled: true, external_enabled: true }}
loading={false}
saving={false}
error={null}
saveMessage={null}
onSave={vi.fn()}
onSourcesChanged={vi.fn()}
onRefresh={vi.fn()}
initialSection="services"
/>
</AuthContext.Provider>
)
const adminHtml = view('admin')
for (const text of [
'测试地址',
'生产地址',
'生产 ID',
'知识库 ID',
'保存并启用服务配置',
'https://weknora.test.example',
'https://weknora.prod.example',
'10000',
'kb-abc123',
'四项留空即表示未配置',
])
expect(adminHtml).toContain(text)
expect(adminHtml).not.toContain('仅管理员可修改')
// 界面只剩这四项:依赖探活矩阵与对内/对外绑定下拉不再出现在服务配置页。
for (const removed of ['MinerU', 'Embedding', 'Redis / MQ', 'PostgreSQL', '测试知识库映射'])
expect(adminHtml).not.toContain(removed)
const engineerHtml = view('engineer')
expect(engineerHtml).toContain('仅管理员可修改')
expect(engineerHtml).not.toContain('保存并启用服务配置')
})
})
it('does not show healthy simulation when the settings data failed to load',()=>{
const html=renderToStaticMarkup(<SystemSettingsView sources={[]} connections={[]} monitor={null} settings={null} productionEnabled={false} routingCapabilities={{internal_enabled:false,external_enabled:false}} loading={false} saving={false} error="加载失败" saveMessage={null} onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} />)
expect(html).toContain('加载失败');expect(html).not.toContain('模拟运行中')
})
it('renders the WeKnora cards and production channel from live probe and the real production gate',()=>{
const probed:MonitorOverview={...monitor,health:[
{key:'weknora',name:'WeKnora API',liveness:'up',readiness:'ready',reason:'',latency_ms:86,observed_at:'2026-09-08T12:00:00Z',last_success_at:'2026-09-08T11:59:00Z',consecutive_failures:0,configured:true,applicable:true},
{key:'weknora-production',name:'生产 WeKnora',liveness:'up',readiness:'ready',reason:'',latency_ms:41,observed_at:'2026-09-08T12:00:00Z',last_success_at:'2026-09-08T11:59:00Z',consecutive_failures:0,configured:true,applicable:true},
{key:'embedding',name:'Embedding',liveness:'up',readiness:'not_applicable',reason:'未部署:本平台不使用该依赖',latency_ms:0,observed_at:'2026-09-08T12:00:00Z',last_success_at:null,consecutive_failures:0,configured:false,applicable:false}]}
const view=(enabled:boolean,verified:boolean)=>renderToStaticMarkup(<SystemSettingsView sources={sources} connections={connections} monitor={probed} settings={settings} productionEnabled={enabled} productionBackupRestoreVerified={verified} routingCapabilities={{internal_enabled:true,external_enabled:true}} loading={false} saving={false} error={null} saveMessage={null} onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} initialSection="services" />)
const on=view(true,true)
expect(on).toContain('测试 WeKnora')
expect(on).toContain('可达 · 可接单');expect(on).toContain('延迟 86ms')
expect(on).toContain('已启用 · 可提交生产请求');expect(on).toContain('生产写入:开启');expect(on).toContain('发布目标与凭据:管理员受限配置')
const off=view(false,false)
expect(off).toContain('未启用');expect(off).toContain('生产写入:关闭')
// 卡片状态由真实探测/门禁驱动,写死的“已连接 / 未连接 / 生产映射:未配置”必须消失。
for(const removed of ['本地真实连接','生产映射:未配置'])expect(off).not.toContain(removed)
// 生产端点可达性来自真实探活,且只说真话:探活不等于验证过接单能力。
expect(on).toContain('端点探测:端点可达 · 未做接单验证')
const blocked=renderToStaticMarkup(<SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={settings} productionEnabled={true} productionBackupRestoreVerified={false} routingCapabilities={{internal_enabled:false,external_enabled:false}} loading={false} saving={false} error={null} saveMessage={null} onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} initialSection="services" />)
expect(blocked).toContain('已启用 · 被阻断')
// 未配置生产端点时必须显式说「未配置」,不得靠文案含糊过去。
expect(blocked).toContain('端点探测:暂无真实探测结果')
const unconfigured=renderToStaticMarkup(<SystemSettingsView sources={sources} connections={connections} monitor={{...monitor,health:[{key:'weknora-production',name:'生产 WeKnora',liveness:'unknown',readiness:'not_configured',reason:'已部署但未配置探测参数',latency_ms:0,observed_at:'2026-09-08T12:00:00Z',last_success_at:null,consecutive_failures:0,configured:false,applicable:false}]}} settings={settings} productionEnabled={false} routingCapabilities={{internal_enabled:false,external_enabled:false}} loading={false} saving={false} error={null} saveMessage={null} onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} initialSection="services" />)
expect(unconfigured).toContain('端点探测:未配置')
expect(unconfigured).not.toContain('端点可达')
describe('SystemSettingsView', () => {
it('separates document-engineer settings from locked administrator and production controls', () => {
const html = renderToStaticMarkup(
<SystemSettingsView
sources={sources}
connections={connections}
monitor={monitor}
settings={settings}
productionEnabled={false}
routingCapabilities={{ internal_enabled: true, external_enabled: true }}
loading={false}
saving={false}
error={null}
saveMessage="刷新与告警参数已验证并启用:文档15秒、资源30秒、停滞30分钟、finalizing 2小时"
onSave={vi.fn()}
onSourcesChanged={vi.fn()}
onRefresh={vi.fn()}
/>
)
for (const text of [
'系统设置',
'数据源配置',
'服务配置',
'存储与备份',
'刷新策略',
'设置服务已启用',
'当前活动版本',
'端点与凭据',
'文档工程师可调整',
'管理员设置已锁定',
])
expect(html).toContain(text)
// 需求(2026-10-14):数据源配置默认只列 PP 资料 + 「可加入的来源」;AList 与钉钉知识库来源
// 不删除,收进折叠开关,展开后才渲染(原来它们默认就在列表里)。
// 折叠开关自己的文案里就含“钉钉知识库”,所以只核对来源卡片才有的标记。
for (const folded of ['公司级技术支持知识库', '专用浏览器扫码会话', '直连 API Token'])
expect(html).not.toContain(folded)
expect(html).toContain('显示 AList/钉钉知识库来源(1)')
expect(html).toContain('这 1 个已接入来源未删除,数据不变')
// 需求(2026-10-10):数据源配置不再做文件格式筛选(格式由目录级标注决定)。
for (const removed of ['文件格式筛选', '未勾选的一律不取件', '保存保留格式', '恢复继承上级规则'])
expect(html).not.toContain(removed)
// 需求(2026-10-10):新增入口只剩「可加入的来源」勾选,粘贴链接的按钮已下线。
for (const removed of ['+ 新增钉钉知识库', '新增钉钉知识库']) expect(html).not.toContain(removed)
const servicesHtml = renderToStaticMarkup(
<SystemSettingsView
sources={sources}
connections={connections}
monitor={monitor}
settings={settings}
productionEnabled={false}
routingCapabilities={{ internal_enabled: true, external_enabled: true }}
loading={false}
saving={false}
error={null}
saveMessage={null}
onSave={vi.fn()}
onSourcesChanged={vi.fn()}
onRefresh={vi.fn()}
initialSection="services"
/>
)
for (const text of ['测试 WeKnora', '生产 WeKnora', '测试地址', '生产地址', '生产 ID', '知识库 ID'])
expect(servicesHtml).toContain(text)
const storageHtml = renderToStaticMarkup(
<SystemSettingsView
sources={sources}
connections={connections}
monitor={monitor}
settings={settings}
productionEnabled={false}
routingCapabilities={{ internal_enabled: true, external_enabled: true }}
loading={false}
saving={false}
error={null}
saveMessage={null}
onSave={vi.fn()}
onSourcesChanged={vi.fn()}
onRefresh={vi.fn()}
initialSection="storage"
/>
)
// 存储与备份分区已换成真实功能(整库逻辑备份的定时计划),静态占位文案不再存在。
expect(storageHtml).toContain('存储与备份')
expect(storageHtml).toContain('正在读取备份计划…')
expect(storageHtml).not.toContain('仅保存凭据引用,不可回读')
const refreshHtml = renderToStaticMarkup(
<SystemSettingsView
sources={sources}
connections={connections}
monitor={monitor}
settings={settings}
productionEnabled={false}
routingCapabilities={{ internal_enabled: true, external_enabled: true }}
loading={false}
saving={false}
error={null}
saveMessage="刷新与告警参数已验证并启用:文档15秒、资源30秒、停滞30分钟、finalizing 2小时"
onSave={vi.fn()}
onSourcesChanged={vi.fn()}
onRefresh={vi.fn()}
initialSection="refresh"
/>
)
for (const text of [
'刷新与告警参数已验证并启用',
'停滞30分钟',
'finalizing 2小时',
'文档状态刷新间隔',
'15秒',
'解析停滞判定',
'30分钟',
'保存并应用刷新与告警参数',
])
expect(refreshHtml).toContain(text)
expect(visibleSaveMessage('已保存', true)).toBeNull()
expect(visibleSaveMessage('已保存', false)).toBe('已保存')
expect(html).not.toContain('本地模拟')
expect(html).not.toContain('保存模拟设置')
for (const forbidden of ['DATABASE_URL', 'RELEASE_CONFIG_FILE', 'API Key明文', 'secret_ref'])
expect(html).not.toContain(forbidden)
// 两个环境卡仍由真实探测驱动(依赖矩阵搬到总览页,本页不再渲染)。
expect(servicesHtml).toContain('解析队列 对内 已配置 · 对外 已配置')
expect(servicesHtml).not.toContain('PostgreSQL')
expect(servicesHtml).toContain('端点探测:暂无真实探测结果')
// V1: left-nav section controls, per-source schedule editing, danger modal & history affordances.
expect(html).toContain('settings-nav')
expect(html).toContain('查看修订历史')
expect(html).toContain('保存并启用')
expect(html).toContain('停用中(不入队)')
// 卡片级调度/停用按钮仍在,只是默认只对可见来源渲染(钉钉/AList 卡片已折起)。
for (const foldedControl of ['下次自动刷新', '保存并启用调度', '停用来源'])
expect(html).not.toContain(foldedControl)
expect(html).toContain('本地手工导入来源不支持定时刷新')
// dead buttons removed
expect(html).not.toContain('添加内容源')
expect(html).not.toContain('管理员编辑')
})
it('lets an administrator bind the internal/external import knowledge bases from 系统设置', () => {
// 组件一直在(RoutingBindingsSection),但从未挂到任何页面 —— 导入目标库只能靠
// 部署 env 钉死,换库必须重建容器。
const view = (section: 'sources' | 'bindings' | 'production-bindings') =>
renderToStaticMarkup(
<AuthContext.Provider value={authValue('admin')}>
<SystemSettingsView
sources={sources}
connections={connections}
monitor={monitor}
settings={settings}
productionEnabled={false}
routingCapabilities={{ internal_enabled: true, external_enabled: true }}
loading={false}
saving={false}
error={null}
saveMessage={null}
onSave={vi.fn()}
onSourcesChanged={vi.fn()}
onRefresh={vi.fn()}
initialSection={section}
/>
</AuthContext.Provider>
)
expect(view('sources')).toContain('测试知识库绑定')
expect(view('sources')).toContain('生产知识库绑定')
const bound = view('bindings')
expect(bound).toContain('id="settings-routing-bindings"')
expect(bound).toContain('分发到对应的测试 WeKnora 知识库')
// 未读到绑定数据时(SSR 不跑 effect)面板也要如实存在,而不是空白。
expect(bound).toContain('读取中…')
// 发布目标(源库 → 目标库)是独立分区,与测试端收件库分开。
const target = view('production-bindings')
expect(target).toContain('id="settings-production-bindings"')
expect(target).toContain('新发布的对内 / 对外内容按这里的绑定写入生产 WeKnora 的对应知识库')
})
it('does not show healthy simulation when the settings data failed to load', () => {
const html = renderToStaticMarkup(
<SystemSettingsView
sources={[]}
connections={[]}
monitor={null}
settings={null}
productionEnabled={false}
routingCapabilities={{ internal_enabled: false, external_enabled: false }}
loading={false}
saving={false}
error="加载失败"
saveMessage={null}
onSave={vi.fn()}
onSourcesChanged={vi.fn()}
onRefresh={vi.fn()}
/>
)
expect(html).toContain('加载失败')
expect(html).not.toContain('模拟运行中')
})
it('renders the WeKnora cards and production channel from live probe and the real production gate', () => {
const probed: MonitorOverview = {
...monitor,
health: [
{
key: 'weknora',
name: 'WeKnora API',
liveness: 'up',
readiness: 'ready',
reason: '',
latency_ms: 86,
observed_at: '2026-09-08T12:00:00Z',
last_success_at: '2026-09-08T11:59:00Z',
consecutive_failures: 0,
configured: true,
applicable: true,
},
{
key: 'weknora-production',
name: '生产 WeKnora',
liveness: 'up',
readiness: 'ready',
reason: '',
latency_ms: 41,
observed_at: '2026-09-08T12:00:00Z',
last_success_at: '2026-09-08T11:59:00Z',
consecutive_failures: 0,
configured: true,
applicable: true,
},
{
key: 'embedding',
name: 'Embedding',
liveness: 'up',
readiness: 'not_applicable',
reason: '未部署:本平台不使用该依赖',
latency_ms: 0,
observed_at: '2026-09-08T12:00:00Z',
last_success_at: null,
consecutive_failures: 0,
configured: false,
applicable: false,
},
],
}
const view = (enabled: boolean, verified: boolean) =>
renderToStaticMarkup(
<SystemSettingsView
sources={sources}
connections={connections}
monitor={probed}
settings={settings}
productionEnabled={enabled}
productionBackupRestoreVerified={verified}
routingCapabilities={{ internal_enabled: true, external_enabled: true }}
loading={false}
saving={false}
error={null}
saveMessage={null}
onSave={vi.fn()}
onSourcesChanged={vi.fn()}
onRefresh={vi.fn()}
initialSection="services"
/>
)
const on = view(true, true)
expect(on).toContain('测试 WeKnora')
expect(on).toContain('可达 · 可接单')
expect(on).toContain('延迟 86ms')
expect(on).toContain('已启用 · 可提交生产请求')
expect(on).toContain('生产写入:开启')
expect(on).toContain('发布目标与凭据:管理员受限配置')
const off = view(false, false)
expect(off).toContain('未启用')
expect(off).toContain('生产写入:关闭')
// 卡片状态由真实探测/门禁驱动,写死的“已连接 / 未连接 / 生产映射:未配置”必须消失。
for (const removed of ['本地真实连接', '生产映射:未配置']) expect(off).not.toContain(removed)
// 生产端点可达性来自真实探活,且只说真话:探活不等于验证过接单能力。
expect(on).toContain('端点探测:端点可达 · 未做接单验证')
const blocked = renderToStaticMarkup(
<SystemSettingsView
sources={sources}
connections={connections}
monitor={monitor}
settings={settings}
productionEnabled={true}
productionBackupRestoreVerified={false}
routingCapabilities={{ internal_enabled: false, external_enabled: false }}
loading={false}
saving={false}
error={null}
saveMessage={null}
onSave={vi.fn()}
onSourcesChanged={vi.fn()}
onRefresh={vi.fn()}
initialSection="services"
/>
)
expect(blocked).toContain('已启用 · 被阻断')
// 未配置生产端点时必须显式说「未配置」,不得靠文案含糊过去。
expect(blocked).toContain('端点探测:暂无真实探测结果')
const unconfigured = renderToStaticMarkup(
<SystemSettingsView
sources={sources}
connections={connections}
monitor={{
...monitor,
health: [
{
key: 'weknora-production',
name: '生产 WeKnora',
liveness: 'unknown',
readiness: 'not_configured',
reason: '已部署但未配置探测参数',
latency_ms: 0,
observed_at: '2026-09-08T12:00:00Z',
last_success_at: null,
consecutive_failures: 0,
configured: false,
applicable: false,
},
],
}}
settings={settings}
productionEnabled={false}
routingCapabilities={{ internal_enabled: false, external_enabled: false }}
loading={false}
saving={false}
error={null}
saveMessage={null}
onSave={vi.fn()}
onSourcesChanged={vi.fn()}
onRefresh={vi.fn()}
initialSection="services"
/>
)
expect(unconfigured).toContain('端点探测:未配置')
expect(unconfigured).not.toContain('端点可达')
})
})
describe('SystemSettingsView 数据源配置的默认清单', () => {
const withPP: SourceConnectionListItem[] = [
{
id: 'conn-pp',
source_type: 'pp',
name: 'PP资料下载中心',
enabled: true,
schedule_configured: true,
health_status: 'healthy',
item_count: 613,
updated_at: '2026-09-09T09:30:32Z',
next_refresh_at: null,
},
{
id: 'conn-alist',
source_type: 'alist',
name: '国内工业',
enabled: false,
schedule_configured: false,
health_status: 'unknown',
item_count: 3027,
updated_at: '2026-09-09T09:30:32Z',
next_refresh_at: null,
},
{
id: 'conn-ding2',
source_type: 'dingtalk',
name: 'ATOM知识库',
enabled: false,
schedule_configured: false,
health_status: 'unknown',
item_count: 109,
updated_at: '2026-09-09T09:30:32Z',
next_refresh_at: null,
},
]
const view = () =>
renderToStaticMarkup(
<SystemSettingsView
sources={[]}
connections={withPP}
monitor={monitor}
settings={settings}
productionEnabled={false}
routingCapabilities={{ internal_enabled: true, external_enabled: true }}
loading={false}
saving={false}
error={null}
saveMessage={null}
onSave={vi.fn()}
onSourcesChanged={vi.fn()}
onRefresh={vi.fn()}
/>
)
it('默认只列 PP 资料:AList 与钉钉知识库来源折起来但没删', () => {
const html = view()
expect(html).toContain('PP资料下载中心')
expect(html).toContain('PP 资料下载中心')
expect(html).not.toContain('国内工业')
expect(html).not.toContain('ATOM知识库')
expect(html).toContain('显示 AList/钉钉知识库来源(2)')
// 登记路径说清楚:新来源一律走「可加入的来源」;格式筛选与旧的新增入口继续不存在。
expect(html).toContain('可加入的来源')
expect(html).toContain('钉盘文件已替代 AList')
for (const removed of ['+ 新增钉钉知识库', '文件格式筛选']) expect(html).not.toContain(removed)
})
})
describe('splitSourceConnections(数据源配置的默认清单规则)', () => {
const rows: SourceConnectionListItem[] = [
{
id: 'a',
source_type: 'pp',
name: 'PP资料下载中心',
enabled: true,
schedule_configured: true,
health_status: 'healthy',
item_count: 1,
updated_at: '2026-09-09T09:30:32Z',
next_refresh_at: null,
},
{
id: 'b',
source_type: 'alist',
name: '国内工业',
enabled: false,
schedule_configured: false,
health_status: 'unknown',
item_count: 2,
updated_at: '2026-09-09T09:30:32Z',
next_refresh_at: null,
},
{
id: 'c',
source_type: 'dingtalk',
name: 'ATOM知识库',
enabled: false,
schedule_configured: false,
health_status: 'unknown',
item_count: 3,
updated_at: '2026-09-09T09:30:32Z',
next_refresh_at: null,
},
{
id: 'd',
source_type: 'manual',
name: '本地手工验收',
enabled: false,
schedule_configured: false,
health_status: 'unknown',
item_count: 4,
updated_at: '2026-09-09T09:30:32Z',
next_refresh_at: null,
},
]
it('默认折起 AList 与钉钉知识库,展开后原样返回(顺序不变、一个不少)', () => {
const folded = splitSourceConnections(rows, false)
expect(folded.visible.map((item) => item.id)).toEqual(['a', 'd'])
expect(folded.legacy.map((item) => item.id)).toEqual(['b', 'c'])
const expanded = splitSourceConnections(rows, true)
expect(expanded.visible.map((item) => item.id)).toEqual(['a', 'b', 'c', 'd'])
expect(expanded.legacy.length).toBe(2)
})
})
+646 -121
View File
@@ -12,9 +12,21 @@ import type { MonitorOverview } from './monitor'
import { fetchReleaseCapabilities } from './reviewRelease'
import { fetchCatalogRoutingCapabilities, fetchCatalogSources } from './sourceCatalog'
import type { CatalogRoutingCapabilities, CatalogSource } from './sourceCatalog'
import { activateSourceSettingsRevision, createSourceSettingsRevision, fetchSourceConnectionList, fetchSourceSettingsRevisions } from './sourceConnections'
import {
activateSourceSettingsRevision,
createSourceSettingsRevision,
fetchSourceConnectionList,
fetchSourceSettingsRevisions,
} from './sourceConnections'
import type { SourceConnectionListItem, SourceSettingsRevision } from './sourceConnections'
import { activateUISettings, createUISettingsCandidate, fetchActiveUISettings, validKnowledgeBaseID, validProductionTenantID, validServiceEndpoint } from './uiSettings'
import {
activateUISettings,
createUISettingsCandidate,
fetchActiveUISettings,
validKnowledgeBaseID,
validProductionTenantID,
validServiceEndpoint,
} from './uiSettings'
import type { UISettings, UISettingsCandidateInput } from './uiSettings'
import './systemSettings.css'
@@ -48,17 +60,37 @@ const sections: { key: SectionKey; label: string; adminOnly?: boolean }[] = [
{ key: 'members', label: '成员与角色', adminOnly: true },
] as { key: SectionKey; label: string; adminOnly?: boolean }[]
const sourceTypeLabels: Record<string, string> = { dingtalk: '钉钉知识库', pp: 'PP 资料下载中心', alist: 'AList 文件源', manual: '本地手工导入' }
const sourceAuthLabels: Record<string, string> = { dingtalk: '专用浏览器扫码会话', pp: '公开只读访问', alist: '直连 API Token', manual: '离线导入,无在线认证' }
const secondsLabel = (value: number) => value < 60 ? `${value}秒` : value < 3600 ? `${value / 60}分钟` : `${value / 3600}小时`
export const visibleSaveMessage = (message: string | null, dirty: boolean) => dirty ? null : message
const sourceTypeLabels: Record<string, string> = {
dingtalk: '钉钉知识库',
pp: 'PP 资料下载中心',
alist: 'AList 文件源',
manual: '本地手工导入',
}
// 已由钉盘文件替代 / 改为按当前钉钉账号发现的来源类型:数据不删,只是在「数据源配置」默认折起来。
export const legacySourceTypes = ['alist', 'dingtalk'] as const
export const splitSourceConnections = (connections: SourceConnectionListItem[], showLegacy: boolean) => {
const legacy = connections.filter((item) => (legacySourceTypes as readonly string[]).includes(item.source_type))
const legacyIDs = new Set(legacy.map((item) => item.id))
return { legacy, visible: showLegacy ? connections : connections.filter((item) => !legacyIDs.has(item.id)) }
}
const sourceAuthLabels: Record<string, string> = {
dingtalk: '专用浏览器扫码会话',
pp: '公开只读访问',
alist: '直连 API Token',
manual: '离线导入,无在线认证',
}
const secondsLabel = (value: number) =>
value < 60 ? `${value}秒` : value < 3600 ? `${value / 60}分钟` : `${value / 3600}小时`
export const visibleSaveMessage = (message: string | null, dirty: boolean) => (dirty ? null : message)
type ServiceHealthView = MonitorOverview['health'][number]
type ServiceView = MonitorOverview['services'][number]
// 服务配置只保留四项可写值(测试地址、生产地址、生产 ID、知识库 ID),
// 依赖与解析队列的状态仍按真实探测呈现,不写死。
const findHealth = (monitor: MonitorOverview | null, name: string): ServiceHealthView | undefined => (monitor?.health || []).find((item) => item.name === name || item.name.startsWith(name))
const findHealth = (monitor: MonitorOverview | null, name: string): ServiceHealthView | undefined =>
(monitor?.health || []).find((item) => item.name === name || item.name.startsWith(name))
export const healthStateLabel = (health: ServiceHealthView | undefined, service: ServiceView | undefined): string => {
if (!health) {
if (!service) return '待配置'
@@ -71,7 +103,9 @@ export const healthStateLabel = (health: ServiceHealthView | undefined, service:
}
export const healthStateDetail = (health: ServiceHealthView | undefined, service: ServiceView | undefined): string => {
if (!health) return service?.detail || '真实 Provider 未接入'
const success = health.last_success_at ? `最近成功 ${new Date(health.last_success_at).toLocaleTimeString('zh-CN', { hour12: false })}` : ''
const success = health.last_success_at
? `最近成功 ${new Date(health.last_success_at).toLocaleTimeString('zh-CN', { hour12: false })}`
: ''
if (health.readiness === 'ready') return [`延迟 ${health.latency_ms}ms`, success].filter(Boolean).join(';')
const failures = health.consecutive_failures ? `连续失败${health.consecutive_failures}次` : ''
return [health.reason, success, failures].filter(Boolean).join(';')
@@ -84,7 +118,12 @@ export const productionWeKnoraProbe = (monitor: MonitorOverview | null): string
const health = findHealth(monitor, '生产 WeKnora')
if (!health) return '端点探测:暂无真实探测结果'
if (!health.configured) return '端点探测:未配置'
const label = health.liveness === 'up' ? (health.readiness === 'ready' ? '端点可达 · 未做接单验证' : '端点可达 · 不可接单') : '端点不可达'
const label =
health.liveness === 'up'
? health.readiness === 'ready'
? '端点可达 · 未做接单验证'
: '端点可达 · 不可接单'
: '端点不可达'
const detail = healthStateDetail(health, undefined)
return `端点探测:${label}${detail ? `(${detail})` : ''}`
}
@@ -103,7 +142,13 @@ function formatHorizon(value: string | null): string {
return `下次自动刷新 ${at.toLocaleString('zh-CN', { hour12: false })}`
}
function SourceSettingsCard({ connection, onSourcesChanged }: { connection: SourceConnectionListItem; onSourcesChanged: () => void }) {
function SourceSettingsCard({
connection,
onSourcesChanged,
}: {
connection: SourceConnectionListItem
onSourcesChanged: () => void
}) {
const auth = useOptionalAuth()
const isAdmin = auth?.identity?.role === 'admin'
const [interval, setInterval] = useState<number>(() => {
@@ -121,15 +166,23 @@ function SourceSettingsCard({ connection, onSourcesChanged }: { connection: Sour
const scheduled = connection.source_type !== 'manual'
const submit = async (nextEnabled: boolean) => {
setBusy(true); setMessage(null); setFailure(null)
setBusy(true)
setMessage(null)
setFailure(null)
try {
const draft = {
source_type: connection.source_type, name: connection.name, endpoint: '', credential_ref: '',
enabled: nextEnabled, schedule: { refresh_interval_seconds: nextEnabled && interval > 0 ? interval : null },
source_type: connection.source_type,
name: connection.name,
endpoint: '',
credential_ref: '',
enabled: nextEnabled,
schedule: { refresh_interval_seconds: nextEnabled && interval > 0 ? interval : null },
}
const created = await createSourceSettingsRevision(connection.id, draft)
const activated = await activateSourceSettingsRevision(connection.id, created.id)
setMessage(`${connection.name}:调度设置已验证并启用${activated.operation === 'replayed' ? '(沿用上次结果)' : ''};${nextEnabled ? formatHorizon(new Date(Date.now() + interval * 1000).toISOString()) : '已停用,新的自动扫描与刷新任务不再入队,历史记录全部保留'}。`)
setMessage(
`${connection.name}:调度设置已验证并启用${activated.operation === 'replayed' ? '(沿用上次结果)' : ''};${nextEnabled ? formatHorizon(new Date(Date.now() + interval * 1000).toISOString()) : '已停用,新的自动扫描与刷新任务不再入队,历史记录全部保留'}。`
)
onSourcesChanged()
} catch (cause) {
setFailure(cause instanceof Error ? cause.message : '保存来源设置失败')
@@ -142,42 +195,150 @@ function SourceSettingsCard({ connection, onSourcesChanged }: { connection: Sour
const loadHistory = async () => {
setShowHistory(true)
if (history) return
try { setHistory(await fetchSourceSettingsRevisions(connection.id)) }
catch (cause) { setFailure(cause instanceof Error ? cause.message : '加载修订历史失败') }
try {
setHistory(await fetchSourceSettingsRevisions(connection.id))
} catch (cause) {
setFailure(cause instanceof Error ? cause.message : '加载修订历史失败')
}
}
const canApply = !busy
return <article className="settings-source-row">
<div className="settings-source-name"><strong>{connection.name}</strong><span>{sourceTypeLabels[connection.source_type] ?? connection.source_type}{connection.enabled ? '' : ' · 已停用'}</span></div>
<dl>
<div><dt>认证方式</dt><dd>{sourceAuthLabels[connection.source_type] ?? '按连接配置'}</dd></div>
<div><dt>端点与凭据</dt><dd>已保存,不可回读(草稿留空即沿用现值)</dd></div>
<div><dt>当前调度</dt><dd>{connection.enabled ? formatHorizon(connection.next_refresh_at) : '停用中(不入队)'}</dd></div>
</dl>
<div className="source-schedule-form">
{scheduled ? <label>自动刷新周期<select value={interval} onChange={(event) => setInterval(Number(event.target.value))}>{intervalChoices.map((choice) => <option key={choice.value} value={choice.value}>{choice.label}</option>)}</select></label>
: <small className="manual-source-note">本地手工导入来源不支持定时刷新,只能手动触发扫描。</small>}
{connection.enabled
? <div className="source-schedule-actions"><button className="secondary" disabled={!canApply || (scheduled && interval === 0 && !connection.schedule_configured)} onClick={() => void submit(true)}>{busy ? '正在验证并启用…' : '保存并启用调度'}</button>
<button className="danger" disabled={!canApply} onClick={() => setPendingDisable(true)}>停用来源</button></div>
: <div className="source-schedule-actions"><button className="secondary" disabled={!canApply} onClick={() => void submit(true)}>保存并启用</button></div>}
{connection.source_type === "dingtalk" && isAdmin ? <DingtalkSessionControl /> : null}
<button className="link" onClick={() => void loadHistory()}>{showHistory ? '收起修订历史' : '查看修订历史'}</button>
</div>
{message ? <p className="success-message" role="status">{message}</p> : null}
{failure ? <p className="error-message" role="alert">{failure}</p> : null}
{showHistory && history ? <ul className="revision-list">{history.map((item) => <li key={item.id}><b>修订 {item.revision_number}</b><span>{item.state === 'active' ? '当前启用' : item.state === 'validated' ? '待启用' : item.state === 'retired' ? '已退休' : '失败'}</span><small>{item.created_by} · {new Date(item.created_at).toLocaleString('zh-CN', { hour12: false })} · {item.refresh_interval_seconds ? `每${secondsLabel(Number(item.refresh_interval_seconds))}` : '仅手动'}</small></li>)}</ul> : null}
{showHistory && !history ? <small>正在加载修订历史…</small> : null}
{pendingDisable ? <div className="modal-backdrop" role="dialog" aria-modal="true"><div className="modal-card">
<h3>停用「{connection.name}」?</h3>
<p>停用会立即停止该来源的自动扫描与新刷新任务入队;历史快照、标注和审计全部保留,随时可以重新启用。此操作会先由后端再次校验权限。</p>
<div className="modal-actions"><button className="danger" disabled={busy} onClick={() => void submit(false)}>{busy ? '正在停用…' : '确认停用'}</button><button className="secondary" disabled={busy} onClick={() => setPendingDisable(false)}>取消</button></div>
</div></div> : null}
</article>
return (
<article className="settings-source-row">
<div className="settings-source-name">
<strong>{connection.name}</strong>
<span>
{sourceTypeLabels[connection.source_type] ?? connection.source_type}
{connection.enabled ? '' : ' · 已停用'}
</span>
</div>
<dl>
<div>
<dt>认证方式</dt>
<dd>{sourceAuthLabels[connection.source_type] ?? '按连接配置'}</dd>
</div>
<div>
<dt>端点与凭据</dt>
<dd>已保存,不可回读(草稿留空即沿用现值)</dd>
</div>
<div>
<dt>当前调度</dt>
<dd>{connection.enabled ? formatHorizon(connection.next_refresh_at) : '停用中(不入队)'}</dd>
</div>
</dl>
<div className="source-schedule-form">
{scheduled ? (
<label>
自动刷新周期
<select value={interval} onChange={(event) => setInterval(Number(event.target.value))}>
{intervalChoices.map((choice) => (
<option key={choice.value} value={choice.value}>
{choice.label}
</option>
))}
</select>
</label>
) : (
<small className="manual-source-note">本地手工导入来源不支持定时刷新,只能手动触发扫描。</small>
)}
{connection.enabled ? (
<div className="source-schedule-actions">
<button
className="secondary"
disabled={!canApply || (scheduled && interval === 0 && !connection.schedule_configured)}
onClick={() => void submit(true)}
>
{busy ? '正在验证并启用…' : '保存并启用调度'}
</button>
<button className="danger" disabled={!canApply} onClick={() => setPendingDisable(true)}>
停用来源
</button>
</div>
) : (
<div className="source-schedule-actions">
<button className="secondary" disabled={!canApply} onClick={() => void submit(true)}>
保存并启用
</button>
</div>
)}
{connection.source_type === 'dingtalk' && isAdmin ? <DingtalkSessionControl /> : null}
<button className="link" onClick={() => void loadHistory()}>
{showHistory ? '收起修订历史' : '查看修订历史'}
</button>
</div>
{message ? (
<p className="success-message" role="status">
{message}
</p>
) : null}
{failure ? (
<p className="error-message" role="alert">
{failure}
</p>
) : null}
{showHistory && history ? (
<ul className="revision-list">
{history.map((item) => (
<li key={item.id}>
<b>修订 {item.revision_number}</b>
<span>
{item.state === 'active'
? '当前启用'
: item.state === 'validated'
? '待启用'
: item.state === 'retired'
? '已退休'
: '失败'}
</span>
<small>
{item.created_by} · {new Date(item.created_at).toLocaleString('zh-CN', { hour12: false })} ·{' '}
{item.refresh_interval_seconds ? `每${secondsLabel(Number(item.refresh_interval_seconds))}` : '仅手动'}
</small>
</li>
))}
</ul>
) : null}
{showHistory && !history ? <small>正在加载修订历史…</small> : null}
{pendingDisable ? (
<div className="modal-backdrop" role="dialog" aria-modal="true">
<div className="modal-card">
<h3>停用「{connection.name}」?</h3>
<p>
停用会立即停止该来源的自动扫描与新刷新任务入队;历史快照、标注和审计全部保留,随时可以重新启用。此操作会先由后端再次校验权限。
</p>
<div className="modal-actions">
<button className="danger" disabled={busy} onClick={() => void submit(false)}>
{busy ? '正在停用…' : '确认停用'}
</button>
<button className="secondary" disabled={busy} onClick={() => setPendingDisable(false)}>
取消
</button>
</div>
</div>
</div>
) : null}
</article>
)
}
export function SystemSettingsView({ sources, connections, monitor, settings, productionEnabled, productionBackupRestoreVerified = false, routingCapabilities, loading, saving, error, saveMessage, onSave, onSourcesChanged, onRefresh, initialSection = 'sources' }: Props) {
export function SystemSettingsView({
sources,
connections,
monitor,
settings,
productionEnabled,
productionBackupRestoreVerified = false,
routingCapabilities,
loading,
saving,
error,
saveMessage,
onSave,
onSourcesChanged,
onRefresh,
initialSection = 'sources',
}: Props) {
const auth = useOptionalAuth()
const identity = auth?.identity ?? null
const [section, setSection] = useState<SectionKey>(initialSection)
@@ -189,9 +350,19 @@ export function SystemSettingsView({ sources, connections, monitor, settings, pr
const [endpoint, setEndpoint] = useState<string>(settings?.production_weknora_base_url ?? '')
const [testEndpoint, setTestEndpoint] = useState<string>(settings?.test_weknora_base_url ?? '')
const [productionTenantID, setProductionTenantID] = useState<string>(settings?.production_tenant_id ?? '')
const [productionKnowledgeBaseID, setProductionKnowledgeBaseID] = useState<string>(settings?.production_knowledge_base_id ?? '')
const [productionKnowledgeBaseID, setProductionKnowledgeBaseID] = useState<string>(
settings?.production_knowledge_base_id ?? ''
)
const [dirty, setDirty] = useState(false)
// 「数据源配置」默认只列 PP 资料:AList 已被钉盘文件替代、钉钉知识库一律走当前账号发现
//(见下方「可加入的来源」)。这 9 个已接入来源**不删除**,收进折叠开关里,随时可展开管理。
const [showLegacySources, setShowLegacySources] = useState(false)
const { legacy: legacyConnections, visible: visibleConnections } = splitSourceConnections(
connections,
showLegacySources
)
useEffect(() => {
if (!settings) return
setDocumentRefresh(settings.document_refresh_seconds)
@@ -212,76 +383,375 @@ export function SystemSettingsView({ sources, connections, monitor, settings, pr
const testEndpointValid = validServiceEndpoint(testEndpoint)
const productionTenantIDValid = validProductionTenantID(productionTenantID)
const productionKnowledgeBaseIDValid = validKnowledgeBaseID(productionKnowledgeBaseID)
const serviceSettingsValid = endpointValid && testEndpointValid && productionTenantIDValid && productionKnowledgeBaseIDValid
const serviceSettingsDirty = Boolean(settings && (
testEndpoint.trim() !== settings.test_weknora_base_url ||
endpoint.trim() !== settings.production_weknora_base_url ||
productionTenantID.trim() !== settings.production_tenant_id ||
productionKnowledgeBaseID.trim() !== settings.production_knowledge_base_id))
const serviceSettingsValid =
endpointValid && testEndpointValid && productionTenantIDValid && productionKnowledgeBaseIDValid
const serviceSettingsDirty = Boolean(
settings &&
(testEndpoint.trim() !== settings.test_weknora_base_url ||
endpoint.trim() !== settings.production_weknora_base_url ||
productionTenantID.trim() !== settings.production_tenant_id ||
productionKnowledgeBaseID.trim() !== settings.production_knowledge_base_id)
)
const candidateInput = (overrides: Partial<UISettingsCandidateInput> = {}): UISettingsCandidateInput => ({
document_refresh_seconds: documentRefresh, resource_refresh_seconds: resourceRefresh,
stalled_after_seconds: stalled, finalizing_after_seconds: finalizing, ingestion_concurrency: concurrency,
test_weknora_base_url: testEndpoint.trim(), production_weknora_base_url: endpoint.trim(),
production_tenant_id: productionTenantID.trim(), production_knowledge_base_id: productionKnowledgeBaseID.trim(), ...overrides,
document_refresh_seconds: documentRefresh,
resource_refresh_seconds: resourceRefresh,
stalled_after_seconds: stalled,
finalizing_after_seconds: finalizing,
ingestion_concurrency: concurrency,
test_weknora_base_url: testEndpoint.trim(),
production_weknora_base_url: endpoint.trim(),
production_tenant_id: productionTenantID.trim(),
production_knowledge_base_id: productionKnowledgeBaseID.trim(),
...overrides,
})
const saveEndpoint = () => { setDirty(false); onSave(candidateInput()) }
return <main className="page-shell system-settings">
<header className="hero compact"><div><h1>系统设置</h1><p className="subtitle">查看内容源、服务与备份状态;来源调度与刷新参数采用版本化保存。</p></div><button onClick={onRefresh} disabled={loading}>{loading ? '刷新中…' : '刷新状态'}</button></header>
{error ? <div className="error-banner" role="alert">{error}</div> : null}
{monitor && settings ? <div className="settings-layout">
<nav className="settings-nav" aria-label="系统设置分区">{sections.filter((item) => !item.adminOnly || identity?.role === 'admin').map((item) => <button key={item.key} className={section === item.key ? 'active' : ''} onClick={() => setSection(item.key)}>{item.label}</button>)}</nav>
<div className="settings-content">
<div className="settings-role-strip"><span className="engineer-role">文档工程师可调整:来源调度周期、刷新间隔、停滞判断</span><span className="admin-role">管理员设置已锁定:端点、凭据、映射、生产开关</span></div>
<div className="simulation-banner server-settings-banner"><strong>设置服务已启用</strong><span>当前活动版本 · 启用人 {settings.updated_by} · 启用时间 {settings.activated_at ? new Date(settings.activated_at).toLocaleString('zh-CN') : '待激活'};新设置先验证,再原子切换。</span></div>
{section === 'sources' ? <section className="settings-panel wide source-settings-panel" id="settings-sources">
<div className="settings-section-heading"><div><h2>数据源配置</h2><p>从下方「可加入的来源」勾选即可登记新来源;逐来源设置自动刷新周期或保持仅手动,保存会先生成修订、验证后原子启用。</p></div></div>
{identity?.role === 'admin' ? <DingtalkSourceDiscovery registeredNames={connections.map((item) => item.name)} onRegistered={onSourcesChanged} /> : null}
{connections.length ? <div className="settings-source-list">
{connections.map((connection) => <SourceSettingsCard key={connection.id} connection={connection} onSourcesChanged={onSourcesChanged}/>)}
{sources.length ? null : <small className="empty-inline">尚无快照数据;快照将在来源首次刷新完成后出现。</small>}
</div> : <div className="empty-state">尚无可显示的来源连接。</div>}
</section> : null}
{section === 'services' ? <section className="settings-panel wide" id="settings-services">
<div className="settings-section-heading"><div><h2>服务配置</h2><p>只配四项:测试地址、生产地址、生产 ID、知识库 ID。保存会先生成修订、验证后原子启用,旧版本保留用于审计;凭据只写不读。</p></div></div>
<div className="environment-cards"><article><b>测试 WeKnora</b><span>{healthStateLabel(findHealth(monitor, 'WeKnora API'), undefined)}</span><small>{`${healthStateDetail(findHealth(monitor, 'WeKnora API'), undefined) || '端点探测:未配置'};解析队列 对内 ${routingCapabilities.internal_enabled ? '已配置' : '未配置'} · 对外 ${routingCapabilities.external_enabled ? '已配置' : '未配置'}`}</small></article><article className="production"><b>生产 WeKnora</b><span>{!productionEnabled ? '未启用' : productionBackupRestoreVerified ? '已启用 · 可提交生产请求' : '已启用 · 被阻断'}</span><small>{`${productionWeKnoraProbe(monitor)};生产写入:${productionEnabled ? '开启' : '关闭'};发布目标与凭据:管理员受限配置,本页不可回读`}</small></article></div>
<div className="safe-setting-grid production-endpoint-form">
{isAdmin ? <>
<label>测试地址<input value={testEndpoint} onChange={(event) => { setTestEndpoint(event.target.value); setDirty(true) }} placeholder="https://weknora.test.example" aria-invalid={!testEndpointValid} /></label>
<label>生产地址<input value={endpoint} onChange={(event) => { setEndpoint(event.target.value); setDirty(true) }} placeholder="https://weknora.prod.example" aria-invalid={!endpointValid} /></label>
<label>生产 ID<input value={productionTenantID} onChange={(event) => { setProductionTenantID(event.target.value); setDirty(true) }} placeholder="10000" aria-invalid={!productionTenantIDValid} /></label>
<label>知识库 ID<input value={productionKnowledgeBaseID} onChange={(event) => { setProductionKnowledgeBaseID(event.target.value); setDirty(true) }} placeholder="生产知识库 ID" aria-invalid={!productionKnowledgeBaseIDValid} /></label>
</> : <>
<label>测试地址<input value={settings.test_weknora_base_url || '未配置'} readOnly disabled /></label>
<label>生产地址<input value={settings.production_weknora_base_url || '未配置'} readOnly disabled /></label>
<label>生产 ID<input value={settings.production_tenant_id || '未配置'} readOnly disabled /></label>
<label>知识库 ID<input value={settings.production_knowledge_base_id || '未配置'} readOnly disabled /></label>
</>}
const saveEndpoint = () => {
setDirty(false)
onSave(candidateInput())
}
return (
<main className="page-shell system-settings">
<header className="hero compact">
<div>
<h1>系统设置</h1>
<p className="subtitle">查看内容源、服务与备份状态;来源调度与刷新参数采用版本化保存。</p>
</div>
<button onClick={onRefresh} disabled={loading}>
{loading ? '刷新中…' : '刷新状态'}
</button>
</header>
{error ? (
<div className="error-banner" role="alert">
{error}
</div>
) : null}
{monitor && settings ? (
<div className="settings-layout">
<nav className="settings-nav" aria-label="系统设置分区">
{sections
.filter((item) => !item.adminOnly || identity?.role === 'admin')
.map((item) => (
<button
key={item.key}
className={section === item.key ? 'active' : ''}
onClick={() => setSection(item.key)}
>
{item.label}
</button>
))}
</nav>
<div className="settings-content">
<div className="settings-role-strip">
<span className="engineer-role">文档工程师可调整:来源调度周期、刷新间隔、停滞判断</span>
<span className="admin-role">管理员设置已锁定:端点、凭据、映射、生产开关</span>
</div>
<div className="simulation-banner server-settings-banner">
<strong>设置服务已启用</strong>
<span>
当前活动版本 · 启用人 {settings.updated_by} · 启用时间{' '}
{settings.activated_at ? new Date(settings.activated_at).toLocaleString('zh-CN') : '待激活'}
;新设置先验证,再原子切换。
</span>
</div>
{section === 'sources' ? (
<section className="settings-panel wide source-settings-panel" id="settings-sources">
<div className="settings-section-heading">
<div>
<h2>数据源配置</h2>
<p>
新来源只从下方「可加入的来源」勾选登记(按当前钉钉账号列出可访问的知识库与钉盘空间,钉盘文件已替代
AList);本页保留 PP 资料。逐来源设置自动刷新周期或保持仅手动,保存会先生成修订、验证后原子启用。
</p>
</div>
</div>
{identity?.role === 'admin' ? (
<DingtalkSourceDiscovery
registeredNames={connections.map((item) => item.name)}
onRegistered={onSourcesChanged}
/>
) : null}
{legacyConnections.length ? (
<div className="settings-legacy-toggle">
<button type="button" className="secondary" onClick={() => setShowLegacySources((value) => !value)}>
{showLegacySources
? `收起 AList/钉钉知识库来源(${legacyConnections.length})`
: `显示 AList/钉钉知识库来源(${legacyConnections.length})`}
</button>
<small>
{showLegacySources
? '这些来源已在两处保留:本列表可改刷新周期与启停,「来源与目录」里照旧浏览它们的内容。'
: `AList 来源已由钉盘文件替代,钉钉知识库来源改为按当前账号发现;这 ${legacyConnections.length} 个已接入来源未删除,数据不变。`}
</small>
</div>
) : null}
{visibleConnections.length ? (
<div className="settings-source-list">
{visibleConnections.map((connection) => (
<SourceSettingsCard
key={connection.id}
connection={connection}
onSourcesChanged={onSourcesChanged}
/>
))}
{sources.length ? null : (
<small className="empty-inline">尚无快照数据;快照将在来源首次刷新完成后出现。</small>
)}
</div>
) : legacyConnections.length ? (
<div className="empty-state">
本页只列 PP 资料;AList/钉钉知识库来源已收在上方开关里(共 {legacyConnections.length}{' '}
个,未删除)。
</div>
) : (
<div className="empty-state">尚无可显示的来源连接。</div>
)}
</section>
) : null}
{section === 'services' ? (
<section className="settings-panel wide" id="settings-services">
<div className="settings-section-heading">
<div>
<h2>服务配置</h2>
<p>
只配四项:测试地址、生产地址、生产 ID、知识库
ID。保存会先生成修订、验证后原子启用,旧版本保留用于审计;凭据只写不读。
</p>
</div>
</div>
<div className="environment-cards">
<article>
<b>测试 WeKnora</b>
<span>{healthStateLabel(findHealth(monitor, 'WeKnora API'), undefined)}</span>
<small>{`${healthStateDetail(findHealth(monitor, 'WeKnora API'), undefined) || '端点探测:未配置'};解析队列 对内 ${routingCapabilities.internal_enabled ? '已配置' : '未配置'} · 对外 ${routingCapabilities.external_enabled ? '已配置' : '未配置'}`}</small>
</article>
<article className="production">
<b>生产 WeKnora</b>
<span>
{!productionEnabled
? '未启用'
: productionBackupRestoreVerified
? '已启用 · 可提交生产请求'
: '已启用 · 被阻断'}
</span>
<small>{`${productionWeKnoraProbe(monitor)};生产写入:${productionEnabled ? '开启' : '关闭'};发布目标与凭据:管理员受限配置,本页不可回读`}</small>
</article>
</div>
<div className="safe-setting-grid production-endpoint-form">
{isAdmin ? (
<>
<label>
测试地址
<input
value={testEndpoint}
onChange={(event) => {
setTestEndpoint(event.target.value)
setDirty(true)
}}
placeholder="https://weknora.test.example"
aria-invalid={!testEndpointValid}
/>
</label>
<label>
生产地址
<input
value={endpoint}
onChange={(event) => {
setEndpoint(event.target.value)
setDirty(true)
}}
placeholder="https://weknora.prod.example"
aria-invalid={!endpointValid}
/>
</label>
<label>
生产 ID
<input
value={productionTenantID}
onChange={(event) => {
setProductionTenantID(event.target.value)
setDirty(true)
}}
placeholder="10000"
aria-invalid={!productionTenantIDValid}
/>
</label>
<label>
知识库 ID
<input
value={productionKnowledgeBaseID}
onChange={(event) => {
setProductionKnowledgeBaseID(event.target.value)
setDirty(true)
}}
placeholder="生产知识库 ID"
aria-invalid={!productionKnowledgeBaseIDValid}
/>
</label>
</>
) : (
<>
<label>
测试地址
<input value={settings.test_weknora_base_url || '未配置'} readOnly disabled />
</label>
<label>
生产地址
<input value={settings.production_weknora_base_url || '未配置'} readOnly disabled />
</label>
<label>
生产 ID
<input value={settings.production_tenant_id || '未配置'} readOnly disabled />
</label>
<label>
知识库 ID
<input value={settings.production_knowledge_base_id || '未配置'} readOnly disabled />
</label>
</>
)}
</div>
{isAdmin ? (
<>
<button
onClick={saveEndpoint}
disabled={!canSave || !serviceSettingsValid || !serviceSettingsDirty}
>
{saving ? '正在验证并启用…' : '保存并启用服务配置'}
</button>
<small>
四项留空即表示未配置。地址只接受 http(s) 源地址(不能带用户名密码、查询串或 #
片段,凭据一律走文件引用);生产 ID 是发布契约里的租户 ID,十进制数字;知识库 ID
是生产知识库标识,粘贴 URL 不会通过。保存写入服务器活动版本(版本化 + 审计 +
原子切换);后端同时对测试地址/生产地址做真实探活,并用生产地址真查这两个 ID(WeKnora
列库接口):端点回答"没有这个知识库"或租户不符会拒绝保存,端点抖动、鉴权失败或未配置生产凭据只警告不拦,核验原话与知识库名在保存后显示。
</small>
{serviceSettingsValid ? null : (
<p className="error-message" role="alert">
格式不合法:地址需 http:// 或 https:// 开头的纯地址,不能带用户名密码、? 查询串或 # 片段;生产
ID 需为十进制数字;知识库 ID 不能含空格、/、?、# 或 \。
</p>
)}
</>
) : (
<small>
服务配置仅管理员可修改;当前值:测试地址 {settings.test_weknora_base_url || '未配置'} · 生产地址{' '}
{settings.production_weknora_base_url || '未配置'} · 生产 ID{' '}
{settings.production_tenant_id || '未配置'} · 知识库 ID{' '}
{settings.production_knowledge_base_id || '未配置'}。
</small>
)}
</section>
) : null}
{section === 'bindings' ? <RoutingBindingsSection /> : null}
{section === 'production-bindings' ? <ProductionBindingsSection /> : null}
{section === 'storage' ? <BackupScheduleSection /> : null}
{section === 'members' && identity?.role === 'admin' ? <MembersSection /> : null}
{section === 'refresh' ? (
<section className="settings-panel wide" id="settings-refresh">
<div className="settings-section-heading">
<div>
<h2>刷新策略</h2>
<p>这些值保存在服务器活动版本中;保存不会修改端点、凭据或生产开关。</p>
</div>
<span className="safe-badge">当前活动版本</span>
</div>
<div className="safe-setting-grid">
<label>
文档状态刷新间隔
<select
value={documentRefresh}
onChange={(event) => {
setDocumentRefresh(Number(event.target.value) as 15 | 30 | 60)
setDirty(true)
}}
>
<option value={15}>15秒</option>
<option value={30}>30秒</option>
<option value={60}>1分钟</option>
</select>
</label>
<label>
资源刷新间隔
<select
value={resourceRefresh}
onChange={(event) => {
setResourceRefresh(Number(event.target.value) as 30 | 60)
setDirty(true)
}}
>
<option value={30}>30秒</option>
<option value={60}>1分钟</option>
</select>
</label>
<label>
解析停滞判定
<select
value={stalled}
onChange={(event) => {
setStalled(Number(event.target.value) as 1800 | 3600)
setDirty(true)
}}
>
<option value={1800}>30分钟</option>
<option value={3600}>1小时</option>
</select>
</label>
<label>
finalizing 告警
<select
value={finalizing}
onChange={(event) => {
setFinalizing(Number(event.target.value) as 7200 | 14400)
setDirty(true)
}}
>
<option value={7200}>2小时</option>
<option value={14400}>4小时</option>
</select>
</label>
<label>
入库并发上限
<select
value={concurrency}
onChange={(event) => {
setConcurrency(Number(event.target.value))
setDirty(true)
}}
>
<option value={1}>1(谨慎,MinerU 并发 1)</option>
<option value={2}>2</option>
<option value={3}>3</option>
<option value={4}>4</option>
<option value={6}>6</option>
<option value={8}>8</option>
</select>
</label>
</div>
<button
onClick={() => {
setDirty(false)
onSave(candidateInput())
}}
disabled={!canSave}
>
{saving ? '正在验证并应用…' : '保存并应用刷新与告警参数'}
</button>
{visibleSaveMessage(saveMessage, dirty) ? (
<p className="success-message" role="status">
{saveMessage}
</p>
) : null}
<small>
当前:文档 {secondsLabel(settings.document_refresh_seconds)}、资源{' '}
{secondsLabel(settings.resource_refresh_seconds)}、停滞 {secondsLabel(settings.stalled_after_seconds)}
、finalizing {secondsLabel(settings.finalizing_after_seconds)}、入库并发{' '}
{settings.ingestion_concurrency}。
</small>
</section>
) : null}
</div>
{isAdmin ? <><button onClick={saveEndpoint} disabled={!canSave || !serviceSettingsValid || !serviceSettingsDirty}>{saving ? '正在验证并启用…' : '保存并启用服务配置'}</button>
<small>四项留空即表示未配置。地址只接受 http(s) 源地址(不能带用户名密码、查询串或 # 片段,凭据一律走文件引用);生产 ID 是发布契约里的租户 ID,十进制数字;知识库 ID 是生产知识库标识,粘贴 URL 不会通过。保存写入服务器活动版本(版本化 + 审计 + 原子切换);后端同时对测试地址/生产地址做真实探活,并用生产地址真查这两个 ID(WeKnora 列库接口):端点回答"没有这个知识库"或租户不符会拒绝保存,端点抖动、鉴权失败或未配置生产凭据只警告不拦,核验原话与知识库名在保存后显示。</small>
{serviceSettingsValid ? null : <p className="error-message" role="alert">格式不合法:地址需 http:// 或 https:// 开头的纯地址,不能带用户名密码、? 查询串或 # 片段;生产 ID 需为十进制数字;知识库 ID 不能含空格、/、?、# 或 \。</p>}</>
: <small>服务配置仅管理员可修改;当前值:测试地址 {settings.test_weknora_base_url || '未配置'} · 生产地址 {settings.production_weknora_base_url || '未配置'} · 生产 ID {settings.production_tenant_id || '未配置'} · 知识库 ID {settings.production_knowledge_base_id || '未配置'}。</small>}
</section> : null}
{section === 'bindings' ? <RoutingBindingsSection /> : null}
{section === 'production-bindings' ? <ProductionBindingsSection /> : null}
{section === 'storage' ? <BackupScheduleSection /> : null}
{section === 'members' && identity?.role === 'admin' ? <MembersSection /> : null}
{section === 'refresh' ? <section className="settings-panel wide" id="settings-refresh">
<div className="settings-section-heading"><div><h2>刷新策略</h2><p>这些值保存在服务器活动版本中;保存不会修改端点、凭据或生产开关。</p></div><span className="safe-badge">当前活动版本</span></div>
<div className="safe-setting-grid">
<label>文档状态刷新间隔<select value={documentRefresh} onChange={(event) => { setDocumentRefresh(Number(event.target.value) as 15 | 30 | 60); setDirty(true) }}><option value={15}>15秒</option><option value={30}>30秒</option><option value={60}>1分钟</option></select></label>
<label>资源刷新间隔<select value={resourceRefresh} onChange={(event) => { setResourceRefresh(Number(event.target.value) as 30 | 60); setDirty(true) }}><option value={30}>30秒</option><option value={60}>1分钟</option></select></label>
<label>解析停滞判定<select value={stalled} onChange={(event) => { setStalled(Number(event.target.value) as 1800 | 3600); setDirty(true) }}><option value={1800}>30分钟</option><option value={3600}>1小时</option></select></label>
<label>finalizing 告警<select value={finalizing} onChange={(event) => { setFinalizing(Number(event.target.value) as 7200 | 14400); setDirty(true) }}><option value={7200}>2小时</option><option value={14400}>4小时</option></select></label>
<label>入库并发上限<select value={concurrency} onChange={(event) => { setConcurrency(Number(event.target.value)); setDirty(true) }}><option value={1}>1(谨慎,MinerU 并发 1)</option><option value={2}>2</option><option value={3}>3</option><option value={4}>4</option><option value={6}>6</option><option value={8}>8</option></select></label>
</div>
<button onClick={() => { setDirty(false); onSave(candidateInput()) }} disabled={!canSave}>{saving ? '正在验证并应用…' : '保存并应用刷新与告警参数'}</button>
{visibleSaveMessage(saveMessage, dirty) ? <p className="success-message" role="status">{saveMessage}</p> : null}
<small>当前:文档 {secondsLabel(settings.document_refresh_seconds)}、资源 {secondsLabel(settings.resource_refresh_seconds)}、停滞 {secondsLabel(settings.stalled_after_seconds)}、finalizing {secondsLabel(settings.finalizing_after_seconds)}、入库并发 {settings.ingestion_concurrency}。</small>
</section> : null}
</div>
</div> : null}
</main>
</div>
) : null}
</main>
)
}
export function SystemSettings() {
@@ -291,7 +761,10 @@ export function SystemSettings() {
const [settings, setSettings] = useState<UISettings | null>(null)
const [productionEnabled, setProductionEnabled] = useState(false)
const [productionBackupRestoreVerified, setProductionBackupRestoreVerified] = useState(false)
const [routingCapabilities, setRoutingCapabilities] = useState<CatalogRoutingCapabilities>({ internal_enabled: false, external_enabled: false })
const [routingCapabilities, setRoutingCapabilities] = useState<CatalogRoutingCapabilities>({
internal_enabled: false,
external_enabled: false,
})
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
@@ -299,24 +772,76 @@ export function SystemSettings() {
const [revision, setRevision] = useState(0)
useEffect(() => {
const controller = new AbortController(); setLoading(true)
void Promise.all([fetchCatalogSources(controller.signal), fetchSourceConnectionList(controller.signal), fetchMonitorOverview(controller.signal), fetchReleaseCapabilities(controller.signal), fetchCatalogRoutingCapabilities(controller.signal), fetchActiveUISettings(controller.signal)]).then(([nextSources, nextConnections, overview, capabilities, routing, active]) => { if (!controller.signal.aborted) { setSources(nextSources); setConnections(nextConnections); setMonitor(overview); setProductionEnabled(capabilities.production_release_requests_enabled); setProductionBackupRestoreVerified(capabilities.production_backup_restore_verified); setRoutingCapabilities(routing); setSettings(active); setError(null) } }).catch((cause) => { if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : '加载系统设置失败') }).finally(() => { if (!controller.signal.aborted) setLoading(false) })
const controller = new AbortController()
setLoading(true)
void Promise.all([
fetchCatalogSources(controller.signal),
fetchSourceConnectionList(controller.signal),
fetchMonitorOverview(controller.signal),
fetchReleaseCapabilities(controller.signal),
fetchCatalogRoutingCapabilities(controller.signal),
fetchActiveUISettings(controller.signal),
])
.then(([nextSources, nextConnections, overview, capabilities, routing, active]) => {
if (!controller.signal.aborted) {
setSources(nextSources)
setConnections(nextConnections)
setMonitor(overview)
setProductionEnabled(capabilities.production_release_requests_enabled)
setProductionBackupRestoreVerified(capabilities.production_backup_restore_verified)
setRoutingCapabilities(routing)
setSettings(active)
setError(null)
}
})
.catch((cause) => {
if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : '加载系统设置失败')
})
.finally(() => {
if (!controller.signal.aborted) setLoading(false)
})
return () => controller.abort()
}, [revision])
const save = async (input: UISettingsCandidateInput) => {
setSaving(true); setSaveMessage(null); setError(null)
setSaving(true)
setSaveMessage(null)
setError(null)
try {
const candidate = await createUISettingsCandidate(input)
const activated = await activateUISettings(candidate.settings.id)
const active = activated.settings
const verification = activated.verification ?? candidate.verification
setSettings(active)
setSaveMessage(`设置已验证并启用:文档${secondsLabel(active.document_refresh_seconds)}、资源${secondsLabel(active.resource_refresh_seconds)}、停滞${secondsLabel(active.stalled_after_seconds)}、finalizing ${secondsLabel(active.finalizing_after_seconds)}、入库并发 ${active.ingestion_concurrency}、测试地址 ${active.test_weknora_base_url || '未配置'}、生产地址 ${active.production_weknora_base_url || '未配置'}、生产 ID ${active.production_tenant_id || '未配置'}、知识库 ID ${active.production_knowledge_base_id || '未配置'};旧版本已保留用于审计。${verification ? `核验:${verification.message}` : ''}`)
setSaveMessage(
`设置已验证并启用:文档${secondsLabel(active.document_refresh_seconds)}、资源${secondsLabel(active.resource_refresh_seconds)}、停滞${secondsLabel(active.stalled_after_seconds)}、finalizing ${secondsLabel(active.finalizing_after_seconds)}、入库并发 ${active.ingestion_concurrency}、测试地址 ${active.test_weknora_base_url || '未配置'}、生产地址 ${active.production_weknora_base_url || '未配置'}、生产 ID ${active.production_tenant_id || '未配置'}、知识库 ID ${active.production_knowledge_base_id || '未配置'};旧版本已保留用于审计。${verification ? `核验:${verification.message}` : ''}`
)
} catch (cause) {
setError(cause instanceof Error ? cause.message : '保存系统设置失败')
} finally {
setSaving(false)
}
catch (cause) { setError(cause instanceof Error ? cause.message : '保存系统设置失败') }
finally { setSaving(false) }
}
const reloadSources = useCallback(() => { setSaveMessage(null); setRevision((value) => value + 1) }, [])
return <SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={settings} productionEnabled={productionEnabled} productionBackupRestoreVerified={productionBackupRestoreVerified} routingCapabilities={routingCapabilities} loading={loading} saving={saving} error={error} saveMessage={saveMessage} onSave={(input) => void save(input)} onSourcesChanged={reloadSources} onRefresh={reloadSources}/>
const reloadSources = useCallback(() => {
setSaveMessage(null)
setRevision((value) => value + 1)
}, [])
return (
<SystemSettingsView
sources={sources}
connections={connections}
monitor={monitor}
settings={settings}
productionEnabled={productionEnabled}
productionBackupRestoreVerified={productionBackupRestoreVerified}
routingCapabilities={routingCapabilities}
loading={loading}
saving={saving}
error={error}
saveMessage={saveMessage}
onSave={(input) => void save(input)}
onSourcesChanged={reloadSources}
onRefresh={reloadSources}
/>
)
}
+222
View File
@@ -0,0 +1,222 @@
// @ts-expect-error The test runner provides Node; the browser bundle intentionally omits @types/node.
import { readFileSync } from 'node:fs'
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, it, vi } from 'vitest'
import { VersionHistoryView } from './VersionHistory'
import type { VersionHistoryItem, VersionHistoryPage } from './versionHistory'
const releaseItem: VersionHistoryItem = {
commit_sha: '6de5d5236380ad619fe35e4bd20f49b2d967903e',
short_sha: '6de5d5236380',
parents: ['97f4b296613e23889997dd14004cd23f6c3a2c3f'],
committed_at: '2026-10-13T16:45:56+08:00',
author_display: '姚章浩',
subject: 'feat(version): 开发号随提交自动递增 + 首个正式版本 0.1.0',
body: '正文第一行\n正文第二行',
record_kind: 'release',
version_label: '0.1.0',
version_state: 'verified',
release_tags: [{ name: 'v0.1.0', url: 'https://gitea.example/Weknora/knowledge-governance/src/tag/v0.1.0' }],
release_notes: '### Added\n\n- 首个正式版本',
commit_url: 'https://gitea.example/Weknora/knowledge-governance/commit/6de5d5236380ad619fe35e4bd20f49b2d967903e',
version_reason: 'annotated_tag_and_changelog_top_match',
is_current_running: true,
}
const developmentItem: VersionHistoryItem = {
...releaseItem,
commit_sha: '950c1b429bc814d9fa7c2c1449f999a05537af21',
short_sha: '950c1b429bc8',
subject: 'feat(release): 抬档门禁',
body: '',
record_kind: 'development',
version_label: '0.1.1',
version_state: 'verified',
release_tags: [],
release_notes: '',
is_current_running: false,
}
const historicalItem: VersionHistoryItem = {
...releaseItem,
commit_sha: 'e1c5f68c0d8a4f2b9c3d5e7a1b2c3d4e5f607182',
short_sha: 'e1c5f68c0d8a',
subject: 'chore(deploy): 部署与备份脚本',
body: '',
record_kind: 'historical',
version_label: '',
version_state: 'unknown',
release_tags: [],
release_notes: '',
version_reason: 'no_baseline',
is_current_running: false,
commit_url: 'https://gitea.example/Weknora/knowledge-governance/commit/e1c5f68c0d8a4f2b9c3d5e7a1b2c3d4e5f607182',
}
const page: VersionHistoryPage = {
items: [releaseItem, developmentItem, historicalItem],
next_cursor: 'cursor-2',
has_more: true,
sync: {
available: true,
status: 'completed',
complete: true,
last_success_at: '2026-10-13T20:00:00+08:00',
fetched_count: 111,
expected_count: 111,
error_code: '',
source_head_sha: 'ad9c5d20d467…',
active_snapshot_id: 12,
repo: 'Weknora/knowledge-governance',
},
current_running: {
state: 'matched',
commit_sha: '6de5d5236380ad619fe35e4bd20f49b2d967903e',
display_version: '0.1.0',
matched_commit_sha: '6de5d5236380ad619fe35e4bd20f49b2d967903e',
},
}
const render = (over: Partial<Parameters<typeof VersionHistoryView>[0]> = {}) =>
renderToStaticMarkup(
<VersionHistoryView
page={page}
build={null}
filter="all"
loading={false}
loadingMore={false}
error={null}
notice={null}
expanded={null}
canSync={false}
onFilter={vi.fn()}
onLoadMore={vi.fn()}
onSync={vi.fn()}
onExpand={vi.fn()}
{...over}
/>
)
describe('VersionHistoryView', () => {
it('lists commits newest-first with kind badges, short sha, times and links', () => {
const html = render()
expect(html).toContain('版本记录')
expect(html).toContain('正式版本')
expect(html).toContain('开发版本')
expect(html).toContain('历史提交')
expect(html).toContain('0.1.0')
expect(html).toContain('0.1.1')
expect(html).toContain('950c1b429bc8')
expect(html).toContain('查看提交')
expect(html).toContain('查看 tag v0.1.0')
expect(html.indexOf('0.1.0')).toBeLessThan(html.indexOf('0.1.1'))
})
it('marks only the exact-match commit as current running', () => {
const html = render()
const flags = html.match(/当前运行/g) ?? []
// 顶部一句「当前运行:…」+ 恰好一个条目徽标
expect(flags.length).toBe(2)
expect(html).toContain('已匹配到下面的提交')
})
it('never labels a commit when the running identity is unknown', () => {
const html = render({
page: {
...page,
current_running: { state: 'unknown', commit_sha: '', display_version: 'dev', matched_commit_sha: '' },
},
})
expect(html).toContain('当前运行版本未知')
expect(html).not.toContain('当前运行</span>')
expect(html).not.toContain('已匹配到下面的提交')
})
it('does not invent a version number for unverified history commits', () => {
const html = render()
const start = html.indexOf('历史提交 · e1c5f68c0d8a')
expect(start).toBeGreaterThan(-1)
expect(html).toContain('版本号未能核验:找不到可核验的发布基线')
expect(html).not.toMatch(/历史提交 · e1c5f68c0d8a[\s\S]{0,200}?\d+\.\d+\.\d+[\s\S]{0,40}?版本号未能核验/)
})
it('keeps two commits that resolve to the same number as separate entries', () => {
const sameNumber: VersionHistoryItem = {
...developmentItem,
commit_sha: 'c'.repeat(40),
short_sha: 'cccccccccccc',
subject: '另一条同号提交',
}
const html = render({ page: { ...page, items: [developmentItem, sameNumber] } })
expect(html).toContain('950c1b429bc8')
expect(html).toContain('cccccccccccc')
expect((html.match(/0\.1\.1/g) ?? []).length).toBe(2)
})
it('shows an honest empty state and never offers tag/publish/deploy actions', () => {
const html = render({ page: { ...page, items: [], has_more: false } })
expect(html).toContain('暂无记录')
expect(html).not.toContain('打 tag')
expect(html).not.toContain('发布</button>')
expect(html).not.toContain('部署</button>')
// 非管理员看不到同步入口
expect(html).not.toContain('同步记录</button>')
})
it('exposes the admin sync entry only for admins and reflects sync failures', () => {
const html = render({ canSync: true })
expect(html).toContain('同步记录')
const failed = render({
canSync: true,
page: {
...page,
sync: { ...page.sync, status: 'failed', complete: false, error_code: 'gitea_unreachable' },
},
})
expect(failed).toContain('上次同步失败(gitea_unreachable)')
expect(failed).toContain('仍展示上次成功的数据')
expect(failed).toContain('同步失败')
})
it('degrades to "not wired" instead of failing when the source is unconfigured', () => {
const html = render({
page: { ...page, items: [], sync: { ...page.sync, available: false, status: '' } },
})
expect(html).toContain('未接线')
expect(html).not.toContain('同步记录</button>')
})
it('never renders a tag link without a URL (an empty href looks broken)', () => {
const withURL = render()
expect(withURL).toContain('查看 tag v0.1.0')
expect(withURL).toContain('https://gitea.example/Weknora/knowledge-governance/src/tag/v0.1.0')
const withoutURL = render({
page: {
...page,
items: [{ ...releaseItem, release_tags: [{ name: 'v0.1.0', url: '' }] }],
},
})
expect(withoutURL).not.toContain('查看 tag')
})
it('keeps mobile single-column rules so nothing overflows horizontally', () => {
const css = readFileSync(new URL('./versionHistory.css', import.meta.url), 'utf8')
expect(css).toMatch(/@media \(max-width: 760px\)[\s\S]*?\.version-history[\s\S]*?overflow-wrap:\s*anywhere/)
expect(css).toMatch(
/@media \(max-width: 760px\)[\s\S]*?\.version-history-entry-head\s*\{\s*flex-direction:\s*column/
)
})
it('renders commit bodies as text, never as markup', () => {
const html = render({
expanded: developmentItem.commit_sha,
page: {
...page,
items: [{ ...developmentItem, body: '<img src=x onerror=alert(1)>', release_notes: '<script>x</script>' }],
},
})
expect(html).not.toContain('<img src=x')
expect(html).not.toContain('<script>x</script>')
expect(html).toContain('&lt;img src=x')
})
})
+288
View File
@@ -0,0 +1,288 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
fetchVersionHistory,
fetchBuildInfo,
reasonLabel,
syncVersionHistory,
type BuildInfo,
type VersionHistoryItem,
type VersionHistoryPage,
} from './versionHistory'
import { useOptionalAuth } from './auth'
import './versionHistory.css'
// 「版本记录」页:追踪**所有已进入远端 main 的提交**,按提交时间倒序。
// 只读:不提供打 tag / 发布 / 部署按钮;版本号只按证据展示,证据不足就说"历史提交"。
const FILTERS: ReadonlyArray<{ id: string; label: string }> = [
{ id: 'all', label: '全部' },
{ id: 'release', label: '正式' },
{ id: 'development', label: '开发' },
{ id: 'historical', label: '历史' },
]
const stamp = (value: string) => (value ? new Date(value).toLocaleString('zh-CN', { hour12: false }) : '—')
const kindLabel: Record<string, string> = { release: '正式版本', development: '开发版本', historical: '历史提交' }
const runningText = (running: VersionHistoryPage['current_running']) => {
if (running.state === 'matched')
return `当前运行:${running.display_version}(${running.commit_sha.slice(0, 12)},已匹配到下面的提交)`
if (running.state === 'development') {
return `当前运行:开发构建 ${running.display_version}(${running.commit_sha.slice(0, 12)})—— 这份产物不在已同步的提交里`
}
return '当前运行版本未知(产物没有注入可核验的提交标识)'
}
const syncText = (sync: VersionHistoryPage['sync']) => {
if (!sync.available) return '未接线:还没有配置只读的仓库来源'
if (!sync.status) return '尚未同步过'
if (sync.status === 'running' || sync.status === 'pending') return `同步中(${sync.status})`
if (sync.status === 'failed') {
return `上次同步失败(${sync.error_code || '未知原因'})· 仍展示上次成功的数据(${stamp(sync.last_success_at)})`
}
if (!sync.complete) {
return `上次同步:部分历史(${sync.fetched_count}/${sync.expected_count ?? '?'})· ${stamp(sync.last_success_at)}`
}
return `最后同步:${stamp(sync.last_success_at)}(${sync.fetched_count} 条提交)`
}
interface ViewProps {
page: VersionHistoryPage | null
build: BuildInfo | null
filter: string
loading: boolean
loadingMore: boolean
error: string | null
notice: string | null
expanded: string | null
canSync: boolean
onFilter: (id: string) => void
onLoadMore: () => void
onSync: () => void
onExpand: (sha: string | null) => void
}
export function VersionHistoryView(props: ViewProps) {
const { page, build } = props
const items = page?.items ?? []
return (
<section className="version-history" aria-label="版本记录">
<header className="version-history-header">
<div>
<h2>版本记录</h2>
<p>
{page
? runningText(page.current_running)
: build
? `当前运行:${build.identity_available ? build.display_version : '未知'}`
: '当前运行版本未知'}
</p>
<p className="version-history-sync-line">
{page ? syncText(page.sync) : '正在读取同步状态…'}
{page?.sync.status === 'running' || page?.sync.status === 'pending' ? (
<span className="version-history-badge pending">同步中</span>
) : null}
{page && page.sync.status === 'failed' ? (
<span className="version-history-badge warn">同步失败</span>
) : null}
</p>
</div>
{props.canSync ? (
<button type="button" onClick={props.onSync} disabled={props.loading || !page?.sync.available}>
{page?.sync.status === 'running' || page?.sync.status === 'pending' ? '同步进行中…' : '同步记录'}
</button>
) : null}
</header>
{props.error ? (
<div className="error-banner" role="alert">
{props.error}
</div>
) : null}
{props.notice ? <div className="version-history-notice">{props.notice}</div> : null}
<nav className="version-history-filters" aria-label="按记录类型筛选">
{FILTERS.map((entry) => (
<button
type="button"
key={entry.id}
className={props.filter === entry.id ? 'active' : ''}
aria-pressed={props.filter === entry.id}
onClick={() => props.onFilter(entry.id)}
>
{entry.label}
</button>
))}
</nav>
{items.length === 0 && !props.loading ? (
<div className="empty-state">
{page?.sync.available
? '暂无记录(先同步一次,或该筛选下没有条目)'
: '版本记录未接线:等待配置只读的仓库来源'}
</div>
) : null}
<ol className="version-history-timeline">
{items.map((item) => (
<TimelineEntry
key={item.commit_sha}
item={item}
// 「当前运行」以页面级判定为准(同一份事实),条目标志只做兜底
currentMatchedSHA={page?.current_running.state === 'matched' ? page.current_running.matched_commit_sha : ''}
expanded={props.expanded === item.commit_sha}
onExpand={() => props.onExpand(props.expanded === item.commit_sha ? null : item.commit_sha)}
/>
))}
</ol>
{props.loading ? <div className="empty-state">正在读取版本记录…</div> : null}
{page?.has_more ? (
<button type="button" className="version-history-more" onClick={props.onLoadMore} disabled={props.loadingMore}>
{props.loadingMore ? '正在加载…' : '加载更多'}
</button>
) : null}
</section>
)
}
function TimelineEntry({
item,
currentMatchedSHA,
expanded,
onExpand,
}: {
item: VersionHistoryItem
currentMatchedSHA: string
expanded: boolean
onExpand: () => void
}) {
const isRelease = item.record_kind === 'release' && item.version_state === 'verified'
const heading = isRelease ? item.version_label : item.version_label || `历史提交 · ${item.short_sha}`
const note = isRelease ? item.release_notes : ''
const hasDetail = Boolean(item.body) || Boolean(note)
return (
<li className={`version-history-entry ${item.record_kind}`}>
<div className="version-history-entry-head">
<strong>{heading}</strong>
<span>{stamp(item.committed_at)}</span>
</div>
<div className="version-history-entry-meta">
<span className={`version-history-badge ${item.record_kind}`}>{kindLabel[item.record_kind] ?? '历史提交'}</span>
<span className="version-history-sha">{item.short_sha}</span>
{item.commit_sha && item.commit_sha === currentMatchedSHA ? (
<span className="version-history-badge current">当前运行</span>
) : null}
<span className="version-history-author">{item.author_display}</span>
</div>
<p className="version-history-subject">{item.subject}</p>
{!item.version_label && item.record_kind === 'historical' ? (
<p className="version-history-reason">版本号未能核验:{reasonLabel(item.version_reason)}</p>
) : null}
{hasDetail ? (
<>
<button type="button" className="version-history-toggle" onClick={onExpand} aria-expanded={expanded}>
{expanded ? '收起详情' : '展开详情'}
</button>
{expanded ? (
<div className="version-history-detail">
{item.record_kind === 'release' && note ? <pre>{note}</pre> : null}
{item.body ? <pre>{item.body}</pre> : null}
</div>
) : null}
</>
) : null}
<div className="version-history-links">
{item.commit_url ? (
<a href={item.commit_url} target="_blank" rel="noreferrer noopener">
查看提交
</a>
) : null}
{/* 没有链接就不渲染:空 href 点下去像"没反应/空白",比不显示更糟 */}
{item.release_tags
.filter((tag) => tag.url)
.map((tag) => (
<a key={tag.name} href={tag.url} target="_blank" rel="noreferrer noopener">
查看 tag {tag.name}
</a>
))}
</div>
</li>
)
}
export function VersionHistory() {
const auth = useOptionalAuth()
const [page, setPage] = useState<VersionHistoryPage | null>(null)
const [build, setBuild] = useState<BuildInfo | null>(null)
const [filter, setFilter] = useState('all')
const [loading, setLoading] = useState(true)
const [loadingMore, setLoadingMore] = useState(false)
const [error, setError] = useState<string | null>(null)
const [notice, setNotice] = useState<string | null>(null)
const [expanded, setExpanded] = useState<string | null>(null)
const cursor = useRef('')
const load = useCallback(async (kind: string, append: boolean) => {
append ? setLoadingMore(true) : setLoading(true)
try {
const next = await fetchVersionHistory({ kind, cursor: append ? cursor.current : '' })
cursor.current = next.next_cursor
setPage((current) => (append && current ? { ...next, items: [...current.items, ...next.items] } : next))
setError(null)
} catch (cause) {
setError(cause instanceof Error ? cause.message : '加载版本记录失败')
} finally {
append ? setLoadingMore(false) : setLoading(false)
}
}, [])
useEffect(() => {
void load(filter, false)
}, [filter, load])
useEffect(() => {
let cancelled = false
void fetchBuildInfo()
.then((value) => {
if (!cancelled) setBuild(value)
})
.catch(() => undefined)
return () => {
cancelled = true
}
}, [])
// 只有管理员能看到同步入口;其他人只能看(服务端也会再判一次角色)
const canSync = auth?.identity?.role === 'admin'
const onSync = useCallback(async () => {
setNotice(null)
try {
const accepted = await syncVersionHistory()
setNotice(accepted.reused ? '已有同步任务在跑,本次复用它。' : '已提交同步任务,稍后刷新即可看到新记录。')
await load(filter, false)
} catch (cause) {
setError(cause instanceof Error ? cause.message : '触发同步失败')
}
}, [filter, load])
const viewProps = useMemo<ViewProps>(
() => ({
page,
build,
filter,
loading,
loadingMore,
error,
notice,
expanded,
canSync,
onFilter: setFilter,
onLoadMore: () => void load(filter, true),
onSync: () => void onSync(),
onExpand: setExpanded,
}),
[page, build, filter, loading, loadingMore, error, notice, expanded, canSync, load, onSync]
)
return <VersionHistoryView {...viewProps} />
}
+841 -62
View File
@@ -1,64 +1,843 @@
.system-settings{max-width:1500px}.settings-role-strip{display:flex;gap:10px;margin-bottom:12px}.settings-role-strip span{border-radius:8px;padding:8px 11px;font-size:10px}.engineer-role{background:var(--c-run-bg);color:var(--c-run)}.admin-role{background:var(--bg-soft);color:var(--ink-mute)}.settings-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}.settings-panel{min-width:0;border:1px solid var(--border-base);border-radius:12px;padding:15px;background:var(--bg-panel)}.settings-panel.wide{grid-column:1/-1}.settings-panel h2{margin:0 0 12px;color:var(--ink-base);font-size:14px}.settings-panel dl{display:grid;grid-template-columns:1fr auto;gap:8px;margin:0;color:var(--ink-mute);font-size:10px}.settings-panel dd{margin:0;color:var(--ink-base);font-weight:700}.settings-panel dd.ok{color:var(--c-done)}.settings-panel dd.off,.settings-panel .production span{color:var(--c-fail)}.environment-cards{display:grid;grid-template-columns:1fr 1fr;gap:10px}.environment-cards article{display:grid;grid-template-columns:1fr auto;gap:6px;border:1px solid var(--border-base);border-radius:9px;padding:11px;background:var(--bg-soft)}.environment-cards b{color:var(--ink-base);font-size:11px}.environment-cards span{color:var(--c-done);font-size:10px}.environment-cards small{grid-column:1/-1;color:var(--ink-mute);font-size:9px}.environment-cards button{grid-column:2;padding:5px 7px}.mapping-row{display:flex;flex-wrap:wrap;gap:8px;margin-top:10px}.mapping-row>*{border-radius:6px;padding:6px 8px;background:var(--border-soft);color:var(--ink-mute);font-size:9px}.dependency-grid{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:8px}.dependency-grid article{display:grid;gap:4px;border-radius:8px;padding:9px;background:var(--bg-soft)}.dependency-grid span{color:var(--ink-mute);font-size:9px}.dependency-grid b{color:var(--ink-base);font-size:10px}.dependency-grid small{color:var(--ink-mute);font-size:8px;line-height:1.5}.target-list{display:grid;gap:7px;margin:0;padding:0;list-style:none}.target-list li{display:flex;justify-content:space-between;gap:10px;color:var(--ink-mute);font-size:10px}.target-list b{color:var(--c-fail)}.settings-panel>button{margin-top:12px;padding:7px 10px}.settings-panel>small{display:block;margin-top:7px;color:var(--ink-mute);font-size:8px}.safe-setting-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px}.safe-setting-grid label{display:grid;gap:6px;color:var(--ink-mute);font-size:10px}.safe-setting-grid select{border:1px solid var(--border-strong);border-radius:7px;padding:8px;background:var(--bg-panel);color:var(--ink-base)}.locked-gates{display:flex;flex-wrap:wrap;gap:7px;margin-top:11px}.locked-gates span{border-radius:6px;padding:6px 8px;background:var(--c-fail-bg);color:var(--c-fail);font-size:9px}@media(max-width:900px){.dependency-grid{grid-template-columns:repeat(3,minmax(0,1fr))}.safe-setting-grid{grid-template-columns:1fr 1fr}}@media(max-width:650px){.settings-grid,.environment-cards{grid-template-columns:1fr}.settings-panel.wide{grid-column:auto}.dependency-grid,.safe-setting-grid{grid-template-columns:1fr}.settings-role-strip{flex-direction:column}}
.settings-section-heading{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;margin-bottom:14px}.settings-section-heading h2{margin-bottom:4px}.settings-section-heading p{margin:0;color:var(--ink-mute);font-size:10px}.settings-section-heading button{padding:7px 10px;box-shadow:none}.settings-source-list{display:grid;gap:9px}.settings-source-row{display:grid;grid-template-columns:minmax(170px,.8fr) minmax(420px,2fr) minmax(130px,.55fr) auto;align-items:center;gap:14px;border:1px solid var(--border-base);border-radius:10px;padding:12px;background:var(--bg-page)}.settings-source-name{display:grid;gap:4px}.settings-source-name strong{color:var(--ink-base);font-size:12px}.settings-source-name span{color:var(--ink-mute);font-size:9px}.settings-source-row dl{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:8px}.settings-source-row dl div{display:grid;gap:3px}.settings-source-row dt{color:var(--ink-mute);font-size:8px}.settings-source-row dd{overflow-wrap:anywhere;color:var(--ink-base);font-size:9px;font-weight:650}.settings-source-row label{display:grid;gap:5px;color:var(--ink-mute);font-size:9px}.settings-source-row select{border:1px solid #c9d9e4;border-radius:7px;padding:7px;background:var(--bg-panel);color:var(--ink-base)}.settings-source-row>button{padding:7px 9px;box-shadow:none}.dependency-grid{margin-top:12px}.storage-settings-grid{display:grid;grid-template-columns:1fr 1fr minmax(220px,.8fr);gap:14px}.storage-settings-grid>dl,.storage-settings-grid>.target-list{border:1px solid var(--border-base);border-radius:9px;padding:12px;background:var(--bg-soft)}@media(max-width:1100px){.settings-source-row{grid-template-columns:1fr 1fr}.settings-source-row dl{grid-column:1/-1}.storage-settings-grid{grid-template-columns:1fr 1fr}.storage-settings-grid>.target-list{grid-column:1/-1}}@media(max-width:700px){.settings-section-heading{flex-direction:column}.settings-source-row,.settings-source-row dl,.storage-settings-grid{grid-template-columns:1fr}.settings-source-row dl{grid-column:auto}.storage-settings-grid>.target-list{grid-column:auto}}.settings-layout{display:grid;grid-template-columns:200px minmax(0,1fr);gap:18px;align-items:start}
.settings-nav{display:flex;flex-direction:column;gap:6px;position:sticky;top:16px}
.settings-nav button{border:1px solid transparent;background:transparent;text-align:left;padding:9px 12px;border-radius:8px;font:inherit;cursor:pointer;color:var(--ink-base)}
.settings-nav button:hover{background:var(--border-soft)}
.settings-nav button.active{background:var(--c-run);color:var(--bg-panel);font-weight:600}
.settings-content{display:flex;flex-direction:column;gap:14px;min-width:0}
.source-schedule-form{display:flex;flex-wrap:wrap;gap:10px;align-items:end;padding-top:6px}
.source-schedule-form label{display:flex;flex-direction:column;gap:4px;font-size:13px;color:var(--ink-base)}
.source-schedule-form select,.source-schedule-form input{padding:6px 8px;border:1px solid var(--border-strong);border-radius:6px;font:inherit;background:var(--bg-panel)}
.source-schedule-actions{display:flex;gap:8px;align-items:end}
button.danger{background:var(--c-fail);color:var(--bg-panel);border:none;padding:8px 14px;border-radius:8px;font:inherit;cursor:pointer}
button.danger:hover{background:var(--c-fail)}
button.danger:disabled{background:var(--c-fail-border);cursor:not-allowed}
button.link{background:none;border:none;color:var(--c-run);cursor:pointer;text-decoration:underline;font:inherit;padding:4px}
.manual-source-note{color:var(--ink-mute);font-size:13px}
.error-message{color:var(--c-fail);font-size:13px;margin:4px 0}
.revision-list{list-style:none;margin:8px 0 0;padding:8px 10px;background:var(--bg-soft);border-radius:8px;display:flex;flex-direction:column;gap:6px;font-size:13px}
.revision-list li{display:flex;gap:8px;align-items:baseline;flex-wrap:wrap}
.revision-list span{color:var(--c-run);font-weight:600}
.revision-list small{color:var(--ink-mute)}
.empty-inline{color:var(--ink-mute);font-size:13px}
.modal-backdrop{position:fixed;inset:0;background:rgba(10,25,40,.45);display:flex;align-items:center;justify-content:center;z-index:50;padding:16px}
.modal-card{background:var(--bg-panel);border-radius:12px;padding:20px;max-width:420px;box-shadow:0 18px 48px rgba(9,28,46,.35)}
.modal-card h3{margin:0 0 8px}
.modal-card p{color:var(--ink-base);font-size:14px;line-height:1.6}
.modal-actions{display:flex;gap:10px;justify-content:flex-end;margin-top:14px}
@media (max-width:900px){.settings-layout{grid-template-columns:1fr}.settings-nav{position:static;flex-direction:row;flex-wrap:wrap}}
.kb-binding-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin:12px 0}.kb-binding-side{display:grid;gap:4px;border:1px solid var(--border-base);border-radius:9px;padding:11px;background:var(--bg-soft)}.kb-binding-side.bound{border-color:var(--c-done)}.kb-binding-side.warn{border-color:var(--c-fail)}.kb-binding-side b{color:var(--ink-base);font-size:11px}.kb-binding-side span{color:var(--c-done);font-size:11px;word-break:break-all}.kb-binding-side.warn span{color:var(--c-fail)}.kb-binding-side small{color:var(--ink-mute);font-size:9px}.kb-binding-editor{display:grid;gap:10px;border-top:1px dashed var(--border-base);margin-top:8px;padding-top:12px}.kb-binding-editor label{display:grid;gap:6px;color:var(--ink-mute);font-size:10px}.kb-binding-editor select,.kb-binding-editor input{border:1px solid var(--border-strong);border-radius:7px;padding:8px;background:var(--bg-panel);color:var(--ink-base)}.kb-binding-editor button{justify-self:start;padding:7px 10px}@media(max-width:650px){.kb-binding-grid{grid-template-columns:1fr}}.hint{color:var(--ink-mute);font-size:10px;margin:4px 0}
.dingtalk-session-control{display:flex;flex-direction:column;gap:4px;align-self:end}
.dingtalk-qr-card{max-width:440px;text-align:center}
.dingtalk-qr-hint{color:var(--ink-mute);font-size:13px;min-height:20px}
.dingtalk-qr-image{display:block;margin:12px auto;width:320px;height:320px;image-rendering:pixelated;border:12px solid #fff;border-radius:4px;background:#fff;box-sizing:content-box}
.dingtalk-qr-loading{display:grid;place-items:center;margin:12px auto;width:320px;height:320px;max-width:80vw;max-height:80vw;border:12px solid #fff;border-radius:4px;background:#fff;box-sizing:content-box}
.dingtalk-qr-loading span{width:42px;height:42px;border:4px solid #dbe4ee;border-top-color:var(--brand);border-radius:50%;animation:dingtalk-qr-spin .8s linear infinite}
@keyframes dingtalk-qr-spin{to{transform:rotate(360deg)}}
.dingtalk-qr-card .modal-actions{justify-content:center}
.filename-filter-editor{flex-basis:100%;margin-top:10px;padding:12px;border:1px solid var(--border-base);border-radius:10px;background:var(--bg-soft)}
.filename-filter-heading{display:flex;justify-content:space-between;gap:10px;margin-bottom:7px}.filename-filter-heading div{display:grid;gap:3px}.filename-filter-heading small{color:var(--ink-mute)}
.filename-filter-inherited,.filename-filter-direct{display:flex;align-items:center;gap:6px;flex-wrap:wrap;margin:6px 0}.filename-filter-inherited span,.filename-filter-direct span{font-size:10px;color:var(--ink-mute)}
.filename-filter-editor code{padding:2px 7px;border-radius:999px;background:#eaf2ff;color:#2456a6;font-family:inherit;font-size:11px}
.filename-filter-form{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin:9px 0}.filename-filter-form input{min-width:220px;flex:1;padding:7px 9px;border:1px solid var(--border-strong);border-radius:7px;background:var(--bg-panel)}
.filename-filter-modes{display:flex;gap:12px;align-self:center;font-size:11px;color:var(--ink-base)}.filename-filter-modes label{display:flex;gap:4px;align-items:center;cursor:pointer}
.filename-filter-groups{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:6px 14px;margin:8px 0}.filename-filter-group{display:grid;gap:4px}.filename-filter-group>span{color:var(--ink-mute);font-size:9px}
.filename-filter-group>div{display:flex;flex-wrap:wrap;gap:4px}.filename-filter-group button{border:1px solid var(--border-base);background:var(--bg-panel);color:var(--ink-base);border-radius:999px;padding:2px 8px;font-size:10px;font-family:inherit;cursor:pointer}
.filename-filter-group button.picked{background:var(--c-run);border-color:var(--c-run);color:var(--bg-panel);font-weight:650}.filename-filter-group button.blocked{color:var(--c-fail)}
@media(max-width:900px){.filename-filter-groups{grid-template-columns:1fr 1fr}}
.system-settings {
max-width: 1500px;
}
.settings-role-strip {
display: flex;
gap: 10px;
margin-bottom: 12px;
}
.settings-role-strip span {
border-radius: 8px;
padding: 8px 11px;
font-size: 10px;
}
.engineer-role {
background: var(--c-run-bg);
color: var(--c-run);
}
.admin-role {
background: var(--bg-soft);
color: var(--ink-mute);
}
.settings-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 14px;
}
.settings-panel {
min-width: 0;
border: 1px solid var(--border-base);
border-radius: 12px;
padding: 15px;
background: var(--bg-panel);
}
.settings-panel.wide {
grid-column: 1/-1;
}
.settings-panel h2 {
margin: 0 0 12px;
color: var(--ink-base);
font-size: 14px;
}
.settings-panel dl {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px;
margin: 0;
color: var(--ink-mute);
font-size: 10px;
}
.settings-panel dd {
margin: 0;
color: var(--ink-base);
font-weight: 700;
}
.settings-panel dd.ok {
color: var(--c-done);
}
.settings-panel dd.off,
.settings-panel .production span {
color: var(--c-fail);
}
.environment-cards {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
.environment-cards article {
display: grid;
grid-template-columns: 1fr auto;
gap: 6px;
border: 1px solid var(--border-base);
border-radius: 9px;
padding: 11px;
background: var(--bg-soft);
}
.environment-cards b {
color: var(--ink-base);
font-size: 11px;
}
.environment-cards span {
color: var(--c-done);
font-size: 10px;
}
.environment-cards small {
grid-column: 1/-1;
color: var(--ink-mute);
font-size: 9px;
}
.environment-cards button {
grid-column: 2;
padding: 5px 7px;
}
.mapping-row {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 10px;
}
.mapping-row > * {
border-radius: 6px;
padding: 6px 8px;
background: var(--border-soft);
color: var(--ink-mute);
font-size: 9px;
}
.dependency-grid {
display: grid;
grid-template-columns: repeat(6, minmax(0, 1fr));
gap: 8px;
}
.dependency-grid article {
display: grid;
gap: 4px;
border-radius: 8px;
padding: 9px;
background: var(--bg-soft);
}
.dependency-grid span {
color: var(--ink-mute);
font-size: 9px;
}
.dependency-grid b {
color: var(--ink-base);
font-size: 10px;
}
.dependency-grid small {
color: var(--ink-mute);
font-size: 8px;
line-height: 1.5;
}
.target-list {
display: grid;
gap: 7px;
margin: 0;
padding: 0;
list-style: none;
}
.target-list li {
display: flex;
justify-content: space-between;
gap: 10px;
color: var(--ink-mute);
font-size: 10px;
}
.target-list b {
color: var(--c-fail);
}
.settings-panel > button {
margin-top: 12px;
padding: 7px 10px;
}
.settings-panel > small {
display: block;
margin-top: 7px;
color: var(--ink-mute);
font-size: 8px;
}
.safe-setting-grid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 10px;
}
.safe-setting-grid label {
display: grid;
gap: 6px;
color: var(--ink-mute);
font-size: 10px;
}
.safe-setting-grid select {
border: 1px solid var(--border-strong);
border-radius: 7px;
padding: 8px;
background: var(--bg-panel);
color: var(--ink-base);
}
.locked-gates {
display: flex;
flex-wrap: wrap;
gap: 7px;
margin-top: 11px;
}
.locked-gates span {
border-radius: 6px;
padding: 6px 8px;
background: var(--c-fail-bg);
color: var(--c-fail);
font-size: 9px;
}
@media (max-width: 900px) {
.dependency-grid {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.safe-setting-grid {
grid-template-columns: 1fr 1fr;
}
}
@media (max-width: 650px) {
.settings-grid,
.environment-cards {
grid-template-columns: 1fr;
}
.settings-panel.wide {
grid-column: auto;
}
.dependency-grid,
.safe-setting-grid {
grid-template-columns: 1fr;
}
.settings-role-strip {
flex-direction: column;
}
}
.settings-section-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
margin-bottom: 14px;
}
.settings-section-heading h2 {
margin-bottom: 4px;
}
.settings-section-heading p {
margin: 0;
color: var(--ink-mute);
font-size: 10px;
}
.settings-section-heading button {
padding: 7px 10px;
box-shadow: none;
}
.settings-source-list {
display: grid;
gap: 9px;
}
.settings-source-row {
display: grid;
grid-template-columns: minmax(170px, 0.8fr) minmax(420px, 2fr) minmax(130px, 0.55fr) auto;
align-items: center;
gap: 14px;
border: 1px solid var(--border-base);
border-radius: 10px;
padding: 12px;
background: var(--bg-page);
}
.settings-source-name {
display: grid;
gap: 4px;
}
.settings-source-name strong {
color: var(--ink-base);
font-size: 12px;
}
.settings-source-name span {
color: var(--ink-mute);
font-size: 9px;
}
.settings-source-row dl {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 8px;
}
.settings-source-row dl div {
display: grid;
gap: 3px;
}
.settings-source-row dt {
color: var(--ink-mute);
font-size: 8px;
}
.settings-source-row dd {
overflow-wrap: anywhere;
color: var(--ink-base);
font-size: 9px;
font-weight: 650;
}
.settings-source-row label {
display: grid;
gap: 5px;
color: var(--ink-mute);
font-size: 9px;
}
.settings-source-row select {
border: 1px solid #c9d9e4;
border-radius: 7px;
padding: 7px;
background: var(--bg-panel);
color: var(--ink-base);
}
.settings-source-row > button {
padding: 7px 9px;
box-shadow: none;
}
.dependency-grid {
margin-top: 12px;
}
.storage-settings-grid {
display: grid;
grid-template-columns: 1fr 1fr minmax(220px, 0.8fr);
gap: 14px;
}
.storage-settings-grid > dl,
.storage-settings-grid > .target-list {
border: 1px solid var(--border-base);
border-radius: 9px;
padding: 12px;
background: var(--bg-soft);
}
@media (max-width: 1100px) {
.settings-source-row {
grid-template-columns: 1fr 1fr;
}
.settings-source-row dl {
grid-column: 1/-1;
}
.storage-settings-grid {
grid-template-columns: 1fr 1fr;
}
.storage-settings-grid > .target-list {
grid-column: 1/-1;
}
}
@media (max-width: 700px) {
.settings-section-heading {
flex-direction: column;
}
.settings-source-row,
.settings-source-row dl,
.storage-settings-grid {
grid-template-columns: 1fr;
}
.settings-source-row dl {
grid-column: auto;
}
.storage-settings-grid > .target-list {
grid-column: auto;
}
}
.settings-layout {
display: grid;
grid-template-columns: 200px minmax(0, 1fr);
gap: 18px;
align-items: start;
}
.settings-nav {
display: flex;
flex-direction: column;
gap: 6px;
position: sticky;
top: 16px;
}
.settings-nav button {
border: 1px solid transparent;
background: transparent;
text-align: left;
padding: 9px 12px;
border-radius: 8px;
font: inherit;
cursor: pointer;
color: var(--ink-base);
}
.settings-nav button:hover {
background: var(--border-soft);
}
.settings-nav button.active {
background: var(--c-run);
color: var(--bg-panel);
font-weight: 600;
}
.settings-content {
display: flex;
flex-direction: column;
gap: 14px;
min-width: 0;
}
.source-schedule-form {
display: flex;
flex-wrap: wrap;
gap: 10px;
align-items: end;
padding-top: 6px;
}
.source-schedule-form label {
display: flex;
flex-direction: column;
gap: 4px;
font-size: 13px;
color: var(--ink-base);
}
.source-schedule-form select,
.source-schedule-form input {
padding: 6px 8px;
border: 1px solid var(--border-strong);
border-radius: 6px;
font: inherit;
background: var(--bg-panel);
}
.source-schedule-actions {
display: flex;
gap: 8px;
align-items: end;
}
button.danger {
background: var(--c-fail);
color: var(--bg-panel);
border: none;
padding: 8px 14px;
border-radius: 8px;
font: inherit;
cursor: pointer;
}
button.danger:hover {
background: var(--c-fail);
}
button.danger:disabled {
background: var(--c-fail-border);
cursor: not-allowed;
}
button.link {
background: none;
border: none;
color: var(--c-run);
cursor: pointer;
text-decoration: underline;
font: inherit;
padding: 4px;
}
.manual-source-note {
color: var(--ink-mute);
font-size: 13px;
}
.error-message {
color: var(--c-fail);
font-size: 13px;
margin: 4px 0;
}
.revision-list {
list-style: none;
margin: 8px 0 0;
padding: 8px 10px;
background: var(--bg-soft);
border-radius: 8px;
display: flex;
flex-direction: column;
gap: 6px;
font-size: 13px;
}
.revision-list li {
display: flex;
gap: 8px;
align-items: baseline;
flex-wrap: wrap;
}
.revision-list span {
color: var(--c-run);
font-weight: 600;
}
.revision-list small {
color: var(--ink-mute);
}
.empty-inline {
color: var(--ink-mute);
font-size: 13px;
}
.modal-backdrop {
position: fixed;
inset: 0;
background: rgba(10, 25, 40, 0.45);
display: flex;
align-items: center;
justify-content: center;
z-index: 50;
padding: 16px;
}
.modal-card {
background: var(--bg-panel);
border-radius: 12px;
padding: 20px;
max-width: 420px;
box-shadow: 0 18px 48px rgba(9, 28, 46, 0.35);
}
.modal-card h3 {
margin: 0 0 8px;
}
.modal-card p {
color: var(--ink-base);
font-size: 14px;
line-height: 1.6;
}
.modal-actions {
display: flex;
gap: 10px;
justify-content: flex-end;
margin-top: 14px;
}
@media (max-width: 900px) {
.settings-layout {
grid-template-columns: 1fr;
}
.settings-nav {
position: static;
flex-direction: row;
flex-wrap: wrap;
}
}
.kb-binding-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
margin: 12px 0;
}
.kb-binding-side {
display: grid;
gap: 4px;
border: 1px solid var(--border-base);
border-radius: 9px;
padding: 11px;
background: var(--bg-soft);
}
.kb-binding-side.bound {
border-color: var(--c-done);
}
.kb-binding-side.warn {
border-color: var(--c-fail);
}
.kb-binding-side b {
color: var(--ink-base);
font-size: 11px;
}
.kb-binding-side span {
color: var(--c-done);
font-size: 11px;
word-break: break-all;
}
.kb-binding-side.warn span {
color: var(--c-fail);
}
.kb-binding-side small {
color: var(--ink-mute);
font-size: 9px;
}
.kb-binding-editor {
display: grid;
gap: 10px;
border-top: 1px dashed var(--border-base);
margin-top: 8px;
padding-top: 12px;
}
.kb-binding-editor label {
display: grid;
gap: 6px;
color: var(--ink-mute);
font-size: 10px;
}
.kb-binding-editor select,
.kb-binding-editor input {
border: 1px solid var(--border-strong);
border-radius: 7px;
padding: 8px;
background: var(--bg-panel);
color: var(--ink-base);
}
.kb-binding-editor button {
justify-self: start;
padding: 7px 10px;
}
@media (max-width: 650px) {
.kb-binding-grid {
grid-template-columns: 1fr;
}
}
.hint {
color: var(--ink-mute);
font-size: 10px;
margin: 4px 0;
}
.dingtalk-session-control {
display: flex;
flex-direction: column;
gap: 4px;
align-self: end;
}
.dingtalk-qr-card {
max-width: 440px;
text-align: center;
}
.dingtalk-qr-hint {
color: var(--ink-mute);
font-size: 13px;
min-height: 20px;
}
.dingtalk-qr-image {
display: block;
margin: 12px auto;
width: 320px;
height: 320px;
image-rendering: pixelated;
border: 12px solid #fff;
border-radius: 4px;
background: #fff;
box-sizing: content-box;
}
.dingtalk-qr-loading {
display: grid;
place-items: center;
margin: 12px auto;
width: 320px;
height: 320px;
max-width: 80vw;
max-height: 80vw;
border: 12px solid #fff;
border-radius: 4px;
background: #fff;
box-sizing: content-box;
}
.dingtalk-qr-loading span {
width: 42px;
height: 42px;
border: 4px solid #dbe4ee;
border-top-color: var(--brand);
border-radius: 50%;
animation: dingtalk-qr-spin 0.8s linear infinite;
}
@keyframes dingtalk-qr-spin {
to {
transform: rotate(360deg);
}
}
.dingtalk-qr-card .modal-actions {
justify-content: center;
}
.filename-filter-editor {
flex-basis: 100%;
margin-top: 10px;
padding: 12px;
border: 1px solid var(--border-base);
border-radius: 10px;
background: var(--bg-soft);
}
.filename-filter-heading {
display: flex;
justify-content: space-between;
gap: 10px;
margin-bottom: 7px;
}
.filename-filter-heading div {
display: grid;
gap: 3px;
}
.filename-filter-heading small {
color: var(--ink-mute);
}
.filename-filter-inherited,
.filename-filter-direct {
display: flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
margin: 6px 0;
}
.filename-filter-inherited span,
.filename-filter-direct span {
font-size: 10px;
color: var(--ink-mute);
}
.filename-filter-editor code {
padding: 2px 7px;
border-radius: 999px;
background: #eaf2ff;
color: #2456a6;
font-family: inherit;
font-size: 11px;
}
.filename-filter-form {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
margin: 9px 0;
}
.filename-filter-form input {
min-width: 220px;
flex: 1;
padding: 7px 9px;
border: 1px solid var(--border-strong);
border-radius: 7px;
background: var(--bg-panel);
}
.filename-filter-modes {
display: flex;
gap: 12px;
align-self: center;
font-size: 11px;
color: var(--ink-base);
}
.filename-filter-modes label {
display: flex;
gap: 4px;
align-items: center;
cursor: pointer;
}
.filename-filter-groups {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 6px 14px;
margin: 8px 0;
}
.filename-filter-group {
display: grid;
gap: 4px;
}
.filename-filter-group > span {
color: var(--ink-mute);
font-size: 9px;
}
.filename-filter-group > div {
display: flex;
flex-wrap: wrap;
gap: 4px;
}
.filename-filter-group button {
border: 1px solid var(--border-base);
background: var(--bg-panel);
color: var(--ink-base);
border-radius: 999px;
padding: 2px 8px;
font-size: 10px;
font-family: inherit;
cursor: pointer;
}
.filename-filter-group button.picked {
background: var(--c-run);
border-color: var(--c-run);
color: var(--bg-panel);
font-weight: 650;
}
.filename-filter-group button.blocked {
color: var(--c-fail);
}
@media (max-width: 900px) {
.filename-filter-groups {
grid-template-columns: 1fr 1fr;
}
}
/* 数据源发现(系统设置 → 数据源配置):列出可勾选为来源的钉钉知识库与钉盘空间。 */
.dingtalk-discovery { display: flex; flex-direction: column; gap: 10px; padding: 12px; margin-bottom: 14px; border: 1px solid var(--border, #e3e8ec); border-radius: 10px; background: var(--card, #fff); }
.dingtalk-discovery-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
.dingtalk-discovery-heading strong { display: block; font-size: 14px; }
.dingtalk-discovery-heading small { display: block; color: var(--muted-foreground, #5b6773); font-size: 12px; }
.dingtalk-discovery-groups { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
.discovery-group h4 { margin: 0 0 6px; font-size: 13px; }
.discovery-group ul { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; max-height: 220px; overflow: auto; }
.discovery-row { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 4px 6px; border-radius: 6px; }
.discovery-row:hover { background: var(--accent, #f2f5f8); }
.discovery-row label { display: flex; align-items: center; gap: 8px; cursor: pointer; }
.discovery-row.registered label { cursor: default; color: var(--muted-foreground, #5b6773); }
.discovery-row strong { font-size: 13px; font-weight: 500; }
.discovery-row small { display: block; font-size: 11px; color: var(--muted-foreground, #5b6773); }
.dingtalk-discovery-actions { display: flex; align-items: center; gap: 10px; }
.dingtalk-discovery-actions small { color: var(--muted-foreground, #5b6773); font-size: 12px; }
.dingtalk-discovery {
display: flex;
flex-direction: column;
gap: 10px;
padding: 12px;
margin-bottom: 14px;
border: 1px solid var(--border, #e3e8ec);
border-radius: 10px;
background: var(--card, #fff);
}
.dingtalk-discovery-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
}
.dingtalk-discovery-heading strong {
display: block;
font-size: 14px;
}
.dingtalk-discovery-heading small {
display: block;
color: var(--muted-foreground, #5b6773);
font-size: 12px;
}
.dingtalk-discovery-groups {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
}
.discovery-group h4 {
margin: 0 0 6px;
font-size: 13px;
}
.discovery-group ul {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 4px;
max-height: 220px;
overflow: auto;
}
.discovery-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 4px 6px;
border-radius: 6px;
}
.discovery-row:hover {
background: var(--accent, #f2f5f8);
}
.discovery-row label {
display: flex;
align-items: center;
gap: 8px;
cursor: pointer;
}
.discovery-row.registered label {
cursor: default;
color: var(--muted-foreground, #5b6773);
}
.discovery-row strong {
font-size: 13px;
font-weight: 500;
}
.discovery-row small {
display: block;
font-size: 11px;
color: var(--muted-foreground, #5b6773);
}
.dingtalk-discovery-actions {
display: flex;
align-items: center;
gap: 10px;
}
.dingtalk-discovery-actions small {
color: var(--muted-foreground, #5b6773);
font-size: 12px;
}
/* 折叠的 AList/钉钉知识库来源开关:默认收起,只露一行说明,不抢 PP 资料的视线。 */
.settings-legacy-toggle {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem 0.75rem;
margin: 0 0 0.75rem;
}
.settings-legacy-toggle small {
color: #5a6572;
font-size: 0.8rem;
line-height: 1.5;
}
+171
View File
@@ -0,0 +1,171 @@
/* 「版本记录」页:只读时间线。窄屏(≤760px,与工作台既有断点一致)单列、无横向溢出。 */
.version-history {
display: flex;
flex-direction: column;
gap: 12px;
min-width: 0;
}
.version-history-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
}
.version-history-header h2 {
margin: 0 0 4px;
font-size: 18px;
}
.version-history-header p {
margin: 0;
color: var(--muted, #666);
font-size: 13px;
}
.version-history-sync-line {
display: flex;
align-items: center;
gap: 8px;
margin-top: 4px !important;
}
.version-history-notice {
padding: 8px 10px;
border-radius: 6px;
background: rgba(64, 158, 255, 0.12);
font-size: 13px;
}
.version-history-filters {
display: flex;
gap: 8px;
flex-wrap: wrap;
}
.version-history-filters button.active {
font-weight: 600;
border-color: currentColor;
}
.version-history-timeline {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 10px;
min-width: 0;
}
.version-history-entry {
border-left: 3px solid rgba(127, 127, 127, 0.35);
padding: 10px 12px;
background: rgba(127, 127, 127, 0.06);
border-radius: 6px;
min-width: 0;
}
.version-history-entry.release {
border-left-color: #2f9e44;
}
.version-history-entry.development {
border-left-color: #1c7ed6;
}
.version-history-entry-head {
display: flex;
justify-content: space-between;
gap: 8px;
flex-wrap: wrap;
}
.version-history-entry-head strong {
font-size: 15px;
}
.version-history-entry-meta {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
margin-top: 4px;
font-size: 12px;
color: var(--muted, #666);
}
.version-history-badge {
padding: 1px 6px;
border-radius: 999px;
border: 1px solid currentColor;
font-size: 12px;
}
.version-history-badge.release {
color: #2f9e44;
}
.version-history-badge.development {
color: #1c7ed6;
}
.version-history-badge.historical {
color: #868e96;
}
.version-history-badge.current {
color: #e8590c;
}
.version-history-badge.pending {
color: #1c7ed6;
}
.version-history-badge.warn {
color: #c92a2a;
}
.version-history-sha {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
overflow-wrap: anywhere;
}
.version-history-subject {
margin: 6px 0 0;
overflow-wrap: anywhere;
}
.version-history-reason {
margin: 4px 0 0;
font-size: 12px;
color: #c92a2a;
overflow-wrap: anywhere;
}
.version-history-toggle {
margin-top: 6px;
}
.version-history-detail pre {
margin: 6px 0 0;
padding: 8px;
max-height: 320px;
overflow: auto;
background: rgba(127, 127, 127, 0.1);
border-radius: 6px;
white-space: pre-wrap;
overflow-wrap: anywhere;
font-size: 12px;
}
.version-history-links {
display: flex;
gap: 10px;
flex-wrap: wrap;
margin-top: 6px;
font-size: 13px;
}
@media (max-width: 760px) {
.version-history-header {
flex-direction: column;
align-items: stretch;
}
.version-history-entry {
padding: 8px 10px;
}
.version-history-entry-head {
flex-direction: column;
gap: 2px;
}
/* 窄屏单列:正文/标题/hash 一律换行,不出现横向滚动 */
.version-history,
.version-history-timeline,
.version-history-entry,
.version-history-subject,
.version-history-sha,
.version-history-reason {
max-width: 100%;
overflow-wrap: anywhere;
word-break: break-word;
}
.version-history-detail pre {
max-height: none;
}
}
+140
View File
@@ -0,0 +1,140 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { fetchBuildInfo, fetchVersionHistory, reasonLabel, syncVersionHistory } from './versionHistory'
const jsonResponse = (body: unknown, status = 200) =>
Promise.resolve({ ok: status >= 200 && status < 300, status, json: () => Promise.resolve(body) } as Response)
afterEach(() => vi.unstubAllGlobals())
const pageBody = {
items: [
{
commit_sha: 'a'.repeat(40),
short_sha: 'aaaaaaaaaaaa',
parents: [],
committed_at: '2026-10-13T10:00:00Z',
author_display: '姚章浩',
subject: 'feat: 甲',
body: '正文',
record_kind: 'development',
version_label: '0.1.2',
version_state: 'verified',
release_tags: [],
release_notes: '',
commit_url: 'https://gitea.example/commit/aaa',
version_reason: 'counted_commits_since_base_tag',
is_current_running: false,
},
],
next_cursor: 'next-cursor',
has_more: true,
sync: {
available: true,
status: 'completed',
complete: true,
last_success_at: '2026-10-13T12:00:00Z',
fetched_count: 111,
expected_count: 111,
error_code: '',
source_head_sha: 'a'.repeat(40),
active_snapshot_id: 3,
repo: 'Weknora/knowledge-governance',
},
current_running: {
state: 'development',
commit_sha: 'b'.repeat(40),
display_version: '0.1.2',
matched_commit_sha: '',
},
}
describe('versionHistory client', () => {
it('loads a page, keeps the cursor and reads sync/current-running facts', async () => {
const fetchMock = vi.fn((_input: RequestInfo | URL, _init?: RequestInit) => jsonResponse(pageBody))
vi.stubGlobal('fetch', fetchMock)
const page = await fetchVersionHistory({ kind: 'all', cursor: '' })
expect(fetchMock).toHaveBeenCalledOnce()
const url = String(fetchMock.mock.calls[0][0])
expect(url).toContain('/api/v1/version-history?')
expect(url).not.toContain('kind=all')
expect(url).toContain('limit=30')
expect(page.items[0].version_label).toBe('0.1.2')
expect(page.next_cursor).toBe('next-cursor')
expect(page.has_more).toBe(true)
expect(page.sync.expected_count).toBe(111)
expect(page.current_running.state).toBe('development')
})
it('passes the kind filter and cursor through', async () => {
const fetchMock = vi.fn((_input: RequestInfo | URL, _init?: RequestInit) =>
jsonResponse({ ...pageBody, items: [], has_more: false })
)
vi.stubGlobal('fetch', fetchMock)
await fetchVersionHistory({ kind: 'historical', cursor: 'c-1', limit: 50 })
const url = String(fetchMock.mock.calls[0][0])
expect(url).toContain('kind=historical')
expect(url).toContain('cursor=c-1')
expect(url).toContain('limit=50')
})
it('explains an expired cursor instead of showing a raw error', async () => {
vi.stubGlobal(
'fetch',
vi.fn(() => jsonResponse({ code: 'cursor_expired' }, 409))
)
await expect(fetchVersionHistory({ kind: 'all', cursor: 'stale' })).rejects.toThrow('已被清理')
})
it('rejects malformed payloads instead of rendering half-truths', async () => {
vi.stubGlobal(
'fetch',
vi.fn(() => jsonResponse({ items: 'nope' }))
)
await expect(fetchVersionHistory({ kind: 'all', cursor: '' })).rejects.toThrow('响应无效')
})
it('posts the sync request and reports reuse', async () => {
const fetchMock = vi.fn((_input: RequestInfo | URL, _init?: RequestInit) =>
jsonResponse({ job_id: 'job-1', status: 'running', reused: true })
)
vi.stubGlobal('fetch', fetchMock)
const accepted = await syncVersionHistory()
expect(String(fetchMock.mock.calls[0][0])).toBe('/api/v1/version-history/sync')
expect(fetchMock.mock.calls[0][1]).toMatchObject({ method: 'POST' })
expect(accepted.reused).toBe(true)
})
it('says admin-only when the sync is refused', async () => {
vi.stubGlobal(
'fetch',
vi.fn(() => jsonResponse({ code: 'forbidden_role' }, 403))
)
await expect(syncVersionHistory()).rejects.toThrow('只有管理员')
})
it('never fabricates a build identity when injection is missing', async () => {
vi.stubGlobal(
'fetch',
vi.fn(() =>
jsonResponse({
release_version: '',
build_kind: 'development',
commit_sha: null,
display_version: 'dev',
built_at: '',
identity_available: false,
})
)
)
const info = await fetchBuildInfo()
expect(info.commit_sha).toBeNull()
expect(info.identity_available).toBe(false)
})
it('maps every evidence reason to a human explanation', () => {
expect(reasonLabel('lightweight_tag')).toContain('轻量 tag')
expect(reasonLabel('no_baseline')).toContain('发布基线')
expect(reasonLabel('shallow_or_incomplete_graph')).toContain('提交图不完整')
expect(reasonLabel('something_new')).toBe('版本号未能核验')
})
})
+195
View File
@@ -0,0 +1,195 @@
// 「版本记录」页的客户端:只读查询 + 管理员手动同步。
// 页面读的是本库缓存(Gitea 不可达也能看),同步动作只允许管理员触发。
export type VersionRecordKind = 'release' | 'development' | 'historical'
export type VersionState = 'verified' | 'unknown'
export type CurrentRunningState = 'matched' | 'development' | 'unknown'
export interface VersionHistoryTag {
name: string
url: string
}
export interface VersionHistoryItem {
commit_sha: string
short_sha: string
parents: string[]
committed_at: string
author_display: string
subject: string
body: string
record_kind: VersionRecordKind
version_label: string
version_state: VersionState
release_tags: VersionHistoryTag[]
release_notes: string
commit_url: string
version_reason: string
is_current_running: boolean
}
export interface VersionHistorySyncState {
available: boolean
status: string
complete: boolean
last_success_at: string
fetched_count: number
expected_count: number | null
error_code: string
source_head_sha: string
active_snapshot_id: number
repo: string
}
export interface VersionHistoryCurrentRunning {
state: CurrentRunningState
commit_sha: string
display_version: string
matched_commit_sha: string
}
export interface VersionHistoryPage {
items: VersionHistoryItem[]
next_cursor: string
has_more: boolean
sync: VersionHistorySyncState
current_running: VersionHistoryCurrentRunning
}
export interface BuildInfo {
release_version: string
build_kind: string
commit_sha: string | null
display_version: string
built_at: string
identity_available: boolean
}
export interface SyncAccepted {
job_id: string
status: string
reused: boolean
}
const record = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null
const text = (value: unknown): string => (typeof value === 'string' ? value : '')
const bool = (value: unknown): boolean => value === true
const count = (value: unknown): number => (typeof value === 'number' && Number.isFinite(value) ? value : 0)
// 「版本号未能核验」的原因码 → 页面文案(不补造版本号,只解释为什么没有号)。
export const reasonLabels: Record<string, string> = {
annotated_tag_and_changelog_top_match: '注释 tag 与提交内版本记录一致',
counted_commits_since_base_tag: '按发布基线数出来的开发号',
lightweight_tag: '该提交上的 tag 是轻量 tag,不作为正式版本证据',
no_changelog_top: '该提交内没有已发布版本的变更记录',
changelog_top_mismatch: 'tag 版本与该提交内的变更记录不一致',
no_release_tag_for_commit: '没有指向该提交的正式 tag',
no_baseline: '找不到可核验的发布基线(该版本没有对应的 tag)',
shallow_or_incomplete_graph: '提交图不完整(检出被截断),提交数算不准',
release_tag_created_later: '该版本是在更晚的提交上发布的 —— 这个提交当时还没有 tag',
}
export const reasonLabel = (reason: string): string => reasonLabels[reason] ?? '版本号未能核验'
const parseItem = (value: unknown): VersionHistoryItem => {
if (!record(value)) throw new Error('版本记录条目无效')
return {
commit_sha: text(value.commit_sha),
short_sha: text(value.short_sha),
parents: Array.isArray(value.parents)
? value.parents.filter((item): item is string => typeof item === 'string')
: [],
committed_at: text(value.committed_at),
author_display: text(value.author_display),
subject: text(value.subject),
body: text(value.body),
record_kind: (text(value.record_kind) || 'historical') as VersionRecordKind,
version_label: text(value.version_label),
version_state: (text(value.version_state) || 'unknown') as VersionState,
release_tags: Array.isArray(value.release_tags)
? value.release_tags.filter(record).map((tag) => ({ name: text(tag.name), url: text(tag.url) }))
: [],
release_notes: text(value.release_notes),
commit_url: text(value.commit_url),
version_reason: text(value.version_reason),
is_current_running: bool(value.is_current_running),
}
}
export async function fetchVersionHistory(
params: { kind: string; cursor: string; limit?: number },
signal?: AbortSignal
): Promise<VersionHistoryPage> {
const query = new URLSearchParams()
if (params.kind && params.kind !== 'all') query.set('kind', params.kind)
if (params.cursor) query.set('cursor', params.cursor)
query.set('limit', String(params.limit ?? 30))
const response = await fetch(`/api/v1/version-history?${query.toString()}`, {
headers: { Accept: 'application/json' },
signal,
})
const value = (await response.json().catch(() => null)) as unknown
if (!response.ok) {
const code = record(value) ? text(value.code) : ''
if (response.status === 409 || code === 'cursor_expired') {
throw new Error('这次翻页依据的记录快照已被清理,请刷新页面重新加载。')
}
throw new Error(`加载版本记录失败(HTTP ${response.status})`)
}
if (!record(value) || !Array.isArray(value.items) || !record(value.sync) || !record(value.current_running)) {
throw new Error('版本记录响应无效')
}
const sync = value.sync
const running = value.current_running
const expected = typeof sync.expected_count === 'number' ? sync.expected_count : null
return {
items: value.items.map(parseItem),
next_cursor: text(value.next_cursor),
has_more: bool(value.has_more),
sync: {
available: bool(sync.available),
status: text(sync.status),
complete: bool(sync.complete),
last_success_at: text(sync.last_success_at),
fetched_count: count(sync.fetched_count),
expected_count: expected,
error_code: text(sync.error_code),
source_head_sha: text(sync.source_head_sha),
active_snapshot_id: count(sync.active_snapshot_id),
repo: text(sync.repo),
},
current_running: {
state: (text(running.state) || 'unknown') as CurrentRunningState,
commit_sha: text(running.commit_sha),
display_version: text(running.display_version),
matched_commit_sha: text(running.matched_commit_sha),
},
}
}
export async function syncVersionHistory(): Promise<SyncAccepted> {
const response = await fetch('/api/v1/version-history/sync', {
method: 'POST',
headers: { Accept: 'application/json' },
})
const value = (await response.json().catch(() => null)) as unknown
if (!response.ok) {
throw new Error(response.status === 403 ? '只有管理员能触发同步。' : `触发同步失败(HTTP ${response.status})`)
}
if (!record(value)) throw new Error('同步响应无效')
return { job_id: text(value.job_id), status: text(value.status), reused: bool(value.reused) }
}
export async function fetchBuildInfo(signal?: AbortSignal): Promise<BuildInfo> {
const response = await fetch('/api/v1/build-info', { headers: { Accept: 'application/json' }, signal })
if (!response.ok) throw new Error(`读取当前运行版本失败(HTTP ${response.status})`)
const value = (await response.json()) as unknown
if (!record(value)) throw new Error('构建身份响应无效')
return {
release_version: text(value.release_version),
build_kind: text(value.build_kind),
commit_sha: typeof value.commit_sha === 'string' ? value.commit_sha : null,
display_version: text(value.display_version),
built_at: text(value.built_at),
identity_available: bool(value.identity_available),
}
}
+4 -9
View File
@@ -1,16 +1,11 @@
export type ModuleId = 'dashboard' | 'sources' | 'knowledge' | 'tasks' | 'releases' | 'settings'
export type ModuleId = 'dashboard' | 'sources' | 'knowledge' | 'tasks' | 'releases' | 'settings' | 'versions'
export interface WorkspaceState {
openTabs: ModuleId[]
activeTab: ModuleId
}
const moduleIds = new Set<ModuleId>([
'dashboard',
'tasks',
'releases',
'settings',
])
const moduleIds = new Set<ModuleId>(['dashboard', 'tasks', 'releases', 'settings'])
export const initialWorkspace: WorkspaceState = {
openTabs: ['dashboard'],
@@ -45,10 +40,10 @@ export function restoreWorkspace(raw: string | null): WorkspaceState {
const saved = JSON.parse(raw) as { openTabs?: unknown; activeTab?: unknown }
if (!Array.isArray(saved.openTabs)) return initialWorkspace
const restoredTabs = saved.openTabs.filter(
(value): value is ModuleId => typeof value === 'string' && moduleIds.has(value as ModuleId),
(value): value is ModuleId => typeof value === 'string' && moduleIds.has(value as ModuleId)
)
const openTabs = ['dashboard', ...restoredTabs.filter((tab) => tab !== 'dashboard')].filter(
(tab, index, tabs) => tabs.indexOf(tab) === index,
(tab, index, tabs) => tabs.indexOf(tab) === index
) as ModuleId[]
const activeTab =
typeof saved.activeTab === 'string' &&