Compare commits

...

5 Commits

Author SHA1 Message Date
姚章浩 dc9e827656 feat(library): 整库版本/作业持久化与状态读取契约,生产同步默认拒绝
build / build (push) Failing after 17s
- 新增 library_versions:测试封存、生产生效、生产预备份三类分开登记,
  生产生效版本唯一(旧版本必须先 supersede),测试快照不能顶替生产版本
- 新增 library_jobs + library_job_stages:业务作业身份、阶段、错误与恢复说明,
  分项计数用 NULL 表示"总量未知";互斥与幂等由数据库唯一索引保证
- 新增 GET /api/v1/library/overview、/jobs、/jobs/{id};POST /syncs 闸口未齐
  返回 503 缺项且不建作业
- 封存作业落库:先建业务作业再入队,worker 推进 export 阶段并登记 test_sealed
- 发布管理读真实状态:生产未知不再顶替、差异 unknown、启动同步按缺项禁用、
  同步明细/四类分项来自持久阶段;阶段勾选只认当前作业证据
- 准备信息标注封存时间与范围,不声称实时测试库已就绪
2026-10-28 13:58:51 +08:00
姚章浩 58d0483d44 feat(release): 按确认稿重做发布管理(两库页签 + 单作业区 + 版本抽屉)
build / build (push) Failing after 19s
- 顶部只有对内/对外两个知识库页签,切换只渲染选中库的一个作业区
- 同步前:生产当前→拟发布、新增/更新/删除与 Wiki 完整快照、准备清单、
  版本与快照/启动同步、本次变更 + 生产保护与恢复、五段作业阶段
- 同步中:作业阶段/版本/已用时 + 四类数据卡 + 同步明细与异常,未接入项
  只显示状态、不编百分比
- 版本与快照抽屉按 scope 列全部封存记录与分项摘要,恢复入口在真实演练前禁用
- 存储口径移到系统设置→存储管理只读区;保留/清理/自动清理标未接线
- 生产段无真实数据一律"未接入/尚无记录",启动同步禁用并说明
2026-10-28 13:23:55 +08:00
姚章浩 bb64c32654 feat(release): 发布管理整库视图 + R4/R5/R6/R7 修复
build / build (push) Failing after 16s
- R4:封存子进程 SIGTERM 宽限停、libraryctl 信号转 ctx;失败/超时后 agent 再做
  有界 recover,恢复失败即降级阻断封存并给出原因;启动先恢复、关闭等恢复完成
- R5:封存闸口以已存 payload 为准,同作业号换范围 409 且不入新队;重放回显真实状态
- R6:作业列表按类型查询(ListByType),不再先取全局再过滤
- R7:根目录 libraryagent 二进制移出版本库,保留运行产物并精确忽略
- UI:发布管理只保留对内/对外两目标,整合快照/完整性/作业/存储;链路未接线项禁用
  并标原因;整库版本独立导航并入;文档级旧流程折叠保留
2026-10-28 12:28:04 +08:00
姚章浩 910c0fcd76 feat(library): 页面发起封存的最小权限主机侧执行边界
build / build (push) Failing after 16s
- libraryagent:0700 目录内 0600 unix socket + SO_PEERCRED 同 uid,
  固定 binary/归档/日志/项目/写入者声明,请求只能选范围与作业号
- API:POST/GET /api/v1/library/captures(入队 library.capture + 读队列状态)
- worker:library.capture handler 走 socket;启动先 recover;不挂 Docker socket、
  不持有来源凭据
- web:整库版本页显示真实作业状态并可发起封存(未接线/无权限给出原因)
- scripts/library-agent-install.sh:构建、安装 systemd user 服务并读回权限
2026-10-28 12:11:08 +08:00
姚章浩 c5e033dd0e fix(library): 幂等重放、跨版本去重用量与契约复核
build / build (push) Failing after 15s
- 同作业号重跑读持久日志+已封存清单按首次请求重放(source_read=false,
  writers_stopped=false),换范围/绑定库或清单校验失败即拒绝
- 归档用量按跨版本去重统计内容字节,清单/未引用 blob/实际分配单列,
  不再用各版本 unique 之和冒充归档占用
