feat(qaops): 接入真实模型补缺任务与总表看板
build / build (push) Successful in 1m12s

按已确认需求提供独立安全模型配置、真实探测、正式字典字段评估与原问题译中,持久批次支持只补空白、暂停恢复、有限重试、幂等和逐字段依据。覆盖固定规则、本地语言、组织关联与主表有效看板共用治理侧读模型,保留源生产和冻结历史。

验证:完整 make verify 退出0,702项Go与329项前端通过;默认118项外部/隔离集成明确跳过,另跑完整镜像及组织隔离PG竞态。12并发、输入漂移、过期租约、暂停/恢复及有限重试通过。用户授权的百炼 deepseek-v4.1-flash 完成真实后台与浏览器评估/翻译;552行、16列、11块看板及完整PNG、独立配置页测试/保存、重开恢复和零JS异常通过。仅非业务样本外发,自动处理关闭,原payload不变。

上线前治理库已做导出快照原生备份并真实恢复,60表行数与17个QA表内容哈希一致;不修改DobotAI生产或隧道。本提交时尚未部署,线上验收须独立完成。
This commit is contained in:
姚章浩
2026-10-19 14:29:49 +08:00
parent 330fd12b3f
commit 533db535f1
83 changed files with 5769 additions and 138 deletions
+64 -1
View File
@@ -47,8 +47,31 @@ func TestOpenAPIContractMatchesRegisteredRoutesAndOmitsSecrets(t *testing.T) {
}
}
var guardBaseURL func(any, string)
guardBaseURL = func(node any, path string) {
switch value := node.(type) {
case map[string]any:
for key, child := range value {
if key == "base_url" && path != "components.schemas.QAAISafeSettings.properties" && path != "components.schemas.QAAISaveSettings.properties" {
t.Fatalf("unapproved endpoint exposure at %s", path)
}
next := key
if path != "" {
next = path + "." + key
}
guardBaseURL(child, next)
}
case []any:
for _, child := range value {
guardBaseURL(child, path)
}
}
}
var tree any
_ = json.Unmarshal(contract, &tree)
guardBaseURL(tree, "")
lower := strings.ToLower(string(contract))
for _, forbidden := range []string{"secret_ref", "authorization_code", "manifest_sha256", "knowledge_id", "test_kb_id", "base_url", "download_code", "cookie"} {
for _, forbidden := range []string{"secret_ref", "authorization_code", "manifest_sha256", "knowledge_id", "test_kb_id", "download_code", "cookie"} {
if strings.Contains(lower, forbidden) {
t.Fatalf("OpenAPI contract must not expose %q", forbidden)
}
@@ -104,6 +127,46 @@ func TestOpenAPICatalogMutationsRequireIdempotencyKeyHeader(t *testing.T) {
}
}
func TestQAAIContractDescribesAllAdministratorPathsAndWriteOnlyCredential(t *testing.T) {
raw, err := os.ReadFile("../../api/openapi.yaml")
if err != nil {
t.Fatal(err)
}
var document struct {
Paths map[string]map[string]any `json:"paths"`
Components struct {
Schemas map[string]map[string]any `json:"schemas"`
} `json:"components"`
}
if json.Unmarshal(raw, &document) != nil {
t.Fatal("invalid API document")
}
for _, route := range []struct{ path, method string }{{"/settings", "get"}, {"/settings", "post"}, {"/settings/test", "post"}, {"/automation", "post"}, {"/previews", "post"}, {"/batches", "post"}, {"/batches/{id}/actions", "post"}, {"/status", "get"}, {"/records/{id}", "get"}} {
path := "/api/v1/qa-ops/ai" + route.path
op, ok := document.Paths[path][route.method].(map[string]any)
if !ok {
t.Fatalf("missing %s %s", route.method, path)
}
responses, _ := op["responses"].(map[string]any)
for _, status := range []string{"400", "401", "403", "500", "503"} {
if responses[status] == nil {
t.Fatalf("missing %s for %s", status, path)
}
}
}
safe := document.Components.Schemas["QAAISafeSettings"]
properties, _ := safe["properties"].(map[string]any)
if properties["api_key"] != nil || properties["key_ciphertext"] != nil || properties["key_configured"] == nil || safe["additionalProperties"] != false {
t.Fatal("safe settings contract exposes secrets or accepts unknown fields")
}
input := document.Components.Schemas["QAAISaveSettings"]
properties, _ = input["properties"].(map[string]any)
key, _ := properties["api_key"].(map[string]any)
if key["writeOnly"] != true {
t.Fatal("API key request property is not write-only")
}
}
func stringValue(value any) string {
result, _ := value.(string)
return result
+208
View File
@@ -0,0 +1,208 @@
package httpapi
import (
"errors"
"knowledge-governance/internal/qaopsai"
"net"
"net/http"
"net/url"
"strings"
)
func qaAIError(w http.ResponseWriter, err error) {
status, code, message := 503, "qa_ai_unavailable", "问答AI存储或安全配置不可用,请检查独立模型配置与执行器;未将失败伪装为成功或空结果"
switch {
case errors.Is(err, qaopsai.ErrInvalid):
status, code, message = 400, "qa_ai_invalid_request", "参数、正式标签或模型输出校验未通过;更换API地址时须重新录入密钥,不能把旧密钥发送到新地址"
case errors.Is(err, qaopsai.ErrConflict):
status, code, message = 409, "qa_ai_version_conflict", "配置、输入、人工复核或预览已变化,请刷新;现有结论未被覆盖"
default:
var remote *qaopsai.RemoteError
if errors.As(err, &remote) {
status, code, message = 422, "qa_ai_"+remote.Code, "模型服务明确拒绝或未返回合格结果,配置未启用;请核对密钥、模型与JSON输出支持"
}
}
writeJSON(w, status, map[string]string{"error": message, "code": code})
}
func qaAIReady(w http.ResponseWriter, r *http.Request, c Config) bool {
if !authorizeQAOps(w, r) {
return false
}
if r.Method != "GET" && !authorizeQAIntent(w, r, "qa-ai") {
return false
}
if c.QAAI == nil {
qaAIError(w, qaopsai.ErrUnavailable)
return false
}
if r.URL.RawQuery != "" {
qaAIError(w, qaopsai.ErrInvalid)
return false
}
return true
}
func qaAISecretTransport(r *http.Request, c Config) bool {
if r.TLS != nil {
return true
}
host := r.Host
if parsed, _, err := net.SplitHostPort(host); err == nil {
host = parsed
}
if strings.EqualFold(host, "localhost") {
return true
}
if ip := net.ParseIP(host); ip != nil && ip.IsLoopback() {
return true
}
if c.QAAITrustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" && r.Header.Get("Sec-Fetch-Site") == "same-origin" {
origin, err := url.Parse(r.Header.Get("Origin"))
return err == nil && origin.Scheme == "https"
}
return false
}
func registerQAAIRoutes(mux *http.ServeMux, c Config) {
mux.HandleFunc("GET /api/v1/qa-ops/ai/settings", func(w http.ResponseWriter, r *http.Request) {
if !qaAIReady(w, r, c) {
return
}
data, err := c.QAAI.GetSettings(r.Context())
if err != nil {
qaAIError(w, err)
return
}
writeJSON(w, 200, map[string]any{"data": data})
})
for _, test := range []bool{false, true} {
path := "POST /api/v1/qa-ops/ai/settings"
if test {
path += "/test"
}
mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
if !qaAIReady(w, r, c) {
return
}
var input qaopsai.SaveSettings
if decodeQualityJSON(w, r, &input, "base_revision", "base_url", "model", "key_action") != nil {
qaAIError(w, qaopsai.ErrInvalid)
return
}
if input.APIKey != "" && !qaAISecretTransport(r, c) {
writeJSON(w, 400, map[string]string{"code": "qa_ai_secure_transport_required", "error": "密钥仅可通过有效HTTPS或本机回环地址录入;未保存、未发送密钥"})
return
}
identity, _ := sessionFrom(r.Context())
var data qaopsai.Settings
var err error
if test {
data, err = c.QAAI.TestSettings(r.Context(), input)
} else {
data, err = c.QAAI.SaveSettings(r.Context(), input, identity.Username)
}
if err != nil {
qaAIError(w, err)
return
}
writeJSON(w, 200, map[string]any{"data": data})
})
}
mux.HandleFunc("POST /api/v1/qa-ops/ai/automation", func(w http.ResponseWriter, r *http.Request) {
if !qaAIReady(w, r, c) {
return
}
var input struct {
Kind string `json:"kind"`
Enabled bool `json:"enabled"`
}
if decodeQualityJSON(w, r, &input, "kind", "enabled") != nil {
qaAIError(w, qaopsai.ErrInvalid)
return
}
identity, _ := sessionFrom(r.Context())
data, err := c.QAAI.SetAutomation(r.Context(), input.Kind, input.Enabled, identity.Username)
if err != nil {
qaAIError(w, err)
return
}
writeJSON(w, 200, map[string]any{"data": data})
})
mux.HandleFunc("POST /api/v1/qa-ops/ai/previews", func(w http.ResponseWriter, r *http.Request) {
if !qaAIReady(w, r, c) {
return
}
var input qaopsai.Scope
if decodeQualityJSON(w, r, &input, "kind") != nil {
qaAIError(w, qaopsai.ErrInvalid)
return
}
identity, _ := sessionFrom(r.Context())
data, err := c.QAAI.Preview(r.Context(), input, identity.Username)
if err != nil {
qaAIError(w, err)
return
}
writeJSON(w, 200, map[string]any{"data": data})
})
mux.HandleFunc("POST /api/v1/qa-ops/ai/batches", func(w http.ResponseWriter, r *http.Request) {
if !qaAIReady(w, r, c) {
return
}
var input struct {
PreviewID string `json:"preview_id"`
Nonce string `json:"nonce"`
}
if decodeQualityJSON(w, r, &input, "preview_id", "nonce") != nil {
qaAIError(w, qaopsai.ErrInvalid)
return
}
identity, _ := sessionFrom(r.Context())
data, err := c.QAAI.Start(r.Context(), input.PreviewID, input.Nonce, identity.Username)
if err != nil {
qaAIError(w, err)
return
}
writeJSON(w, 202, map[string]any{"data": data})
})
mux.HandleFunc("POST /api/v1/qa-ops/ai/batches/{id}/actions", func(w http.ResponseWriter, r *http.Request) {
if !qaAIReady(w, r, c) {
return
}
var input struct {
Action string `json:"action"`
Nonce string `json:"nonce"`
}
if decodeQualityJSON(w, r, &input, "action", "nonce") != nil || r.Header.Get("Idempotency-Key") != input.Nonce {
qaAIError(w, qaopsai.ErrInvalid)
return
}
identity, _ := sessionFrom(r.Context())
data, err := c.QAAI.ManageBatch(r.Context(), r.PathValue("id"), input.Action, input.Nonce, identity.Username)
if err != nil {
qaAIError(w, err)
return
}
writeJSON(w, 200, map[string]any{"data": data})
})
mux.HandleFunc("GET /api/v1/qa-ops/ai/status", func(w http.ResponseWriter, r *http.Request) {
if !qaAIReady(w, r, c) {
return
}
data, err := c.QAAI.GetStatus(r.Context())
if err != nil {
qaAIError(w, err)
return
}
writeJSON(w, 200, map[string]any{"data": data})
})
mux.HandleFunc("GET /api/v1/qa-ops/ai/records/{id}", func(w http.ResponseWriter, r *http.Request) {
if !qaAIReady(w, r, c) {
return
}
data, err := c.QAAI.RecordEvidence(r.Context(), r.PathValue("id"))
if err != nil {
qaAIError(w, err)
return
}
writeJSON(w, 200, map[string]any{"data": data})
})
}
+53
View File
@@ -0,0 +1,53 @@
package httpapi
import (
"knowledge-governance/internal/qaopsai"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestAIUnavailableDoesNotFalselyClaimNoModelCallOccurred(t *testing.T) {
response := httptest.NewRecorder()
qaAIError(response, qaopsai.ErrUnavailable)
if strings.Contains(response.Body.String(), "未调用模型") {
t.Fatal("a persistence failure after a model call was reported as no call")
}
}
func TestAIEndpointsRequireAdminAndExplicitSameOriginWriteIntent(t *testing.T) {
auth := newFakeAuthStore()
auth.sessions["fixture-ai-admin"] = "usr-boss"
auth.sessions["fixture-ai-viewer"] = "usr-eye"
handler, err := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}})
if err != nil {
t.Fatal(err)
}
for _, route := range []struct{ method, path, body string }{{"GET", "/api/v1/qa-ops/ai/settings", ""}, {"GET", "/api/v1/qa-ops/ai/status", ""}, {"POST", "/api/v1/qa-ops/ai/settings", `{}`}, {"POST", "/api/v1/qa-ops/ai/settings/test", `{}`}, {"POST", "/api/v1/qa-ops/ai/previews", `{}`}, {"POST", "/api/v1/qa-ops/ai/batches", `{}`}, {"POST", "/api/v1/qa-ops/ai/automation", `{}`}, {"POST", "/api/v1/qa-ops/ai/batches/fixture/actions", `{}`}} {
for _, who := range []struct {
token string
want int
}{{"", 401}, {"fixture-ai-viewer", 403}, {"fixture-ai-admin", 503}} {
request := httptest.NewRequest(route.method, route.path, strings.NewReader(route.body))
if who.token != "" {
request.AddCookie(&http.Cookie{Name: sessionCookieName, Value: who.token})
}
request.Header.Set("X-Governance-Action", "qa-ai")
response := httptest.NewRecorder()
handler.ServeHTTP(response, request)
if response.Code != who.want {
t.Fatalf("%s %s role=%s status=%d want=%d", route.method, route.path, who.token, response.Code, who.want)
}
}
if route.method == "POST" {
request := httptest.NewRequest(route.method, route.path, strings.NewReader(route.body))
request.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "fixture-ai-admin"})
response := httptest.NewRecorder()
handler.ServeHTTP(response, request)
if response.Code != 403 {
t.Fatal("write without explicit action was accepted")
}
}
}
}
+5 -1
View File
@@ -34,7 +34,11 @@ func attributionVersion(p *qaopsorg.Attribution) dobotaiops.OrganizationVersion
return dobotaiops.OrganizationVersion{State: p.Metadata.State, DirectoryID: p.Metadata.DirectoryID, DirectorySource: p.Metadata.DirectorySource, SyncedAt: p.Metadata.DirectorySyncedAt, RevisionID: p.Metadata.RevisionID, Basis: "current_directory", RegionNames: p.Metadata.RegionLabels()}
}
func enrichQARecord(item *dobotaiops.Record, p *qaopsorg.Attribution) {
person := p.Resolve(item.Identity.StaffID, item.Identity.UnionID)
trigger := item.TriggerPerson
if raw, ok := item.MasterFields["trigger_person"]; ok {
trigger = raw
}
person := p.Resolve(item.Identity.StaffID, item.Identity.UnionID, item.Asker, trigger)
o := &dobotaiops.RecordOrganization{Version: attributionVersion(p), State: person.State, Departments: person.Departments, Region: person.Region, SourceDepartment: item.Department, SourceRegion: item.Region, DepartmentOrigin: "unavailable", RegionOrigin: "unavailable"}
if item.Department != "" {
o.DepartmentOrigin = "source_snapshot"
+2 -2
View File
@@ -11,7 +11,7 @@ import (
)
type qaDashboardReader interface {
ReadDashboard(context.Context, dobotaiops.RecordQuery) (qaopsmirror.Dashboard, error)
ReadMasterDashboard(context.Context, dobotaiops.RecordQuery) (qaopsmirror.Dashboard, error)
}
func qaOperationsDashboard(w http.ResponseWriter, r *http.Request, c Config) {
@@ -37,7 +37,7 @@ func qaOperationsDashboard(w http.ResponseWriter, r *http.Request, c Config) {
qaOpsError(w, e)
return
}
dashboard, e := reader.ReadDashboard(r.Context(), dobotaiops.RecordQuery{Window: window, Keyword: request.Keyword})
dashboard, e := reader.ReadMasterDashboard(r.Context(), dobotaiops.RecordQuery{Window: window, Keyword: request.Keyword})
if e != nil {
if errors.Is(e, qaopsquality.ErrConflict) {
writeQualityError(w, e)
+9 -4
View File
@@ -14,9 +14,10 @@ import (
type dashboardReaderSpy struct {
attributedReader
calls int
query dobotaiops.RecordQuery
err error
calls int
masterCalls int
query dobotaiops.RecordQuery
err error
}
func (s *dashboardReaderSpy) ReadDashboard(_ context.Context, q dobotaiops.RecordQuery) (qaopsmirror.Dashboard, error) {
@@ -24,6 +25,10 @@ func (s *dashboardReaderSpy) ReadDashboard(_ context.Context, q dobotaiops.Recor
s.query = q
return qaopsmirror.Dashboard{TotalIssues: 7, NewThisWeek: 2}, s.err
}
func (s *dashboardReaderSpy) ReadMasterDashboard(ctx context.Context, q dobotaiops.RecordQuery) (qaopsmirror.Dashboard, error) {
s.masterCalls++
return s.ReadDashboard(ctx, q)
}
func TestQADashboardIsFixedTenantAdminAndReadOnly(t *testing.T) {
reader := &dashboardReaderSpy{}
auth := newFakeAuthStore()
@@ -58,7 +63,7 @@ func TestQADashboardIsFixedTenantAdminAndReadOnly(t *testing.T) {
t.Fatal("private dashboard response may be cached")
}
}
if reader.calls != 1 || reader.query.Window.TenantKey != "fixed-dashboard-tenant" || reader.query.Keyword != "100%_" {
if reader.masterCalls != 1 || reader.calls != 1 || reader.query.Window.TenantKey != "fixed-dashboard-tenant" || reader.query.Keyword != "100%_" {
t.Fatal("rejected requests reached the reader or browser controlled the tenant")
}
reader.err = qaopsquality.ErrConflict
+5
View File
@@ -40,6 +40,11 @@ func (s qaMasterReader) ReadQualityScope(ctx context.Context, q dobotaiops.Recor
return s.master.ReadMasterQualityScope(ctx, q)
}
func (s qaMasterReader) ReadStoredQuality(ctx context.Context, keys []dobotaiops.QualityKey) (map[string]qaopsquality.View, error) {
if reader, ok := s.master.(interface {
ReadMasterQualityViews(context.Context, []dobotaiops.QualityKey) (map[string]qaopsquality.View, error)
}); ok {
return reader.ReadMasterQualityViews(ctx, keys)
}
return s.master.MasterQualityStore().ReadViews(ctx, keys)
}
func withQAMaster(w http.ResponseWriter, r *http.Request, c Config, handler func(http.ResponseWriter, *http.Request, Config)) {
+2 -31
View File
@@ -8,6 +8,7 @@ import (
"io"
"knowledge-governance/internal/dobotaiops"
"knowledge-governance/internal/qaopsquality"
"knowledge-governance/internal/strictjson"
"net/http"
"strconv"
"time"
@@ -95,37 +96,7 @@ func enrichQAQualityPage(ctx context.Context, c Config, page *dobotaiops.RecordP
dobotaiops.AddRecordColumns(page, columns...)
return nil
}
func walkQualityJSON(d *json.Decoder) error {
token, err := d.Token()
if err != nil {
return err
}
if token == nil {
return qaopsquality.ErrInvalid
}
if delimiter, ok := token.(json.Delim); ok {
if delimiter != '{' && delimiter != '[' {
return qaopsquality.ErrInvalid
}
keys := map[string]bool{}
for d.More() {
if delimiter == '{' {
key, e := d.Token()
name, ok := key.(string)
if e != nil || !ok || keys[name] {
return qaopsquality.ErrInvalid
}
keys[name] = true
}
if walkQualityJSON(d) != nil {
return qaopsquality.ErrInvalid
}
}
_, err = d.Token()
return err
}
return nil
}
func walkQualityJSON(d *json.Decoder) error { return strictjson.Walk(d) }
func decodeQualityJSON(w http.ResponseWriter, r *http.Request, target any, required ...string) error {
if r.URL.RawQuery != "" {
return qaopsquality.ErrInvalid
+4
View File
@@ -19,6 +19,7 @@ import (
"knowledge-governance/internal/jobs"
"knowledge-governance/internal/monitoring"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/qaopsai"
"knowledge-governance/internal/qaopsmirror"
"knowledge-governance/internal/qaopsorg"
)
@@ -103,6 +104,8 @@ type Store interface {
}
type Config struct {
QAAI *qaopsai.Store
QAAITrustTLSProxy bool
QAQuality QAQualityStore
QAOrgSync QAOrgSyncStore
QAOrgSyncEnabled bool
@@ -177,6 +180,7 @@ func NewHandler(config Config) (http.Handler, error) {
config.NewID = newID
}
mux := http.NewServeMux()
registerQAAIRoutes(mux, config)
mux.HandleFunc("POST /api/v1/qa-ops/dashboard", func(w http.ResponseWriter, r *http.Request) { qaOperationsDashboard(w, r, config) })
mux.HandleFunc("POST /api/v1/qa-ops/quality/query", func(w http.ResponseWriter, r *http.Request) { qaQualityQuery(w, r, config) })
mux.HandleFunc("POST /api/v1/qa-ops/records/{id}/reviews", func(w http.ResponseWriter, r *http.Request) { qaQualityReview(w, r, config) })