Compare commits

...

2 Commits

Author SHA1 Message Date
姚章浩 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
31 changed files with 2491 additions and 558 deletions
+1
View File
@@ -29,6 +29,7 @@
/release-diag
/worker
/libraryctl
/libraryagent
/apply_s5_patch.py
/tmp_*
.style-backup-*/
+31
View File
@@ -1,5 +1,36 @@
# Changelog
## 开发快照 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
+66
View File
@@ -832,6 +832,72 @@
}
}
},
"/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": [
+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"
+8 -1
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 {
+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 是轮换制,不能在两处各留一份)
+18 -1
View File
@@ -45,7 +45,24 @@
同一个作业号重跑是**幂等重放**:直接返回已封存的同一份候选(`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 实测(本机测试栈)
+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)
}
+143
View File
@@ -0,0 +1,143 @@
package httpapi
import (
"context"
"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()
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 {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot enqueue 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"`
}
if err = json.Unmarshal(job.Payload, &stored); err != nil || stored.CaptureJob != captureJob {
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 {
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)
}
}
+9 -2
View File
@@ -58,14 +58,20 @@ type librarySnapshotList struct {
UnreferencedBytes int64 `json:"unreferenced_bytes"`
ManifestFileBytes int64 `json:"manifest_file_bytes"`
ManifestAllocatedBytes int64 `json:"manifest_allocated_bytes"`
// 页面必须能说清"封存由谁执行",不能让人以为页面上有个没实现的按钮。
CaptureNote string `json:"capture_note"`
// 页面必须能说清"封存由谁执行";能不能从这里发起,取决于主机侧 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 在目标主机执行(停写入者→导出→恢复)。页面只读展示已封存的完整版本:它通过了数据完整性检查(身份、双向正文覆盖、生成问题、资源与摘要),这已满足封版所需的完整性口径;授权与生产同步仍是独立步骤。"
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})
@@ -110,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
+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)
+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")
}
+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 {
+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' ? (
-271
View File
@@ -1,271 +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"
title="跨版本去重后被版本引用的内容字节;不是磁盘占用,也不是可回收空间"
>
共 {snapshots.length} 份 · 被引用的去重内容 {formatBytes(page?.content_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>
<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>
) : (
<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>
)
}
+133
View File
@@ -0,0 +1,133 @@
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, it, vi } from 'vitest'
import { ReleaseTargetsView } from './ReleaseTargets'
import type { LibraryCaptureJob, LibrarySnapshot, LibrarySnapshotList } from './librarySnapshots'
const snapshot: 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: '137cde2965f3b56521f5fb722b4e0617f46d0e509e571b217fe01e090d5e4d01',
},
parts: [
{ kind: 'database', name: 'knowledges', sha256: 'a'.repeat(64), count: 4, bytes: 10654 },
{ kind: 'index', name: 'chunks', sha256: 'b'.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 job: 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:51Z',
}
const page: LibrarySnapshotList = {
available: true,
reason: '',
archive_root: '/var/lib/knowledge-governance/library',
snapshots: [snapshot],
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 baseProps = {
page,
jobs: [] as LibraryCaptureJob[],
loading: false,
error: null,
notice: null,
expanded: null,
pendingScope: null,
canCapture: true,
onRefresh: () => undefined,
onCapture: vi.fn(),
onToggleExpanded: () => undefined,
}
const render = (overrides: Partial<typeof baseProps> = {}) =>
renderToStaticMarkup(<ReleaseTargetsView {...baseProps} {...overrides} />)
describe('ReleaseTargetsView', () => {
it('shows exactly the two library targets with real counts and integrity wording', () => {
const html = render()
expect(html).toContain('对内')
expect(html).toContain('对外')
expect(html).not.toContain('第三目标')
expect(html).toContain('122')
expect(html).toContain('31')
expect(html).toMatch(/完整性:读取时已重算 2 项摘要/)
expect(html).toContain('text-embedding-v4')
})
it('keeps the unbuilt chain stages disabled instead of faking progress', () => {
const html = render()
expect(html).toMatch(/生产预备份[\s\S]*未接线/)
expect(html).toMatch(/同步到生产[\s\S]*未授权/)
expect(html).toMatch(/校验 \/ 恢复[\s\S]*未接线/)
expect(html).not.toMatch(/\d+%/)
// Disabled actions carry a reason in the title attribute.
expect(html).toContain('title="生产独立预备份与恢复演练未接线"')
expect(html).toContain('title="生产写入需要独立授权闸口,当前未开放"')
})
it('offers the capture action only when the agent is wired and the role allows it', () => {
expect(render()).toContain('发起对内封存')
const readonly = render({ canCapture: false })
expect(readonly).toContain('发起封存需要知识工程师及以上权限')
const unwired = render({
page: { ...page, capture_available: false, capture_reason: '未接线:主机侧封存 agent 没有挂载' },
})
expect(unwired).toContain('未接线:主机侧封存 agent 没有挂载')
expect(unwired).not.toContain('发起对内封存')
})
it('reports the live job instead of a guessed stage', () => {
const html = render({ jobs: [job] })
expect(html).toContain('执行中')
expect(html).toContain('lib-internal-20261028T033457')
expect(html).toContain('yaozhanghao')
// A running job disables the capture button for that scope.
expect(html).toMatch(/disabled[^>]*>发起对内封存/)
})
it('states that storage numbers are content accounting, not reclaimable space', () => {
const html = render()
expect(html).toContain('被版本引用的去重内容')
expect(html).toContain('不是可回收空间')
expect(html).toMatch(/保留策略、依赖保护、清理预览都没有接线/)
})
it('shows an empty target as an invitation, with the blocking reason', () => {
const html = render({ page: { ...page, snapshots: [], available: false, reason: '未接线:归档根未配置' } })
expect(html).toContain('未接线:归档根未配置')
})
})
+446
View File
@@ -0,0 +1,446 @@
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 './releaseTargets.css'
// 发布管理的主视图:只服务『对内 / 对外』两个整库目标。
//
// 这条链有四段:封存 → 生产预备份 → 同步 → 校验/恢复。目前只有第一段接通,
// 其余三段一律禁用并写明"未接线/未授权"——不用假进度、不推算阶段、不显示假成功。
// 文档级旧流程折叠保留在页面底部,它成功也不代表整库发布成功。
const stamp = (value: string) =>
value && Number.isFinite(new Date(value).getTime())
? new Date(value).toLocaleString('zh-CN', {
timeZone: 'Asia/Shanghai',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hour12: false,
})
: '—'
const jobStateLabel: Record<string, string> = {
pending: '排队中',
running: '执行中',
retry: '重试中',
completed: '已完成',
failed: '失败',
}
const ACTIVE_STATES = ['pending', 'running', 'retry']
const metric = (snapshot: LibrarySnapshot, key: string) => snapshot.totals[key] ?? 0
interface StageProps {
id: string
label: string
state: 'ready' | 'not-wired' | 'not-authorized'
detail: string
}
function Stage({ label, state, detail }: StageProps) {
const chip =
state === 'ready' ? '已接通' : state === 'not-authorized' ? '未授权' : '未接线'
return (
<li className={`release-stage ${state}`}>
<span className="release-stage-name">{label}</span>
<span className="release-stage-chip">{chip}</span>
<span className="release-stage-detail">{detail}</span>
</li>
)
}
interface ReleaseTargetsViewProps {
page: LibrarySnapshotList | null
jobs: LibraryCaptureJob[]
loading: boolean
error: string | null
notice: string | null
expanded: string | null
pendingScope: string | null
canCapture: boolean
onRefresh: () => void
onCapture: (scope: string) => void
onToggleExpanded: (snapshotID: string) => void
}
export function ReleaseTargetsView(props: ReleaseTargetsViewProps) {
const { page, jobs, loading, error, notice, expanded, pendingScope, canCapture, onRefresh, onCapture, onToggleExpanded } = props
const latestByScope = useMemo(() => {
const map: Record<string, LibrarySnapshot | undefined> = {}
for (const snapshot of page?.snapshots ?? []) {
if (!map[snapshot.scope]) map[snapshot.scope] = snapshot
}
return map
}, [page])
return (
<section className="release-targets" aria-label="整库发布">
<header className="release-targets-head">
<div>
<h1>发布管理</h1>
<p>
两个目标:对内与对外。每个目标是一份<strong>完整封存</strong>的整库版本,不是若干单篇文档。
这条链只有第一段接通,其余动作按真实状态禁用。
</p>
</div>
<button type="button" className="secondary" onClick={() => onRefresh()} disabled={loading}>
{loading ? '刷新中…' : '刷新'}
</button>
</header>
<ol className="release-chain" aria-label="整库发布链路">
<Stage id="seal" label="封存" state="ready" detail="停写入者→导出十表/索引/对象/Wiki→恢复;读取时重算摘要" />
<Stage id="prebackup" label="生产预备份" state="not-wired" detail="生产独立备份与恢复演练未接线" />
<Stage id="sync" label="同步到生产" state="not-authorized" detail="生产写入需要独立授权闸口,当前未开放" />
<Stage id="verify" label="校验 / 恢复" state="not-wired" detail="同步后校验与按版本回退未接线" />
</ol>
{error ? (
<div className="release-blocked">
<strong>读取失败</strong>
<p>{error}</p>
</div>
) : null}
{page && !page.available ? (
<div className="release-blocked">
<strong>归档未接线</strong>
<p>{page.reason || '整库归档根未配置'}</p>
</div>
) : null}
{notice ? <p className="release-notice">{notice}</p> : null}
<div className="release-target-grid">
{(['internal', 'external'] as const).map((scope) => {
const snapshot = latestByScope[scope]
const activeJob = jobs.find((job) => job.scope === scope && ACTIVE_STATES.includes(job.state))
const lastJob = jobs.find((job) => job.scope === scope)
const expandedHere = snapshot && expanded === snapshot.snapshot_id
const blockedReason = !page
? '正在读取归档'
: !page.available
? page.reason || '归档根未配置'
: !page.capture_available
? page.capture_reason || '主机侧封存 agent 未接线'
: null
return (
<article key={scope} className="release-target">
<header className="release-target-head">
<h2>{scopeLabel(scope)}</h2>
<span className={snapshot ? 'release-state ready' : 'release-state empty'}>
{snapshot ? '已封存' : '尚无封存'}
</span>
</header>
{snapshot ? (
<>
<p className="release-target-meta">
封存于 {stamp(snapshot.created_at)} · 快照 <code>{snapshot.snapshot_id.slice(0, 16)}</code>
</p>
<dl className="release-metrics">
<div>
<dt>文档</dt>
<dd>{metric(snapshot, 'documents')}</dd>
</div>
<div>
<dt>分块</dt>
<dd>{metric(snapshot, 'chunks')}</dd>
</div>
<div>
<dt>索引</dt>
<dd>{metric(snapshot, 'index_documents')}</dd>
</div>
<div>
<dt>资源</dt>
<dd>{metric(snapshot, 'resources')}</dd>
</div>
<div>
<dt>Wiki 页</dt>
<dd>{metric(snapshot, 'wiki_pages')}</dd>
</div>
<div>
<dt>内容字节</dt>
<dd>{formatBytes(snapshot.logical_bytes)}</dd>
</div>
</dl>
<p className="release-integrity">
完整性:读取时已重算 {snapshot.parts.length} 项摘要并逐项匹配(A04 口径)。
模型 {snapshot.compatibility.embedding_model || '未知'} /{' '}
{snapshot.compatibility.embedding_dimension || '?'} 维 · schema{' '}
{snapshot.compatibility.schema_version || '?'} · 策略 {snapshot.validation_policy || '—'}
</p>
<button
type="button"
className="release-parts-toggle"
onClick={() => onToggleExpanded(snapshot.snapshot_id)}
aria-expanded={expandedHere}
>
{expandedHere ? '收起分项与校验结果' : '展开分项与校验结果'}
</button>
{expandedHere ? (
<div className="release-parts">
<table>
<thead>
<tr>
<th>类别</th>
<th>分项</th>
<th>数量</th>
<th>字节</th>
<th>摘要(SHA256)</th>
</tr>
</thead>
<tbody>
{snapshot.parts.map((part) => (
<tr key={`${part.kind}-${part.name}`}>
<td>{part.kind}</td>
<td>{part.name}</td>
<td>{part.count}</td>
<td>{part.bytes.toLocaleString('zh-CN')}</td>
<td>
<code title={part.sha256}>{part.sha256.slice(0, 12)}</code>
</td>
</tr>
))}
</tbody>
</table>
<p className="release-parts-note">
校验结果:{snapshot.parts.length} 项全部可读且摘要一致;未发现异常。
这证明的是数据完整性,不是效果测试(A06 已取消)。
</p>
</div>
) : null}
</>
) : (
<p className="release-target-empty">
{blockedReason || '还没有封存产物。先发起一次封存,产出一份完整版本。'}
</p>
)}
<div className="release-target-job">
{activeJob ? (
<>
<span className={`release-job-state ${activeJob.state}`}>
{jobStateLabel[activeJob.state] ?? activeJob.state}
</span>
<code>{activeJob.capture_job}</code>
<span className="release-job-owner">{activeJob.requested_by || '—'}</span>
</>
) : lastJob ? (
<>
<span className={`release-job-state ${lastJob.state}`}>
{jobStateLabel[lastJob.state] ?? lastJob.state}
</span>
<span>上次作业 {lastJob.capture_job}</span>
{lastJob.last_error ? (
<span className="release-job-error" title={lastJob.last_error}>
{lastJob.last_error.slice(0, 80)}
</span>
) : null}
</>
) : (
<span className="release-job-idle">当前没有封存作业</span>
)}
</div>
<div className="release-actions">
{page?.capture_available ? (
canCapture ? (
<button
type="button"
className="primary"
onClick={() => onCapture(scope)}
disabled={pendingScope === scope || Boolean(activeJob)}
>
{pendingScope === scope ? '投递中…' : `发起${scopeLabel(scope)}封存`}
</button>
) : (
<span className="release-action-hint">发起封存需要知识工程师及以上权限</span>
)
) : (
<span className="release-action-hint">{page?.capture_reason || '封存未接线'}</span>
)}
<button type="button" disabled title="生产独立预备份与恢复演练未接线">
生产预备份
</button>
<button type="button" disabled title="生产写入需要独立授权闸口,当前未开放">
同步到生产
</button>
<button type="button" disabled title="同步后校验与按版本回退未接线">
校验 / 恢复
</button>
</div>
<p className="release-target-foot">
禁用项不是流程建议,而是能力状态:预备份、同步、校验恢复都没有接线,点击不会发生任何事。
</p>
</article>
)
})}
</div>
{jobs.length > 0 ? (
<section className="release-jobs" aria-label="封存作业">
<h2>封存作业</h2>
<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}</code>
</td>
<td>{job.requested_by || '—'}</td>
<td className="release-job-error">{job.last_error || '—'}</td>
</tr>
))}
</tbody>
</table>
</section>
) : null}
<section className="release-storage" aria-label="存储">
<h2>归档存储</h2>
{page?.available ? (
<>
<dl className="release-storage-grid">
<div>
<dt>被版本引用的去重内容</dt>
<dd>{formatBytes(page.content_bytes)}</dd>
</div>
<div>
<dt>blob 表观字节</dt>
<dd>{formatBytes(page.blob_file_bytes)}</dd>
</div>
<div>
<dt>实际分配字节</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>
<div>
<dt>版本数</dt>
<dd>{page.versions}</dd>
</div>
</dl>
<p className="release-storage-note">
去重内容按跨版本重新计算;这些都<strong>不是可回收空间</strong>。
保留策略、依赖保护、清理预览都没有接线,自动清理保持关闭,页面不会删除任何东西。
</p>
</>
) : (
<p className="release-storage-note">{page?.reason || '归档未接线,存储口径不可读。'}</p>
)}
</section>
</section>
)
}
export function ReleaseTargets() {
const auth = useOptionalAuth()
const [page, setPage] = useState<LibrarySnapshotList | null>(null)
const [jobs, setJobs] = useState<LibraryCaptureJob[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [expanded, setExpanded] = useState<string | null>(null)
const [pendingScope, setPendingScope] = useState<string | null>(null)
const [notice, setNotice] = useState<string | null>(null)
const load = useCallback(async (signal?: AbortSignal) => {
setLoading(true)
try {
const [snapshots, captures] = await Promise.all([
fetchLibrarySnapshots(signal),
fetchLibraryCaptures(signal),
])
setPage(snapshots)
setJobs(captures)
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 busy = jobs.some((job) => ACTIVE_STATES.includes(job.state))
useEffect(() => {
if (!busy) return
const timer = window.setInterval(() => {
void load().catch(() => undefined)
}, 3000)
return () => window.clearInterval(timer)
}, [busy, load])
const role = auth?.identity?.role
const canCapture = (role === 'engineer' || role === 'admin') && page?.capture_available === true
const startCapture = async (scope: string) => {
setPendingScope(scope)
setNotice(null)
try {
const accepted = await enqueueLibraryCapture(scope)
setNotice(
accepted.reused
? `该作业已存在:${scopeLabel(scope)} · ${accepted.capture_job}(状态 ${jobStateLabel[accepted.state] ?? accepted.state})`
: `已投递封存作业:${scopeLabel(scope)} · ${accepted.capture_job}`
)
await load()
} catch (captureError) {
setNotice(captureError instanceof Error ? captureError.message : '发起封存失败')
} finally {
setPendingScope(null)
}
}
return (
<ReleaseTargetsView
page={page}
jobs={jobs}
loading={loading}
error={error}
notice={notice}
expanded={expanded}
pendingScope={pendingScope}
canCapture={canCapture}
onRefresh={() => void load()}
onCapture={(scope) => void startCapture(scope)}
onToggleExpanded={(snapshotID) => setExpanded(expanded === snapshotID ? null : snapshotID)}
/>
)
}
+71
View File
@@ -37,6 +37,28 @@ 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
@@ -53,6 +75,8 @@ export interface LibrarySnapshotList {
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> =>
@@ -131,9 +155,56 @@ export async function fetchLibrarySnapshots(signal?: AbortSignal): Promise<Libra
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']
-271
View File
@@ -1,271 +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-accounting {
justify-content: flex-start;
font-size: 12px;
color: var(--ink-mute, #64748b);
line-height: 1.6;
}
.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));
}
}
+360
View File
@@ -0,0 +1,360 @@
/* 发布管理:两个整库目标 + 四段链路。沿用页面既有的明亮面板风格。 */
.release-targets {
display: flex;
flex-direction: column;
gap: 18px;
min-width: 0;
padding: 24px;
color: var(--ink-base);
}
.release-targets-head,
.release-chain,
.release-target,
.release-jobs,
.release-storage,
.release-blocked {
background: var(--bg-panel, #fff);
border: 1px solid var(--border-base, #e2e8f0);
border-radius: 10px;
}
.release-targets-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
padding: 20px;
flex-wrap: wrap;
}
.release-targets h1 {
margin: 0 0 6px;
font-size: 22px;
}
.release-targets-head p {
margin: 0;
max-width: 70ch;
font-size: 13px;
line-height: 1.65;
color: var(--ink-mute, #64748b);
}
.release-targets-head button {
padding: 7px 14px;
border-radius: 8px;
border: 1px solid var(--border-base, #e2e8f0);
background: var(--bg-panel, #fff);
cursor: pointer;
}
.release-targets-head button:disabled {
cursor: progress;
opacity: 0.6;
}
/* 链路:四段各自带真实能力状态,不用百分比或进度条伪装。 */
.release-chain {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 1px;
padding: 0;
margin: 0;
list-style: none;
overflow: hidden;
background: var(--border-base, #e2e8f0);
}
.release-stage {
background: var(--bg-panel, #fff);
padding: 14px 16px;
display: flex;
flex-direction: column;
gap: 6px;
min-width: 0;
}
.release-stage-name {
font-size: 14px;
font-weight: 600;
}
.release-stage-chip {
align-self: flex-start;
font-size: 11px;
padding: 2px 8px;
border-radius: 999px;
border: 1px solid transparent;
}
.release-stage.ready .release-stage-chip {
background: #ecfdf5;
border-color: #a7f3d0;
color: #047857;
}
.release-stage.not-wired .release-stage-chip {
background: #f8fafc;
border-color: #e2e8f0;
color: #64748b;
}
.release-stage.not-authorized .release-stage-chip {
background: #fff7ed;
border-color: #fed7aa;
color: #b45309;
}
.release-stage-detail {
font-size: 12px;
line-height: 1.5;
color: var(--ink-mute, #64748b);
}
.release-target-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(380px, 1fr));
gap: 16px;
}
.release-target {
padding: 20px;
display: flex;
flex-direction: column;
gap: 12px;
min-width: 0;
}
.release-target-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
}
.release-target-head h2 {
margin: 0;
font-size: 20px;
}
.release-state {
font-size: 12px;
padding: 2px 10px;
border-radius: 999px;
border: 1px solid #e2e8f0;
background: #f8fafc;
color: #64748b;
}
.release-state.ready {
background: #ecfdf5;
border-color: #a7f3d0;
color: #047857;
}
.release-target-meta {
margin: 0;
font-size: 12px;
color: var(--ink-mute, #64748b);
overflow-wrap: anywhere;
}
.release-metrics {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 8px;
margin: 0;
}
.release-metrics div {
border: 1px solid var(--border-base, #e2e8f0);
border-radius: 8px;
padding: 8px 10px;
}
.release-metrics dt {
font-size: 11px;
color: var(--ink-mute, #64748b);
}
.release-metrics dd {
margin: 2px 0 0;
font-size: 17px;
font-variant-numeric: tabular-nums;
}
.release-integrity,
.release-target-empty,
.release-target-foot,
.release-storage-note,
.release-parts-note {
margin: 0;
font-size: 12px;
line-height: 1.6;
color: var(--ink-mute, #64748b);
}
.release-parts-toggle {
align-self: flex-start;
padding: 5px 10px;
border-radius: 7px;
border: 1px solid var(--border-base, #e2e8f0);
background: #f8fafc;
cursor: pointer;
font-size: 12px;
}
.release-parts table,
.release-jobs table {
width: 100%;
border-collapse: collapse;
font-size: 12px;
}
.release-parts th,
.release-jobs th {
text-align: left;
padding: 6px 8px;
background: #f8fafc;
color: var(--ink-mute, #64748b);
font-weight: 600;
border-bottom: 1px solid var(--border-base, #eef2f7);
}
.release-parts td,
.release-jobs td {
padding: 6px 8px;
border-bottom: 1px solid var(--border-base, #eef2f7);
font-variant-numeric: tabular-nums;
}
.release-parts-note {
margin-top: 8px;
}
.release-target-job {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
font-size: 12px;
color: var(--ink-mute, #64748b);
min-height: 22px;
}
.release-job-state {
font-size: 11px;
padding: 2px 8px;
border-radius: 999px;
border: 1px solid #e2e8f0;
background: #f8fafc;
}
.release-job-state.running,
.release-job-state.pending,
.release-job-state.retry {
background: #eff6ff;
border-color: #bfdbfe;
color: #1d4ed8;
}
.release-job-state.completed {
background: #ecfdf5;
border-color: #a7f3d0;
color: #047857;
}
.release-job-state.failed {
background: #fef2f2;
border-color: #fecaca;
color: #b91c1c;
}
.release-job-error {
color: #b91c1c;
overflow-wrap: anywhere;
}
.release-job-idle {
color: var(--ink-mute, #64748b);
}
.release-actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
}
.release-actions button {
padding: 7px 12px;
border-radius: 8px;
border: 1px solid var(--border-base, #e2e8f0);
background: #fff;
cursor: pointer;
font-size: 13px;
}
.release-actions button.primary {
border-color: #2563eb;
background: #eff6ff;
color: #1d4ed8;
}
.release-actions button:disabled {
cursor: not-allowed;
opacity: 0.55;
background: #f8fafc;
}
.release-action-hint {
font-size: 12px;
color: var(--ink-mute, #64748b);
}
.release-blocked {
border-color: #f3c2b8;
background: #fff6f3;
padding: 14px 18px;
}
.release-blocked strong {
display: block;
margin-bottom: 4px;
color: #a03a1e;
font-size: 13px;
}
.release-blocked p {
margin: 0;
font-size: 12px;
color: #7c2d12;
}
.release-notice {
margin: 0;
padding: 10px 14px;
border-radius: 8px;
background: #eff6ff;
border: 1px solid #bfdbfe;
color: #1d4ed8;
font-size: 13px;
}
.release-jobs,
.release-storage {
padding: 18px 20px;
}
.release-jobs h2,
.release-storage h2 {
margin: 0 0 12px;
font-size: 16px;
}
.release-storage-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(190px, 1fr));
gap: 10px;
margin: 0 0 10px;
}
.release-storage-grid div {
border: 1px solid var(--border-base, #e2e8f0);
border-radius: 8px;
padding: 10px 12px;
}
.release-storage-grid dt {
font-size: 11px;
color: var(--ink-mute, #64748b);
}
.release-storage-grid dd {
margin: 3px 0 0;
font-size: 16px;
font-variant-numeric: tabular-nums;
}
/* 旧文档级流程:折叠保留,标题就写明它不是整库发布。 */
.release-legacy {
margin: 0 24px 24px;
border: 1px dashed var(--border-base, #cbd5e1);
border-radius: 10px;
background: #fcfcfd;
}
.release-legacy > summary {
padding: 14px 18px;
cursor: pointer;
font-size: 13px;
color: var(--ink-mute, #64748b);
}
.release-legacy[open] > summary {
border-bottom: 1px solid var(--border-base, #e2e8f0);
}
@media (max-width: 860px) {
.release-targets {
padding: 12px;
}
.release-chain {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.release-legacy {
margin: 0 12px 12px;
}
}
+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'],