feat(ECR-023): AICoreConfig KnowledgeSource 只读并 Closed
运营可观测知识源目录(knowledge_sources + admin /ai),不含 Chunk/Embedding。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -321,6 +321,32 @@ export const adminApi = {
|
||||
system: boolean
|
||||
updated_at: string
|
||||
}>('GET', `/ai/system-prompts/${id}`),
|
||||
knowledgeSources: () =>
|
||||
request<{
|
||||
items: Array<{
|
||||
id: string
|
||||
code: string
|
||||
title: string
|
||||
description?: string
|
||||
source_kind: string
|
||||
version: number
|
||||
active: boolean
|
||||
system: boolean
|
||||
updated_at: string
|
||||
}>
|
||||
}>('GET', '/ai/knowledge-sources'),
|
||||
knowledgeSource: (id: string) =>
|
||||
request<{
|
||||
id: string
|
||||
code: string
|
||||
title: string
|
||||
description?: string
|
||||
source_kind: string
|
||||
version: number
|
||||
active: boolean
|
||||
system: boolean
|
||||
updated_at: string
|
||||
}>('GET', `/ai/knowledge-sources/${id}`),
|
||||
crisisPolicies: () =>
|
||||
request<{
|
||||
items: Array<{
|
||||
|
||||
@@ -3,6 +3,7 @@ import { onMounted, ref } from 'vue'
|
||||
import { adminApi } from '@/api/client'
|
||||
|
||||
type Prompt = Awaited<ReturnType<typeof adminApi.systemPrompts>>['items'][number]
|
||||
type Source = Awaited<ReturnType<typeof adminApi.knowledgeSources>>['items'][number]
|
||||
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
@@ -10,6 +11,12 @@ const items = ref<Prompt[]>([])
|
||||
const selected = ref<Prompt | null>(null)
|
||||
const detailErr = ref('')
|
||||
|
||||
const ksLoading = ref(false)
|
||||
const ksError = ref('')
|
||||
const sources = ref<Source[]>([])
|
||||
const selectedSource = ref<Source | null>(null)
|
||||
const ksDetailErr = ref('')
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
@@ -23,6 +30,19 @@ async function load() {
|
||||
}
|
||||
}
|
||||
|
||||
async function loadSources() {
|
||||
ksLoading.value = true
|
||||
ksError.value = ''
|
||||
try {
|
||||
const res = await adminApi.knowledgeSources()
|
||||
sources.value = res.items || []
|
||||
} catch (e) {
|
||||
ksError.value = e instanceof Error ? e.message : '加载失败'
|
||||
} finally {
|
||||
ksLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function openPrompt(id: string) {
|
||||
detailErr.value = ''
|
||||
try {
|
||||
@@ -33,6 +53,16 @@ async function openPrompt(id: string) {
|
||||
}
|
||||
}
|
||||
|
||||
async function openSource(id: string) {
|
||||
ksDetailErr.value = ''
|
||||
try {
|
||||
selectedSource.value = await adminApi.knowledgeSource(id)
|
||||
} catch (e) {
|
||||
ksDetailErr.value = e instanceof Error ? e.message : '详情失败'
|
||||
selectedSource.value = null
|
||||
}
|
||||
}
|
||||
|
||||
function fmtTime(iso?: string) {
|
||||
if (!iso) return '—'
|
||||
try {
|
||||
@@ -42,13 +72,16 @@ function fmtTime(iso?: string) {
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
onMounted(() => {
|
||||
void load()
|
||||
void loadSources()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section>
|
||||
<h1>AI 配置</h1>
|
||||
<p class="muted">SystemPrompt 只读目录 · 本切片不可编辑发布</p>
|
||||
<p class="muted">SystemPrompt / KnowledgeSource 只读目录 · 本切片不可编辑发布</p>
|
||||
<p v-if="loading" class="muted">加载中…</p>
|
||||
<p v-else-if="error" class="err">{{ error }}</p>
|
||||
<div v-else class="layout">
|
||||
@@ -80,6 +113,41 @@ onMounted(load)
|
||||
<p v-else class="muted">选择左侧提示词查看正文</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p v-if="ksLoading" class="muted ks-gap">知识源加载中…</p>
|
||||
<p v-else-if="ksError" class="err ks-gap">{{ ksError }}</p>
|
||||
<div v-else class="layout ks-gap">
|
||||
<div class="card">
|
||||
<h2>知识源</h2>
|
||||
<p v-if="!sources.length" class="muted">暂无</p>
|
||||
<table v-else>
|
||||
<thead>
|
||||
<tr><th>代码</th><th>标题</th><th>类型</th><th>状态</th><th></th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="s in sources" :key="s.id">
|
||||
<td><code>{{ s.code }}</code></td>
|
||||
<td>{{ s.title }}</td>
|
||||
<td>{{ s.source_kind }}</td>
|
||||
<td>{{ s.active ? '启用' : '停用' }}{{ s.system ? ' · 系统' : '' }}</td>
|
||||
<td><button class="btn" type="button" @click="openSource(s.id)">查看</button></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>知识源详情</h2>
|
||||
<p v-if="ksDetailErr" class="err">{{ ksDetailErr }}</p>
|
||||
<template v-else-if="selectedSource">
|
||||
<p class="meta">
|
||||
{{ selectedSource.title }} · {{ selectedSource.source_kind }} ·
|
||||
更新 {{ fmtTime(selectedSource.updated_at) }}
|
||||
</p>
|
||||
<p>{{ selectedSource.description || '无描述' }}</p>
|
||||
</template>
|
||||
<p v-else class="muted">选择左侧知识源查看详情</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
@@ -87,6 +155,7 @@ onMounted(load)
|
||||
h1 { margin: 0 0 0.35rem; font-size: 1.35rem; }
|
||||
h2 { margin: 0 0 0.6rem; font-size: 1.05rem; }
|
||||
.layout { display: grid; grid-template-columns: 1fr 1.1fr; gap: 1rem; margin-top: 1rem; }
|
||||
.ks-gap { margin-top: 1.5rem; }
|
||||
.meta { color: var(--muted); font-size: 0.85rem; margin-bottom: 0.5rem; }
|
||||
pre {
|
||||
margin: 0;
|
||||
|
||||
@@ -16,6 +16,8 @@ func (h *AdminHandler) registerAIConfig(authed *gin.RouterGroup) {
|
||||
g := authed.Group("/ai")
|
||||
g.GET("/system-prompts", middleware.RequireAdminPermission(h.Svc, admin.PermAIConfigRead), h.ListSystemPrompts)
|
||||
g.GET("/system-prompts/:id", middleware.RequireAdminPermission(h.Svc, admin.PermAIConfigRead), h.GetSystemPrompt)
|
||||
g.GET("/knowledge-sources", middleware.RequireAdminPermission(h.Svc, admin.PermAIConfigRead), h.ListKnowledgeSources)
|
||||
g.GET("/knowledge-sources/:id", middleware.RequireAdminPermission(h.Svc, admin.PermAIConfigRead), h.GetKnowledgeSource)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) ListSystemPrompts(c *gin.Context) {
|
||||
@@ -44,3 +46,30 @@ func (h *AdminHandler) GetSystemPrompt(c *gin.Context) {
|
||||
}
|
||||
response.OK(c, row)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) ListKnowledgeSources(c *gin.Context) {
|
||||
items, err := h.Svc.ListKnowledgeSources(c.Request.Context())
|
||||
if err != nil {
|
||||
response.Fail(c, http.StatusInternalServerError, 50029, "list knowledge sources failed")
|
||||
return
|
||||
}
|
||||
response.OK(c, gin.H{"items": items})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) GetKnowledgeSource(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
response.Fail(c, http.StatusBadRequest, 40002, "invalid id")
|
||||
return
|
||||
}
|
||||
row, err := h.Svc.GetKnowledgeSource(c.Request.Context(), id)
|
||||
if errors.Is(err, admin.ErrKnowledgeSourceNotFound) {
|
||||
response.Fail(c, http.StatusNotFound, 40405, "knowledge source not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.Fail(c, http.StatusInternalServerError, 50030, "get knowledge source failed")
|
||||
return
|
||||
}
|
||||
response.OK(c, row)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func TestAICoreKnowledgeSources(t *testing.T) {
|
||||
r, pool := setupAPIPool(t)
|
||||
ctx := context.Background()
|
||||
tok := adminLogin(t, r, "admin", "change-me")
|
||||
|
||||
_, code := doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/ai/knowledge-sources", nil, "")
|
||||
if code != http.StatusUnauthorized {
|
||||
t.Fatalf("expected 401, got %d", code)
|
||||
}
|
||||
|
||||
limitedRoleID := uuid.New()
|
||||
_, err := pool.Exec(ctx, `
|
||||
INSERT INTO admin_roles(id, name, system) VALUES ($1,$2,false)`,
|
||||
limitedRoleID, "ks_lim_"+limitedRoleID.String()[:8])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = pool.Exec(ctx, `
|
||||
INSERT INTO admin_role_permissions(role_id, code) VALUES ($1,'admin.users.read')`, limitedRoleID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte("limited-pass"), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
limUser := fmt.Sprintf("kslim_%d", time.Now().UnixNano())
|
||||
_, err = pool.Exec(ctx, `
|
||||
INSERT INTO admin_accounts(username, password_hash, role_id) VALUES ($1,$2,$3)`,
|
||||
limUser, string(hash), limitedRoleID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_, _ = pool.Exec(ctx, `DELETE FROM admin_accounts WHERE username=$1`, limUser)
|
||||
_, _ = pool.Exec(ctx, `DELETE FROM admin_roles WHERE id=$1`, limitedRoleID)
|
||||
})
|
||||
limTok := adminLogin(t, r, limUser, "limited-pass")
|
||||
_, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/ai/knowledge-sources", nil, limTok)
|
||||
if code != http.StatusForbidden {
|
||||
t.Fatalf("expected 403, got %d", code)
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
env, code := doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/ai/knowledge-sources", nil, tok)
|
||||
if code != 200 || env.Code != 0 {
|
||||
t.Fatalf("list http=%d msg=%s", code, env.Message)
|
||||
}
|
||||
if time.Since(start) > 500*time.Millisecond {
|
||||
t.Fatalf("list too slow %v", time.Since(start))
|
||||
}
|
||||
var list struct {
|
||||
Items []struct {
|
||||
ID string `json:"id"`
|
||||
Code string `json:"code"`
|
||||
SourceKind string `json:"source_kind"`
|
||||
} `json:"items"`
|
||||
}
|
||||
_ = json.Unmarshal(env.Data, &list)
|
||||
var srcID string
|
||||
for _, it := range list.Items {
|
||||
if it.Code == "ask_grounding" {
|
||||
srcID = it.ID
|
||||
if it.SourceKind != "faq" && it.SourceKind != "policy" && it.SourceKind != "guide" {
|
||||
t.Fatalf("bad source_kind %q", it.SourceKind)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
if srcID == "" {
|
||||
t.Fatalf("missing ask_grounding: %#v", list.Items)
|
||||
}
|
||||
|
||||
env, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/ai/knowledge-sources/"+srcID, nil, tok)
|
||||
if code != 200 {
|
||||
t.Fatalf("get %d", code)
|
||||
}
|
||||
var detail struct {
|
||||
Code string `json:"code"`
|
||||
SourceKind string `json:"source_kind"`
|
||||
}
|
||||
_ = json.Unmarshal(env.Data, &detail)
|
||||
if detail.Code != "ask_grounding" || detail.SourceKind == "" {
|
||||
t.Fatalf("bad detail %#v", detail)
|
||||
}
|
||||
|
||||
_, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/ai/knowledge-sources/"+fakeUUID(), nil, tok)
|
||||
if code != http.StatusNotFound {
|
||||
t.Fatalf("expected 404, got %d", code)
|
||||
}
|
||||
}
|
||||
@@ -60,3 +60,59 @@ func (r *AdminRepo) GetSystemPrompt(ctx context.Context, id uuid.UUID) (*SystemP
|
||||
}
|
||||
return &p, nil
|
||||
}
|
||||
|
||||
// KnowledgeSourceRow is AICoreConfig KnowledgeSource catalog row.
|
||||
type KnowledgeSourceRow struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Code string `json:"code"`
|
||||
Title string `json:"title"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
SourceKind string `json:"source_kind"`
|
||||
Version int `json:"version"`
|
||||
Active bool `json:"active"`
|
||||
System bool `json:"system"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// ListKnowledgeSources returns knowledge source catalog.
|
||||
func (r *AdminRepo) ListKnowledgeSources(ctx context.Context) ([]KnowledgeSourceRow, error) {
|
||||
rows, err := r.Pool.Query(ctx, `
|
||||
SELECT id, code, title, description, source_kind, version, active, system, updated_at
|
||||
FROM knowledge_sources
|
||||
ORDER BY active DESC, code ASC`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []KnowledgeSourceRow
|
||||
for rows.Next() {
|
||||
var k KnowledgeSourceRow
|
||||
if err := rows.Scan(
|
||||
&k.ID, &k.Code, &k.Title, &k.Description, &k.SourceKind,
|
||||
&k.Version, &k.Active, &k.System, &k.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, k)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// GetKnowledgeSource loads one source by id.
|
||||
func (r *AdminRepo) GetKnowledgeSource(ctx context.Context, id uuid.UUID) (*KnowledgeSourceRow, error) {
|
||||
var k KnowledgeSourceRow
|
||||
err := r.Pool.QueryRow(ctx, `
|
||||
SELECT id, code, title, description, source_kind, version, active, system, updated_at
|
||||
FROM knowledge_sources WHERE id=$1`, id,
|
||||
).Scan(
|
||||
&k.ID, &k.Code, &k.Title, &k.Description, &k.SourceKind,
|
||||
&k.Version, &k.Active, &k.System, &k.UpdatedAt,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, err
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &k, nil
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
)
|
||||
|
||||
var ErrSystemPromptNotFound = errString("system prompt not found")
|
||||
var ErrKnowledgeSourceNotFound = errString("knowledge source not found")
|
||||
|
||||
// ListSystemPrompts returns SystemPrompt catalog.
|
||||
func (s *Service) ListSystemPrompts(ctx context.Context) ([]repository.SystemPromptRow, error) {
|
||||
@@ -32,3 +33,24 @@ func (s *Service) GetSystemPrompt(ctx context.Context, id uuid.UUID) (*repositor
|
||||
}
|
||||
return row, err
|
||||
}
|
||||
|
||||
// ListKnowledgeSources returns KnowledgeSource catalog.
|
||||
func (s *Service) ListKnowledgeSources(ctx context.Context) ([]repository.KnowledgeSourceRow, error) {
|
||||
items, err := s.Repo.ListKnowledgeSources(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if items == nil {
|
||||
items = []repository.KnowledgeSourceRow{}
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
// GetKnowledgeSource loads one source.
|
||||
func (s *Service) GetKnowledgeSource(ctx context.Context, id uuid.UUID) (*repository.KnowledgeSourceRow, error) {
|
||||
row, err := s.Repo.GetKnowledgeSource(ctx, id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrKnowledgeSourceNotFound
|
||||
}
|
||||
return row, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
-- ECR-023 down
|
||||
DROP TABLE IF EXISTS knowledge_sources;
|
||||
@@ -0,0 +1,29 @@
|
||||
-- ECR-023 AICoreConfig KnowledgeSource (read catalog)
|
||||
|
||||
CREATE TABLE IF NOT EXISTS knowledge_sources (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
code varchar(64) NOT NULL UNIQUE,
|
||||
title varchar(128) NOT NULL,
|
||||
description text NULL,
|
||||
source_kind varchar(32) NOT NULL
|
||||
CHECK (source_kind IN ('faq', 'policy', 'guide')),
|
||||
version int NOT NULL DEFAULT 1 CHECK (version > 0),
|
||||
active boolean NOT NULL DEFAULT true,
|
||||
system boolean NOT NULL DEFAULT false,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_knowledge_sources_active ON knowledge_sources(active);
|
||||
|
||||
INSERT INTO knowledge_sources(code, title, description, source_kind, version, active, system)
|
||||
VALUES (
|
||||
'ask_grounding',
|
||||
'问答 grounding 知识源',
|
||||
'运营可观测的 Ask grounding 目录占位;本切片不含 KnowledgeChunk。',
|
||||
'faq',
|
||||
1,
|
||||
true,
|
||||
true
|
||||
)
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
Reference in New Issue
Block a user