feat(reconciliation): T6 导入对账(契约/后端/前端) #41

Merged
zheromiku merged 10 commits from hifox-agent/rin/CYWL-34 into main 2026-12-01 16:17:38 +08:00
16 changed files with 344 additions and 28 deletions
Showing only changes of commit 095aa3ed68 - Show all commits
+4
View File
@@ -4874,6 +4874,10 @@
"target_kb": {
"type": "string"
},
"weknora_url": {
"type": "string",
"description": "目标测试知识库在 WeKnora 控制台的链接;未配置测试端点时为空"
},
"action": {
"type": "string"
},
+1
View File
@@ -342,6 +342,7 @@ func run(ctx context.Context, getenv func(string) string) error {
Store: postgresstore.NewStore(pool).WithLibraryTarget(config.LibraryTargetIdentity()).WithRoutingDefaults(config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID),
Monitor: monitorProvider,
Reconciliation: reconciliationService,
WeKnoraWebBase: testEndpointResolver,
InternalRoutingKnowledgeBaseID: config.InternalRoutingKnowledgeBaseID,
ExternalRoutingKnowledgeBaseID: config.ExternalRoutingKnowledgeBaseID,
RoutingBindings: postgresstore.NewStore(pool),
@@ -156,6 +156,8 @@ T6a 的**第一个提交**必须先把以下接口写进 `api/openapi.yaml`,
| GET | `/api/v1/reconciliation/documents/{document_id}/progress` | 实时转发 WeKnora `runtime/documents/{id}`,经过脱敏;未配置平台 Key 时返回 503 `runtime_read_unavailable` | 所有登录角色 |
| GET | `/api/v1/monitor/overview`(已有) | 新增 `weknora_queues` 字段(来自 `runtime/queues`,不可用时为 null);删除 Embedding/LLM 两张常量"未知"卡 | 不变 |
**`/api/v1/monitor/tasks`(已有,T6a 增量)**:每行新增可选 `weknora_url`(目标测试知识库的 WeKnora 控制台链接;未配置测试端点时为空字符串),供文件详情抽屉在 progress 返回 503 时显示跳转链接。该字段为附加字段,既有字段与筛选语义不变;与 finding 的 `weknora_url` 使用同一拼接规则(`internal/platform/weknora.KnowledgeBaseConsoleURL`)。
**run 对象**:`id`、`kb_id`、`state`(`running` \| `succeeded` \| `failed`)、`trigger`(`schedule` \| `manual`)、`started_at`(同时是观测时刻)、`finished_at`、`ledger_count`、`kb_count`、`counts`(键为 R1–R8,值为整数)、`previous_counts`(上一成功批次的 counts,没有则为 null)、`window_overlapped`(bool,Q6)、`error_code`。
**finding 对象**:`id`、`run_id`、`type`(R1–R8)、`publication_id`、`document_id`、`title`、`path`、`source`、`target_scope`、`ledger_state`、`weknora_parse_status`、`normalized_state`(按 §4 矩阵归一后的值,供前端直接显示)、`ledger_sha256`、`declared_sha256`、`weknora_file_md5`、`evidence_level`(`independent` \| `declared_only` \| `none`)、`confirmation_state`(`confirmed` \| `pending`,仅 R1/R2 在 `window_overlapped` 批次里可为 pending)、`detail`(中文一句话)、`suggested_action`(`requeue_upload` \| `remove_from_test` \| `writeback_state` \| `enter_removal` \| `none`)、`action_state`(`open` \| `done`)、`weknora_url`(在 WeKnora 中打开的链接,可为空)。
+9
View File
@@ -4,6 +4,7 @@ import (
"context"
"errors"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/platform/weknora"
"net/http"
"strconv"
"strings"
@@ -97,6 +98,14 @@ func listMonitorTasks(w http.ResponseWriter, r *http.Request, config Config) {
writeJSON(w, 500, map[string]string{"error": "无法读取文件处理状态"})
return
}
// One origin per request: every row uses the same effective test endpoint the
// reconciliation scan used, so a KB opens at the same place from both tabs.
if config.WeKnoraWebBase != nil {
origin := config.WeKnoraWebBase(r.Context())
for i := range page.Items {
page.Items[i].WeKnoraURL = weknora.KnowledgeBaseConsoleURL(origin, page.Items[i].TargetKB)
}
}
// 目标同名不罕见(两侧都叫“对内知识库”):把当前生效绑定随页返回,
// 前端才能在同一口径下标注“当前绑定/历史”,而不是拿本页条目反推全局。
internal, external := config.effectiveRoutingTargets(r.Context())
+65 -1
View File
@@ -11,11 +11,16 @@ import (
type monitorTasksTestStore struct {
fakeJobStore
filter postgresstore.MonitorTaskFilter
items []postgresstore.MonitorTask
}
func (s *monitorTasksTestStore) ListMonitorTasks(_ context.Context, f postgresstore.MonitorTaskFilter) (postgresstore.MonitorTaskPage, error) {
s.filter = f
return postgresstore.MonitorTaskPage{Items: []postgresstore.MonitorTask{}, Total: 145, Limit: f.Limit, Offset: f.Offset}, nil
items := s.items
if items == nil {
items = []postgresstore.MonitorTask{}
}
return postgresstore.MonitorTaskPage{Items: items, Total: 145, Limit: f.Limit, Offset: f.Offset}, nil
}
func TestMonitorTasksRoute(t *testing.T) {
s := &monitorTasksTestStore{}
@@ -95,3 +100,62 @@ func TestMonitorTasksReportsEffectiveTargetBindings(t *testing.T) {
t.Fatalf("bindings = %#v, want the persisted current bindings", payload.Data.Bindings)
}
}
// The platform drawer's 503 fallback needs the same jump link a finding carries.
// The handler, not the browser, decides the origin: it must use the effective
// test endpoint, and an unwired resolver must leave the field empty instead of
// inventing a host.
func TestMonitorTasksAddsWeKnoraConsoleURL(t *testing.T) {
store := &monitorTasksTestStore{items: []postgresstore.MonitorTask{{ID: "mt-1", TargetKB: "kb-1"}}}
handler, err := NewHandler(Config{
Store: store,
WeKnoraWebBase: func(context.Context) string { return "https://weknora.test/" },
})
if err != nil {
t.Fatal(err)
}
req := httptest.NewRequest("GET", "/api/v1/monitor/tasks?limit=20", nil)
req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleViewer}))
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
if recorder.Code != 200 {
t.Fatalf("status %d: %s", recorder.Code, recorder.Body.String())
}
var payload struct {
Data struct {
Items []struct {
WeKnoraURL string `json:"weknora_url"`
} `json:"items"`
} `json:"data"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if len(payload.Data.Items) != 1 || payload.Data.Items[0].WeKnoraURL != "https://weknora.test/platform/knowledge-bases/kb-1" {
t.Fatalf("weknora_url = %#v", payload.Data.Items)
}
store.items = []postgresstore.MonitorTask{{ID: "mt-1", TargetKB: "kb-1"}}
unwired, err := NewHandler(Config{Store: store})
if err != nil {
t.Fatal(err)
}
recorder = httptest.NewRecorder()
unwired.ServeHTTP(recorder, req)
if recorder.Code != 200 {
t.Fatalf("unwired status %d: %s", recorder.Code, recorder.Body.String())
}
payload = struct {
Data struct {
Items []struct {
WeKnoraURL string `json:"weknora_url"`
} `json:"items"`
} `json:"data"`
}{}
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if len(payload.Data.Items) != 1 || payload.Data.Items[0].WeKnoraURL != "" {
t.Fatalf("unwired weknora_url = %#v", payload.Data.Items)
}
}
+5 -1
View File
@@ -136,7 +136,11 @@ type Config struct {
Monitor MonitorProvider
// Reconciliation is the T6 reconciliation domain. Nil keeps the routes
// unavailable instead of returning fake empty batches.
Reconciliation ReconciliationService
Reconciliation ReconciliationService
// WeKnoraWebBase resolves the test WeKnora console origin used to build the
// drawer jump link on /monitor/tasks rows. Nil (or an empty answer) leaves
// weknora_url empty; the contract allows that, and no host is invented.
WeKnoraWebBase func(context.Context) string
InternalRoutingKnowledgeBaseID string
ExternalRoutingKnowledgeBaseID string
RoutingBindings RoutingBindingStore
+13 -9
View File
@@ -29,15 +29,19 @@ type MonitorTask struct {
TargetScope string `json:"target_scope"`
TargetKB string `json:"target_kb"`
DocumentID string `json:"document_id"`
Action string `json:"action"`
Stage string `json:"stage"`
Status string `json:"status"`
Detail string `json:"detail"`
UpdatedAt string `json:"updated_at"`
RetryKind string `json:"retry_kind"`
FailureID string `json:"failure_id"`
RetryCount int `json:"retry_count"`
VersionID string `json:"version_id"`
// WeKnoraURL is the console link for this row's target knowledge base. The
// handler fills it from the effective test endpoint so the detail drawer can
// offer the same jump link as a reconciliation finding; empty = not configured.
WeKnoraURL string `json:"weknora_url"`
Action string `json:"action"`
Stage string `json:"stage"`
Status string `json:"status"`
Detail string `json:"detail"`
UpdatedAt string `json:"updated_at"`
RetryKind string `json:"retry_kind"`
FailureID string `json:"failure_id"`
RetryCount int `json:"retry_count"`
VersionID string `json:"version_id"`
}
type MonitorTaskPage struct {
Items []MonitorTask `json:"items"`
@@ -128,4 +128,23 @@ func TestMonitorTasksUnifiedPaginationIntegration(t *testing.T) {
exec(`UPDATE jobs SET state='retry' WHERE id='mt-fetch-job'`)
check("retrying", 0)
})
t.Run("weknora stage facet merges parsing and indexing in SQL", func(t *testing.T) {
insertReviewFixture(t, ctx, pool, 8, "mt-merge-parse", now)
insertReviewFixture(t, ctx, pool, 9, "mt-merge-index", now)
exec(`UPDATE test_publications SET processing_state='processing' WHERE id='mt-merge-parse'`)
exec(`UPDATE test_publications SET processing_state='finalizing' WHERE id='mt-merge-index'`)
query := MonitorTaskFilter{Search: "Synthetic mt-merge", Limit: 20}
merged, err := store.ListMonitorTasks(ctx, MonitorTaskFilter{Search: query.Search, Stage: "weknora", Limit: query.Limit})
if err != nil || merged.Total != 2 {
t.Fatalf("weknora facet: %#v %v", merged, err)
}
parsing, err := store.ListMonitorTasks(ctx, MonitorTaskFilter{Search: query.Search, Stage: "parsing", Limit: query.Limit})
if err != nil || parsing.Total != 1 || parsing.Items[0].ID != "mt-merge-parse" {
t.Fatalf("parsing facet: %#v %v", parsing, err)
}
indexing, err := store.ListMonitorTasks(ctx, MonitorTaskFilter{Search: query.Search, Stage: "indexing", Limit: query.Limit})
if err != nil || indexing.Total != 1 || indexing.Items[0].ID != "mt-merge-index" {
t.Fatalf("indexing facet: %#v %v", indexing, err)
}
})
}
+20
View File
@@ -0,0 +1,20 @@
package weknora
import (
"net/url"
"strings"
)
// KnowledgeBaseConsoleURL builds the console link for one knowledge base.
// Reconciliation findings and the platform task drawer both use this rule: if
// they drift, the same knowledge base opens at two different addresses, and the
// 503 fallback link in one drawer points somewhere else than the other.
// An empty origin or base id yields an empty link, which both callers treat as
// "no link configured" rather than inventing a host.
func KnowledgeBaseConsoleURL(origin, knowledgeBaseID string) string {
origin, knowledgeBaseID = strings.TrimSpace(origin), strings.TrimSpace(knowledgeBaseID)
if origin == "" || knowledgeBaseID == "" {
return ""
}
return strings.TrimSuffix(origin, "/") + "/platform/knowledge-bases/" + url.PathEscape(knowledgeBaseID)
}
@@ -0,0 +1,19 @@
package weknora
import "testing"
func TestKnowledgeBaseConsoleURLCannotInventAHost(t *testing.T) {
cases := []struct{ origin, kb, want string }{
{"", "kb-1", ""},
{"https://weknora.test", "", ""},
{" ", "kb-1", ""},
{"https://weknora.test/", "kb-1", "https://weknora.test/platform/knowledge-bases/kb-1"},
{" https://weknora.test/ ", " kb-1 ", "https://weknora.test/platform/knowledge-bases/kb-1"},
{"https://weknora.test/base", "kb 1", "https://weknora.test/base/platform/knowledge-bases/kb%201"},
}
for _, c := range cases {
if got := KnowledgeBaseConsoleURL(c.origin, c.kb); got != c.want {
t.Fatalf("KnowledgeBaseConsoleURL(%q,%q) = %q, want %q", c.origin, c.kb, got, c.want)
}
}
}
+39
View File
@@ -68,3 +68,42 @@ func TestRuntimeProviderUnavailableAndNotFound(t *testing.T) {
t.Fatalf("missing document err=%v", err)
}
}
// The progress passthrough is a projection, not a proxy: whatever extra fields
// the platform endpoint returns (keys, authorization headers, token echoes) must
// never reach the browser. This guards the shape if someone later switches to
// forwarding the upstream body.
func TestRuntimeProviderDropsSensitiveUpstreamFields(t *testing.T) {
const secret = "leak-sentinel"
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode(map[string]any{"success": true, "data": map[string]any{
"document": map[string]any{
"id": "doc-1", "parse_status": "completed", "ingestion_status": "completed", "wiki_status": "none",
"api_key": secret, "apiKey": secret, "authorization": "Bearer " + secret,
"headers": map[string]any{"X-API-Key": secret},
},
"failures": []map[string]any{},
"has_more_failures": false,
"api_key": secret,
}})
}))
defer server.Close()
provider := NewRuntimeProvider(RuntimeConfig{
BaseURL: func(context.Context) string { return server.URL },
APIKey: "runtime-key", Timeout: 5 * time.Second,
})
progress, err := provider.DocumentProgress(context.Background(), "doc-1")
if err != nil {
t.Fatal(err)
}
payload, err := json.Marshal(progress)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(payload), secret) || strings.Contains(string(payload), "Bearer ") {
t.Fatalf("progress leaked upstream credentials: %s", payload)
}
if progress.DocumentID != "doc-1" || progress.ParseStatus != "completed" {
t.Fatalf("projection dropped real fields: %#v", progress)
}
}
+2 -5
View File
@@ -5,7 +5,6 @@ import (
"crypto/sha256"
"encoding/hex"
"fmt"
"net/url"
"sort"
"strings"
"sync"
@@ -153,10 +152,8 @@ func (s *Service) buildFindings(ctx context.Context, run governance.Reconciliati
}
finding.ActionState = "open"
finding.ID = deterministicFindingID(run.ID, finding)
if finding.WeKnoraURL == "" && run.KBID != "" && s.weKnoraWebBase != nil {
if base := strings.TrimSpace(s.weKnoraWebBase(ctx)); base != "" {
finding.WeKnoraURL = strings.TrimSuffix(base, "/") + "/platform/knowledge-bases/" + url.PathEscape(run.KBID)
}
if finding.WeKnoraURL == "" && s.weKnoraWebBase != nil {
finding.WeKnoraURL = weknora.KnowledgeBaseConsoleURL(s.weKnoraWebBase(ctx), run.KBID)
}
findings = append(findings, finding)
}
+72 -10
View File
@@ -2,7 +2,11 @@ package reconciliation
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"testing"
@@ -10,6 +14,8 @@ import (
"knowledge-governance/internal/governance"
"knowledge-governance/internal/platform/weknora"
"knowledge-governance/internal/readiness"
"knowledge-governance/internal/weknoraaccess"
)
func TestMatrixCoversEveryLedgerAndUpstreamState(t *testing.T) {
@@ -199,9 +205,63 @@ func TestExecuteRunFindsR1ToR8WithoutRemoteWrites(t *testing.T) {
ledger: ledger,
removal: []governance.ReconciliationLedgerRow{{PublicationID: "pub-r6"}},
}
remote := &fakeReconciliationRemote{
items: items, missing: map[string]bool{"doc-r1": true},
gets: map[string]weknora.Knowledge{"doc-r2": items[0]},
// The ledger scan must be read-only over the wire, not merely against a fake
// that remembers it has no write methods. This server speaks the real client
// protocol and records every non-GET request.
var mu sync.Mutex
var writes []string
var pageSizes []int
listInFlight, maxInFlight := 0, 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
if r.Method != http.MethodGet {
writes = append(writes, r.Method+" "+r.URL.Path)
}
mu.Unlock()
path := r.URL.Path
switch {
case path == "/api/v1/knowledge-bases/kb-1":
_ = json.NewEncoder(w).Encode(map[string]any{"success": true, "data": map[string]any{"id": "kb-1", "tenant_id": 7}})
case path == "/api/v1/knowledge-bases/kb-1/knowledge":
size, _ := strconv.Atoi(r.URL.Query().Get("page_size"))
mu.Lock()
pageSizes = append(pageSizes, size)
listInFlight++
if listInFlight > maxInFlight {
maxInFlight = listInFlight
}
mu.Unlock()
defer func() {
mu.Lock()
listInFlight--
mu.Unlock()
}()
_ = json.NewEncoder(w).Encode(map[string]any{"success": true, "data": items, "total": len(items), "page": 1, "page_size": size})
case strings.HasPrefix(path, "/api/v1/knowledge/"):
id := strings.TrimPrefix(path, "/api/v1/knowledge/")
if id == "doc-r1" {
w.WriteHeader(http.StatusNotFound)
_ = json.NewEncoder(w).Encode(map[string]any{"success": false, "message": "not found"})
return
}
for _, item := range items {
if item.ID == id {
_ = json.NewEncoder(w).Encode(map[string]any{"success": true, "data": item})
return
}
}
w.WriteHeader(http.StatusNotFound)
_ = json.NewEncoder(w).Encode(map[string]any{"success": false, "message": "not found"})
default:
w.WriteHeader(http.StatusNotFound)
}
}))
defer server.Close()
remote := &weknoraaccess.Client{
Resolver: readiness.Resolver{ResolveConnection: func(context.Context) (string, string, error) {
return server.URL, "test-key", nil
}},
Timeout: 5 * time.Second,
}
service, err := New(Config{Store: store, Remote: remote, Now: func() time.Time { return now },
Grace: 30 * time.Minute, StallAfter: 2 * time.Hour, StaleAfter: 6 * time.Hour,
@@ -214,16 +274,18 @@ func TestExecuteRunFindsR1ToR8WithoutRemoteWrites(t *testing.T) {
t.Fatal(err)
}
if store.completedRun == nil {
t.Fatal("run was not completed")
t.Fatalf("run was not completed: fail code %q", store.failCode)
}
if remote.deleteCalls != 0 {
t.Fatalf("reconciliation wrote remotely: %d", remote.deleteCalls)
mu.Lock()
defer mu.Unlock()
if len(writes) != 0 {
t.Fatalf("reconciliation wrote remotely over HTTP: %v", writes)
}
if len(remote.pageSizes) == 0 || remote.pageSizes[0] != scanPageSize {
t.Fatalf("page size = %v, want %d", remote.pageSizes, scanPageSize)
if len(pageSizes) == 0 || pageSizes[0] != scanPageSize {
t.Fatalf("page size = %v, want %d", pageSizes, scanPageSize)
}
if remote.maxInFlight != 1 {
t.Fatalf("scan in-flight peak = %d, want 1", remote.maxInFlight)
if maxInFlight != 1 {
t.Fatalf("scan in-flight peak = %d, want 1", maxInFlight)
}
got := map[string]int{}
for _, finding := range store.findings {
+68
View File
@@ -0,0 +1,68 @@
// @vitest-environment jsdom
import { act } from 'react'
import { createRoot } from 'react-dom/client'
import type { Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { TaskDetail } from './WeKnoraMonitor'
import type { MonitorTask } from './monitorTasks'
const item: MonitorTask = {
id: 'tp-1',
title: '维护手册.pdf',
path: '产品/维护',
node_id: 'node-1',
parent_node_id: 'folder-1',
source_id: 's1',
source_name: '技术资料',
target_scope: 'internal',
target_kb: 'kb-1',
document_id: 'doc-1',
weknora_url: 'https://weknora.test/platform/knowledge-bases/kb-1',
action: 'update',
stage: 'parsing',
status: 'running',
detail: '正在解析处理',
updated_at: '2026-12-01T02:00:00Z',
retry_kind: '',
failure_id: '',
retry_count: 0,
version_id: 'v1',
}
let container: HTMLDivElement
let root: Root
beforeEach(() => {
// React's test-only global; the test environment exposes it without a type.
const reactTestGlobal: { IS_REACT_ACT_ENVIRONMENT: boolean } = globalThis as unknown as {
IS_REACT_ACT_ENVIRONMENT: boolean
}
reactTestGlobal.IS_REACT_ACT_ENVIRONMENT = true
// jsdom does not implement the dialog methods the drawer calls on mount.
HTMLDialogElement.prototype.showModal = function showModal(this: HTMLDialogElement) {
this.open = true
}
container = document.createElement('div')
document.body.appendChild(container)
root = createRoot(container)
})
afterEach(() => {
act(() => root.unmount())
container.remove()
vi.unstubAllGlobals()
})
describe('platform task drawer', () => {
it('offers the WeKnora jump link when progress answers 503', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue(
new Response(JSON.stringify({ error: 'runtime_read_unavailable', code: 'runtime_read_unavailable' }), {
status: 503,
})
)
)
await act(async () => root.render(<TaskDetail item={item} onClose={vi.fn()} />))
await act(async () => await Promise.resolve())
expect(container.textContent).toContain('未配置 WeKnora 只读 Key')
expect(container.querySelector('a[href="https://weknora.test/platform/knowledge-bases/kb-1"]')).not.toBeNull()
})
})
+4 -2
View File
@@ -506,7 +506,7 @@ export function WeKnoraMonitorView(p: ViewProps) {
</main>
)
}
function TaskDetail({
export function TaskDetail({
item,
onClose,
onLocateSource,
@@ -572,7 +572,9 @@ function TaskDetail({
))}
</section>
) : null}
{item.document_id ? <WeKnoraProgress documentID={item.document_id} compact /> : null}
{item.document_id ? (
<WeKnoraProgress documentID={item.document_id} weknoraURL={item.weknora_url} compact />
) : null}
<p className="monitor-muted">新增、更新完成表示测试库处理完成;移除完成表示测试库内容移除,不代表生产发布。</p>
{item.status === 'attention' ? (
<p className="monitor-alert">
+2
View File
@@ -10,6 +10,8 @@ export interface MonitorTask {
target_scope: string
target_kb: string
document_id?: string
// 目标测试知识库的控制台链接;后端按当前生效测试端点生成,未配置时为空。
weknora_url?: string
action: string
stage: string
status: string