Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 013ce4a24e | |||
| 90901a4458 | |||
| 3566f208e0 | |||
| 2ea2111420 | |||
| 828c2c5fa0 | |||
| 4b3aaff321 |
+293
-1
@@ -4,6 +4,15 @@
|
||||
|
||||
### Added
|
||||
|
||||
- 问答记录新增“本周”快捷查询,默认展示北京时间本周数据;所选范围自动读取全部记录,校验完整数量后展示,不再需要分页或加载更多。固定展示完整字段,空列不再隐藏,中文原文直接展示、外语未翻译明确标记;保留源端有界传输、取消和失败保护。
|
||||
|
||||
- 问答记录新增年份与自然周选择,周次展示起止日期,支持跨年及每年实际周数;按北京时间周一至周日填入查询范围,默认本周且仅查询截至当前的数据。保留自定义时间与原查询按钮,浏览器时区不改变查询边界。
|
||||
|
||||
- 问答运营按已确认口径显示知识覆盖率、回答正确率及原始分子/分母、排除数量与构成。使用完整筛选范围和当前有效人工优先结论,精确规则命中的未覆盖可进入覆盖分母;部分覆盖不算完全覆盖,待确认/未评估/失效/不计入按对应指标排除,零分母显示“暂无可计算数据”。返回独立规则版本,AI 模型与绩效范围仍未接入。
|
||||
|
||||
- 问答详情支持治理侧人工复核及不可变审计:覆盖、正确性、产品分类、问题类型、根因与理由由管理员明确填写,操作人取登录身份;保存后独立读回复核历史。保留源端判断和自动规则,输入变化使旧人工结论失效,已观测的内容回退不自动恢复旧结论;并发修改冲突、重复请求不重复留档。
|
||||
- 新增覆盖复检历史、已采集输入快照和完整筛选范围质量数量。批量统计只传指纹与规则命中元数据,原文在读取问答/复核时采集,未采集版本明确提示而非伪造空快照;源事务时点阻止延迟旧扫描回退新输入。基础数量与本期经确认新增的质量比例分开显示;不接 AI 模型、不定义绩效分母、不回写 DobotAI 原问答。
|
||||
|
||||
- 「使用统计 → 个人月明细」按北京时间自然月及截止时点展示当前应用可见名册的人员用量(包含本源零记录),支持部门含子部门、区域/待核对状态、姓名/完整部门路径和已有提问/零记录筛选。稳定身份关联去重、不可关联问答单列、过期组织版本阻断翻页;源端姓名可缺失并提示重新同步,不按姓名匹配身份。姓名筛选通过有界只读 POST 请求体传递、不进入 URL,原始员工标识不返回浏览器;名册不作为在职/考核分母,当月进度不作为绩效结论。
|
||||
|
||||
- 问答运营按稳定身份关联当前治理通讯录,缺失部门/区域补全并保留源快照及目录/区域版本;空列判断包含完整筛选结果,不混合配置已变化的分页。新增完整时间/关键词范围的使用统计,问答计次、名册内人员去重,跨区/未匹配/身份缺失分列,不输出绩效结论;不回写 DobotAI 原表。
|
||||
@@ -28,6 +37,8 @@
|
||||
|
||||
### Fixed
|
||||
|
||||
- 修复通过带端口的 HTTP 地址访问问答运营时,正常同源操作被误报“拒绝跨站配置请求”:网页代理保留原始 Host 及端口,使缺少 Fetch Metadata 的浏览器也能正确执行 Origin 校验。保留后端跨站、异端口、伪造转发头与缺失操作意图的拒绝保护。
|
||||
|
||||
- **登记钉钉知识库失败(HTTP 409 `space_registration_conflict`)的真实原因与修复**:`source_connections.name` 有唯一约束,而早期路径登记的钉钉来源(`base_url` 为空、id 与 dws 现在推导的确定性 id 不同)被**归档后仍占着名字槽位** ⇒ 重新登记时 INSERT 撞唯一约束;处理器又把**所有**存储层错误都翻译成同一个 409,真实原因被吞掉(线上只能看到一个无细节的错误码)。现在:① 同名来源**已归档**时,把它改名腾位(`…(已下架 · <短ID>)`,归档行不显示、数据与审计一行不动);② 同名来源**仍在使用**时返回 `space_name_conflict` + 可行动提示(先「去掉来源」);③ 同一登记键指向别的空间且该行仍在用时返回 `space_identity_conflict`(已归档的行则允许就地改写 —— 这就是"去掉后再用 dws 重新获取");④ 其余内部故障改回 **500** `space_registration_failed`,不再伪装成冲突;前端优先显示后端 `hint`,并为这两个新码补了中文说明。
|
||||
|
||||
- 前端入口与静态资源的缓存语义("新功能看起来没上线"与"页面偶尔裸奔/空白"的根因):
|
||||
@@ -62,9 +73,290 @@
|
||||
> **版本怎么走**(两行就够):
|
||||
> · **正式版本** = 下面那条 `## [x.y.z] - 日期`,是**发版事实**,由人批准后打注释 tag `vX.Y.Z`;
|
||||
> · **开发版本自动递增** = `<正式版本的主.次>.<自那个 tag 以来的提交数>`(正式 `0.1.0` 之后第 12 个提交 =
|
||||
> `0.1.12`),由 `scripts/version.py` 从 git **算出来**,**不写进本文件** ⇒ 每个提交都有自己的版本号,
|
||||
> `0.1.12`),由 `scripts/version.py` 从 git **算出来**;开发交付的独立说明写入本文件“开发快照”章节,并打 `snapshot/vX.Y.Z` 注释标签 ⇒ 每次开发交付均可追溯,
|
||||
> 但"发布版本"仍然只能由人定(CI 不会自动升版本、不会打 tag)。
|
||||
|
||||
## 开发快照 snapshot/v0.1.26 - 2026-10-18
|
||||
|
||||
### Fixed
|
||||
|
||||
- 版本记录收录已交付开发快照与当前运行提交,不再只同步 main;开发版本显示对应的独立变更说明。
|
||||
- 修复同步重复返回旧已完成任务:进行中同步合并,完成后允许新一轮同步。
|
||||
- 构建启动后自动请求版本同步;部署后独立读回当前完整 SHA、开发标签与变更说明,缺失时不宣称交付完成。
|
||||
|
||||
### Added
|
||||
|
||||
- 增加开发快照计划、显式发布及远端读回工具;历史说明按原提交补记,正式 tag 与 Release 保持独立授权。
|
||||
|
||||
## 开发快照 snapshot/v0.1.25 - 2026-10-18
|
||||
|
||||
目标提交:90901a4458054aca721047c9a2896f2130d46b5c
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- 问答记录新增“本周”快捷查询,默认展示北京时间本周数据;所选范围自动读取全部记录,校验完整数量后展示,不再需要分页或加载更多。固定展示完整字段,空列不再隐藏,中文原文直接展示、外语未翻译明确标记;保留源端有界传输、取消和失败保护。
|
||||
|
||||
## 开发快照 snapshot/v0.1.24 - 2026-10-18
|
||||
|
||||
目标提交:3566f208e0e15fdec2cc98c29f93c46f5f7c91ca
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- 问答记录新增年份与自然周选择,周次展示起止日期,支持跨年及每年实际周数;按北京时间周一至周日填入查询范围,默认本周且仅查询截至当前的数据。保留自定义时间与原查询按钮,浏览器时区不改变查询边界。
|
||||
|
||||
## 开发快照 snapshot/v0.1.23 - 2026-10-18
|
||||
|
||||
目标提交:2ea2111420e501fec37e0ea0c4bcd3cd8c866403
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 修复通过带端口的 HTTP 地址访问问答运营时,正常同源操作被误报“拒绝跨站配置请求”:网页代理保留原始 Host 及端口,使缺少 Fetch Metadata 的浏览器也能正确执行 Origin 校验。保留后端跨站、异端口、伪造转发头与缺失操作意图的拒绝保护。
|
||||
|
||||
## 开发快照 snapshot/v0.1.22 - 2026-10-18
|
||||
|
||||
目标提交:828c2c5fa0d4e3e0eee3987085a4d782872f7e95
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- 问答运营按已确认口径显示知识覆盖率、回答正确率及原始分子/分母、排除数量与构成。使用完整筛选范围和当前有效人工优先结论,精确规则命中的未覆盖可进入覆盖分母;部分覆盖不算完全覆盖,待确认/未评估/失效/不计入按对应指标排除,零分母显示“暂无可计算数据”。返回独立规则版本,AI 模型与绩效范围仍未接入。
|
||||
- 新增覆盖复检历史、已采集输入快照和完整筛选范围质量数量。批量统计只传指纹与规则命中元数据,原文在读取问答/复核时采集,未采集版本明确提示而非伪造空快照;源事务时点阻止延迟旧扫描回退新输入。基础数量与本期经确认新增的质量比例分开显示;不接 AI 模型、不定义绩效分母、不回写 DobotAI 原问答。
|
||||
|
||||
## 开发快照 snapshot/v0.1.21 - 2026-10-17
|
||||
|
||||
目标提交:4b3aaff3219e78ae3dfd5d12ba36f82e323a21ba
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- 问答详情支持治理侧人工复核及不可变审计:覆盖、正确性、产品分类、问题类型、根因与理由由管理员明确填写,操作人取登录身份;保存后独立读回复核历史。保留源端判断和自动规则,输入变化使旧人工结论失效,已观测的内容回退不自动恢复旧结论;并发修改冲突、重复请求不重复留档。
|
||||
- 新增覆盖复检历史、已采集输入快照和完整筛选范围质量数量。批量统计只传指纹与规则命中元数据,原文在读取问答/复核时采集,未采集版本明确提示而非伪造空快照;源事务时点阻止延迟旧扫描回退新输入。仅提供数量,不接 AI 模型、不定义质量率或绩效分母、不回写 DobotAI 原问答。
|
||||
|
||||
## 开发快照 snapshot/v0.1.20 - 2026-10-17
|
||||
|
||||
目标提交:9556db1ef01add21064553f64be6a7e25f838e9e
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- 「使用统计 → 个人月明细」按北京时间自然月及截止时点展示当前应用可见名册的人员用量(包含本源零记录),支持部门含子部门、区域/待核对状态、姓名/完整部门路径和已有提问/零记录筛选。稳定身份关联去重、不可关联问答单列、过期组织版本阻断翻页;源端姓名可缺失并提示重新同步,不按姓名匹配身份。姓名筛选通过有界只读 POST 请求体传递、不进入 URL,原始员工标识不返回浏览器;名册不作为在职/考核分母,当月进度不作为绩效结论。
|
||||
|
||||
## 开发快照 snapshot/v0.1.19 - 2026-10-17
|
||||
|
||||
目标提交:56b8cabed9213911b6beb4aeaac9baa22e872a00
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- 问答运营按稳定身份关联当前治理通讯录,缺失部门/区域补全并保留源快照及目录/区域版本;空列判断包含完整筛选结果,不混合配置已变化的分页。新增完整时间/关键词范围的使用统计,问答计次、名册内人员去重,跨区/未匹配/身份缺失分列,不输出绩效结论;不回写 DobotAI 原表。
|
||||
- 新增治理侧通讯录实时桥接,复用既有周报读取能力,向源端读取真实缺失祖先以补齐部门树;不改旧周报脚本、配置或输出。私有 JSON 与受控子进程执行器拒绝不完整数据、模拟同步、公开文件和异常输出,超时清理临时人员文件。同步默认关闭,容器启用仍需批准的既有周报 SDK/配置及兼容 Python 运行时挂载。
|
||||
- **「问答运营 → 区域使用」区域归属配置切片**:按稳定部门 ID 搜索和勾选完整路径,预览去重归属人数,保存版本后重新读取;父部门包含子部门、子部门显式配置优先,多部门跨区域人员单独待核对。预览不写入,过期版本和不完整部门树被阻断。基础使用统计见本期新增,不代表绩效验收;翻译及 AI 评估模型接入按用户要求暂缓。
|
||||
- **「问答运营 → 问答记录」首个开发切片**:在现有导航中查看 DobotAI 2.0 钉钉问答,支持半开时间范围、原问题关键词、稳定游标分页和完整详情;按整个筛选结果隐藏空列,反馈聚合不放大问答条数。外语翻译、AI 评估尚未接入,不标为第一阶段完成。
|
||||
|
||||
## 开发快照 snapshot/v0.1.18 - 2026-10-17
|
||||
|
||||
目标提交:cc4906b6a9f33683a5c0017d83b24d96d5c997b1
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- 「问答运营 → 区域使用」支持管理员从网页发起持久化通讯录同步,重复请求重放、进行中操作合并;按服务器固定范围注册后台执行器,未接线或未检测到心跳时不创建新任务。界面显示真实任务状态、不编造百分比;失败保留旧快照与区域规则,同步完成不覆盖未保存草稿。旧执行器丢失租约后不能激活结果,重启接管和已提交快照的续跑使用原任务。
|
||||
- 新增治理侧通讯录实时桥接,复用既有周报读取能力,向源端读取真实缺失祖先以补齐部门树;不改旧周报脚本、配置或输出。私有 JSON 与受控子进程执行器拒绝不完整数据、模拟同步、公开文件和异常输出,超时清理临时人员文件;问答组织关联尚未接入。同步默认关闭,容器启用仍需批准的既有周报 SDK/配置及兼容 Python 运行时挂载。
|
||||
- **「问答运营 → 区域使用」区域归属配置切片**:按稳定部门 ID 搜索和勾选完整路径,预览去重归属人数,保存版本后重新读取;父部门包含子部门、子部门显式配置优先,多部门跨区域人员单独待核对。预览不写入,过期版本和不完整部门树被阻断。当前不是使用/绩效统计验收,翻译及 AI 评估模型接入按用户要求暂缓。
|
||||
|
||||
## 开发快照 snapshot/v0.1.17 - 2026-10-17
|
||||
|
||||
目标提交:6adfdcdd4fe0e5c35018bf0e4857c203dd24e5d1
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- 区域归属表支持长部门路径换行,避免继承全局不换行规则后将生效区域与归属依据列挤出桌面面板。
|
||||
|
||||
## 开发快照 snapshot/v0.1.16 - 2026-10-17
|
||||
|
||||
目标提交:5874134e049b0896a202b41d9d400d1be5386f89
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- 新增治理侧通讯录实时桥接,复用既有周报读取能力,向源端读取真实缺失祖先以补齐部门树;不改旧周报脚本、配置或输出。私有 JSON 与受控子进程执行器拒绝不完整数据、模拟同步、公开文件和异常输出,超时清理临时人员文件;网页触发的后台同步队列及问答组织关联尚未接入。
|
||||
|
||||
## 开发快照 snapshot/v0.1.15 - 2026-10-17
|
||||
|
||||
目标提交:dab74b706b5b87da3ecb71a8e0f6b6caa5fba4ad
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- **「问答运营 → 区域使用」区域归属配置切片**:按稳定部门 ID 搜索和勾选完整路径,预览去重归属人数,保存版本后重新读取;父部门包含子部门、子部门显式配置优先,多部门跨区域人员单独待核对。预览不写入,过期版本和不完整部门树被阻断。当前不是实时通讯录同步或使用/绩效统计验收,翻译及 AI 评估模型接入按用户要求暂缓。
|
||||
- 新增治理侧组织快照与区域修订迁移、受确认保护的后台导入命令;不修改 DobotAI 原表或钉钉组织结构。
|
||||
|
||||
## 开发快照 snapshot/v0.1.14 - 2026-10-17
|
||||
|
||||
目标提交:fd04bf7886aa4eba68b247dd7c1092894a5282da
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- **「问答运营 → 问答记录」首个开发切片**:在现有导航中查看 DobotAI 2.0 钉钉问答,支持半开时间范围、原问题关键词、稳定游标分页和完整详情;按整个筛选结果隐藏空列,反馈聚合不放大问答条数。外语翻译、AI 评估、人员区域映射尚未接入,不标为第一阶段完成。
|
||||
- 治理侧重新检查答案:包含 `暂无已发布` 即未覆盖,引用和源端 covered 不能抵消;未命中仍待评估,源端规则单独保留作对照。独立只读源默认关闭、租户后端固定、管理员会话鉴权,源故障不回退治理主库;安全告警明确保留 TEMP/TLS 尚未整改状态。
|
||||
- **「版本记录」页**(一级入口):只读时间线追踪**远端 main 可达的全部提交**(含合并提交与已并入 main 的侧分支提交),按提交时间倒序显示标题/正文、`[正式版本] / [开发版本] / [历史提交]` 徽标、短 SHA、提交内变更记录与 `[查看提交]`/`[查看 tag]`;支持「全部 / 正式 / 开发 / 历史」筛选与游标翻页,窄屏单列。
|
||||
|
||||
## 开发快照 snapshot/v0.1.13 - 2026-10-14
|
||||
|
||||
目标提交:c1d49adb622f3bf18e51bddb415795a894ed227e
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Changed
|
||||
|
||||
- 补三Agent交接闭环工作流(状态机、快照tag与验收模板)。
|
||||
|
||||
## 开发快照 snapshot/v0.1.12 - 2026-10-14
|
||||
|
||||
目标提交:9a8a3e77956149d116360bbb561efd67e20fb062
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Fixed
|
||||
|
||||
- **登记钉钉知识库失败(HTTP 409 `space_registration_conflict`)的真实原因与修复**:`source_connections.name` 有唯一约束,而早期路径登记的钉钉来源(`base_url` 为空、id 与 dws 现在推导的确定性 id 不同)被**归档后仍占着名字槽位** ⇒ 重新登记时 INSERT 撞唯一约束;处理器又把**所有**存储层错误都翻译成同一个 409,真实原因被吞掉(线上只能看到一个无细节的错误码)。现在:① 同名来源**已归档**时,把它改名腾位(`…(已下架 · <短ID>)`,归档行不显示、数据与审计一行不动);② 同名来源**仍在使用**时返回 `space_name_conflict` + 可行动提示(先「去掉来源」);③ 同一登记键指向别的空间且该行仍在用时返回 `space_identity_conflict`(已归档的行则允许就地改写 —— 这就是"去掉后再用 dws 重新获取");④ 其余内部故障改回 **500** `space_registration_failed`,不再伪装成冲突;前端优先显示后端 `hint`,并为这两个新码补了中文说明。
|
||||
|
||||
## 开发快照 snapshot/v0.1.11 - 2026-10-14
|
||||
|
||||
目标提交:2c7265efc47a2cd6b324bf278fa5ddb0c4a9fe57
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Changed
|
||||
|
||||
- 「系统设置 → 数据源配置」**收敛成两个入口**:**dws 导入**(按当前钉钉账号列出可访问的知识库与钉盘空间)与 **PP 导入**。AList(已由钉盘文件替代)、静态登记的钉钉知识库、本地手工导入与 PP legacy 都**不再出现在这一页**;已接入的这类来源用**归档**下架(`POST /api/v1/source-connections/{id}/archive`,管理员、幂等,带写意图头与幂等键):从列表、来源与目录、计划刷新与手动扫描里消失,**目录快照、发布记录与审计数据一行不删**。恢复用 `…/restore`(保持停用、不自动带回调度),或让 dws 重新登记同一来源 —— 钉钉空间登记是确定性 ID + `ON CONFLICT`,**原地复活同一行、不产生重复**。卡片上新增「去掉来源」按钮(管理员,带确认弹窗)。
|
||||
- 迁移 `000047_source_connection_archive`:新增 `archived_at` / `archived_by` 与只覆盖未归档行的部分索引;列表、目录、计划刷新、手动扫描四类查询一律排除归档行(漏一条就等于入口没去掉)。
|
||||
|
||||
## 开发快照 snapshot/v0.1.10 - 2026-10-14
|
||||
|
||||
目标提交:64b32c2da64881b3c9bf6de6b8f9af3f833128fd
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Changed
|
||||
|
||||
- 「系统设置 → 数据源配置」默认只列 PP 资料与「可加入的来源」:AList 来源(已由钉盘文件替代)与静态登记的钉钉知识库来源(改为按当前钉钉账号发现)**不再默认列出**,收进「显示 AList/钉钉知识库来源(N)」折叠开关 —— **来源一个都没删**,展开后照旧可改刷新周期与启停,「来源与目录」里的内容不变。手动导入来源(本地手工验收)不在这次范围内,照旧显示。
|
||||
|
||||
## 开发快照 snapshot/v0.1.9 - 2026-10-14
|
||||
|
||||
目标提交:b7f7e4f12101569db5bb76af9d836043eefc342b
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Fixed
|
||||
|
||||
- **上线前护栏 + 事故复盘**:`scripts/deploy-api-web.sh` 现在先校验 `.env` 的键值形状(值里再出现 `KEY=` 或键名不合法 ⇒ **拒绝上线**),配置校验失败时也会给出"两行粘成一行"的线索。事故:`.env` 最后一行没有结尾换行、又被追加新键 ⇒ 两行粘成一行 ⇒ `VERSION_HISTORY_GITEA_BASE_URL` 变成非法值 ⇒ api/worker 按设计拒绝启动、崩溃重启(平台整体不可用)。已修数据、加护栏、加回归用例。
|
||||
|
||||
## 开发快照 snapshot/v0.1.8 - 2026-10-14
|
||||
|
||||
目标提交:4cb51108454c3559e8a6305ad3316f74ed4e2daf
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 「版本记录」页的链接改为**抓取与链接分离**:抓取仍走配置的(内网)地址,页面上的「查看提交 / 查看 tag」用 `VERSION_HISTORY_LINK_ORIGIN`(公网 origin)拼 —— 原先两者共用内网地址,内网外的浏览器点开是空白;另外 tag 记录原先不带链接(空 `href` 点下去没反应),现在补上链接、没有链接就不渲染该按钮。
|
||||
|
||||
## 开发快照 snapshot/v0.1.7 - 2026-10-14
|
||||
|
||||
目标提交:90db243a68a5d16d643dd0273614b93666d65ca7
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 前端入口与静态资源的缓存语义("新功能看起来没上线"与"页面偶尔裸奔/空白"的根因):
|
||||
|
||||
## 开发快照 snapshot/v0.1.6 - 2026-10-14
|
||||
|
||||
目标提交:062a3b3cb60ede5ebcca64a0f14df53fffa1f359
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 前端入口的缓存策略:`index.html` 此前没有缓存头,CDN/浏览器会启发式缓存它,于是**页面会一直停在旧构建上**(实测被腾讯云 EdgeOne 卡住:源站已是新包,公网入口仍发旧包,看起来像"新菜单/新页面没上线")。现在 `index.html` 每次回源校验(`no-cache, must-revalidate`)、带内容哈希的 `/assets/` 长缓存(`immutable`),旧哈希资源明确 404 而不是回退成 HTML。
|
||||
|
||||
## 开发快照 snapshot/v0.1.5 - 2026-10-14
|
||||
|
||||
目标提交:4d43a9386a8a97969a1568956213f6f17b13edfb
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Changed
|
||||
|
||||
- tag 之前的提交不再被编号 + 部署脚本注入构建身份。
|
||||
|
||||
## 开发快照 snapshot/v0.1.4 - 2026-10-13
|
||||
|
||||
目标提交:0974d8dfa2aad5650eefbcee3edb365a8afd4868
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### 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 成功不等于已部署。
|
||||
|
||||
### Security
|
||||
|
||||
- 版本记录同步**匿名只读**远端仓库(**不使用任何凭据**),来源限配置里批准的 origin 与固定仓库:拒绝任意 URL、拒绝跨主机重定向,单个响应设大小上限与超时、5xx/429 才有退避重试。
|
||||
- 提交正文与变更记录一律按**纯文本**渲染(不产生 HTML/脚本注入面);页面不含打 tag / 发布 / 部署入口;同步动作仅管理员可用,服务端再次判角色。
|
||||
|
||||
## 开发快照 snapshot/v0.1.3 - 2026-10-13
|
||||
|
||||
目标提交:ad9c5d20d467a077e88bbfe63b1a56355d263e51
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Changed
|
||||
|
||||
- Merge remote-tracking branch 'origin/main'。
|
||||
|
||||
## 开发快照 snapshot/v0.1.1 - 2026-10-13
|
||||
|
||||
目标提交:3a1d32da8fba90eb5081865b1f3ad424a46639ee
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Changed
|
||||
|
||||
- 重写平台定位与能力边界并归档原说明。
|
||||
|
||||
## 开发快照 snapshot/v0.1.1 - 2026-10-13
|
||||
|
||||
目标提交:950c1b429bc814d9fa7c2c1449f999a05537af21
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Changed
|
||||
|
||||
- 抬档门禁(破坏性 ⇒ 0.x 抬次 / ≥1.0.0 抬主)+ 1.0.0 前置(稳定契约承诺)。
|
||||
|
||||
## [0.1.0] - 2026-10-13
|
||||
|
||||
### Added
|
||||
|
||||
@@ -101,6 +101,10 @@
|
||||
},
|
||||
"/api/v1/qa-ops/usage/people": {"post": {"tags": ["QA operations"], "operationId": "queryQAOperationsMonthlyPeople", "summary": "按北京时间自然月列出当前名册人员的2.0用量(含零记录),仅管理员,不返回原始员工标识,不作为在职/考核名单", "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}, "409": {"description": "完整名册缺失或目录/区域版本变化,请同步/重新查询,不返回伪零"}}, "description": "只读查询,不写治理库或生产库;姓名筛选置于 JSON 请求体,不进入 URL;整名册指标不随人员筛选变化。第2页起须带首页目录、区域版本及 end 截止。", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "required": ["month"], "properties": {"month": {"type": "string", "pattern": "^(?!0000)[0-9]{4}-(0[1-9]|1[0-2])$"}, "cutoff": {"type": "string", "format": "date-time"}, "region": {"type": "string", "enum": ["国内工业", "APAC", "EMEA", "America", "unassigned", "cross_region"]}, "department_id": {"type": "string"}, "activity": {"type": "string", "enum": ["all", "used", "zero"]}, "search": {"type": "string", "maxLength": 100}, "page": {"type": "integer", "minimum": 1, "maximum": 100000, "default": 1}, "limit": {"type": "integer", "minimum": 1, "maximum": 100, "default": 30}, "directory_id": {"type": "string"}, "revision_id": {"type": "string"}}}}}}, "parameters": [{"name": "X-Governance-Action", "in": "header", "required": true, "schema": {"type": "string", "enum": ["qa-usage-read"]}}]}},
|
||||
"/api/v1/qa-ops/usage": {"get": {"tags": ["QA operations"], "operationId": "getQAOperationsUsage", "summary": "完整筛选范围内按当前通讯录和区域版本回看2.0问答使用;固定租户、管理员访问,不输出绩效结论", "parameters": [{"name": "start", "in": "query", "required": true, "schema": {"type": "string", "format": "date-time"}}, {"name": "end", "in": "query", "required": true, "schema": {"type": "string", "format": "date-time"}}, {"name": "keyword", "in": "query", "schema": {"type": "string", "maxLength": 200}}], "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}}}},
|
||||
"/api/v1/qa-ops/quality/query": {"post": {"operationId": "queryQAQualityCounts", "summary": "按完整筛选范围读取指纹/规则元数据并留档统计,最多5000条;summary.rates 返回 quality-rates-human-first-v1、原始分子/分母、百分比与分母构成。覆盖率=covered/(covered+uncovered+partial),正确率=covered_correct/(covered_correct+covered_incorrect);失效/不计入/相应待确认与未评估排除,零分母percent=null。原文仅在读取问答/复核时采集", "parameters": [{"name": "X-Governance-Action", "in": "header", "required": true, "schema": {"type": "string", "enum": ["qa-quality"]}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "properties": {"start": {"type": "string", "format": "date-time"}, "end": {"type": "string", "format": "date-time"}, "keyword": {"type": "string", "maxLength": 200}}, "required": ["start", "end"]}}}}, "tags": ["QA operations"], "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}, "409": {"description": "输入或复核版本变化/重复操作载荷不一致,未覆盖原结论"}, "404": {"description": "当前授权范围内未找到记录/历史输入"}}}},
|
||||
"/api/v1/qa-ops/records/{id}/reviews": {"post": {"operationId": "saveQAQualityReview", "summary": "治理库追加人工复核,登录身份审计,源端只读,输入/复核乐观锁和nonce幂等;正确时根因为空,不计入须说明原因", "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string"}}, {"name": "X-Governance-Action", "in": "header", "required": true, "schema": {"type": "string", "enum": ["qa-quality"]}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "properties": {"input_hash": {"type": "string", "pattern": "^[a-f0-9]{64}$"}, "input_epoch": {"type": "integer", "minimum": 1}, "base_revision": {"type": "integer", "minimum": 0}, "nonce": {"type": "string", "pattern": "^[A-Za-z0-9_-]{16,128}$"}, "fields": {"type": "object", "additionalProperties": false, "properties": {"coverage": {"type": "string", "enum": ["covered", "uncovered", "partial", "pending", "excluded"]}, "correctness": {"type": "string", "enum": ["correct", "incorrect", "pending"]}, "product_category": {"type": "string", "maxLength": 128}, "problem_type": {"type": "string", "maxLength": 128}, "root_cause": {"type": "string", "maxLength": 2000}, "exclusion_reason": {"type": "string", "maxLength": 2000}}, "required": ["coverage", "correctness"]}, "reason": {"type": "string", "minLength": 1, "maxLength": 4000}}, "required": ["input_hash", "input_epoch", "base_revision", "nonce", "fields", "reason"]}}}}, "tags": ["QA operations"], "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}, "409": {"description": "输入或复核版本变化/重复操作载荷不一致,未覆盖原结论"}, "404": {"description": "当前授权范围内未找到记录/历史输入"}}}},
|
||||
"/api/v1/qa-ops/records/{id}/quality/history": {"get": {"operationId": "listQAQualityHistory", "summary": "按当前固定租户查询不可变复检/人工历史,分别倒序分页,各20条", "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string"}}, {"name": "review_before", "in": "query", "schema": {"type": "integer", "minimum": 1}}, {"name": "check_before", "in": "query", "schema": {"type": "integer", "minimum": 1}}], "tags": ["QA operations"], "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}, "409": {"description": "输入或复核版本变化/重复操作载荷不一致,未覆盖原结论"}, "404": {"description": "当前授权范围内未找到记录/历史输入"}}}},
|
||||
"/api/v1/qa-ops/records/{id}/quality/inputs/{epoch}": {"get": {"operationId": "getQAQualityInputSnapshot", "summary": "管理员读取已采集的历史质量输入快照,不另存人员关联/反馈字段;元数据留档但未采集原文返回409,不编造空快照", "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string"}}, {"name": "epoch", "in": "path", "required": true, "schema": {"type": "integer", "minimum": 1}}], "tags": ["QA operations"], "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}, "409": {"description": "该输入版本仅有指纹/规则元数据、原文未采集"}, "404": {"description": "当前授权范围内未找到记录/历史输入"}}}},
|
||||
"/api/v1/qa-ops/status": {
|
||||
"get": {
|
||||
"tags": ["QA operations"],
|
||||
|
||||
@@ -21,7 +21,9 @@ import (
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"knowledge-governance/internal/serviceverify"
|
||||
"knowledge-governance/internal/version"
|
||||
)
|
||||
|
||||
// dingtalkSourceLister 是「系统设置 → 数据源配置」的数据源发现实现:只读列举钉钉知识库与
|
||||
@@ -36,6 +38,9 @@ func (dingtalkSourceLister) ListAvailableDingtalkSources(ctx context.Context) (d
|
||||
func main() {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
if len(os.Args) == 2 && os.Args[1] == "--version-record-status" {
|
||||
os.Exit(versionRecordStatus(ctx, os.Getenv))
|
||||
}
|
||||
if err := run(ctx, os.Getenv); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
@@ -125,6 +130,12 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
versionHistoryStore, versionHistoryRepo := httpapi.VersionHistoryStore(nil), ""
|
||||
if config.VersionHistoryGiteaBaseURL != "" {
|
||||
versionHistoryStore, versionHistoryRepo = postgresstore.NewStore(pool), config.VersionHistoryRepo
|
||||
info := version.Snapshot()
|
||||
if info.IdentityAvailable && info.CommitSHA != nil {
|
||||
if _, e := actionStore.EnqueueVersionHistorySync(ctx, config.VersionHistoryRepo, "system:deployment", *info.CommitSHA, time.Now()); e != nil {
|
||||
log.Print("version history deployment synchronization could not be queued")
|
||||
}
|
||||
}
|
||||
}
|
||||
qaReader, qaSettings := openQAOperations(ctx, getenv, config.DatabaseURL)
|
||||
if closer, ok := qaReader.(interface{ Close() }); ok {
|
||||
@@ -143,6 +154,7 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
qaSyncStore = qaOrganizationStore
|
||||
}
|
||||
handler, err := httpapi.NewHandler(httpapi.Config{
|
||||
QAQuality: qaopsquality.NewStore(pool, getenv("DOBOTAI_OPS_TENANT_KEY")),
|
||||
QAOrgSync: qaSyncStore,
|
||||
QAOrgSyncEnabled: qaSyncErr == nil && qaSyncSettings.Enabled,
|
||||
QAOrg: qaOrganizationStore,
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/appconfig"
|
||||
"knowledge-governance/internal/version"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Operator-only read-back in the existing API binary; no new public endpoint,
|
||||
// no session/credential creation and no migrations or remote forge access.
|
||||
func versionRecordStatus(ctx context.Context, getenv func(string) string) int {
|
||||
info := version.Snapshot()
|
||||
if !info.IdentityAvailable || info.CommitSHA == nil {
|
||||
return printVersionStatus(false, "build_identity_missing", "")
|
||||
}
|
||||
config, e := appconfig.Load(getenv)
|
||||
if e != nil {
|
||||
return printVersionStatus(false, "configuration_invalid", *info.CommitSHA)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
pool, e := pgxpool.New(ctx, config.DatabaseURL)
|
||||
if e != nil {
|
||||
return printVersionStatus(false, "database_unavailable", *info.CommitSHA)
|
||||
}
|
||||
defer pool.Close()
|
||||
tag := "snapshot/v" + info.DisplayVersion
|
||||
kind := "development"
|
||||
if info.BuildKind == "release" {
|
||||
tag = "v" + info.DisplayVersion
|
||||
kind = "release"
|
||||
}
|
||||
evidence, _ := json.Marshal([]map[string]any{{"name": tag, "annotated": true}})
|
||||
var ready bool
|
||||
e = pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM version_history_commits c WHERE repo_key=$1 AND commit_sha=$2 AND version_label=$3 AND record_kind=$4 AND btrim(release_notes)<>'' AND release_tags @> $5::jsonb AND snapshot_id=(SELECT max(id) FROM version_history_sync_runs WHERE repo_key=$1 AND status='completed' AND complete))`, config.VersionHistoryRepo, *info.CommitSHA, info.DisplayVersion, kind, evidence).Scan(&ready)
|
||||
if e != nil {
|
||||
return printVersionStatus(false, "database_unavailable", *info.CommitSHA)
|
||||
}
|
||||
if !ready {
|
||||
return printVersionStatus(false, "version_record_pending", *info.CommitSHA)
|
||||
}
|
||||
return printVersionStatus(true, "verified", *info.CommitSHA)
|
||||
}
|
||||
func printVersionStatus(ready bool, code, sha string) int {
|
||||
raw, _ := json.Marshal(map[string]any{"ready": ready, "code": code, "commit_sha": sha})
|
||||
fmt.Fprintln(os.Stdout, string(raw))
|
||||
if ready {
|
||||
return 0
|
||||
}
|
||||
return 1
|
||||
}
|
||||
+10
-1
@@ -137,11 +137,20 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
|
||||
triggeredBy := ""
|
||||
var payload struct {
|
||||
TriggeredBy string `json:"triggered_by"`
|
||||
TargetSHA string `json:"target_sha"`
|
||||
}
|
||||
if err := json.Unmarshal(job.Payload, &payload); err == nil {
|
||||
triggeredBy = payload.TriggeredBy
|
||||
}
|
||||
run, err := syncer.Sync(ctx, job.ID, triggeredBy)
|
||||
activeSyncer := syncer
|
||||
if payload.TargetSHA != "" {
|
||||
var e error
|
||||
activeSyncer, e = versionhistory.NewSyncer(versionhistory.SyncerConfig{Source: client, Store: store, RepoKey: config.VersionHistoryRepo, MaxPages: config.VersionHistoryMaxPages, TargetSHAs: []string{payload.TargetSHA}})
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
run, err := activeSyncer.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
|
||||
|
||||
+2
-2
@@ -14,7 +14,7 @@ server {
|
||||
set $api_upstream http://api:8080;
|
||||
proxy_pass $api_upstream;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
@@ -22,7 +22,7 @@ server {
|
||||
location = /health {
|
||||
set $health_upstream http://api:8080;
|
||||
proxy_pass $health_upstream/health;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header Host $http_host;
|
||||
}
|
||||
|
||||
# 带内容哈希的构建产物:可以长期缓存(换版本必然换文件名);旧哈希文件已被新构建替换
|
||||
|
||||
@@ -44,12 +44,16 @@ type UsageGroups struct {
|
||||
func decodeRecord(raw string) (Record, error) {
|
||||
var wire struct {
|
||||
Record
|
||||
Identity ActorIdentity `json:"_identity"`
|
||||
Identity ActorIdentity `json:"_identity"`
|
||||
QualityHash string `json:"_quality_hash"`
|
||||
QualityObservedAt time.Time `json:"_quality_observed_at"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(raw), &wire); err != nil {
|
||||
return Record{}, err
|
||||
}
|
||||
wire.Record.Identity = wire.Identity
|
||||
wire.Record.QualityInputHash = wire.QualityHash
|
||||
wire.Record.QualityObservedAt = wire.QualityObservedAt
|
||||
wire.Record.Coverage = CheckAnswerCoverage(wire.Record.Answer)
|
||||
return wire.Record, nil
|
||||
}
|
||||
|
||||
@@ -27,6 +27,9 @@ func TestQARecordInternalIdentityAndWholeFilterKeys(t *testing.T) {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if len(page.ScopeQuality) != 4 || len(page.Items[0].QualityInputHash) != 64 {
|
||||
t.Fatal("whole-scope quality versions missing")
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("whole-filter keys missing; later-page department would be hidden")
|
||||
}
|
||||
@@ -34,6 +37,15 @@ func TestQARecordInternalIdentityAndWholeFilterKeys(t *testing.T) {
|
||||
if err != nil || item.Identity.StaffID != "ext-actor-1" || item.Identity.UnionID != "fixture-union" {
|
||||
t.Fatalf("stable identity not read from inbound actor/message: %v", err)
|
||||
}
|
||||
scope, se := client.ReadQualityScope(context.Background(), query)
|
||||
if se != nil || len(scope.Keys) != 4 || scope.AsOf.IsZero() {
|
||||
t.Fatal("quality metadata scope incomplete", se)
|
||||
}
|
||||
for _, key := range scope.Keys {
|
||||
if len(key.InputHash) != 64 || key.ObservedAt.IsZero() {
|
||||
t.Fatal("scope omitted input version")
|
||||
}
|
||||
}
|
||||
raw, _ := json.Marshal(page)
|
||||
detail, _ := json.Marshal(item)
|
||||
for _, s := range []string{string(raw), string(detail)} {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
type QualityScope struct {
|
||||
Keys []QualityKey
|
||||
AsOf time.Time
|
||||
}
|
||||
|
||||
func (c *Client) ReadQualityScope(ctx context.Context, query RecordQuery) (QualityScope, error) {
|
||||
if err := c.validateQueryWindow(query.Window); err != nil {
|
||||
return QualityScope{}, err
|
||||
}
|
||||
if query.Cursor != "" {
|
||||
return QualityScope{}, ErrInvalidQuery
|
||||
}
|
||||
pattern, err := recordKeywordPattern(query.Keyword)
|
||||
if err != nil {
|
||||
return QualityScope{}, err
|
||||
}
|
||||
result := QualityScope{Keys: []QualityKey{}}
|
||||
err = c.withReadOnlyTx(ctx, func(ctx context.Context, q querier) error {
|
||||
if q.QueryRow(ctx, "SELECT transaction_timestamp()").Scan(&result.AsOf) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
rows, err := q.Query(ctx, recordsBaseSQL+` SELECT id,quality_hash,strpos(payload->>'answer',$5)>0,(payload->'source_coverage')::text FROM records WHERE `+recordFilterSQL+` ORDER BY id LIMIT 5001`, query.Window.TenantKey, query.Window.Start, query.Window.End, pattern, noPublishedMarker)
|
||||
if err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var key QualityKey
|
||||
var raw string
|
||||
if rows.Scan(&key.ID, &key.InputHash, &key.Marker, &raw) != nil || json.Unmarshal([]byte(raw), &key.Source) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
if len(result.Keys) >= 5000 {
|
||||
return ErrInvalidQuery
|
||||
}
|
||||
key.ObservedAt = result.AsOf
|
||||
result.Keys = append(result.Keys, key)
|
||||
}
|
||||
return rows.Err()
|
||||
})
|
||||
return result, err
|
||||
}
|
||||
@@ -29,8 +29,11 @@ type CoverageCheck struct {
|
||||
|
||||
// Absence of this exact substring is not evidence that knowledge covers a question.
|
||||
func CheckAnswerCoverage(answer string) CoverageCheck {
|
||||
return CheckMarkerCoverage(strings.Contains(answer, noPublishedMarker))
|
||||
}
|
||||
func CheckMarkerCoverage(matched bool) CoverageCheck {
|
||||
result := CoverageCheck{State: "pending", RuleVersion: CoverageRuleVersion}
|
||||
if strings.Contains(answer, noPublishedMarker) {
|
||||
if matched {
|
||||
result.State = "checked"
|
||||
result.Verdict = "uncovered"
|
||||
result.MatchedText = noPublishedMarker
|
||||
@@ -51,23 +54,26 @@ type RecordFeedback struct {
|
||||
}
|
||||
|
||||
type Record struct {
|
||||
Identity ActorIdentity `json:"-"`
|
||||
Organization *RecordOrganization `json:"organization,omitempty"`
|
||||
ID string `json:"id"`
|
||||
Status string `json:"status"`
|
||||
Question string `json:"question"`
|
||||
Answer string `json:"answer"`
|
||||
AskedAt time.Time `json:"asked_at"`
|
||||
TimeSource string `json:"time_source"`
|
||||
Asker string `json:"asker"`
|
||||
TriggerPerson string `json:"trigger_person"`
|
||||
Department string `json:"department"`
|
||||
Region string `json:"region"`
|
||||
References json.RawMessage `json:"references"`
|
||||
Media json.RawMessage `json:"media"`
|
||||
SourceCoverage SourceCoverage `json:"source_coverage"`
|
||||
Feedback RecordFeedback `json:"feedback"`
|
||||
Coverage CoverageCheck `json:"coverage"`
|
||||
QualityObservedAt time.Time `json:"-"`
|
||||
QualityInputHash string `json:"-"`
|
||||
Quality json.RawMessage `json:"quality,omitempty"`
|
||||
Identity ActorIdentity `json:"-"`
|
||||
Organization *RecordOrganization `json:"organization,omitempty"`
|
||||
ID string `json:"id"`
|
||||
Status string `json:"status"`
|
||||
Question string `json:"question"`
|
||||
Answer string `json:"answer"`
|
||||
AskedAt time.Time `json:"asked_at"`
|
||||
TimeSource string `json:"time_source"`
|
||||
Asker string `json:"asker"`
|
||||
TriggerPerson string `json:"trigger_person"`
|
||||
Department string `json:"department"`
|
||||
Region string `json:"region"`
|
||||
References json.RawMessage `json:"references"`
|
||||
Media json.RawMessage `json:"media"`
|
||||
SourceCoverage SourceCoverage `json:"source_coverage"`
|
||||
Feedback RecordFeedback `json:"feedback"`
|
||||
Coverage CoverageCheck `json:"coverage"`
|
||||
}
|
||||
|
||||
type RecordQuery struct {
|
||||
@@ -77,7 +83,15 @@ type RecordQuery struct {
|
||||
Limit int
|
||||
}
|
||||
|
||||
type QualityKey struct {
|
||||
ObservedAt time.Time `json:"-"`
|
||||
Marker bool `json:"marker"`
|
||||
Source SourceCoverage `json:"source"`
|
||||
ID string `json:"id"`
|
||||
InputHash string `json:"input_hash"`
|
||||
}
|
||||
type RecordPage struct {
|
||||
ScopeQuality []QualityKey `json:"-"`
|
||||
ScopeActors []ActorIdentity `json:"-"`
|
||||
Organization *OrganizationVersion `json:"organization,omitempty"`
|
||||
Items []Record `json:"items"`
|
||||
@@ -97,11 +111,12 @@ type recordCursor struct {
|
||||
// A single inbound-message join controls names/time. Feedback is preaggregated;
|
||||
// joining each feedback row directly would multiply the business event count.
|
||||
const actorIdentitySQL = `jsonb_build_object('actor_id',COALESCE(a.id,''),'staff_id',COALESCE(a.external_actor_id,''),'union_id',COALESCE(m.actor_union_id_snapshot,''))`
|
||||
const qualityHashSQL = `encode(sha256(convert_to(jsonb_build_array('quality-input-v1',t.id,t.status,t.question,t.answer,t.references_json,COALESCE(m.media_json,'[]'::jsonb))::text,'UTF8')),'hex')`
|
||||
const recordsBaseSQL = `
|
||||
WITH records AS (
|
||||
SELECT t.id,COALESCE(m.created_at,t.created_at) AS asked_at,t.question,t.status,` + actorIdentitySQL + ` AS identity,
|
||||
SELECT t.id,COALESCE(m.created_at,t.created_at) AS asked_at,t.question,t.status,` + actorIdentitySQL + ` AS identity,` + qualityHashSQL + ` AS quality_hash,
|
||||
jsonb_build_object(
|
||||
'_identity',` + actorIdentitySQL + `,
|
||||
'_identity',` + actorIdentitySQL + `, '_quality_hash',` + qualityHashSQL + `,'_quality_observed_at',transaction_timestamp(),
|
||||
'id',t.id,'status',t.status,'question',t.question,'answer',t.answer,
|
||||
'asked_at',COALESCE(m.created_at,t.created_at),
|
||||
'time_source',CASE WHEN m.id IS NULL THEN 'turn.created_at' ELSE 'request_message.created_at' END,
|
||||
@@ -143,7 +158,7 @@ const recordColumnsSQL = `SELECT count(*),jsonb_build_object(
|
||||
'region',COALESCE(bool_or(payload->>'region'<>''),false),
|
||||
'feedback',COALESCE(bool_or(payload->'feedback'->>'asker_value'<>'' OR
|
||||
(payload->'feedback'->>'up')::bigint>0 OR (payload->'feedback'->>'down')::bigint>0),false)
|
||||
)::text,COALESCE(jsonb_agg(DISTINCT identity),'[]'::jsonb)::text FROM records WHERE `
|
||||
)::text,COALESCE(jsonb_agg(DISTINCT identity),'[]'::jsonb)::text,COALESCE(jsonb_agg(jsonb_build_object('id',id,'input_hash',quality_hash,'marker',strpos(payload->>'answer',$5)>0,'source',payload->'source_coverage')),'[]'::jsonb)::text FROM records WHERE `
|
||||
|
||||
var recordColumnOrder = []string{"question_chinese", "answer", "coverage", "is_correct", "product_category", "problem_type", "root_cause", "asked_at", "asker", "question", "language", "trigger_person", "department", "region", "feedback"}
|
||||
|
||||
@@ -186,10 +201,16 @@ func (c *Client) ListRecords(ctx context.Context, query RecordQuery) (RecordPage
|
||||
if err := q.QueryRow(ctx, "SELECT transaction_timestamp()").Scan(&page.AsOf); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
var rawColumns, rawActors string
|
||||
if err := q.QueryRow(ctx, recordsBaseSQL+recordColumnsSQL+recordFilterSQL, append(args, noPublishedMarker)...).Scan(&page.Total, &rawColumns, &rawActors); err != nil {
|
||||
var rawColumns, rawActors, rawQuality string
|
||||
if err := q.QueryRow(ctx, recordsBaseSQL+recordColumnsSQL+recordFilterSQL, append(args, noPublishedMarker)...).Scan(&page.Total, &rawColumns, &rawActors, &rawQuality); err != nil {
|
||||
return fmt.Errorf("%w: record count failed", ErrUnavailable)
|
||||
}
|
||||
if json.Unmarshal([]byte(rawQuality), &page.ScopeQuality) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
for i := range page.ScopeQuality {
|
||||
page.ScopeQuality[i].ObservedAt = page.AsOf
|
||||
}
|
||||
var available map[string]bool
|
||||
if json.Unmarshal([]byte(rawActors), &page.ScopeActors) != nil {
|
||||
return ErrUnavailable
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package governance
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Development headings cannot replace the formal release baseline.
|
||||
func ExtractDevelopmentNotes(changelog, version string) string {
|
||||
if !SemverValid(version) {
|
||||
return ""
|
||||
}
|
||||
lines := strings.Split(changelog, "\n")
|
||||
prefix := "## 开发快照 snapshot/v" + version + " - "
|
||||
for i, line := range lines {
|
||||
if strings.HasPrefix(line, prefix) {
|
||||
end := len(lines)
|
||||
for j := i + 1; j < len(lines); j++ {
|
||||
if strings.HasPrefix(lines[j], "## ") {
|
||||
end = j
|
||||
break
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(strings.Join(lines[i+1:end], "\n"))
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -104,6 +104,10 @@ func listQAOpsRecords(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
return
|
||||
}
|
||||
enrichQAPage(&page, projection)
|
||||
if err := enrichQAQualityPage(r.Context(), config, &page); err != nil {
|
||||
writeQualityError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": page})
|
||||
}
|
||||
|
||||
@@ -130,6 +134,10 @@ func getQAOpsRecord(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
return
|
||||
}
|
||||
enrichQARecord(&item, projection)
|
||||
if err := enrichQAQualityRecord(r.Context(), config, &item); err != nil {
|
||||
writeQualityError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": item})
|
||||
}
|
||||
|
||||
|
||||
@@ -17,8 +17,11 @@ type QAOrgSyncStore interface {
|
||||
}
|
||||
|
||||
func authorizeQAOrganizationWrite(w http.ResponseWriter, r *http.Request) bool {
|
||||
if r.Header.Get("X-Governance-Action") != "qa-organization" || r.Header.Get("Sec-Fetch-Site") == "cross-site" {
|
||||
writeJSON(w, 403, map[string]string{"error": "区域配置需要同源操作意图"})
|
||||
return authorizeQAIntent(w, r, "qa-organization")
|
||||
}
|
||||
func authorizeQAIntent(w http.ResponseWriter, r *http.Request, intent string) bool {
|
||||
if r.Header.Get("X-Governance-Action") != intent || r.Header.Get("Sec-Fetch-Site") == "cross-site" {
|
||||
writeJSON(w, 403, map[string]string{"error": "此操作需要同源操作意图"})
|
||||
return false
|
||||
}
|
||||
// Fetch Metadata survives same-origin proxies that rewrite Host; untrusted
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"regexp"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// HTTP LAN/tailnet origins may omit Fetch Metadata. nginx must preserve the
|
||||
// external authority including its port so Origin can be checked without it.
|
||||
func TestQAProxyPreservesBrowserAuthority(t *testing.T) {
|
||||
config, err := os.ReadFile("../../deploy/nginx.conf")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hosts := regexp.MustCompile(`(?m)^\s*proxy_set_header\s+Host\s+([^;]+);`).FindAllStringSubmatch(string(config), -1)
|
||||
if len(hosts) < 2 {
|
||||
t.Fatal("API and health proxy Host directives must both be explicit")
|
||||
}
|
||||
for _, host := range hosts {
|
||||
if host[1] != "$http_host" {
|
||||
t.Fatalf("proxy drops browser authority/port: got %q, want $http_host", host[1])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestQAIntentWithoutFetchMetadataChecksExactAuthority(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, host, origin, forwarded, site, intent string
|
||||
allowed bool
|
||||
}{
|
||||
{"LAN same authority", "192.168.50.134:8088", "http://192.168.50.134:8088", "", "", "qa-quality", true},
|
||||
{"tailnet same authority", "100.92.49.78:8088", "http://100.92.49.78:8088", "", "", "qa-quality", true},
|
||||
{"proxy stripped port", "192.168.50.134", "http://192.168.50.134:8088", "", "", "qa-quality", false},
|
||||
{"foreign origin", "192.168.50.134:8088", "http://foreign.invalid:8088", "", "", "qa-quality", false},
|
||||
{"different port", "192.168.50.134:8088", "http://192.168.50.134:8089", "", "", "qa-quality", false},
|
||||
{"forwarded header cannot grant", "192.168.50.134:8088", "http://foreign.invalid:8088", "foreign.invalid:8088", "", "qa-quality", false},
|
||||
{"opaque origin", "192.168.50.134:8088", "null", "", "", "qa-quality", false},
|
||||
{"explicit cross site", "192.168.50.134:8088", "http://192.168.50.134:8088", "", "cross-site", "qa-quality", false},
|
||||
{"missing intent", "192.168.50.134:8088", "http://192.168.50.134:8088", "", "", "", false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
req := httptest.NewRequest("POST", "http://"+tc.host+"/api/v1/qa-ops/quality/query", nil)
|
||||
req.Header.Set("Origin", tc.origin)
|
||||
req.Header.Set("X-Governance-Action", tc.intent)
|
||||
if tc.forwarded != "" {
|
||||
req.Header.Set("X-Forwarded-Host", tc.forwarded)
|
||||
}
|
||||
if tc.site != "" {
|
||||
req.Header.Set("Sec-Fetch-Site", tc.site)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
if got := authorizeQAIntent(rec, req, "qa-quality"); got != tc.allowed {
|
||||
t.Fatalf("authorized=%v want %v, HTTP=%d", got, tc.allowed, rec.Code)
|
||||
}
|
||||
if !tc.allowed && rec.Code != 403 {
|
||||
t.Fatalf("rejected authority should be 403, got %d", rec.Code)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
type QAQualityStore interface {
|
||||
ObserveKeys(context.Context, []dobotaiops.QualityKey) (map[string]qaopsquality.View, error)
|
||||
Observe(context.Context, []dobotaiops.Record) (map[string]qaopsquality.View, error)
|
||||
Save(context.Context, dobotaiops.Record, qaopsquality.SaveRequest, string) (qaopsquality.Receipt, error)
|
||||
Columns(context.Context, []dobotaiops.QualityKey) ([]string, error)
|
||||
History(context.Context, string, int64, int64) (qaopsquality.History, error)
|
||||
Snapshot(context.Context, string, int64) (qaopsquality.Snapshot, error)
|
||||
}
|
||||
|
||||
type qaQualityReader interface {
|
||||
ReadQualityScope(context.Context, dobotaiops.RecordQuery) (dobotaiops.QualityScope, error)
|
||||
}
|
||||
|
||||
func writeQualityError(w http.ResponseWriter, err error) {
|
||||
status, code, message := 503, "quality_unavailable", "质量留档/复核存储不可用,未将失败伪装为空值或零统计"
|
||||
switch {
|
||||
case errors.Is(err, qaopsquality.ErrInvalid) || errors.Is(err, dobotaiops.ErrInvalidQuery):
|
||||
status, code, message = 400, "invalid_quality_request", "质量操作参数无效:请核对结论、理由、版本和筛选范围(最多5000条/32MiB)"
|
||||
case errors.Is(err, qaopsquality.ErrConflict):
|
||||
status, code, message = 409, "quality_conflict", "原始问答或人工复核版本已变化,请重新读取问答后核对;未覆盖现有结论"
|
||||
case errors.Is(err, qaopsquality.ErrSnapshotMissing):
|
||||
status, code, message = 409, "quality_input_metadata_only", "此版本仅留存指纹与复检元数据,未采集原文;未编造空问题或空答案"
|
||||
case errors.Is(err, qaopsquality.ErrNotFound):
|
||||
status, code, message = 404, "quality_input_not_found", "未找到当前授权范围的输入版本"
|
||||
}
|
||||
writeJSON(w, status, map[string]string{"error": message, "code": code})
|
||||
}
|
||||
func enrichQAQualityRecord(ctx context.Context, c Config, item *dobotaiops.Record) error {
|
||||
if c.QAQuality == nil {
|
||||
return nil
|
||||
}
|
||||
views, err := c.QAQuality.Observe(ctx, []dobotaiops.Record{*item})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
v, ok := views[item.ID]
|
||||
if !ok {
|
||||
return qaopsquality.ErrUnavailable
|
||||
}
|
||||
item.Quality, err = json.Marshal(v)
|
||||
return err
|
||||
}
|
||||
func enrichQAQualityPage(ctx context.Context, c Config, page *dobotaiops.RecordPage) error {
|
||||
if c.QAQuality == nil {
|
||||
return nil
|
||||
}
|
||||
views, err := c.QAQuality.Observe(ctx, page.Items)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for i := range page.Items {
|
||||
v, ok := views[page.Items[i].ID]
|
||||
if !ok {
|
||||
return qaopsquality.ErrUnavailable
|
||||
}
|
||||
page.Items[i].Quality, err = json.Marshal(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
columns, err := c.QAQuality.Columns(ctx, page.ScopeQuality)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dobotaiops.AddRecordColumns(page, columns...)
|
||||
return nil
|
||||
}
|
||||
func walkQualityJSON(d *json.Decoder) error {
|
||||
token, err := d.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if token == nil {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
if delimiter, ok := token.(json.Delim); ok {
|
||||
if delimiter != '{' && delimiter != '[' {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
keys := map[string]bool{}
|
||||
for d.More() {
|
||||
if delimiter == '{' {
|
||||
key, e := d.Token()
|
||||
name, ok := key.(string)
|
||||
if e != nil || !ok || keys[name] {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
keys[name] = true
|
||||
}
|
||||
if walkQualityJSON(d) != nil {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
}
|
||||
_, err = d.Token()
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func decodeQualityJSON(w http.ResponseWriter, r *http.Request, target any, required ...string) error {
|
||||
if r.URL.RawQuery != "" {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 64<<10))
|
||||
if err != nil || bytes.Equal(bytes.TrimSpace(raw), []byte("null")) {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
var top map[string]json.RawMessage
|
||||
if json.Unmarshal(raw, &top) != nil || top == nil {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
for _, key := range required {
|
||||
if _, ok := top[key]; !ok {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
}
|
||||
check := json.NewDecoder(bytes.NewReader(raw))
|
||||
if walkQualityJSON(check) != nil {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
var extra any
|
||||
if check.Decode(&extra) != io.EOF {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
d := json.NewDecoder(bytes.NewReader(raw))
|
||||
d.DisallowUnknownFields()
|
||||
if d.Decode(target) != nil || d.Decode(&extra) != io.EOF {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func qaQualityReview(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) || !authorizeQAIntent(w, r, "qa-quality") {
|
||||
return
|
||||
}
|
||||
var request qaopsquality.SaveRequest
|
||||
if decodeQualityJSON(w, r, &request, "input_hash", "input_epoch", "base_revision", "nonce", "fields", "reason") != nil || qaopsquality.Validate(request) != nil {
|
||||
writeQualityError(w, qaopsquality.ErrInvalid)
|
||||
return
|
||||
}
|
||||
if c.QAQuality == nil || c.QAOps == nil || c.QAOpsTenantKey == "" {
|
||||
writeQualityError(w, qaopsquality.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
record, err := c.QAOps.GetRecord(r.Context(), c.QAOpsTenantKey, r.PathValue("id"))
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
identity, _ := sessionFrom(r.Context())
|
||||
receipt, err := c.QAQuality.Save(r.Context(), record, request, identity.Username)
|
||||
if err != nil {
|
||||
writeQualityError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": receipt})
|
||||
}
|
||||
func qaQualityQuery(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) || !authorizeQAIntent(w, r, "qa-quality") {
|
||||
return
|
||||
}
|
||||
var request struct {
|
||||
Start string `json:"start"`
|
||||
End string `json:"end"`
|
||||
Keyword string `json:"keyword"`
|
||||
}
|
||||
if decodeQualityJSON(w, r, &request) != nil {
|
||||
writeQualityError(w, qaopsquality.ErrInvalid)
|
||||
return
|
||||
}
|
||||
window, err := dobotaiops.NewWindow(c.QAOpsTenantKey, request.Start, request.End, 90*24*time.Hour, c.Now())
|
||||
if err != nil {
|
||||
writeQualityError(w, err)
|
||||
return
|
||||
}
|
||||
reader, ok := c.QAOps.(qaQualityReader)
|
||||
if !ok || c.QAQuality == nil {
|
||||
writeQualityError(w, qaopsquality.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
scope, err := reader.ReadQualityScope(r.Context(), dobotaiops.RecordQuery{Window: window, Keyword: request.Keyword})
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
views, err := c.QAQuality.ObserveKeys(r.Context(), scope.Keys)
|
||||
if err != nil || len(views) != len(scope.Keys) {
|
||||
if err == nil {
|
||||
err = qaopsquality.ErrUnavailable
|
||||
}
|
||||
writeQualityError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": map[string]any{"summary": qaopsquality.Summarize(views), "start": window.Start, "end": window.End, "keyword": request.Keyword, "as_of": scope.AsOf, "ai_state": "not_configured", "scope": "whole_filter"}})
|
||||
}
|
||||
func qaQualityHistory(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
if c.QAQuality == nil {
|
||||
writeQualityError(w, qaopsquality.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
values := r.URL.Query()
|
||||
for key, v := range values {
|
||||
if (key != "review_before" && key != "check_before") || len(v) != 1 {
|
||||
writeQualityError(w, qaopsquality.ErrInvalid)
|
||||
return
|
||||
}
|
||||
}
|
||||
cursors := map[string]int64{}
|
||||
for _, key := range []string{"review_before", "check_before"} {
|
||||
raw := values.Get(key)
|
||||
if raw == "" {
|
||||
continue
|
||||
}
|
||||
n, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || n < 1 {
|
||||
writeQualityError(w, qaopsquality.ErrInvalid)
|
||||
return
|
||||
}
|
||||
cursors[key] = n
|
||||
}
|
||||
value, err := c.QAQuality.History(r.Context(), r.PathValue("id"), cursors["review_before"], cursors["check_before"])
|
||||
if err != nil {
|
||||
writeQualityError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": value})
|
||||
}
|
||||
func qaQualitySnapshot(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
epoch, err := strconv.ParseInt(r.PathValue("epoch"), 10, 64)
|
||||
if err != nil || epoch < 1 || r.URL.RawQuery != "" {
|
||||
writeQualityError(w, qaopsquality.ErrInvalid)
|
||||
return
|
||||
}
|
||||
if c.QAQuality == nil {
|
||||
writeQualityError(w, qaopsquality.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
value, err := c.QAQuality.Snapshot(r.Context(), r.PathValue("id"), epoch)
|
||||
if err != nil {
|
||||
writeQualityError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": value})
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type qualityFake struct {
|
||||
actor string
|
||||
calls int
|
||||
fail bool
|
||||
}
|
||||
|
||||
func (s *qualityFake) Observe(_ context.Context, records []dobotaiops.Record) (map[string]qaopsquality.View, error) {
|
||||
s.calls++
|
||||
if s.fail {
|
||||
return nil, qaopsquality.ErrUnavailable
|
||||
}
|
||||
out := map[string]qaopsquality.View{}
|
||||
for _, r := range records {
|
||||
e, _ := qaopsquality.EvidenceFor(r)
|
||||
out[r.ID] = qaopsquality.Project(e.Hash, 1, 0, qaopsquality.Check{InputEpoch: 1, InputHash: e.Hash, Result: dobotaiops.CheckAnswerCoverage(r.Answer)}, nil)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func (s *qualityFake) ObserveKeys(_ context.Context, keys []dobotaiops.QualityKey) (map[string]qaopsquality.View, error) {
|
||||
s.calls++
|
||||
out := map[string]qaopsquality.View{}
|
||||
for _, key := range keys {
|
||||
out[key.ID] = qaopsquality.Project(key.InputHash, 1, 0, qaopsquality.Check{Result: dobotaiops.CheckMarkerCoverage(key.Marker)}, nil)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func (s *qualityFake) Save(_ context.Context, r dobotaiops.Record, q qaopsquality.SaveRequest, actor string) (qaopsquality.Receipt, error) {
|
||||
s.actor = actor
|
||||
v := qaopsquality.Project(q.InputHash, 1, 1, qaopsquality.Check{Result: dobotaiops.CheckAnswerCoverage(r.Answer)}, &qaopsquality.Review{InputEpoch: 1, InputHash: q.InputHash, Fields: q.Fields, Reason: q.Reason, Reviewer: actor})
|
||||
return qaopsquality.Receipt{View: v, SavedRevision: 1}, nil
|
||||
}
|
||||
func (s *qualityFake) Columns(_ context.Context, keys []dobotaiops.QualityKey) ([]string, error) {
|
||||
return []string{"is_correct", "product_category"}, nil
|
||||
}
|
||||
func (s *qualityFake) History(context.Context, string, int64, int64) (qaopsquality.History, error) {
|
||||
return qaopsquality.History{Reviews: []qaopsquality.Review{}, Checks: []qaopsquality.Check{}}, nil
|
||||
}
|
||||
func (s *qualityFake) Snapshot(context.Context, string, int64) (qaopsquality.Snapshot, error) {
|
||||
return qaopsquality.Snapshot{}, qaopsquality.ErrNotFound
|
||||
}
|
||||
|
||||
type qualitySource struct {
|
||||
attributedReader
|
||||
record dobotaiops.Record
|
||||
tenant string
|
||||
scopeCalls int
|
||||
}
|
||||
|
||||
func (s *qualitySource) GetRecord(_ context.Context, tenant, id string) (dobotaiops.Record, error) {
|
||||
s.tenant = tenant
|
||||
return s.record, nil
|
||||
}
|
||||
func (s *qualitySource) ListRecords(_ context.Context, q dobotaiops.RecordQuery) (dobotaiops.RecordPage, error) {
|
||||
return dobotaiops.RecordPage{Items: []dobotaiops.Record{s.record}, Columns: []string{"question"}, Total: 2, AsOf: time.Now()}, nil
|
||||
}
|
||||
func (s *qualitySource) ReadQualityScope(_ context.Context, q dobotaiops.RecordQuery) (dobotaiops.QualityScope, error) {
|
||||
s.scopeCalls++
|
||||
s.tenant = q.Window.TenantKey
|
||||
second := s.record
|
||||
second.ID = "second-turn"
|
||||
keys := []dobotaiops.QualityKey{}
|
||||
for _, r := range []dobotaiops.Record{s.record, second} {
|
||||
e, _ := qaopsquality.EvidenceFor(r)
|
||||
keys = append(keys, dobotaiops.QualityKey{ID: r.ID, InputHash: e.Hash, Marker: e.Result.Verdict == "uncovered", Source: r.SourceCoverage})
|
||||
}
|
||||
return dobotaiops.QualityScope{Keys: keys, AsOf: time.Now()}, nil
|
||||
}
|
||||
func qualityTestHandler(t *testing.T) (http.Handler, *qualityFake, *qualitySource) {
|
||||
t.Helper()
|
||||
store := &qualityFake{}
|
||||
source := &qualitySource{record: dobotaiops.Record{ID: "fixture-turn", Status: "succeeded", Question: "示例", Answer: "暂无已发布"}}
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["quality-admin"] = "usr-boss"
|
||||
auth.sessions["quality-viewer"] = "usr-eye"
|
||||
h, e := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}, QAOps: source, QAOpsTenantKey: "fixed", QAQuality: store, Now: func() time.Time { return time.Date(2026, 10, 17, 0, 0, 0, 0, time.UTC) }})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return h, store, source
|
||||
}
|
||||
func qualityRequest(h http.Handler, method, path, token, body string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
r.Header.Set("X-Governance-Action", "qa-quality")
|
||||
if token != "" {
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: token})
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
func TestQAQualityDetailListAndWholeScopeCounts(t *testing.T) {
|
||||
h, store, source := qualityTestHandler(t)
|
||||
w := qualityRequest(h, "GET", "/api/v1/qa-ops/records/fixture-turn", "quality-admin", "")
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"quality"`) {
|
||||
t.Fatal("persisted quality absent in detail", w.Code)
|
||||
}
|
||||
w = qualityRequest(h, "GET", "/api/v1/qa-ops/records?start=2026-10-14T00:00:00Z&end=2026-10-15T00:00:00Z", "quality-admin", "")
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"is_correct"`) {
|
||||
t.Fatal("whole-filter quality columns absent")
|
||||
}
|
||||
w = qualityRequest(h, "POST", "/api/v1/qa-ops/quality/query", "quality-admin", `{"start":"2026-10-14T00:00:00Z","end":"2026-10-15T00:00:00Z","keyword":""}`)
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"unreviewed":2`) || source.scopeCalls != 1 || source.tenant != "fixed" || store.calls < 2 {
|
||||
t.Fatal("quality summary estimated from page instead of scope", w.Code, w.Body.String())
|
||||
}
|
||||
var counts struct {
|
||||
Data struct {
|
||||
Summary qaopsquality.Summary `json:"summary"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if json.Unmarshal(w.Body.Bytes(), &counts) != nil || counts.Data.Summary.Rates.Coverage.Denominator != 2 || counts.Data.Summary.Rates.Coverage.Numerator != 0 || counts.Data.Summary.Rates.Correctness.Percent != nil {
|
||||
t.Fatal("confirmed quality metrics were not computed for the whole scope")
|
||||
}
|
||||
store.fail = true
|
||||
w = qualityRequest(h, "GET", "/api/v1/qa-ops/records/fixture-turn", "quality-admin", "")
|
||||
if w.Code != 503 || !strings.Contains(w.Body.String(), "quality_unavailable") {
|
||||
t.Fatal("quality storage failure presented as empty success")
|
||||
}
|
||||
}
|
||||
func TestQAQualityReviewUsesSessionActorAndStrictReadOnlySourceBoundary(t *testing.T) {
|
||||
h, store, source := qualityTestHandler(t)
|
||||
e, _ := qaopsquality.EvidenceFor(source.record)
|
||||
q := qaopsquality.SaveRequest{InputHash: e.Hash, InputEpoch: 1, Nonce: strings.Repeat("n", 32), Fields: qaopsquality.Fields{Coverage: "uncovered", Correctness: "pending"}, Reason: "人工核对"}
|
||||
raw, _ := json.Marshal(q)
|
||||
path := "/api/v1/qa-ops/records/fixture-turn/reviews"
|
||||
w := qualityRequest(h, "POST", path, "quality-admin", string(raw))
|
||||
if w.Code != 200 || store.actor != "boss" || source.tenant != "fixed" {
|
||||
t.Fatal("manual review failed or actor came from request", w.Code, store.actor)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
token, body string
|
||||
status int
|
||||
}{{"", string(raw), 401}, {"quality-viewer", string(raw), 403}, {"quality-admin", strings.TrimSuffix(string(raw), "}") + `,"reviewer":"forged"}`, 400}, {"quality-admin", `null`, 400}, {"quality-admin", string(raw) + `{}`, 400}, {"quality-admin", `{"nonce":"a","nonce":"b"}`, 400}} {
|
||||
w = qualityRequest(h, "POST", path, tc.token, tc.body)
|
||||
if w.Code != tc.status {
|
||||
t.Fatal("review boundary failed", w.Code, tc.status)
|
||||
}
|
||||
}
|
||||
r := httptest.NewRequest("POST", path, strings.NewReader(string(raw)))
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "quality-admin"})
|
||||
r.Header.Set("X-Governance-Action", "qa-quality")
|
||||
r.Header.Set("Sec-Fetch-Site", "cross-site")
|
||||
w = httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != 403 {
|
||||
t.Fatal("cross-site review accepted")
|
||||
}
|
||||
w = qualityRequest(h, "GET", path+"/invalid", "quality-admin", "")
|
||||
if w.Code != 404 {
|
||||
t.Fatal("unknown endpoint silently accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQAQualityReviewRejectsMissingRevisionAndNestedNull(t *testing.T) {
|
||||
h, _, source := qualityTestHandler(t)
|
||||
e, _ := qaopsquality.EvidenceFor(source.record)
|
||||
q := qaopsquality.SaveRequest{InputHash: e.Hash, InputEpoch: 1, Nonce: strings.Repeat("n", 32), Fields: qaopsquality.Fields{Coverage: "pending", Correctness: "pending"}, Reason: "示例复核"}
|
||||
raw, _ := json.Marshal(q)
|
||||
for _, body := range []string{strings.Replace(string(raw), `"base_revision":0,`, "", 1), strings.Replace(string(raw), `"base_revision":0`, `"base_revision":null`, 1), strings.Replace(string(raw), `"product_category":""`, `"product_category":null`, 1)} {
|
||||
w := qualityRequest(h, "POST", "/api/v1/qa-ops/records/fixture-turn/reviews", "quality-admin", body)
|
||||
if w.Code != 400 {
|
||||
t.Fatal("missing/null version or field silently became a default", w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -102,6 +102,7 @@ type Store interface {
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
QAQuality QAQualityStore
|
||||
QAOrgSync QAOrgSyncStore
|
||||
QAOrgSyncEnabled bool
|
||||
QAOrg QAOrgStore
|
||||
@@ -175,6 +176,11 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
config.NewID = newID
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/quality/query", func(w http.ResponseWriter, r *http.Request) { qaQualityQuery(w, r, config) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/records/{id}/reviews", func(w http.ResponseWriter, r *http.Request) { qaQualityReview(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/records/{id}/quality/history", func(w http.ResponseWriter, r *http.Request) { qaQualityHistory(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/records/{id}/quality/inputs/{epoch}", func(w http.ResponseWriter, r *http.Request) { qaQualitySnapshot(w, r, config) })
|
||||
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/usage/people", func(w http.ResponseWriter, r *http.Request) { qaMonthlyPeople(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/usage", func(w http.ResponseWriter, r *http.Request) { qaOpsUsage(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/organization/sync", func(w http.ResponseWriter, r *http.Request) { qaOrganizationSync(w, r, config) })
|
||||
|
||||
@@ -225,10 +225,26 @@ func versionHistorySync(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
versionHistoryError(w, http.StatusInternalServerError, "version_history_unavailable", "构造同步任务失败")
|
||||
return
|
||||
}
|
||||
if queue, ok := config.Store.(interface {
|
||||
EnqueueVersionHistorySync(context.Context, string, string, string, time.Time) (*jobs.Job, error)
|
||||
}); ok {
|
||||
target := ""
|
||||
info := version.Snapshot()
|
||||
if info.IdentityAvailable && info.CommitSHA != nil {
|
||||
target = *info.CommitSHA
|
||||
}
|
||||
job, e := queue.EnqueueVersionHistorySync(r.Context(), config.VersionHistoryRepo, triggeredBy, target, now)
|
||||
if e != nil || job == nil {
|
||||
versionHistoryError(w, 500, "version_history_unavailable", "入队同步任务失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, 202, map[string]any{"job_id": job.ID, "status": job.State})
|
||||
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)
|
||||
IdempotencyKey: "version-history.sync:" + config.VersionHistoryRepo + ":" + requestedID}, now)
|
||||
if err != nil || job == nil {
|
||||
versionHistoryError(w, http.StatusInternalServerError, "version_history_unavailable", "入队同步任务失败")
|
||||
return
|
||||
|
||||
@@ -237,7 +237,7 @@ func TestVersionHistorySyncRequiresAdminAndEnqueuesOnce(t *testing.T) {
|
||||
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" {
|
||||
if queue.enqueued.Type != VersionHistoryJobType || queue.enqueued.IdempotencyKey != "version-history.sync:Weknora/knowledge-governance:"+queue.enqueued.ID {
|
||||
t.Fatalf("入队参数不对:%+v", queue.enqueued)
|
||||
}
|
||||
if queue.enqueued.MaxAttempts != 3 || queue.enqueued.AvailableAt != now {
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
DROP TABLE qa_ops_quality_reviews;
|
||||
DROP TABLE qa_ops_quality_checks;
|
||||
DROP TABLE qa_ops_quality_inputs;
|
||||
DROP TABLE qa_ops_quality_records;
|
||||
@@ -0,0 +1,13 @@
|
||||
CREATE TABLE qa_ops_quality_records (
|
||||
tenant_key TEXT NOT NULL,record_id TEXT NOT NULL,observed_at TIMESTAMPTZ,input_hash TEXT NOT NULL DEFAULT '',input_epoch BIGINT NOT NULL DEFAULT 0 CHECK(input_epoch>=0),review_revision BIGINT NOT NULL DEFAULT 0 CHECK(review_revision>=0),PRIMARY KEY(tenant_key,record_id)
|
||||
);
|
||||
CREATE TABLE qa_ops_quality_inputs (
|
||||
tenant_key TEXT NOT NULL,record_id TEXT NOT NULL,input_epoch BIGINT NOT NULL CHECK(input_epoch>0),input_hash TEXT NOT NULL CHECK(input_hash ~ '^[a-f0-9]{64}$'),payload JSONB CHECK(payload IS NULL OR jsonb_typeof(payload)='object'),created_at TIMESTAMPTZ NOT NULL DEFAULT now(),PRIMARY KEY(tenant_key,record_id,input_epoch),FOREIGN KEY(tenant_key,record_id) REFERENCES qa_ops_quality_records(tenant_key,record_id)
|
||||
);
|
||||
CREATE TABLE qa_ops_quality_checks (
|
||||
id BIGSERIAL PRIMARY KEY,tenant_key TEXT NOT NULL,record_id TEXT NOT NULL,input_epoch BIGINT NOT NULL,rule_version TEXT NOT NULL,result JSONB NOT NULL CHECK(jsonb_typeof(result)='object'),source JSONB NOT NULL CHECK(jsonb_typeof(source)='object'),created_at TIMESTAMPTZ NOT NULL DEFAULT now(),UNIQUE(tenant_key,record_id,input_epoch,rule_version),FOREIGN KEY(tenant_key,record_id,input_epoch) REFERENCES qa_ops_quality_inputs(tenant_key,record_id,input_epoch)
|
||||
);
|
||||
CREATE TABLE qa_ops_quality_reviews (
|
||||
tenant_key TEXT NOT NULL,record_id TEXT NOT NULL,revision BIGINT NOT NULL CHECK(revision>0),input_epoch BIGINT NOT NULL,input_hash TEXT NOT NULL CHECK(input_hash ~ '^[a-f0-9]{64}$'),fields JSONB NOT NULL CHECK(jsonb_typeof(fields)='object'),reason TEXT NOT NULL CHECK(length(btrim(reason))>0),reviewer TEXT NOT NULL CHECK(length(btrim(reviewer))>0),nonce TEXT NOT NULL,request_hash TEXT NOT NULL,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),PRIMARY KEY(tenant_key,record_id,revision),UNIQUE(tenant_key,record_id,nonce),FOREIGN KEY(tenant_key,record_id,input_epoch) REFERENCES qa_ops_quality_inputs(tenant_key,record_id,input_epoch)
|
||||
);
|
||||
CREATE INDEX idx_qa_quality_checks_history ON qa_ops_quality_checks(tenant_key,record_id,id DESC);
|
||||
@@ -11,8 +11,8 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("loadMigrations() error = %v", err)
|
||||
}
|
||||
if len(migrations) != 48 {
|
||||
t.Fatalf("migration count = %d, want 48", len(migrations))
|
||||
if len(migrations) != 49 {
|
||||
t.Fatalf("migration count = %d, want 49", 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])
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/versionhistory"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (s *Store) EnqueueVersionHistorySync(ctx context.Context, repo, actor, target string, now time.Time) (*jobs.Job, error) {
|
||||
if strings.Count(repo, "/") != 1 || strings.TrimSpace(repo) != repo || len(repo) > 200 || actor == "" || len(actor) > 256 || target != "" && !regexp.MustCompile(`^[a-f0-9]{40}$`).MatchString(target) {
|
||||
return nil, errors.New("invalid version synchronization request")
|
||||
}
|
||||
tx, e := s.db.Begin(ctx)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
if _, e = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, "version-history:"+repo); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
// Retire exhausted expired owners. Terminal jobs are history, not a perpetual
|
||||
// idempotency key: a later refresh must be allowed to execute again.
|
||||
if _, e = tx.Exec(ctx, `UPDATE jobs SET state='failed',lease_owner=NULL,lease_until=NULL,updated_at=$3 WHERE type=$1 AND payload->>'repo_key'=$2 AND state='running' AND lease_until<clock_timestamp() AND attempt>=max_attempts`, versionhistory.JobType, repo, now); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
var active string
|
||||
e = tx.QueryRow(ctx, `SELECT id FROM jobs WHERE type=$1 AND payload->>'repo_key'=$2 AND state IN ('pending','running','retry') ORDER BY created_at DESC,id DESC LIMIT 1`, versionhistory.JobType, repo).Scan(&active)
|
||||
if e != nil && !errors.Is(e, pgx.ErrNoRows) {
|
||||
return nil, e
|
||||
}
|
||||
if active != "" {
|
||||
job, e := scanJob(tx.QueryRow(ctx, `SELECT id,type,payload,state,priority,available_at,lease_owner,lease_until,attempt,max_attempts,last_error,idempotency_key,created_at,updated_at FROM jobs WHERE id=$1`, active))
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if e = tx.Commit(ctx); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
return job, nil
|
||||
}
|
||||
var random [16]byte
|
||||
if _, e = rand.Read(random[:]); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
id := "vh-" + hex.EncodeToString(random[:])
|
||||
payload, _ := json.Marshal(map[string]string{"repo_key": repo, "triggered_by": actor, "target_sha": target})
|
||||
job, e := NewStore(tx).Enqueue(ctx, jobs.EnqueueRequest{ID: id, Type: versionhistory.JobType, Payload: payload, AvailableAt: now, MaxAttempts: 3, IdempotencyKey: "version-history:" + repo + ":" + id}, now)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if e = tx.Commit(ctx); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
return job, nil
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/versionhistory"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestVersionHistorySyncQueueCanRefreshAfterCompletion(t *testing.T) {
|
||||
dsn := os.Getenv("KG_VERSION_HISTORY_TEST_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("explicit disposable version-history DB required")
|
||||
}
|
||||
u, e := url.Parse(dsn)
|
||||
if e != nil || u.Hostname() != "127.0.0.1" || !strings.HasPrefix(u.Path, "/kg_version_history_test_") {
|
||||
t.Fatal("refusing shared database")
|
||||
}
|
||||
ctx := context.Background()
|
||||
p, e := pgxpool.New(ctx, dsn)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer p.Close()
|
||||
if e = ApplyMigrations(ctx, p); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
s := NewStore(p)
|
||||
one, e := s.EnqueueVersionHistorySync(ctx, "fixture/repo", "fixture-admin", strings.Repeat("a", 40), time.Now())
|
||||
if e != nil || one == nil {
|
||||
t.Fatal("first sync missing", e)
|
||||
}
|
||||
same, e := s.EnqueueVersionHistorySync(ctx, "fixture/repo", "fixture-admin", strings.Repeat("a", 40), time.Now())
|
||||
if e != nil || same.ID != one.ID {
|
||||
t.Fatal("pending sync not coalesced", e)
|
||||
}
|
||||
claimed, e := s.Claim(ctx, "fixture-worker", []string{versionhistory.JobType}, time.Now(), time.Minute)
|
||||
if e != nil || claimed == nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = s.Complete(ctx, claimed.ID, claimed.LeaseOwner, time.Now()); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
next, e := s.EnqueueVersionHistorySync(ctx, "fixture/repo", "fixture-admin", strings.Repeat("b", 40), time.Now())
|
||||
if e != nil || next == nil || next.ID == one.ID || next.State != "pending" {
|
||||
t.Fatal("completed request was replayed forever instead of starting a new refresh", e)
|
||||
}
|
||||
}
|
||||
@@ -134,6 +134,19 @@ func TestOrganizationStoreRoundTripAndOptimisticConflict(t *testing.T) {
|
||||
if err = pool.QueryRow(ctx, "SELECT count(*) FROM qa_ops_region_revisions WHERE tenant_key=$1", "fixture-tenant").Scan(&revisions); err != nil || revisions != 2 {
|
||||
t.Fatal("revision history changed unexpectedly")
|
||||
}
|
||||
// This test exercises migration 48, not whichever unrelated migration is latest.
|
||||
for {
|
||||
var latest int64
|
||||
if pool.QueryRow(ctx, "SELECT max(version) FROM schema_migrations").Scan(&latest) != nil {
|
||||
t.Fatal("migration version unavailable")
|
||||
}
|
||||
if latest <= 48 {
|
||||
break
|
||||
}
|
||||
if postgresstore.RollbackLatestMigration(ctx, pool) != nil {
|
||||
t.Fatal("could not reach organization migration")
|
||||
}
|
||||
}
|
||||
if err = postgresstore.RollbackLatestMigration(ctx, pool); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
package qaopsquality
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
var hashPattern = regexp.MustCompile(`^[a-f0-9]{64}$`)
|
||||
var noncePattern = regexp.MustCompile(`^[A-Za-z0-9_-]{16,128}$`)
|
||||
|
||||
func validText(s string, max int) bool {
|
||||
return utf8.ValidString(s) && utf8.RuneCountInString(s) <= max && !strings.ContainsRune(s, 0)
|
||||
}
|
||||
func validID(s string) bool { return strings.TrimSpace(s) != "" && validText(s, 256) }
|
||||
func canonical(raw json.RawMessage) (json.RawMessage, error) {
|
||||
if len(raw) == 0 {
|
||||
return json.RawMessage("null"), nil
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(raw))
|
||||
decoder.UseNumber()
|
||||
var v any
|
||||
if decoder.Decode(&v) != nil {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
var extra any
|
||||
if decoder.Decode(&extra) != io.EOF {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
out, err := json.Marshal(v)
|
||||
return out, err
|
||||
}
|
||||
func EvidenceFor(record dobotaiops.Record) (Evidence, error) {
|
||||
if !validID(record.ID) {
|
||||
return Evidence{}, ErrInvalid
|
||||
}
|
||||
refs, err := canonical(record.References)
|
||||
if err != nil {
|
||||
return Evidence{}, ErrInvalid
|
||||
}
|
||||
media, err := canonical(record.Media)
|
||||
if err != nil {
|
||||
return Evidence{}, ErrInvalid
|
||||
}
|
||||
// Keep only assessment inputs, never personnel or mutable feedback/organisation.
|
||||
payload, err := json.Marshal(struct {
|
||||
Version string `json:"version"`
|
||||
ID string `json:"id"`
|
||||
Status string `json:"status"`
|
||||
Question string `json:"question"`
|
||||
Answer string `json:"answer"`
|
||||
References json.RawMessage `json:"references"`
|
||||
Media json.RawMessage `json:"media"`
|
||||
}{"dobotai-2.0-dingtalk-quality-v1", record.ID, record.Status, record.Question, record.Answer, refs, media})
|
||||
if err != nil || len(payload) > 8<<20 {
|
||||
return Evidence{}, ErrInvalid
|
||||
}
|
||||
sum := sha256.Sum256(payload)
|
||||
hash := hex.EncodeToString(sum[:])
|
||||
if record.QualityInputHash != "" {
|
||||
if !hashPattern.MatchString(record.QualityInputHash) {
|
||||
return Evidence{}, ErrInvalid
|
||||
}
|
||||
hash = record.QualityInputHash
|
||||
}
|
||||
return Evidence{Hash: hash, Payload: payload, Record: record, Result: dobotaiops.CheckAnswerCoverage(record.Answer)}, nil
|
||||
}
|
||||
func Validate(r SaveRequest) error {
|
||||
if !hashPattern.MatchString(r.InputHash) || r.InputEpoch < 1 || r.BaseRevision < 0 || !noncePattern.MatchString(r.Nonce) || strings.TrimSpace(r.Reason) == "" || !validText(r.Reason, 4000) {
|
||||
return ErrInvalid
|
||||
}
|
||||
f := r.Fields
|
||||
validCoverage := false
|
||||
for _, s := range []string{"covered", "uncovered", "partial", "pending", "excluded"} {
|
||||
validCoverage = validCoverage || f.Coverage == s
|
||||
}
|
||||
if !validCoverage || (f.Correctness != "correct" && f.Correctness != "incorrect" && f.Correctness != "pending") {
|
||||
return ErrInvalid
|
||||
}
|
||||
if !validText(f.ProductCategory, 128) || !validText(f.ProblemType, 128) || !validText(f.RootCause, 2000) || !validText(f.ExclusionReason, 2000) {
|
||||
return ErrInvalid
|
||||
}
|
||||
if f.Correctness == "correct" && f.RootCause != "" || f.Coverage == "excluded" && strings.TrimSpace(f.ExclusionReason) == "" || f.Coverage != "excluded" && f.ExclusionReason != "" {
|
||||
return ErrInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func Project(hash string, epoch, revision int64, automatic Check, review *Review) View {
|
||||
view := View{InputHash: hash, InputEpoch: epoch, Revision: revision, State: "unreviewed", Automatic: automatic, LatestReview: review, Effective: Fields{Coverage: automatic.Result.Verdict}}
|
||||
if review == nil {
|
||||
return view
|
||||
}
|
||||
view.State = "stale"
|
||||
if review.InputEpoch == epoch && review.InputHash == hash {
|
||||
view.State = "reviewed"
|
||||
view.Effective = review.Fields
|
||||
}
|
||||
return view
|
||||
}
|
||||
func Summarize(views map[string]View) Summary {
|
||||
result := Summary{Total: len(views), Rates: ComputeRates(views)}
|
||||
for _, v := range views {
|
||||
switch v.State {
|
||||
case "reviewed":
|
||||
result.Reviewed++
|
||||
if v.Effective.Coverage == "pending" || v.Effective.Correctness == "pending" {
|
||||
result.PendingConfirmation++
|
||||
}
|
||||
case "stale":
|
||||
result.Stale++
|
||||
default:
|
||||
result.Unreviewed++
|
||||
}
|
||||
if v.Automatic.Result.Verdict == "uncovered" {
|
||||
result.RuleUncovered++
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package qaopsquality
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrInvalid = errors.New("invalid quality request")
|
||||
var ErrConflict = errors.New("quality input or review revision changed")
|
||||
var ErrUnavailable = errors.New("quality store unavailable")
|
||||
var ErrNotFound = errors.New("quality input snapshot not found")
|
||||
var ErrSnapshotMissing = errors.New("only quality metadata was observed for this input")
|
||||
|
||||
type Fields struct {
|
||||
Coverage string `json:"coverage"`
|
||||
Correctness string `json:"correctness"`
|
||||
ProductCategory string `json:"product_category"`
|
||||
ProblemType string `json:"problem_type"`
|
||||
RootCause string `json:"root_cause"`
|
||||
ExclusionReason string `json:"exclusion_reason"`
|
||||
}
|
||||
type SaveRequest struct {
|
||||
InputHash string `json:"input_hash"`
|
||||
InputEpoch int64 `json:"input_epoch"`
|
||||
BaseRevision int64 `json:"base_revision"`
|
||||
Nonce string `json:"nonce"`
|
||||
Fields Fields `json:"fields"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
type Review struct {
|
||||
Revision int64 `json:"revision"`
|
||||
InputEpoch int64 `json:"input_epoch"`
|
||||
InputHash string `json:"input_hash"`
|
||||
Fields Fields `json:"fields"`
|
||||
Reason string `json:"reason"`
|
||||
Reviewer string `json:"reviewer"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
type Check struct {
|
||||
InputAvailable bool `json:"input_available"`
|
||||
ID int64 `json:"id"`
|
||||
InputEpoch int64 `json:"input_epoch"`
|
||||
InputHash string `json:"input_hash"`
|
||||
Result dobotaiops.CoverageCheck `json:"result"`
|
||||
Source dobotaiops.SourceCoverage `json:"source"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
type View struct {
|
||||
InputHash string `json:"input_hash"`
|
||||
InputEpoch int64 `json:"input_epoch"`
|
||||
Revision int64 `json:"revision"`
|
||||
State string `json:"state"`
|
||||
Automatic Check `json:"automatic"`
|
||||
LatestReview *Review `json:"latest_review"`
|
||||
Effective Fields `json:"effective"`
|
||||
}
|
||||
type History struct {
|
||||
Reviews []Review `json:"reviews"`
|
||||
Checks []Check `json:"checks"`
|
||||
NextReview int64 `json:"next_review"`
|
||||
NextCheck int64 `json:"next_check"`
|
||||
}
|
||||
type Summary struct {
|
||||
Rates Rates `json:"rates"`
|
||||
Total int `json:"total"`
|
||||
Reviewed int `json:"reviewed"`
|
||||
Unreviewed int `json:"unreviewed"`
|
||||
Stale int `json:"stale"`
|
||||
PendingConfirmation int `json:"pending_confirmation"`
|
||||
RuleUncovered int `json:"rule_uncovered"`
|
||||
}
|
||||
type Receipt struct {
|
||||
View View `json:"view"`
|
||||
SavedRevision int64 `json:"saved_revision"`
|
||||
Replayed bool `json:"replayed"`
|
||||
}
|
||||
type Evidence struct {
|
||||
Result dobotaiops.CoverageCheck
|
||||
Hash string
|
||||
Payload json.RawMessage
|
||||
Record dobotaiops.Record
|
||||
}
|
||||
|
||||
type Snapshot struct {
|
||||
InputEpoch int64 `json:"input_epoch"`
|
||||
InputHash string `json:"input_hash"`
|
||||
Payload json.RawMessage `json:"payload"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
tenant string
|
||||
}
|
||||
|
||||
func NewStore(pool *pgxpool.Pool, tenant string) *Store { return &Store{pool: pool, tenant: tenant} }
|
||||
@@ -0,0 +1,73 @@
|
||||
package qaopsquality
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEvidenceBindsQualityInputsNotPeopleFeedbackOrJSONKeyOrder(t *testing.T) {
|
||||
record := dobotaiops.Record{ID: "fixture-turn", Status: "succeeded", Question: "示例问题", Answer: "有暂无已发布但存在引用", References: json.RawMessage(`[{"b":2,"a":1}]`), Media: json.RawMessage(`[]`)}
|
||||
a, err := EvidenceFor(record)
|
||||
if err != nil || len(a.Hash) != 64 || !strings.Contains(string(a.Payload), record.Answer) {
|
||||
t.Fatal("quality inputs not snapshotted")
|
||||
}
|
||||
record.Asker = "another-person"
|
||||
record.Department = "changed"
|
||||
record.Feedback.Up = 10
|
||||
record.References = json.RawMessage(`[{"a":1,"b":2}]`)
|
||||
b, _ := EvidenceFor(record)
|
||||
if b.Hash != a.Hash {
|
||||
t.Fatal("irrelevant identity/feedback or JSON object ordering invalidated review")
|
||||
}
|
||||
record.Answer = "原答案变更"
|
||||
b, _ = EvidenceFor(record)
|
||||
if b.Hash == a.Hash {
|
||||
t.Fatal("answer change undetected")
|
||||
}
|
||||
}
|
||||
func TestHumanProjectionKeepsRuleAndStalesObservedInputChanges(t *testing.T) {
|
||||
automatic := Check{Result: dobotaiops.CheckAnswerCoverage("暂无已发布"), InputEpoch: 2, InputHash: strings.Repeat("a", 64)}
|
||||
review := &Review{InputEpoch: 1, InputHash: automatic.InputHash, Fields: Fields{Coverage: "covered", Correctness: "correct", ProductCategory: "MG400"}}
|
||||
view := Project(automatic.InputHash, 2, 1, automatic, review)
|
||||
if view.State != "stale" || view.Effective.Coverage != "uncovered" || view.Effective.Correctness != "" {
|
||||
t.Fatal("old conclusion remained effective after input epoch changed")
|
||||
}
|
||||
review.InputEpoch = 2
|
||||
view = Project(automatic.InputHash, 2, 1, automatic, review)
|
||||
if view.State != "reviewed" || view.Effective.Coverage != "covered" || view.Automatic.Result.Verdict != "uncovered" {
|
||||
t.Fatal("human and immutable rule not separated")
|
||||
}
|
||||
summary := Summarize(map[string]View{"a": view, "b": Project(automatic.InputHash, 3, 1, automatic, review), "c": Project(automatic.InputHash, 1, 0, automatic, nil)})
|
||||
if summary.Total != 3 || summary.Reviewed != 1 || summary.Stale != 1 || summary.Unreviewed != 1 || summary.PendingConfirmation != 0 {
|
||||
t.Fatal("quality counts invent rates or unknown judgments")
|
||||
}
|
||||
}
|
||||
func TestReviewRequiresExplicitOutcomesAndEvidence(t *testing.T) {
|
||||
valid := SaveRequest{InputHash: strings.Repeat("a", 64), InputEpoch: 1, Nonce: strings.Repeat("n", 32), Fields: Fields{Coverage: "uncovered", Correctness: "pending"}, Reason: "人工核对引用与答案,证据不足"}
|
||||
if Validate(valid) != nil {
|
||||
t.Fatal("valid review rejected")
|
||||
}
|
||||
for _, field := range []string{"reason", "hash", "coverage", "correctness", "root", "exclusion"} {
|
||||
bad := valid
|
||||
switch field {
|
||||
case "reason":
|
||||
bad.Reason = " "
|
||||
case "hash":
|
||||
bad.InputHash = "malformed"
|
||||
case "coverage":
|
||||
bad.Fields.Coverage = ""
|
||||
case "correctness":
|
||||
bad.Fields.Correctness = ""
|
||||
case "root":
|
||||
bad.Fields.Correctness = "correct"
|
||||
bad.Fields.RootCause = "知识缺失"
|
||||
case "exclusion":
|
||||
bad.Fields.Coverage = "excluded"
|
||||
}
|
||||
if Validate(bad) == nil {
|
||||
t.Fatal("invalid review accepted", field)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package qaopsquality
|
||||
|
||||
type Rate struct {
|
||||
Numerator int `json:"numerator"`
|
||||
Denominator int `json:"denominator"`
|
||||
Percent *float64 `json:"percent"`
|
||||
}
|
||||
type RateBreakdown struct {
|
||||
Covered int `json:"covered"`
|
||||
Uncovered int `json:"uncovered"`
|
||||
Partial int `json:"partial"`
|
||||
Pending int `json:"pending"`
|
||||
Unassessed int `json:"unassessed"`
|
||||
Excluded int `json:"excluded"`
|
||||
Stale int `json:"stale"`
|
||||
CoveredCorrect int `json:"covered_correct"`
|
||||
CoveredIncorrect int `json:"covered_incorrect"`
|
||||
CoveredPending int `json:"covered_pending"`
|
||||
CoveredUnassessed int `json:"covered_unassessed"`
|
||||
}
|
||||
type Rates struct {
|
||||
PolicyVersion string `json:"policy_version"`
|
||||
Coverage Rate `json:"coverage"`
|
||||
Correctness Rate `json:"correctness"`
|
||||
Breakdown RateBreakdown `json:"breakdown"`
|
||||
}
|
||||
|
||||
func ComputeRates(views map[string]View) Rates {
|
||||
out := Rates{PolicyVersion: "quality-rates-human-first-v1"}
|
||||
b := &out.Breakdown
|
||||
for _, v := range views {
|
||||
if v.State == "stale" {
|
||||
b.Stale++
|
||||
continue
|
||||
}
|
||||
switch v.Effective.Coverage {
|
||||
case "covered":
|
||||
b.Covered++
|
||||
switch v.Effective.Correctness {
|
||||
case "correct":
|
||||
b.CoveredCorrect++
|
||||
case "incorrect":
|
||||
b.CoveredIncorrect++
|
||||
case "pending":
|
||||
b.CoveredPending++
|
||||
default:
|
||||
b.CoveredUnassessed++
|
||||
}
|
||||
case "uncovered":
|
||||
b.Uncovered++
|
||||
case "partial":
|
||||
b.Partial++
|
||||
case "pending":
|
||||
b.Pending++
|
||||
case "excluded":
|
||||
b.Excluded++
|
||||
default:
|
||||
b.Unassessed++
|
||||
}
|
||||
}
|
||||
out.Coverage = makeRate(b.Covered, b.Covered+b.Uncovered+b.Partial)
|
||||
out.Correctness = makeRate(b.CoveredCorrect, b.CoveredCorrect+b.CoveredIncorrect)
|
||||
return out
|
||||
}
|
||||
func makeRate(numerator, denominator int) Rate {
|
||||
r := Rate{Numerator: numerator, Denominator: denominator}
|
||||
if denominator > 0 {
|
||||
p := 100 * float64(numerator) / float64(denominator)
|
||||
r.Percent = &p
|
||||
}
|
||||
return r
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package qaopsquality
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"math"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestQualityRatesUseEffectiveCurrentConclusionsAndExplicitDenominators(t *testing.T) {
|
||||
views := map[string]View{}
|
||||
for i, fields := range []Fields{{Coverage: "covered", Correctness: "correct"}, {Coverage: "covered", Correctness: "incorrect"}, {Coverage: "covered", Correctness: "pending"}, {Coverage: "uncovered"}, {Coverage: "partial", Correctness: "correct"}, {Coverage: "pending", Correctness: "correct"}, {}, {Coverage: "excluded", Correctness: "pending"}, {Coverage: "covered", Correctness: "correct"}, {Coverage: "covered"}} {
|
||||
state := "reviewed"
|
||||
if i == 3 || i == 6 {
|
||||
state = "unreviewed"
|
||||
}
|
||||
if i == 8 {
|
||||
state = "stale"
|
||||
}
|
||||
views[string(rune('a'+i))] = View{State: state, Effective: fields, Automatic: Check{Result: dobotaiops.CheckAnswerCoverage("暂无已发布")}}
|
||||
}
|
||||
r := ComputeRates(views)
|
||||
if r.PolicyVersion != "quality-rates-human-first-v1" || r.Coverage.Numerator != 4 || r.Coverage.Denominator != 6 || r.Correctness.Numerator != 1 || r.Correctness.Denominator != 2 {
|
||||
t.Fatal("effective decisions, partial or exclusion scopes incorrect", r)
|
||||
}
|
||||
if r.Coverage.Percent == nil || math.Abs(*r.Coverage.Percent-100*float64(4)/6) > 1e-10 || r.Correctness.Percent == nil || *r.Correctness.Percent != 50 {
|
||||
t.Fatal("ratio value disagrees with raw counts")
|
||||
}
|
||||
b := r.Breakdown
|
||||
if b.Covered+b.Uncovered+b.Partial+b.Pending+b.Unassessed+b.Excluded+b.Stale != len(views) || b.CoveredCorrect+b.CoveredIncorrect+b.CoveredPending+b.CoveredUnassessed != b.Covered {
|
||||
t.Fatal("denominator breakdown not conserved")
|
||||
}
|
||||
if got := Summarize(views); got.Rates.Coverage.Denominator != 6 {
|
||||
t.Fatal("scope summary did not consume the one shared calculation")
|
||||
}
|
||||
}
|
||||
func TestQualityRatesEmptyScopeHasNullPercent(t *testing.T) {
|
||||
r := ComputeRates(map[string]View{})
|
||||
raw, _ := json.Marshal(r)
|
||||
if r.Coverage.Percent != nil || r.Correctness.Percent != nil || strings.Count(string(raw), `"percent":null`) != 2 {
|
||||
t.Fatal("zero denominator fabricated zero or full rate")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
package qaopsquality
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"sort"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (s *Store) Columns(ctx context.Context, keys []dobotaiops.QualityKey) ([]string, error) {
|
||||
if !s.available() {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
if len(keys) > 100000 {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
for _, key := range keys {
|
||||
if !validID(key.ID) || !hashPattern.MatchString(key.InputHash) {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
}
|
||||
raw, err := json.Marshal(keys)
|
||||
if err != nil {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
if len(keys) == 0 {
|
||||
return []string{}, nil
|
||||
}
|
||||
var coverage, correctness, product, problem, root bool
|
||||
err = s.pool.QueryRow(ctx, `SELECT COALESCE(bool_or(r.fields->>'coverage'<>''),false),COALESCE(bool_or(r.fields->>'correctness'<>''),false),COALESCE(bool_or(r.fields->>'product_category'<>''),false),COALESCE(bool_or(r.fields->>'problem_type'<>''),false),COALESCE(bool_or(r.fields->>'root_cause'<>''),false) FROM jsonb_to_recordset($2::jsonb) k(id text,input_hash text) JOIN qa_ops_quality_records h ON h.tenant_key=$1 AND h.record_id=k.id AND h.input_hash=k.input_hash JOIN qa_ops_quality_reviews r ON r.tenant_key=h.tenant_key AND r.record_id=h.record_id AND r.revision=h.review_revision AND r.input_epoch=h.input_epoch`, s.tenant, raw).Scan(&coverage, &correctness, &product, &problem, &root)
|
||||
if err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
out := []string{}
|
||||
for _, c := range []struct {
|
||||
key string
|
||||
yes bool
|
||||
}{{"coverage", coverage}, {"is_correct", correctness}, {"product_category", product}, {"problem_type", problem}, {"root_cause", root}} {
|
||||
if c.yes {
|
||||
out = append(out, c.key)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func (s *Store) Snapshot(ctx context.Context, id string, epoch int64) (Snapshot, error) {
|
||||
if !s.available() {
|
||||
return Snapshot{}, ErrUnavailable
|
||||
}
|
||||
if !validID(id) || epoch < 1 {
|
||||
return Snapshot{}, ErrInvalid
|
||||
}
|
||||
var value Snapshot
|
||||
value.InputEpoch = epoch
|
||||
err := s.pool.QueryRow(ctx, `SELECT input_hash,payload,created_at FROM qa_ops_quality_inputs WHERE tenant_key=$1 AND record_id=$2 AND input_epoch=$3`, s.tenant, id, epoch).Scan(&value.InputHash, &value.Payload, &value.CreatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return Snapshot{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return Snapshot{}, ErrUnavailable
|
||||
}
|
||||
if len(value.Payload) == 0 {
|
||||
return Snapshot{}, ErrSnapshotMissing
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
func (s *Store) available() bool { return s != nil && s.pool != nil && validID(s.tenant) }
|
||||
func (s *Store) observeLocked(ctx context.Context, tx pgx.Tx, e Evidence) error {
|
||||
id := e.Record.ID
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO qa_ops_quality_records(tenant_key,record_id) VALUES($1,$2) ON CONFLICT DO NOTHING`, s.tenant, id); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
var previous string
|
||||
var epoch int64
|
||||
var observedAt *time.Time
|
||||
if tx.QueryRow(ctx, `SELECT input_hash,input_epoch,observed_at FROM qa_ops_quality_records WHERE tenant_key=$1 AND record_id=$2 FOR UPDATE`, s.tenant, id).Scan(&previous, &epoch, &observedAt) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
// Source transaction time orders concurrent page/detail/scope observations.
|
||||
// A late different input is rejected, never projected against a newer answer.
|
||||
if observedAt != nil && !e.Record.QualityObservedAt.IsZero() && e.Record.QualityObservedAt.Before(*observedAt) && previous != e.Hash {
|
||||
return ErrConflict
|
||||
}
|
||||
if !e.Record.QualityObservedAt.IsZero() {
|
||||
if _, err := tx.Exec(ctx, `UPDATE qa_ops_quality_records SET observed_at=$3 WHERE tenant_key=$1 AND record_id=$2 AND(observed_at IS NULL OR observed_at<$3)`, s.tenant, id, e.Record.QualityObservedAt); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
}
|
||||
var payload any
|
||||
if len(e.Payload) > 0 {
|
||||
payload = e.Payload
|
||||
}
|
||||
if previous != e.Hash {
|
||||
epoch++
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO qa_ops_quality_inputs(tenant_key,record_id,input_epoch,input_hash,payload) VALUES($1,$2,$3,$4,$5)`, s.tenant, id, epoch, e.Hash, payload); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
tag, err := tx.Exec(ctx, `UPDATE qa_ops_quality_records SET input_hash=$3,input_epoch=$4 WHERE tenant_key=$1 AND record_id=$2`, s.tenant, id, e.Hash, epoch)
|
||||
if err != nil || tag.RowsAffected() != 1 {
|
||||
return ErrUnavailable
|
||||
}
|
||||
}
|
||||
if payload != nil {
|
||||
if _, err := tx.Exec(ctx, `UPDATE qa_ops_quality_inputs SET payload=$4 WHERE tenant_key=$1 AND record_id=$2 AND input_epoch=$3 AND payload IS NULL`, s.tenant, id, epoch, payload); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
}
|
||||
automatic, _ := json.Marshal(e.Result)
|
||||
source, _ := json.Marshal(e.Record.SourceCoverage)
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO qa_ops_quality_checks(tenant_key,record_id,input_epoch,rule_version,result,source) VALUES($1,$2,$3,$4,$5,$6) ON CONFLICT(tenant_key,record_id,input_epoch,rule_version) DO NOTHING`, s.tenant, id, epoch, dobotaiops.CoverageRuleVersion, automatic, source); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const checkObject = `jsonb_build_object('id',c.id,'input_epoch',c.input_epoch,'input_hash',i.input_hash,'result',c.result,'source',c.source,'created_at',c.created_at,'input_available',i.payload IS NOT NULL)`
|
||||
const reviewObject = `jsonb_build_object('revision',r.revision,'input_epoch',r.input_epoch,'input_hash',r.input_hash,'fields',r.fields,'reason',r.reason,'reviewer',r.reviewer,'created_at',r.created_at)`
|
||||
|
||||
func (s *Store) view(ctx context.Context, tx pgx.Tx, id string) (View, error) {
|
||||
var hash, checkRaw, reviewRaw string
|
||||
var epoch, revision int64
|
||||
err := tx.QueryRow(ctx, `SELECT h.input_hash,h.input_epoch,h.review_revision,`+checkObject+`::text,COALESCE((SELECT `+reviewObject+` FROM qa_ops_quality_reviews r WHERE r.tenant_key=h.tenant_key AND r.record_id=h.record_id AND r.revision=h.review_revision),'null'::jsonb)::text FROM qa_ops_quality_records h JOIN qa_ops_quality_inputs i ON i.tenant_key=h.tenant_key AND i.record_id=h.record_id AND i.input_epoch=h.input_epoch JOIN qa_ops_quality_checks c ON c.tenant_key=h.tenant_key AND c.record_id=h.record_id AND c.input_epoch=h.input_epoch AND c.rule_version=$3 WHERE h.tenant_key=$1 AND h.record_id=$2`, s.tenant, id, dobotaiops.CoverageRuleVersion).Scan(&hash, &epoch, &revision, &checkRaw, &reviewRaw)
|
||||
var automatic Check
|
||||
var review *Review
|
||||
if err != nil || json.Unmarshal([]byte(checkRaw), &automatic) != nil || json.Unmarshal([]byte(reviewRaw), &review) != nil {
|
||||
return View{}, ErrUnavailable
|
||||
}
|
||||
return Project(hash, epoch, revision, automatic, review), nil
|
||||
}
|
||||
func (s *Store) Observe(ctx context.Context, records []dobotaiops.Record) (map[string]View, error) {
|
||||
if len(records) > 5000 {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
items := make([]Evidence, 0, len(records))
|
||||
for _, record := range records {
|
||||
e, err := EvidenceFor(record)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, e)
|
||||
}
|
||||
return s.observeEvidence(ctx, items)
|
||||
}
|
||||
func (s *Store) ObserveKeys(ctx context.Context, keys []dobotaiops.QualityKey) (map[string]View, error) {
|
||||
if len(keys) > 5000 {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
items := make([]Evidence, 0, len(keys))
|
||||
for _, key := range keys {
|
||||
if !validID(key.ID) || !hashPattern.MatchString(key.InputHash) {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
items = append(items, Evidence{Hash: key.InputHash, Record: dobotaiops.Record{ID: key.ID, SourceCoverage: key.Source, QualityObservedAt: key.ObservedAt}, Result: dobotaiops.CheckMarkerCoverage(key.Marker)})
|
||||
}
|
||||
return s.observeEvidence(ctx, items)
|
||||
}
|
||||
func (s *Store) observeEvidence(ctx context.Context, items []Evidence) (map[string]View, error) {
|
||||
if !s.available() {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
evidence := map[string]Evidence{}
|
||||
ids := []string{}
|
||||
bytes := 0
|
||||
for _, e := range items {
|
||||
id := e.Record.ID
|
||||
if old, ok := evidence[id]; ok {
|
||||
if old.Hash != e.Hash || old.Result != e.Result {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
continue
|
||||
}
|
||||
evidence[id] = e
|
||||
ids = append(ids, id)
|
||||
bytes += len(e.Payload)
|
||||
if bytes > 32<<20 {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
}
|
||||
sort.Strings(ids)
|
||||
result := map[string]View{}
|
||||
if len(ids) == 0 {
|
||||
return result, nil
|
||||
}
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
for _, id := range ids {
|
||||
if err = s.observeLocked(ctx, tx, evidence[id]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v, err := s.view(ctx, tx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result[id] = v
|
||||
}
|
||||
if tx.Commit(ctx) != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
func (s *Store) Save(ctx context.Context, record dobotaiops.Record, request SaveRequest, actor string) (Receipt, error) {
|
||||
if !s.available() {
|
||||
return Receipt{}, ErrUnavailable
|
||||
}
|
||||
if Validate(request) != nil || !validID(actor) {
|
||||
return Receipt{}, ErrInvalid
|
||||
}
|
||||
e, err := EvidenceFor(record)
|
||||
if err != nil {
|
||||
return Receipt{}, err
|
||||
}
|
||||
payload, _ := json.Marshal(request)
|
||||
sum := sha256.Sum256(payload)
|
||||
requestHash := hex.EncodeToString(sum[:])
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return Receipt{}, ErrUnavailable
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
if err = s.observeLocked(ctx, tx, e); err != nil {
|
||||
return Receipt{}, err
|
||||
}
|
||||
var existingHash, existingActor string
|
||||
var savedRevision int64
|
||||
err = tx.QueryRow(ctx, `SELECT request_hash,reviewer,revision FROM qa_ops_quality_reviews WHERE tenant_key=$1 AND record_id=$2 AND nonce=$3`, s.tenant, record.ID, request.Nonce).Scan(&existingHash, &existingActor, &savedRevision)
|
||||
replay := err == nil
|
||||
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
||||
return Receipt{}, ErrUnavailable
|
||||
}
|
||||
current, err := s.view(ctx, tx, record.ID)
|
||||
if err != nil {
|
||||
return Receipt{}, err
|
||||
}
|
||||
if replay {
|
||||
if existingHash != requestHash || existingActor != actor {
|
||||
return Receipt{}, ErrConflict
|
||||
}
|
||||
} else {
|
||||
if current.InputHash != request.InputHash || current.InputEpoch != request.InputEpoch || current.Revision != request.BaseRevision {
|
||||
if tx.Commit(ctx) != nil {
|
||||
return Receipt{}, ErrUnavailable
|
||||
}
|
||||
return Receipt{}, ErrConflict
|
||||
}
|
||||
savedRevision = current.Revision + 1
|
||||
fields, _ := json.Marshal(request.Fields)
|
||||
if _, err = tx.Exec(ctx, `INSERT INTO qa_ops_quality_reviews(tenant_key,record_id,revision,input_epoch,input_hash,fields,reason,reviewer,nonce,request_hash) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, s.tenant, record.ID, savedRevision, current.InputEpoch, current.InputHash, fields, request.Reason, actor, request.Nonce, requestHash); err != nil {
|
||||
return Receipt{}, ErrUnavailable
|
||||
}
|
||||
tag, err := tx.Exec(ctx, `UPDATE qa_ops_quality_records SET review_revision=$3 WHERE tenant_key=$1 AND record_id=$2`, s.tenant, record.ID, savedRevision)
|
||||
if err != nil || tag.RowsAffected() != 1 {
|
||||
return Receipt{}, ErrUnavailable
|
||||
}
|
||||
current, err = s.view(ctx, tx, record.ID)
|
||||
if err != nil {
|
||||
return Receipt{}, err
|
||||
}
|
||||
}
|
||||
if tx.Commit(ctx) != nil {
|
||||
return Receipt{}, ErrUnavailable
|
||||
}
|
||||
return Receipt{View: current, SavedRevision: savedRevision, Replayed: replay}, nil
|
||||
}
|
||||
func (s *Store) History(ctx context.Context, id string, reviewBefore, checkBefore int64) (History, error) {
|
||||
result := History{Reviews: []Review{}, Checks: []Check{}}
|
||||
if !s.available() {
|
||||
return result, ErrUnavailable
|
||||
}
|
||||
if !validID(id) || reviewBefore < 0 || checkBefore < 0 {
|
||||
return result, ErrInvalid
|
||||
}
|
||||
rows, err := s.pool.Query(ctx, `SELECT `+reviewObject+`::text FROM qa_ops_quality_reviews r WHERE tenant_key=$1 AND record_id=$2 AND ($3::bigint=0 OR revision<$3) ORDER BY revision DESC LIMIT 21`, s.tenant, id, reviewBefore)
|
||||
if err != nil {
|
||||
return result, ErrUnavailable
|
||||
}
|
||||
for rows.Next() {
|
||||
var raw string
|
||||
var value Review
|
||||
if rows.Scan(&raw) != nil || json.Unmarshal([]byte(raw), &value) != nil {
|
||||
rows.Close()
|
||||
return result, ErrUnavailable
|
||||
}
|
||||
result.Reviews = append(result.Reviews, value)
|
||||
}
|
||||
err = rows.Err()
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
return result, ErrUnavailable
|
||||
}
|
||||
if len(result.Reviews) > 20 {
|
||||
result.Reviews = result.Reviews[:20]
|
||||
result.NextReview = result.Reviews[19].Revision
|
||||
}
|
||||
rows, err = s.pool.Query(ctx, `SELECT `+checkObject+`::text FROM qa_ops_quality_checks c JOIN qa_ops_quality_inputs i USING(tenant_key,record_id,input_epoch) WHERE c.tenant_key=$1 AND c.record_id=$2 AND ($3::bigint=0 OR c.id<$3) ORDER BY c.id DESC LIMIT 21`, s.tenant, id, checkBefore)
|
||||
if err != nil {
|
||||
return result, ErrUnavailable
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var raw string
|
||||
var value Check
|
||||
if rows.Scan(&raw) != nil || json.Unmarshal([]byte(raw), &value) != nil {
|
||||
return result, ErrUnavailable
|
||||
}
|
||||
result.Checks = append(result.Checks, value)
|
||||
}
|
||||
if rows.Err() != nil {
|
||||
return result, ErrUnavailable
|
||||
}
|
||||
if len(result.Checks) > 20 {
|
||||
result.Checks = result.Checks[:20]
|
||||
result.NextCheck = result.Checks[19].ID
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package qaopsquality_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
pg "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestQualityStoreImmutableHistoryReplayConcurrencyAndStaleness(t *testing.T) {
|
||||
dsn := os.Getenv("KG_QAOPS_QUALITY_TEST_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("explicit disposable quality DB required")
|
||||
}
|
||||
u, e := url.Parse(dsn)
|
||||
if e != nil || u.Hostname() != "127.0.0.1" || !strings.HasPrefix(u.Path, "/kg_qaops_quality_test_") || os.Getenv("KG_QAOPS_QUALITY_TEST_ISOLATED") != "1" {
|
||||
t.Fatal("refusing shared quality database")
|
||||
}
|
||||
ctx := context.Background()
|
||||
pool, e := pgxpool.New(ctx, dsn)
|
||||
if e != nil {
|
||||
t.Fatal("fixture connection failed")
|
||||
}
|
||||
defer pool.Close()
|
||||
if e = pg.ApplyMigrations(ctx, pool); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
store := qaopsquality.NewStore(pool, "fixture-tenant")
|
||||
record := dobotaiops.Record{ID: "fixture-turn", Status: "succeeded", Question: "示例", Answer: "暂无已发布", AskedAt: time.Now()}
|
||||
views, e := store.Observe(ctx, []dobotaiops.Record{record})
|
||||
if e != nil {
|
||||
t.Fatal("source observation not persisted", e)
|
||||
}
|
||||
first := views[record.ID]
|
||||
again, e := store.Observe(ctx, []dobotaiops.Record{record})
|
||||
if e != nil || again[record.ID].Automatic.ID != first.Automatic.ID {
|
||||
t.Fatal("repeated GET duplicated immutable checks")
|
||||
}
|
||||
metaKey := dobotaiops.QualityKey{ID: "metadata-only-turn", InputHash: strings.Repeat("f", 64), Marker: true}
|
||||
meta, me := store.ObserveKeys(ctx, []dobotaiops.QualityKey{metaKey})
|
||||
if me != nil || meta[metaKey.ID].Automatic.InputAvailable {
|
||||
t.Fatal("compact scope observation not stored honestly", me)
|
||||
}
|
||||
if _, me = store.Snapshot(ctx, metaKey.ID, 1); !errors.Is(me, qaopsquality.ErrSnapshotMissing) {
|
||||
t.Fatal("metadata-only input fabricated an empty original")
|
||||
}
|
||||
full, me := store.Observe(ctx, []dobotaiops.Record{{ID: metaKey.ID, QualityInputHash: metaKey.InputHash, Question: "示例", Answer: "暂无已发布"}})
|
||||
if me != nil || !full[metaKey.ID].Automatic.InputAvailable || full[metaKey.ID].Automatic.ID != meta[metaKey.ID].Automatic.ID {
|
||||
t.Fatal("reading full content duplicated/replaced the same check")
|
||||
}
|
||||
req := qaopsquality.SaveRequest{InputHash: first.InputHash, InputEpoch: first.InputEpoch, BaseRevision: first.Revision, Nonce: strings.Repeat("n", 32), Fields: qaopsquality.Fields{Coverage: "covered", Correctness: "correct", ProductCategory: "MG400", ProblemType: "咨询"}, Reason: "人工核对有效引用"}
|
||||
saved, e := store.Save(ctx, record, req, "fixture-admin")
|
||||
if e != nil || saved.View.State != "reviewed" || saved.View.Effective.Coverage != "covered" || saved.View.Automatic.Result.Verdict != "uncovered" || saved.View.LatestReview.Reviewer != "fixture-admin" {
|
||||
t.Fatal("manual override lost audit/rule separation", e)
|
||||
}
|
||||
cols, ce := store.Columns(ctx, []dobotaiops.QualityKey{{ID: record.ID, InputHash: first.InputHash}})
|
||||
if ce != nil || len(cols) != 4 {
|
||||
t.Fatal("review fields absent from whole-scope projection", ce)
|
||||
}
|
||||
replay, e := store.Save(ctx, record, req, "fixture-admin")
|
||||
if e != nil || !replay.Replayed || replay.SavedRevision != saved.SavedRevision {
|
||||
t.Fatal("retry duplicated review")
|
||||
}
|
||||
bad := req
|
||||
bad.Reason = "changed body"
|
||||
if _, e = store.Save(ctx, record, bad, "fixture-admin"); !errors.Is(e, qaopsquality.ErrConflict) {
|
||||
t.Fatal("nonce reused with different request")
|
||||
}
|
||||
if _, e = store.Save(ctx, record, req, "other-admin"); !errors.Is(e, qaopsquality.ErrConflict) {
|
||||
t.Fatal("nonce replay changed operator")
|
||||
}
|
||||
record.Answer = "新答案"
|
||||
changed, e := store.Observe(ctx, []dobotaiops.Record{record})
|
||||
if e != nil || changed[record.ID].State != "stale" || changed[record.ID].Effective.Correctness != "" {
|
||||
t.Fatal("old manual result silently survived change")
|
||||
}
|
||||
if _, e = store.Save(ctx, record, req, "fixture-admin"); e != nil {
|
||||
t.Fatal("old completed request should replay without a new review")
|
||||
}
|
||||
record.Answer = "暂无已发布"
|
||||
reverted, e := store.Observe(ctx, []dobotaiops.Record{record})
|
||||
v := reverted[record.ID]
|
||||
if e != nil || v.InputHash != first.InputHash || v.InputEpoch <= first.InputEpoch || v.State != "stale" {
|
||||
t.Fatal("answer revert reactivated old judgment")
|
||||
}
|
||||
req.InputHash = v.InputHash
|
||||
req.InputEpoch = v.InputEpoch
|
||||
req.BaseRevision = v.Revision
|
||||
start := make(chan struct{})
|
||||
results := make(chan error, 2)
|
||||
for _, nonce := range []string{strings.Repeat("a", 32), strings.Repeat("b", 32)} {
|
||||
go func(nonce string) {
|
||||
q := req
|
||||
q.Nonce = nonce
|
||||
<-start
|
||||
_, err := store.Save(ctx, record, q, "fixture-admin")
|
||||
results <- err
|
||||
}(nonce)
|
||||
}
|
||||
close(start)
|
||||
success, conflict := 0, 0
|
||||
for range 2 {
|
||||
e = <-results
|
||||
if e == nil {
|
||||
success++
|
||||
} else if errors.Is(e, qaopsquality.ErrConflict) {
|
||||
conflict++
|
||||
} else {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
if success != 1 || conflict != 1 {
|
||||
t.Fatal("concurrent reviewers overwrote each other")
|
||||
}
|
||||
h, e := store.History(ctx, record.ID, 0, 0)
|
||||
if e != nil || len(h.Reviews) != 2 || len(h.Checks) != 3 || h.Checks[0].InputEpoch != 3 {
|
||||
t.Fatal("history missing/replaced", e)
|
||||
}
|
||||
oldInput, oe := store.Snapshot(ctx, record.ID, 1)
|
||||
if oe != nil || oldInput.InputHash != first.InputHash || !strings.Contains(string(oldInput.Payload), "暂无已发布") {
|
||||
t.Fatal("old assessment evidence not readable")
|
||||
}
|
||||
// A slow older source scan must not roll back a newer observed input.
|
||||
ordered := dobotaiops.Record{ID: "ordered-source-turn", Answer: "旧输入", QualityObservedAt: time.Now().Add(-time.Minute)}
|
||||
oldEvidence, _ := qaopsquality.EvidenceFor(ordered)
|
||||
if _, e = store.Observe(ctx, []dobotaiops.Record{ordered}); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
ordered.Answer = "新输入"
|
||||
ordered.QualityObservedAt = ordered.QualityObservedAt.Add(time.Second)
|
||||
newViews, ne := store.Observe(ctx, []dobotaiops.Record{ordered})
|
||||
if ne != nil {
|
||||
t.Fatal(ne)
|
||||
}
|
||||
newView := newViews[ordered.ID]
|
||||
if _, e = store.ObserveKeys(ctx, []dobotaiops.QualityKey{{ID: ordered.ID, InputHash: oldEvidence.Hash, ObservedAt: ordered.QualityObservedAt.Add(-time.Second)}}); !errors.Is(e, qaopsquality.ErrConflict) {
|
||||
t.Fatal("late old source scan rolled back the current input")
|
||||
}
|
||||
current, ce := store.Observe(ctx, []dobotaiops.Record{ordered})
|
||||
if ce != nil || current[ordered.ID].InputEpoch != newView.InputEpoch {
|
||||
t.Fatal("stale scan created extra input epochs")
|
||||
}
|
||||
// Independent cursors must enumerate more than one page without loss.
|
||||
paging := dobotaiops.Record{ID: "history-paging-turn", Answer: "示例"}
|
||||
pageSeen := map[int64]bool{}
|
||||
checkSeen := map[int64]bool{}
|
||||
for i := 0; i < 23; i++ {
|
||||
paging.Answer = fmt.Sprintf("示例输入%d", i)
|
||||
vv, ee := store.Observe(ctx, []dobotaiops.Record{paging})
|
||||
if ee != nil {
|
||||
t.Fatal(ee)
|
||||
}
|
||||
value := vv[paging.ID]
|
||||
_, ee = store.Save(ctx, paging, qaopsquality.SaveRequest{InputHash: value.InputHash, InputEpoch: value.InputEpoch, BaseRevision: value.Revision, Nonce: fmt.Sprintf("history_%020d", i), Fields: qaopsquality.Fields{Coverage: "pending", Correctness: "pending"}, Reason: "隔离分页验证"}, "fixture-admin")
|
||||
if ee != nil {
|
||||
t.Fatal(ee)
|
||||
}
|
||||
}
|
||||
rc, cc := int64(0), int64(0)
|
||||
for {
|
||||
page, ee := store.History(ctx, paging.ID, rc, cc)
|
||||
if ee != nil {
|
||||
t.Fatal(ee)
|
||||
}
|
||||
for _, r := range page.Reviews {
|
||||
if pageSeen[r.Revision] {
|
||||
t.Fatal("duplicate history review")
|
||||
}
|
||||
pageSeen[r.Revision] = true
|
||||
}
|
||||
for _, c := range page.Checks {
|
||||
if checkSeen[c.ID] {
|
||||
t.Fatal("duplicate history check")
|
||||
}
|
||||
checkSeen[c.ID] = true
|
||||
}
|
||||
rc, cc = page.NextReview, page.NextCheck
|
||||
if rc == 0 && cc == 0 {
|
||||
break
|
||||
}
|
||||
if rc == 0 || cc == 0 {
|
||||
t.Fatal("unexpected fixture cursor shape")
|
||||
}
|
||||
}
|
||||
if len(pageSeen) != 23 || len(checkSeen) != 23 {
|
||||
t.Fatal("history cursor omitted immutable rows")
|
||||
}
|
||||
freshPool, fe := pgxpool.New(ctx, dsn)
|
||||
if fe != nil {
|
||||
t.Fatal(fe)
|
||||
}
|
||||
persisted, fe := qaopsquality.NewStore(freshPool, "fixture-tenant").History(ctx, record.ID, 0, 0)
|
||||
freshPool.Close()
|
||||
if fe != nil || len(persisted.Reviews) != 2 || len(persisted.Checks) != 3 {
|
||||
t.Fatal("history did not survive a new connection pool")
|
||||
}
|
||||
// History survives a fresh store/connection, not merely an in-memory cache.
|
||||
if h, e = qaopsquality.NewStore(pool, "other-tenant").History(ctx, record.ID, 0, 0); e != nil || len(h.Reviews) != 0 || len(h.Checks) != 0 {
|
||||
t.Fatal("quality history crossed tenants")
|
||||
}
|
||||
if e = pg.RollbackLatestMigration(ctx, pool); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var gone bool
|
||||
if pool.QueryRow(ctx, `SELECT to_regclass('qa_ops_quality_records') IS NULL AND to_regclass('qa_ops_quality_inputs') IS NULL AND to_regclass('qa_ops_quality_checks') IS NULL AND to_regclass('qa_ops_quality_reviews') IS NULL`).Scan(&gone) != nil || !gone {
|
||||
t.Fatal("quality down migration left data tables")
|
||||
}
|
||||
if e = pg.ApplyMigrations(ctx, pool); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package versionhistory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"knowledge-governance/internal/governance"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func (s *Syncer) includeDeliveredCommits(ctx context.Context, commits []RawCommit, tags []RawTag) ([]RawCommit, error) {
|
||||
seen := map[string]bool{}
|
||||
for _, c := range commits {
|
||||
seen[c.SHA] = true
|
||||
}
|
||||
refs := append([]string{}, s.targetSHAs...)
|
||||
snapshots := []RawTag{}
|
||||
for _, tag := range tags {
|
||||
if tag.Annotated && strings.HasPrefix(tag.Name, "snapshot/v") && governance.SemverValid(strings.TrimPrefix(tag.Name, "snapshot/v")) {
|
||||
snapshots = append(snapshots, tag)
|
||||
}
|
||||
}
|
||||
sort.Slice(snapshots, func(i, j int) bool {
|
||||
return governance.CompareSemver(strings.TrimPrefix(snapshots[i].Name, "snapshot/v"), strings.TrimPrefix(snapshots[j].Name, "snapshot/v")) > 0
|
||||
})
|
||||
for _, tag := range snapshots {
|
||||
refs = append(refs, tag.TargetSHA)
|
||||
}
|
||||
for _, ref := range refs {
|
||||
if seen[ref] {
|
||||
continue
|
||||
}
|
||||
if !fullSHA.MatchString(ref) {
|
||||
return nil, fmt.Errorf("开发快照缺少完整提交身份")
|
||||
}
|
||||
extra, total, e := s.fetchCommitsAt(ctx, ref)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if total > 0 && len(extra) != total {
|
||||
return nil, codeError{code: ErrorCodeCountMismatch, message: "开发快照提交历史不完整"}
|
||||
}
|
||||
found := false
|
||||
for _, c := range extra {
|
||||
if c.SHA == ref {
|
||||
found = true
|
||||
}
|
||||
if !seen[c.SHA] {
|
||||
seen[c.SHA] = true
|
||||
commits = append(commits, c)
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return nil, codeError{code: ErrorCodeIncompletePages, message: "开发快照目标没有被取回"}
|
||||
}
|
||||
}
|
||||
return commits, nil
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package versionhistory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"knowledge-governance/internal/governance"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestGiteaSnapshotRefIsExplicitAndNotesArePreserved(t *testing.T) {
|
||||
server := fakeGitea(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/api/v1/repos/Weknora/knowledge-governance/commits" {
|
||||
if r.URL.Query().Get("sha") != shaB {
|
||||
t.Error("snapshot commit history silently used default branch")
|
||||
}
|
||||
fmt.Fprintf(w, `[{"sha":%q,"parents":[],"commit":{"message":"fixture"}}]`, shaB)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/api/v1/repos/Weknora/knowledge-governance/git/refs/tags" {
|
||||
fmt.Fprintf(w, `[{"ref":"refs/tags/snapshot/v0.1.1","object":{"type":"tag","sha":%q}}]`, shaT)
|
||||
return
|
||||
}
|
||||
fmt.Fprintf(w, `{"message":"development notes","object":{"type":"commit","sha":%q}}`, shaB)
|
||||
})
|
||||
c, _ := NewGiteaClient(validConfig(server.URL))
|
||||
if _, _, e := c.ListCommitsAtRef(context.Background(), shaB, 1, 50); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
tags, e := c.ListTags(context.Background())
|
||||
if e != nil || len(tags) != 1 || tags[0].Message != "development notes" {
|
||||
t.Fatal("annotated snapshot notes lost", e)
|
||||
}
|
||||
}
|
||||
func TestDevelopmentVersionsHaveTheirOwnChangelogNotes(t *testing.T) {
|
||||
a, b := shaA, shaB
|
||||
now := time.Now()
|
||||
text := "# Changelog\n\n## [Unreleased]\n\n### Added\n\n- unrelated future work\n\n## 开发快照 snapshot/v0.1.1 - 2026-10-18\n\n### Fixed\n\n- fix specifically delivered here\n\n## [0.1.0] - 2026-10-13\n\n### Added\n\n- baseline\n"
|
||||
result := DeriveVersions(DeriveInput{Commits: []RawCommit{{SHA: a, CommittedAt: now}, {SHA: b, Parents: []string{a}, CommittedAt: now}}, Tags: []RawTag{{Name: "v0.1.0", TargetSHA: a, Annotated: true}}, Changelog: func(string) (string, error) { return text, nil }})
|
||||
for _, v := range result.Records {
|
||||
if v.CommitSHA == b && (v.ReleaseNotes != "### Fixed\n\n- fix specifically delivered here" || v.RecordKind != governance.RecordKindDevelopment) {
|
||||
t.Fatalf("development version lacks its own notes: %q", v.ReleaseNotes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHistoricDevelopmentArchiveBindsExactCommit(t *testing.T) {
|
||||
archive := "## 开发快照 snapshot/v0.1.1 - 2026-10-18\n\n目标提交:" + shaB + "\n\n### Fixed\n\n- historic delivery notes\n"
|
||||
input := DeriveInput{DeliveryArchive: archive, Commits: []RawCommit{{SHA: shaA}, {SHA: shaB, Parents: []string{shaA}}}, Tags: []RawTag{{Name: "v0.1.0", TargetSHA: shaA, Annotated: true}}, Changelog: func(string) (string, error) { return "## [0.1.0] - 2026-10-13\n\n### Added\n\n- baseline", nil }}
|
||||
result := DeriveVersions(input)
|
||||
for _, v := range result.Records {
|
||||
if v.CommitSHA == shaB && !strings.Contains(v.ReleaseNotes, "historic delivery notes") {
|
||||
t.Fatal("archived notes missing")
|
||||
}
|
||||
}
|
||||
input.DeliveryArchive = strings.ReplaceAll(archive, shaB, strings.Repeat("c", 40))
|
||||
result = DeriveVersions(input)
|
||||
for _, v := range result.Records {
|
||||
if v.CommitSHA == shaB && v.ReleaseNotes != "" {
|
||||
t.Fatal("different commit reused same-number archive notes")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type snapshotRefSource struct {
|
||||
fakeSource
|
||||
other []RawCommit
|
||||
}
|
||||
|
||||
func (s *snapshotRefSource) ListCommitsAtRef(_ context.Context, _ string, page, limit int) ([]RawCommit, int, error) {
|
||||
if page == 1 {
|
||||
return s.other, len(s.other), nil
|
||||
}
|
||||
return nil, len(s.other), nil
|
||||
}
|
||||
func TestSyncIncludesDeliveredSnapshotOutsideMain(t *testing.T) {
|
||||
a := RawCommit{SHA: shaA}
|
||||
b := RawCommit{SHA: shaB, Parents: []string{shaA}}
|
||||
src := &snapshotRefSource{fakeSource: fakeSource{commits: []RawCommit{a}, total: 1, pageSize: 50, head: shaA, tags: []RawTag{{Name: "snapshot/v0.1.1", TargetSHA: shaB, Annotated: true}}}, other: []RawCommit{b, a}}
|
||||
store := &fakeStore{}
|
||||
run, e := newTestSyncer(t, src, store).Sync(context.Background(), "fixture", "admin")
|
||||
if e != nil || len(store.saved) != 1 || len(store.saved[0].records) != 2 || !run.Complete {
|
||||
t.Fatal("delivered non-main snapshot omitted", e, run.FetchedCount)
|
||||
}
|
||||
}
|
||||
@@ -188,6 +188,12 @@ var errGiteaNotFound = newGiteaError(KindNotFound, http.StatusNotFound, "版本
|
||||
|
||||
// ListCommits 读一页提交;同时返回 X-Total-Count(用于完整性对账,不做假 total)。
|
||||
func (c *GiteaClient) ListCommits(ctx context.Context, page, limit int) ([]RawCommit, int, error) {
|
||||
return c.ListCommitsAtRef(ctx, "main", page, limit)
|
||||
}
|
||||
func (c *GiteaClient) ListCommitsAtRef(ctx context.Context, ref string, page, limit int) ([]RawCommit, int, error) {
|
||||
if ref != "main" && !fullSHA.MatchString(ref) {
|
||||
return nil, 0, newGiteaError(KindParse, 0, "版本记录:只接受 main 或完整提交 SHA", nil)
|
||||
}
|
||||
if limit <= 0 || limit > giteaDefaultPageSize {
|
||||
limit = giteaDefaultPageSize
|
||||
}
|
||||
@@ -196,6 +202,7 @@ func (c *GiteaClient) ListCommits(ctx context.Context, page, limit int) ([]RawCo
|
||||
query.Set("page", fmt.Sprintf("%d", page))
|
||||
query.Set("stat", "false")
|
||||
query.Set("verification", "false")
|
||||
query.Set("sha", ref)
|
||||
body, header, err := c.get(ctx, c.apiURL("/commits", query))
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
@@ -322,7 +329,8 @@ func (c *GiteaClient) ListTags(ctx context.Context) ([]RawTag, error) {
|
||||
return nil, err
|
||||
}
|
||||
var annotated struct {
|
||||
Object struct {
|
||||
Message string `json:"message"`
|
||||
Object struct {
|
||||
SHA string `json:"sha"`
|
||||
} `json:"object"`
|
||||
}
|
||||
@@ -333,6 +341,7 @@ func (c *GiteaClient) ListTags(ctx context.Context) ([]RawTag, error) {
|
||||
continue
|
||||
}
|
||||
tag.TargetSHA = annotated.Object.SHA
|
||||
tag.Message = annotated.Message
|
||||
}
|
||||
tags = append(tags, tag)
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ package versionhistory
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
@@ -25,6 +26,7 @@ type RawCommit struct {
|
||||
|
||||
// RawTag 是一个 tag 及其可核验属性;Annotated=false 表示轻量 tag(不算正式版本的证据)。
|
||||
type RawTag struct {
|
||||
Message string
|
||||
Name string
|
||||
TagSHA string
|
||||
TargetSHA string
|
||||
@@ -36,13 +38,14 @@ 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
|
||||
DeliveryArchive string
|
||||
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 是换算结果。
|
||||
@@ -192,6 +195,25 @@ func DeriveVersions(in DeriveInput) DeriveResult {
|
||||
}
|
||||
if kind == governance.RecordKindRelease {
|
||||
record.ReleaseNotes = governance.ExtractReleaseNotes(changelog, label)
|
||||
} else if kind == governance.RecordKindDevelopment {
|
||||
record.ReleaseNotes = governance.ExtractDevelopmentNotes(changelog, label)
|
||||
if record.ReleaseNotes == "" {
|
||||
archived := governance.ExtractDevelopmentNotes(in.DeliveryArchive, label)
|
||||
if strings.Contains(archived, "目标提交:"+commit.SHA) {
|
||||
record.ReleaseNotes = archived
|
||||
}
|
||||
}
|
||||
if record.ReleaseNotes == "" {
|
||||
for _, tag := range tagsByTarget[commit.SHA] {
|
||||
if tag.Annotated && tag.Name == "snapshot/v"+label {
|
||||
_, body, found := strings.Cut(tag.Message, "\n\n")
|
||||
if found {
|
||||
record.ReleaseNotes = strings.TrimSpace(body)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
records = append(records, record)
|
||||
}
|
||||
|
||||
@@ -130,22 +130,24 @@ type SyncOutcome struct {
|
||||
|
||||
// SyncerConfig 装配同步器。
|
||||
type SyncerConfig struct {
|
||||
Source Source
|
||||
Store SyncStore
|
||||
RepoKey string
|
||||
Changelog string // 提交内的变更记录文件路径,默认 CHANGELOG.md
|
||||
Now func() time.Time
|
||||
MaxPages int
|
||||
Source Source
|
||||
Store SyncStore
|
||||
RepoKey string
|
||||
Changelog string // 提交内的变更记录文件路径,默认 CHANGELOG.md
|
||||
Now func() time.Time
|
||||
MaxPages int
|
||||
TargetSHAs []string
|
||||
}
|
||||
|
||||
// Syncer 抓取远端 main 可达的全部提交并换算版本记录。
|
||||
type Syncer struct {
|
||||
source Source
|
||||
store SyncStore
|
||||
repoKey string
|
||||
changelog string
|
||||
now func() time.Time
|
||||
maxPages int
|
||||
source Source
|
||||
store SyncStore
|
||||
repoKey string
|
||||
changelog string
|
||||
now func() time.Time
|
||||
maxPages int
|
||||
targetSHAs []string
|
||||
}
|
||||
|
||||
const syncerDefaultMaxPages = 200
|
||||
@@ -170,7 +172,12 @@ func NewSyncer(config SyncerConfig) (*Syncer, error) {
|
||||
if maxPages <= 0 {
|
||||
maxPages = syncerDefaultMaxPages
|
||||
}
|
||||
return &Syncer{source: config.Source, store: config.Store, repoKey: config.RepoKey,
|
||||
for _, sha := range config.TargetSHAs {
|
||||
if !fullSHA.MatchString(sha) {
|
||||
return nil, errors.New("版本记录:运行身份必须是完整 SHA")
|
||||
}
|
||||
}
|
||||
return &Syncer{targetSHAs: append([]string{}, config.TargetSHAs...), source: config.Source, store: config.Store, repoKey: config.RepoKey,
|
||||
changelog: changelog, now: now, maxPages: maxPages}, nil
|
||||
}
|
||||
|
||||
@@ -204,9 +211,22 @@ func (s *Syncer) Sync(ctx context.Context, jobID, triggeredBy string) (governanc
|
||||
return fail(err)
|
||||
}
|
||||
|
||||
commits, err = s.includeDeliveredCommits(ctx, commits, tags)
|
||||
if err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
total = len(commits)
|
||||
deliveryArchive := ""
|
||||
if len(s.targetSHAs) > 0 {
|
||||
deliveryArchive, err = s.source.ReadFile(ctx, s.targetSHAs[0], s.changelog)
|
||||
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,
|
||||
TagURLBase: s.source.TagURLBase(),
|
||||
DeliveryArchive: deliveryArchive,
|
||||
Commits: commits, Tags: tags, SnapshotID: runID,
|
||||
Changelog: func(sha string) (string, error) {
|
||||
return s.source.ReadFile(ctx, sha, s.changelog)
|
||||
}})
|
||||
@@ -220,6 +240,9 @@ func (s *Syncer) Sync(ctx context.Context, jobID, triggeredBy string) (governanc
|
||||
} else {
|
||||
sourceHead = headSHA(commits) // 读分支失败不致命:退回提交列表最新一条
|
||||
}
|
||||
if len(s.targetSHAs) > 0 {
|
||||
sourceHead = s.targetSHAs[0]
|
||||
}
|
||||
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 {
|
||||
@@ -232,6 +255,9 @@ func (s *Syncer) Sync(ctx context.Context, jobID, triggeredBy string) (governanc
|
||||
|
||||
// fetchAllCommits 逐页抓取并按 SHA 去重;短页即终止(也防住服务端忽略 page 参数)。
|
||||
func (s *Syncer) fetchAllCommits(ctx context.Context) ([]RawCommit, int, error) {
|
||||
return s.fetchCommitsAt(ctx, "")
|
||||
}
|
||||
func (s *Syncer) fetchCommitsAt(ctx context.Context, ref string) ([]RawCommit, int, error) {
|
||||
pageSize := s.source.PageSize()
|
||||
if pageSize <= 0 {
|
||||
pageSize = giteaDefaultPageSize
|
||||
@@ -240,7 +266,18 @@ func (s *Syncer) fetchAllCommits(ctx context.Context) ([]RawCommit, int, error)
|
||||
commits := make([]RawCommit, 0, pageSize)
|
||||
total := 0
|
||||
for page := 1; page <= s.maxPages; page++ {
|
||||
pageCommits, pageTotal, err := s.source.ListCommits(ctx, page, pageSize)
|
||||
var pageCommits []RawCommit
|
||||
var pageTotal int
|
||||
var err error
|
||||
if ref == "" {
|
||||
pageCommits, pageTotal, err = s.source.ListCommits(ctx, page, pageSize)
|
||||
} else if source, ok := s.source.(interface {
|
||||
ListCommitsAtRef(context.Context, string, int, int) ([]RawCommit, int, error)
|
||||
}); ok {
|
||||
pageCommits, pageTotal, err = source.ListCommitsAtRef(ctx, ref, page, pageSize)
|
||||
} else {
|
||||
return nil, 0, errors.New("版本来源不支持开发快照历史")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
@@ -356,6 +356,9 @@ def cmd_internal_web_test() -> int:
|
||||
def cmd_internal_contracts(go: str) -> int:
|
||||
"""版本契约:结构 + 注入身份必须**真 PASS**(SKIP 判红),
|
||||
并且**开发构建不许自称正式版**(负例:标成 release ⇒ 必须红)。"""
|
||||
snapshot_rc = subprocess.run(py("scripts/development_snapshot.py","--self-test"),cwd=ROOT).returncode
|
||||
if snapshot_rc:
|
||||
return 1
|
||||
rc = subprocess.run(py("scripts/check_changelog.py"), cwd=ROOT).returncode
|
||||
if rc:
|
||||
return 1
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
# 重建并上线 governance api + web(本机 docker build 需要宿主代理 + --network host)
|
||||
set -u
|
||||
cd /home/zheromiku/knowledge-governance || exit 1
|
||||
cd "$(dirname "${BASH_SOURCE[0]}")/.." || exit 1
|
||||
[ -z "$(git status --porcelain --untracked-files=normal)" ] || { printf "%s\n" "REFUSED_DIRTY_SOURCE"; exit 1; }
|
||||
TS=$(date +%Y%m%d-%H%M%S)
|
||||
PROXY_ARGS=(--build-arg HTTP_PROXY=http://127.0.0.1:7890 --build-arg HTTPS_PROXY=http://127.0.0.1:7890 --build-arg NO_PROXY=localhost,127.0.0.1 --build-arg GOPROXY=https://goproxy.cn,direct)
|
||||
|
||||
@@ -123,4 +124,12 @@ if docker exec knowledge-governance-p1-api-1 sh -lc "strings /app/api | grep -q
|
||||
else
|
||||
echo "INJECTION_MISSING(产物里没有 $INJECTED —— 页面会显示当前运行未知)"
|
||||
fi
|
||||
echo "=== 10. 版本记录同步读回(当前 SHA + 注释快照 + 独立变更说明)"
|
||||
# Startup queues the read-only history job. A healthy API alone is not proof.
|
||||
VERIFIED=0
|
||||
for ((attempt=0;attempt<90;attempt++)); do
|
||||
if docker exec knowledge-governance-p1-api-1 /app/api --version-record-status; then VERIFIED=1; break; fi
|
||||
sleep 2
|
||||
done
|
||||
[ "$VERIFIED" = "1" ] || { printf '%s\n' 'VERSION_RECORD_NOT_VERIFIED'; exit 1; }
|
||||
echo "DONE"
|
||||
@@ -0,0 +1,82 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Explicit development delivery tags; never creates formal tags or releases."""
|
||||
import argparse,json,re,subprocess,tempfile
|
||||
from pathlib import Path
|
||||
ROOT=Path(__file__).resolve().parent.parent
|
||||
SHA=re.compile(r'^[a-f0-9]{40}$')
|
||||
def git(root,*args):
|
||||
p=subprocess.run(['git',*args],cwd=root,text=True,capture_output=True)
|
||||
if p.returncode:raise RuntimeError('git operation failed: '+args[0])
|
||||
return p.stdout.strip()
|
||||
def notes(text,version):
|
||||
heading=re.search(r'^## 开发快照 snapshot/v'+re.escape(version)+r' - \d{4}-\d{2}-\d{2}\s*$',text,re.M)
|
||||
if not heading:return ''
|
||||
tail=text[heading.end():];return re.split(r'^##\s',tail,maxsplit=1,flags=re.M)[0].strip()
|
||||
def plan(root,sha,backfill=False):
|
||||
if not sha or not SHA.fullmatch(sha):raise ValueError('exact 40-character commit SHA required')
|
||||
if git(root,'cat-file','-t',sha)!='commit':raise ValueError('snapshot target must be a commit')
|
||||
text=git(root,'show',sha+':CHANGELOG.md');m=re.search(r'^##\s*\[(\d+\.\d+\.\d+)\]',text,re.M)
|
||||
if not m:raise ValueError('formal baseline missing')
|
||||
baseline=m.group(1);base='v'+baseline
|
||||
if git(root,'cat-file','-t','refs/tags/'+base)!='tag':raise ValueError('annotated formal baseline missing')
|
||||
git(root,'merge-base','--is-ancestor',base,sha)
|
||||
n=int(git(root,'rev-list','--count',base+'..'+sha));version='.'.join(baseline.split('.')[:2]+[str(n)])
|
||||
if n<=0:raise ValueError('formal baseline cannot be tagged as a development delivery')
|
||||
body=notes(text,version)
|
||||
if not body and backfill:
|
||||
body=notes(git(root,'show','HEAD:CHANGELOG.md'),version)
|
||||
if '目标提交:'+sha not in body:raise ValueError('backfilled notes must bind the exact historic SHA')
|
||||
if not body:raise ValueError('this development version has no independent CHANGELOG entry')
|
||||
if not re.search(r'^### (Added|Changed|Fixed|Security)\s*$',body,re.M):raise ValueError('snapshot notes have no change category')
|
||||
return {'commit_sha':sha,'display_version':version,'tag':'snapshot/v'+version,'message':'Development snapshot '+version+'\n\n'+body,'backfilled':bool(backfill)}
|
||||
def publish(root,p):
|
||||
# Only explicitly named development refs are written. Existing refs, including
|
||||
# legacy misnumbered snapshots, are never moved or overwritten.
|
||||
tag=p['tag'];sha=p['commit_sha'];ref='refs/tags/'+tag
|
||||
remote=git(root,'ls-remote','origin');pairs=[line.split() for line in remote.splitlines() if line.strip()];refs={name:obj for obj,name in pairs}
|
||||
if ref in refs:
|
||||
if refs.get(ref+'^{}')!=sha:raise ValueError('remote snapshot already exists with different or non-annotated identity')
|
||||
return {'tag':tag,'commit_sha':sha,'state':'already_published'}
|
||||
reachable=False
|
||||
for obj,name in pairs:
|
||||
if name.startswith('refs/heads/') and subprocess.run(['git','merge-base','--is-ancestor',sha,obj],cwd=root,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL).returncode==0:reachable=True;break
|
||||
if not reachable:raise ValueError('snapshot target has not been pushed to a remote branch')
|
||||
exists=subprocess.run(['git','show-ref','--verify','--quiet',ref],cwd=root).returncode==0
|
||||
if exists:
|
||||
if git(root,'cat-file','-t',ref)!='tag' or git(root,'rev-parse',ref+'^{}')!=sha:raise ValueError('local snapshot conflicts with requested identity')
|
||||
if git(root,'for-each-ref','--format=%(contents)',ref).strip()!=p['message'].strip():raise ValueError('existing snapshot annotation differs; will not overwrite')
|
||||
else:
|
||||
with tempfile.NamedTemporaryFile(mode='w',prefix='kg-snapshot-note-',encoding='utf-8') as f:
|
||||
f.write(p['message']+'\n');f.flush();git(root,'tag','-a',tag,sha,'-F',f.name)
|
||||
git(root,'push','origin',ref+':'+ref)
|
||||
readback={line.split()[1]:line.split()[0] for line in git(root,'ls-remote','--tags','origin',ref,ref+'^{}').splitlines()}
|
||||
if readback.get(ref+'^{}')!=sha or readback.get(ref)!=git(root,'rev-parse',ref):raise RuntimeError('remote snapshot read-back failed')
|
||||
return {'tag':tag,'commit_sha':sha,'state':'published_and_read_back'}
|
||||
def self_test():
|
||||
with tempfile.TemporaryDirectory(prefix='kg-snapshot-test-') as d:
|
||||
r=Path(d);git(r,'init','-b','main');git(r,'config','user.name','Fixture');git(r,'config','user.email','fixture@example.invalid')
|
||||
base='# Changelog\n\n## [0.1.0] - 2026-10-13\n\n### Added\n\n- fixture baseline\n'
|
||||
(r/'CHANGELOG.md').write_text(base);git(r,'add','CHANGELOG.md');git(r,'commit','-m','feat: fixture baseline');git(r,'tag','-a','v0.1.0','-m','fixture')
|
||||
(r/'CHANGELOG.md').write_text('## 开发快照 snapshot/v0.1.1 - 2026-10-18\n\n### Fixed\n\n- specific fixture fix\n\n'+base);git(r,'add','CHANGELOG.md');git(r,'commit','-m','fix: fixture change')
|
||||
sha=git(r,'rev-parse','HEAD');before=git(r,'tag');p=plan(r,sha)
|
||||
assert p['tag']=='snapshot/v0.1.1' and 'specific fixture fix' in p['message']
|
||||
assert before==git(r,'tag'),'planning wrote a tag'
|
||||
try:plan(r,'a'*7)
|
||||
except ValueError:pass
|
||||
else:raise AssertionError('short SHA accepted')
|
||||
bare=r/'remote.git';git(r,'init','--bare',str(bare));git(r,'remote','add','origin',str(bare));git(r,'push','origin','main')
|
||||
out=publish(r,p);assert out['state']=='published_and_read_back'
|
||||
assert git(r,'rev-parse',p['tag']+'^{}')==sha
|
||||
assert publish(r,p)['state']=='already_published'
|
||||
wrong=dict(p,commit_sha='a'*40)
|
||||
try:publish(r,wrong)
|
||||
except ValueError:pass
|
||||
else:raise AssertionError('conflicting remote snapshot overwritten')
|
||||
assert git(r,'tag','--list','v*').splitlines()==['v0.1.0'],'formal tags changed'
|
||||
print('development snapshot fixture passed; real repository tags untouched')
|
||||
def main():
|
||||
a=argparse.ArgumentParser();a.add_argument('--sha');a.add_argument('--backfill',action='store_true');a.add_argument('--publish',action='store_true');a.add_argument('--self-test',action='store_true');o=a.parse_args()
|
||||
if o.self_test:return self_test()
|
||||
p=plan(ROOT,o.sha,o.backfill)
|
||||
print(json.dumps(publish(ROOT,p) if o.publish else p,ensure_ascii=False))
|
||||
if __name__=='__main__':main()
|
||||
@@ -9,6 +9,7 @@
|
||||
"⚠️ 文件缺失或解析不了 ⇒ 门禁红:范围声明不出来时,不许默认放行。"
|
||||
],
|
||||
"optional": [
|
||||
{"package":"knowledge-governance/internal/qaopsquality","test":"TestQualityStoreImmutableHistoryReplayConcurrencyAndStaleness","reason":"仅在显式一次性 loopback kg_qaops_quality_test_ 库执行;默认 CI 不连接共享/生产库,隔离 PG 另行实跑"},
|
||||
{"package": "knowledge-governance/internal/dobotaiops", "test": "TestQARecordInternalIdentityAndWholeFilterKeys", "reason": "必须显式一次性隔离PG;验证真实只读SQL身份关联/计数及隐私,不连接生产;默认无库时明确跳过,另行本地补验"},
|
||||
{"package": "knowledge-governance/internal/dobotaiops", "test": "TestQAUsageGroupsCountEventsOnceOverTheFullFilter", "reason": "必须显式一次性隔离PG;验证真实只读SQL身份关联/计数及隐私,不连接生产;默认无库时明确跳过,另行本地补验"},
|
||||
{
|
||||
|
||||
@@ -50,17 +50,40 @@ const props = {
|
||||
}
|
||||
|
||||
describe('QA operations workbench', () => {
|
||||
it('shows populated columns in required order and keeps false/downvotes visible', () => {
|
||||
it('shows all required columns even when empty and keeps false/downvotes visible', () => {
|
||||
const html = renderToStaticMarkup(<QAOperationsView {...props} />)
|
||||
expect(html).toContain('原始问题')
|
||||
expect(html.indexOf('AI答案')).toBeLessThan(html.indexOf('是否覆盖'))
|
||||
expect(html.indexOf('是否正确')).toBeLessThan(html.indexOf('提问时间'))
|
||||
expect(html).toContain('否(点踩)')
|
||||
expect(html).toContain('是否正确')
|
||||
expect(html).not.toContain('<th>部门</th>')
|
||||
expect(html).not.toContain('<th>产品分类</th>')
|
||||
expect(html).toContain('<th>部门</th>')
|
||||
expect([...html.matchAll(/<th>(.*?)<\/th>/g)].slice(0, 14).map((match) => match[1])).toEqual([
|
||||
'中文问题',
|
||||
'AI答案',
|
||||
'是否覆盖',
|
||||
'是否正确',
|
||||
'产品分类',
|
||||
'问题类型',
|
||||
'根因分析',
|
||||
'提问时间',
|
||||
'提问人',
|
||||
'原始问题',
|
||||
'语言',
|
||||
'流程触发人员信息',
|
||||
'部门',
|
||||
'区域',
|
||||
])
|
||||
expect(html).toContain('<th>产品分类</th>')
|
||||
expect(html).not.toContain('<script>not executable</script>')
|
||||
})
|
||||
it('never shows a load-more control for the all-records table', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<QAOperationsView {...props} page={{ ...page, total: 2, has_more: true, next_cursor: 'next' }} />
|
||||
)
|
||||
expect(html).not.toContain('加载更多')
|
||||
expect(html).not.toContain('空列按整个筛选结果隐藏')
|
||||
})
|
||||
it('distinguishes an unavailable source from a successful empty query', () => {
|
||||
const html = renderToStaticMarkup(<QAOperationsView {...props} page={null} error="只读源不可用" />)
|
||||
expect(html).toContain('role="alert"')
|
||||
|
||||
+106
-56
@@ -1,15 +1,21 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import type { FormEvent } from 'react'
|
||||
import { useOptionalAuth } from './auth'
|
||||
import { fetchQARecord, fetchQARecords, fetchQAStatus, mergeQAPages, qaCellValue, qaColumns } from './qaOps'
|
||||
import { fetchQARecord, fetchAllQARecords, fetchQAStatus, qaCellValue, qaColumns } from './qaOps'
|
||||
import type { QAQuery, QARecord, QARecordPage, QAStatus } from './qaOps'
|
||||
import './qaOps.css'
|
||||
import { QARegions } from './QARegions'
|
||||
import { QAUsage } from './QAUsage'
|
||||
import { QAMonthly } from './QAMonthly'
|
||||
import { QAQualityEditor, QAQualityCounts } from './QAQuality'
|
||||
import { qualityLabels } from './qaQuality'
|
||||
import { usageLabels } from './qaUsage'
|
||||
import { QAWeekPicker } from './QAWeekPicker'
|
||||
import { currentQAWeek, qaDateTimeToISO, qaWeekQueryRange } from './qaWeeks'
|
||||
|
||||
interface ViewProps {
|
||||
onQualitySaved?: (record: QARecord) => void
|
||||
onReloadDetail?: () => void
|
||||
page: QARecordPage | null
|
||||
status: QAStatus | null
|
||||
loading: boolean
|
||||
@@ -19,7 +25,7 @@ interface ViewProps {
|
||||
detailError: string | null
|
||||
onSelect: (id: string) => void
|
||||
onCloseDetail: () => void
|
||||
onLoadMore: () => void
|
||||
progress?: { loaded: number; total: number }
|
||||
onRetry: () => void
|
||||
}
|
||||
const stateLabels = { disabled: '未配置', unavailable: '连接不可用', blocked: '接入被阻断', connected: '已连接' }
|
||||
@@ -38,14 +44,18 @@ const sourceCoverageLabels: Record<string, string> = { covered: '已覆盖', unc
|
||||
|
||||
export function QAOperationsView(props: ViewProps) {
|
||||
const page = props.page
|
||||
const columns = qaColumns.filter(({ key }) => page?.columns.includes(key))
|
||||
const columns = qaColumns
|
||||
const detail = props.detail
|
||||
const showDrawer = Boolean(detail || props.detailLoading || props.detailError)
|
||||
return (
|
||||
<section className="qa-ops-results" aria-label="问答记录">
|
||||
<div className="qa-ops-result-bar">
|
||||
<span>
|
||||
{props.loading ? '正在读取…' : page ? `共 ${page.total} 条 · 已显示 ${page.items.length} 条` : '尚未读取问答'}
|
||||
{props.loading
|
||||
? `正在读取全部问答…${props.progress ? `(${props.progress.loaded} / ${props.progress.total})` : ''}`
|
||||
: page
|
||||
? `共 ${page.total} 条 · 已展示 ${page.items.length} 条`
|
||||
: '尚未读取问答'}
|
||||
</span>
|
||||
<span className="qa-ops-source">
|
||||
DobotAI 2.0 / 钉钉 · 独立只读连接{props.status ? ` · ${stateLabels[props.status.state]}` : ''}
|
||||
@@ -96,7 +106,10 @@ export function QAOperationsView(props: ViewProps) {
|
||||
>
|
||||
<span
|
||||
className={
|
||||
key === 'coverage' && item.coverage.verdict === 'uncovered' ? 'qa-ops-uncovered' : ''
|
||||
key === 'coverage' &&
|
||||
(item.quality?.effective.coverage ?? item.coverage.verdict) === 'uncovered'
|
||||
? 'qa-ops-uncovered'
|
||||
: ''
|
||||
}
|
||||
>
|
||||
{qaCellValue(item, key) ?? '—'}
|
||||
@@ -111,6 +124,9 @@ export function QAOperationsView(props: ViewProps) {
|
||||
>
|
||||
详情
|
||||
</button>
|
||||
{item.quality ? (
|
||||
<small className="qa-quality-state">{qualityLabels[item.quality.state]}</small>
|
||||
) : null}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
@@ -122,14 +138,8 @@ export function QAOperationsView(props: ViewProps) {
|
||||
) : null}
|
||||
{page ? (
|
||||
<footer className="qa-ops-page-bar">
|
||||
<span>本次读取:{stamp(page.as_of)} · 空列按整个筛选结果隐藏</span>
|
||||
{page.has_more ? (
|
||||
<button type="button" onClick={props.onLoadMore} disabled={props.loading}>
|
||||
{props.loading ? '读取中…' : '加载更多'}
|
||||
</button>
|
||||
) : page.items.length > 0 ? (
|
||||
<span>已显示全部</span>
|
||||
) : null}
|
||||
<span>本次读取:{stamp(page.as_of)} · 固定显示完整字段,左右滚动查看;— 表示暂无数据</span>
|
||||
<span>{page.items.length === page.total ? '已全部展示' : '全量读取尚未完成'}</span>
|
||||
</footer>
|
||||
) : null}
|
||||
{showDrawer ? (
|
||||
@@ -149,7 +159,9 @@ export function QAOperationsView(props: ViewProps) {
|
||||
if (event.key === 'Escape') props.onCloseDetail()
|
||||
if (event.key === 'Tab') {
|
||||
const buttons = Array.from(
|
||||
event.currentTarget.querySelectorAll<HTMLElement>('button, a[href], input, [tabindex="0"]')
|
||||
event.currentTarget.querySelectorAll<HTMLElement>(
|
||||
'button:not([disabled]), a[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), summary, [tabindex="0"]'
|
||||
)
|
||||
)
|
||||
const first = buttons[0],
|
||||
last = buttons[buttons.length - 1]
|
||||
@@ -242,6 +254,17 @@ export function QAOperationsView(props: ViewProps) {
|
||||
{detail.source_coverage.evaluator_version || '无版本'}
|
||||
</p>
|
||||
<p className="qa-ops-muted">{detail.source_coverage.reason_code || '未记录判定原因'}</p>
|
||||
{detail.quality ? (
|
||||
<QAQualityEditor
|
||||
key={detail.id}
|
||||
recordId={detail.id}
|
||||
quality={detail.quality}
|
||||
onSaved={props.onQualitySaved ?? (() => {})}
|
||||
onReload={props.onReloadDetail ?? (() => {})}
|
||||
/>
|
||||
) : (
|
||||
<p className="qa-ops-muted">质量留档/人工复核未配置。</p>
|
||||
)}
|
||||
<h4>用户反馈</h4>
|
||||
<p>
|
||||
提问人:
|
||||
@@ -267,12 +290,10 @@ export function QAOperationsView(props: ViewProps) {
|
||||
)
|
||||
}
|
||||
|
||||
function localInput(value: Date): string {
|
||||
return new Date(value.getTime() - value.getTimezoneOffset() * 60_000).toISOString().slice(0, 16)
|
||||
}
|
||||
function initialDraft() {
|
||||
const end = new Date()
|
||||
return { start: localInput(new Date(end.getTime() - 7 * 24 * 3600_000)), end: localInput(end), keyword: '' }
|
||||
const current = currentQAWeek()
|
||||
const { year, week, start, end } = qaWeekQueryRange(current.year, current.week)
|
||||
return { year, week: week as number | null, start, end, keyword: '' }
|
||||
}
|
||||
|
||||
export function QAOperations() {
|
||||
@@ -287,19 +308,19 @@ export function QAOperations() {
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [revision, setRevision] = useState(0)
|
||||
const [qualityRevision, setQualityRevision] = useState(0)
|
||||
const [detail, setDetail] = useState<QARecord | null>(null)
|
||||
const [detailLoading, setDetailLoading] = useState(false)
|
||||
const [detailError, setDetailError] = useState<string | null>(null)
|
||||
const generation = useRef(0)
|
||||
const [progress, setProgress] = useState<{ loaded: number; total: number } | undefined>()
|
||||
const detailRequest = useRef<AbortController | null>(null)
|
||||
const moreRequest = useRef<AbortController | null>(null)
|
||||
const returnFocus = useRef<HTMLElement | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!canRead || query) return
|
||||
setQuery({
|
||||
start: new Date(draft.start).toISOString(),
|
||||
end: new Date(draft.end).toISOString(),
|
||||
start: qaDateTimeToISO(draft.start),
|
||||
end: qaDateTimeToISO(draft.end),
|
||||
keyword: draft.keyword,
|
||||
cursor: '',
|
||||
})
|
||||
@@ -309,18 +330,16 @@ export function QAOperations() {
|
||||
if (!query || !canRead) return
|
||||
if (view !== 'records') {
|
||||
setLoading(false)
|
||||
moreRequest.current?.abort()
|
||||
detailRequest.current?.abort()
|
||||
setDetail(null)
|
||||
return
|
||||
}
|
||||
const controller = new AbortController()
|
||||
generation.current += 1
|
||||
moreRequest.current?.abort()
|
||||
detailRequest.current?.abort()
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
setPage(null)
|
||||
setProgress(undefined)
|
||||
setDetail(null)
|
||||
setDetailError(null)
|
||||
setDetailLoading(false)
|
||||
@@ -329,7 +348,9 @@ export function QAOperations() {
|
||||
.catch(() => {
|
||||
if (!controller.signal.aborted) setStatus(null)
|
||||
})
|
||||
void fetchQARecords(query, controller.signal)
|
||||
void fetchAllQARecords(query, controller.signal, (loaded, total) => {
|
||||
if (!controller.signal.aborted) setProgress({ loaded, total })
|
||||
})
|
||||
.then((result) => {
|
||||
if (!controller.signal.aborted) setPage(result)
|
||||
})
|
||||
@@ -345,7 +366,6 @@ export function QAOperations() {
|
||||
useEffect(
|
||||
() => () => {
|
||||
detailRequest.current?.abort()
|
||||
moreRequest.current?.abort()
|
||||
},
|
||||
[]
|
||||
)
|
||||
@@ -353,10 +373,11 @@ export function QAOperations() {
|
||||
const submit = (event: FormEvent) => {
|
||||
event.preventDefault()
|
||||
try {
|
||||
const start = new Date(draft.start),
|
||||
end = new Date(draft.end)
|
||||
if (!(start < end)) throw new Error('开始时间必须早于结束时间')
|
||||
setQuery({ start: start.toISOString(), end: end.toISOString(), keyword: draft.keyword, cursor: '' })
|
||||
const start = qaDateTimeToISO(draft.start),
|
||||
end = qaDateTimeToISO(draft.end)
|
||||
if (!(Date.parse(start) < Date.parse(end))) throw new Error('开始时间必须早于结束时间')
|
||||
if (Date.parse(start) >= Date.now()) throw new Error('所选周或时间尚未开始,请选择已开始的时间范围')
|
||||
setQuery({ start, end, keyword: draft.keyword, cursor: '' })
|
||||
} catch (reason) {
|
||||
setError(reason instanceof Error ? reason.message : '时间格式无效')
|
||||
}
|
||||
@@ -385,25 +406,6 @@ export function QAOperations() {
|
||||
setDetailLoading(false)
|
||||
returnFocus.current?.focus()
|
||||
}
|
||||
const loadMore = async () => {
|
||||
if (!query || !page?.has_more || loading) return
|
||||
const currentGeneration = generation.current
|
||||
const controller = new AbortController()
|
||||
moreRequest.current = controller
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
try {
|
||||
const result = await fetchQARecords({ ...query, cursor: page.next_cursor }, controller.signal)
|
||||
if (!controller.signal.aborted && currentGeneration === generation.current) {
|
||||
setPage(mergeQAPages(page, result))
|
||||
}
|
||||
} catch (reason) {
|
||||
if (!controller.signal.aborted && currentGeneration === generation.current)
|
||||
setError(reason instanceof Error ? reason.message : '翻页失败')
|
||||
} finally {
|
||||
if (!controller.signal.aborted && currentGeneration === generation.current) setLoading(false)
|
||||
}
|
||||
}
|
||||
return (
|
||||
<section className="qa-ops" aria-label="问答运营">
|
||||
<header className="qa-ops-header">
|
||||
@@ -446,22 +448,45 @@ export function QAOperations() {
|
||||
) : (
|
||||
<>
|
||||
<form className="qa-ops-query" onSubmit={submit}>
|
||||
{view === 'records' ? (
|
||||
<QAWeekPicker
|
||||
year={draft.year}
|
||||
week={draft.week}
|
||||
onCurrentWeek={() => {
|
||||
const current = initialDraft()
|
||||
setDraft({ ...current, keyword: draft.keyword })
|
||||
setQuery({
|
||||
start: qaDateTimeToISO(current.start),
|
||||
end: qaDateTimeToISO(current.end),
|
||||
keyword: draft.keyword,
|
||||
cursor: '',
|
||||
})
|
||||
}}
|
||||
onChange={(year, week) => {
|
||||
setDraft((old) => {
|
||||
if (week === null) return { ...old, year, week }
|
||||
const { start, end } = qaWeekQueryRange(year, week)
|
||||
return { ...old, year, week, start, end }
|
||||
})
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
<label>
|
||||
开始时间
|
||||
开始时间(北京时间)
|
||||
<input
|
||||
type="datetime-local"
|
||||
required
|
||||
value={draft.start}
|
||||
onChange={(event) => setDraft({ ...draft, start: event.target.value })}
|
||||
onChange={(event) => setDraft({ ...draft, start: event.target.value, week: null })}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
结束时间(不含)
|
||||
结束时间(北京时间,不含)
|
||||
<input
|
||||
type="datetime-local"
|
||||
required
|
||||
value={draft.end}
|
||||
onChange={(event) => setDraft({ ...draft, end: event.target.value })}
|
||||
onChange={(event) => setDraft({ ...draft, end: event.target.value, week: null })}
|
||||
/>
|
||||
</label>
|
||||
<label className="qa-ops-keyword">
|
||||
@@ -481,6 +506,7 @@ export function QAOperations() {
|
||||
<p className="qa-ops-slice-note">
|
||||
部门/区域保留源快照,缺失时按当前通讯录补全;使用统计不是绩效结论。外语翻译与AI评估仍暂缓,空值不默认填“否”。
|
||||
</p>
|
||||
{view === 'records' ? <QAQualityCounts query={query} revision={qualityRevision} /> : null}
|
||||
{view === 'usage' ? (
|
||||
<QAUsage query={query} />
|
||||
) : (
|
||||
@@ -492,9 +518,33 @@ export function QAOperations() {
|
||||
detail={detail}
|
||||
detailLoading={detailLoading}
|
||||
detailError={detailError}
|
||||
onReloadDetail={() => {
|
||||
if (detail) void select(detail.id)
|
||||
}}
|
||||
onQualitySaved={(fresh) => {
|
||||
if (fresh.id !== detail?.id) return
|
||||
setDetail(fresh)
|
||||
setPage((old) => {
|
||||
if (!old) return old
|
||||
const all = new Set(old.columns)
|
||||
const f = fresh.quality?.effective
|
||||
if (f) {
|
||||
if (f.coverage) all.add('coverage')
|
||||
if (f.correctness) all.add('is_correct')
|
||||
for (const key of ['product_category', 'problem_type', 'root_cause'] as const)
|
||||
if (f[key]) all.add(key)
|
||||
}
|
||||
return {
|
||||
...old,
|
||||
items: old.items.map((item) => (item.id === fresh.id ? fresh : item)),
|
||||
columns: qaColumns.filter((c) => all.has(c.key)).map((c) => c.key),
|
||||
}
|
||||
})
|
||||
setQualityRevision((v) => v + 1)
|
||||
}}
|
||||
onSelect={(id) => void select(id)}
|
||||
onCloseDetail={close}
|
||||
onLoadMore={() => void loadMore()}
|
||||
progress={progress}
|
||||
onRetry={() => setRevision((value) => value + 1)}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { QAQualityEditor, QAQualitySummaryView } from './QAQuality'
|
||||
import { qualityFixture, summaryFixture } from './qaQuality.fixture'
|
||||
import { parseQAQuality, parseQualitySummary } from './qaQuality'
|
||||
describe('manual quality operations', () => {
|
||||
it('renders separate evidence, session reviewer and safe text', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<QAQualityEditor
|
||||
recordId="fixture"
|
||||
quality={parseQAQuality(qualityFixture)}
|
||||
onSaved={() => {}}
|
||||
onReload={() => {}}
|
||||
/>
|
||||
)
|
||||
for (const value of ['人工复核', '保存并读回', '覆盖结论', '正确性', '复核理由', 'fixture-admin'])
|
||||
expect(html).toContain(value)
|
||||
expect(html).not.toContain('<script>')
|
||||
})
|
||||
it('labels stale manual judgment as needing reconfirmation', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<QAQualityEditor
|
||||
recordId="fixture"
|
||||
quality={{ ...parseQAQuality(qualityFixture), state: 'stale' }}
|
||||
onSaved={() => {}}
|
||||
onReload={() => {}}
|
||||
/>
|
||||
)
|
||||
expect(html).toContain('待重新核对')
|
||||
})
|
||||
it('does not turn unavailable quality counts into zeros or rates', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<QAQualitySummaryView data={null} error="质量存储不可用" loading={false} onRefresh={() => {}} />
|
||||
)
|
||||
expect(html).toContain('质量存储不可用')
|
||||
expect(html).not.toContain('覆盖率')
|
||||
const ok = renderToStaticMarkup(
|
||||
<QAQualitySummaryView data={parseQualitySummary(summaryFixture)} error="" loading={false} onRefresh={() => {}} />
|
||||
)
|
||||
expect(ok).toContain('完整筛选范围')
|
||||
expect(ok).toContain('AI 评估未接入')
|
||||
})
|
||||
})
|
||||
|
||||
it('displays approved rates with raw denominators and exclusions', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<QAQualitySummaryView data={parseQualitySummary(summaryFixture)} error="" loading={false} onRefresh={() => {}} />
|
||||
)
|
||||
for (const value of [
|
||||
'知识覆盖率',
|
||||
'回答正确率',
|
||||
'50.0%',
|
||||
'100.0%',
|
||||
'分子',
|
||||
'分母',
|
||||
'排除',
|
||||
'部分覆盖',
|
||||
'quality-rates-human-first-v1',
|
||||
])
|
||||
expect(html).toContain(value)
|
||||
expect(html).not.toContain('不计算比例')
|
||||
})
|
||||
it('does not turn zero denominators into 0% or 100%', () => {
|
||||
const v = parseQualitySummary(structuredClone(summaryFixture))
|
||||
v.summary = {
|
||||
total: 0,
|
||||
reviewed: 0,
|
||||
unreviewed: 0,
|
||||
stale: 0,
|
||||
pending_confirmation: 0,
|
||||
rule_uncovered: 0,
|
||||
rates: {
|
||||
policy_version: 'quality-rates-human-first-v1',
|
||||
coverage: { numerator: 0, denominator: 0, percent: null },
|
||||
correctness: { numerator: 0, denominator: 0, percent: null },
|
||||
breakdown: {
|
||||
covered: 0,
|
||||
uncovered: 0,
|
||||
partial: 0,
|
||||
pending: 0,
|
||||
unassessed: 0,
|
||||
excluded: 0,
|
||||
stale: 0,
|
||||
covered_correct: 0,
|
||||
covered_incorrect: 0,
|
||||
covered_pending: 0,
|
||||
covered_unassessed: 0,
|
||||
},
|
||||
},
|
||||
} as typeof v.summary
|
||||
const html = renderToStaticMarkup(
|
||||
<QAQualitySummaryView data={parseQualitySummary(v)} error="" loading={false} onRefresh={() => {}} />
|
||||
)
|
||||
expect(html).toContain('暂无可计算数据')
|
||||
expect(html).not.toContain('0.0%')
|
||||
})
|
||||
@@ -0,0 +1,522 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import type { FormEvent } from 'react'
|
||||
import { getPayload, fetchQARecord } from './qaOps'
|
||||
import type { QAQuery, QARecord } from './qaOps'
|
||||
import { newOperationID } from './operationKey'
|
||||
import {
|
||||
emptyQualityFields,
|
||||
qualityLabels,
|
||||
parseQAQuality,
|
||||
parseQualityHistory,
|
||||
parseQualitySnapshot,
|
||||
parseQualitySummary,
|
||||
} from './qaQuality'
|
||||
import type { QAQuality, QualityFields, QualityHistory, QualitySnapshot, QualitySummary } from './qaQuality'
|
||||
const stamp = (v: string) => new Date(v).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })
|
||||
const message = (e: unknown) => (e instanceof Error ? e.message : '质量操作失败,请重试')
|
||||
interface EditorProps {
|
||||
recordId: string
|
||||
quality: QAQuality
|
||||
onSaved: (record: QARecord) => void
|
||||
onReload: () => void
|
||||
}
|
||||
export function QAQualityEditor({ recordId, quality, onSaved, onReload }: EditorProps) {
|
||||
const initial = quality.state === 'reviewed' ? quality.effective : emptyQualityFields
|
||||
const [fields, setFields] = useState<QualityFields>({ ...initial }),
|
||||
[reason, setReason] = useState(quality.state === 'reviewed' ? quality.latest_review?.reason || '' : ''),
|
||||
[loading, setLoading] = useState(false),
|
||||
[error, setError] = useState(''),
|
||||
[notice, setNotice] = useState('')
|
||||
const [history, setHistory] = useState<QualityHistory | null>(null),
|
||||
[snapshot, setSnapshot] = useState<QualitySnapshot | null>(null),
|
||||
[historyError, setHistoryError] = useState(''),
|
||||
[historyLoading, setHistoryLoading] = useState(false)
|
||||
const saving = useRef<AbortController | null>(null),
|
||||
reading = useRef<AbortController | null>(null),
|
||||
snapshotReading = useRef<AbortController | null>(null),
|
||||
nonce = useRef({ signature: '', value: '' })
|
||||
useEffect(() => {
|
||||
setFields({ ...(quality.state === 'reviewed' ? quality.effective : emptyQualityFields) })
|
||||
setReason(quality.state === 'reviewed' ? quality.latest_review?.reason || '' : '')
|
||||
setHistory(null)
|
||||
setSnapshot(null)
|
||||
}, [
|
||||
recordId,
|
||||
quality.input_hash,
|
||||
quality.input_epoch,
|
||||
quality.revision,
|
||||
quality.state,
|
||||
quality.effective,
|
||||
quality.latest_review,
|
||||
])
|
||||
useEffect(
|
||||
() => () => {
|
||||
saving.current?.abort()
|
||||
reading.current?.abort()
|
||||
snapshotReading.current?.abort()
|
||||
},
|
||||
[]
|
||||
)
|
||||
const change = (key: keyof QualityFields, value: string) => {
|
||||
setFields({
|
||||
...fields,
|
||||
[key]: value,
|
||||
...(key === 'correctness' && value === 'correct' ? { root_cause: '' } : {}),
|
||||
...(key === 'coverage' && value !== 'excluded' ? { exclusion_reason: '' } : {}),
|
||||
})
|
||||
setNotice('')
|
||||
setError('')
|
||||
}
|
||||
const submit = async (event: FormEvent) => {
|
||||
event.preventDefault()
|
||||
if (loading) return
|
||||
setLoading(true)
|
||||
setError('')
|
||||
setNotice('')
|
||||
const controller = new AbortController()
|
||||
saving.current = controller
|
||||
const body = {
|
||||
input_hash: quality.input_hash,
|
||||
input_epoch: quality.input_epoch,
|
||||
base_revision: quality.revision,
|
||||
fields,
|
||||
reason,
|
||||
}
|
||||
const signature = JSON.stringify(body)
|
||||
try {
|
||||
if (nonce.current.signature !== signature) nonce.current = { signature, value: newOperationID() }
|
||||
const raw = await getPayload(
|
||||
`/api/v1/qa-ops/records/${encodeURIComponent(recordId)}/reviews`,
|
||||
controller.signal,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'X-Governance-Action': 'qa-quality' },
|
||||
body: JSON.stringify({ ...body, nonce: nonce.current.value }),
|
||||
}
|
||||
)
|
||||
if (!raw || typeof raw !== 'object') throw Error('复核回执无效')
|
||||
const receipt = raw as Record<string, unknown>
|
||||
parseQAQuality(receipt.view)
|
||||
if (!Number.isSafeInteger(receipt.saved_revision) || Number(receipt.saved_revision) < 1)
|
||||
throw Error('复核回执缺少版本')
|
||||
const savedRevision = Number(receipt.saved_revision)
|
||||
const audit = parseQualityHistory(
|
||||
await getPayload(
|
||||
`/api/v1/qa-ops/records/${encodeURIComponent(recordId)}/quality/history?review_before=${savedRevision + 1}`,
|
||||
controller.signal
|
||||
)
|
||||
)
|
||||
const saved = audit.reviews.find((r) => r.revision === savedRevision)
|
||||
if (
|
||||
!saved ||
|
||||
saved.input_hash !== body.input_hash ||
|
||||
saved.input_epoch !== body.input_epoch ||
|
||||
saved.reason !== reason ||
|
||||
Object.keys(fields).some(
|
||||
(key) => saved.fields[key as keyof QualityFields] !== fields[key as keyof QualityFields]
|
||||
)
|
||||
)
|
||||
throw Error('保存后的精确复核记录尚未读回,请用原表单重试,重复请求不会重复留档')
|
||||
const fresh = await fetchQARecord(recordId, controller.signal)
|
||||
if (!fresh.quality || fresh.quality.revision < savedRevision)
|
||||
throw Error('复核已留档但当前问答尚未读回,请重新读取')
|
||||
if (!controller.signal.aborted) {
|
||||
setNotice(
|
||||
`已保存并读回复核第 ${savedRevision} 版${fresh.quality.state === 'stale' ? ';原始输入又有变化,旧结论不再生效' : ''}`
|
||||
)
|
||||
onSaved(fresh)
|
||||
}
|
||||
} catch (e) {
|
||||
if (!controller.signal.aborted) setError(message(e))
|
||||
} finally {
|
||||
if (!controller.signal.aborted) setLoading(false)
|
||||
}
|
||||
}
|
||||
const loadHistory = async (kind: 'initial' | 'reviews' | 'checks' = 'initial') => {
|
||||
reading.current?.abort()
|
||||
const controller = new AbortController()
|
||||
reading.current = controller
|
||||
setHistoryError('')
|
||||
setHistoryLoading(true)
|
||||
const params = new URLSearchParams()
|
||||
if (kind === 'reviews' && history?.next_review) params.set('review_before', String(history.next_review))
|
||||
if (kind === 'checks' && history?.next_check) params.set('check_before', String(history.next_check))
|
||||
try {
|
||||
const next = parseQualityHistory(
|
||||
await getPayload(
|
||||
`/api/v1/qa-ops/records/${encodeURIComponent(recordId)}/quality/history${params.size ? '?' + params : ''}`,
|
||||
controller.signal
|
||||
)
|
||||
)
|
||||
if (!controller.signal.aborted)
|
||||
setHistory((old) =>
|
||||
kind === 'initial' || !old
|
||||
? next
|
||||
: kind === 'reviews'
|
||||
? { ...old, reviews: [...old.reviews, ...next.reviews], next_review: next.next_review }
|
||||
: { ...old, checks: [...old.checks, ...next.checks], next_check: next.next_check }
|
||||
)
|
||||
} catch (e) {
|
||||
if (!controller.signal.aborted) setHistoryError(message(e))
|
||||
} finally {
|
||||
if (!controller.signal.aborted) setHistoryLoading(false)
|
||||
}
|
||||
}
|
||||
const loadInput = async (epoch: number) => {
|
||||
snapshotReading.current?.abort()
|
||||
const controller = new AbortController()
|
||||
snapshotReading.current = controller
|
||||
setHistoryError('')
|
||||
setSnapshot(null)
|
||||
try {
|
||||
const next = parseQualitySnapshot(
|
||||
await getPayload(
|
||||
`/api/v1/qa-ops/records/${encodeURIComponent(recordId)}/quality/inputs/${epoch}`,
|
||||
controller.signal
|
||||
)
|
||||
)
|
||||
if (next.payload.id !== recordId || next.input_epoch !== epoch) throw Error('历史输入版本不匹配')
|
||||
if (!controller.signal.aborted) setSnapshot(next)
|
||||
} catch (e) {
|
||||
if (!controller.signal.aborted) setHistoryError(message(e))
|
||||
}
|
||||
}
|
||||
return (
|
||||
<section className="qa-quality-editor" aria-label="人工复核与留档">
|
||||
<h4>
|
||||
人工复核 <span>{qualityLabels[quality.state]}</span>
|
||||
</h4>
|
||||
{quality.state === 'stale' ? (
|
||||
<p className="qa-ops-warning">
|
||||
待重新核对:原始问答输入已变化,旧人工结论仅供查阅,不再用于当前有效结果。请核对完整问题、答案、引用与媒体。
|
||||
</p>
|
||||
) : null}
|
||||
{quality.latest_review ? (
|
||||
<p className="qa-ops-muted">
|
||||
最近复核:{quality.latest_review.reviewer} · {stamp(quality.latest_review.created_at)} · 第{' '}
|
||||
{quality.latest_review.revision} 版
|
||||
</p>
|
||||
) : null}
|
||||
<p className="qa-ops-muted">
|
||||
AI 评估未接入。自动规则、源端判断和人工结论独立保留;以下分类沿用正式标签,不自动猜测。复核人取登录身份。
|
||||
</p>
|
||||
{error ? (
|
||||
<div role="alert" className="error-banner">
|
||||
{error}{' '}
|
||||
<button type="button" onClick={onReload} disabled={loading}>
|
||||
重新读取问答
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
{notice ? <p role="status">{notice}</p> : null}
|
||||
<form onSubmit={(event) => void submit(event)} aria-label="人工复核表单" className="qa-quality-form">
|
||||
<label>
|
||||
覆盖结论
|
||||
<select
|
||||
required
|
||||
disabled={loading}
|
||||
value={fields.coverage}
|
||||
onChange={(e) => change('coverage', e.target.value)}
|
||||
>
|
||||
<option value="">请选择</option>
|
||||
{['covered', 'uncovered', 'partial', 'pending', 'excluded'].map((key) => (
|
||||
<option key={key} value={key}>
|
||||
{qualityLabels[key]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
正确性
|
||||
<select
|
||||
required
|
||||
disabled={loading}
|
||||
value={fields.correctness}
|
||||
onChange={(e) => change('correctness', e.target.value)}
|
||||
>
|
||||
<option value="">请选择</option>
|
||||
{['correct', 'incorrect', 'pending'].map((key) => (
|
||||
<option key={key} value={key}>
|
||||
{qualityLabels[key]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
产品分类(可留空)
|
||||
<input
|
||||
disabled={loading}
|
||||
value={fields.product_category}
|
||||
maxLength={128}
|
||||
onChange={(e) => change('product_category', e.target.value)}
|
||||
placeholder="沿用正式标签"
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
问题类型(可留空)
|
||||
<input
|
||||
disabled={loading}
|
||||
value={fields.problem_type}
|
||||
maxLength={128}
|
||||
onChange={(e) => change('problem_type', e.target.value)}
|
||||
placeholder="沿用正式标签"
|
||||
/>
|
||||
</label>
|
||||
<label className="qa-quality-full">
|
||||
根因分析(有依据才填)
|
||||
<textarea
|
||||
disabled={loading || fields.correctness === 'correct'}
|
||||
value={fields.root_cause}
|
||||
maxLength={2000}
|
||||
onChange={(e) => change('root_cause', e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
{fields.coverage === 'excluded' ? (
|
||||
<label className="qa-quality-full">
|
||||
不计入原因
|
||||
<textarea
|
||||
required
|
||||
disabled={loading}
|
||||
value={fields.exclusion_reason}
|
||||
maxLength={2000}
|
||||
onChange={(e) => change('exclusion_reason', e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
) : null}
|
||||
<label className="qa-quality-full">
|
||||
复核理由
|
||||
<textarea
|
||||
required
|
||||
disabled={loading}
|
||||
value={reason}
|
||||
maxLength={4000}
|
||||
onChange={(e) => {
|
||||
setReason(e.target.value)
|
||||
setNotice('')
|
||||
}}
|
||||
placeholder="说明核对依据;不确定时选择待确认"
|
||||
/>
|
||||
</label>
|
||||
{quality.automatic.result.verdict === 'uncovered' && ['covered', 'partial'].includes(fields.coverage) ? (
|
||||
<p className="qa-ops-warning qa-quality-full">
|
||||
将采用有理由的人工结论;“暂无已发布”的自动命中记录仍保留,不伪装为未命中。
|
||||
</p>
|
||||
) : null}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={
|
||||
loading ||
|
||||
!fields.coverage ||
|
||||
!fields.correctness ||
|
||||
!reason.trim() ||
|
||||
(fields.coverage === 'excluded' && !fields.exclusion_reason.trim())
|
||||
}
|
||||
>
|
||||
{loading ? '正在保存并核对…' : '保存并读回'}
|
||||
</button>
|
||||
</form>
|
||||
<p className="qa-ops-muted qa-ops-organization">
|
||||
当前输入第 {quality.input_epoch} 次观察 · 复核版本 {quality.revision} · 自动复检已留档于{' '}
|
||||
{stamp(quality.automatic.created_at)}。当前输入指纹:{quality.input_hash}
|
||||
</p>
|
||||
<button type="button" disabled={historyLoading} onClick={() => void loadHistory()}>
|
||||
读取复核/复检历史
|
||||
</button>
|
||||
{historyError ? (
|
||||
<p role="alert" className="error-banner">
|
||||
{historyError}
|
||||
</p>
|
||||
) : null}
|
||||
{history ? (
|
||||
<div className="qa-quality-history">
|
||||
<h4>人工修改历史</h4>
|
||||
{history.reviews.length ? (
|
||||
history.reviews.map((r) => (
|
||||
<article key={r.revision}>
|
||||
<strong>
|
||||
复核 #{r.revision} · {r.reviewer} · {stamp(r.created_at)}
|
||||
</strong>
|
||||
<p>
|
||||
{qualityLabels[r.fields.coverage]} / {qualityLabels[r.fields.correctness]} ·{' '}
|
||||
{r.fields.product_category || '产品未填'} / {r.fields.problem_type || '类型未填'}
|
||||
</p>
|
||||
<p>{r.reason}</p>
|
||||
{r.fields.root_cause ? <p>根因:{r.fields.root_cause}</p> : null}
|
||||
{r.fields.exclusion_reason ? <p>不计入原因:{r.fields.exclusion_reason}</p> : null}
|
||||
<button type="button" onClick={() => void loadInput(r.input_epoch)}>
|
||||
查看第 {r.input_epoch} 次输入
|
||||
</button>
|
||||
</article>
|
||||
))
|
||||
) : (
|
||||
<p>尚无人工修改记录。</p>
|
||||
)}
|
||||
{history.next_review ? (
|
||||
<button disabled={historyLoading} type="button" onClick={() => void loadHistory('reviews')}>
|
||||
更多人工历史
|
||||
</button>
|
||||
) : null}
|
||||
<h4>自动复检历史(不是 AI 评估)</h4>
|
||||
{history.checks.map((c) => (
|
||||
<article key={c.id}>
|
||||
<p>
|
||||
输入 #{c.input_epoch} · {c.result.rule_version} · {stamp(c.created_at)}
|
||||
</p>
|
||||
<p>
|
||||
{c.result.verdict === 'uncovered' ? '命中“暂无已发布”:未覆盖' : '未命中:仍待评估,不默认覆盖'}
|
||||
;当次源判断:{c.source.verdict || '未记录'}
|
||||
</p>
|
||||
<button type="button" disabled={!c.input_available} onClick={() => void loadInput(c.input_epoch)}>
|
||||
{c.input_available ? `查看第 ${c.input_epoch} 次输入` : '此版本仅留存指纹/命中元数据'}
|
||||
</button>
|
||||
</article>
|
||||
))}
|
||||
{history.next_check ? (
|
||||
<button disabled={historyLoading} type="button" onClick={() => void loadHistory('checks')}>
|
||||
更多复检历史
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
{snapshot ? (
|
||||
<section aria-label="历史评估输入">
|
||||
<h4>历史输入 #{snapshot.input_epoch}</h4>
|
||||
<p>{stamp(snapshot.created_at)} · 仅此历史版本,不代表当前答案</p>
|
||||
<h5>原始问题</h5>
|
||||
<pre>{snapshot.payload.question}</pre>
|
||||
<h5>当时答案</h5>
|
||||
<pre>{snapshot.payload.answer}</pre>
|
||||
<details>
|
||||
<summary>当时引用与媒体</summary>
|
||||
<pre>
|
||||
{JSON.stringify({ references: snapshot.payload.references, media: snapshot.payload.media }, null, 2)}
|
||||
</pre>
|
||||
</details>
|
||||
</section>
|
||||
) : null}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
interface SummaryProps {
|
||||
data: QualitySummary | null
|
||||
loading: boolean
|
||||
error: string
|
||||
onRefresh: () => void
|
||||
}
|
||||
export function QAQualitySummaryView({ data, loading, error, onRefresh }: SummaryProps) {
|
||||
return (
|
||||
<section className="qa-quality-summary" aria-label="质量数量">
|
||||
<button type="button" disabled={loading} onClick={onRefresh}>
|
||||
{loading ? '正在复检留档…' : '复检留档与质量数量'}
|
||||
</button>
|
||||
{error ? (
|
||||
<p role="alert" className="error-banner">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
{data && !error && !loading ? (
|
||||
<>
|
||||
<p>
|
||||
完整筛选范围 {data.summary.total} 条 · 已复核 {data.summary.reviewed} · 未复核 {data.summary.unreviewed} ·
|
||||
待重新核对 {data.summary.stale} · 人工待确认 {data.summary.pending_confirmation} · 规则命中未覆盖{' '}
|
||||
{data.summary.rule_uncovered}
|
||||
</p>
|
||||
<div className="qa-quality-rates" aria-label="质量比例">
|
||||
{(
|
||||
[
|
||||
['知识覆盖率', data.summary.rates.coverage],
|
||||
['回答正确率', data.summary.rates.correctness],
|
||||
] as const
|
||||
).map(([label, rate]) => (
|
||||
<div key={label}>
|
||||
<strong>
|
||||
{label}:{rate.percent === null ? '暂无可计算数据' : `${rate.percent.toFixed(1)}%`}
|
||||
</strong>
|
||||
<p>
|
||||
分子 {rate.numerator} / 分母 {rate.denominator};排除 {data.summary.total - rate.denominator} 条
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<details className="qa-ops-organization">
|
||||
<summary>查看比例口径和分母构成</summary>
|
||||
<p>
|
||||
覆盖分母:已覆盖 {data.summary.rates.breakdown.covered} + 未覆盖 {data.summary.rates.breakdown.uncovered}{' '}
|
||||
+ 部分覆盖 {data.summary.rates.breakdown.partial};部分覆盖不计完全覆盖。
|
||||
</p>
|
||||
<p>
|
||||
覆盖分母排除:待确认 {data.summary.rates.breakdown.pending}、未评估{' '}
|
||||
{data.summary.rates.breakdown.unassessed}、不计入 {data.summary.rates.breakdown.excluded}、待重新核对{' '}
|
||||
{data.summary.rates.breakdown.stale}。
|
||||
</p>
|
||||
<p>
|
||||
正确性分母仅含已覆盖且判断明确:正确 {data.summary.rates.breakdown.covered_correct} + 错误{' '}
|
||||
{data.summary.rates.breakdown.covered_incorrect};已覆盖中的待确认{' '}
|
||||
{data.summary.rates.breakdown.covered_pending}、未评估 {data.summary.rates.breakdown.covered_unassessed}{' '}
|
||||
不计入,其余未覆盖/部分覆盖等记录也不计入。
|
||||
</p>
|
||||
<p>
|
||||
当前有效人工结论优先;精确规则命中的未覆盖可进入覆盖分母,但不证明回答错误。失效记录暂不参与两项比例,原始问答运行成功也不代表答案正确。
|
||||
</p>
|
||||
<p className="qa-ops-muted">统计规则:{data.summary.rates.policy_version}</p>
|
||||
</details>
|
||||
<p className="qa-ops-muted">
|
||||
AI 评估未接入;人工待确认是已复核中的子集,规则命中可与人工结论不同。读取:{stamp(data.as_of)}
|
||||
</p>
|
||||
</>
|
||||
) : !error && !loading ? (
|
||||
<span className="qa-ops-muted">按当前完整时间/关键词范围留档,不按当前页估算。</span>
|
||||
) : null}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
export function QAQualityCounts({ query, revision }: { query: QAQuery | null; revision: number }) {
|
||||
const [data, setData] = useState<QualitySummary | null>(null),
|
||||
[loading, setLoading] = useState(false),
|
||||
[error, setError] = useState(''),
|
||||
[requested, setRequested] = useState(false),
|
||||
[refresh, setRefresh] = useState(0)
|
||||
useEffect(() => {
|
||||
if (!query || !requested) {
|
||||
setData(null)
|
||||
return
|
||||
}
|
||||
const controller = new AbortController()
|
||||
setData(null)
|
||||
setError('')
|
||||
setLoading(true)
|
||||
getPayload('/api/v1/qa-ops/quality/query', controller.signal, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'X-Governance-Action': 'qa-quality' },
|
||||
body: JSON.stringify({ start: query.start, end: query.end, keyword: query.keyword }),
|
||||
})
|
||||
.then((raw) => {
|
||||
const next = parseQualitySummary(raw)
|
||||
if (
|
||||
(next.start !== query.start && Date.parse(next.start) !== Date.parse(query.start)) ||
|
||||
Date.parse(next.end) !== Date.parse(query.end) ||
|
||||
next.keyword !== query.keyword
|
||||
)
|
||||
throw Error('质量数量与当前查询范围不一致')
|
||||
if (!controller.signal.aborted) setData(next)
|
||||
})
|
||||
.catch((e) => {
|
||||
if (!controller.signal.aborted) setError(message(e))
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) setLoading(false)
|
||||
})
|
||||
return () => controller.abort()
|
||||
}, [query, revision, requested, refresh])
|
||||
return (
|
||||
<QAQualitySummaryView
|
||||
data={data}
|
||||
loading={loading}
|
||||
error={error}
|
||||
onRefresh={() => {
|
||||
setRequested(true)
|
||||
setRefresh((v) => v + 1)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { QAWeekPicker } from './QAWeekPicker'
|
||||
|
||||
describe('QA week picker', () => {
|
||||
it('offers a one-click current-week shortcut', () => {
|
||||
const html = renderToStaticMarkup(<QAWeekPicker year={2026} week={40} onChange={vi.fn()} />)
|
||||
expect(html).toContain('>本周</button>')
|
||||
})
|
||||
it('shows a year and numbered weeks with visible inclusive date ranges', () => {
|
||||
const html = renderToStaticMarkup(<QAWeekPicker year={2026} week={40} onChange={vi.fn()} />)
|
||||
expect(html).toContain('aria-label="年份"')
|
||||
expect(html).toContain('2026年')
|
||||
expect(html).toContain('aria-label="周次"')
|
||||
expect(html).toContain('value="40" selected=""')
|
||||
expect(html).toContain('第40周(09-28 到 10-04)')
|
||||
expect(html).toContain('第53周(2026-12-28 到 2027-01-03)')
|
||||
expect(html).toContain('北京时间')
|
||||
expect(html).toContain('周一至周日')
|
||||
})
|
||||
it('preserves custom range mode and does not offer invalid week 53', () => {
|
||||
const html = renderToStaticMarkup(<QAWeekPicker year={2027} week={null} onChange={vi.fn()} />)
|
||||
expect(html).toContain('value="" selected=""')
|
||||
expect(html).toContain('自定义时间')
|
||||
expect(html).not.toContain('第53周')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,56 @@
|
||||
import { currentQAWeek, qaWeek, qaWeeksInYear } from './qaWeeks'
|
||||
|
||||
interface Props {
|
||||
year: number
|
||||
week: number | null
|
||||
onChange: (year: number, week: number | null) => void
|
||||
onCurrentWeek?: () => void
|
||||
}
|
||||
|
||||
export function QAWeekPicker({ year, week, onChange, onCurrentWeek }: Props) {
|
||||
const currentYear = currentQAWeek().year
|
||||
const firstYear = Math.min(currentYear - 5, year)
|
||||
const lastYear = Math.max(currentYear + 1, year)
|
||||
return (
|
||||
<div className="qa-week-picker" role="group" aria-label="按周选择">
|
||||
<label>
|
||||
年份
|
||||
<select
|
||||
aria-label="年份"
|
||||
value={year}
|
||||
onChange={(event) => {
|
||||
const nextYear = Number(event.target.value)
|
||||
onChange(nextYear, Math.min(week ?? 1, qaWeeksInYear(nextYear)))
|
||||
}}
|
||||
>
|
||||
{Array.from({ length: lastYear - firstYear + 1 }, (_, i) => firstYear + i)
|
||||
.reverse()
|
||||
.map((value) => (
|
||||
<option key={value} value={value}>
|
||||
{value}年
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
周次
|
||||
<select
|
||||
aria-label="周次"
|
||||
value={week ?? ''}
|
||||
onChange={(event) => onChange(year, event.target.value === '' ? null : Number(event.target.value))}
|
||||
>
|
||||
<option value="">自定义时间</option>
|
||||
{Array.from({ length: qaWeeksInYear(year) }, (_, i) => i + 1).map((value) => (
|
||||
<option key={value} value={value}>
|
||||
{qaWeek(year, value).label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<button className="qa-week-current" type="button" onClick={onCurrentWeek}>
|
||||
本周
|
||||
</button>
|
||||
<span className="qa-ops-muted">北京时间 · 周一至周日 · 本周截至当前</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -98,6 +98,13 @@ const render = (over: Partial<Parameters<typeof VersionHistoryView>[0]> = {}) =>
|
||||
)
|
||||
|
||||
describe('VersionHistoryView', () => {
|
||||
it('renders the exact development changelog instead of hiding all non-release notes', () => {
|
||||
const html = render({
|
||||
expanded: developmentItem.commit_sha,
|
||||
page: { ...page, items: [{ ...developmentItem, release_notes: '这次开发独有的变更说明' }] },
|
||||
})
|
||||
expect(html).toContain('这次开发独有的变更说明')
|
||||
})
|
||||
it('lists commits newest-first with kind badges, short sha, times and links', () => {
|
||||
const html = render()
|
||||
expect(html).toContain('版本记录')
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
import { useOptionalAuth } from './auth'
|
||||
import './versionHistory.css'
|
||||
|
||||
// 「版本记录」页:追踪**所有已进入远端 main 的提交**,按提交时间倒序。
|
||||
// 「版本记录」页:追踪远端 main、已交付开发快照及当前运行 SHA 的提交,按提交时间倒序。
|
||||
// 只读:不提供打 tag / 发布 / 部署按钮;版本号只按证据展示,证据不足就说"历史提交"。
|
||||
const FILTERS: ReadonlyArray<{ id: string; label: string }> = [
|
||||
{ id: 'all', label: '全部' },
|
||||
@@ -158,7 +158,7 @@ function TimelineEntry({
|
||||
}) {
|
||||
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 note = item.version_state === 'verified' ? item.release_notes : ''
|
||||
const hasDetail = Boolean(item.body) || Boolean(note)
|
||||
return (
|
||||
<li className={`version-history-entry ${item.record_kind}`}>
|
||||
@@ -185,7 +185,7 @@ function TimelineEntry({
|
||||
</button>
|
||||
{expanded ? (
|
||||
<div className="version-history-detail">
|
||||
{item.record_kind === 'release' && note ? <pre>{note}</pre> : null}
|
||||
{note ? <pre>{note}</pre> : null}
|
||||
{item.body ? <pre>{item.body}</pre> : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { fetchAllQARecords } from './qaOps'
|
||||
const row = (id: string) => ({
|
||||
id,
|
||||
status: 'succeeded',
|
||||
question: '明确合成问题',
|
||||
answer: '明确合成答案',
|
||||
asked_at: '2026-10-14T03:00:00Z',
|
||||
time_source: 'request_message.created_at',
|
||||
asker: '合成夹具',
|
||||
trigger_person: '',
|
||||
department: '',
|
||||
region: '',
|
||||
references: [],
|
||||
media: [],
|
||||
source_coverage: { verdict: '', reason_code: '', evaluator_version: '' },
|
||||
feedback: { asker_value: '', up: 0, down: 0 },
|
||||
coverage: { state: 'pending', rule_version: 'fixture-rule' },
|
||||
})
|
||||
const page = (ids: string[], total: number, cursor = '') => ({
|
||||
items: ids.map(row),
|
||||
columns: [],
|
||||
total,
|
||||
has_more: Boolean(cursor),
|
||||
next_cursor: cursor,
|
||||
as_of: '2026-10-14T04:00:00Z',
|
||||
})
|
||||
const query = { start: '2026-10-11T16:00:00Z', end: '2026-10-18T08:00:00Z', keyword: '%_原文', cursor: 'stale-cursor' }
|
||||
const respond = (data: unknown) => new Response(JSON.stringify({ data }), { status: 200 })
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
describe('all QA records without manual pagination', () => {
|
||||
it('rejects incomplete, duplicate, drifting and cycling batches', async () => {
|
||||
const cases = [
|
||||
[page(['a'], 2)],
|
||||
[page(['a'], 2, 'n'), page(['a'], 2)],
|
||||
[page(['a'], 2, 'n'), page(['b'], 3)],
|
||||
[page(['a'], 3, 'n'), page(['b'], 3, 'n')],
|
||||
]
|
||||
for (const pages of cases) {
|
||||
const fetcher = vi.fn()
|
||||
pages.forEach((data) => fetcher.mockResolvedValueOnce(respond(data)))
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
await expect(fetchAllQARecords(query)).rejects.toThrow()
|
||||
}
|
||||
})
|
||||
it('surfaces a later source failure instead of returning the first batch', async () => {
|
||||
const fetcher = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(respond(page(['a'], 2, 'n')))
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ error: '明确合成源不可用' }), { status: 503 }))
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
await expect(fetchAllQARecords(query)).rejects.toThrow('明确合成源不可用')
|
||||
})
|
||||
it('accepts a genuinely empty complete scope', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(respond(page([], 0))))
|
||||
expect((await fetchAllQARecords(query)).items).toEqual([])
|
||||
})
|
||||
it('does not start or continue requests after cancellation', async () => {
|
||||
const controller = new AbortController()
|
||||
controller.abort()
|
||||
const fetcher = vi.fn().mockResolvedValue(respond(page([], 0)))
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
await expect(fetchAllQARecords(query, controller.signal)).rejects.toMatchObject({ name: 'AbortError' })
|
||||
expect(fetcher).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reads every transport batch and verifies final count before returning', async () => {
|
||||
const fetcher = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(respond(page(['a', 'b'], 3, 'next')))
|
||||
.mockResolvedValueOnce(respond(page(['c'], 3)))
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
const progress = vi.fn()
|
||||
const result = await fetchAllQARecords(query, undefined, progress)
|
||||
expect(result.items.map((r) => r.id)).toEqual(['a', 'b', 'c'])
|
||||
expect(result.has_more).toBe(false)
|
||||
expect(result.total).toBe(3)
|
||||
expect(progress.mock.calls).toEqual([
|
||||
[2, 3],
|
||||
[3, 3],
|
||||
])
|
||||
const urls = fetcher.mock.calls.map((call) => new URL(String(call[0]), 'http://localhost'))
|
||||
expect(urls.map((url) => url.searchParams.get('cursor'))).toEqual(['', 'next'])
|
||||
expect(
|
||||
urls.every((url) => url.searchParams.get('limit') === '100' && url.searchParams.get('keyword') === query.keyword)
|
||||
).toBe(true)
|
||||
})
|
||||
})
|
||||
+118
-1
@@ -55,6 +55,81 @@
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
.qa-quality-state {
|
||||
display: block;
|
||||
margin-top: 5px;
|
||||
color: var(--ink-mute);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.qa-quality-summary {
|
||||
padding: 10px 14px;
|
||||
border: 1px solid var(--border-base);
|
||||
background: var(--bg-panel);
|
||||
font-size: 12px;
|
||||
}
|
||||
.qa-quality-summary > span {
|
||||
margin-left: 10px;
|
||||
}
|
||||
.qa-quality-summary p {
|
||||
margin: 7px 0 0;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.qa-quality-editor {
|
||||
border-top: 1px solid var(--border-base);
|
||||
margin-top: 20px;
|
||||
padding-top: 2px;
|
||||
}
|
||||
.qa-quality-form {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
.qa-quality-form label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
font-size: 12px;
|
||||
color: var(--ink-mute);
|
||||
}
|
||||
.qa-quality-form input,
|
||||
.qa-quality-form select,
|
||||
.qa-quality-form textarea {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding: 8px;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--r-sm);
|
||||
background: var(--bg-panel);
|
||||
color: var(--ink-strong);
|
||||
font: inherit;
|
||||
}
|
||||
.qa-quality-form textarea {
|
||||
min-height: 68px;
|
||||
resize: vertical;
|
||||
}
|
||||
.qa-quality-full {
|
||||
grid-column: 1/-1;
|
||||
}
|
||||
.qa-quality-editor > p {
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.qa-quality-history article {
|
||||
border-bottom: 1px solid var(--border-base);
|
||||
padding: 10px 0;
|
||||
overflow-wrap: anywhere;
|
||||
font-size: 12px;
|
||||
}
|
||||
.qa-quality-editor pre {
|
||||
max-height: 300px;
|
||||
overflow: auto;
|
||||
}
|
||||
@media (max-width: 500px) {
|
||||
.qa-quality-form {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
.qa-ops-header h2 {
|
||||
margin: 0 0 5px;
|
||||
font-size: 21px;
|
||||
@@ -88,7 +163,8 @@
|
||||
color: var(--ink-mute);
|
||||
font-size: 12px;
|
||||
}
|
||||
.qa-ops-query input {
|
||||
.qa-ops-query input,
|
||||
.qa-week-picker select {
|
||||
min-height: 36px;
|
||||
min-width: 0;
|
||||
padding: 7px 10px;
|
||||
@@ -97,6 +173,24 @@
|
||||
border-radius: var(--r-sm);
|
||||
background: var(--bg-panel);
|
||||
}
|
||||
.qa-week-picker {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: end;
|
||||
flex-basis: 100%;
|
||||
min-width: 0;
|
||||
gap: 12px;
|
||||
}
|
||||
.qa-week-picker label {
|
||||
min-width: 0;
|
||||
}
|
||||
.qa-week-picker select {
|
||||
max-width: 100%;
|
||||
font: inherit;
|
||||
}
|
||||
.qa-week-picker > span {
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
.qa-ops-keyword {
|
||||
flex: 1;
|
||||
min-width: 170px;
|
||||
@@ -108,8 +202,17 @@
|
||||
background: var(--c-run);
|
||||
border: 1px solid var(--c-run);
|
||||
}
|
||||
.qa-ops-query .qa-week-current {
|
||||
color: var(--ink-strong);
|
||||
background: var(--bg-panel);
|
||||
border-color: var(--border-strong);
|
||||
}
|
||||
.qa-ops-query .qa-week-current:hover {
|
||||
background: var(--bg-soft);
|
||||
}
|
||||
.qa-ops button:focus-visible,
|
||||
.qa-ops input:focus-visible,
|
||||
.qa-ops select:focus-visible,
|
||||
.qa-ops-table-scroll:focus-visible {
|
||||
outline: 2px solid var(--c-run);
|
||||
outline-offset: 2px;
|
||||
@@ -319,3 +422,17 @@
|
||||
grid-template-columns: 100px 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.qa-quality-rates {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px 32px;
|
||||
margin: 12px 0;
|
||||
}
|
||||
.qa-quality-rates > div {
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.qa-quality-rates p {
|
||||
margin: 4px 0 0;
|
||||
}
|
||||
|
||||
+56
-1
@@ -1,3 +1,5 @@
|
||||
import { parseQAQuality } from './qaQuality'
|
||||
import type { QAQuality } from './qaQuality'
|
||||
export const qaColumns = [
|
||||
{ key: 'question_chinese', label: '中文问题' },
|
||||
{ key: 'answer', label: 'AI答案' },
|
||||
@@ -69,6 +71,7 @@ export function mergeQAPages(current: QARecordPage, next: QARecordPage): QARecor
|
||||
}
|
||||
}
|
||||
export interface QARecord {
|
||||
quality?: QAQuality
|
||||
organization?: QARecordOrganization
|
||||
id: string
|
||||
status: string
|
||||
@@ -145,6 +148,7 @@ export function parseQARecord(value: unknown): QARecord {
|
||||
const askerValue = text(feedback.asker_value)
|
||||
if (!['', 'up', 'down'].includes(askerValue)) return invalid()
|
||||
const item: QARecord = {
|
||||
...(row.quality === undefined ? {} : { quality: parseQAQuality(row.quality) }),
|
||||
id: text(row.id),
|
||||
status: text(row.status),
|
||||
question: text(row.question),
|
||||
@@ -255,6 +259,35 @@ export async function fetchQARecords(query: QAQuery, signal?: AbortSignal): Prom
|
||||
})
|
||||
return parseQARecordPage(await getPayload(`/api/v1/qa-ops/records?${parameters}`, signal))
|
||||
}
|
||||
export async function fetchAllQARecords(
|
||||
query: QAQuery,
|
||||
signal?: AbortSignal,
|
||||
onProgress?: (loaded: number, total: number) => void
|
||||
): Promise<QARecordPage> {
|
||||
if (signal?.aborted) throw new DOMException('读取已取消', 'AbortError')
|
||||
let page = await fetchQARecords({ ...query, cursor: '', limit: 100 }, signal)
|
||||
const total = page.total
|
||||
const ids = new Set(page.items.map((item) => item.id))
|
||||
const cursors = new Set<string>()
|
||||
onProgress?.(ids.size, total)
|
||||
while (page.has_more) {
|
||||
if (signal?.aborted) throw new DOMException('读取已取消', 'AbortError')
|
||||
const cursor = page.next_cursor
|
||||
if (cursors.has(cursor) || ids.size >= total) throw new Error('全量读取游标异常,请重新查询')
|
||||
cursors.add(cursor)
|
||||
const next = await fetchQARecords({ ...query, cursor, limit: 100 }, signal)
|
||||
if (next.total !== total) throw new Error('查询总数已变化,请重新查询,未将部分记录当作全部结果')
|
||||
for (const item of next.items) {
|
||||
if (ids.has(item.id)) throw new Error('全量读取出现重复记录,请重新查询')
|
||||
ids.add(item.id)
|
||||
}
|
||||
page = mergeQAPages(page, next)
|
||||
onProgress?.(ids.size, total)
|
||||
}
|
||||
if (ids.size !== total) throw new Error('全量读取数量不完整,请重试,未将部分记录当作全部结果')
|
||||
return page
|
||||
}
|
||||
|
||||
export async function fetchQARecord(id: string, signal?: AbortSignal): Promise<QARecord> {
|
||||
return parseQARecord(await getPayload(`/api/v1/qa-ops/records/${encodeURIComponent(id)}`, signal))
|
||||
}
|
||||
@@ -279,6 +312,27 @@ export async function fetchQAStatus(signal?: AbortSignal): Promise<QAStatus> {
|
||||
}
|
||||
|
||||
export function qaCellValue(item: QARecord, column: QAColumn): string | null {
|
||||
if (column === 'question_chinese')
|
||||
return item.question_chinese || (/\p{Script=Han}/u.test(item.question) ? item.question : '待翻译')
|
||||
if (column === 'language') return item.language || '未识别'
|
||||
const f = item.quality?.effective
|
||||
if (f) {
|
||||
if (column === 'coverage')
|
||||
return f.coverage
|
||||
? (
|
||||
{ covered: '是', uncovered: '否', partial: '部分覆盖', pending: '待确认', excluded: '不计入' } as Record<
|
||||
string,
|
||||
string
|
||||
>
|
||||
)[f.coverage]
|
||||
: null
|
||||
if (column === 'is_correct')
|
||||
return f.correctness
|
||||
? ({ correct: '是', incorrect: '否', pending: '待确认' } as Record<string, string>)[f.correctness]
|
||||
: null
|
||||
if (column === 'product_category' || column === 'problem_type' || column === 'root_cause') return f[column] || null
|
||||
}
|
||||
|
||||
if (column === 'coverage') return item.coverage.verdict === 'uncovered' ? '否' : null
|
||||
if (column === 'is_correct') return typeof item.is_correct === 'boolean' ? (item.is_correct ? '是' : '否') : null
|
||||
if (column === 'feedback') {
|
||||
@@ -287,6 +341,7 @@ export function qaCellValue(item: QARecord, column: QAColumn): string | null {
|
||||
if (item.feedback.up || item.feedback.down) return `其他人:赞 ${item.feedback.up} / 踩 ${item.feedback.down}`
|
||||
return null
|
||||
}
|
||||
if (column === 'asked_at') return new Date(item.asked_at).toLocaleString('zh-CN', { hour12: false })
|
||||
if (column === 'asked_at')
|
||||
return new Date(item.asked_at).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })
|
||||
return item[column] || null
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
export const hash = 'a'.repeat(64)
|
||||
export const fields = {
|
||||
coverage: 'covered',
|
||||
correctness: 'correct',
|
||||
product_category: 'MG400',
|
||||
problem_type: '咨询',
|
||||
root_cause: '',
|
||||
exclusion_reason: '',
|
||||
}
|
||||
export const check = {
|
||||
input_available: true,
|
||||
id: 1,
|
||||
input_epoch: 1,
|
||||
input_hash: hash,
|
||||
result: {
|
||||
state: 'checked',
|
||||
verdict: 'uncovered',
|
||||
rule_version: 'governance-answer-substring-v1',
|
||||
matched_text: '暂无已发布',
|
||||
},
|
||||
source: { verdict: 'covered', reason_code: 'source only', evaluator_version: 'v5' },
|
||||
created_at: '2026-10-17T12:00:00Z',
|
||||
}
|
||||
export const review = {
|
||||
revision: 1,
|
||||
input_epoch: 1,
|
||||
input_hash: hash,
|
||||
fields,
|
||||
reason: '<script>示例理由</script>',
|
||||
reviewer: 'fixture-admin',
|
||||
created_at: '2026-10-17T12:01:00Z',
|
||||
}
|
||||
export const qualityFixture = {
|
||||
input_hash: hash,
|
||||
input_epoch: 1,
|
||||
revision: 1,
|
||||
state: 'reviewed',
|
||||
automatic: check,
|
||||
latest_review: review,
|
||||
effective: fields,
|
||||
}
|
||||
export const summaryFixture = {
|
||||
summary: {
|
||||
total: 3,
|
||||
reviewed: 1,
|
||||
unreviewed: 1,
|
||||
stale: 1,
|
||||
pending_confirmation: 0,
|
||||
rule_uncovered: 2,
|
||||
rates: {
|
||||
policy_version: 'quality-rates-human-first-v1',
|
||||
coverage: { numerator: 1, denominator: 2, percent: 50 },
|
||||
correctness: { numerator: 1, denominator: 1, percent: 100 },
|
||||
breakdown: {
|
||||
covered: 1,
|
||||
uncovered: 1,
|
||||
partial: 0,
|
||||
pending: 0,
|
||||
unassessed: 0,
|
||||
excluded: 0,
|
||||
stale: 1,
|
||||
covered_correct: 1,
|
||||
covered_incorrect: 0,
|
||||
covered_pending: 0,
|
||||
covered_unassessed: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
start: '2026-10-14T00:00:00Z',
|
||||
end: '2026-10-15T00:00:00Z',
|
||||
keyword: '',
|
||||
as_of: '2026-10-17T12:01:00Z',
|
||||
scope: 'whole_filter',
|
||||
ai_state: 'not_configured',
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseQAQuality, parseQualitySummary, parseQualityHistory } from './qaQuality'
|
||||
import { qualityFixture, summaryFixture, check, review } from './qaQuality.fixture'
|
||||
import { parseQARecord, qaCellValue } from './qaOps'
|
||||
describe('quality evidence contracts', () => {
|
||||
it('renders effective manual labels in agreed columns without changing the rule result', () => {
|
||||
const record = parseQARecord({
|
||||
id: 'fixture',
|
||||
status: 'succeeded',
|
||||
question: '示例',
|
||||
answer: '暂无已发布',
|
||||
asked_at: '2026-10-17T12:00:00Z',
|
||||
time_source: 'request_message.created_at',
|
||||
asker: '',
|
||||
trigger_person: '',
|
||||
department: '',
|
||||
region: '',
|
||||
references: [],
|
||||
media: [],
|
||||
source_coverage: check.source,
|
||||
feedback: { asker_value: '', up: 0, down: 0 },
|
||||
coverage: check.result,
|
||||
quality: qualityFixture,
|
||||
})
|
||||
expect(qaCellValue(record, 'coverage')).toBe('是')
|
||||
expect(qaCellValue(record, 'is_correct')).toBe('是')
|
||||
expect(qaCellValue(record, 'product_category')).toBe('MG400')
|
||||
expect(record.coverage.verdict).toBe('uncovered')
|
||||
})
|
||||
|
||||
it('separates immutable rule/source results and explicit human outcomes', () => {
|
||||
const v = parseQAQuality(qualityFixture)
|
||||
expect(v.effective.coverage).toBe('covered')
|
||||
expect(v.automatic.result.verdict).toBe('uncovered')
|
||||
})
|
||||
it('rejects stale conclusions kept effective and forged revisions', () => {
|
||||
expect(() =>
|
||||
parseQAQuality({ ...qualityFixture, state: 'stale', input_epoch: 2, automatic: { ...check, input_epoch: 2 } })
|
||||
).toThrow()
|
||||
expect(() => parseQAQuality({ ...qualityFixture, revision: 2 })).toThrow()
|
||||
})
|
||||
it('keeps scope counts whole and conservative without made-up rates', () => {
|
||||
expect(parseQualitySummary(summaryFixture).summary.total).toBe(3)
|
||||
expect(() => parseQualitySummary({ ...summaryFixture, summary: { ...summaryFixture.summary, total: 4 } })).toThrow()
|
||||
})
|
||||
it('retains pageable human and automatic history independently', () => {
|
||||
expect(
|
||||
parseQualityHistory({ reviews: [review], checks: [check], next_review: 0, next_check: 0 }).reviews
|
||||
).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('confirmed quality rate contract', () => {
|
||||
it('retains raw counts, null rates, scope breakdown and policy version', () => {
|
||||
const result = parseQualitySummary(summaryFixture)
|
||||
expect(result.summary.rates.coverage.numerator).toBe(1)
|
||||
expect(result.summary.rates.coverage.denominator).toBe(2)
|
||||
expect(result.summary.rates.correctness.percent).toBe(100)
|
||||
})
|
||||
it('rejects invalid or inconsistent numerator, denominator, percent and category sums', () => {
|
||||
for (const change of [
|
||||
(r: any) => (r.coverage.numerator = 3),
|
||||
(r: any) => (r.coverage.denominator = 3),
|
||||
(r: any) => (r.coverage.percent = 99),
|
||||
(r: any) => (r.breakdown.stale = 0),
|
||||
(r: any) => (r.correctness.percent = null),
|
||||
(r: any) => (r.policy_version = 'unknown'),
|
||||
]) {
|
||||
const v = structuredClone(summaryFixture)
|
||||
change(v.summary.rates)
|
||||
expect(() => parseQualitySummary(v)).toThrow()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,339 @@
|
||||
export interface QualityFields {
|
||||
coverage: string
|
||||
correctness: string
|
||||
product_category: string
|
||||
problem_type: string
|
||||
root_cause: string
|
||||
exclusion_reason: string
|
||||
}
|
||||
export interface QualityCheck {
|
||||
input_available: boolean
|
||||
id: number
|
||||
input_epoch: number
|
||||
input_hash: string
|
||||
result: { state: string; verdict?: string; rule_version: string; matched_text?: string }
|
||||
source: { verdict: string; reason_code: string; evaluator_version: string }
|
||||
created_at: string
|
||||
}
|
||||
export interface QualityReview {
|
||||
revision: number
|
||||
input_epoch: number
|
||||
input_hash: string
|
||||
fields: QualityFields
|
||||
reason: string
|
||||
reviewer: string
|
||||
created_at: string
|
||||
}
|
||||
export interface QAQuality {
|
||||
input_hash: string
|
||||
input_epoch: number
|
||||
revision: number
|
||||
state: 'unreviewed' | 'reviewed' | 'stale'
|
||||
automatic: QualityCheck
|
||||
latest_review: QualityReview | null
|
||||
effective: QualityFields
|
||||
}
|
||||
export interface QualityHistory {
|
||||
reviews: QualityReview[]
|
||||
checks: QualityCheck[]
|
||||
next_review: number
|
||||
next_check: number
|
||||
}
|
||||
export interface QualitySnapshot {
|
||||
input_epoch: number
|
||||
input_hash: string
|
||||
created_at: string
|
||||
payload: { id: string; question: string; answer: string; status: string; references: unknown; media: unknown }
|
||||
}
|
||||
export interface QualityRate {
|
||||
numerator: number
|
||||
denominator: number
|
||||
percent: number | null
|
||||
}
|
||||
export interface QualityRates {
|
||||
policy_version: 'quality-rates-human-first-v1'
|
||||
coverage: QualityRate
|
||||
correctness: QualityRate
|
||||
breakdown: {
|
||||
covered: number
|
||||
uncovered: number
|
||||
partial: number
|
||||
pending: number
|
||||
unassessed: number
|
||||
excluded: number
|
||||
stale: number
|
||||
covered_correct: number
|
||||
covered_incorrect: number
|
||||
covered_pending: number
|
||||
covered_unassessed: number
|
||||
}
|
||||
}
|
||||
export interface QualitySummary {
|
||||
summary: {
|
||||
total: number
|
||||
reviewed: number
|
||||
unreviewed: number
|
||||
stale: number
|
||||
pending_confirmation: number
|
||||
rule_uncovered: number
|
||||
rates: QualityRates
|
||||
}
|
||||
start: string
|
||||
end: string
|
||||
keyword: string
|
||||
as_of: string
|
||||
scope: 'whole_filter'
|
||||
ai_state: 'not_configured'
|
||||
}
|
||||
export const emptyQualityFields: QualityFields = {
|
||||
coverage: '',
|
||||
correctness: '',
|
||||
product_category: '',
|
||||
problem_type: '',
|
||||
root_cause: '',
|
||||
exclusion_reason: '',
|
||||
}
|
||||
export const qualityLabels: Record<string, string> = {
|
||||
covered: '已覆盖',
|
||||
uncovered: '未覆盖',
|
||||
partial: '部分覆盖',
|
||||
pending: '待确认',
|
||||
excluded: '不计入',
|
||||
correct: '正确',
|
||||
incorrect: '错误',
|
||||
unreviewed: '未复核',
|
||||
reviewed: '已复核',
|
||||
stale: '待重新核对',
|
||||
}
|
||||
const bad = (): never => {
|
||||
throw new Error('质量留档响应无效,未展示可能失真的结论')
|
||||
}
|
||||
const obj = (v: unknown): Record<string, unknown> =>
|
||||
v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : bad()
|
||||
const text = (v: unknown): string => (typeof v === 'string' ? v : bad())
|
||||
const num = (v: unknown): number => (typeof v === 'number' && Number.isSafeInteger(v) && v >= 0 ? v : bad())
|
||||
const positive = (v: unknown): number => {
|
||||
const n = num(v)
|
||||
return n > 0 ? n : bad()
|
||||
}
|
||||
const hash = (v: unknown): string => {
|
||||
const t = text(v)
|
||||
return /^[a-f0-9]{64}$/.test(t) ? t : bad()
|
||||
}
|
||||
const stamp = (v: unknown): string => {
|
||||
const t = text(v)
|
||||
return Number.isFinite(Date.parse(t)) ? t : bad()
|
||||
}
|
||||
function fields(v: unknown, complete = false): QualityFields {
|
||||
const r = obj(v)
|
||||
const f = {
|
||||
coverage: text(r.coverage),
|
||||
correctness: text(r.correctness),
|
||||
product_category: text(r.product_category),
|
||||
problem_type: text(r.problem_type),
|
||||
root_cause: text(r.root_cause),
|
||||
exclusion_reason: text(r.exclusion_reason),
|
||||
}
|
||||
if (
|
||||
!['', 'covered', 'uncovered', 'partial', 'pending', 'excluded'].includes(f.coverage) ||
|
||||
!['', 'correct', 'incorrect', 'pending'].includes(f.correctness) ||
|
||||
(complete && (!f.coverage || !f.correctness)) ||
|
||||
(f.correctness === 'correct' && f.root_cause !== '') ||
|
||||
(f.coverage === 'excluded' && !f.exclusion_reason.trim()) ||
|
||||
(f.coverage !== 'excluded' && f.exclusion_reason !== '')
|
||||
)
|
||||
return bad()
|
||||
return f
|
||||
}
|
||||
function check(value: unknown): QualityCheck {
|
||||
const v = obj(value),
|
||||
r = obj(v.result),
|
||||
s = obj(v.source)
|
||||
const state = text(r.state),
|
||||
rule_version = text(r.rule_version)
|
||||
if (
|
||||
!rule_version ||
|
||||
(state !== 'pending' && state !== 'checked') ||
|
||||
(state === 'checked' && (r.verdict !== 'uncovered' || r.matched_text !== '暂无已发布')) ||
|
||||
(state === 'pending' && r.verdict !== undefined)
|
||||
)
|
||||
return bad()
|
||||
return {
|
||||
input_available: typeof v.input_available === 'boolean' ? v.input_available : bad(),
|
||||
id: positive(v.id),
|
||||
input_epoch: positive(v.input_epoch),
|
||||
input_hash: hash(v.input_hash),
|
||||
result: {
|
||||
state,
|
||||
rule_version,
|
||||
...(r.verdict === undefined ? {} : { verdict: text(r.verdict), matched_text: text(r.matched_text) }),
|
||||
},
|
||||
source: {
|
||||
verdict: text(s.verdict),
|
||||
reason_code: text(s.reason_code),
|
||||
evaluator_version: text(s.evaluator_version),
|
||||
},
|
||||
created_at: stamp(v.created_at),
|
||||
}
|
||||
}
|
||||
function review(value: unknown): QualityReview {
|
||||
const v = obj(value),
|
||||
reason = text(v.reason),
|
||||
reviewer = text(v.reviewer)
|
||||
if (!reason.trim() || !reviewer) return bad()
|
||||
return {
|
||||
revision: positive(v.revision),
|
||||
input_epoch: positive(v.input_epoch),
|
||||
input_hash: hash(v.input_hash),
|
||||
fields: fields(v.fields, true),
|
||||
reason,
|
||||
reviewer,
|
||||
created_at: stamp(v.created_at),
|
||||
}
|
||||
}
|
||||
export function parseQAQuality(value: unknown): QAQuality {
|
||||
const v = obj(value),
|
||||
state = text(v.state)
|
||||
if (!['unreviewed', 'reviewed', 'stale'].includes(state)) return bad()
|
||||
const automatic = check(v.automatic),
|
||||
latest_review = v.latest_review === null ? null : review(v.latest_review),
|
||||
input_hash = hash(v.input_hash),
|
||||
input_epoch = positive(v.input_epoch),
|
||||
revision = num(v.revision),
|
||||
effective = fields(v.effective)
|
||||
if (
|
||||
automatic.input_hash !== input_hash ||
|
||||
automatic.input_epoch !== input_epoch ||
|
||||
(latest_review && latest_review.revision !== revision) ||
|
||||
(!latest_review && revision !== 0)
|
||||
)
|
||||
return bad()
|
||||
const actual = latest_review
|
||||
? latest_review.input_hash === input_hash && latest_review.input_epoch === input_epoch
|
||||
? 'reviewed'
|
||||
: 'stale'
|
||||
: 'unreviewed'
|
||||
if (state !== actual) return bad()
|
||||
const expected =
|
||||
state === 'reviewed' ? latest_review!.fields : { ...emptyQualityFields, coverage: automatic.result.verdict || '' }
|
||||
for (const key of Object.keys(expected) as (keyof QualityFields)[]) if (expected[key] !== effective[key]) return bad()
|
||||
return { input_hash, input_epoch, revision, state: state as QAQuality['state'], automatic, latest_review, effective }
|
||||
}
|
||||
function qualityRate(value: unknown): QualityRate {
|
||||
const v = obj(value),
|
||||
numerator = num(v.numerator),
|
||||
denominator = num(v.denominator)
|
||||
if (numerator > denominator) return bad()
|
||||
if (denominator === 0) {
|
||||
if (v.percent !== null) return bad()
|
||||
return { numerator, denominator, percent: null }
|
||||
}
|
||||
if (
|
||||
typeof v.percent !== 'number' ||
|
||||
!Number.isFinite(v.percent) ||
|
||||
v.percent < 0 ||
|
||||
v.percent > 100 ||
|
||||
Math.abs(v.percent - (100 * numerator) / denominator) > 1e-8
|
||||
)
|
||||
return bad()
|
||||
return { numerator, denominator, percent: v.percent }
|
||||
}
|
||||
function qualityRates(value: unknown, total: number, stale: number): QualityRates {
|
||||
const v = obj(value),
|
||||
r = obj(v.breakdown)
|
||||
const b = {
|
||||
covered: num(r.covered),
|
||||
uncovered: num(r.uncovered),
|
||||
partial: num(r.partial),
|
||||
pending: num(r.pending),
|
||||
unassessed: num(r.unassessed),
|
||||
excluded: num(r.excluded),
|
||||
stale: num(r.stale),
|
||||
covered_correct: num(r.covered_correct),
|
||||
covered_incorrect: num(r.covered_incorrect),
|
||||
covered_pending: num(r.covered_pending),
|
||||
covered_unassessed: num(r.covered_unassessed),
|
||||
}
|
||||
const coverage = qualityRate(v.coverage),
|
||||
correctness = qualityRate(v.correctness)
|
||||
if (
|
||||
v.policy_version !== 'quality-rates-human-first-v1' ||
|
||||
b.stale !== stale ||
|
||||
num(b.covered + b.uncovered + b.partial + b.pending + b.unassessed + b.excluded + b.stale) !== total ||
|
||||
num(b.covered_correct + b.covered_incorrect + b.covered_pending + b.covered_unassessed) !== b.covered ||
|
||||
coverage.numerator !== b.covered ||
|
||||
coverage.denominator !== b.covered + b.uncovered + b.partial ||
|
||||
correctness.numerator !== b.covered_correct ||
|
||||
correctness.denominator !== b.covered_correct + b.covered_incorrect
|
||||
)
|
||||
return bad()
|
||||
return { policy_version: 'quality-rates-human-first-v1', coverage, correctness, breakdown: b }
|
||||
}
|
||||
export function parseQualitySummary(value: unknown): QualitySummary {
|
||||
const v = obj(value),
|
||||
s = obj(v.summary),
|
||||
summary = {
|
||||
total: num(s.total),
|
||||
reviewed: num(s.reviewed),
|
||||
unreviewed: num(s.unreviewed),
|
||||
stale: num(s.stale),
|
||||
pending_confirmation: num(s.pending_confirmation),
|
||||
rule_uncovered: num(s.rule_uncovered),
|
||||
rates: qualityRates(s.rates, num(s.total), num(s.stale)),
|
||||
}
|
||||
const start = stamp(v.start),
|
||||
end = stamp(v.end)
|
||||
if (
|
||||
v.scope !== 'whole_filter' ||
|
||||
v.ai_state !== 'not_configured' ||
|
||||
summary.total !== summary.reviewed + summary.unreviewed + summary.stale ||
|
||||
summary.pending_confirmation > summary.reviewed ||
|
||||
summary.rule_uncovered > summary.total ||
|
||||
Date.parse(start) >= Date.parse(end)
|
||||
)
|
||||
return bad()
|
||||
return {
|
||||
summary,
|
||||
start,
|
||||
end,
|
||||
keyword: text(v.keyword),
|
||||
as_of: stamp(v.as_of),
|
||||
scope: 'whole_filter',
|
||||
ai_state: 'not_configured',
|
||||
}
|
||||
}
|
||||
export function parseQualityHistory(value: unknown): QualityHistory {
|
||||
const v = obj(value)
|
||||
if (!Array.isArray(v.reviews) || !Array.isArray(v.checks)) return bad()
|
||||
const reviews = v.reviews.map(review),
|
||||
checks = v.checks.map(check),
|
||||
next_review = num(v.next_review),
|
||||
next_check = num(v.next_check)
|
||||
if (
|
||||
reviews.length > 20 ||
|
||||
checks.length > 20 ||
|
||||
reviews.some((r, i) => i > 0 && r.revision >= reviews[i - 1].revision) ||
|
||||
checks.some((c, i) => i > 0 && c.id >= checks[i - 1].id) ||
|
||||
(next_review && next_review !== reviews.at(-1)?.revision) ||
|
||||
(next_check && next_check !== checks.at(-1)?.id)
|
||||
)
|
||||
return bad()
|
||||
return { reviews, checks, next_review, next_check }
|
||||
}
|
||||
export function parseQualitySnapshot(value: unknown): QualitySnapshot {
|
||||
const v = obj(value),
|
||||
p = obj(v.payload)
|
||||
return {
|
||||
input_epoch: positive(v.input_epoch),
|
||||
input_hash: hash(v.input_hash),
|
||||
created_at: stamp(v.created_at),
|
||||
payload: {
|
||||
id: text(p.id),
|
||||
question: text(p.question),
|
||||
answer: text(p.answer),
|
||||
status: text(p.status),
|
||||
references: p.references,
|
||||
media: p.media,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { currentQAWeek, qaDateTimeToISO, qaWeek, qaWeeksInYear, qaWeekQueryRange } from './qaWeeks'
|
||||
|
||||
describe('QA natural-week query ranges', () => {
|
||||
it('caps the in-progress week at now but leaves completed weeks intact', () => {
|
||||
const now = new Date('2026-10-18T06:00:00Z')
|
||||
expect(qaWeekQueryRange(2026, 42, now).end).toBe('2026-10-18T14:00')
|
||||
expect(qaWeekQueryRange(2026, 40, now).end).toBe('2026-10-05T00:00')
|
||||
expect(qaWeekQueryRange(2026, 53, now).start).toBe('2026-12-28T00:00')
|
||||
})
|
||||
it('resolves the current ISO week at the Beijing midnight boundary', () => {
|
||||
expect(currentQAWeek(new Date('2026-10-18T15:59:00Z'))).toMatchObject({ year: 2026, week: 42 })
|
||||
expect(currentQAWeek(new Date('2026-10-18T16:01:00Z'))).toMatchObject({ year: 2026, week: 43 })
|
||||
expect(currentQAWeek(new Date('2027-01-01T12:00:00Z'))).toMatchObject({ year: 2026, week: 53 })
|
||||
})
|
||||
it('converts Beijing form input to UTC without relying on the browser timezone', () => {
|
||||
expect(qaDateTimeToISO('2026-09-28T00:00')).toBe('2026-09-27T16:00:00.000Z')
|
||||
expect(qaDateTimeToISO('2026-10-05T00:00')).toBe('2026-10-04T16:00:00.000Z')
|
||||
for (const input of ['', '2026-02-30T00:00', '2026-10-04', '2026-10-04T24:00', 'invalid']) {
|
||||
expect(() => qaDateTimeToISO(input)).toThrow()
|
||||
}
|
||||
})
|
||||
it('counts only the valid weeks for each year', () => {
|
||||
expect(qaWeeksInYear(2026)).toBe(53)
|
||||
expect(qaWeeksInYear(2027)).toBe(52)
|
||||
expect(qaWeeksInYear(2020)).toBe(53)
|
||||
expect(qaWeeksInYear(2021)).toBe(52)
|
||||
})
|
||||
|
||||
it('shows week dates inclusively and queries through the exclusive next Monday', () => {
|
||||
expect(qaWeek(2026, 40)).toEqual({
|
||||
year: 2026,
|
||||
week: 40,
|
||||
start: '2026-09-28T00:00',
|
||||
end: '2026-10-05T00:00',
|
||||
label: '第40周(09-28 到 10-04)',
|
||||
})
|
||||
})
|
||||
it('rejects nonexistent weeks instead of spilling into the next year', () => {
|
||||
expect(() => qaWeek(2027, 53)).toThrow()
|
||||
for (const week of [0, -1, 54, 1.5, Number.NaN]) expect(() => qaWeek(2026, week)).toThrow()
|
||||
for (const year of [0, 2026.5, Number.NaN]) expect(() => qaWeek(year, 1)).toThrow()
|
||||
})
|
||||
it('keeps the ISO week-year and shows years on crossing ranges', () => {
|
||||
expect(qaWeek(2026, 1)).toMatchObject({
|
||||
start: '2025-12-29T00:00',
|
||||
end: '2026-01-05T00:00',
|
||||
label: '第1周(2025-12-29 到 2026-01-04)',
|
||||
})
|
||||
expect(qaWeek(2026, 53)).toMatchObject({
|
||||
start: '2026-12-28T00:00',
|
||||
end: '2027-01-04T00:00',
|
||||
label: '第53周(2026-12-28 到 2027-01-03)',
|
||||
})
|
||||
expect(qaWeek(2024, 9)).toMatchObject({ start: '2024-02-26T00:00', end: '2024-03-04T00:00' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,67 @@
|
||||
export interface QAWeek {
|
||||
year: number
|
||||
week: number
|
||||
start: string
|
||||
end: string
|
||||
label: string
|
||||
}
|
||||
|
||||
const day = 86_400_000
|
||||
const dateOnly = (value: number) => new Date(value).toISOString().slice(0, 10)
|
||||
|
||||
export function currentQAWeek(now = new Date()): QAWeek {
|
||||
const beijing = new Date(now.getTime() + 8 * 3_600_000)
|
||||
beijing.setUTCHours(0, 0, 0, 0)
|
||||
beijing.setUTCDate(beijing.getUTCDate() + 3 - ((beijing.getUTCDay() + 6) % 7))
|
||||
const year = beijing.getUTCFullYear()
|
||||
const week = Math.floor((beijing.getTime() - firstMonday(year)) / (7 * day)) + 1
|
||||
return qaWeek(year, week)
|
||||
}
|
||||
|
||||
export function qaDateTimeToISO(value: string): string {
|
||||
if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(value)) throw new Error('时间格式无效')
|
||||
const parsed = new Date(`${value}:00+08:00`)
|
||||
if (
|
||||
!Number.isFinite(parsed.getTime()) ||
|
||||
new Date(parsed.getTime() + 8 * 3_600_000).toISOString().slice(0, 16) !== value
|
||||
) {
|
||||
throw new Error('时间格式无效')
|
||||
}
|
||||
return parsed.toISOString()
|
||||
}
|
||||
|
||||
export function qaWeekQueryRange(year: number, week: number, now = new Date()): QAWeek {
|
||||
const range = qaWeek(year, week)
|
||||
if (
|
||||
Date.parse(qaDateTimeToISO(range.start)) < now.getTime() &&
|
||||
now.getTime() < Date.parse(qaDateTimeToISO(range.end))
|
||||
) {
|
||||
return { ...range, end: new Date(now.getTime() + 8 * 3_600_000).toISOString().slice(0, 16) }
|
||||
}
|
||||
return range
|
||||
}
|
||||
|
||||
const firstMonday = (year: number) => {
|
||||
const jan4 = new Date(Date.UTC(year, 0, 4))
|
||||
return jan4.getTime() - ((jan4.getUTCDay() + 6) % 7) * day
|
||||
}
|
||||
|
||||
export function qaWeeksInYear(year: number): number {
|
||||
if (!Number.isInteger(year) || year < 1900 || year > 9998) throw new Error('年份无效')
|
||||
return (firstMonday(year + 1) - firstMonday(year)) / (7 * day)
|
||||
}
|
||||
|
||||
export function qaWeek(year: number, week: number): QAWeek {
|
||||
if (!Number.isInteger(week) || week < 1 || week > qaWeeksInYear(year)) throw new Error('周次无效')
|
||||
const start = firstMonday(year) + (week - 1) * 7 * day
|
||||
const first = dateOnly(start)
|
||||
const last = dateOnly(start + 6 * day)
|
||||
const crossYear = first.slice(0, 4) !== String(year) || last.slice(0, 4) !== String(year)
|
||||
return {
|
||||
year,
|
||||
week,
|
||||
start: `${first}T00:00`,
|
||||
end: `${dateOnly(start + 7 * day)}T00:00`,
|
||||
label: `第${week}周(${crossYear ? first : first.slice(5)} 到 ${crossYear ? last : last.slice(5)})`,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user