- 冻结窗口内复核来源契约,不一致即中止;拒绝组外同镜像运行容器
- 补齐整库只读接口的 OpenAPI 契约
- 按用户确认取消 A06:文档/页面/接口不再把效果测试列为封版门槛
2026-10-28 12:01:09 +08:00
47 changed files with 5880 additions and 586 deletions
+1
View File
@@ -29,6 +29,7 @@
/release-diag
/worker
/libraryctl
/libraryagent
/apply_s5_patch.py
/tmp_*
.style-backup-*/
+78
View File
@@ -1,5 +1,83 @@
# Changelog
## 开发快照 snapshot/v0.1.114 - 2026-10-28
### Added
- 整库版本与持久作业:新增 `library_versions`(test_sealed / production_effective / production_prebackup 三类分开登记,生产生效版本唯一)、`library_jobs`(业务作业身份、阶段、错误与恢复说明)与 `library_job_stages`(分项计数,NULL 表示总量未知)。互斥与幂等由数据库唯一索引保证,不依赖前端禁用或单 worker。
- 读接口:`GET /api/v1/library/overview`(三类版本 + 差异 + 作业 + 启动缺项)、`GET /api/v1/library/jobs`、`GET /api/v1/library/jobs/{id}`。
- 写接口:`POST /api/v1/library/syncs`,闸口、生产恢复演练证据、生产权威版本、本次预备份缺一即 503 并逐条给出原因,且**不创建**作业。
- 封存作业落库:发起封存先建业务作业(同一目标只能一个在飞),worker 推进 export 阶段、成功登记 test_sealed 版本、失败同时记录阶段与作业状态。
- 发布管理改为读取真实状态:生产当前来自生产生效版本(没有就显示未知)、目标来自测试封存、差异未接线保持 unknown、启动同步按缺项禁用、同步明细与四类分项来自持久阶段。
### Fixed
- 没有当前作业时不再把历史测试封存当作「固定测试版本」已完成:阶段勾选只来自当前作业的阶段证据,并提示「已有测试封存(历史)/ 本次作业尚未开始」。
- 准备信息注明依据哪次封存快照与范围,明确「不代表实时测试库已就绪」,没有放宽任何完整性检查。
## 开发快照 snapshot/v0.1.113 - 2026-10-28
### Changed
- 发布管理按已确认稿重做:顶部只保留「对内知识库 / 对外知识库」两个页签,切换后只渲染选中库的一个作业区,不再并排两张巨型数据卡。
- 同步前布局回到原稿:生产当前 → 拟发布版本行、新增/更新/删除文档与 Wiki 完整快照、准备清单(文档解析与索引、Wiki、数据完整性)、右上「版本与快照 / 启动同步」、下方左「本次变更」右「生产保护与恢复」、底部五段作业阶段。
- 同步中布局:顶部作业阶段/版本/已用时,中间四类数据卡(数据库、原文件、索引、Wiki),底部「同步明细」与异常说明;没有真实总量与完成量的项目只显示状态,不编造百分比。
- 「版本与快照」改为右侧抽屉:按选中库列出全部已封存记录,区分测试封存与生产生效/备份,展开看到文档/索引/资源/Wiki 分项数量、字节与逐项摘要;恢复入口在有真实恢复演练前保持禁用并说明。
- 存储口径从发布主页移到「系统设置 → 存储管理」只读区(跨版本去重内容、blob 表观/分配、未引用、清单),保留策略/依赖保护/清理预览标未接线,自动清理保持关闭。
- 生产段(当前版本、变更差异、预备份、同步、生产验证)没有真实数据的一律显示「未接入 / 尚无记录」;「启动同步」保持禁用并写明原因,不把发起封存冒充启动同步。
### Removed
- 主页面上的研发口径文案(A04/A06、schema、SHA、内部表名等)移入必要的分项详情。
## 开发快照 snapshot/v0.1.112 - 2026-10-28
### Changed
- 发布管理改为一版可操作的整库视图:只给「对内 / 对外」两个目标,把整库版本页的封存信息、完整性结果、分项数量/字节/摘要、封存作业状态与归档存储口径并入同一页;链路按真实能力标注「封存已接通、生产预备份未接线、同步未授权、校验/恢复未接线」,禁用项写明原因,不用假进度。
- 「整库版本」独立导航并入发布管理(不再保留第三个相近入口);文档级旧流程折叠保留在页底,并明确单篇文档发布成功不等于整库发布成功。
### Fixed
- R4:封存子进程不再被默认 SIGKILL。超时/取消先发 SIGTERM 并给宽限期(`StopGrace`),`libraryctl` 把 SIGTERM 转成上下文取消,让停机窗口走恢复路径;任何失败的封存/恢复操作之后 agent 都会再执行一次有界的 `recover`,恢复失败则进入降级状态、阻断后续封存并给出原因(`recover`/`status` 仍可用);agent 启动时先恢复上次遗留的停机窗口,关闭时等待在飞操作完成其恢复责任。
- R5:同一作业号换范围不再被回显成新范围。接口以已存 payload 为准,范围不一致返回 409(`library_capture_scope_conflict`)且不入新队;相同请求重放返回真实 `reused`/存储范围。
- R6:封存作业列表改为按类型查询(`ListByType`),不再先取全局 200 条再过滤;存储不支持按类型查询时明确返回不可用,页面不据此判断空闲。
### Added
- `ListByType` 作用域查询与测试;封存闸口单测(未接线 503、非法 400、范围冲突 409、重放回显)。
- 发布管理新增 6 条渲染测试(两个目标、真实数量、链路禁用原因、权限/未接线分支、作业态、存储口径)。
## 开发快照 snapshot/v0.1.111 - 2026-10-28
### Added
- 主机侧封存 agent(`libraryagent` + systemd user 服务):只监听一个 0700 目录里的 0600 unix socket,校验 `SO_PEERCRED` 同 uid,固定 binary/归档/日志/项目/写入者声明,请求只能选范围与作业号。
- 页面「发起封存」:`POST /api/v1/library/captures` 只入队 `library.capture` 作业,`GET /api/v1/library/captures` 读队列真实状态;未接线时 503 并给出原因,权限不足 403。
- worker `library.capture` 处理器:通过挂载的 socket 调 agent,启动时先做一次 `recover`;容器内**不挂** Docker socket、**不持有**来源凭据。
- `scripts/library-agent-install.sh`:构建、安装、启用 linger 并读回 socket 权限与服务状态。
### Changed
- 整库版本页显示封存作业的真实状态(待执行/执行中/重试/完成/失败与最后错误),完成后自动刷新快照列表。
## 开发快照 snapshot/v0.1.110 - 2026-10-28
### Fixed
- 同一作业号重跑不再必然冲突:命令先读持久日志与已封存清单,按首次请求(时间、范围、契约、绑定库)幂等重放,`source_read=false`、`writers_stopped=false`;同一作业号换了范围或绑定库仍明确拒绝,已封存清单校验失败也拒绝。
- 归档用量改按跨版本去重统计内容字节,并把清单、未被引用 blob、文件实际分配单独列出;不再把"各版本 unique 之和"当归档占用,也不再暗示可回收空间(真实两份清单:各版之和 55,309,695 字节,跨版本去重 55,309,693 字节,磁盘分配 55,373,824 字节)。
### Added
- 冻结窗口内的契约复核:窗口内重新读取来源契约,与窗口前不一致即中止(不封存、恢复写入者)。
- 写入者组之外的同镜像容器检查:若有不属于声明组的运行中容器使用声明写入者的镜像,拒绝封存。
- 补齐 `GET /api/v1/library/snapshots`、`GET /api/v1/library/snapshots/{id}` 的 OpenAPI 契约(上一版遗漏,契约测试可检出)。
### Changed
- 按用户确认取消 A06:文档、页面与接口说明不再把内容/问答/引用图片效果/性能测试列为封版或发布门槛;A04 数据完整性口径保留。
## 开发快照 snapshot/v0.1.108 - 2026-10-28
### Added
+286
View File
@@ -812,6 +812,292 @@
}
}
},
"/api/v1/library/snapshots": {
"get": {
"tags": [
"Runtime"
],
"operationId": "listLibrarySnapshots",
"summary": "列出已封存的整库完整版本(只读;含分项数量/字节/摘要、跨版本去重内容字节与文件系统事实)",
"responses": {
"200": {
"$ref": "#/components/responses/Envelope"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"500": {
"$ref": "#/components/responses/InternalError"
}
}
}
},
"/api/v1/library/captures": {
"get": {
"tags": [
"Runtime"
],
"operationId": "listLibraryCaptures",
"summary": "列出最近的整库封存作业(读队列,不是归档;页面据此显示真实状态)",
"responses": {
"200": {
"$ref": "#/components/responses/Envelope"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"500": {
"$ref": "#/components/responses/InternalError"
}
}
},
"post": {
"tags": [
"Runtime"
],
"operationId": "enqueueLibraryCapture",
"summary": "投递一次整库封存作业(需要工程师及以上;执行在主机侧 agent,容器没有 Docker/来源凭据)",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"scope": {
"type": "string",
"enum": [
"internal",
"external"
]
},
"job": {
"type": "string"
}
},
"required": [
"scope"
]
}
}
}
},
"responses": {
"202": {
"description": "已入队封存作业(同一 scope+job 复用同一作业)"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"500": {
"$ref": "#/components/responses/InternalError"
},
"503": {
"description": "主机侧封存 agent 未接线"
}
}
}
},
"/api/v1/library/overview": {
"get": {
"tags": [
"Runtime"
],
"operationId": "getLibraryOverview",
"summary": "整库状态:测试封存 / 生产生效 / 生产预备份三类版本分开返回,差异未接线时为 unknown,并给出启动同步的缺项",
"parameters": [
{
"name": "scope",
"in": "query",
"required": false,
"schema": {
"type": "string",
"enum": [
"internal",
"external"
]
}
}
],
"responses": {
"200": {
"$ref": "#/components/responses/Envelope"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"500": {
"$ref": "#/components/responses/InternalError"
},
"503": {
"description": "整库版本登记存储不可用"
}
}
}
},
"/api/v1/library/jobs": {
"get": {
"tags": [
"Runtime"
],
"operationId": "listLibraryJobs",
"summary": "列出该目标最近的整库作业(测试封存与生产同步分开,含阶段与结果;重启后仍可读)",
"parameters": [
{
"name": "scope",
"in": "query",
"required": false,
"schema": {
"type": "string",
"enum": [
"internal",
"external"
]
}
}
],
"responses": {
"200": {
"$ref": "#/components/responses/Envelope"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"500": {
"$ref": "#/components/responses/InternalError"
}
}
}
},
"/api/v1/library/jobs/{id}": {
"get": {
"tags": [
"Runtime"
],
"operationId": "getLibraryJob",
"summary": "读取单个整库作业的阶段、计数、错误与恢复说明",
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"$ref": "#/components/responses/Envelope"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"404": {
"description": "作业不存在"
},
"500": {
"$ref": "#/components/responses/InternalError"
}
}
}
},
"/api/v1/library/syncs": {
"post": {
"tags": [
"Runtime"
],
"operationId": "startLibrarySync",
"summary": "启动生产同步:闸口、生产恢复演练证据、生产权威版本或本次预备份缺一即拒绝,且不创建作业",
"parameters": [
{
"name": "X-Governance-Action",
"in": "header",
"required": false,
"schema": {
"const": "library-sync"
}
}
],
"responses": {
"202": {
"description": "已创建同步作业(互斥与幂等由数据库唯一索引保证)"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"409": {
"description": "该目标已有在飞同步作业,或同一幂等键对应不同请求"
},
"500": {
"$ref": "#/components/responses/InternalError"
},
"503": {
"description": "闸口或证据未齐,返回具体缺项且不创建作业"
}
},
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"additionalProperties": false,
"required": [
"scope",
"target_snapshot_id"
],
"properties": {
"scope": {
"type": "string",
"enum": [
"internal",
"external"
]
},
"target_snapshot_id": {
"type": "string"
}
}
}
}
}
}
}
},
"/api/v1/library/snapshots/{id}": {
"get": {
"tags": [
"Runtime"
],
"operationId": "getLibrarySnapshot",
"summary": "读取单个已封存整库版本的分项与兼容契约(只读;不存在或校验失败返回 404)",
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"$ref": "#/components/responses/Envelope"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"404": {
"description": "快照不存在或归档校验失败"
},
"500": {
"$ref": "#/components/responses/InternalError"
}
}
}
},
"/api/v1/version-history": {
"get": {
"tags": [
+1
View File
@@ -202,6 +202,7 @@ func run(ctx context.Context, getenv func(string) string) error {
VersionHistory: versionHistoryStore,
VersionHistoryRepo: versionHistoryRepo,
LibraryArchiveRoot: config.LibraryArchiveRoot,
LibraryAgentSocket: config.LibraryAgentSocket,
BackupHost: backuphost.New(backuphost.Config{
SSHConfig: config.BackupHostSSHConfig,
Target: config.BackupHostTarget,
+70
View File
@@ -0,0 +1,70 @@
// Command libraryagent is the host-side execution boundary for whole-library
// capture. It runs as the ordinary operator account, owns no network listener
// other than one 0600 unix socket, and executes exactly one fixed command shape.
package main
import (
"context"
"flag"
"log"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"knowledge-governance/internal/libraryagent"
)
func main() {
home, _ := os.UserHomeDir()
var config libraryagent.Config
flag.StringVar(&config.Socket, "socket", filepath.Join(home, ".local/share/knowledge-governance/agent.sock"), "unix socket for capture requests")
flag.StringVar(&config.Binary, "binary", "/home/zheromiku/knowledge-governance/libraryctl", "libraryctl binary this agent executes")
flag.StringVar(&config.ArchiveRoot, "archive", filepath.Join(home, ".local/share/knowledge-governance/library"), "sealed artifact root")
flag.StringVar(&config.JournalRoot, "journal", filepath.Join(home, ".local/share/knowledge-governance/freeze"), "freeze journal root")
flag.StringVar(&config.SourceApp, "source-app", "WKNFull-app", "source container describing the stack")
flag.StringVar(&config.SourcePG, "source-pg", "WKNFull-postgres", "source PostgreSQL container")
flag.StringVar(&config.SourceES, "source-es", "WKNFull-elasticsearch", "source Elasticsearch container")
flag.StringVar(&config.GovernancePG, "governance-pg", "knowledge-governance-p1-postgres-1", "governance PostgreSQL container")
flag.StringVar(&config.Project, "project", "weknora071full", "Compose project owning the writers")
flag.StringVar(&config.Writers, "writers", "app", "declared writer services")
nonWriters := flag.String("non-writers", defaultNonWriters, "service=reason for every other project service")
flag.DurationVar(&config.MaxDuration, "max-duration", 10*time.Minute, "upper bound for one operation")
describe := flag.Bool("describe", false, "print the fixed configuration and exit")
flag.Parse()
config.NonWriters = *nonWriters
agent, err := libraryagent.New(config)
if err != nil {
log.Fatal(err)
}
if *describe {
log.Printf("library agent config: %+v", agent.Describe())
return
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
log.Printf("library agent listening on %s (project %s, writers %s)", config.Socket, config.Project, config.Writers)
if err = agent.Serve(ctx); err != nil {
log.Fatal(err)
}
}
// defaultNonWriters mirrors scripts/library-capture.sh: every sibling service of
// the source project is declared, with the reason it cannot write knowledge.
const defaultNonWriters = "frontend=UI only; no knowledge writes" +
",mcp=read-only MCP server" +
",dobotai-target=alpine placeholder; no knowledge writes" +
",docreader=parse RPC service; app persists parse output and settlement requires zero pending ops" +
",elasticsearch=search store; not an initiator" +
",postgres=database store; not an initiator" +
",redis=queue/cache store; not an initiator" +
",neo4j=graph store; not an initiator" +
",langfuse-web=LLM observability UI" +
",langfuse-worker=LLM observability worker; own storage" +
",langfuse-clickhouse=observability store" +
",langfuse-minio=observability object store" +
",langfuse-db-init=one-shot init; exited" +
",searxng=read-only search proxy" +
",searxng-init=one-shot init; exited"
+170 -29
View File
@@ -23,9 +23,11 @@ import (
"fmt"
"os"
"os/exec"
"os/signal"
"path/filepath"
"sort"
"strings"
"syscall"
"time"
"github.com/jackc/pgx/v5/pgxpool"
@@ -67,7 +69,12 @@ func main() {
os.Exit(2)
}
_ = rest
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
// SIGTERM must not kill this process mid-window: the capture path restores the
// source writers through a cancelled-context recovery, so the signal is turned
// into a context cancellation and the process exits only after that cleanup.
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
ctx, cancel := context.WithTimeout(ctx, 30*time.Minute)
defer cancel()
var runErr error
switch command {
@@ -224,11 +231,10 @@ type sourceConfig struct {
ObjectDetail string
}
func discoverSource(ctx context.Context, opts options) (sourceConfig, error) {
func discoverSource(ctx context.Context, opts options, binding map[string]string) (sourceConfig, error) {
var config sourceConfig
binding, err := readRoutingBindings(ctx, opts.governancePG)
if err != nil {
return config, err
if binding == nil {
return config, errors.New("routing bindings are required")
}
config.Scopes = binding
app, err := containerEnv(ctx, opts.sourceApp)
@@ -385,7 +391,14 @@ func openArchive(opts options) (*librarysnapshot.Archive, error) {
func runStatus(ctx context.Context, opts options) error {
report := map[string]any{}
config, err := discoverSource(ctx, opts)
binding, bindingErr := readRoutingBindings(ctx, opts.governancePG)
var config sourceConfig
var err error
if bindingErr != nil {
err = bindingErr
} else {
config, err = discoverSource(ctx, opts, binding)
}
if err != nil {
report["source_discovery"] = err.Error()
} else {
@@ -471,7 +484,11 @@ func runPreflight(ctx context.Context, opts options) error {
if opts.scope != "internal" && opts.scope != "external" {
return errors.New("-scope must be internal or external")
}
config, err := discoverSource(ctx, opts)
binding, err := readRoutingBindings(ctx, opts.governancePG)
if err != nil {
return err
}
config, err := discoverSource(ctx, opts, binding)
if err != nil {
return err
}
@@ -547,7 +564,41 @@ func runCapture(ctx context.Context, opts options) error {
if job == "" {
job = "lib-" + opts.scope + "-" + time.Now().UTC().Format("20060102T150405")
}
config, err := discoverSource(ctx, opts)
archive, err := openArchive(opts)
if err != nil {
return err
}
defer archive.Close()
coordinator, control, err := openFreeze(ctx, opts)
if err != nil {
return err
}
defer coordinator.Close()
defer control.Close()
if err = coordinator.Recover(ctx); err != nil {
return fmt.Errorf("pending freeze requires recovery: %w", err)
}
// Replay is answered from the persisted journal + sealed archive: the same job
// re-used with the same scope/binding returns the original candidate without
// reading the source or stopping a writer, and a job re-used with different
// parameters is refused instead of silently sealing under a stale identity.
existing, found, err := coordinator.Inspect(job)
if err != nil {
return err
}
binding, err := readRoutingBindings(ctx, opts.governancePG)
if err != nil {
return err
}
scopedKB := binding[opts.scope]
if found {
manifest, err := replayCapture(job, opts.scope, scopedKB, existing, archive)
if err != nil {
return err
}
return printCapture(job, existing.SnapshotID, manifest, true)
}
config, err := discoverSource(ctx, opts, binding)
if err != nil {
return err
}
@@ -573,23 +624,24 @@ func runCapture(ctx context.Context, opts options) error {
if err != nil {
return err
}
archive, err := openArchive(opts)
if err != nil {
return err
// The contract above is read before the maintenance window. Re-read it inside
// the stopped window and refuse if a model/index change happened in between:
// sealing a candidate whose contract no longer matches the source would hide
// exactly the change a later production sync cannot reproduce.
verifyContract := func(ctx context.Context) error {
live, err := compatibilityContract(ctx, pool, search, config.SearchIndex, tenant, kb)
if err != nil {
return err
}
if live != contract {
return errors.New("source contract changed between preflight and the frozen window; capture aborted")
}
return nil
}
defer archive.Close()
coordinator, control, err := openFreeze(ctx, opts)
if err != nil {
return err
}
defer coordinator.Close()
defer control.Close()
if err = coordinator.Recover(ctx); err != nil {
return fmt.Errorf("pending freeze requires recovery: %w", err)
}
// sourceReady proves the *group* is complete and consistent. Recorded work
// settlement is enforced separately by CaptureLibrary; neither check can see
// unrecorded or remote work.
// sourceReady proves the declared writer group is complete and no other
// running container uses a declared writer image. Recorded work settlement is
// enforced separately by CaptureLibrary; neither check can see unrecorded or
// remote work, so this is not a cross-system consistency proof.
sourceReady := func(ctx context.Context) error {
items, err := control.Inventory(ctx)
if err != nil {
@@ -598,12 +650,21 @@ func runCapture(ctx context.Context, opts options) error {
if len(items) == 0 {
return errors.New("writer group is empty")
}
return nil
declared := make(map[string]bool, len(items))
for _, item := range items {
declared[item.ID] = true
}
images, err := writerImageIDs(ctx, items)
if err != nil {
return err
}
return checkNoUndeclaredWriter(ctx, images, declared)
}
result, err := v071.CaptureLibrary(ctx, coordinator, archive, pool, search, objects, sourceReady,
v071.LibraryCaptureRequest{JobID: job, Scope: opts.scope,
Identity: v071.PostgresIdentity{TenantID: tenant, KnowledgeBaseID: kb},
Compatibility: contract, CreatedAt: time.Now().UTC(), MaxDocuments: opts.maxDocuments})
Compatibility: contract, CreatedAt: time.Now().UTC(), MaxDocuments: opts.maxDocuments,
VerifyContract: verifyContract})
if err != nil {
printJSON(map[string]any{"job": job, "state": result.State, "snapshot_id": result.SnapshotID, "error": err.Error()})
return err
@@ -612,6 +673,32 @@ func runCapture(ctx context.Context, opts options) error {
if err != nil {
return err
}
return printCapture(job, result.SnapshotID, manifest, false)
}
// replayCapture answers a repeated job from persisted state. It never reads the
// source and never stops a writer; conflicting parameters are refused.
func replayCapture(job, scope, expectedKB string, result libraryfreeze.Result, archive *librarysnapshot.Archive) (librarysnapshot.Manifest, error) {
if result.State != "succeeded" || result.SnapshotID == "" {
return librarysnapshot.Manifest{}, fmt.Errorf("job %q already exists with state %q: recover it or use a new job id", job, result.State)
}
manifest, err := archive.Load(result.SnapshotID)
if err != nil {
return librarysnapshot.Manifest{}, errors.New("captured library archive no longer verifies")
}
if manifest.ValidationPolicy != librarysnapshot.ArtifactAcceptancePolicy {
return librarysnapshot.Manifest{}, errors.New("existing job was sealed under a different validation policy")
}
if manifest.Scope != scope {
return librarysnapshot.Manifest{}, fmt.Errorf("job %q was captured for scope %q, not %q", job, manifest.Scope, scope)
}
if manifest.KnowledgeBaseID != expectedKB {
return librarysnapshot.Manifest{}, fmt.Errorf("job %q was captured for knowledge base %q, which is no longer the %q binding", job, manifest.KnowledgeBaseID, scope)
}
return manifest, nil
}
func printCapture(job, snapshotID string, manifest librarysnapshot.Manifest, replay bool) error {
parts := make([]map[string]any, 0, len(manifest.Parts))
var total int64
for _, part := range manifest.Parts {
@@ -621,13 +708,58 @@ func runCapture(ctx context.Context, opts options) error {
sort.Slice(parts, func(i, j int) bool {
return fmt.Sprint(parts[i]["kind"])+fmt.Sprint(parts[i]["name"]) < fmt.Sprint(parts[j]["kind"])+fmt.Sprint(parts[j]["name"])
})
printJSON(map[string]any{"job": job, "state": result.State, "snapshot_id": result.SnapshotID,
printJSON(map[string]any{"job": job, "state": "succeeded", "snapshot_id": snapshotID,
"scope": manifest.Scope, "knowledge_base_id": manifest.KnowledgeBaseID, "tenant_id": manifest.TenantID,
"compatibility": manifest.Compatibility, "parts": parts, "logical_bytes": total,
"validation_policy": manifest.ValidationPolicy, "writers_restored": true})
"validation_policy": manifest.ValidationPolicy, "writers_restored": true,
"replay": replay, "source_read": !replay, "writers_stopped": !replay})
return nil
}
func writerImageIDs(ctx context.Context, items []libraryfreeze.Service) ([]string, error) {
images := make([]string, 0, len(items))
seen := map[string]bool{}
for _, item := range items {
image, err := containerImageOf(ctx, item.ID)
if err != nil {
return nil, err
}
if !seen[image] {
seen[image] = true
images = append(images, image)
}
}
return images, nil
}
// checkNoUndeclaredWriter refuses to run when a running container uses a declared
// writer image but is not part of the declared group: such a container could keep
// writing during the maintenance window.
func checkNoUndeclaredWriter(ctx context.Context, images []string, declared map[string]bool) error {
for _, image := range images {
out, err := dockerOutput(ctx, "ps", "-q", "--filter", "ancestor="+image)
if err != nil {
return err
}
for _, id := range strings.Fields(out) {
if !declared[id] {
return fmt.Errorf("container %s uses a declared writer image but is not in the declared writer group", id[:12])
}
}
}
return nil
}
func containerImageOf(ctx context.Context, id string) (string, error) {
image, err := dockerOutput(ctx, "inspect", "--format", "{{.Image}}", id)
if err != nil {
return "", err
}
if image == "" {
return "", errors.New("declared writer has no image identity")
}
return image, nil
}
func runList(opts options) error {
archive, err := openArchive(opts)
if err != nil {
@@ -638,6 +770,10 @@ func runList(opts options) error {
if err != nil {
return err
}
total, err := archive.ContentUsage()
if err != nil {
return err
}
items := make([]map[string]any, 0, len(usage))
for _, item := range usage {
manifest, err := archive.Load(item.VersionID)
@@ -649,7 +785,12 @@ func runList(opts options) error {
"logical_bytes": item.LogicalBytes, "unique_bytes": item.UniqueBytes, "shared_bytes": item.SharedBytes,
"parts": len(manifest.Parts), "policy": manifest.ValidationPolicy})
}
printJSON(map[string]any{"archive": opts.archiveRoot, "snapshots": items})
printJSON(map[string]any{"archive": opts.archiveRoot, "snapshots": items,
// 跨版本去重后的内容字节;文件系统事实单列,任何一项都不是可回收空间。
"versions": total.Versions, "content_bytes": total.ContentBytes,
"blob_file_bytes": total.BlobFileBytes, "blob_allocated_bytes": total.BlobAllocatedBytes,
"unreferenced_blobs": total.UnreferencedBlobs, "unreferenced_bytes": total.UnreferencedBytes,
"manifest_file_bytes": total.ManifestFileBytes, "manifest_allocated_bytes": total.ManifestAllocatedBytes})
return nil
}
+126
View File
@@ -0,0 +1,126 @@
package main
import (
"bytes"
"fmt"
"os"
"strings"
"testing"
"time"
"knowledge-governance/internal/libraryfreeze"
"knowledge-governance/internal/librarysnapshot"
)
// sealedFixture writes one complete sealed candidate and returns its ID.
func sealedFixture(t *testing.T, archive *librarysnapshot.Archive, scope, knowledgeBaseID string, createdAt time.Time) string {
t.Helper()
rows := func(count int) string {
if count == 0 {
return "[]"
}
items := make([]string, count)
for i := range items {
items[i] = fmt.Sprintf(`{"id":"00000000-0000-4000-8000-%012d"}`, i)
}
return "[" + strings.Join(items, ",") + "]"
}
parts := []struct {
kind, name string
count int64
}{
{"database", "knowledges", 4},
{"database", "chunks", 38},
{"database", "resources", 0},
{"database", "resource_bindings", 0},
{"database", "knowledge_tags", 0},
{"database", "knowledge_tag_relations", 0},
{"index", "chunks", 122},
{"wiki", "wiki_pages", 31},
{"wiki", "wiki_folders", 21},
{"wiki", "wiki_page_issues", 0},
{"wiki", "wiki_log_entries", 11},
}
manifest := librarysnapshot.Manifest{ValidationPolicy: librarysnapshot.ArtifactAcceptancePolicy,
Format: librarysnapshot.Format, Scope: scope, TenantID: 10000, KnowledgeBaseID: knowledgeBaseID,
CreatedAt: createdAt, Compatibility: librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1",
SchemaVersion: 74, RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "text-embedding-v4",
EmbeddingDimension: 1024, IndexMappingSHA256: strings.Repeat("b", 64)}}
for _, part := range parts {
stored, err := archive.Put(bytes.NewReader([]byte(rows(int(part.count)))))
if err != nil {
t.Fatal(err)
}
stored.Kind, stored.Name, stored.Count = part.kind, part.name, part.count
manifest.Parts = append(manifest.Parts, stored)
}
id, err := archive.Seal(manifest)
if err != nil {
t.Fatal(err)
}
return id
}
func fixtureArchive(t *testing.T) (*librarysnapshot.Archive, string) {
t.Helper()
root, err := os.MkdirTemp(os.TempDir(), "kglc-")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.RemoveAll(root) })
if err = os.Chmod(root, 0700); err != nil {
t.Fatal(err)
}
archive, err := librarysnapshot.Open(root, 1024*1024)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { archive.Close() })
return archive, root
}
const fixtureKB = "0c84a098-d3ed-4b82-a165-e6de9691d6a8"
// A repeated job with the same parameters must return the original candidate
// without touching the source or stopping a writer (this function has no access
// to either), instead of failing with a conflicting-request error.
func TestReplayCaptureReturnsOriginalCandidate(t *testing.T) {
archive, _ := fixtureArchive(t)
created := time.Date(2026, 10, 28, 3, 34, 57, 0, time.UTC)
id := sealedFixture(t, archive, "internal", fixtureKB, created)
manifest, err := replayCapture("lib-internal-1", "internal", fixtureKB,
libraryfreeze.Result{State: "succeeded", SnapshotID: id}, archive)
if err != nil {
t.Fatal(err)
}
if !manifest.CreatedAt.Equal(created) || manifest.Compatibility.EmbeddingModel != "text-embedding-v4" {
t.Fatalf("replay lost the original request identity: %+v", manifest)
}
}
func TestReplayCaptureRejectsChangedParameters(t *testing.T) {
archive, root := fixtureArchive(t)
id := sealedFixture(t, archive, "internal", fixtureKB, time.Date(2026, 10, 28, 3, 34, 57, 0, time.UTC))
// Different scope.
if _, err := replayCapture("lib-internal-1", "external", fixtureKB,
libraryfreeze.Result{State: "succeeded", SnapshotID: id}, archive); err == nil {
t.Fatal("scope conflict was accepted")
}
// Binding moved to another knowledge base.
if _, err := replayCapture("lib-internal-1", "internal", "aec3dfc9-4ad3-4a39-926b-5bfa5d6a9654",
libraryfreeze.Result{State: "succeeded", SnapshotID: id}, archive); err == nil {
t.Fatal("knowledge base binding change was accepted")
}
// A job that never succeeded must not be answered as success.
if _, err := replayCapture("lib-internal-1", "internal", fixtureKB,
libraryfreeze.Result{State: "failed"}, archive); err == nil {
t.Fatal("failed job replayed as success")
}
// A sealed candidate that no longer verifies must not be reported as replay.
if err := os.Remove(root + "/versions/" + id + ".json"); err == nil {
if _, err := replayCapture("lib-internal-1", "internal", fixtureKB,
libraryfreeze.Result{State: "succeeded", SnapshotID: id}, archive); err == nil {
t.Fatal("missing sealed candidate replayed as success")
}
}
}
+103
View File
@@ -3,18 +3,22 @@ package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/appconfig"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
"knowledge-governance/internal/libraryagent"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/platform/weknora"
"knowledge-governance/internal/versionhistory"
@@ -24,6 +28,12 @@ import (
"knowledge-governance/internal/workflows/testweknora"
)
// libraryCaptureJobType is shared with the API which enqueues it.
const libraryCaptureJobType = "library.capture"
// librarySyncJobType 是生产同步作业的队列类型;与封存严格分开,状态不共用。
const librarySyncJobType = "library.sync"
func main() {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
@@ -126,6 +136,99 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
return nil, fmt.Errorf("create artifact fetch handler: %w", err)
}
handlers["artifact.fetch"] = artifactHandler.Handle
if config.LibraryAgentSocket != "" {
// 整库封存:worker 只投递请求并记录结果,真正的停机/导出/恢复发生在主机侧
// agent(同 uid unix socket)。容器里既没有 Docker socket,也没有来源凭据。
agentConfig := libraryagent.ClientConfig{Socket: config.LibraryAgentSocket, Timeout: 15 * time.Minute}
handlers[libraryCaptureJobType] = func(ctx context.Context, job jobs.Job) error {
var payload struct {
Scope string `json:"scope"`
CaptureJob string `json:"capture_job"`
RequestedBy string `json:"requested_by"`
}
if err := json.Unmarshal(job.Payload, &payload); err != nil || (payload.Scope != "internal" && payload.Scope != "external") || payload.CaptureJob == "" {
return fmt.Errorf("invalid library capture payload")
}
// 持久作业:页面读的是这里写的阶段与结果,worker 重启后仍能如实展示。
libraryJobID := "libseal-" + payload.CaptureJob
startedAt := time.Now().UTC()
if advanceErr := store.AdvanceLibraryJob(ctx, libraryJobID, governance.LibraryJobRunning, "export", "", "", "", "", startedAt); advanceErr != nil {
log.Printf("library seal job %s cannot be advanced: %v", libraryJobID, advanceErr)
}
if stageErr := store.UpdateLibraryStage(ctx, libraryJobID, "export", "running", nil, nil, nil, nil,
"主机侧正在暂停写入者、导出并恢复", startedAt); stageErr != nil {
log.Printf("library seal job %s stage update failed: %v", libraryJobID, stageErr)
}
result, err := libraryagent.Capture(ctx, agentConfig, payload.Scope, payload.CaptureJob)
finishedAt := time.Now().UTC()
if err != nil {
// 导出失败时阶段与作业都要留痕;恢复责任在 agent,不会因为作业失败而假装来源已恢复。
_ = store.UpdateLibraryStage(ctx, libraryJobID, "export", "failed", nil, nil, nil, nil, err.Error(), finishedAt)
_ = store.AdvanceLibraryJob(ctx, libraryJobID, governance.LibraryJobFailed, "export", err.Error(),
"agent 已执行恢复检查;确认来源 healthy 后可重试同一作业号", "", "", finishedAt)
log.Printf("library capture failed scope=%s capture_job=%s: %v", payload.Scope, payload.CaptureJob, err)
return err
}
// 封存产物成版本记录:只登记"测试封存",绝不写成生产生效版本。
versionErr := store.RecordLibraryVersion(ctx, governance.LibraryVersion{
ID: "libver-" + payload.Scope + "-" + result.SnapshotID, Scope: payload.Scope,
Kind: governance.LibraryVersionTestSealed, SnapshotID: result.SnapshotID, SourceJobID: libraryJobID,
Evidence: map[string]any{"capture_job": payload.CaptureJob, "replay": result.Replay,
"requested_by": payload.RequestedBy, "agent_result": json.RawMessage(result.Payload)},
CreatedBy: payload.RequestedBy, CreatedAt: finishedAt,
})
if versionErr != nil {
log.Printf("library seal job %s cannot record version: %v", libraryJobID, versionErr)
}
_ = store.UpdateLibraryStage(ctx, libraryJobID, "export", "succeeded", nil, nil, nil, nil,
"已封存快照 "+result.SnapshotID, finishedAt)
_ = store.AdvanceLibraryJob(ctx, libraryJobID, governance.LibraryJobSucceeded, "export", "", "",
result.SnapshotID, "", finishedAt)
log.Printf("library capture completed scope=%s capture_job=%s snapshot=%s replay=%v requested_by=%s",
payload.Scope, payload.CaptureJob, result.SnapshotID, result.Replay, payload.RequestedBy)
return nil
}
// 生产同步:唯一入口在 API(闸口未齐不建作业)。这里仍实现执行器,
// 但默认 fail-closed:没有闸口证据就明确失败,绝不向生产写入半个字节。
handlers[librarySyncJobType] = func(ctx context.Context, job jobs.Job) error {
var payload struct {
LibraryJobID string `json:"library_job_id"`
Scope string `json:"scope"`
TargetSnapshotID string `json:"target_snapshot_id"`
}
if err := json.Unmarshal(job.Payload, &payload); err != nil || payload.LibraryJobID == "" {
return fmt.Errorf("invalid library sync payload")
}
now := time.Now().UTC()
reasons := make([]string, 0, 3)
if !config.ProductionReleaseRequestsEnabled {
reasons = append(reasons, "生产写入闸口关闭")
}
if !config.ProductionBackupRestoreVerified {
reasons = append(reasons, "没有已核验的生产恢复演练证据")
}
// 生产写入适配与预备份实现之前,执行链本身就是缺项:直接拒绝而不是空转。
reasons = append(reasons, "生产预备份与写入适配尚未实现")
message := "生产同步执行链未接通:" + strings.Join(reasons, ";")
_ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobRunning, "prebackup", "", "", "", "", now)
_ = store.UpdateLibraryStage(ctx, payload.LibraryJobID, "prebackup", "failed", nil, nil, nil, nil, message, now)
_ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobFailed, "prebackup", message,
"未对生产执行任何写入,无需恢复", "", "", now)
log.Printf("library sync refused job=%s scope=%s: %s", payload.LibraryJobID, payload.Scope, message)
return errors.New(message)
}
// A crash can leave the source writer stopped: recover before taking work,
// and keep the failure visible instead of pretending the worker is ready.
go func() {
recoveryCtx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
if _, err := libraryagent.Recover(recoveryCtx, agentConfig); err != nil {
log.Printf("library agent recovery check failed: %v", err)
return
}
log.Printf("library agent reachable; freeze journals recovered")
}()
}
if config.VersionHistoryGiteaBaseURL != "" {
// 「版本记录」同步:匿名只读远端仓库的提交/tag,写本库快照。未配置来源就不注册,
// 界面上的同步按钮也会显示"未接线",不会入队一个没人处理的作业。
+6
View File
@@ -52,6 +52,9 @@ services:
# 「整库版本」页:只读已封存的整库候选产物。归档根由 `libraryctl capture`
# 在主机上写入(私有 0700),这里只挂只读;留空 = 未接线(页面降级展示原因)。
LIBRARY_ARCHIVE_ROOT: "${LIBRARY_ARCHIVE_ROOT:-/var/lib/knowledge-governance/library}"
# 主机侧封存 agent 的 unix socket:api 只用它判断"能不能从页面发起",
# worker 用它投递作业。容器里没有 Docker socket,也没有来源凭据。
LIBRARY_AGENT_SOCKET: "${LIBRARY_AGENT_SOCKET:-/run/library-agent/agent.sock}"
# Mount this independent master-key file read-only using the deployment overlay.
QA_AI_MASTER_KEY_FILE: "${QA_AI_MASTER_KEY_FILE:-}"
QA_AI_DNS_OVER_TLS: "${QA_AI_DNS_OVER_TLS:-}"
@@ -141,6 +144,9 @@ services:
volumes:
- ./spool:/var/lib/governance/spool:ro
- ./spool/ingestion:/var/lib/governance/ingestion
# 整库封存 agent 的 socket 目录(由主机侧 systemd user 服务持有)。
# 容器只拿到"投递作业"这一条通道:Docker socket 与来源凭据都不在这里。
- /home/zheromiku/.local/share/knowledge-governance/agent:/run/library-agent
- "${PP_SCAN_HOST_DATA_ROOT:-/home/zheromiku/dobot-portal-sync/data}:${PP_SCAN_CONTAINER_DATA_ROOT:-/home/zheromiku/dobot-portal-sync/data}:ro"
- /home/zheromiku/dingtalk_kb_download:/sources/dingtalk:ro
# dws 凭据:与宿主共享同一份 state(refresh token 是轮换制,不能在两处各留一份)
+30 -7
View File
@@ -41,7 +41,28 @@
./scripts/library-capture.sh recover
```
产物默认写到 `~/.local/share/knowledge-governance/library`(0700),日志写到 `~/.local/share/knowledge-governance/freeze`(0700)。api 容器只以只读方式挂载前者,「整库版本」页据此展示;页面**没有**封存按钮,因为封存要维护窗口与来源凭据,只能在目标主机执行。
产物默认写到 `~/.local/share/knowledge-governance/library`(0700),日志写到 `~/.local/share/knowledge-governance/freeze`(0700)。api 容器只以只读方式挂载前者;发布管理的「版本与快照」抽屉与系统设置 → 存储管理据此展示。
同一个作业号重跑是**幂等重放**:直接返回已封存的同一份候选(`replay=true`、`source_read=false`、`writers_stopped=false`),不读来源、不停写入者;同一作业号换了 scope 或绑定库则明确拒绝。
## 从页面发起封存(主机侧 agent)
页面点「发起对内/对外封存」只是**投递一个作业**;执行发生在这台主机上的 agent:
- `scripts/library-agent-install.sh` 构建并安装 `libraryagent`(systemd **user** 服务),
监听 `~/.local/share/knowledge-governance/agent/agent.sock`,目录 0700、socket 0600,
并额外用 `SO_PEERCRED` 要求对端与 agent 同 uid。
- agent 自己固定 `libraryctl` 的路径、归档与日志根、Compose 项目与写入者声明;
请求只能选 `scope`(internal/external)和作业号,**不能**指定路径、项目、容器或命令。
- 只有 worker 通过挂载的 socket 目录投递作业(`LIBRARY_AGENT_SOCKET`)。容器里
**没有** Docker socket,**没有**来源凭据:停写入者、读来源、恢复都在主机进程里完成。
- worker 启动时会先调一次 `recover`,把上次崩溃留下的停机窗口收尾;
失败会记日志而不是假装就绪。
- 同一 `scope + 作业号` 重复投递时,agent 走幂等重放,不会第二次停源。
安全边界要说清:socket 目录对 worker 可写,因此被攻破的 worker 可以让 agent 执行
"封存 internal/external"这一类动作(这正是页面能力),但拿不到 Docker API、
拿不到来源凭据,也不能重定向到别的项目或路径。
## 2026-10-28 实测(本机测试栈)
@@ -57,13 +78,15 @@
## 它证明了什么 / 没有证明什么
已证明:这一份整库内容在**写入者停住**之后被完整导出,PostgreSQL 与 Elasticsearch 双向覆盖、生成问题、资源与摘要逐项核验通过,产物可寻址、可复读、可校验。
已证明(A04 数据完整性口径):这一份整库内容在**写入者停住**之后被完整导出,PostgreSQL 与 Elasticsearch 双向覆盖、生成问题、资源与摘要逐项核验通过,产物可寻址、可复读、可校验。这正是封版所需的完整性口径。
没有证明(不要把候选当版本):
用户已确认取消 A06:**不要求**内容、问答、引用/图片效果与性能测试及其报告,也不作为封版/生产发布门槛。因此这里不再把"没有做效果测试"列为缺口。
- **内容/问答/性能验收**没有做,也没有把结果绑定到快照;
- **跨 PG / ES / 资源的一致切点**只是在维护窗口里取得,没有独立的切点证据;
仍然不成立(不许把完整性通过说成这些):
- **跨 PG / ES / 资源的一致切点**只在维护窗口内取得;写入者组完整性有检查,但没有独立的切点证据,不能当成已验收的一致性证明;
- **Wiki 删除贡献的语义重算**没有做;Wiki 队列空不等于语义正确;
- 对外库当前是空的(0 文档 1 Wiki 页),这份快照只说明"它当时确实是空的";
- 生产备份/恢复、双闸授权、整库同步与失败续作都没有接线,本文不涉及;
- 上游父子分块漏正文索引的风险仍在:本次候选通过是因为库里现有数据已补齐,**以后再重解析**仍可能漏项,届时封存会因覆盖核验失败而阻断(这是设计如此)。
- 生产独立预备份、恢复演练、双闸授权、整库同步协调与失败续作都没有接线,本文不涉及;
- 从页面发起封存、持久作业互斥、启动恢复还没有接线(封存目前只能在目标主机执行命令);
- 上游父子分块漏正文索引的风险仍在:本次通过是因为库里现有数据已补齐,**以后再重解析**仍可能漏项,届时封存会因覆盖核验失败而阻断(这是设计如此)。
+8 -1
View File
@@ -71,7 +71,10 @@ type Config struct {
// 留空即与抓取 origin 相同。只用于拼展示链接,不参与任何请求。
// LibraryArchiveRoot 是整库封存产物的只读归档根(主机私有 0700 目录的只读挂载)。
// 留空即"未接线":页面只显示原因,不显示空表冒充没有快照。
LibraryArchiveRoot string
LibraryArchiveRoot string
// LibraryAgentSocket 是主机侧封存 agent 的 unix socket(只由 worker 连接)。
// 留空即"未接线":页面不显示可用的封存入口,接口返回原因而不是假装已排队。
LibraryAgentSocket string
VersionHistoryLinkOrigin string
VersionHistoryHTTPTimeout time.Duration
VersionHistoryMaxPages int
@@ -120,6 +123,7 @@ func Load(getenv func(string) string) (Config, error) {
VersionHistoryRepo: valueOrDefault(strings.TrimSpace(getenv("VERSION_HISTORY_REPO")), "Weknora/knowledge-governance"),
VersionHistoryAllowedOrigins: splitOrigins(getenv("VERSION_HISTORY_ALLOWED_ORIGINS")),
LibraryArchiveRoot: strings.TrimSpace(getenv("LIBRARY_ARCHIVE_ROOT")),
LibraryAgentSocket: strings.TrimSpace(getenv("LIBRARY_AGENT_SOCKET")),
VersionHistoryLinkOrigin: strings.TrimSpace(getenv("VERSION_HISTORY_LINK_ORIGIN")),
VersionHistoryHTTPTimeout: 15 * time.Second,
VersionHistoryMaxPages: valueOrDefaultInt(getenv("VERSION_HISTORY_MAX_PAGES"), 200),
@@ -233,6 +237,9 @@ func Load(getenv func(string) string) (Config, error) {
if config.LibraryArchiveRoot != "" && !filepath.IsAbs(config.LibraryArchiveRoot) {
return Config{}, errors.New("LIBRARY_ARCHIVE_ROOT 必须是绝对路径(归档根按只读目录挂载)")
}
if config.LibraryAgentSocket != "" && !filepath.IsAbs(config.LibraryAgentSocket) {
return Config{}, errors.New("LIBRARY_AGENT_SOCKET 必须是绝对路径(unix socket 由主机侧 agent 持有)")
}
if config.TestWeKnoraHTTPTimeout, err = durationOrDefault(getenv("TEST_WEKNORA_HTTP_TIMEOUT"), config.TestWeKnoraHTTPTimeout); err != nil {
return Config{}, fmt.Errorf("TEST_WEKNORA_HTTP_TIMEOUT: %w", err)
}
+117
View File
@@ -0,0 +1,117 @@
package governance
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"time"
)
// 整库版本与作业的领域类型:与队列(jobs)分开——队列负责租约与重试,
// 这里负责业务身份、阶段与结果,重启后仍能如实展示。
type LibraryVersionKind string
const (
// LibraryVersionTestSealed 是测试库封存产物:只证明一份完整测试版本被封存,
// 不代表生产生效,也不代表做过生产恢复演练。
LibraryVersionTestSealed LibraryVersionKind = "test_sealed"
// LibraryVersionProductionEffective 是生产当前权威版本:只有生产验证通过并
// 记录证据后才能写入,测试快照不能顶替它。
LibraryVersionProductionEffective LibraryVersionKind = "production_effective"
// LibraryVersionProductionPrebackup 是每次生产写入前的独立预备份。
LibraryVersionProductionPrebackup LibraryVersionKind = "production_prebackup"
)
type LibraryJobKind string
const (
LibraryJobSeal LibraryJobKind = "seal"
LibraryJobSync LibraryJobKind = "sync"
)
type LibraryJobState string
const (
LibraryJobPending LibraryJobState = "pending"
LibraryJobRunning LibraryJobState = "running"
LibraryJobSucceeded LibraryJobState = "succeeded"
LibraryJobFailed LibraryJobState = "failed"
LibraryJobCancelled LibraryJobState = "cancelled"
)
// ErrLibraryJobActive:同一目标同一类作业已有在飞作业(数据库级互斥)。
var ErrLibraryJobActive = errors.New("library job already active for this target")
// ErrLibraryJobIdempotencyConflict:同一幂等键对应了不同的请求体。
var ErrLibraryJobIdempotencyConflict = errors.New("library job idempotency key reused with a different request")
type LibraryStage struct {
Stage string `json:"stage"`
State string `json:"state"`
// Total/Completed/BytesTotal/BytesDone 为 nil 表示该维度没有可靠数据,
// 界面必须显示"未知",不得当 0 或据此算百分比。
Total *int64 `json:"total"`
Completed *int64 `json:"completed"`
BytesTotal *int64 `json:"bytes_total"`
BytesDone *int64 `json:"bytes_done"`
Detail string `json:"detail"`
UpdatedAt time.Time `json:"updated_at"`
}
type LibraryJob struct {
ID string `json:"id"`
Scope string `json:"scope"`
Kind LibraryJobKind `json:"kind"`
State LibraryJobState `json:"state"`
Stage string `json:"stage"`
IdempotencyKey string `json:"-"`
RequestDigest string `json:"request_digest"`
QueueJobID string `json:"queue_job_id"`
SnapshotID string `json:"snapshot_id"`
TargetSnapshotID string `json:"target_snapshot_id"`
Actor string `json:"actor"`
Error string `json:"error"`
Recovery string `json:"recovery"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
FinishedAt *time.Time `json:"finished_at"`
Stages []LibraryStage `json:"stages"`
}
type LibraryVersion struct {
ID string `json:"id"`
Scope string `json:"scope"`
Kind LibraryVersionKind `json:"kind"`
SnapshotID string `json:"snapshot_id"`
VersionLabel string `json:"version_label"`
SourceJobID string `json:"source_job_id"`
Evidence map[string]any `json:"evidence"`
CreatedBy string `json:"created_by"`
CreatedAt time.Time `json:"created_at"`
SupersededAt *time.Time `json:"superseded_at"`
}
// LibraryRequestDigest 绑定一次请求的确切含义:同键不同体必须被拒绝,而不是
// 复用旧作业。只覆盖会影响执行结果的字段;actor 不参与摘要。
func LibraryRequestDigest(scope string, kind LibraryJobKind, payload map[string]any) (string, error) {
canonical := map[string]any{"scope": scope, "kind": string(kind), "payload": payload}
raw, err := json.Marshal(canonical)
if err != nil {
return "", err
}
sum := sha256.Sum256(raw)
return hex.EncodeToString(sum[:]), nil
}
// SyncStages 是生产同步作业的固定阶段顺序:先备份并核验恢复条件,再写生产,
// 最后验证;失败时走恢复而不是把作业标成功。
func SyncStages() []string {
return []string{"prebackup", "database", "resources", "index", "wiki", "verify", "rollback"}
}
// SealStages 是封存作业的阶段:导出是原子操作,没有分项进度。
func SealStages() []string {
return []string{"export"}
}
+194
View File
@@ -0,0 +1,194 @@
package httpapi
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"regexp"
"strings"
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
)
// 页面发起封存:只投递一个作业,真正的停机/导出/恢复发生在主机侧 agent。
// 这里没有任何 Docker 访问,也没有来源凭据 —— 调用方只能选择范围与作业号。
const libraryCaptureJobType = "library.capture"
var libraryCaptureJobPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`)
type libraryCaptureRequest struct {
Scope string `json:"scope"`
Job string `json:"job"`
}
func libraryCaptureEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
if config.LibraryAgentSocket == "" {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{
"code": "library_capture_unwired",
"reason": "未接线:主机侧封存 agent 没有挂载,页面无法发起封存",
})
return
}
var request libraryCaptureRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&request); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid request body"})
return
}
if request.Scope != "internal" && request.Scope != "external" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "scope must be internal or external"})
return
}
// The job id is the idempotency key handed to the agent: repeating the same
// scope+job returns the already sealed version instead of sealing twice.
captureJob := strings.TrimSpace(request.Job)
if captureJob == "" {
captureJob = "lib-" + request.Scope + "-" + time.Now().UTC().Format("20060102T150405")
}
if !libraryCaptureJobPattern.MatchString(captureJob) {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid job id"})
return
}
requestedBy := ""
if identity, ok := sessionFrom(r.Context()); ok {
requestedBy = identity.Username
}
payload, err := json.Marshal(map[string]string{
"scope": request.Scope, "capture_job": captureJob, "requested_by": requestedBy,
})
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot build capture job"})
return
}
now := time.Now().UTC()
// 业务作业先建:互斥由 library_jobs 的唯一索引保证,这样不会出现"队列里排着两个封存"。
// 队列投递失败或请求冲突时把业务作业取消,不留下永远 pending 的占位。
libraryJobID := "libseal-" + captureJob
createdSealJob := false
if store, ok := libraryStore(config); ok {
digest, digestErr := governance.LibraryRequestDigest(request.Scope, governance.LibraryJobSeal,
map[string]any{"capture_job": captureJob})
if digestErr == nil {
sealJob, reusedSeal, sealErr := store.CreateLibraryJob(r.Context(), governance.LibraryJob{
ID: libraryJobID, Scope: request.Scope, Kind: governance.LibraryJobSeal,
IdempotencyKey: "library.seal:" + captureJob, RequestDigest: digest, Actor: requestedBy,
}, governance.SealStages(), now)
switch {
case errors.Is(sealErr, governance.ErrLibraryJobActive):
writeJSON(w, http.StatusConflict, map[string]any{
"code": "library_seal_active", "error": "该目标已有在飞的封存作业,等它结束再发起",
})
return
case errors.Is(sealErr, governance.ErrLibraryJobIdempotencyConflict):
writeJSON(w, http.StatusConflict, map[string]any{
"code": "library_seal_scope_conflict", "error": "同一作业号已按另一个范围封存",
})
return
case sealErr != nil:
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot create seal job"})
return
case !reusedSeal:
createdSealJob = true
default:
libraryJobID = sealJob.ID
}
}
}
requestedID := fmt.Sprintf("library-capture-%s-%d", request.Scope, now.UnixNano())
// The idempotency key is the capture job id: the same logical capture must map
// to one queue row. Binding the scope into the key would silently create a
// second job instead of reporting a conflicting request, so the conflict is
// detected by comparing the stored payload below.
job, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{
ID: requestedID,
Type: libraryCaptureJobType,
Payload: payload,
AvailableAt: now,
MaxAttempts: 2,
IdempotencyKey: "library.capture:" + captureJob,
}, now)
if err != nil || job == nil {
if store, ok := libraryStore(config); ok && createdSealJob {
_ = store.CancelLibraryJob(r.Context(), libraryJobID, "队列投递失败,未开始封存", now)
}
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot enqueue capture job"})
return
}
if store, ok := libraryStore(config); ok {
if attachErr := store.AttachLibraryQueueJob(r.Context(), libraryJobID, job.ID, now); attachErr != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot attach capture job"})
return
}
}
// Enqueue returns the existing row for a reused key. Answer from that row, not
// from the current request: a reused job id with another scope must be refused
// instead of being reported as a job for the new scope.
var stored struct {
Scope string `json:"scope"`
CaptureJob string `json:"capture_job"`
RequestedBy string `json:"requested_by"`
}
cancelSeal := func(reason string) {
if store, ok := libraryStore(config); ok && createdSealJob {
_ = store.CancelLibraryJob(r.Context(), libraryJobID, reason, now)
}
}
if err = json.Unmarshal(job.Payload, &stored); err != nil || stored.CaptureJob != captureJob {
cancelSeal("请求冲突,未开始封存")
writeJSON(w, http.StatusConflict, map[string]any{
"code": "library_capture_conflict", "error": "该作业号已被另一个封存请求占用",
"existing_scope": stored.Scope, "requested_scope": request.Scope,
})
return
}
if stored.Scope != request.Scope {
cancelSeal("同一作业号已按另一个范围投递")
writeJSON(w, http.StatusConflict, map[string]any{
"code": "library_capture_scope_conflict", "error": "同一作业号已按另一个范围投递",
"existing_scope": stored.Scope, "requested_scope": request.Scope,
})
return
}
writeJSON(w, http.StatusAccepted, map[string]any{
"job_id": job.ID, "capture_job": stored.CaptureJob, "scope": stored.Scope,
"state": job.State, "reused": job.ID != requestedID, "requested_by": stored.RequestedBy,
})
}
// libraryCaptureJobs lists recent capture jobs so the page can show real state
// instead of an optimistic spinner. It reads the queue, not the archive.
func libraryCaptureJobs(w http.ResponseWriter, r *http.Request, config Config) {
// Ask the store for this type only. Reading the global queue and filtering in
// the handler would hide capture jobs behind unrelated traffic and make the
// page claim "idle" while a capture is still queued.
byType, ok := config.Store.(interface {
ListByType(ctx context.Context, jobType string, limit int) ([]jobs.Job, error)
})
if !ok {
writeJSON(w, http.StatusOK, map[string]any{"available": false,
"reason": "任务存储不支持按类型查询,页面不会据此判断空闲", "jobs": []any{}})
return
}
queue, err := byType.ListByType(r.Context(), libraryCaptureJobType, 20)
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read capture jobs"})
return
}
views := make([]map[string]any, 0, len(queue))
for _, job := range queue {
var payload struct {
Scope string `json:"scope"`
CaptureJob string `json:"capture_job"`
RequestedBy string `json:"requested_by"`
}
_ = json.Unmarshal(job.Payload, &payload)
views = append(views, map[string]any{"job_id": job.ID, "capture_job": payload.CaptureJob,
"scope": payload.Scope, "state": job.State, "attempt": job.Attempt,
"last_error": job.LastError, "requested_by": payload.RequestedBy,
"created_at": job.CreatedAt, "updated_at": job.UpdatedAt})
}
writeJSON(w, http.StatusOK, map[string]any{"available": true, "jobs": views})
}
+159
View File
@@ -0,0 +1,159 @@
package httpapi
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"knowledge-governance/internal/jobs"
)
func captureRequest(body string) *http.Request {
request := httptest.NewRequest(http.MethodPost, "/api/v1/library/captures", strings.NewReader(body))
request.Header.Set("Content-Type", "application/json")
return request
}
// An unwired agent must refuse clearly instead of queueing a job nobody can run.
func TestLibraryCaptureRefusedWhenAgentUnwired(t *testing.T) {
store := &fakeJobStore{}
recorder := httptest.NewRecorder()
libraryCaptureEnqueue(recorder, captureRequest(`{"scope":"internal"}`), Config{Store: store})
if recorder.Code != http.StatusServiceUnavailable {
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
}
var body map[string]any
if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body["code"] != "library_capture_unwired" || body["reason"] == "" {
t.Fatalf("unexpected body %v", body)
}
if store.enqueued.Type != "" {
t.Fatal("unwired agent still enqueued a job")
}
}
func TestLibraryCaptureEnqueuesFixedJobShape(t *testing.T) {
store := &fakeJobStore{enqueueEchoRequestedID: true}
recorder := httptest.NewRecorder()
libraryCaptureEnqueue(recorder, captureRequest(`{"scope":"external","job":"lib-external-review"}`),
Config{Store: store, LibraryAgentSocket: "/run/library-agent/agent.sock"})
if recorder.Code != http.StatusAccepted {
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
}
enqueued := store.enqueued
if enqueued.Type != libraryCaptureJobType {
t.Fatalf("job type %q", enqueued.Type)
}
if enqueued.IdempotencyKey != "library.capture:lib-external-review" {
t.Fatalf("idempotency key %q", enqueued.IdempotencyKey)
}
var payload map[string]string
if err := json.Unmarshal(enqueued.Payload, &payload); err != nil {
t.Fatal(err)
}
if payload["scope"] != "external" || payload["capture_job"] != "lib-external-review" {
t.Fatalf("payload %v", payload)
}
var body map[string]any
if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body["capture_job"] != "lib-external-review" || body["scope"] != "external" {
t.Fatalf("response %v", body)
}
}
func TestLibraryCaptureRejectsInvalidRequest(t *testing.T) {
for _, body := range []string{
`{"scope":"production"}`,
`{"scope":"internal","job":"bad job; rm -rf /"}`,
`not json`,
} {
store := &fakeJobStore{}
recorder := httptest.NewRecorder()
libraryCaptureEnqueue(recorder, captureRequest(body), Config{Store: store, LibraryAgentSocket: "/tmp/agent.sock"})
if recorder.Code != http.StatusBadRequest {
t.Fatalf("body %q status=%d", body, recorder.Code)
}
if store.enqueued.Type != "" {
t.Fatalf("invalid request %q still enqueued", body)
}
}
}
func TestLibraryCaptureJobsAsksStoreForItsOwnType(t *testing.T) {
// The global queue is busy with unrelated traffic; the capture job must still
// be visible because the query is type-scoped, not filtered after the fact.
store := &fakeJobStore{
listResult: []jobs.Job{{ID: "busy", Type: "artifact.fetch", State: "running"}},
listByTypeResult: []jobs.Job{
{ID: "a", Type: libraryCaptureJobType, State: "completed",
Payload: json.RawMessage(`{"scope":"internal","capture_job":"lib-internal-1","requested_by":"yaozhanghao"}`),
CreatedAt: time.Date(2026, 10, 28, 3, 0, 0, 0, time.UTC)},
},
}
recorder := httptest.NewRecorder()
libraryCaptureJobs(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/library/captures", nil), Config{Store: store})
if recorder.Code != http.StatusOK {
t.Fatalf("status=%d", recorder.Code)
}
if store.listType != libraryCaptureJobType {
t.Fatalf("store queried with type %q", store.listType)
}
var body struct {
Available bool `json:"available"`
Jobs []map[string]any `json:"jobs"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if !body.Available || len(body.Jobs) != 1 || body.Jobs[0]["capture_job"] != "lib-internal-1" {
t.Fatalf("unexpected body %+v", body)
}
}
// Reusing a capture job id with another scope must be refused, and the response
// must report the scope that was actually stored.
func TestLibraryCaptureRejectsScopeConflictForReusedJob(t *testing.T) {
store := &fakeJobStore{enqueueResult: &jobs.Job{ID: "existing-job", Type: libraryCaptureJobType,
State: jobs.StateCompleted,
Payload: json.RawMessage(`{"scope":"internal","capture_job":"lib-shared","requested_by":"yaozhanghao"}`)}}
recorder := httptest.NewRecorder()
libraryCaptureEnqueue(recorder, captureRequest(`{"scope":"external","job":"lib-shared"}`),
Config{Store: store, LibraryAgentSocket: "/run/library-agent/agent.sock"})
if recorder.Code != http.StatusConflict {
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
}
var body map[string]any
if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body["code"] != "library_capture_scope_conflict" || body["existing_scope"] != "internal" || body["requested_scope"] != "external" {
t.Fatalf("unexpected conflict body %v", body)
}
}
// A reused job id with an identical request is answered from the stored row.
func TestLibraryCaptureReplayReportsStoredJob(t *testing.T) {
store := &fakeJobStore{enqueueResult: &jobs.Job{ID: "existing-job", Type: libraryCaptureJobType,
State: jobs.StateCompleted,
Payload: json.RawMessage(`{"scope":"internal","capture_job":"lib-shared","requested_by":"yaozhanghao"}`)}}
recorder := httptest.NewRecorder()
libraryCaptureEnqueue(recorder, captureRequest(`{"scope":"internal","job":"lib-shared"}`),
Config{Store: store, LibraryAgentSocket: "/run/library-agent/agent.sock"})
if recorder.Code != http.StatusAccepted {
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
}
var body map[string]any
if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body["scope"] != "internal" || body["capture_job"] != "lib-shared" || body["reused"] != true || body["job_id"] != "existing-job" {
t.Fatalf("unexpected replay body %v", body)
}
}
+337
View File
@@ -0,0 +1,337 @@
package httpapi
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"time"
"knowledge-governance/internal/governance"
)
// 整库版本/状态/差异读取契约 + 生产同步的 fail-closed 入口。
//
// 三类版本严格分开,不能互相顶替:
// - 测试封存(archive 里的 sealed 产物)——只证明测试库有一份完整版本;
// - 生产当前生效(library_versions.kind=production_effective)——必须有生产验证证据;
// - 生产预备份(kind=production_prebackup)——每次生产写入前的独立备份。
// 生产未建立权威版本时返回 unknown,不拿最新测试快照冒充。
type libraryVersionView struct {
ID string `json:"id"`
Kind string `json:"kind"`
SnapshotID string `json:"snapshot_id"`
VersionLabel string `json:"version_label"`
SourceJobID string `json:"source_job_id"`
Evidence map[string]any `json:"evidence"`
CreatedBy string `json:"created_by"`
CreatedAt time.Time `json:"created_at"`
SupersededAt *time.Time `json:"superseded_at,omitempty"`
}
type libraryKnownView struct {
State string `json:"state"` // known | unknown
Version *libraryVersionView `json:"version,omitempty"`
Reason string `json:"reason,omitempty"`
}
type libraryDiffView struct {
State string `json:"state"` // unknown | computed
Reason string `json:"reason,omitempty"`
Added []any `json:"added"`
Updated []any `json:"updated"`
Removed []any `json:"removed"`
}
type libraryGateView struct {
SyncAllowed bool `json:"sync_allowed"`
Reasons []string `json:"reasons"`
}
type libraryOverview struct {
Scope string `json:"scope"`
TestSealed *librarySnapshotView `json:"test_sealed,omitempty"`
TestSealedReason string `json:"test_sealed_reason,omitempty"`
Production libraryKnownView `json:"production"`
Prebackup libraryKnownView `json:"prebackup"`
Diff libraryDiffView `json:"diff"`
Job *governance.LibraryJob `json:"job,omitempty"`
Jobs []governance.LibraryJob `json:"jobs"`
Gate libraryGateView `json:"gate"`
CaptureAvailable bool `json:"capture_available"`
CaptureReason string `json:"capture_reason,omitempty"`
Now time.Time `json:"now"`
}
type libraryJobStore interface {
CreateLibraryJob(ctx context.Context, job governance.LibraryJob, stages []string, now time.Time) (governance.LibraryJob, bool, error)
LibraryJob(ctx context.Context, id string) (governance.LibraryJob, error)
ListLibraryJobs(ctx context.Context, scope string, limit int) ([]governance.LibraryJob, error)
RecordLibraryVersion(ctx context.Context, version governance.LibraryVersion) error
LibraryVersions(ctx context.Context, scope string, limit int) ([]governance.LibraryVersion, error)
UpdateLibraryStage(ctx context.Context, jobID, stage, state string, total, completed, bytesTotal, bytesDone *int64, detail string, now time.Time) error
AdvanceLibraryJob(ctx context.Context, jobID string, state governance.LibraryJobState, stage, message, recovery, snapshotID, targetSnapshotID string, now time.Time) error
AttachLibraryQueueJob(ctx context.Context, jobID, queueJobID string, now time.Time) error
CancelLibraryJob(ctx context.Context, jobID, reason string, now time.Time) error
}
func libraryStore(config Config) (libraryJobStore, bool) {
store, ok := config.Store.(libraryJobStore)
return store, ok
}
func scopeFromQuery(r *http.Request) (string, error) {
scope := strings.TrimSpace(r.URL.Query().Get("scope"))
if scope == "" {
scope = "internal"
}
if scope != "internal" && scope != "external" {
return "", errors.New("scope must be internal or external")
}
return scope, nil
}
func libraryVersionViewOf(item governance.LibraryVersion) libraryVersionView {
return libraryVersionView{ID: item.ID, Kind: string(item.Kind), SnapshotID: item.SnapshotID,
VersionLabel: item.VersionLabel, SourceJobID: item.SourceJobID, Evidence: item.Evidence,
CreatedBy: item.CreatedBy, CreatedAt: item.CreatedAt, SupersededAt: item.SupersededAt}
}
// librarySyncGate 只依据真实存在的证据判断能不能写生产:闸口、生产端点、
// 生产权威版本、目标快照的预备份。任何一项缺失都给出具体原因,不默认放行。
func librarySyncGate(config Config, production libraryKnownView, prebackup libraryKnownView, target string) libraryGateView {
gate := libraryGateView{SyncAllowed: false, Reasons: []string{}}
if !config.ProductionReleaseRequestsEnabled {
gate.Reasons = append(gate.Reasons, "生产写入闸口关闭(PRODUCTION_RELEASE_REQUESTS_ENABLED=false)")
}
if !config.ProductionBackupRestoreVerified {
gate.Reasons = append(gate.Reasons, "没有已核验的生产恢复演练证据(PRODUCTION_BACKUP_RESTORE_VERIFIED=false)")
}
if strings.TrimSpace(config.ProductionWeKnoraBaseURL) == "" {
gate.Reasons = append(gate.Reasons, "生产端点未配置,无法核验生产当前版本")
}
if production.State != "known" {
gate.Reasons = append(gate.Reasons, "生产当前权威版本未知,不能启动写入")
}
if target == "" {
gate.Reasons = append(gate.Reasons, "还没有可同步的测试封存版本")
}
if prebackup.State != "known" {
gate.Reasons = append(gate.Reasons, "本次目标快照还没有生产预备份")
}
gate.SyncAllowed = len(gate.Reasons) == 0
return gate
}
func libraryOverviewHandler(w http.ResponseWriter, r *http.Request, config Config) {
scope, err := scopeFromQuery(r)
if err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
return
}
store, ok := libraryStore(config)
if !ok {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false,
"reason": "版本登记存储不可用"})
return
}
now := time.Now().UTC()
overview := libraryOverview{Scope: scope, Jobs: []governance.LibraryJob{}, Now: now,
CaptureAvailable: strings.TrimSpace(config.LibraryAgentSocket) != "",
Gate: libraryGateView{Reasons: []string{}},
Diff: libraryDiffView{State: "unknown", Reason: "生产与测试的文档级差异读取未接线", Added: []any{}, Updated: []any{}, Removed: []any{}}}
if !overview.CaptureAvailable {
overview.CaptureReason = "主机侧封存 agent 未接线"
}
// 测试封存来自归档:它只是测试侧事实。
snapshots, snapErr := readLibrarySnapshots(config.LibraryArchiveRoot)
if snapErr != nil {
overview.TestSealedReason = "归档不可读"
} else if !snapshots.Available {
overview.TestSealedReason = snapshots.Reason
} else {
for index := range snapshots.Snapshots {
if snapshots.Snapshots[index].Scope == scope {
overview.TestSealed = &snapshots.Snapshots[index]
break
}
}
if overview.TestSealed == nil {
overview.TestSealedReason = "还没有该目标的测试封存"
}
}
// 生产生效 / 预备份 / 作业来自持久登记。
versions, err := store.LibraryVersions(r.Context(), scope, 50)
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read library versions"})
return
}
overview.Production = libraryKnownView{State: "unknown", Reason: "还没有生产验证通过的生效版本记录"}
overview.Prebackup = libraryKnownView{State: "unknown", Reason: "本次目标快照还没有生产预备份"}
target := ""
if overview.TestSealed != nil {
target = overview.TestSealed.SnapshotID
}
for index := range versions {
item := versions[index]
view := libraryVersionViewOf(item)
switch item.Kind {
case governance.LibraryVersionProductionEffective:
if item.SupersededAt == nil {
overview.Production = libraryKnownView{State: "known", Version: &view}
}
case governance.LibraryVersionProductionPrebackup:
// 只有与目标快照绑定的预备份才算"这次同步前的备份"。
if target != "" && item.SnapshotID == target {
overview.Prebackup = libraryKnownView{State: "known", Version: &view}
}
}
}
recent, err := store.ListLibraryJobs(r.Context(), scope, 20)
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read library jobs"})
return
}
overview.Jobs = recent
for index := range recent {
if recent[index].State == governance.LibraryJobPending || recent[index].State == governance.LibraryJobRunning {
overview.Job = &recent[index]
break
}
}
if overview.Job == nil && len(recent) > 0 {
overview.Job = &recent[0]
}
overview.Gate = librarySyncGate(config, overview.Production, overview.Prebackup, target)
writeJSON(w, http.StatusOK, overview)
}
func libraryJobsHandler(w http.ResponseWriter, r *http.Request, config Config) {
scope, err := scopeFromQuery(r)
if err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
return
}
store, ok := libraryStore(config)
if !ok {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false, "reason": "版本登记存储不可用", "jobs": []any{}})
return
}
items, err := store.ListLibraryJobs(r.Context(), scope, 20)
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read library jobs"})
return
}
writeJSON(w, http.StatusOK, map[string]any{"available": true, "jobs": items})
}
func libraryJobDetailHandler(w http.ResponseWriter, r *http.Request, config Config) {
store, ok := libraryStore(config)
if !ok {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false, "reason": "版本登记存储不可用"})
return
}
id := strings.TrimSpace(r.PathValue("id"))
if id == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "job id required"})
return
}
job, err := store.LibraryJob(r.Context(), id)
if err != nil {
writeJSON(w, http.StatusNotFound, map[string]any{"available": false, "reason": "作业不存在"})
return
}
writeJSON(w, http.StatusOK, map[string]any{"available": true, "job": job})
}
// librarySyncEnqueue 是生产同步的唯一入口:闸口未齐时**不建作业**,直接说明缺项。
// 这样按钮永远不会假接通,也不会留下一个永远失败的空作业。
func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
if r.Method != http.MethodPost {
writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"})
return
}
store, ok := libraryStore(config)
if !ok {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"code": "library_sync_unavailable", "reasons": []string{"版本登记存储不可用"}})
return
}
var request struct {
Scope string `json:"scope"`
Target string `json:"target_snapshot_id"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&request); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid request body"})
return
}
if request.Scope != "internal" && request.Scope != "external" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "scope must be internal or external"})
return
}
overview := libraryOverview{Scope: request.Scope}
versions, err := store.LibraryVersions(r.Context(), request.Scope, 50)
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read library versions"})
return
}
overview.Production = libraryKnownView{State: "unknown"}
overview.Prebackup = libraryKnownView{State: "unknown"}
for index := range versions {
item := versions[index]
if item.Kind == governance.LibraryVersionProductionEffective && item.SupersededAt == nil {
view := libraryVersionViewOf(item)
overview.Production = libraryKnownView{State: "known", Version: &view}
}
if item.Kind == governance.LibraryVersionProductionPrebackup && request.Target != "" && item.SnapshotID == request.Target {
view := libraryVersionViewOf(item)
overview.Prebackup = libraryKnownView{State: "known", Version: &view}
}
}
gate := librarySyncGate(config, overview.Production, overview.Prebackup, request.Target)
if !gate.SyncAllowed {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{
"code": "library_sync_blocked", "reasons": gate.Reasons,
"production": overview.Production, "prebackup": overview.Prebackup,
})
return
}
// 走到这里说明闸口与证据都齐了才真正建作业;互斥与幂等由数据库索引保证。
digest, err := governance.LibraryRequestDigest(request.Scope, governance.LibraryJobSync,
map[string]any{"target_snapshot_id": request.Target})
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot digest request"})
return
}
actor := ""
if identity, ok := sessionFrom(r.Context()); ok {
actor = identity.Username
}
now := time.Now().UTC()
jobID := fmt.Sprintf("libsync-%s-%d", request.Scope, now.UnixNano())
job, reused, err := store.CreateLibraryJob(r.Context(), governance.LibraryJob{
ID: jobID, Scope: request.Scope, Kind: governance.LibraryJobSync,
IdempotencyKey: "library.sync:" + request.Scope + ":" + request.Target, RequestDigest: digest,
TargetSnapshotID: request.Target, Actor: actor,
}, governance.SyncStages(), now)
if errors.Is(err, governance.ErrLibraryJobActive) {
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_sync_active", "error": "该目标已有在飞的同步作业"})
return
}
if errors.Is(err, governance.ErrLibraryJobIdempotencyConflict) {
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_sync_conflict", "error": "同一幂等键对应了不同的请求"})
return
}
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot create library sync job"})
return
}
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": reused})
}
+230
View File
@@ -0,0 +1,230 @@
package httpapi
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"knowledge-governance/internal/governance"
)
// 生产闸口与整库状态契约的针对性测试:不做数据库集成,只验证
// "证据不齐就不建作业" 与 "三类版本不互相顶替" 这两条硬规则。
// 复用既有 fakeJobStore 提供 Store 的其余方法,只覆盖整库作业这几个。
type fakeLibraryStore struct {
fakeJobStore
versions []governance.LibraryVersion
jobs []governance.LibraryJob
createN int
lastJob governance.LibraryJob
lastState governance.LibraryJobState
}
func (f *fakeLibraryStore) CreateLibraryJob(_ context.Context, job governance.LibraryJob, _ []string, _ time.Time) (governance.LibraryJob, bool, error) {
f.createN++
f.lastJob = job
return job, false, nil
}
func (f *fakeLibraryStore) LibraryJob(_ context.Context, id string) (governance.LibraryJob, error) {
return governance.LibraryJob{ID: id}, nil
}
func (f *fakeLibraryStore) ListLibraryJobs(_ context.Context, scope string, _ int) ([]governance.LibraryJob, error) {
result := make([]governance.LibraryJob, 0, len(f.jobs))
for _, job := range f.jobs {
if job.Scope == scope {
result = append(result, job)
}
}
return result, nil
}
func (f *fakeLibraryStore) RecordLibraryVersion(_ context.Context, version governance.LibraryVersion) error {
f.versions = append(f.versions, version)
return nil
}
func (f *fakeLibraryStore) LibraryVersions(_ context.Context, scope string, _ int) ([]governance.LibraryVersion, error) {
result := make([]governance.LibraryVersion, 0, len(f.versions))
for _, version := range f.versions {
if version.Scope == scope {
result = append(result, version)
}
}
return result, nil
}
func (f *fakeLibraryStore) UpdateLibraryStage(_ context.Context, _, _, _ string, _, _, _, _ *int64, _ string, _ time.Time) error {
return nil
}
func (f *fakeLibraryStore) AdvanceLibraryJob(_ context.Context, _ string, state governance.LibraryJobState, _, _, _, _, _ string, _ time.Time) error {
f.lastState = state
return nil
}
func (f *fakeLibraryStore) AttachLibraryQueueJob(_ context.Context, _, _ string, _ time.Time) error {
return nil
}
func (f *fakeLibraryStore) CancelLibraryJob(_ context.Context, _, _ string, _ time.Time) error {
f.lastState = governance.LibraryJobCancelled
return nil
}
func TestLibrarySyncGateRequiresEveryPieceOfEvidence(t *testing.T) {
known := libraryKnownView{State: "known", Version: &libraryVersionView{ID: "v1"}}
cases := []struct {
name string
config Config
production libraryKnownView
prebackup libraryKnownView
target string
allowed bool
reason string
}{
{
name: "default installation is closed",
config: Config{},
production: libraryKnownView{State: "unknown"},
prebackup: libraryKnownView{State: "unknown"},
target: "snap-1",
allowed: false,
reason: "生产写入闸口关闭",
},
{
name: "flags on but restore evidence missing",
config: Config{ProductionReleaseRequestsEnabled: true,
ProductionWeKnoraBaseURL: "http://prod.invalid"},
production: known,
prebackup: known,
target: "snap-1",
allowed: false,
reason: "没有已核验的生产恢复演练证据",
},
{
name: "everything present",
config: Config{ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
ProductionWeKnoraBaseURL: "http://prod.invalid"},
production: known,
prebackup: known,
target: "snap-1",
allowed: true,
},
}
for _, testCase := range cases {
t.Run(testCase.name, func(t *testing.T) {
gate := librarySyncGate(testCase.config, testCase.production, testCase.prebackup, testCase.target)
if gate.SyncAllowed != testCase.allowed {
t.Fatalf("sync_allowed = %v, want %v (%v)", gate.SyncAllowed, testCase.allowed, gate.Reasons)
}
if testCase.reason != "" {
joined := strings.Join(gate.Reasons, "|")
if !strings.Contains(joined, testCase.reason) {
t.Fatalf("reasons %v missing %q", gate.Reasons, testCase.reason)
}
}
})
}
}
// 闸口关闭时 POST /api/v1/library/syncs 必须直接拒绝,并且**不创建**作业:
// 不能留下一个永远失败的空作业,也不能让按钮看起来接通了。
func TestLibrarySyncEnqueueRefusesWithoutCreatingJob(t *testing.T) {
store := &fakeLibraryStore{}
config := Config{Store: store}
request := httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs",
strings.NewReader(`{"scope":"internal","target_snapshot_id":"snap-1"}`))
recorder := httptest.NewRecorder()
librarySyncEnqueue(recorder, request, config)
if recorder.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want 503", recorder.Code)
}
if store.createN != 0 {
t.Fatalf("created %d jobs while gate is closed", store.createN)
}
var body struct {
Code string `json:"code"`
Reasons []string `json:"reasons"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil {
t.Fatalf("decode body: %v", err)
}
if body.Code != "library_sync_blocked" || len(body.Reasons) == 0 {
t.Fatalf("unexpected refusal body: %s", recorder.Body.String())
}
}
// 即使闸口打开,缺少与目标快照绑定的预备份也必须拒绝。
func TestLibrarySyncEnqueueRequiresPrebackupForTarget(t *testing.T) {
store := &fakeLibraryStore{versions: []governance.LibraryVersion{{
ID: "ver-prod-1", Scope: "internal", Kind: governance.LibraryVersionProductionEffective,
SnapshotID: "prod-snap", VersionLabel: "prod-2026.10", CreatedAt: time.Now().UTC(),
}}}
config := Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
ProductionWeKnoraBaseURL: "http://prod.invalid"}
request := httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs",
strings.NewReader(`{"scope":"internal","target_snapshot_id":"snap-1"}`))
recorder := httptest.NewRecorder()
librarySyncEnqueue(recorder, request, config)
if recorder.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want 503", recorder.Code)
}
if !strings.Contains(recorder.Body.String(), "预备份") {
t.Fatalf("refusal must name the missing prebackup: %s", recorder.Body.String())
}
if store.createN != 0 {
t.Fatalf("created %d jobs without a prebackup", store.createN)
}
}
// 三类版本必须分开读:production_effective 才是生产当前,测试封存不能顶替。
func TestLibraryOverviewKeepsVersionKindsSeparate(t *testing.T) {
now := time.Now().UTC()
store := &fakeLibraryStore{versions: []governance.LibraryVersion{
{ID: "ver-test", Scope: "internal", Kind: governance.LibraryVersionTestSealed, SnapshotID: "snap-1", CreatedAt: now},
{ID: "ver-prod", Scope: "internal", Kind: governance.LibraryVersionProductionEffective,
SnapshotID: "prod-snap", VersionLabel: "prod-2026.10", CreatedAt: now},
{ID: "ver-backup-other", Scope: "internal", Kind: governance.LibraryVersionProductionPrebackup,
SnapshotID: "other-snap", CreatedAt: now},
}}
config := Config{Store: store, LibraryArchiveRoot: t.TempDir()}
request := httptest.NewRequest(http.MethodGet, "/api/v1/library/overview?scope=internal", nil)
recorder := httptest.NewRecorder()
libraryOverviewHandler(recorder, request, config)
if recorder.Code != http.StatusOK {
t.Fatalf("status = %d: %s", recorder.Code, recorder.Body.String())
}
var body struct {
Production libraryKnownView `json:"production"`
Prebackup libraryKnownView `json:"prebackup"`
Diff struct {
State string `json:"state"`
} `json:"diff"`
Gate struct {
SyncAllowed bool `json:"sync_allowed"`
} `json:"gate"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil {
t.Fatalf("decode overview: %v", err)
}
if body.Production.State != "known" || body.Production.Version == nil || body.Production.Version.ID != "ver-prod" {
t.Fatalf("production must be the effective version, got %+v", body.Production)
}
// 预备份只对匹配目标快照的那一份生效;这里目标为空(归档不可用),所以是未知。
if body.Prebackup.State != "unknown" {
t.Fatalf("prebackup must stay unknown without a matching target snapshot: %+v", body.Prebackup)
}
if body.Diff.State != "unknown" {
t.Fatalf("diff must be unknown until the comparison is wired, got %q", body.Diff.State)
}
if body.Gate.SyncAllowed {
t.Fatal("gate must stay closed")
}
}
+38 -7
View File
@@ -15,8 +15,8 @@ import (
// 边界(刻意不做的事):
// - 不触发封存、不停/起写入者:封存需要维护窗口与来源凭据,只能由运维命令
// scripts/library-capture.sh 在目标主机执行;
// - 不把候选当版本:候选只证明"这一份内容被完整、可核验地封存了",内容/问答/
// 性能验收与生产发布是另外的、需要独立授权的事;
// - 不把完整性当发布:候选证明"这一份内容被完整、可核验地封存了"(A04 口径),
// 而授权与生产同步是另外的、需要独立授权的步骤(A06 效果测试已由用户取消);
// - 归档根没接线时返回可用性=false 与原因,不返回空表冒充"没有快照"。
type librarySnapshotPart struct {
Kind string `json:"kind"`
@@ -47,15 +47,31 @@ type librarySnapshotList struct {
Reason string `json:"reason,omitempty"`
ArchiveRoot string `json:"archive_root,omitempty"`
Snapshots []librarySnapshotView `json:"snapshots"`
StoredBytes int64 `json:"stored_bytes"`
// 页面必须能说清"封存由谁执行",不能让人以为页面上有个没实现的按钮。
CaptureNote string `json:"capture_note"`
// 归档级口径:ContentBytes 是**跨版本去重后、被版本引用的内容字节**。
// 它不是磁盘占用(清单、未引用 blob、块对齐与元数据都不在里面),
// 更不是可回收空间——清理需要保留策略、依赖保护与在线作业引用。
Versions int `json:"versions"`
ContentBytes int64 `json:"content_bytes"`
BlobFileBytes int64 `json:"blob_file_bytes"`
BlobAllocatedBytes int64 `json:"blob_allocated_bytes"`
UnreferencedBlobs int `json:"unreferenced_blobs"`
UnreferencedBytes int64 `json:"unreferenced_bytes"`
ManifestFileBytes int64 `json:"manifest_file_bytes"`
ManifestAllocatedBytes int64 `json:"manifest_allocated_bytes"`
// 页面必须能说清"封存由谁执行";能不能从这里发起,取决于主机侧 agent 是否接线。
CaptureNote string `json:"capture_note"`
CaptureAvailable bool `json:"capture_available"`
CaptureReason string `json:"capture_reason,omitempty"`
}
const libraryCaptureNote = "封存由运维命令 scripts/library-capture.sh capture -scope internal|external 在目标主机执行(停写入者→导出→恢复)。页面只读展示已封存的候选;候选不等于验收通过或可发布。"
const libraryCaptureNote = "封存由运维命令 scripts/library-capture.sh capture -scope internal|external 在目标主机执行(停写入者→导出→恢复)。页面只读展示已封存的完整版本:它通过了数据完整性检查(身份、双向正文覆盖、生成问题、资源与摘要),这已满足封版所需的完整性口径;授权与生产同步仍是独立步骤。"
func librarySnapshotsList(w http.ResponseWriter, r *http.Request, config Config) {
view, err := readLibrarySnapshots(config.LibraryArchiveRoot)
view.CaptureAvailable = config.LibraryAgentSocket != ""
if !view.CaptureAvailable {
view.CaptureReason = "未接线:主机侧封存 agent 没有挂载,页面只能查看已封存版本"
}
if err != nil {
writeJSON(w, http.StatusServiceUnavailable, librarySnapshotList{Available: false,
Reason: "归档不可读:" + err.Error(), Snapshots: []librarySnapshotView{}, CaptureNote: libraryCaptureNote})
@@ -100,6 +116,7 @@ func librarySnapshotDetail(w http.ResponseWriter, r *http.Request, config Config
func readLibrarySnapshots(root string) (librarySnapshotList, error) {
view := librarySnapshotList{Snapshots: []librarySnapshotView{}, CaptureNote: libraryCaptureNote}
_ = root
if root == "" {
view.Reason = "未接线:LIBRARY_ARCHIVE_ROOT 未配置,本平台没有整库归档可读"
return view, nil
@@ -114,10 +131,24 @@ func readLibrarySnapshots(root string) (librarySnapshotList, error) {
if err != nil {
return view, errors.New("归档用量不可读")
}
// Per-version UniqueBytes deduplicates only inside one version, so summing it
// over versions over-reports shared blobs. The archive-wide accounting below
// deduplicates across versions and keeps filesystem facts separate.
total, err := archive.ContentUsage()
if err != nil {
return view, errors.New("归档用量不可读")
}
view.Versions = total.Versions
view.ContentBytes = total.ContentBytes
view.BlobFileBytes = total.BlobFileBytes
view.BlobAllocatedBytes = total.BlobAllocatedBytes
view.UnreferencedBlobs = total.UnreferencedBlobs
view.UnreferencedBytes = total.UnreferencedBytes
view.ManifestFileBytes = total.ManifestFileBytes
view.ManifestAllocatedBytes = total.ManifestAllocatedBytes
byID := map[string]librarysnapshot.Usage{}
for _, item := range usage {
byID[item.VersionID] = item
view.StoredBytes += item.UniqueBytes
}
for id, item := range byID {
manifest, loadErr := archive.Load(id)
+7 -4
View File
@@ -101,10 +101,13 @@ func TestReadLibrarySnapshotsReportsSealedTotals(t *testing.T) {
t.Fatalf("total %s = %d, want %d", key, snapshot.Totals[key], value)
}
}
// Stored bytes are deduplicated per blob, so they can be smaller than the
// logical sum but never larger.
if snapshot.LogicalBytes <= 0 || list.StoredBytes <= 0 || list.StoredBytes > snapshot.LogicalBytes {
t.Fatalf("bytes not reported: logical=%d stored=%d", snapshot.LogicalBytes, list.StoredBytes)
// The archive-wide content figure deduplicates blobs across versions, so it
// can be smaller than a version's logical sum but never larger.
if snapshot.LogicalBytes <= 0 || list.ContentBytes <= 0 || list.ContentBytes > snapshot.LogicalBytes {
t.Fatalf("bytes not reported: logical=%d content=%d", snapshot.LogicalBytes, list.ContentBytes)
}
if list.BlobAllocatedBytes < list.BlobFileBytes || list.ManifestFileBytes <= 0 {
t.Fatalf("filesystem facts not separated: %+v", list)
}
if snapshot.Compatibility.EmbeddingDimension != 1024 || snapshot.ValidationPolicy != librarysnapshot.ArtifactAcceptancePolicy {
t.Fatalf("contract not reported: %+v", snapshot)
+24 -1
View File
@@ -130,7 +130,9 @@ type Config struct {
VersionHistory VersionHistoryStore
VersionHistoryRepo string
// LibraryArchiveRoot 是整库封存产物的只读归档根;留空即未接线(页面降级)。
LibraryArchiveRoot string
LibraryArchiveRoot string
// LibraryAgentSocket 是主机侧封存 agent 的 unix socket;留空即页面不能发起封存。
LibraryAgentSocket string
BackupSchedule BackupScheduleStore
BackupHost BackupHost
BackupRuns *BackupRunTracker
@@ -396,6 +398,27 @@ func NewHandler(config Config) (http.Handler, error) {
mux.HandleFunc("GET /api/v1/library/snapshots/{id}", func(w http.ResponseWriter, r *http.Request) {
librarySnapshotDetail(w, r, config)
})
// 页面发起封存:只投递作业(主机侧 agent 执行),并回读作业真实状态。
mux.HandleFunc("POST /api/v1/library/captures", func(w http.ResponseWriter, r *http.Request) {
libraryCaptureEnqueue(w, r, config)
})
mux.HandleFunc("GET /api/v1/library/captures", func(w http.ResponseWriter, r *http.Request) {
libraryCaptureJobs(w, r, config)
})
// 整库状态:测试封存 / 生产生效 / 生产预备份 三类版本 + 差异 + 持久作业。
mux.HandleFunc("GET /api/v1/library/overview", func(w http.ResponseWriter, r *http.Request) {
libraryOverviewHandler(w, r, config)
})
mux.HandleFunc("GET /api/v1/library/jobs", func(w http.ResponseWriter, r *http.Request) {
libraryJobsHandler(w, r, config)
})
mux.HandleFunc("GET /api/v1/library/jobs/{id}", func(w http.ResponseWriter, r *http.Request) {
libraryJobDetailHandler(w, r, config)
})
// 生产同步唯一入口:闸口未齐不建作业,返回缺项而不是假 Accepted。
mux.HandleFunc("POST /api/v1/library/syncs", func(w http.ResponseWriter, r *http.Request) {
librarySyncEnqueue(w, r, config)
})
// 全部 main 提交时间线(读本库缓存,不直接打 Gitea)
mux.HandleFunc("GET /api/v1/version-history", func(w http.ResponseWriter, r *http.Request) {
versionHistoryList(w, r, config)
+13 -1
View File
@@ -1526,6 +1526,10 @@ type fakeJobStore struct {
enqueued jobs.EnqueueRequest
enqueueResult *jobs.Job
listResult []jobs.Job
listType string
listByTypeResult []jobs.Job
listByTypeLimit int
listByTypeErr error
listLimit int
assetResult governance.SourceAssetPage
assetFilter governance.SourceAssetFilter
@@ -1871,7 +1875,9 @@ func (s *fakeJobStore) ActivateUISettingsWithOperation(_ context.Context, revisi
func (s *fakeJobStore) Enqueue(_ context.Context, request jobs.EnqueueRequest, _ time.Time) (*jobs.Job, error) {
s.enqueued = request
if s.enqueueEchoRequestedID {
return &jobs.Job{ID: request.ID, Type: request.Type, State: jobs.StatePending}, nil
// The real store returns the stored row, including its payload: a reused
// idempotency key must be judged by that payload, not by the request.
return &jobs.Job{ID: request.ID, Type: request.Type, State: jobs.StatePending, Payload: request.Payload}, nil
}
return s.enqueueResult, nil
}
@@ -1881,6 +1887,12 @@ func (s *fakeJobStore) List(_ context.Context, limit int) ([]jobs.Job, error) {
return s.listResult, nil
}
func (s *fakeJobStore) ListByType(_ context.Context, jobType string, limit int) ([]jobs.Job, error) {
s.listType = jobType
s.listByTypeLimit = limit
return s.listByTypeResult, s.listByTypeErr
}
func (s *fakeJobStore) ListTestPublications(_ context.Context, filter governance.TestPublicationFilter) (governance.TestPublicationPage, error) {
s.publicationFilter = filter
return s.publicationResult, nil
+314
View File
@@ -0,0 +1,314 @@
// Package libraryagent is the least-privilege execution boundary for
// whole-library capture on the target host.
//
// Why it exists: capturing a library has to stop the source writer for a few
// seconds and read source credentials. Handing the governance containers the
// Docker socket (a full write API) or the source credentials would be a much
// larger privilege than that operation needs. Instead this agent runs as the
// ordinary operator account on the host, listens on one unix socket which only
// that account can connect to, and executes one fixed command with a fixed
// writer declaration. A caller can choose the scope and (optionally) a job id —
// nothing else.
package libraryagent
import (
"bufio"
"context"
"encoding/json"
"errors"
"log"
"net"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"sync"
"syscall"
"time"
)
// Config is fixed at start-up by the operator (systemd unit / CLI flags). It is
// never taken from a request.
type Config struct {
Socket string
Binary string
ArchiveRoot string
JournalRoot string
// Writer declaration passed to the binary, exactly as reviewed in
// scripts/library-capture.sh. Clients cannot influence it.
SourceApp string
SourcePG string
SourceES string
GovernancePG string
Project string
Writers string
NonWriters string
MaxDuration time.Duration
// StopGrace bounds the graceful stop of one operation: SIGTERM first (the
// child aborts the maintenance window and restores writers), then SIGKILL
// only after this grace period. It must exceed the child's own restore budget.
StopGrace time.Duration
// RecoverTimeout bounds the recovery run performed after a failed or killed
// operation, and at agent start-up.
RecoverTimeout time.Duration
// Run executes the binary; replaced in tests.
Run func(ctx context.Context, name string, args ...string) ([]byte, error)
}
type request struct {
Action string `json:"action"`
Scope string `json:"scope,omitempty"`
Job string `json:"job,omitempty"`
}
type response struct {
OK bool `json:"ok"`
Action string `json:"action"`
Scope string `json:"scope,omitempty"`
Job string `json:"job,omitempty"`
Error string `json:"error,omitempty"`
Payload json.RawMessage `json:"payload,omitempty"`
}
var jobPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`)
// Agent serves capture requests. Only one operation runs at a time: a library
// capture owns the writer group, so overlapping requests would race the window.
type Agent struct {
config Config
mu sync.Mutex
// degraded is non-empty when a failed operation could not be followed by a
// verified recovery. While set, capture requests are refused: leaving the
// source writer stopped is worse than refusing work.
degraded string
wg sync.WaitGroup
}
func New(config Config) (*Agent, error) {
if !filepath.IsAbs(config.Socket) || !filepath.IsAbs(config.ArchiveRoot) || !filepath.IsAbs(config.JournalRoot) {
return nil, errors.New("library agent paths must be absolute")
}
if config.Binary == "" || config.Project == "" || config.Writers == "" || !strings.Contains(config.NonWriters, "=") {
return nil, errors.New("library agent needs a binary, project, writers and a non-writer declaration")
}
if config.MaxDuration <= 0 || config.MaxDuration > 30*time.Minute {
return nil, errors.New("library agent duration bound is invalid")
}
if config.StopGrace == 0 {
config.StopGrace = 3 * time.Minute
}
if config.RecoverTimeout == 0 {
config.RecoverTimeout = 3 * time.Minute
}
if config.StopGrace <= 0 || config.StopGrace > 10*time.Minute || config.RecoverTimeout <= 0 || config.RecoverTimeout > 10*time.Minute {
return nil, errors.New("library agent recovery/stop budget is invalid")
}
return &Agent{config: config}, nil
}
// Serve listens until ctx is cancelled. The socket is created 0600 inside a
// 0700 directory and removed on shutdown.
func (a *Agent) Serve(ctx context.Context) error {
if err := os.MkdirAll(filepath.Dir(a.config.Socket), 0700); err != nil {
return err
}
if err := os.Chmod(filepath.Dir(a.config.Socket), 0700); err != nil {
return err
}
_ = os.Remove(a.config.Socket)
listener, err := net.Listen("unix", a.config.Socket)
if err != nil {
return err
}
defer func() {
listener.Close()
_ = os.Remove(a.config.Socket)
}()
if err := os.Chmod(a.config.Socket, 0600); err != nil {
return err
}
// Startup responsibility: an agent restart may have inherited a stopped
// writer from a previous killed run. Recover before accepting work; if that
// fails, stay degraded and refuse captures instead of pretending to be ready.
if err := a.recoverWriters(ctx); err != nil {
a.degraded = err.Error()
log.Printf("library agent: pending freeze recovery failed: %v", err)
}
go func() {
<-ctx.Done()
_ = listener.Close()
}()
for {
conn, err := listener.Accept()
if err != nil {
if ctx.Err() != nil {
// Drain in-flight operations: each of them still owes a bounded
// recovery before the agent may exit.
done := make(chan struct{})
go func() { a.wg.Wait(); close(done) }()
select {
case <-done:
case <-time.After(a.config.StopGrace + a.config.RecoverTimeout):
log.Printf("library agent: shutdown deadline exceeded with operations in flight")
}
return nil
}
return err
}
a.wg.Add(1)
go func(conn net.Conn) {
defer a.wg.Done()
a.handle(ctx, conn)
}(conn)
}
}
func (a *Agent) handle(ctx context.Context, conn net.Conn) {
defer conn.Close()
if err := peerAllowed(conn); err != nil {
_ = json.NewEncoder(conn).Encode(response{OK: false, Error: err.Error()})
return
}
_ = conn.SetDeadline(time.Now().Add(a.config.MaxDuration + 30*time.Second))
decoder := json.NewDecoder(bufio.NewReader(conn))
var req request
if err := decoder.Decode(&req); err != nil {
_ = json.NewEncoder(conn).Encode(response{OK: false, Error: "invalid request"})
return
}
result := a.execute(ctx, req)
_ = json.NewEncoder(conn).Encode(result)
}
// execute serialises operations and maps a request onto the one fixed command.
func (a *Agent) execute(ctx context.Context, req request) response {
a.mu.Lock()
defer a.mu.Unlock()
out := response{Action: req.Action, Scope: req.Scope, Job: req.Job}
// Degraded blocks new captures, but recover and status must stay reachable:
// otherwise there is no way back to a verified state.
if a.degraded != "" && req.Action == "capture" {
out.Error = "封存执行边界处于降级状态(上次恢复失败:" + a.degraded + "),先执行 recover"
return out
}
var args []string
switch req.Action {
case "status":
args = []string{"status"}
case "recover":
args = []string{"recover"}
case "capture":
if req.Scope != "internal" && req.Scope != "external" {
out.Error = "scope must be internal or external"
return out
}
if req.Job != "" && !jobPattern.MatchString(req.Job) {
out.Error = "invalid job id"
return out
}
args = []string{"capture", "-scope", req.Scope}
if req.Job != "" {
args = append(args, "-job", req.Job)
}
default:
out.Error = "unsupported action"
return out
}
args = append(args, a.config.declaration()...)
bounded, cancel := context.WithTimeout(ctx, a.config.MaxDuration)
defer cancel()
payload, err := a.config.run(bounded, a.config.Binary, args...)
if err != nil {
detail := "operation failed"
if message := strings.TrimSpace(string(payload)); message != "" && len(message) <= 2000 {
detail = message
}
// A killed or aborted child may have left the source writer stopped. The
// recovery responsibility does not end with the failed request: run the
// idempotent recovery now, and refuse further captures if it does not
// verify.
if req.Action == "capture" || req.Action == "recover" {
if recoveryErr := a.recoverWriters(ctx); recoveryErr != nil {
a.degraded = recoveryErr.Error()
out.Error = detail + ";写入者恢复失败:" + recoveryErr.Error() + "(已阻断后续封存,需人工处理)"
return out
}
detail += ";已执行 recover 并确认写入者恢复"
} else {
// status 失败不需要恢复;它不改变停机状态。
}
out.Error = detail
return out
}
if req.Action == "recover" {
a.degraded = ""
}
out.OK = true
if json.Valid(payload) {
out.Payload = json.RawMessage(payload)
} else {
out.Payload = json.RawMessage(`{}`)
}
return out
}
// recoverWriters runs the idempotent recovery command with its own budget, even
// when the triggering context is already cancelled (timeout / shutdown).
func (a *Agent) recoverWriters(ctx context.Context) error {
bounded, cancel := context.WithTimeout(context.WithoutCancel(ctx), a.config.RecoverTimeout)
defer cancel()
if _, err := a.config.run(bounded, a.config.Binary, append([]string{"recover"}, a.config.declaration()...)...); err != nil {
return err
}
a.degraded = ""
return nil
}
// declaration pins every path and the writer group so a request cannot redirect
// the operation to another stack, archive or journal.
func (c Config) declaration() []string {
return []string{
"-source-app", c.SourceApp,
"-source-pg", c.SourcePG,
"-source-es", c.SourceES,
"-governance-pg", c.GovernancePG,
"-project", c.Project,
"-writers", c.Writers,
"-non-writers", c.NonWriters,
"-archive", c.ArchiveRoot,
"-journal", c.JournalRoot,
}
}
func (c Config) run(ctx context.Context, name string, args ...string) ([]byte, error) {
if c.Run != nil {
return c.Run(ctx, name, args...)
}
command := exec.CommandContext(ctx, name, args...)
command.Env = append(os.Environ(), "LIBRARYCTL_AGENT=1")
// Default CommandContext behaviour is SIGKILL, which would skip the child's
// window restore and leave the source writer stopped. Ask for a graceful stop
// first and only escalate after the grace period.
command.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
command.Cancel = func() error {
if command.Process == nil {
return nil
}
return command.Process.Signal(syscall.SIGTERM)
}
command.WaitDelay = c.StopGrace
return command.CombinedOutput()
}
// Describe returns a redacted view for logs and health checks.
func (a *Agent) Describe() map[string]any {
return map[string]any{
"socket": a.config.Socket,
"archive_root": a.config.ArchiveRoot,
"journal_root": a.config.JournalRoot,
"project": a.config.Project,
"writers": a.config.Writers,
"scope_choice": "request may select internal or external only",
}
}
+338
View File
@@ -0,0 +1,338 @@
package libraryagent
import (
"context"
"encoding/json"
"errors"
"net"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
)
func testAgent(t *testing.T) (*Agent, string, func() []string) {
t.Helper()
root, err := os.MkdirTemp(os.TempDir(), "kgag-")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.RemoveAll(root) })
if err = os.Chmod(root, 0700); err != nil {
t.Fatal(err)
}
var mu sync.Mutex
var calls []string
config := Config{
Socket: filepath.Join(root, "agent.sock"),
Binary: "/bin/echo",
ArchiveRoot: filepath.Join(root, "library"),
JournalRoot: filepath.Join(root, "freeze"),
SourceApp: "WKNFull-app",
SourcePG: "WKNFull-postgres",
SourceES: "WKNFull-elasticsearch",
GovernancePG: "knowledge-governance-p1-postgres-1",
Project: "weknora071full",
Writers: "app",
NonWriters: "frontend=UI only; no knowledge writes",
MaxDuration: time.Minute,
Run: func(_ context.Context, name string, args ...string) ([]byte, error) {
mu.Lock()
calls = append(calls, name+" "+strings.Join(args, " "))
mu.Unlock()
return []byte(`{"snapshot_id":"abc","state":"succeeded"}`), nil
},
}
agent, err := New(config)
if err != nil {
t.Fatal(err)
}
return agent, config.Socket, func() []string {
mu.Lock()
defer mu.Unlock()
return append([]string(nil), calls...)
}
}
func roundTrip(t *testing.T, socket string, payload string) response {
t.Helper()
conn, err := net.Dial("unix", socket)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
if _, err = conn.Write([]byte(payload + "\n")); err != nil {
t.Fatal(err)
}
var out response
if err = json.NewDecoder(conn).Decode(&out); err != nil {
t.Fatal(err)
}
return out
}
// The socket is the whole security boundary: 0600 in a 0700 directory, and the
// declaration (archive, journal, project, writers) comes from the agent's own
// configuration, never from the request.
func TestAgentSocketIsPrivateAndPinsTheDeclaration(t *testing.T) {
agent, socket, calls := testAgent(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() { _ = agent.Serve(ctx) }()
deadline := time.Now().Add(2 * time.Second)
for {
if _, err := os.Stat(socket); err == nil {
break
}
if time.Now().After(deadline) {
t.Fatal("agent socket never appeared")
}
time.Sleep(10 * time.Millisecond)
}
info, err := os.Stat(socket)
if err != nil {
t.Fatal(err)
}
if info.Mode().Perm() != 0600 {
t.Fatalf("socket mode %v", info.Mode().Perm())
}
dir, err := os.Stat(filepath.Dir(socket))
if err != nil {
t.Fatal(err)
}
if dir.Mode().Perm() != 0700 {
t.Fatalf("socket directory mode %v", dir.Mode().Perm())
}
out := roundTrip(t, socket, `{"action":"capture","scope":"internal","job":"lib-internal-test"}`)
if !out.OK || out.Job != "lib-internal-test" {
t.Fatalf("capture rejected: %+v", out)
}
recorded := captureCalls(calls())
if len(recorded) != 1 {
t.Fatalf("expected one capture execution, got %v", recorded)
}
for _, want := range []string{"capture -scope internal -job lib-internal-test",
"-archive " + filepath.Join(filepath.Dir(socket), "library"),
"-journal " + filepath.Join(filepath.Dir(socket), "freeze"),
"-project weknora071full", "-writers app"} {
if !strings.Contains(recorded[0], want) {
t.Fatalf("execution %q missing %q", recorded[0], want)
}
}
if strings.Contains(recorded[0], "..") {
t.Fatal("unexpected path traversal in declaration")
}
}
func TestAgentRejectsUnsupportedRequestsWithoutExecuting(t *testing.T) {
agent, socket, calls := testAgent(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() { _ = agent.Serve(ctx) }()
deadline := time.Now().Add(2 * time.Second)
for {
if _, err := os.Stat(socket); err == nil {
break
}
if time.Now().After(deadline) {
t.Fatal("agent socket never appeared")
}
time.Sleep(10 * time.Millisecond)
}
for _, payload := range []string{
`{"action":"shell","command":"docker ps"}`,
`{"action":"capture","scope":"production"}`,
`{"action":"capture","scope":"internal","job":"bad job; rm -rf /"}`,
`not json`,
} {
out := roundTrip(t, socket, payload)
if out.OK || out.Error == "" {
t.Fatalf("accepted %q: %+v", payload, out)
}
}
if got := captureCalls(calls()); len(got) != 0 {
t.Fatalf("rejected requests still executed: %v", got)
}
}
func captureCalls(calls []string) []string {
kept := make([]string, 0, len(calls))
for _, call := range calls {
if strings.Contains(call, " capture ") {
kept = append(kept, call)
}
}
return kept
}
func recoverCalls(calls []string) []string {
kept := make([]string, 0, len(calls))
for _, call := range calls {
if strings.Contains(call, " recover ") {
kept = append(kept, call)
}
}
return kept
}
// failingAgent builds an agent whose capture always fails and whose recovery
// outcome can be switched, to prove the recovery responsibility after a
// killed/aborted child.
func failingAgent(t *testing.T) (*Agent, string, func() []string, func(error)) {
t.Helper()
root, err := os.MkdirTemp(os.TempDir(), "kgrf-")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.RemoveAll(root) })
if err = os.Chmod(root, 0700); err != nil {
t.Fatal(err)
}
var mu sync.Mutex
var calls []string
var recoverErr error
agent, err := New(Config{
Socket: filepath.Join(root, "agent.sock"), Binary: "/bin/echo",
ArchiveRoot: filepath.Join(root, "library"), JournalRoot: filepath.Join(root, "freeze"),
SourceApp: "app-container", SourcePG: "pg", SourceES: "es", GovernancePG: "gov",
Project: "weknora071full", Writers: "app", NonWriters: "frontend=UI only",
MaxDuration: time.Minute, StopGrace: time.Minute, RecoverTimeout: time.Minute,
Run: func(_ context.Context, name string, args ...string) ([]byte, error) {
mu.Lock()
calls = append(calls, name+" "+strings.Join(args, " "))
current := recoverErr
mu.Unlock()
if len(args) > 0 && args[0] == "recover" {
if current != nil {
return []byte("writer restart failed"), current
}
return []byte(`{"recovered":true}`), nil
}
return []byte("LIBRARYCTL_FAILED: stop outcome uncertain"), errors.New("exit status 1")
},
})
if err != nil {
t.Fatal(err)
}
return agent, filepath.Join(root, "agent.sock"), func() []string {
mu.Lock()
defer mu.Unlock()
return append([]string(nil), calls...)
}, func(err error) {
mu.Lock()
defer mu.Unlock()
recoverErr = err
}
}
// A failed capture must be followed by a recovery attempt, not just an error.
func TestAgentRecoversWritersAfterFailedCapture(t *testing.T) {
agent, socket, calls, _ := failingAgent(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() { _ = agent.Serve(ctx) }()
waitSocket(t, socket)
out := roundTrip(t, socket, `{"action":"capture","scope":"internal","job":"lib-fail-1"}`)
if out.OK {
t.Fatalf("failed capture reported success: %+v", out)
}
if !strings.Contains(out.Error, "已执行 recover 并确认写入者恢复") {
t.Fatalf("error does not state the recovery outcome: %q", out.Error)
}
if len(recoverCalls(calls())) == 0 {
t.Fatal("no recovery ran after the failed capture")
}
}
// If recovery itself fails, the boundary must refuse further captures instead of
// leaving the source stopped and merely marking a job failed.
func TestAgentBlocksCapturesWhenRecoveryFails(t *testing.T) {
agent, socket, calls, setRecoverErr := failingAgent(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() { _ = agent.Serve(ctx) }()
waitSocket(t, socket)
setRecoverErr(errors.New("docker restart failed"))
out := roundTrip(t, socket, `{"action":"capture","scope":"internal","job":"lib-fail-2"}`)
if out.OK || !strings.Contains(out.Error, "写入者恢复失败") || !strings.Contains(out.Error, "已阻断后续封存") {
t.Fatalf("recovery failure not surfaced: %+v", out)
}
before := len(captureCalls(calls()))
blocked := roundTrip(t, socket, `{"action":"capture","scope":"external","job":"lib-fail-3"}`)
if blocked.OK || !strings.Contains(blocked.Error, "降级") {
t.Fatalf("degraded agent accepted a capture: %+v", blocked)
}
if got := len(captureCalls(calls())); got != before {
t.Fatalf("blocked capture still executed (%d -> %d)", before, got)
}
// A verified recovery clears the degraded state and lets work resume.
setRecoverErr(nil)
if recovered := roundTrip(t, socket, `{"action":"recover"}`); !recovered.OK {
t.Fatalf("explicit recovery failed: %+v", recovered)
}
if resumed := roundTrip(t, socket, `{"action":"capture","scope":"internal","job":"lib-fail-4"}`); strings.Contains(resumed.Error, "降级") {
t.Fatalf("recovery did not clear the degraded state: %+v", resumed)
}
}
// The child is stopped with SIGTERM and the grace period, not an immediate kill.
func TestRunStopsChildWithSigterm(t *testing.T) {
dir := t.TempDir()
script := filepath.Join(dir, "child.sh")
// A real child that only exits 0 when it receives SIGTERM.
child := "#!/bin/sh\ntrap 'exit 0' TERM\nwhile :; do sleep 0.05; done\n"
if err := os.WriteFile(script, []byte(child), 0o700); err != nil {
t.Fatal(err)
}
agent, err := New(Config{Socket: "/tmp/irrelevant.sock", Binary: script,
ArchiveRoot: filepath.Join(dir, "library"), JournalRoot: filepath.Join(dir, "freeze"),
SourceApp: "app-container", SourcePG: "pg", SourceES: "es", GovernancePG: "gov",
Project: "weknora071full", Writers: "app", NonWriters: "frontend=UI only",
MaxDuration: 2 * time.Second, StopGrace: 5 * time.Second, RecoverTimeout: 5 * time.Second})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
defer cancel()
started := time.Now()
_, err = agent.config.run(ctx, script)
if err == nil {
t.Fatal("cancelled run reported success")
}
if elapsed := time.Since(started); elapsed > 4*time.Second {
t.Fatalf("child was not stopped within the graceful window: %s", elapsed)
}
if ctx.Err() == nil {
t.Fatal("test did not exercise cancellation")
}
}
func waitSocket(t *testing.T, socket string) {
t.Helper()
deadline := time.Now().Add(2 * time.Second)
for {
if _, err := os.Stat(socket); err == nil {
return
}
if time.Now().After(deadline) {
t.Fatal("agent socket never appeared")
}
time.Sleep(10 * time.Millisecond)
}
}
func TestNewRejectsIncompleteConfiguration(t *testing.T) {
if _, err := New(Config{}); err == nil {
t.Fatal("empty configuration accepted")
}
if _, err := New(Config{Socket: "relative.sock", ArchiveRoot: "/tmp/a", JournalRoot: "/tmp/j",
Binary: "/bin/true", Project: "p", Writers: "app", NonWriters: "frontend=ui", MaxDuration: time.Minute}); err == nil {
t.Fatal("relative socket path accepted")
}
if _, err := New(Config{Socket: "/tmp/a.sock", ArchiveRoot: "/tmp/a", JournalRoot: "/tmp/j",
Binary: "/bin/true", Project: "p", Writers: "app", NonWriters: "frontend", MaxDuration: time.Minute}); err == nil {
t.Fatal("non-writer declaration without a reason accepted")
}
}
+92
View File
@@ -0,0 +1,92 @@
package libraryagent
import (
"context"
"encoding/json"
"errors"
"net"
"time"
)
// ClientConfig is what a governance process needs: one socket path. It never
// carries source credentials or Docker access — those stay with the agent.
type ClientConfig struct {
Socket string
Timeout time.Duration
}
// Result is the agent's answer to one capture/status/recover request.
type Result struct {
OK bool
Scope string
Job string
SnapshotID string
Replay bool
Error string
Payload json.RawMessage
}
// Capture asks the agent to seal one library scope. The job id makes the call
// idempotent: repeating it returns the already sealed candidate.
func Capture(ctx context.Context, config ClientConfig, scope, job string) (Result, error) {
return call(ctx, config, map[string]string{"action": "capture", "scope": scope, "job": job})
}
// Status probes the agent (source wiring, writer group, archive usage).
func Status(ctx context.Context, config ClientConfig) (Result, error) {
return call(ctx, config, map[string]string{"action": "status"})
}
// Recover restores writers from an interrupted freeze journal.
func Recover(ctx context.Context, config ClientConfig) (Result, error) {
return call(ctx, config, map[string]string{"action": "recover"})
}
func call(ctx context.Context, config ClientConfig, request map[string]string) (Result, error) {
if config.Socket == "" {
return Result{}, errors.New("library agent socket is not configured")
}
timeout := config.Timeout
if timeout <= 0 {
timeout = 2 * time.Minute
}
bounded, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
var dialer net.Dialer
conn, err := dialer.DialContext(bounded, "unix", config.Socket)
if err != nil {
return Result{}, errors.New("library agent is unreachable")
}
defer conn.Close()
if deadline, ok := bounded.Deadline(); ok {
_ = conn.SetDeadline(deadline)
}
if err = json.NewEncoder(conn).Encode(request); err != nil {
return Result{}, errors.New("library agent request failed")
}
var response struct {
OK bool `json:"ok"`
Scope string `json:"scope"`
Job string `json:"job"`
Error string `json:"error"`
Payload json.RawMessage `json:"payload"`
}
if err = json.NewDecoder(conn).Decode(&response); err != nil {
return Result{}, errors.New("library agent returned an invalid response")
}
result := Result{OK: response.OK, Scope: response.Scope, Job: response.Job, Error: response.Error, Payload: response.Payload}
var payload struct {
SnapshotID string `json:"snapshot_id"`
Replay bool `json:"replay"`
}
if len(response.Payload) > 0 && json.Unmarshal(response.Payload, &payload) == nil {
result.SnapshotID, result.Replay = payload.SnapshotID, payload.Replay
}
if !result.OK {
if result.Error == "" {
result.Error = "library agent refused the request"
}
return result, errors.New(result.Error)
}
return result, nil
}
+37
View File
@@ -0,0 +1,37 @@
package libraryagent
import (
"errors"
"net"
"os"
"syscall"
)
// peerAllowed enforces that the connecting process runs as the same uid as the
// agent. File mode 0600 already limits connect() to that uid; the credential
// check makes the boundary explicit and fails closed if the socket is ever
// reached another way (bind mount into a container with a different uid).
func peerAllowed(conn net.Conn) error {
unixConn, ok := conn.(*net.UnixConn)
if !ok {
return errors.New("unsupported transport")
}
raw, err := unixConn.SyscallConn()
if err != nil {
return errors.New("peer credentials unavailable")
}
var credential *syscall.Ucred
var controlErr error
if err = raw.Control(func(fd uintptr) {
credential, controlErr = syscall.GetsockoptUcred(int(fd), syscall.SOL_SOCKET, syscall.SO_PEERCRED)
}); err != nil {
return errors.New("peer credentials unavailable")
}
if controlErr != nil || credential == nil {
return errors.New("peer credentials unavailable")
}
if credential.Uid != uint32(os.Geteuid()) {
return errors.New("peer uid is not allowed")
}
return nil
}
+14
View File
@@ -0,0 +1,14 @@
//go:build !linux
package libraryagent
import (
"errors"
"net"
)
// The capture host is Linux (Docker + unix socket); other platforms refuse
// rather than guess at peer credentials.
func peerAllowed(net.Conn) error {
return errors.New("library agent requires Linux peer credentials")
}
+19
View File
@@ -129,6 +129,25 @@ func (c *Coordinator) Recover(ctx context.Context) error {
}
return nil
}
// Inspect reports the persisted result of a job, if this coordinator ever ran it.
// A caller which re-uses a job ID needs the original request identity (time,
// scope, knowledge base, contract) to replay idempotently instead of guessing a
// fresh one, which would be rejected as a conflicting request.
func (c *Coordinator) Inspect(job string) (Result, bool, error) {
if !validID(job) {
return Result{}, false, errors.New("invalid freeze job id")
}
j, err := c.load(job)
if errors.Is(err, os.ErrNotExist) {
return Result{}, false, nil
}
if err != nil {
return Result{}, false, err
}
return j.Result, true, nil
}
func invokeCapture(ctx context.Context, capture func(context.Context) (string, error)) (id string, err error) {
defer func() {
if recover() != nil {
+131
View File
@@ -6,9 +6,11 @@ import (
"errors"
"io"
"math"
"os"
"slices"
"sort"
"strings"
"syscall"
)
type Usage struct {
@@ -97,6 +99,135 @@ func (a *Archive) Usage() ([]Usage, error) {
return result, nil
}
// ContentUsage is the archive-wide accounting of *content* bytes.
//
// It exists because per-version Usage() deduplicates only within one version: a
// blob shared by two versions is counted in both UniqueBytes, so summing those
// numbers over-reports the archive. ContentBytes here is deduplicated across
// every sealed version.
//
// It is still not filesystem occupancy: manifests, unreferenced blobs left by an
// interrupted Put and filesystem allocation (block rounding, metadata) are
// reported separately, and none of these numbers are reclaimable space. Cleanup
// needs retention/protection and live-job references from the coordinator.
type ContentUsage struct {
Versions int `json:"versions"`
ReferencedBlobs int `json:"referenced_blobs"`
ContentBytes int64 `json:"content_bytes"`
UnreferencedBlobs int `json:"unreferenced_blobs"`
UnreferencedBytes int64 `json:"unreferenced_bytes"`
BlobFileBytes int64 `json:"blob_file_bytes"`
BlobAllocatedBytes int64 `json:"blob_allocated_bytes"`
ManifestFileBytes int64 `json:"manifest_file_bytes"`
ManifestAllocatedBytes int64 `json:"manifest_allocated_bytes"`
}
// ContentUsage walks the sealed versions and the blob directory once, with the
// same "inventory must not change under us" guard as Usage.
func (a *Archive) ContentUsage() (ContentUsage, error) {
var usage ContentUsage
ids, err := a.versionIDs()
if err != nil {
return usage, err
}
referenced := map[string]int64{}
for _, id := range ids {
m, err := a.Load(id)
if err != nil {
return usage, err
}
for _, p := range m.Parts {
referenced[p.SHA256] = p.Bytes
}
}
after, err := a.versionIDs()
if err != nil {
return usage, err
}
if !slices.Equal(ids, after) {
return usage, errors.New("snapshot inventory changed; retry usage read")
}
usage.Versions = len(ids)
usage.ReferencedBlobs = len(referenced)
for _, size := range referenced {
if usage.ContentBytes > math.MaxInt64-size {
return usage, errors.New("snapshot usage overflow")
}
usage.ContentBytes += size
}
blobs, err := directoryBytes(a.blobs, func(name string) error {
if !validDigest(name) {
return errors.New("unexpected archive blob entry")
}
return nil
})
if err != nil {
return usage, err
}
usage.BlobFileBytes, usage.BlobAllocatedBytes = blobs.fileBytes, blobs.allocatedBytes
usage.UnreferencedBlobs = blobs.files - len(referenced)
usage.UnreferencedBytes = blobs.fileBytes
for _, size := range referenced {
usage.UnreferencedBytes -= size
}
if usage.UnreferencedBytes < 0 || usage.UnreferencedBlobs < 0 {
return usage, errors.New("archive blob inventory is inconsistent")
}
manifests, err := directoryBytes(a.versions, func(name string) error {
if strings.HasPrefix(name, ".pending-") {
return nil
}
if !strings.HasSuffix(name, ".json") {
return errors.New("unexpected archive version entry")
}
return nil
})
if err != nil {
return usage, err
}
usage.ManifestFileBytes, usage.ManifestAllocatedBytes = manifests.fileBytes, manifests.allocatedBytes
return usage, nil
}
type directoryUsage struct {
files int
fileBytes int64
allocatedBytes int64
}
// directoryBytes reports apparent size and allocated size (st_blocks) so callers
// can tell content size from what the filesystem actually reserved.
func directoryBytes(root *os.Root, validate func(string) error) (directoryUsage, error) {
var usage directoryUsage
dir, err := root.Open(".")
if err != nil {
return usage, err
}
defer dir.Close()
entries, err := dir.ReadDir(-1)
if err != nil {
return usage, err
}
for _, entry := range entries {
if err := validate(entry.Name()); err != nil {
return usage, err
}
info, err := entry.Info()
if err != nil {
return usage, err
}
if !info.Mode().IsRegular() {
return usage, errors.New("archive entry is not a regular file")
}
usage.files++
usage.fileBytes += info.Size()
if stat, ok := info.Sys().(*syscall.Stat_t); ok {
usage.allocatedBytes += stat.Blocks * 512
}
}
return usage, nil
}
func (a *Archive) versionIDs() ([]string, error) {
f, err := a.versions.Open(".")
if err != nil {
@@ -0,0 +1,149 @@
package librarysnapshot
import (
"bytes"
"fmt"
"os"
"strings"
"testing"
"time"
)
// sealFixtureVersion seals one complete manifest whose parts are all derived
// from the same rows, so two versions of the same content share every blob.
func sealFixtureVersion(t *testing.T, archive *Archive, scope string, createdAt time.Time, documents int) string {
t.Helper()
rows := func(count int) string {
if count == 0 {
return "[]"
}
items := make([]string, count)
for i := range items {
items[i] = fmt.Sprintf(`{"id":"00000000-0000-4000-8000-%012d"}`, i)
}
return "[" + strings.Join(items, ",") + "]"
}
parts := []struct {
kind, name string
count int64
body string
}{
{"database", "knowledges", int64(documents), rows(documents)},
{"database", "chunks", int64(documents), rows(documents)},
{"database", "resources", 0, rows(0)},
{"database", "resource_bindings", 0, rows(0)},
{"database", "knowledge_tags", 0, rows(0)},
{"database", "knowledge_tag_relations", 0, rows(0)},
{"index", "chunks", int64(documents), rows(documents)},
{"wiki", "wiki_pages", 0, rows(0)},
{"wiki", "wiki_folders", 0, rows(0)},
{"wiki", "wiki_page_issues", 0, rows(0)},
{"wiki", "wiki_log_entries", 0, rows(0)},
}
manifest := Manifest{ValidationPolicy: ArtifactAcceptancePolicy, Format: Format, Scope: scope,
TenantID: 10000, KnowledgeBaseID: "kb-safe", CreatedAt: createdAt,
Compatibility: Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74,
RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "fixture-model", EmbeddingDimension: 1024,
IndexMappingSHA256: strings.Repeat("a", 64)}}
for _, part := range parts {
stored, err := archive.Put(bytes.NewReader([]byte(part.body)))
if err != nil {
t.Fatal(err)
}
stored.Kind, stored.Name, stored.Count = part.kind, part.name, part.count
manifest.Parts = append(manifest.Parts, stored)
}
id, err := archive.Seal(manifest)
if err != nil {
t.Fatal(err)
}
return id
}
func fixtureArchive(t *testing.T) (*Archive, string) {
t.Helper()
root, err := os.MkdirTemp(os.TempDir(), "kgsnap-")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.RemoveAll(root) })
if err = os.Chmod(root, 0700); err != nil {
t.Fatal(err)
}
archive, err := Open(root, 1024*1024)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { archive.Close() })
return archive, root
}
// Two sealed versions with identical content share every blob: summing the
// per-version UniqueBytes double counts them, which is the reporting bug this
// accounting fixes.
func TestContentUsageDeduplicatesAcrossVersions(t *testing.T) {
archive, _ := fixtureArchive(t)
sealFixtureVersion(t, archive, "internal", time.Date(2026, 10, 28, 1, 0, 0, 0, time.UTC), 4)
sealFixtureVersion(t, archive, "internal", time.Date(2026, 10, 28, 2, 0, 0, 0, time.UTC), 4)
perVersion, err := archive.Usage()
if err != nil {
t.Fatal(err)
}
if len(perVersion) != 2 {
t.Fatalf("expected two versions, got %d", len(perVersion))
}
sum := perVersion[0].UniqueBytes + perVersion[1].UniqueBytes
total, err := archive.ContentUsage()
if err != nil {
t.Fatal(err)
}
if total.Versions != 2 {
t.Fatalf("versions=%d", total.Versions)
}
if total.ContentBytes <= 0 {
t.Fatal("no content bytes reported")
}
if total.ContentBytes*2 != sum {
t.Fatalf("shared content not deduplicated: content=%d sum-of-versions=%d", total.ContentBytes, sum)
}
if total.UnreferencedBlobs != 0 || total.UnreferencedBytes != 0 {
t.Fatalf("unexpected unreferenced blobs: %+v", total)
}
if total.BlobFileBytes != total.ContentBytes {
t.Fatalf("blob files=%d content=%d", total.BlobFileBytes, total.ContentBytes)
}
if total.BlobAllocatedBytes < total.BlobFileBytes {
t.Fatalf("allocated=%d smaller than apparent=%d", total.BlobAllocatedBytes, total.BlobFileBytes)
}
if total.ManifestFileBytes <= 0 || total.ManifestAllocatedBytes < total.ManifestFileBytes {
t.Fatalf("manifest accounting wrong: %+v", total)
}
}
// A blob written by an interrupted capture is referenced by no manifest and must
// be reported separately, never folded into content bytes.
func TestContentUsageSeparatesUnreferencedBlobs(t *testing.T) {
archive, _ := fixtureArchive(t)
sealFixtureVersion(t, archive, "internal", time.Date(2026, 10, 28, 3, 0, 0, 0, time.UTC), 2)
before, err := archive.ContentUsage()
if err != nil {
t.Fatal(err)
}
stray, err := archive.Put(bytes.NewReader([]byte("interrupted-write")))
if err != nil {
t.Fatal(err)
}
after, err := archive.ContentUsage()
if err != nil {
t.Fatal(err)
}
if after.ContentBytes != before.ContentBytes {
t.Fatal("unreferenced blob changed content bytes")
}
if after.UnreferencedBlobs != 1 || after.UnreferencedBytes != stray.Bytes {
t.Fatalf("unreferenced accounting wrong: %+v (stray=%d)", after, stray.Bytes)
}
if after.BlobFileBytes != before.BlobFileBytes+stray.Bytes {
t.Fatal("blob file bytes do not include the unreferenced blob")
}
}
+276
View File
@@ -0,0 +1,276 @@
package postgres
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"knowledge-governance/internal/governance"
)
// 整库作业与版本:队列(jobs)负责租约重试,本文件负责业务身份、阶段与结果。
// 互斥与幂等都由数据库唯一索引保证,不依赖前端或单 worker 部署。
func (s *Store) CreateLibraryJob(ctx context.Context, job governance.LibraryJob, stages []string, now time.Time) (governance.LibraryJob, bool, error) {
request := job.RequestDigest
if request == "" {
return governance.LibraryJob{}, false, errors.New("library job requires a request digest")
}
rawRequest, err := json.Marshal(map[string]any{"digest": request, "kind": string(job.Kind), "scope": job.Scope})
if err != nil {
return governance.LibraryJob{}, false, err
}
var id string
err = s.db.QueryRow(ctx, `
INSERT INTO library_jobs (id, scope, kind, state, stage, idempotency_key, request_digest, request,
queue_job_id, snapshot_id, target_snapshot_id, actor, error, recovery, created_at, updated_at)
VALUES ($1,$2,$3,'pending','',$4,$5,$6,$7,$8,$9,$10,'','',$11,$11)
ON CONFLICT (idempotency_key) DO NOTHING
RETURNING id`,
job.ID, job.Scope, string(job.Kind), job.IdempotencyKey, request, rawRequest,
job.QueueJobID, job.SnapshotID, job.TargetSnapshotID, job.Actor, now.UTC()).Scan(&id)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
if pgErr.ConstraintName == "library_jobs_active" {
return governance.LibraryJob{}, false, governance.ErrLibraryJobActive
}
}
if !errors.Is(err, pgx.ErrNoRows) {
return governance.LibraryJob{}, false, fmt.Errorf("create library job: %w", err)
}
// 幂等键已存在:必须返回**已存**作业,并核对请求体是否一致。
existing, loadErr := s.libraryJobByKey(ctx, job.IdempotencyKey)
if loadErr != nil {
return governance.LibraryJob{}, false, loadErr
}
if existing.RequestDigest != request {
return existing, false, governance.ErrLibraryJobIdempotencyConflict
}
return existing, true, nil
}
for _, stage := range stages {
if _, err := s.db.Exec(ctx, `
INSERT INTO library_job_stages (job_id, stage, state, detail, updated_at)
VALUES ($1,$2,'pending','',$3)
ON CONFLICT (job_id, stage) DO NOTHING`, id, stage, now.UTC()); err != nil {
return governance.LibraryJob{}, false, fmt.Errorf("create library job stage: %w", err)
}
}
created, err := s.LibraryJob(ctx, id)
return created, false, err
}
func (s *Store) libraryJobByKey(ctx context.Context, key string) (governance.LibraryJob, error) {
var id string
if err := s.db.QueryRow(ctx, `SELECT id FROM library_jobs WHERE idempotency_key=$1`, key).Scan(&id); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return governance.LibraryJob{}, errors.New("library job idempotency key not found")
}
return governance.LibraryJob{}, fmt.Errorf("load library job by key: %w", err)
}
return s.LibraryJob(ctx, id)
}
func (s *Store) LibraryJob(ctx context.Context, id string) (governance.LibraryJob, error) {
var job governance.LibraryJob
var kind, state string
var finished *time.Time
if err := s.db.QueryRow(ctx, `
SELECT id, scope, kind, state, stage, idempotency_key, request_digest, queue_job_id, snapshot_id,
target_snapshot_id, actor, error, recovery, created_at, updated_at, finished_at
FROM library_jobs WHERE id=$1`, id).Scan(&job.ID, &job.Scope, &kind, &state, &job.Stage, &job.IdempotencyKey,
&job.RequestDigest, &job.QueueJobID, &job.SnapshotID, &job.TargetSnapshotID, &job.Actor, &job.Error,
&job.Recovery, &job.CreatedAt, &job.UpdatedAt, &finished); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return governance.LibraryJob{}, err
}
return governance.LibraryJob{}, fmt.Errorf("load library job: %w", err)
}
job.Kind, job.State, job.FinishedAt = governance.LibraryJobKind(kind), governance.LibraryJobState(state), finished
stages, err := s.libraryStages(ctx, id)
if err != nil {
return governance.LibraryJob{}, err
}
job.Stages = stages
return job, nil
}
func (s *Store) libraryStages(ctx context.Context, id string) ([]governance.LibraryStage, error) {
rows, err := s.db.Query(ctx, `
SELECT stage, state, total, completed, bytes_total, bytes_done, detail, updated_at
FROM library_job_stages WHERE job_id=$1 ORDER BY updated_at, stage`, id)
if err != nil {
return nil, fmt.Errorf("load library job stages: %w", err)
}
defer rows.Close()
result := make([]governance.LibraryStage, 0, 7)
for rows.Next() {
var stage governance.LibraryStage
if err := rows.Scan(&stage.Stage, &stage.State, &stage.Total, &stage.Completed, &stage.BytesTotal,
&stage.BytesDone, &stage.Detail, &stage.UpdatedAt); err != nil {
return nil, fmt.Errorf("scan library job stage: %w", err)
}
result = append(result, stage)
}
return result, rows.Err()
}
// ListLibraryJobs 返回某目标最近的作业(按创建时间倒序),供页面在重启后恢复展示。
func (s *Store) ListLibraryJobs(ctx context.Context, scope string, limit int) ([]governance.LibraryJob, error) {
if limit < 1 || limit > 50 {
return nil, errors.New("library job list limit out of range")
}
rows, err := s.db.Query(ctx, `SELECT id FROM library_jobs WHERE scope=$1 ORDER BY created_at DESC, id DESC LIMIT $2`, scope, limit)
if err != nil {
return nil, fmt.Errorf("list library jobs: %w", err)
}
defer rows.Close()
ids := make([]string, 0, limit)
for rows.Next() {
var id string
if err := rows.Scan(&id); err != nil {
return nil, fmt.Errorf("scan library job id: %w", err)
}
ids = append(ids, id)
}
if err := rows.Err(); err != nil {
return nil, err
}
result := make([]governance.LibraryJob, 0, len(ids))
for _, id := range ids {
job, err := s.LibraryJob(ctx, id)
if err != nil {
return nil, err
}
result = append(result, job)
}
return result, nil
}
// UpdateLibraryStage 只改调用方给了值的维度:nil 表示"这一维还没有可靠数据",
// 保持 NULL,绝不写成 0。
func (s *Store) UpdateLibraryStage(ctx context.Context, jobID, stage, state string, total, completed, bytesTotal, bytesDone *int64, detail string, now time.Time) error {
tag, err := s.db.Exec(ctx, `
UPDATE library_job_stages SET
state = CASE WHEN $3='' THEN state ELSE $3 END,
total = COALESCE($4, total),
completed = COALESCE($5, completed),
bytes_total = COALESCE($6, bytes_total),
bytes_done = COALESCE($7, bytes_done),
detail = CASE WHEN $8='' THEN detail ELSE $8 END,
updated_at = $9
WHERE job_id=$1 AND stage=$2`, jobID, stage, state, total, completed, bytesTotal, bytesDone, detail, now.UTC())
if err != nil {
return fmt.Errorf("update library stage: %w", err)
}
if tag.RowsAffected() != 1 {
return errors.New("library stage not found")
}
return nil
}
// AttachLibraryQueueJob 把队列作业号写到已建的业务作业上(两步创建,避免先入队后才发现互斥冲突)。
func (s *Store) AttachLibraryQueueJob(ctx context.Context, jobID, queueJobID string, now time.Time) error {
tag, err := s.db.Exec(ctx, `UPDATE library_jobs SET queue_job_id=$2, updated_at=$3 WHERE id=$1`, jobID, queueJobID, now.UTC())
if err != nil {
return fmt.Errorf("attach library queue job: %w", err)
}
if tag.RowsAffected() != 1 {
return errors.New("library job not found")
}
return nil
}
func (s *Store) CancelLibraryJob(ctx context.Context, jobID, reason string, now time.Time) error {
return s.AdvanceLibraryJob(ctx, jobID, governance.LibraryJobCancelled, "", reason, "", "", "", now)
}
func (s *Store) AdvanceLibraryJob(ctx context.Context, jobID string, state governance.LibraryJobState, stage, message, recovery, snapshotID, targetSnapshotID string, now time.Time) error {
finished := any(nil)
if state == governance.LibraryJobSucceeded || state == governance.LibraryJobFailed || state == governance.LibraryJobCancelled {
finished = now.UTC()
}
tag, err := s.db.Exec(ctx, `
UPDATE library_jobs SET
state=$2,
stage = CASE WHEN $3='' THEN stage ELSE $3 END,
error = CASE WHEN $4='' THEN error ELSE $4 END,
recovery = CASE WHEN $5='' THEN recovery ELSE $5 END,
snapshot_id = CASE WHEN $6='' THEN snapshot_id ELSE $6 END,
target_snapshot_id = CASE WHEN $7='' THEN target_snapshot_id ELSE $7 END,
updated_at=$8,
finished_at=COALESCE($9, finished_at)
WHERE id=$1`, jobID, string(state), stage, message, recovery, snapshotID, targetSnapshotID, now.UTC(), finished)
if err != nil {
return fmt.Errorf("advance library job: %w", err)
}
if tag.RowsAffected() != 1 {
return errors.New("library job not found")
}
return nil
}
// RecordLibraryVersion 写入一个版本记录。生产生效版本必须先把旧的 supersede 掉,
// 否则唯一索引会拒绝——这正是"不许两个生效版本并存"的保证。
func (s *Store) RecordLibraryVersion(ctx context.Context, version governance.LibraryVersion) error {
evidence, err := json.Marshal(version.Evidence)
if err != nil {
return fmt.Errorf("encode library version evidence: %w", err)
}
tx, err := s.db.Begin(ctx)
if err != nil {
return fmt.Errorf("begin library version: %w", err)
}
defer func() { _ = tx.Rollback(ctx) }()
if version.Kind == governance.LibraryVersionProductionEffective {
if _, err := tx.Exec(ctx, `
UPDATE library_versions SET superseded_at=$2
WHERE scope=$1 AND kind='production_effective' AND superseded_at IS NULL`, version.Scope, version.CreatedAt.UTC()); err != nil {
return fmt.Errorf("supersede library version: %w", err)
}
}
if _, err := tx.Exec(ctx, `
INSERT INTO library_versions (id, scope, kind, snapshot_id, version_label, source_job_id, evidence, created_by, created_at)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)
ON CONFLICT (id) DO NOTHING`,
version.ID, version.Scope, string(version.Kind), version.SnapshotID, version.VersionLabel,
version.SourceJobID, evidence, version.CreatedBy, version.CreatedAt.UTC()); err != nil {
return fmt.Errorf("record library version: %w", err)
}
return tx.Commit(ctx)
}
func (s *Store) LibraryVersions(ctx context.Context, scope string, limit int) ([]governance.LibraryVersion, error) {
if limit < 1 || limit > 100 {
return nil, errors.New("library version limit out of range")
}
rows, err := s.db.Query(ctx, `
SELECT id, scope, kind, snapshot_id, version_label, source_job_id, evidence, created_by, created_at, superseded_at
FROM library_versions WHERE scope=$1 ORDER BY created_at DESC, id DESC LIMIT $2`, scope, limit)
if err != nil {
return nil, fmt.Errorf("list library versions: %w", err)
}
defer rows.Close()
result := make([]governance.LibraryVersion, 0, limit)
for rows.Next() {
var item governance.LibraryVersion
var kind string
var evidence []byte
if err := rows.Scan(&item.ID, &item.Scope, &kind, &item.SnapshotID, &item.VersionLabel, &item.SourceJobID,
&evidence, &item.CreatedBy, &item.CreatedAt, &item.SupersededAt); err != nil {
return nil, fmt.Errorf("scan library version: %w", err)
}
item.Kind = governance.LibraryVersionKind(kind)
if len(evidence) > 0 {
_ = json.Unmarshal(evidence, &item.Evidence)
}
result = append(result, item)
}
return result, rows.Err()
}
@@ -0,0 +1,3 @@
DROP TABLE IF EXISTS library_job_stages;
DROP TABLE IF EXISTS library_jobs;
DROP TABLE IF EXISTS library_versions;
@@ -0,0 +1,57 @@
-- 整库版本与作业:把"测试封存 / 生产生效 / 生产预备份"三种版本与持久作业分开记录。
-- 现有 jobs 表是队列与租约;这里记录业务身份、阶段与结果,重启后仍可读。
CREATE TABLE library_versions (
id VARCHAR(64) PRIMARY KEY,
scope VARCHAR(16) NOT NULL CHECK (scope IN ('internal','external')),
kind VARCHAR(24) NOT NULL CHECK (kind IN ('test_sealed','production_effective','production_prebackup')),
snapshot_id VARCHAR(64) NOT NULL DEFAULT '',
version_label VARCHAR(64) NOT NULL DEFAULT '',
source_job_id VARCHAR(64) NOT NULL DEFAULT '',
evidence JSONB NOT NULL DEFAULT '{}'::jsonb,
created_by VARCHAR(128) NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL,
superseded_at TIMESTAMPTZ
);
CREATE INDEX library_versions_scope_kind ON library_versions(scope, kind, created_at DESC, id DESC);
-- 每个目标只有一个"当前生产生效版本";写入新版本时旧的必须先被 supersede。
CREATE UNIQUE INDEX library_versions_effective ON library_versions(scope)
WHERE kind = 'production_effective' AND superseded_at IS NULL;
CREATE TABLE library_jobs (
id VARCHAR(64) PRIMARY KEY,
scope VARCHAR(16) NOT NULL CHECK (scope IN ('internal','external')),
kind VARCHAR(16) NOT NULL CHECK (kind IN ('seal','sync')),
state VARCHAR(16) NOT NULL CHECK (state IN ('pending','running','succeeded','failed','cancelled')),
stage VARCHAR(32) NOT NULL DEFAULT '',
idempotency_key VARCHAR(255) NOT NULL,
request_digest VARCHAR(64) NOT NULL,
request JSONB NOT NULL DEFAULT '{}'::jsonb,
queue_job_id VARCHAR(64) NOT NULL DEFAULT '',
snapshot_id VARCHAR(64) NOT NULL DEFAULT '',
target_snapshot_id VARCHAR(64) NOT NULL DEFAULT '',
actor VARCHAR(128) NOT NULL DEFAULT '',
error TEXT NOT NULL DEFAULT '',
recovery VARCHAR(255) NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL,
finished_at TIMESTAMPTZ
);
CREATE UNIQUE INDEX library_jobs_idempotency ON library_jobs(idempotency_key);
-- 同一目标同一类作业只能有一个在飞:互斥由数据库保证,不依赖前端或单 worker 部署。
CREATE UNIQUE INDEX library_jobs_active ON library_jobs(scope, kind)
WHERE state IN ('pending','running');
CREATE INDEX library_jobs_recent ON library_jobs(scope, created_at DESC, id DESC);
CREATE TABLE library_job_stages (
job_id VARCHAR(64) NOT NULL REFERENCES library_jobs(id) ON DELETE CASCADE,
stage VARCHAR(32) NOT NULL,
state VARCHAR(16) NOT NULL DEFAULT 'pending' CHECK (state IN ('pending','running','succeeded','failed','skipped')),
-- NULL 表示"总量未知":绝不能当成 0,也不据此算百分比。
total BIGINT,
completed BIGINT,
bytes_total BIGINT,
bytes_done BIGINT,
detail TEXT NOT NULL DEFAULT '',
updated_at TIMESTAMPTZ NOT NULL,
PRIMARY KEY (job_id, stage)
);
+12
View File
@@ -132,6 +132,18 @@ RETURNING job_id
SELECT id FROM updated
`
// One job type, newest first: a caller which needs "the recent jobs of MY type"
// must not page the global queue (other traffic would hide its own rows).
const listJobsByTypeSQL = `
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 type = $1
ORDER BY created_at DESC, id DESC
LIMIT $2
`
const listJobsSQL = `
SELECT id, type, payload, state, priority, available_at,
lease_owner, lease_until, attempt, max_attempts,
+25
View File
@@ -65,6 +65,31 @@ func (s *Store) Claim(ctx context.Context, workerID string, allowedTypes []strin
return job, nil
}
// ListByType lists only the requested job type, so a busy queue cannot hide the
// caller's own recent jobs behind unrelated traffic.
func (s *Store) ListByType(ctx context.Context, jobType string, limit int) ([]jobs.Job, error) {
if strings.TrimSpace(jobType) == "" || limit < 1 || limit > 200 {
return nil, errors.New("list jobs by type requires a type and a bounded limit")
}
rows, err := s.db.Query(ctx, listJobsByTypeSQL, jobType, limit)
if err != nil {
return nil, fmt.Errorf("list jobs by type: %w", err)
}
defer rows.Close()
result := make([]jobs.Job, 0, limit)
for rows.Next() {
job, err := scanJob(rows)
if err != nil {
return nil, fmt.Errorf("scan listed job: %w", err)
}
result = append(result, *job)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate jobs: %w", err)
}
return result, nil
}
func (s *Store) List(ctx context.Context, limit int) ([]jobs.Job, error) {
rows, err := s.db.Query(ctx, listJobsSQL, limit)
if err != nil {
@@ -15,6 +15,11 @@ type LibraryCaptureRequest struct {
Compatibility librarysnapshot.Compatibility
CreatedAt time.Time
MaxDocuments int
// VerifyContract, when set, runs inside the stopped window immediately before
// the export. The caller re-reads the source contract and returns an error if
// it differs from Compatibility, so a model/index change between the
// preflight read and the maintenance window cannot be sealed silently.
VerifyContract func(context.Context) error
}
// CaptureLibrary connects maintenance to the actual PG/PIT/object archive path.
@@ -45,6 +50,11 @@ func CaptureLibrary(ctx context.Context, freeze *libraryfreeze.Coordinator, arch
if err := sourceReady(ctx); err != nil {
return "", err
}
if req.VerifyContract != nil {
if err := req.VerifyContract(ctx); err != nil {
return "", err
}
}
pg, err := ExportLibrary(ctx, db, req.Identity)
if err != nil {
return "", err
@@ -2,6 +2,7 @@ package v071
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
@@ -14,6 +15,8 @@ import (
"knowledge-governance/internal/librarysnapshot"
)
var errTestContractChanged = errors.New("source contract changed inside the maintenance window")
type captureWriter struct {
running atomic.Bool
db *libraryFixture
@@ -38,6 +41,85 @@ func (c *captureWriter) Stop(context.Context, string) error {
return nil
}
func (c *captureWriter) Start(context.Context, string) error { c.running.Store(true); return nil }
// The contract is read before the window and must be re-checked inside it: a
// model or mapping change between those two moments must abort, restore writers
// and seal nothing.
func TestLibraryCaptureRechecksContractInsideFrozenWindow(t *testing.T) {
writer := &captureWriter{db: newLibraryFixture()}
writer.running.Store(true)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/chunks/_mapping":
fmt.Fprint(w, `{"chunks":{"mappings":{"properties":{"knowledge_base_id":{"type":"keyword"},"knowledge_id":{"type":"keyword"},"tenant_id":{"type":"long"}}}}}`)
case "/chunks/_pit":
fmt.Fprint(w, `{"id":"fixed-pit"}`)
case "/_search":
fmt.Fprint(w, `{"timed_out":false,"_shards":{"total":1,"successful":1,"failed":0},"hits":{"total":{"value":0,"relation":"eq"},"hits":[]}}`)
case "/_pit":
fmt.Fprint(w, `{"succeeded":true}`)
default:
http.Error(w, "unexpected", 400)
}
}))
defer server.Close()
search, err := NewSearchExporter(SearchExporterConfig{BaseURL: server.URL, Index: "chunks", PageSize: 10})
if err != nil {
t.Fatal(err)
}
mapping, err := search.inspectMapping(context.Background())
if err != nil {
t.Fatal(err)
}
root := t.TempDir()
_ = os.Chmod(root, 0700)
freeze, err := libraryfreeze.Open(root, "test-source", writer)
if err != nil {
t.Fatal(err)
}
defer freeze.Close()
archiveRoot := t.TempDir()
_ = os.Chmod(archiveRoot, 0700)
archive, err := librarysnapshot.Open(archiveRoot, 1024*1024)
if err != nil {
t.Fatal(err)
}
defer archive.Close()
req := LibraryCaptureRequest{JobID: "contract-job", Scope: "internal",
Identity: PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"},
Compatibility: librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74,
RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "fixture-model", EmbeddingDimension: 1024,
IndexMappingSHA256: mapping.digest},
CreatedAt: time.Date(2026, 10, 28, 0, 0, 0, 0, time.UTC), MaxDocuments: 100}
called := 0
req.VerifyContract = func(context.Context) error {
called++
if writer.running.Load() {
t.Error("contract re-check ran before writers stopped")
}
return errTestContractChanged
}
ready := func(context.Context) error { return nil }
result, err := CaptureLibrary(context.Background(), freeze, archive, dbFixture(t, writer), search, &libraryCandidateReader{}, ready, req)
if err == nil || result.State == "succeeded" || result.SnapshotID != "" {
t.Fatalf("contract change was sealed: %+v %v", result, err)
}
if called != 1 {
t.Fatalf("contract re-check called %d times", called)
}
if !writer.running.Load() {
t.Fatal("writer left stopped after a contract abort")
}
if usage, usageErr := archive.Usage(); usageErr != nil || len(usage) != 0 {
t.Fatalf("aborted capture left an artifact: %v %v", usage, usageErr)
}
}
func dbFixture(t *testing.T, writer *captureWriter) *libraryFixture {
t.Helper()
return writer.db
}
func TestLibraryCaptureMaintenanceOwnsArchiveAndRestoresOnFailure(t *testing.T) {
for _, mode := range []string{"success", "initial-busy", "late-pending", "search-failure", "other-library-busy", "other-library-late-pending"} {
t.Run(mode, func(t *testing.T) {
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env bash
# Install/refresh the host-side library capture agent.
#
# The agent is the only component with the Docker socket and the source
# credentials. It runs as this user (no root), listens on one 0600 unix socket and
# executes the fixed capture command with the declaration below. Containers get
# the socket path only.
set -euo pipefail
ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
UNIT_DIR="$HOME/.config/systemd/user"
SOCKET_DIR="$HOME/.local/share/knowledge-governance/agent"
mkdir -p "$UNIT_DIR" "$SOCKET_DIR"
chmod 700 "$SOCKET_DIR"
echo "=== build libraryctl + libraryagent ==="
(cd "$ROOT" && go build -o libraryctl ./cmd/libraryctl && go build -o libraryagent ./cmd/libraryagent)
echo "=== systemd user unit ==="
cat > "$UNIT_DIR/knowledge-governance-library-agent.service" <<UNIT
[Unit]
Description=Knowledge governance whole-library capture agent (host-side execution boundary)
After=network.target
[Service]
Type=simple
WorkingDirectory=$ROOT
ExecStart=$ROOT/libraryagent \\
-socket $SOCKET_DIR/agent.sock \\
-binary $ROOT/libraryctl \\
-archive $HOME/.local/share/knowledge-governance/library \\
-journal $HOME/.local/share/knowledge-governance/freeze \\
-project weknora071full \\
-writers app
Restart=always
RestartSec=5
[Install]
WantedBy=default.target
UNIT
echo "=== enable + restart ==="
systemctl --user daemon-reload
systemctl --user enable knowledge-governance-library-agent.service >/dev/null
systemctl --user restart knowledge-governance-library-agent.service
# Keep the agent running when no login session is open (it owns no privilege
# beyond this account, but a stopped agent means the page cannot capture).
loginctl enable-linger "$(id -un)" >/dev/null 2>&1 || echo " WARN: enable-linger failed; agent stops with the last session"
echo "=== read back ==="
for _ in $(seq 1 30); do
if [ -S "$SOCKET_DIR/agent.sock" ]; then break; fi
sleep 0.2
done
[ -S "$SOCKET_DIR/agent.sock" ] || { echo "AGENT_SOCKET_MISSING"; exit 1; }
stat -c '%A %n' "$SOCKET_DIR" "$SOCKET_DIR/agent.sock"
systemctl --user is-active knowledge-governance-library-agent.service
+10 -7
View File
@@ -4,7 +4,7 @@ import { DocumentWorkbench } from './DocumentWorkbench'
import { SourceCatalogBrowser } from './SourceCatalogBrowser'
import { WeKnoraMonitor } from './WeKnoraMonitor'
import { VersionHistory } from './VersionHistory'
import { LibraryVersions } from './LibraryVersions'
import { ReleaseTargets } from './ReleaseTargets'
import { QAOperations } from './QAOperations'
import { SourceLinkManager } from './SourceLinkManager'
import { SystemSettings } from './SystemSettings'
@@ -63,7 +63,6 @@ const modules: ReadonlyArray<{ id: ModuleId; label: string; icon: string }> = [
{ id: 'tasks', label: '解析监控', icon: '↻' },
{ id: 'qaops', label: '问答运营', icon: '▤' },
{ id: 'releases', label: '发布管理', icon: '⇧' },
{ id: 'library', label: '整库版本', icon: '▦' },
{ id: 'settings', label: '系统设置', icon: '⚙' },
{ id: 'versions', label: '版本记录', icon: '⌥' },
]
@@ -409,7 +408,11 @@ export function ModulePage({
}
if (moduleId === 'releases') {
return (
<ReleaseManagement
<div className="release-module">
<ReleaseTargets />
<details className="release-legacy">
<summary>文档级发布(旧流程,折叠保留):单篇文档发布成功不等于整库发布成功</summary>
<ReleaseManagement
reviewPage={reviewPage}
reviewLoading={reviewLoading}
reviewError={reviewError}
@@ -451,8 +454,10 @@ export function ModulePage({
onStartReleaseAction={onStartReleaseAction}
onReleaseActionPhrase={onReleaseActionPhrase}
onSubmitReleaseAction={onSubmitReleaseAction}
onCancelReleaseAction={onCancelReleaseAction}
/>
onCancelReleaseAction={onCancelReleaseAction}
/>
</details>
</div>
)
}
if (moduleId === 'settings') {
@@ -2972,8 +2977,6 @@ export default function App() {
<SystemSettings />
) : workspace.activeTab === 'knowledge' ? (
<DocumentWorkbench mode="attention" connections={connectionPage.items} />
) : workspace.activeTab === 'library' ? (
<LibraryVersions />
) : workspace.activeTab === 'versions' ? (
<VersionHistory />
) : workspace.activeTab === 'qaops' ? (
+79
View File
@@ -0,0 +1,79 @@
import { useEffect, useState } from 'react'
import { fetchLibrarySnapshots, formatBytes, type LibrarySnapshotList } from './librarySnapshots'
import './libraryStorage.css'
// 系统设置 → 存储管理:只读展示整库归档的真实口径。
// 保留策略、依赖保护、清理预览都没有实现,自动清理保持关闭——页面不能暗示可以删。
export function LibraryStorageSection() {
const [page, setPage] = useState<LibrarySnapshotList | null>(null)
const [error, setError] = useState<string | null>(null)
const [loading, setLoading] = useState(true)
useEffect(() => {
const controller = new AbortController()
fetchLibrarySnapshots(controller.signal)
.then((value) => {
setPage(value)
setError(null)
})
.catch((loadError) => {
if ((loadError as Error).name === 'AbortError') return
setError(loadError instanceof Error ? loadError.message : '读取归档用量失败')
})
.finally(() => setLoading(false))
return () => controller.abort()
}, [])
return (
<section className="library-storage" aria-label="存储管理">
<header>
<h3>版本快照与归档占用</h3>
<p>只读口径:被版本引用的去重内容、blob 文件表观/实际分配字节、未被引用对象、清单文件。</p>
</header>
{loading ? <p className="library-storage-hint">读取中…</p> : null}
{error ? (
<div className="library-storage-blocked">
<strong>读取失败</strong>
<p>{error}</p>
</div>
) : null}
{page && !page.available ? <p className="library-storage-hint">{page.reason || '归档未接线'}</p> : null}
{page?.available ? (
<dl className="library-storage-grid">
<div>
<dt>版本数</dt>
<dd>{page.versions}</dd>
</div>
<div>
<dt>被版本引用的去重内容</dt>
<dd>{formatBytes(page.content_bytes)}</dd>
</div>
<div>
<dt>blob 文件(表观)</dt>
<dd>{formatBytes(page.blob_file_bytes)}</dd>
</div>
<div>
<dt>blob 实际分配</dt>
<dd>{formatBytes(page.blob_allocated_bytes)}</dd>
</div>
<div>
<dt>未被任何版本引用</dt>
<dd>
{page.unreferenced_blobs} 个 / {formatBytes(page.unreferenced_bytes)}
</dd>
</div>
<div>
<dt>清单文件</dt>
<dd>{formatBytes(page.manifest_file_bytes)}</dd>
</div>
</dl>
) : null}
<ul className="library-storage-limits">
<li>保留策略:未接线(不提供保留几版/多少天的设置)</li>
<li>依赖保护与清理预览:未接线</li>
<li>自动清理:保持关闭,页面不提供删除动作</li>
<li>以上数字都不是“可回收空间”,不能用来估算清理收益</li>
</ul>
</section>
)
}
-258
View File
@@ -1,258 +0,0 @@
import { useCallback, useEffect, useMemo, useState } from 'react'
import {
fetchLibrarySnapshots,
formatBytes,
scopeLabel,
type LibrarySnapshot,
type LibrarySnapshotList,
} from './librarySnapshots'
import './libraryVersions.css'
// 「整库版本」页:只读展示已封存的整库候选产物(对内/对外各一份最新)。
// 页面不提供封存按钮:封存要停真实写入者并读来源凭据,只能在目标主机用
// scripts/library-capture.sh 执行。候选 != 验收通过,也 != 可发布。
const stamp = (value: string) =>
value && Number.isFinite(new Date(value).getTime())
? new Date(value).toLocaleString('zh-CN', {
timeZone: 'Asia/Shanghai',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hour12: false,
})
: '—'
const metric = (snapshot: LibrarySnapshot, key: string) => String(snapshot.totals[key] ?? 0)
export function LibraryVersions() {
const [page, setPage] = useState<LibrarySnapshotList | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [expanded, setExpanded] = useState<string | null>(null)
const [scopeFilter, setScopeFilter] = useState<'all' | 'internal' | 'external'>('all')
const load = useCallback(async (signal?: AbortSignal) => {
setLoading(true)
try {
const result = await fetchLibrarySnapshots(signal)
setPage(result)
setError(null)
} catch (loadError) {
if ((loadError as Error).name === 'AbortError') return
setError(loadError instanceof Error ? loadError.message : '加载整库版本失败')
} finally {
setLoading(false)
}
}, [])
useEffect(() => {
const controller = new AbortController()
void load(controller.signal)
return () => controller.abort()
}, [load])
const snapshots = page?.snapshots ?? []
const latestByScope = useMemo(() => {
const map: Record<string, LibrarySnapshot | undefined> = {}
for (const snapshot of snapshots) {
if (!map[snapshot.scope]) map[snapshot.scope] = snapshot
}
return map
}, [snapshots])
const visible = snapshots.filter((snapshot) => scopeFilter === 'all' || snapshot.scope === scopeFilter)
return (
<section className="library-versions" aria-label="整库版本">
<header className="library-versions-header">
<div>
<h2>整库版本</h2>
<p className="library-versions-sub">
每个条目是一份<b>完整封存</b>的整库候选:数据库十表、原始索引正文与向量、对象资源与 Wiki 快照,
带逐项摘要与兼容契约。封存期间真实写入者被停住,完成后已恢复。
</p>
</div>
<div className="library-versions-actions">
<span className="library-versions-usage">
共 {snapshots.length} 份 · 归档占用 {formatBytes(page?.stored_bytes ?? 0)}
</span>
<button type="button" onClick={() => void load()} disabled={loading}>
{loading ? '刷新中…' : '刷新'}
</button>
</div>
</header>
{page && !page.available ? (
<div className="library-versions-blocked">
<strong>未接线</strong>
<p>{page.reason || '归档根未配置'}</p>
</div>
) : null}
{error ? (
<div className="library-versions-blocked">
<strong>读取失败</strong>
<p>{error}</p>
</div>
) : null}
{page?.available ? (
<>
<div className="library-versions-scopes">
{(['internal', 'external'] as const).map((scope) => {
const latest = latestByScope[scope]
return (
<article key={scope} className={`library-scope-card ${latest ? '' : 'empty'}`}>
<header>
<h3>{scopeLabel(scope)}</h3>
<span className="library-scope-state">{latest ? '已封存' : '尚无封存'}</span>
</header>
{latest ? (
<>
<p className="library-scope-time">封存于 {stamp(latest.created_at)}</p>
<dl className="library-scope-metrics">
<div>
<dt>文档</dt>
<dd>{metric(latest, 'documents')}</dd>
</div>
<div>
<dt>分块</dt>
<dd>{metric(latest, 'chunks')}</dd>
</div>
<div>
<dt>索引</dt>
<dd>{metric(latest, 'index_documents')}</dd>
</div>
<div>
<dt>资源</dt>
<dd>{metric(latest, 'resources')}</dd>
</div>
<div>
<dt>Wiki 页</dt>
<dd>{metric(latest, 'wiki_pages')}</dd>
</div>
<div>
<dt>体积</dt>
<dd>{formatBytes(latest.logical_bytes)}</dd>
</div>
</dl>
<p className="library-scope-id">
快照 <code>{latest.snapshot_id.slice(0, 16)}</code>
</p>
</>
) : (
<p className="library-scope-hint">
该库没有封存产物。封存在目标主机执行:
<code>scripts/library-capture.sh capture -scope {scope}</code>
</p>
)}
</article>
)
})}
</div>
<div className="library-versions-toolbar">
<div className="library-versions-filters" role="group" aria-label="按范围筛选">
{(
[
{ id: 'all', label: '全部' },
{ id: 'internal', label: '对内' },
{ id: 'external', label: '对外' },
] as const
).map((item) => (
<button
key={item.id}
type="button"
className={scopeFilter === item.id ? 'active' : ''}
onClick={() => setScopeFilter(item.id)}
>
{item.label}
</button>
))}
</div>
<span className="library-versions-note">{page.capture_note}</span>
</div>
{visible.length === 0 ? (
<p className="library-versions-empty">还没有封存产物。</p>
) : (
<table className="library-versions-table">
<thead>
<tr>
<th>封存时间</th>
<th>范围</th>
<th>文档</th>
<th>分块</th>
<th>索引</th>
<th>资源</th>
<th>Wiki</th>
<th>体积</th>
<th>模型 / 维度</th>
<th>快照</th>
</tr>
</thead>
<tbody>
{visible.map((snapshot) => (
<tr key={snapshot.snapshot_id}>
<td>{stamp(snapshot.created_at)}</td>
<td>{scopeLabel(snapshot.scope)}</td>
<td>{metric(snapshot, 'documents')}</td>
<td>{metric(snapshot, 'chunks')}</td>
<td>{metric(snapshot, 'index_documents')}</td>
<td>{metric(snapshot, 'resources')}</td>
<td>{metric(snapshot, 'wiki_pages')}</td>
<td title={`逻辑 ${snapshot.logical_bytes} 字节 · 去重后 ${snapshot.unique_bytes} 字节`}>
{formatBytes(snapshot.logical_bytes)}
</td>
<td>
{snapshot.compatibility.embedding_model || '—'} / {snapshot.compatibility.embedding_dimension}
</td>
<td>
<button
type="button"
className="library-snapshot-toggle"
onClick={() =>
setExpanded(expanded === snapshot.snapshot_id ? null : snapshot.snapshot_id)
}
aria-expanded={expanded === snapshot.snapshot_id}
>
<code>{snapshot.snapshot_id.slice(0, 12)}</code>
{expanded === snapshot.snapshot_id ? ' 收起' : ' 分项'}
</button>
</td>
</tr>
))}
</tbody>
</table>
)}
{visible
.filter((snapshot) => snapshot.snapshot_id === expanded)
.map((snapshot) => (
<div key={snapshot.snapshot_id} className="library-snapshot-parts">
<header>
<strong>{scopeLabel(snapshot.scope)} · {snapshot.snapshot_id}</strong>
<span>
策略 {snapshot.validation_policy || '—'} · WeKnora {snapshot.compatibility.weknora_version} ·
schema {snapshot.compatibility.schema_version} · 映射{' '}
{snapshot.compatibility.index_mapping_sha256.slice(0, 12)}
</span>
</header>
<ul>
{snapshot.parts.map((part) => (
<li key={`${part.kind}-${part.name}`}>
<span className="library-part-kind">{part.kind}</span>
<span className="library-part-name">{part.name}</span>
<span>{part.count} 项</span>
<span>{formatBytes(part.bytes)}</span>
<code title={part.sha256}>{part.sha256.slice(0, 12)}</code>
</li>
))}
</ul>
</div>
))}
</>
) : null}
</section>
)
}
+257
View File
@@ -0,0 +1,257 @@
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, it, vi } from 'vitest'
import { ReleaseTargetsView } from './ReleaseTargets'
import type {
LibraryCaptureJob,
LibraryJobRecord,
LibraryOverview,
LibrarySnapshot,
LibrarySnapshotList,
} from './librarySnapshots'
const internalSnapshot: LibrarySnapshot = {
snapshot_id: 'f992d64ea45bf737a0721a465b5aef2b150ef7757157eb84f3aaf8b6972d98f9',
scope: 'internal',
knowledge_base_id: '0c84a098-d3ed-4b82-a165-e6de9691d6a8',
tenant_id: 10000,
created_at: '2026-10-28T03:34:57.314178223Z',
validation_policy: 'artifact-acceptance-v1',
format: 'weknora-library-snapshot/v1',
compatibility: {
weknora_version: 'v0.7.1',
schema_version: 74,
retriever_engine: 'elasticsearch_v8',
embedding_model: 'text-embedding-v4',
embedding_dimension: 1024,
index_mapping_sha256: 'a'.repeat(64),
},
parts: [
{ kind: 'database', name: 'knowledges', sha256: 'b'.repeat(64), count: 4, bytes: 10654 },
{ kind: 'index', name: 'chunks', sha256: 'c'.repeat(64), count: 122, bytes: 1624880 },
],
logical_bytes: 55309044,
unique_bytes: 55309040,
shared_bytes: 2,
totals: { documents: 4, chunks: 38, index_documents: 122, resources: 21, wiki_pages: 31 },
}
const externalSnapshot: LibrarySnapshot = {
...internalSnapshot,
snapshot_id: '01343b0b310b3977c2fdda05f5b8a6272148c4f7bfa124a6c5944123cf0c51c3',
scope: 'external',
created_at: '2026-10-28T03:35:53.000000000Z',
totals: { documents: 0, chunks: 0, index_documents: 0, resources: 0, wiki_pages: 1 },
}
const runningJob: LibraryCaptureJob = {
job_id: 'library-capture-internal-1',
capture_job: 'lib-internal-20261028T033457',
scope: 'internal',
state: 'running',
attempt: 1,
last_error: '',
requested_by: 'yaozhanghao',
created_at: '2026-10-28T03:34:50Z',
updated_at: '2026-10-28T03:34:55Z',
}
const page: LibrarySnapshotList = {
available: true,
reason: '',
archive_root: '/var/lib/knowledge-governance/library',
snapshots: [internalSnapshot, externalSnapshot],
versions: 2,
content_bytes: 55309693,
blob_file_bytes: 55309693,
blob_allocated_bytes: 55373824,
unreferenced_blobs: 0,
unreferenced_bytes: 0,
manifest_file_bytes: 7544,
manifest_allocated_bytes: 12288,
capture_note: '',
capture_available: true,
capture_reason: '',
}
// 真实接口形状:生产段未知、闸口未开、没有持久作业。
const overview: LibraryOverview = {
scope: 'internal',
test_sealed: internalSnapshot,
production: { state: 'unknown', reason: '还没有生产验证通过的生效版本记录' },
prebackup: { state: 'unknown', reason: '本次目标快照还没有生产预备份' },
diff: {
state: 'unknown',
reason: '生产与测试的文档级差异读取未接线',
added: [],
updated: [],
removed: [],
},
jobs: [],
gate: {
sync_allowed: false,
reasons: [
'生产写入闸口关闭(PRODUCTION_RELEASE_REQUESTS_ENABLED=false)',
'没有已核验的生产恢复演练证据(PRODUCTION_BACKUP_RESTORE_VERIFIED=false)',
'生产当前权威版本未知,不能启动写入',
'本次目标快照还没有生产预备份',
],
},
capture_available: true,
now: '2026-10-28T03:40:00Z',
}
const persistedSeal: LibraryJobRecord = {
id: 'libseal-lib-internal-20261028T033457',
scope: 'internal',
kind: 'seal',
state: 'running',
stage: 'export',
request_digest: 'd'.repeat(64),
queue_job_id: 'library-capture-internal-1',
snapshot_id: '',
target_snapshot_id: '',
actor: 'yaozhanghao',
error: '',
recovery: '',
created_at: '2026-10-28T03:34:50Z',
updated_at: '2026-10-28T03:34:55Z',
finished_at: null,
stages: [
{
stage: 'export',
state: 'running',
total: null,
completed: null,
bytes_total: null,
bytes_done: null,
detail: '主机侧正在暂停写入者、导出并恢复',
updated_at: '2026-10-28T03:34:55Z',
},
],
}
type ViewProps = Parameters<typeof ReleaseTargetsView>[0]
const base: ViewProps = {
page,
jobs: [],
overview,
loading: false,
error: null,
notice: null,
scope: 'internal',
onScope: vi.fn(),
drawerOpen: false,
onDrawer: vi.fn(),
expandedSnapshot: null,
onExpandSnapshot: vi.fn(),
pendingCapture: false,
canCapture: true,
canWrite: true,
now: new Date('2026-10-28T03:35:00Z').getTime(),
onRefresh: vi.fn(),
onCapture: vi.fn(),
}
const render = (overrides: Partial<ViewProps> = {}) => renderToStaticMarkup(<ReleaseTargetsView {...base} {...overrides} />)
describe('ReleaseTargetsView(确认稿布局)', () => {
it('顶部只有两个知识库页签,且一次只显示选中库的作业区', () => {
const html = render()
expect(html).toContain('对内知识库')
expect(html).toContain('对外知识库')
expect(html).toContain('role="tab"')
// 只显示一个主作业卡:选中库标题出现一次,另一个库不渲染作业卡
expect(html.match(/· 已封存,生产同步未接入/g)?.length).toBe(1)
expect(html).not.toContain('对外知识库 · 尚无')
})
it('未接入项显示“未接入/未知”,不用 0 / 无变化冒充', () => {
const html = render()
expect(html).toContain('生产当前')
// 生产没有权威版本时必须写未知,不能拿测试快照顶替
expect(html).toContain('未知(尚未建立权威版本)')
expect(html).toContain('尚无记录 · 生产与测试的文档级差异读取未接线')
expect(html).toContain('未接入')
})
it('“启动同步”保持禁用并逐条说明缺项,不把封存当成同步', () => {
const html = render()
expect(html).toMatch(/<button[^>]*class="rel-primary"[^>]*disabled/)
expect(html).toContain('生产写入闸口关闭')
expect(html).toContain('没有已核验的生产恢复演练证据')
expect(html).toContain('本次目标快照还没有生产预备份')
expect(html).toContain('封存测试版本')
})
it('没有当前作业时不把历史封存当成阶段完成', () => {
const html = render()
// 阶段条第一段必须是 idle(○),"✓" 只允许出现在准备清单,不出现在阶段条
const stageBar = html.slice(html.indexOf('aria-label="作业阶段"'), html.indexOf('rel-steps-note'))
expect(stageBar).not.toContain('✓')
expect(stageBar).toContain('本次作业尚未开始')
expect(html).toContain('已有测试封存')
expect(html).toContain('没有当前作业证据时不会把历史封存当作阶段完成')
})
it('准备信息注明快照时间与范围,不声称实时测试库已就绪', () => {
const html = render()
expect(html).toContain('依据 10/28 11:34 封存的测试库全库快照,不代表实时测试库已就绪')
expect(html).toContain('同一份封存快照,不是实时 Wiki 队列状态')
expect(html).toContain('封存时的逐项校验和,重新封存才会更新')
})
it('版本与快照抽屉按 scope 列出全部历史并区分测试封存/不可直接恢复', () => {
const html = render({ drawerOpen: true, expandedSnapshot: internalSnapshot.snapshot_id })
expect(html).toContain('版本与快照')
expect(html).toContain('封存 f992d64ea45b')
expect(html).toContain('测试封存')
expect(html).toContain('不可直接恢复')
expect(html).toContain('恢复至该版本')
expect(html).toMatch(/恢复至该版本[^<]*<\/button>/)
expect(html).toContain('分项数量 / 字节 / 摘要(2 项)')
expect(html).toContain('不支持只选择 Wiki 或某张数据表恢复')
})
it('抽屉只展示当前选中库的历史', () => {
const html = render({ drawerOpen: true, scope: 'external' })
expect(html).toContain('封存 01343b0b310b')
expect(html).not.toContain('封存 f992d64ea45b')
})
it('同步中布局显示四类数据卡与明细,且不编造百分比', () => {
const html = render({
jobs: [runningJob],
overview: { ...overview, job: persistedSeal, jobs: [persistedSeal] },
})
expect(html).toContain('测试库封存作业')
expect(html).toContain('数据库 · 文档与分块')
expect(html).toContain('原文件 · 图片 · 附件')
expect(html).toContain('检索索引 · 向量')
expect(html).toContain('Wiki · 完整快照')
expect(html).toContain('同步明细')
// 唯一允许出现的百分比是免责声明里的「100% ≠ 作业完成」,没有任何进度主张
expect(html.match(/[1-9]\d*%/g) ?? []).toEqual(['100%'])
expect(html).toContain('文件传输 100% ≠ 作业完成')
expect(html).toContain('不编造百分比')
// 没有真实总量时只写"未知总量",不画百分比
expect(html).toContain('未知总量')
expect(html).toContain('主机侧正在暂停写入者、导出并恢复')
})
it('无权限时不给封存入口,未接线时说明通道状态', () => {
expect(render({ canCapture: false, canWrite: false })).toContain('封存需要知识工程师及以上权限')
const unwired = render({
canCapture: false,
canWrite: true,
page: { ...page, capture_available: false, capture_reason: '主机侧封存 agent 未接线' },
})
expect(unwired).toContain('封存通道未接线')
})
it('无封存时给出“尚无封存”而不是空表', () => {
const html = render({ page: { ...page, snapshots: [] } })
expect(html).toContain('尚无测试封存')
expect(html).toContain('还没有测试库封存')
})
})
File diff suppressed because it is too large Load Diff
+7 -1
View File
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useState } from 'react'
import { BackupScheduleSection } from './BackupScheduleSection'
import { LibraryStorageSection } from './LibraryStorageSection'
import { QAModelSettings } from './QAModelSettings'
import { MembersSection } from './MembersSection'
import { DingtalkAccountStatus, SourceManagementDetails, SourceSettingsCard } from './SourceManagement'
@@ -394,7 +395,12 @@ export function SystemSettingsView({
) : null}
{section === 'bindings' ? <RoutingBindingsSection /> : null}
{section === 'production-bindings' ? <ProductionBindingsSection /> : null}
{section === 'storage' ? <BackupScheduleSection /> : null}
{section === 'storage' ? (
<>
<LibraryStorageSection />
<BackupScheduleSection />
</>
) : null}
{section === 'members' && identity?.role === 'admin' ? <MembersSection /> : null}
{section === 'refresh' ? (
<section className="settings-panel wide" id="settings-refresh">
+176 -3
View File
@@ -37,13 +37,46 @@ export interface LibrarySnapshot {
totals: Record<string, number>
}
export interface LibraryCaptureJob {
job_id: string
capture_job: string
scope: string
state: string
attempt: number
last_error: string
requested_by: string
created_at: string
updated_at: string
}
export interface LibraryCaptureAccepted {
job_id: string
capture_job: string
scope: string
state: string
// true when the idempotency key matched an existing job; the response then
// reports the stored job's scope, not the requested one.
reused: boolean
}
export interface LibrarySnapshotList {
available: boolean
reason: string
archive_root: string
snapshots: LibrarySnapshot[]
stored_bytes: number
// 归档级口径:content_bytes 是跨版本去重后、被版本引用的内容字节;
// 其余字段是文件系统事实,都不是可回收空间。
versions: number
content_bytes: number
blob_file_bytes: number
blob_allocated_bytes: number
unreferenced_blobs: number
unreferenced_bytes: number
manifest_file_bytes: number
manifest_allocated_bytes: number
capture_note: string
capture_available: boolean
capture_reason: string
}
const record = (value: unknown): value is Record<string, unknown> =>
@@ -113,11 +146,65 @@ export async function fetchLibrarySnapshots(signal?: AbortSignal): Promise<Libra
reason: text(value.reason),
archive_root: text(value.archive_root),
snapshots,
stored_bytes: num(value.stored_bytes),
versions: num(value.versions),
content_bytes: num(value.content_bytes),
blob_file_bytes: num(value.blob_file_bytes),
blob_allocated_bytes: num(value.blob_allocated_bytes),
unreferenced_blobs: num(value.unreferenced_blobs),
unreferenced_bytes: num(value.unreferenced_bytes),
manifest_file_bytes: num(value.manifest_file_bytes),
manifest_allocated_bytes: num(value.manifest_allocated_bytes),
capture_note: text(value.capture_note),
capture_available: bool(value.capture_available),
capture_reason: text(value.capture_reason),
}
}
// 页面发起的封存只投递作业;停写入者、导出与恢复都在主机侧 agent 执行。
export async function enqueueLibraryCapture(scope: string): Promise<LibraryCaptureAccepted> {
const response = await fetch('/api/v1/library/captures', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({ scope }),
})
const value = (await response.json().catch(() => null)) as unknown
if (!response.ok) {
if (response.status === 403) throw new Error('只有知识工程师及以上可以发起封存。')
if (response.status === 503 && record(value)) {
throw new Error(text(value.reason) || '主机侧封存 agent 未接线')
}
throw new Error(`发起封存失败(HTTP ${response.status})`)
}
if (!record(value)) throw new Error('封存作业响应无效')
return {
job_id: text(value.job_id),
capture_job: text(value.capture_job),
scope: text(value.scope),
state: text(value.state),
reused: bool(value.reused),
}
}
export async function fetchLibraryCaptures(signal?: AbortSignal): Promise<LibraryCaptureJob[]> {
const response = await fetch('/api/v1/library/captures', {
headers: { Accept: 'application/json' },
signal,
})
const value = (await response.json().catch(() => null)) as unknown
if (!response.ok || !record(value) || !Array.isArray(value.jobs)) return []
return value.jobs.filter(record).map((job) => ({
job_id: text(job.job_id),
capture_job: text(job.capture_job),
scope: text(job.scope),
state: text(job.state),
attempt: num(job.attempt),
last_error: text(job.last_error),
requested_by: text(job.requested_by),
created_at: text(job.created_at),
updated_at: text(job.updated_at),
}))
}
export function formatBytes(bytes: number): string {
if (!Number.isFinite(bytes) || bytes <= 0) return '0 B'
const units = ['B', 'KB', 'MB', 'GB', 'TB']
@@ -134,4 +221,90 @@ export function scopeLabel(scope: string): string {
if (scope === 'internal') return '对内'
if (scope === 'external') return '对外'
return scope || '未知范围'
}
}
// ---- 整库状态:测试封存 / 生产生效 / 生产预备份 三类版本 + 差异 + 持久作业 ----
export interface LibraryVersionRecord {
id: string
kind: 'test_sealed' | 'production_effective' | 'production_prebackup'
snapshot_id: string
version_label: string
source_job_id: string
evidence: Record<string, unknown>
created_by: string
created_at: string
superseded_at?: string | null
}
export interface LibraryKnown {
state: 'known' | 'unknown'
version?: LibraryVersionRecord
reason?: string
}
export interface LibraryDiff {
state: 'unknown' | 'computed'
reason?: string
added: unknown[]
updated: unknown[]
removed: unknown[]
}
export interface LibraryStageRow {
stage: string
state: string
total: number | null
completed: number | null
bytes_total: number | null
bytes_done: number | null
detail: string
updated_at: string
}
export interface LibraryJobRecord {
id: string
scope: string
kind: 'seal' | 'sync'
state: 'pending' | 'running' | 'succeeded' | 'failed' | 'cancelled'
stage: string
request_digest: string
queue_job_id: string
snapshot_id: string
target_snapshot_id: string
actor: string
error: string
recovery: string
created_at: string
updated_at: string
finished_at?: string | null
stages: LibraryStageRow[]
}
export interface LibraryGate {
sync_allowed: boolean
reasons: string[]
}
export interface LibraryOverview {
scope: string
test_sealed?: LibrarySnapshot
test_sealed_reason?: string
production: LibraryKnown
prebackup: LibraryKnown
diff: LibraryDiff
job?: LibraryJobRecord
jobs: LibraryJobRecord[]
gate: LibraryGate
capture_available: boolean
capture_reason?: string
now: string
}
export async function fetchLibraryOverview(scope: string, signal?: AbortSignal): Promise<LibraryOverview | null> {
const response = await fetch(`/api/v1/library/overview?scope=${encodeURIComponent(scope)}`, {
headers: { Accept: 'application/json' },
signal,
})
const value = (await response.json().catch(() => null)) as unknown
if (!record(value)) return null
return value as unknown as LibraryOverview
}
+66
View File
@@ -0,0 +1,66 @@
.library-storage {
border: 1px solid var(--border-base, #e2e8f0);
border-radius: 10px;
padding: 16px 18px;
margin-bottom: 18px;
background: #fff;
}
.library-storage header h3 {
margin: 0 0 4px;
font-size: 16px;
}
.library-storage header p {
margin: 0 0 12px;
font-size: 12px;
color: var(--ink-mute, #64748b);
line-height: 1.6;
}
.library-storage-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 10px;
margin: 0 0 12px;
}
.library-storage-grid div {
border: 1px solid #e6edf2;
border-radius: 8px;
padding: 9px 11px;
}
.library-storage-grid dt {
font-size: 11px;
color: var(--ink-mute, #64748b);
}
.library-storage-grid dd {
margin: 3px 0 0;
font-size: 16px;
font-variant-numeric: tabular-nums;
}
.library-storage-limits {
margin: 0;
padding-left: 18px;
font-size: 12px;
color: #986b24;
line-height: 1.8;
}
.library-storage-hint {
margin: 0;
font-size: 12px;
color: var(--ink-mute, #64748b);
}
.library-storage-blocked {
border: 1px solid #f3c2b8;
background: #fff6f3;
border-radius: 8px;
padding: 10px 12px;
margin-bottom: 10px;
}
.library-storage-blocked strong {
display: block;
font-size: 12px;
color: #a03a1e;
}
.library-storage-blocked p {
margin: 2px 0 0;
font-size: 12px;
color: #7c2d12;
}
-265
View File
@@ -1,265 +0,0 @@
/* Whole-library versions: scope cards first, then a compact sealed-artifact table. */
.library-versions {
display: flex;
flex-direction: column;
gap: 18px;
min-width: 0;
padding: 24px;
color: var(--ink-base);
}
.library-versions-header,
.library-versions-toolbar,
.library-snapshot-parts,
.library-scope-card {
background: var(--bg-panel, #fff);
border: 1px solid var(--border-base, #e2e8f0);
border-radius: 10px;
padding: 20px;
min-width: 0;
}
.library-versions-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
}
.library-versions h2 {
margin: 0 0 6px;
font-size: 22px;
}
.library-versions-sub {
margin: 0;
max-width: 68ch;
color: var(--ink-mute, #64748b);
font-size: 13px;
line-height: 1.6;
}
.library-versions-actions {
display: flex;
align-items: center;
gap: 12px;
flex-shrink: 0;
}
.library-versions-usage {
font-size: 13px;
color: var(--ink-mute, #64748b);
font-variant-numeric: tabular-nums;
}
.library-versions-actions button,
.library-versions-filters button {
padding: 7px 14px;
border-radius: 8px;
border: 1px solid var(--border-base, #e2e8f0);
background: var(--bg-panel, #fff);
color: inherit;
cursor: pointer;
}
.library-versions-actions button:disabled {
cursor: progress;
opacity: 0.6;
}
.library-versions-blocked {
border: 1px solid #f3c2b8;
background: #fff6f3;
border-radius: 10px;
padding: 16px 20px;
}
.library-versions-blocked strong {
display: block;
margin-bottom: 4px;
color: #a03a1e;
}
.library-versions-blocked p {
margin: 0;
font-size: 13px;
color: #7c2d12;
}
.library-versions-scopes {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
gap: 16px;
}
.library-scope-card header {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
}
.library-scope-card h3 {
margin: 0;
font-size: 18px;
}
.library-scope-state {
font-size: 12px;
padding: 2px 10px;
border-radius: 999px;
background: #ecfdf5;
color: #047857;
border: 1px solid #a7f3d0;
}
.library-scope-card.empty .library-scope-state {
background: #f8fafc;
color: #64748b;
border-color: #e2e8f0;
}
.library-scope-time {
margin: 8px 0 14px;
font-size: 12px;
color: var(--ink-mute, #64748b);
}
.library-scope-metrics {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 10px;
margin: 0 0 12px;
}
.library-scope-metrics div {
border: 1px solid var(--border-base, #e2e8f0);
border-radius: 8px;
padding: 8px 10px;
}
.library-scope-metrics dt {
font-size: 12px;
color: var(--ink-mute, #64748b);
}
.library-scope-metrics dd {
margin: 2px 0 0;
font-size: 18px;
font-variant-numeric: tabular-nums;
}
.library-scope-id,
.library-scope-hint {
margin: 0;
font-size: 12px;
color: var(--ink-mute, #64748b);
overflow-wrap: anywhere;
}
.library-scope-hint code,
.library-scope-id code {
font-size: 12px;
background: #f1f5f9;
border-radius: 5px;
padding: 1px 6px;
}
.library-versions-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 12px 16px;
flex-wrap: wrap;
}
.library-versions-filters {
display: flex;
gap: 8px;
}
.library-versions-filters button.active {
border-color: #2563eb;
color: #1d4ed8;
background: #eff6ff;
}
.library-versions-note {
font-size: 12px;
color: var(--ink-mute, #64748b);
max-width: 70ch;
line-height: 1.5;
}
.library-versions-empty {
margin: 0;
padding: 24px;
border: 1px dashed var(--border-base, #e2e8f0);
border-radius: 10px;
color: var(--ink-mute, #64748b);
font-size: 13px;
}
.library-versions-table {
width: 100%;
border-collapse: collapse;
background: var(--bg-panel, #fff);
border: 1px solid var(--border-base, #e2e8f0);
border-radius: 10px;
overflow: hidden;
font-size: 13px;
}
.library-versions-table th,
.library-versions-table td {
padding: 10px 12px;
text-align: left;
border-bottom: 1px solid var(--border-base, #eef2f7);
white-space: nowrap;
}
.library-versions-table th {
font-weight: 600;
font-size: 12px;
color: var(--ink-mute, #64748b);
background: #f8fafc;
}
.library-versions-table td {
font-variant-numeric: tabular-nums;
}
.library-snapshot-toggle {
border: 1px solid var(--border-base, #e2e8f0);
border-radius: 7px;
background: #fff;
padding: 4px 8px;
cursor: pointer;
font-size: 12px;
color: inherit;
}
.library-snapshot-parts header {
display: flex;
flex-direction: column;
gap: 4px;
margin-bottom: 12px;
font-size: 12px;
color: var(--ink-mute, #64748b);
overflow-wrap: anywhere;
}
.library-snapshot-parts header strong {
font-size: 14px;
color: var(--ink-base);
}
.library-snapshot-parts ul {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 6px;
}
.library-snapshot-parts li {
display: grid;
grid-template-columns: 90px minmax(140px, 2fr) 80px 90px 110px;
gap: 10px;
align-items: center;
font-size: 12px;
padding: 6px 8px;
border-radius: 7px;
background: #f8fafc;
overflow-wrap: anywhere;
}
.library-part-kind {
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--ink-mute, #64748b);
}
.library-part-name {
font-weight: 600;
}
@media (max-width: 760px) {
.library-versions {
padding: 12px;
}
.library-versions-table {
display: block;
overflow-x: auto;
}
.library-snapshot-parts li {
grid-template-columns: 1fr;
}
.library-scope-metrics {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
+600
View File
@@ -0,0 +1,600 @@
/* 发布管理:按已确认稿的布局与色系(浅底、青绿主色、白色圆角面板)。 */
.release-targets {
--rel-ink: #26394a;
--rel-muted: #7b8d9a;
--rel-line: #dce6ed;
--rel-teal: #269e88;
--rel-teal-dark: #228b75;
--rel-teal-soft: #eaf8f3;
display: flex;
flex-direction: column;
gap: 16px;
padding: 24px 28px 40px;
color: var(--rel-ink);
min-width: 0;
}
.release-targets h1 {
margin: 0 0 4px;
font-size: 28px;
}
.release-targets h2 {
margin: 0;
font-size: 18px;
}
.release-targets h3 {
margin: 0;
font-size: 14px;
}
.rel-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
}
.rel-head p {
margin: 0;
color: var(--rel-muted);
font-size: 13px;
}
.rel-head-actions {
display: flex;
gap: 8px;
align-items: center;
flex-wrap: wrap;
}
.release-targets button {
font: inherit;
cursor: pointer;
background: #fff;
border: 1px solid #d6e2e8;
border-radius: 7px;
padding: 7px 14px;
color: #41596b;
}
.release-targets button:hover:not(:disabled) {
background: #edf8f5;
}
.release-targets button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.rel-primary {
background: var(--rel-teal) !important;
border-color: var(--rel-teal) !important;
color: #fff !important;
font-weight: 600;
}
.rel-secondary {
background: #fff;
}
.rel-tabs {
display: flex;
gap: 12px;
flex-wrap: wrap;
}
.rel-tab {
width: 310px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 13px 18px !important;
text-align: left;
border-radius: 9px !important;
}
.rel-tab strong {
font-size: 16px;
}
.rel-tab.selected {
background: var(--rel-teal-soft) !important;
border: 2px solid var(--rel-teal) !important;
}
.rel-pill {
border-radius: 5px;
font-size: 12px;
padding: 2px 9px;
white-space: nowrap;
border: 1px solid transparent;
}
.rel-pill.green {
color: #228368;
background: #e6f5ef;
border-color: #bfe6d8;
}
.rel-pill.blue {
color: #387eb8;
background: #eaf3fc;
border-color: #c6ddf1;
}
.rel-pill.gray {
color: #7c8d99;
background: #eff3f6;
border-color: #dde5ea;
}
.rel-pill.red {
color: #b4381f;
background: #fdecea;
border-color: #f3c6bc;
}
.rel-panel {
background: #fff;
border: 1px solid var(--rel-line);
border-radius: 12px;
padding: 20px 22px;
min-width: 0;
}
.rel-between {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 14px;
flex-wrap: wrap;
}
.rel-panel-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
}
.rel-panel-head p {
margin: 3px 0 0;
font-size: 12px;
color: var(--rel-muted);
}
.rel-jobhead h2 {
font-size: 19px;
}
.rel-versionline {
margin: 12px 0 0;
color: #496579;
font-size: 14px;
}
.rel-versionline b {
color: var(--rel-teal-dark);
}
.rel-unknown {
color: #9aa9b4 !important;
font-weight: 500;
}
.rel-metrics {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 10px;
margin: 16px 0 0;
}
.rel-metrics div {
border: 1px solid #e6edf2;
border-radius: 9px;
padding: 10px 12px;
}
.rel-metrics dt {
font-size: 12px;
color: var(--rel-muted);
}
.rel-metrics dd {
margin: 4px 0 0;
font-size: 20px;
font-weight: 700;
}
.rel-checklist {
list-style: none;
display: flex;
gap: 22px;
flex-wrap: wrap;
margin: 14px 0 0;
padding: 11px 14px;
border-radius: 9px;
background: #f2faf6;
font-size: 13px;
color: #228368;
}
.rel-checklist .unknown {
color: #8a9aa6;
}
.rel-footnote {
margin: 12px 0 0;
font-size: 12px;
color: var(--rel-muted);
line-height: 1.6;
}
.rel-grid {
display: grid;
grid-template-columns: minmax(0, 1.6fr) minmax(0, 1fr);
gap: 16px;
}
.rel-grid-4 {
grid-template-columns: repeat(auto-fit, minmax(230px, 1fr));
}
.rel-changes table,
.rel-details table,
.rel-drawer-table,
.rel-parts table {
width: 100%;
border-collapse: collapse;
font-size: 13px;
}
.rel-changes th,
.rel-details th,
.rel-drawer-table th,
.rel-parts th {
text-align: left;
background: #f8fafb;
color: #8a9aa6;
font-size: 12px;
font-weight: 500;
padding: 9px 12px;
}
.rel-changes td,
.rel-details td,
.rel-drawer-table td,
.rel-parts td {
padding: 10px 12px;
border-top: 1px solid #eef2f5;
vertical-align: top;
}
.rel-table-empty {
color: var(--rel-muted);
font-size: 12px;
text-align: center;
padding: 22px 12px !important;
}
.rel-protection dl {
display: grid;
grid-template-columns: auto 1fr;
gap: 8px 14px;
margin: 0 0 12px;
font-size: 13px;
}
.rel-protection dt {
color: var(--rel-muted);
}
.rel-protection dd {
margin: 0;
color: var(--rel-ink);
}
.rel-hint {
margin: 0 0 10px;
font-size: 12px;
color: var(--rel-muted);
line-height: 1.6;
}
.rel-warn {
margin: 12px 0 0;
font-size: 12px;
color: #986b24;
background: #fff8e8;
border: 1px solid #ead7b0;
border-radius: 7px;
padding: 8px 10px;
line-height: 1.6;
}
.rel-notice {
margin: 0;
font-size: 12px;
color: #986b24;
background: #fff8e8;
border: 1px solid #ead7b0;
border-radius: 8px;
padding: 9px 12px;
line-height: 1.6;
}
.rel-blocked {
border: 1px solid #f3c2b8;
background: #fff6f3;
border-radius: 10px;
padding: 12px 16px;
}
.rel-blocked strong {
display: block;
color: #a03a1e;
font-size: 13px;
margin-bottom: 3px;
}
.rel-blocked p {
margin: 0;
font-size: 12px;
color: #7c2d12;
}
/* 阶段条 */
.rel-steps {
display: flex;
align-items: stretch;
gap: 8px;
list-style: none;
margin: 16px 0 6px;
padding: 0;
flex-wrap: wrap;
}
.rel-step {
flex: 1 1 150px;
position: relative;
display: flex;
flex-direction: column;
gap: 2px;
padding: 11px 12px;
border-radius: 8px;
background: #f5f8fa;
border: 1px solid #e1e8ed;
color: #8a9aa6;
font-size: 13px;
}
.rel-step strong {
font-size: 13px;
font-weight: 600;
}
.rel-step small {
font-size: 11px;
}
.rel-step.done {
color: #25886b;
background: #f0faf5;
}
.rel-step.live {
color: #167f70;
background: #e9f8f4;
border-color: #4eb49f;
font-weight: 700;
}
.rel-step-mark {
position: absolute;
top: 9px;
right: 12px;
font-size: 12px;
}
.rel-step-arrow {
display: none;
}
.rel-steps-note {
margin: 0;
font-size: 12px;
color: var(--rel-muted);
line-height: 1.6;
}
/* 仅剩的次级操作:封存测试版本 */
.rel-seal {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
background: #fbfdfe;
}
.rel-seal p {
margin: 6px 0 0;
font-size: 12px;
color: var(--rel-muted);
line-height: 1.6;
}
/* 同步中 */
.rel-jobmeta {
margin: 8px 0 0;
font-size: 12px;
color: var(--rel-muted);
}
.rel-progress-foot {
margin-top: 12px;
border-top: 1px solid #eef2f5;
padding-top: 10px;
font-size: 12px;
color: var(--rel-muted);
}
.rel-link {
border: 0 !important;
background: transparent !important;
padding: 2px 4px !important;
color: #2b7fa6 !important;
font-size: 12px;
}
.rel-datacard {
border: 1px solid #dce6ed;
border-radius: 10px;
padding: 14px 16px;
background: #fff;
}
.rel-datacard header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.rel-datacount {
margin: 10px 0 6px;
font-size: 13px;
color: var(--rel-muted);
}
.rel-datacount strong {
font-size: 24px;
color: #9aa9b4;
margin-right: 4px;
}
.rel-progress {
height: 6px;
border-radius: 8px;
background: #edf1f4;
overflow: hidden;
}
.rel-progress span {
display: block;
height: 100%;
background: var(--rel-teal);
}
.rel-datadetail {
margin: 10px 0 0;
font-size: 12px;
color: var(--rel-muted);
line-height: 1.55;
}
.rel-filters {
display: flex;
gap: 6px;
}
.rel-filters button {
font-size: 12px;
padding: 4px 11px;
}
.rel-filters .chosen {
color: #168b73;
background: #ebf8f3;
border-color: #a6d7c8;
}
.rel-log {
display: flex;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
background: #f9fbfc;
border-top: 1px solid #eef2f5;
padding: 10px 12px;
font-size: 12px;
color: #7b8e9c;
}
/* 版本与快照抽屉 */
.rel-drawer-backdrop {
position: fixed;
inset: 0;
background: rgba(20, 52, 74, 0.4);
display: flex;
justify-content: flex-end;
z-index: 40;
}
.rel-drawer {
width: min(1024px, 92vw);
height: 100%;
overflow-y: auto;
background: #fff;
border-left: 1px solid #dce6ed;
box-shadow: -12px 0 32px rgba(19, 44, 61, 0.18);
padding: 22px 26px 28px;
display: flex;
flex-direction: column;
gap: 14px;
}
.rel-drawer-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
}
.rel-drawer-head p {
margin: 4px 0 0;
font-size: 12px;
color: var(--rel-muted);
}
.rel-close {
padding: 5px 10px !important;
font-size: 12px;
}
.rel-drawer-table td small {
display: block;
color: var(--rel-muted);
font-size: 11px;
margin-top: 2px;
}
.rel-drawer-table tr.selected td {
background: #f4fbf8;
}
.rel-snapshot {
border: 1px solid #cfe6dd;
border-radius: 10px;
padding: 16px 18px;
background: #fbfefd;
}
.rel-snapshot header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 8px;
}
.rel-snapshot-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 10px;
margin: 12px 0;
}
.rel-snapshot-grid div {
border: 1px solid #e2eef7;
border-radius: 8px;
background: #fff;
padding: 9px 11px;
}
.rel-snapshot-grid dt {
font-size: 11px;
color: var(--rel-muted);
}
.rel-snapshot-grid dd {
margin: 4px 0 0;
font-size: 13px;
}
.rel-parts {
margin: 8px 0 12px;
}
.rel-parts summary {
cursor: pointer;
font-size: 12px;
color: #2b7fa6;
}
.rel-parts table {
margin-top: 8px;
border: 1px solid #e6edf2;
border-radius: 8px;
overflow: hidden;
}
.rel-drawer-actions {
display: flex;
gap: 8px;
flex-wrap: wrap;
}
.rel-danger {
border-color: #e7b4a8 !important;
color: #b4381f !important;
}
.rel-drawer-foot {
margin-top: auto;
border-top: 1px solid #eef2f5;
padding-top: 14px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
flex-wrap: wrap;
}
.rel-drawer-foot p {
margin: 4px 0 0;
font-size: 12px;
color: var(--rel-muted);
line-height: 1.6;
max-width: 62ch;
}
@media (max-width: 1100px) {
.rel-grid {
grid-template-columns: minmax(0, 1fr);
}
.rel-metrics {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 760px) {
.release-targets {
padding: 14px;
}
.rel-tab {
width: 100%;
}
.rel-drawer {
width: 100vw;
padding: 16px;
}
.rel-changes table,
.rel-details table {
display: block;
overflow-x: auto;
}
}
+1 -2
View File
@@ -4,7 +4,6 @@ export type ModuleId =
| 'knowledge'
| 'tasks'
| 'releases'
| 'library'
| 'settings'
| 'versions'
| 'qaops'
@@ -14,7 +13,7 @@ export interface WorkspaceState {
activeTab: ModuleId
}
const moduleIds = new Set<ModuleId>(['dashboard', 'tasks', 'releases', 'library', 'settings', 'qaops'])
const moduleIds = new Set<ModuleId>(['dashboard', 'tasks', 'releases', 'settings', 'qaops'])
export const initialWorkspace: WorkspaceState = {
openTabs: ['dashboard'],