Compare commits

...

3 Commits

Author SHA1 Message Date
姚章浩 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
姚章浩 20fc40a147 test(library): 验证只读整库版本读取路径并修正部署校验
build / build (push) Failing after 15s
- 合成归档断言数量/字节/契约/策略与"未接线"行为
- 部署校验改用容器内读回,不再依赖需登录的 build-info
2026-10-28 11:44:05 +08:00
30 changed files with 2244 additions and 54 deletions
+30
View File
@@ -1,5 +1,35 @@
# Changelog
## 开发快照 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
+119
View File
@@ -812,6 +812,125 @@
}
}
},
"/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/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"
+162 -28
View File
@@ -224,11 +224,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 +384,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 +477,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 +557,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 +617,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 +643,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 +666,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 +701,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 +763,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 +778,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")
}
}
}
+39
View File
@@ -9,12 +9,14 @@ import (
"os/signal"
"path/filepath"
"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 +26,9 @@ import (
"knowledge-governance/internal/workflows/testweknora"
)
// libraryCaptureJobType is shared with the API which enqueues it.
const libraryCaptureJobType = "library.capture"
func main() {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
@@ -126,6 +131,40 @@ 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")
}
result, err := libraryagent.Capture(ctx, agentConfig, payload.Scope, payload.CaptureJob)
if err != nil {
log.Printf("library capture failed scope=%s capture_job=%s: %v", payload.Scope, payload.CaptureJob, err)
return err
}
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
}
// 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)
}
+106
View File
@@ -0,0 +1,106 @@
package httpapi
import (
"encoding/json"
"fmt"
"net/http"
"regexp"
"strings"
"time"
"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()
job, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{
ID: fmt.Sprintf("library-capture-%s-%d", request.Scope, now.UnixNano()),
Type: libraryCaptureJobType,
Payload: payload,
AvailableAt: now,
MaxAttempts: 2,
IdempotencyKey: "library.capture:" + captureJob,
}, now)
if err != nil || job == nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot enqueue capture job"})
return
}
writeJSON(w, http.StatusAccepted, map[string]any{
"job_id": job.ID, "capture_job": captureJob, "scope": request.Scope, "state": job.State,
})
}
// 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) {
queue, err := config.Store.List(r.Context(), 200)
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read capture jobs"})
return
}
views := make([]map[string]any, 0, 20)
for _, job := range queue {
if job.Type != libraryCaptureJobType || len(views) >= 20 {
continue
}
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})
}
+111
View File
@@ -0,0 +1,111 @@
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 TestLibraryCaptureJobsListsOnlyCaptureJobs(t *testing.T) {
store := &fakeJobStore{listResult: []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)},
{ID: "b", Type: "artifact.fetch", State: "completed"},
}}
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)
}
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)
}
}
+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)
+131
View File
@@ -0,0 +1,131 @@
package httpapi
import (
"bytes"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
"knowledge-governance/internal/librarysnapshot"
)
// The 整库版本 page reads a sealed archive through this exact function. A
// synthetic archive keeps the assertion about what the page shows independent of
// whether a real capture has run on this host.
func TestReadLibrarySnapshotsReportsSealedTotals(t *testing.T) {
root, err := os.MkdirTemp(os.TempDir(), "kglib-")
if err != nil {
t.Fatal(err)
}
defer 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)
}
// The archive re-derives row counts from the stored bytes, so the bodies must
// carry exactly the declared number of rows.
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", 4, rows(4)},
{"database", "chunks", 38, rows(38)},
{"database", "resources", 21, rows(21)},
{"database", "resource_bindings", 4, rows(4)},
{"database", "knowledge_tags", 0, rows(0)},
{"database", "knowledge_tag_relations", 0, rows(0)},
{"index", "chunks", 122, rows(122)},
{"wiki", "wiki_pages", 31, rows(31)},
{"wiki", "wiki_folders", 21, rows(21)},
{"wiki", "wiki_page_issues", 0, rows(0)},
{"wiki", "wiki_log_entries", 11, rows(11)},
}
// Every resource row must have its own archived object: the archive refuses a
// snapshot whose resource dependencies are incomplete.
for i := 0; i < 21; i++ {
parts = append(parts, struct {
kind, name string
count int64
body string
}{"resource", fmt.Sprintf("00000000-0000-4000-8000-%012d", i), 1, fmt.Sprintf("object-%d", i)})
}
manifest := librarysnapshot.Manifest{ValidationPolicy: librarysnapshot.ArtifactAcceptancePolicy,
Format: librarysnapshot.Format, Scope: "internal", TenantID: 10000,
KnowledgeBaseID: "0c84a098-d3ed-4b82-a165-e6de9691d6a8", CreatedAt: time.Now().UTC(),
Compatibility: librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74,
RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "text-embedding-v4", EmbeddingDimension: 1024,
IndexMappingSHA256: "137cde2965f3b56521f5fb722b4e0617f46d0e509e571b217fe01e090d5e4d01"}}
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)
}
snapshotID, err := archive.Seal(manifest)
if err != nil {
t.Fatal(err)
}
if err = archive.Close(); err != nil {
t.Fatal(err)
}
list, err := readLibrarySnapshots(root)
if err != nil {
t.Fatal(err)
}
if !list.Available || len(list.Snapshots) != 1 || list.Snapshots[0].SnapshotID != snapshotID {
t.Fatalf("unexpected list %+v", list)
}
snapshot := list.Snapshots[0]
want := map[string]int64{"documents": 4, "chunks": 38, "index_documents": 122, "resources": 21, "wiki_pages": 31}
for key, value := range want {
if snapshot.Totals[key] != value {
t.Fatalf("total %s = %d, want %d", key, snapshot.Totals[key], value)
}
}
// 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)
}
if list.CaptureNote == "" {
t.Fatal("page must explain who runs the capture")
}
if _, err = os.Stat(filepath.Join(root, "versions", snapshotID+".json")); err != nil {
t.Fatalf("sealed manifest missing: %v", err)
}
}
func TestReadLibrarySnapshotsWithoutArchiveIsExplicitlyUnwired(t *testing.T) {
list, err := readLibrarySnapshots("")
if err != nil {
t.Fatal(err)
}
if list.Available || list.Reason == "" || len(list.Snapshots) != 0 {
t.Fatalf("empty configuration must be reported as unwired, got %+v", list)
}
}
+10 -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,13 @@ 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)
})
// 全部 main 提交时间线(读本库缓存,不直接打 Gitea)
mux.HandleFunc("GET /api/v1/version-history", func(w http.ResponseWriter, r *http.Request) {
versionHistoryList(w, r, config)
+224
View File
@@ -0,0 +1,224 @@
// 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"
"net"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"sync"
"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
// 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
}
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")
}
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
}
go func() {
<-ctx.Done()
_ = listener.Close()
}()
for {
conn, err := listener.Accept()
if err != nil {
if ctx.Err() != nil {
return nil
}
return err
}
go a.handle(ctx, 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}
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 {
out.Error = "operation failed"
if message := strings.TrimSpace(string(payload)); message != "" && len(message) <= 2000 {
out.Error = message
}
return out
}
out.OK = true
if json.Valid(payload) {
out.Payload = json.RawMessage(payload)
} else {
out.Payload = json.RawMessage(`{}`)
}
return out
}
// 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")
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",
}
}
+171
View File
@@ -0,0 +1,171 @@
package libraryagent
import (
"context"
"encoding/json"
"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 := calls()
if len(recorded) != 1 {
t.Fatalf("expected one 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 := calls(); len(got) != 0 {
t.Fatalf("rejected requests still executed: %v", got)
}
}
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")
}
}
@@ -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) {
Executable
BIN
View File
Binary file not shown.
+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
+137 -8
View File
@@ -1,16 +1,20 @@
import { useCallback, useEffect, useMemo, useState } from 'react'
import {
enqueueLibraryCapture,
fetchLibraryCaptures,
fetchLibrarySnapshots,
formatBytes,
scopeLabel,
type LibraryCaptureJob,
type LibrarySnapshot,
type LibrarySnapshotList,
} from './librarySnapshots'
import { useOptionalAuth } from './auth'
import './libraryVersions.css'
// 「整库版本」页:只读展示已封存的整库候选产物(对内/对外各一份最新)。
// 页面不提供封存按钮:封存要停真实写入者并读来源凭据,只能在目标主机用
// scripts/library-capture.sh 执行。候选 != 验收通过,也 != 可发布。
// scripts/library-capture.sh 执行。通过完整性检查 != 已发布,授权仍走发布管理。
const stamp = (value: string) =>
value && Number.isFinite(new Date(value).getTime())
? new Date(value).toLocaleString('zh-CN', {
@@ -26,12 +30,24 @@ const stamp = (value: string) =>
const metric = (snapshot: LibrarySnapshot, key: string) => String(snapshot.totals[key] ?? 0)
const jobStateLabel: Record<string, string> = {
pending: '待执行',
running: '执行中',
retry: '重试中',
completed: '已完成',
failed: '失败',
}
export function LibraryVersions() {
const auth = useOptionalAuth()
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 [jobs, setJobs] = useState<LibraryCaptureJob[]>([])
const [pendingScope, setPendingScope] = useState<string | null>(null)
const [notice, setNotice] = useState<string | null>(null)
const load = useCallback(async (signal?: AbortSignal) => {
setLoading(true)
@@ -53,6 +69,51 @@ export function LibraryVersions() {
return () => controller.abort()
}, [load])
const refreshJobs = useCallback(async (signal?: AbortSignal) => {
const items = await fetchLibraryCaptures(signal)
setJobs(items)
return items
}, [])
useEffect(() => {
const controller = new AbortController()
void refreshJobs(controller.signal).catch(() => undefined)
return () => controller.abort()
}, [refreshJobs])
// A capture runs in a maintenance window (seconds), so a short poll is enough
// to show the real queue state and to pick up the new sealed version.
const active = jobs.some((job) => job.state === 'pending' || job.state === 'running' || job.state === 'retry')
useEffect(() => {
if (!active) return
const timer = window.setInterval(() => {
void refreshJobs()
.then((items) => {
if (!items.some((job) => job.state === 'pending' || job.state === 'running' || job.state === 'retry')) {
void load()
}
})
.catch(() => undefined)
}, 3000)
return () => window.clearInterval(timer)
}, [active, refreshJobs, load])
const canCapture = (auth?.identity?.role === 'engineer' || auth?.identity?.role === 'admin') && page?.capture_available === true
const startCapture = async (scope: string) => {
setPendingScope(scope)
setNotice(null)
try {
const accepted = await enqueueLibraryCapture(scope)
setNotice(`已投递封存作业:${scopeLabel(scope)} · ${accepted.capture_job}(等待主机侧执行)`)
await refreshJobs()
} catch (captureError) {
setNotice(captureError instanceof Error ? captureError.message : '发起封存失败')
} finally {
setPendingScope(null)
}
}
const snapshots = page?.snapshots ?? []
const latestByScope = useMemo(() => {
const map: Record<string, LibrarySnapshot | undefined> = {}
@@ -74,8 +135,11 @@ export function LibraryVersions() {
</p>
</div>
<div className="library-versions-actions">
<span className="library-versions-usage">
共 {snapshots.length} 份 · 归档占用 {formatBytes(page?.stored_bytes ?? 0)}
<span
className="library-versions-usage"
title="跨版本去重后被版本引用的内容字节;不是磁盘占用,也不是可回收空间"
>
共 {snapshots.length} 份 · 被引用的去重内容 {formatBytes(page?.content_bytes ?? 0)}
</span>
<button type="button" onClick={() => void load()} disabled={loading}>
{loading ? '刷新中…' : '刷新'}
@@ -141,11 +205,32 @@ export function LibraryVersions() {
</p>
</>
) : (
<p className="library-scope-hint">
该库没有封存产物。封存在目标主机执行:
<code>scripts/library-capture.sh capture -scope {scope}</code>
</p>
<p className="library-scope-hint">该库还没有封存产物。</p>
)}
<div className="library-scope-actions">
{page?.capture_available ? (
canCapture ? (
<button
type="button"
onClick={() => void startCapture(scope)}
disabled={
pendingScope === scope ||
jobs.some(
(job) =>
job.scope === scope &&
(job.state === 'pending' || job.state === 'running' || job.state === 'retry')
)
}
>
{pendingScope === scope ? '投递中…' : `发起${scopeLabel(scope)}封存`}
</button>
) : (
<span>发起封存需要知识工程师及以上权限</span>
)
) : (
<span>{page?.capture_reason}</span>
)}
</div>
</article>
)
})}
@@ -173,6 +258,14 @@ export function LibraryVersions() {
<span className="library-versions-note">{page.capture_note}</span>
</div>
<div className="library-versions-toolbar library-versions-accounting">
<span>
磁盘事实(不是可回收空间):清单 {formatBytes(page.manifest_file_bytes)} · blob 文件{' '}
{formatBytes(page.blob_file_bytes)}(实际分配 {formatBytes(page.blob_allocated_bytes)})· 未被任何版本引用{' '}
{page.unreferenced_blobs} 个 / {formatBytes(page.unreferenced_bytes)}
</span>
</div>
{visible.length === 0 ? (
<p className="library-versions-empty">还没有封存产物。</p>
) : (
@@ -201,7 +294,9 @@ export function LibraryVersions() {
<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} 字节`}>
<td
title={`本版逻辑 ${snapshot.logical_bytes} 字节 · 本版内去重 ${snapshot.unique_bytes} 字节(跨版本去重见上方合计)`}
>
{formatBytes(snapshot.logical_bytes)}
</td>
<td>
@@ -226,6 +321,40 @@ export function LibraryVersions() {
</table>
)}
{notice ? <p className="library-capture-notice">{notice}</p> : null}
{jobs.length > 0 ? (
<div className="library-capture-jobs">
<h3>封存作业</h3>
<table className="library-versions-table">
<thead>
<tr>
<th>投递时间</th>
<th>范围</th>
<th>状态</th>
<th>作业号</th>
<th>发起人</th>
<th>最后错误</th>
</tr>
</thead>
<tbody>
{jobs.map((job) => (
<tr key={job.job_id}>
<td>{stamp(job.created_at)}</td>
<td>{scopeLabel(job.scope)}</td>
<td>{jobStateLabel[job.state] ?? job.state}</td>
<td>
<code>{job.capture_job.slice(0, 24)}</code>
</td>
<td>{job.requested_by || '—'}</td>
<td className="library-capture-error">{job.last_error || '—'}</td>
</tr>
))}
</tbody>
</table>
</div>
) : null}
{visible
.filter((snapshot) => snapshot.snapshot_id === expanded)
.map((snapshot) => (
+85 -2
View File
@@ -37,13 +37,43 @@ 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
}
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 +143,64 @@ 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),
}
}
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']
+50
View File
@@ -165,6 +165,56 @@
max-width: 70ch;
line-height: 1.5;
}
.library-scope-actions {
margin-top: 14px;
display: flex;
align-items: center;
gap: 10px;
font-size: 12px;
color: var(--ink-mute, #64748b);
}
.library-scope-actions button {
padding: 7px 14px;
border-radius: 8px;
border: 1px solid #2563eb;
background: #eff6ff;
color: #1d4ed8;
cursor: pointer;
}
.library-scope-actions button:disabled {
cursor: progress;
opacity: 0.6;
}
.library-capture-notice {
margin: 0;
padding: 10px 14px;
border-radius: 8px;
background: #eff6ff;
border: 1px solid #bfdbfe;
color: #1d4ed8;
font-size: 13px;
}
.library-capture-jobs {
background: var(--bg-panel, #fff);
border: 1px solid var(--border-base, #e2e8f0);
border-radius: 10px;
padding: 16px 20px;
}
.library-capture-jobs h3 {
margin: 0 0 10px;
font-size: 15px;
}
.library-capture-error {
max-width: 360px;
overflow-wrap: anywhere;
white-space: normal;
}
.library-versions-accounting {
justify-content: flex-start;
font-size: 12px;
color: var(--ink-mute, #64748b);
line-height: 1.6;
}
.library-versions-empty {
margin: 0;
padding: 24px;