diff --git a/go.mod b/go.mod index 4642fec..efa6a64 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module shangshu-ontology -go 1.25 +go 1.25.0 require ( github.com/gin-gonic/gin v1.10.0 @@ -34,11 +34,11 @@ require ( github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.2.12 // indirect golang.org/x/arch v0.8.0 // indirect - golang.org/x/crypto v0.27.0 // indirect - golang.org/x/net v0.25.0 // indirect - golang.org/x/sync v0.8.0 // indirect - golang.org/x/sys v0.26.0 // indirect - golang.org/x/text v0.18.0 // indirect + golang.org/x/crypto v0.55.0 // indirect + golang.org/x/net v0.57.0 // indirect + golang.org/x/sync v0.22.0 // indirect + golang.org/x/sys v0.47.0 // indirect + golang.org/x/text v0.41.0 // indirect google.golang.org/protobuf v1.34.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index b386a46..88e9654 100644 --- a/go.sum +++ b/go.sum @@ -85,16 +85,26 @@ golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc= golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= golang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A= golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70= +golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M= +golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis= golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac= golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= +golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE= +golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU= golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= +golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo= golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224= golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= +golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= +golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg= diff --git a/server/access_control.go b/server/access_control.go index abb949e..fd697dd 100644 --- a/server/access_control.go +++ b/server/access_control.go @@ -14,6 +14,7 @@ package main import ( "context" "errors" + "fmt" "log" "strings" "sync" @@ -71,7 +72,7 @@ func (a *Authz) AllowedMarking(marking string) bool { // ---------- Principal 识别 ---------- // principalFromRequest 从请求头推断主体。 -// 优先级:X-Principal > 查 principals 表的 api_key > MANAGER_API_KEY/CONNECTOR_API_KEY 内置映射 > public +// 优先级:X-Principal > cookie session > 查 principals 表的 api_key > MANAGER_API_KEY/CONNECTOR_API_KEY 内置映射 > public // // dev 模式(MANAGER_API_KEY 与 CONNECTOR_API_KEY 都为空)→ 视为 manager(开放,保留旧的开发体验)。 // 一旦设置了任何一个 API KEY,真实鉴权就生效。 @@ -79,6 +80,12 @@ func (a *app) principalFromRequest(c *gin.Context) string { if p := strings.TrimSpace(c.GetHeader("X-Principal")); p != "" { return p } + // cookie session(账号密码登录后写入) + if tok, err := c.Cookie(SessionCookieName); err == nil && tok != "" { + if p := principalFromSession(tok); p != "" { + return p + } + } if key := c.GetHeader("X-API-Key"); key != "" { // 先查自定义 principal(按 api_key 字段) var name string @@ -341,6 +348,7 @@ CREATE TABLE IF NOT EXISTS principals ( name TEXT UNIQUE NOT NULL, description TEXT DEFAULT '', api_key TEXT DEFAULT '', + password_hash TEXT DEFAULT NULL, is_builtin BOOLEAN DEFAULT FALSE, created_at TIMESTAMPTZ DEFAULT now() ); @@ -373,6 +381,8 @@ CREATE TABLE IF NOT EXISTS grants ( ); CREATE INDEX IF NOT EXISTS idx_grants_principal ON grants(principal); +ALTER TABLE principals ADD COLUMN IF NOT EXISTS password_hash TEXT DEFAULT NULL; + CREATE TABLE IF NOT EXISTS field_policies ( id BIGSERIAL PRIMARY KEY, object_type TEXT NOT NULL, @@ -390,6 +400,7 @@ CREATE TABLE IF NOT EXISTS field_policies ( // seedAccessControlDefaults 幂等灌入内置主体/clearances/grants; // 若已存在则跳过。对象 marking 默认全部 L0(公开),可通过 API 升级。 // ingestKey 非空时写入 ingest 主体的 api_key(供 MCP/agent 知识导入鉴权)。 +// 默认密码 hash(dev)由 DefaultBuiltinPassword 决定;已存在 hash 不覆盖(首次启动后用户改密不会被回滚)。 func seedAccessControlDefaults(ctx context.Context, p *pgxpool.Pool, ingestKey string) error { // 1. 内置主体 builtins := []Principal{ @@ -405,6 +416,15 @@ func seedAccessControlDefaults(ctx context.Context, p *pgxpool.Pool, ingestKey s return err } } + // 内置主体默认密码(仅在 hash 为 NULL 时写入;用户改密后不会被覆盖) + defaultHash, err := bcryptHashPassword(DefaultBuiltinPassword) + if err != nil { + return fmt.Errorf("默认密码 hash 失败: %w", err) + } + if _, err := p.Exec(ctx, + `UPDATE principals SET password_hash=$1 WHERE is_builtin=true AND password_hash IS NULL`, defaultHash); err != nil { + return fmt.Errorf("写入默认密码失败: %w", err) + } // ingest 主体的 api_key(若有):优先用传入值,已设置则保留 if ingestKey != "" { if _, err := p.Exec(ctx, diff --git a/server/handlers_auth.go b/server/handlers_auth.go new file mode 100644 index 0000000..1d64e72 --- /dev/null +++ b/server/handlers_auth.go @@ -0,0 +1,291 @@ +package main + +// 账号密码登录与会话。 +// POST /api/v1/auth/login { name, password } → 200 + Set-Cookie +// POST /api/v1/auth/logout 撤销 session +// GET /api/v1/auth/me 当前已登录主体(含 clearances/grants) +// +// 设计:进程内 session store(map[token]sessionEntry)+ TTL 8h; +// 适合单机部署。重启服务不会丢失密码(存 DB bcrypt),但所有已签发 session 会失效—— +// 多副本 / 持久化场景可后续替换为 Redis。 + +import ( + "context" + "crypto/rand" + "encoding/hex" + "fmt" + "net/http" + "strings" + "sync" + "time" + + "github.com/gin-gonic/gin" + "golang.org/x/crypto/bcrypt" +) + +const ( + // SessionCookieName 浏览器 cookie 名 + SessionCookieName = "ontology_session" + // SessionTTL 会话有效期 + SessionTTL = 8 * time.Hour + // DefaultBuiltinPassword dev 模式三个内置主体的初始密码(首次启动时写入 hash)。 + // ⚠️ 首次登录后请管理员立即在「用户管理 → 编辑 → 重置密码」改密。 + DefaultBuiltinPassword = "changeme" + // MinPasswordLength 用户提交密码的最短长度 + MinPasswordLength = 6 +) + +// ---------- session store ---------- + +type sessionEntry struct { + principal string + expires time.Time +} + +var ( + sessionStore = map[string]sessionEntry{} + sessionStoreMu sync.Mutex +) + +func newSessionToken() string { + b := make([]byte, 32) + if _, err := rand.Read(b); err != nil { + // 极低概率 fallback;crypto/rand 失败时退到时间戳+盐 + return fmt.Sprintf("s-%d", time.Now().UnixNano()) + } + return hex.EncodeToString(b) +} + +// issueSession 注册并返回 token +func issueSession(principal string) string { + tok := newSessionToken() + sessionStoreMu.Lock() + defer sessionStoreMu.Unlock() + sessionStore[tok] = sessionEntry{principal: principal, expires: time.Now().Add(SessionTTL)} + return tok +} + +// revokeSession 撤销单个 token +func revokeSession(tok string) { + sessionStoreMu.Lock() + defer sessionStoreMu.Unlock() + delete(sessionStore, tok) +} + +// principalFromSession 查 cookie token → principal;过期或不存在返回 "" +func principalFromSession(token string) string { + if token == "" { + return "" + } + sessionStoreMu.Lock() + defer sessionStoreMu.Unlock() + e, ok := sessionStore[token] + if !ok { + return "" + } + if time.Now().After(e.expires) { + delete(sessionStore, token) + return "" + } + return e.principal +} + +// gcSessions 定期清理过期(粗粒度:每 30 分钟一次,启动时跑 goroutine) +func gcSessions() { + t := time.NewTicker(30 * time.Minute) + defer t.Stop() + for range t.C { + now := time.Now() + sessionStoreMu.Lock() + for k, e := range sessionStore { + if now.After(e.expires) { + delete(sessionStore, k) + } + } + sessionStoreMu.Unlock() + } +} + +// ---------- bcrypt 帮手 ---------- + +// bcryptHashPassword 对密码做 bcrypt hash(cost=10) +func bcryptHashPassword(pw string) (string, error) { + h, err := bcrypt.GenerateFromPassword([]byte(pw), bcrypt.DefaultCost) + if err != nil { + return "", err + } + return string(h), nil +} + +// bcryptVerifyPassword 校验密码与 hash;err=nil 表示匹配 +func bcryptVerifyPassword(hash, pw string) error { + return bcrypt.CompareHashAndPassword([]byte(hash), []byte(pw)) +} + +// ---------- handlers ---------- + +type loginInput struct { + Name string `json:"name"` + Password string `json:"password"` +} + +func (a *app) authLogin(c *gin.Context) { + var in loginInput + if err := c.ShouldBindJSON(&in); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "请求体无效: " + err.Error()}) + return + } + name := strings.TrimSpace(in.Name) + pw := in.Password + if name == "" || pw == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "用户名 / 密码必填"}) + return + } + + // public 主体不允许密码登录 + if name == "public" { + c.JSON(http.StatusUnauthorized, gin.H{"error": "public 主体不可登录"}) + return + } + + var hash string + err := a.pool.QueryRow(c, `SELECT COALESCE(password_hash,'') FROM principals WHERE name=$1`, name).Scan(&hash) + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "用户名或密码错误"}) + return + } + if hash == "" { + c.JSON(http.StatusUnauthorized, gin.H{"error": "该主体未设置密码,请联系管理员"}) + return + } + if err := bcryptVerifyPassword(hash, pw); err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "用户名或密码错误"}) + return + } + + tok := issueSession(name) + c.SetSameSite(http.SameSiteLaxMode) + c.SetCookie(SessionCookieName, tok, int(SessionTTL.Seconds()), "/", "", false, true) + c.JSON(http.StatusOK, gin.H{ + "ok": true, + "principal": name, + "expires_in_seconds": int(SessionTTL.Seconds()), + }) +} + +func (a *app) authLogout(c *gin.Context) { + if tok, err := c.Cookie(SessionCookieName); err == nil { + revokeSession(tok) + } + c.SetCookie(SessionCookieName, "", -1, "/", "", false, true) + c.JSON(http.StatusOK, gin.H{"ok": true}) +} + +// authMe 返回当前已登录主体的会话/授权上下文。 +// 任意已登录主体可调(不限 manager);未登录返回 401。 +func (a *app) authMe(c *gin.Context) { + p := principalFromSession(c.Request.Header.Get("X-Session-Token")) + if p == "" { + if tok, err := c.Cookie(SessionCookieName); err == nil { + p = principalFromSession(tok) + } + } + if p == "" { + c.JSON(http.StatusUnauthorized, gin.H{"error": "未登录"}) + return + } + authz, _ := a.authzFor(c, p) + cls := make([]string, 0, len(authz.Clearances)) + for m := range authz.Clearances { + cls = append(cls, m) + } + c.JSON(http.StatusOK, gin.H{ + "principal": p, + "is_manager": p == "manager", + "clearances": cls, + "grants": authz.Grants, + }) +} + +// ---------- password change(自助 / 管理员重置) ---------- + +type changePasswordInput struct { + OldPassword string `json:"old_password"` // 自助改密时必填 + NewPassword string `json:"new_password"` // 必填 + TargetPrincipal string `json:"target_principal"` // 管理员重置别人的密码时填;自助改密留空 +} + +func (a *app) changePassword(c *gin.Context) { + var in changePasswordInput + if err := c.ShouldBindJSON(&in); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + if len(in.NewPassword) < MinPasswordLength { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("新密码至少 %d 位", MinPasswordLength)}) + return + } + + actor := principalFromSession(c.Request.Header.Get("X-Session-Token")) + if actor == "" { + if tok, err := c.Cookie(SessionCookieName); err == nil { + actor = principalFromSession(tok) + } + } + if actor == "" { + c.JSON(http.StatusUnauthorized, gin.H{"error": "未登录"}) + return + } + + target := strings.TrimSpace(in.TargetPrincipal) + if target == "" { + target = actor + } + // 非 manager 改别人 → 403;admin 重置他人不需 old_password + if target != actor && actor != "manager" { + c.JSON(http.StatusForbidden, gin.H{"error": "只有管理员可以重置他人密码"}) + return + } + if target == actor && in.OldPassword != "" { + // 自助改密:必须提供旧密码(双因素) + var hash string + if err := a.pool.QueryRow(c, `SELECT COALESCE(password_hash,'') FROM principals WHERE name=$1`, target).Scan(&hash); err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "主体不存在"}) + return + } + if hash == "" || bcryptVerifyPassword(hash, in.OldPassword) != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "旧密码错误"}) + return + } + } else if target == actor && actor != "manager" { + // 自助且不是管理员,必须填旧密码 + c.JSON(http.StatusBadRequest, gin.H{"error": "改自己的密码必须提供旧密码"}) + return + } + + newHash, err := bcryptHashPassword(in.NewPassword) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + tag, err := a.pool.Exec(c, `UPDATE principals SET password_hash=$1 WHERE name=$2`, newHash, target) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + if tag.RowsAffected() == 0 { + c.JSON(http.StatusNotFound, gin.H{"error": "主体不存在"}) + return + } + a.InvalidateAuthzCache(target) + c.JSON(http.StatusOK, gin.H{"ok": true, "principal": target}) +} + +// ---------- 初始化 session 清理 goroutine ---------- + +func init() { + go gcSessions() +} + +// ensureCtxAlive 仅占位,避免 unused import +var _ = context.Background \ No newline at end of file diff --git a/server/handlers_connector.go b/server/handlers_connector.go index 56fce7b..b172abc 100644 --- a/server/handlers_connector.go +++ b/server/handlers_connector.go @@ -359,6 +359,17 @@ func (a *app) mcpManifest(c *gin.Context) { "auth": authHint(a.cfg), "usage": "知识导入约定:本平台 MCP 仅接受 Markdown 文本。调用方(WorkBuddy/Cursor/Claude 等客户端智能体)须先将 docx/pdf/html/xlsx/ppt 等原文档在本地转换为 Markdown,再调用 km_upload_markdown(content 为 Markdown 文本、filename 以 .md 结尾)上传,最后用 km_extract 抽取导入本体。平台不提供任何二进制/原生文档解析能力。", "tools": mcpToolList(), + "ui_template": gin.H{ + "review_workbench": "/", + "review_tab": "导入核对(仅管理员可见)", + "proxy_script": "skill:ssw-ontology-reviewer/references/mcp-review-proxy.js", + "description": "导入核对工作台(SPA 内置):管理员登录主站后切到「导入核对」tab;首次进入自动加载内置清单(/builtin-review-manifest.json);可导入 scan.py 产出的 review-manifest.json 逐项核对;具备写权限时可直接 Apply(create_object_type / update_enum / km_upload_markdown + km_extract),否则导出 JSON/MD 执行清单交管理员。", + "proxy": gin.H{ + "purpose": "浏览器直连远程本体 MCP 被系统/企业代理拦截(502) 或 CORS / SSE 解析失败时,用本地反向代理绕过。", + "source": "skill:ssw-ontology-reviewer/references/mcp-review-proxy.js(与本平台解耦,可任意宿主使用)", + "run": "PROXY_TARGET=http://<本体host>:8081 node mcp-review-proxy.js 然后浏览器打开 http://127.0.0.1:9333/(代理会反向代理整站 SPA)", + }, + }, }) } diff --git a/server/handlers_mcp.go b/server/handlers_mcp.go index 471cdff..536ec4a 100644 --- a/server/handlers_mcp.go +++ b/server/handlers_mcp.go @@ -107,6 +107,11 @@ func mcpToolList() []MCPTool { "required": []string{"type"}, }, }, + { + Name: "whoami", + Description: "返回当前 MCP 调用主体的身份(principal)与是否具备写权限(can_write),供核对工作台判断「可执行 / 只读导出」模式。", + InputSchema: map[string]interface{}{"type": "object", "properties": map[string]interface{}{}}, + }, // ---------- 知识导入(写入,需 manager/ingest 主体) ---------- { Name: "km_list_tree", @@ -172,6 +177,80 @@ func mcpToolList() []MCPTool { "required": []string{"rel_paths"}, }, }, + // ---------- 本体管理写入(manager/ingest 可写,直接 apply,无需 SQL / schema 迁移) ---------- + { + Name: "create_object_type", + Description: "【写入】新建对象类型(元原语)。可内联 properties 数组一次性建好关键属性。用于「缺失元原语 / 新建类型」。", + InputSchema: map[string]interface{}{ + "type": "object", + "properties": map[string]interface{}{ + "api_name": map[string]interface{}{"type": "string", "description": "类型稳定标识,如 Product"}, + "display_name": map[string]interface{}{"type": "string", "description": "中文显示名"}, + "description": map[string]interface{}{"type": "string"}, + "icon": map[string]interface{}{"type": "string", "description": "emoji 图标"}, + "group": map[string]interface{}{"type": "string", "description": "分类分组"}, + "properties": map[string]interface{}{"type": "array", "description": "可选内联属性:[{api_name,display_name,data_type,required,enum_values,description}]"}, + }, + "required": []string{"api_name", "display_name"}, + }, + }, + { + Name: "create_link_type", + Description: "【写入】新建链接类型(关系边),表达两个对象类型之间的关系,如 tds_uses_tee / consumes_ontology。", + InputSchema: map[string]interface{}{ + "type": "object", + "properties": map[string]interface{}{ + "api_name": map[string]interface{}{"type": "string"}, + "display_name": map[string]interface{}{"type": "string"}, + "source_type": map[string]interface{}{"type": "string"}, + "target_type": map[string]interface{}{"type": "string"}, + "cardinality": map[string]interface{}{"type": "string", "description": "one_to_many/many_to_many/one_to_one,默认 many_to_many"}, + "description": map[string]interface{}{"type": "string"}, + }, + "required": []string{"api_name", "source_type", "target_type"}, + }, + }, + { + Name: "create_object", + Description: "【写入】在指定对象类型下新建实例(数字孪生节点),properties 为属性键值对。用于「补充实例」。", + InputSchema: map[string]interface{}{ + "type": "object", + "properties": map[string]interface{}{ + "type": map[string]interface{}{"type": "string", "description": "对象类型 api_name"}, + "pk": map[string]interface{}{"type": "string", "description": "实例主键"}, + "properties": map[string]interface{}{"type": "object", "description": "属性键值对,如 {\"name\":\"...\",\"industry\":\"...\"}"}, + }, + "required": []string{"type", "pk"}, + }, + }, + { + Name: "create_link", + Description: "【写入】在指定链接类型下新建关系实例(边),连接两个对象实例。", + InputSchema: map[string]interface{}{ + "type": "object", + "properties": map[string]interface{}{ + "type": map[string]interface{}{"type": "string", "description": "链接类型 api_name"}, + "source_type": map[string]interface{}{"type": "string"}, + "source_pk": map[string]interface{}{"type": "string"}, + "target_type": map[string]interface{}{"type": "string"}, + "target_pk": map[string]interface{}{"type": "string"}, + }, + "required": []string{"type", "source_type", "source_pk", "target_type", "target_pk"}, + }, + }, + { + Name: "update_enum", + Description: "【写入】向某对象类型的某个枚举属性追加取值(自动去重)。用于「修订枚举」——无需 schema 迁移或管理员 SQL。", + InputSchema: map[string]interface{}{ + "type": "object", + "properties": map[string]interface{}{ + "type": map[string]interface{}{"type": "string", "description": "对象类型 api_name"}, + "property": map[string]interface{}{"type": "string", "description": "属性 api_name"}, + "add_values": map[string]interface{}{"type": "array", "items": map[string]interface{}{"type": "string"}, "description": "要追加的枚举值"}, + }, + "required": []string{"type", "property", "add_values"}, + }, + }, } } @@ -379,11 +458,128 @@ func (a *app) mcpDispatchTool(c *gin.Context, name string, args map[string]inter body, _ := json.Marshal(queryInput{Type: typ, Filters: filters, Expand: expand, Limit: limit}) return a.callConn("POST", "/api/v1/connector/query", body), false, false + case "whoami": + // principal / canWrite 已在函数顶部解析 + return fmt.Sprintf(`{"principal":%q,"can_write":%v}`, principal, canWrite), false, false + + // ---------- 本体管理写入:直接进程内调用 handler(绕过HTTP中间件,按 canWrite 放行,兼容 manager/ingest) ---------- + case "create_object_type": + if !canWrite { + return denyWrite() + } + name, _ := args["api_name"].(string) + disp, _ := args["display_name"].(string) + if name == "" || disp == "" { + return "参数错误:api_name 与 display_name 必填", false, true + } + body, _ := json.Marshal(map[string]interface{}{ + "api_name": name, "display_name": disp, + "description": optStr(args, "description"), "icon": optStr(args, "icon"), "group": optStr(args, "group"), + }) + t, st := a.callHandler(a.createObjectType, nil, body, principal) + if st >= 400 { + return t, false, true + } + // 内联属性(幂等:已存在则 ON CONFLICT DO NOTHING) + if props, ok := args["properties"].([]interface{}); ok { + for _, p := range props { + pm, ok := p.(map[string]interface{}) + if !ok { + continue + } + pb, _ := json.Marshal(map[string]interface{}{ + "api_name": pm["api_name"], "display_name": pm["display_name"], + "data_type": pm["data_type"], "required": pm["required"], + "enum_values": pm["enum_values"], "description": pm["description"], + }) + a.callHandler(a.addProperty, gin.Params{gin.Param{Key: "name", Value: name}}, pb, principal) + } + } + return t, false, false + + case "create_link_type": + if !canWrite { + return denyWrite() + } + body, _ := json.Marshal(args) + t, st := a.callHandler(a.createLinkType, nil, body, principal) + return t, false, st >= 400 + + case "create_object": + if !canWrite { + return denyWrite() + } + body, _ := json.Marshal(args) + t, st := a.callHandler(a.createObject, nil, body, principal) + return t, false, st >= 400 + + case "create_link": + if !canWrite { + return denyWrite() + } + body, _ := json.Marshal(args) + t, st := a.callHandler(a.createLink, nil, body, principal) + return t, false, st >= 400 + + case "update_enum": + if !canWrite { + return denyWrite() + } + typ, _ := args["type"].(string) + prop, _ := args["property"].(string) + vals, _ := args["add_values"].([]interface{}) + if typ == "" || prop == "" || len(vals) == 0 { + return "参数错误:type / property / add_values 必填", false, true + } + add := make([]string, 0, len(vals)) + for _, v := range vals { + if s, ok := v.(string); ok { + add = append(add, s) + } + } + if len(add) == 0 { + return "add_values 为空或非字符串", false, true + } + tag, err := a.pool.Exec(c, ` + UPDATE properties SET enum_values = ( + SELECT jsonb_agg(DISTINCT elem) FROM jsonb_array_elements_text( + COALESCE(enum_values, '[]'::jsonb) || $3::jsonb + ) AS t(elem) + ) WHERE object_type_id = (SELECT id FROM object_types WHERE api_name=$1) AND api_name=$2`, + typ, prop, mustJSON(add)) + if err != nil { + return "枚举追加失败:" + err.Error(), false, true + } + return fmt.Sprintf(`{"ok":true,"rows_affected":%d,"type":%q,"property":%q,"added":%s}`, tag.RowsAffected(), typ, prop, mustJSON(add)), false, false + default: return "", true, false } } +// callHandler 进程内直接调用本体管理 handler,绕过 HTTP 中间件(managerAuth 仅放行 manager), +// 由调用方 mcpDispatchTool 的 canWrite 统一放行 manager/ingest。X-Principal 透传以走正常鉴权链路。 +func (a *app) callHandler(h gin.HandlerFunc, params gin.Params, body []byte, principal string) (string, int) { + req := httptest.NewRequest(http.MethodPost, "/x", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Principal", principal) + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = req + if params != nil { + c.Params = params + } + h(c) + return w.Body.String(), w.Code +} + +func optStr(m map[string]interface{}, k string) string { + if v, ok := m[k].(string); ok { + return v + } + return "" +} + // mcpCall 进程内把请求路由到 KM/管理 handler,并携带当前 MCP 主体身份(X-Principal), // 使 ingestOrManagerAuth 中间件能正确放行(manager/ingest),复用现有逻辑、零漂移。 func (a *app) mcpCall(method, path string, body []byte, principal string) (string, int) { diff --git a/server/main.go b/server/main.go index 658370d..b41cece 100644 --- a/server/main.go +++ b/server/main.go @@ -154,9 +154,15 @@ func registerRoutes(r *gin.Engine, a *app) { api := r.Group("/api/v1") + // 账号密码登录(公开端点,登录前访问) + api.POST("/auth/login", a.authLogin) + api.POST("/auth/logout", a.authLogout) + api.GET("/auth/me", a.authMe) + api.POST("/auth/change-password", a.changePassword) + // 管理类接口(本体/实例/AI摄取),可配置 MANAGER_API_KEY mgmt := api.Group("") - mgmt.Use(a.managerAuth()) + mgmt.Use(a.loginRequired(), a.managerAuth()) { ot := mgmt.Group("/ontology") ot.GET("/object-types", a.listObjectTypes) @@ -246,7 +252,7 @@ func registerRoutes(r *gin.Engine, a *app) { } // 访问控制元原语管理接口(manager 主体可见) - // whoami 任何 principal 都可调(诊断当前身份) + // whoami 任何 principal 都可调(诊断当前身份)——挂在 mgmt 外,登录即可查 api.GET("/access/whoami", a.whoami) acc := mgmt.Group("/access") { @@ -294,6 +300,27 @@ func (a *app) managerAuth() gin.HandlerFunc { } } +// loginRequired 强制要求已登录(cookie session 或 X-API-Key)。 +// dev 模式(两个 API KEY env 都为空)→ 跳过,保持旧开发体验。 +// 真实鉴权模式开启时,凡到达此中间件的请求必须带 session 或 API Key,否则 401。 +// 注意:本中间件不区分角色(manager/ingest/connector 都可过); +// 角色门由 managerAuth / ingestOrManagerAuth 等下游中间件把控。 +func (a *app) loginRequired() gin.HandlerFunc { + return func(c *gin.Context) { + // dev 模式保留旧体验:无人也能进(默认 manager) + if a.cfg.ManagerAPIKey == "" && a.cfg.ConnectorAPIKey == "" { + c.Next() + return + } + p := a.principalFromRequest(c) + if p == "" || p == "public" { + c.AbortWithStatusJSON(401, gin.H{"error": "需要登录或有效 API Key", "principal": p}) + return + } + c.Next() + } +} + func (a *app) connectorAuth() gin.HandlerFunc { return func(c *gin.Context) { if a.cfg.ConnectorAPIKey == "" { diff --git a/web/import-review.html b/web/import-review.html new file mode 100644 index 0000000..6945a68 --- /dev/null +++ b/web/import-review.html @@ -0,0 +1,17 @@ + + + + + +导入核对 · 非管理员入口 + + + +
载入中…
+ + + \ No newline at end of file diff --git a/web/public/builtin-review-manifest.json b/web/public/builtin-review-manifest.json new file mode 100644 index 0000000..7f59143 --- /dev/null +++ b/web/public/builtin-review-manifest.json @@ -0,0 +1,952 @@ +{ + "meta": { + "title": "尚数网本体核对执行清单(内置 / 两类型)", + "generatedAt": "2026-08-21T05:59:04.447Z", + "sourceDoc": "尚数网完整技术架构 v1.1.2 (2026-08-21)", + "totalItems": 29, + "defaultMode": "管理员可直接执行(操作项调 MCP 直连应用;文档项 km 导入)。无需任何 SQL 或人工 schema 迁移。", + "schema": "每条 items[].kind ∈ {operation, document}。operation={method,params} 直接调 MCP 工具;document={filename,markdown} 调 km_upload_markdown+km_extract。", + "note": "本清单为内置示例(与远端导出的 ontology-execution-list.json 同源,已重排为两类型)。管理员可直接执行,或同事用 scan.py 生成后导出供管理员导入。" + }, + "items": [ + { + "id": 1, + "category": "missing-type", + "severity": "red", + "name": "Product(产品)", + "ref": "§1.1 产品矩阵", + "description": "新建对象类型「Product」,从 §1.1 产品矩阵抽取「数小估/数小规/数牙子/交易助手」等 C 端数据应用超市产品的属性定义(名称、行业、形态、运营方、上架状态),并创建这 4 个产品的实例,关联到 DataAppMarket。", + "status": "applied", + "appliedAt": "2026-08-21T05:53:58.858Z", + "kind": "operation", + "title": "新建对象类型 Product", + "rationale": "C 端超市产品只能用 AppScenario 或自由文本描述,无法做产品图谱与关系分析", + "method": "create_object_type", + "params": { + "api_name": "Product", + "display_name": "Product", + "group": "缺失元原语", + "description": "新建对象类型「Product」,从 §1.1 产品矩阵抽取「数小估/数小规/数牙子/交易助手」等 C 端数据应用超市产品的属性定义(名称、行业、形态、运营方、上架状态),并创建这 4 个产品的实例,关联到 DataAppMarket。", + "properties": [ + { + "api_name": "name", + "display_name": "名称", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "industry", + "display_name": "行业", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "form", + "display_name": "形态", + "data_type": "enum", + "required": false, + "enum_values": [ + "C端应用", + "平台", + "组件" + ], + "description": "" + }, + { + "api_name": "operator", + "display_name": "运营方", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "listing_status", + "display_name": "上架状态", + "data_type": "enum", + "required": false, + "enum_values": [ + "上架", + "下架", + "内测" + ], + "description": "" + } + ] + } + }, + { + "id": 2, + "category": "missing-type", + "severity": "red", + "name": "OrchestrationPlatform(SAOP)", + "ref": "§6.1 智能编排引擎", + "description": "新建对象类型「OrchestrationPlatform」,从 §6.1 抽取 SAOP 智能编排引擎的属性(Flow/Agent/规则引擎混合执行、节点类型、执行实例、调度策略),并创建 1 个 SAOP 平台实例及典型节点类型实例。", + "status": "pending", + "kind": "operation", + "title": "新建对象类型 OrchestrationPlatform", + "rationale": "本体完全没体现\"编排引擎\"这一核心产品", + "method": "create_object_type", + "params": { + "api_name": "OrchestrationPlatform", + "display_name": "OrchestrationPlatform", + "group": "缺失元原语", + "description": "新建对象类型「OrchestrationPlatform」,从 §6.1 抽取 SAOP 智能编排引擎的属性(Flow/Agent/规则引擎混合执行、节点类型、执行实例、调度策略),并创建 1 个 SAOP 平台实例及典型节点类型实例。", + "properties": [ + { + "api_name": "name", + "display_name": "名称", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "engine_type", + "display_name": "引擎类型", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "node_types", + "display_name": "节点类型", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "scheduling", + "display_name": "调度策略", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + } + ] + } + }, + { + "id": 3, + "category": "missing-type", + "severity": "red", + "name": "DataAsset(数据资产)", + "ref": "§1.1 + §7.2 dat_asset 表", + "description": "新建对象类型「DataAsset」,区分 raw/curated/published 状态,从 §1.1 + dat_asset 表抽取数据资产管理平台的资产实例(资产名、来源、格式、责任人、密级)。", + "status": "applied", + "appliedAt": "2026-08-21T05:54:58.064Z", + "kind": "operation", + "title": "新建对象类型 DataAsset", + "rationale": "无法对数据资产管理平台的\"资产\"做建模与溯源", + "method": "create_object_type", + "params": { + "api_name": "DataAsset", + "display_name": "DataAsset", + "group": "缺失元原语", + "description": "新建对象类型「DataAsset」,区分 raw/curated/published 状态,从 §1.1 + dat_asset 表抽取数据资产管理平台的资产实例(资产名、来源、格式、责任人、密级)。", + "properties": [ + { + "api_name": "name", + "display_name": "名称", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "asset_state", + "display_name": "资产状态", + "data_type": "enum", + "required": false, + "enum_values": [ + "raw", + "curated", + "published" + ], + "description": "" + }, + { + "api_name": "owner", + "display_name": "归属", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + } + ] + } + }, + { + "id": 4, + "category": "missing-type", + "severity": "red", + "name": "TradingPlatform(数据交易平台)", + "ref": "§1.1 + §7.2 trd_* 表", + "description": "新建对象类型「TradingPlatform」,从 §1.1 + trd_* 表抽取数据交易平台的属性与实例(定价模式、结算方式、订单流程、合规要求)。", + "status": "applied", + "appliedAt": "2026-08-21T05:55:21.263Z", + "kind": "operation", + "title": "新建对象类型 TradingPlatform", + "rationale": "交易/定价/订单等核心能力无法挂到平台实体上", + "method": "create_object_type", + "params": { + "api_name": "TradingPlatform", + "display_name": "TradingPlatform", + "group": "缺失元原语", + "description": "新建对象类型「TradingPlatform」,从 §1.1 + trd_* 表抽取数据交易平台的属性与实例(定价模式、结算方式、订单流程、合规要求)。", + "properties": [ + { + "api_name": "name", + "display_name": "名称", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "pricing_model", + "display_name": "定价模式", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "settlement", + "display_name": "结算方式", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "compliance", + "display_name": "合规要求", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + } + ] + } + }, + { + "id": 5, + "category": "missing-type", + "severity": "red", + "name": "DataAppMarket(数据应用超市)", + "ref": "§1.1 + §1.6 生态应用层", + "description": "新建对象类型「DataAppMarket」,从 §1.1 + §1.6 生态应用层抽取 C 端应用超市的属性与实例(超市名称、所属平台、上架产品列表、运营方)。", + "status": "applied", + "appliedAt": "2026-08-21T05:55:41.227Z", + "kind": "operation", + "title": "新建对象类型 DataAppMarket", + "rationale": "C 端运营入口缺失,产品矩阵不完整", + "method": "create_object_type", + "params": { + "api_name": "DataAppMarket", + "display_name": "DataAppMarket", + "group": "缺失元原语", + "description": "新建对象类型「DataAppMarket」,从 §1.1 + §1.6 生态应用层抽取 C 端应用超市的属性与实例(超市名称、所属平台、上架产品列表、运营方)。", + "properties": [ + { + "api_name": "name", + "display_name": "名称", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "platform", + "display_name": "所属平台", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "operator", + "display_name": "运营方", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "product_count", + "display_name": "上架产品数", + "data_type": "integer", + "required": false, + "enum_values": [], + "description": "" + } + ] + } + }, + { + "id": 6, + "category": "missing-type", + "severity": "red", + "name": "DataAccessConnector(数据接入连接器)", + "ref": "§7.2 tdc_connector 表 + §4.2", + "description": "新建对象类型「DataAccessConnector」,从 §7.2 tdc_connector + §4.2 抽取数据接入连接器的属性与实例(连接器类型、支持协议、接入资源、状态),区别于 TDS 侧 Connector。", + "status": "pending", + "kind": "operation", + "title": "新建对象类型 DataAccessConnector", + "rationale": "数据接入连接器无法作为独立资产被检索、授权和审计", + "method": "create_object_type", + "params": { + "api_name": "DataAccessConnector", + "display_name": "DataAccessConnector", + "group": "缺失元原语", + "description": "新建对象类型「DataAccessConnector」,从 §7.2 tdc_connector + §4.2 抽取数据接入连接器的属性与实例(连接器类型、支持协议、接入资源、状态),区别于 TDS 侧 Connector。", + "properties": [ + { + "api_name": "name", + "display_name": "名称", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "connector_type", + "display_name": "连接器类型", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "protocols", + "display_name": "支持协议", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "resource", + "display_name": "接入资源", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "status", + "display_name": "状态", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + } + ] + } + }, + { + "id": 7, + "category": "missing-type", + "severity": "red", + "name": "FlowExecution(流程执行实例)", + "ref": "§7.2 saop_execution / flow_node / audit_log", + "description": "新建对象类型「FlowExecution」,从 §7.2 saop_execution/flow_node/audit_log 抽取 SAOP 运行时的执行实例、节点实例与审计日志实例。", + "status": "pending", + "kind": "operation", + "title": "新建对象类型 FlowExecution", + "rationale": "无法对 SAOP 运行时做本体化追踪", + "method": "create_object_type", + "params": { + "api_name": "FlowExecution", + "display_name": "FlowExecution", + "group": "缺失元原语", + "description": "新建对象类型「FlowExecution」,从 §7.2 saop_execution/flow_node/audit_log 抽取 SAOP 运行时的执行实例、节点实例与审计日志实例。", + "properties": [ + { + "api_name": "exec_id", + "display_name": "执行实例ID", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "flow", + "display_name": "所属流程", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "status", + "display_name": "状态", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "started_at", + "display_name": "开始时间", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + } + ] + } + }, + { + "id": 8, + "category": "missing-type", + "severity": "red", + "name": "AIAgent(智能体)", + "ref": "§5.2 工具协议扩展 + §6.1.5", + "description": "新建对象类型「AIAgent」,从 §5.2 + §6.1.5 抽取 SAOP Multi-Agent 体系的内置/第三方/自定义 Agent 实例(Agent 名称、能力、工具协议、所属编排流),并标注其暴露的 MCP tool。", + "status": "pending", + "kind": "operation", + "title": "新建对象类型 AIAgent", + "rationale": "AI 能力层核心对象缺失,MCP tool 也无法自描述", + "method": "create_object_type", + "params": { + "api_name": "AIAgent", + "display_name": "AIAgent", + "group": "缺失元原语", + "description": "新建对象类型「AIAgent」,从 §5.2 + §6.1.5 抽取 SAOP Multi-Agent 体系的内置/第三方/自定义 Agent 实例(Agent 名称、能力、工具协议、所属编排流),并标注其暴露的 MCP tool。", + "properties": [ + { + "api_name": "agent_name", + "display_name": "Agent名称", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "category", + "display_name": "分类", + "data_type": "enum", + "required": false, + "enum_values": [ + "内置", + "第三方", + "自定义" + ], + "description": "" + }, + { + "api_name": "tools", + "display_name": "工具协议", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "orchestration", + "display_name": "所属编排流", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + } + ] + } + }, + { + "id": 9, + "category": "missing-type", + "severity": "red", + "name": "KnowledgeBase(知识库)", + "ref": "§5.3 知识库体系", + "description": "新建对象类型「KnowledgeBase」,从 §5.3 抽取通用/行业/业务/法规/字典 5 类知识库实例(库名、类型、来源、更新频率、关联产品)。", + "status": "pending", + "kind": "operation", + "title": "新建对象类型 KnowledgeBase", + "rationale": "RAG 与知识管理无法在本体中显式建模", + "method": "create_object_type", + "params": { + "api_name": "KnowledgeBase", + "display_name": "KnowledgeBase", + "group": "缺失元原语", + "description": "新建对象类型「KnowledgeBase」,从 §5.3 抽取通用/行业/业务/法规/字典 5 类知识库实例(库名、类型、来源、更新频率、关联产品)。", + "properties": [ + { + "api_name": "kb_name", + "display_name": "库名", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "category", + "display_name": "类别", + "data_type": "enum", + "required": false, + "enum_values": [ + "通用", + "行业", + "业务", + "法规", + "字典" + ], + "description": "" + }, + { + "api_name": "source", + "display_name": "来源", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "update_freq", + "display_name": "更新频率", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + } + ] + } + }, + { + "id": 10, + "category": "missing-type", + "severity": "red", + "name": "LLMProvider(大模型供应商)", + "ref": "§5.1 LLM 集成", + "description": "新建对象类型「LLMProvider」,从 §5.1 抽取已接入的大模型供应商(MiniMax-M3 等)及路由配置实例(供应商名、模型、endpoint、用途、合规约束)。", + "status": "pending", + "kind": "operation", + "title": "新建对象类型 LLMProvider", + "rationale": "模型路由、成本、合规无法统一管理", + "method": "create_object_type", + "params": { + "api_name": "LLMProvider", + "display_name": "LLMProvider", + "group": "缺失元原语", + "description": "新建对象类型「LLMProvider」,从 §5.1 抽取已接入的大模型供应商(MiniMax-M3 等)及路由配置实例(供应商名、模型、endpoint、用途、合规约束)。", + "properties": [ + { + "api_name": "provider_name", + "display_name": "供应商", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "model", + "display_name": "模型", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "endpoint", + "display_name": "endpoint", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "purpose", + "display_name": "用途", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + } + ] + } + }, + { + "id": 11, + "category": "missing-type", + "severity": "red", + "name": "TechFramework(技术栈组件)", + "ref": "§2.1 核心技术栈", + "description": "新建对象类型「TechFramework」,从 §2.1 抽取 Spring Boot/Vue3/Flowable/Vue Flow/Activity/OPA 等 30+ 技术栈组件实例,按架构五层(基础设施/安全执行/AI 能力/应用开发/业务/门户)归类,标注层级与用途。", + "status": "pending", + "kind": "operation", + "title": "新建对象类型 TechFramework", + "rationale": "\"公司大脑\"未记录自己的技术栈", + "method": "create_object_type", + "params": { + "api_name": "TechFramework", + "display_name": "TechFramework", + "group": "缺失元原语", + "description": "新建对象类型「TechFramework」,从 §2.1 抽取 Spring Boot/Vue3/Flowable/Vue Flow/Activity/OPA 等 30+ 技术栈组件实例,按架构五层(基础设施/安全执行/AI 能力/应用开发/业务/门户)归类,标注层级与用途。", + "properties": [ + { + "api_name": "component", + "display_name": "组件名", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "layer", + "display_name": "架构层级", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "purpose", + "display_name": "用途", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + } + ] + } + }, + { + "id": 12, + "category": "missing-type", + "severity": "red", + "name": "BusinessTable(业务数据库表)", + "ref": "§7.2 16 张业务表", + "description": "新建对象类型「BusinessTable」,从 §7.2 抽取 16 张业务数据库表的实例(表名、所属产品模块、关键字段、关联关系)。", + "status": "pending", + "kind": "operation", + "title": "新建对象类型 BusinessTable", + "rationale": "无法做\"产品—表—字段\"血缘与影响分析", + "method": "create_object_type", + "params": { + "api_name": "BusinessTable", + "display_name": "BusinessTable", + "group": "缺失元原语", + "description": "新建对象类型「BusinessTable」,从 §7.2 抽取 16 张业务数据库表的实例(表名、所属产品模块、关键字段、关联关系)。", + "properties": [ + { + "api_name": "table_name", + "display_name": "表名", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "module", + "display_name": "所属模块", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + }, + { + "api_name": "key_fields", + "display_name": "关键字段", + "data_type": "string", + "required": false, + "enum_values": [], + "description": "" + } + ] + } + }, + { + "id": 13, + "category": "missing-instance", + "severity": "amber", + "name": "ArchitectureComponent 实例", + "ref": "§1.2 五层架构 + §2.1", + "description": "在「ArchitectureComponent」类型下补充 §1.2 五层架构 + §2.1 的 30+ 组件实例(如低代码引擎、工作流引擎、隐私计算框架、TEE、MCP Router、统一认证网关等),标注所属层级。", + "status": "pending", + "kind": "document", + "title": "导入文档 ArchitectureComponent 实例", + "rationale": "架构组件图谱空白", + "filename": "架构/v1.1.2/B-13-ArchitectureComponent.md", + "markdown": "# ArchitectureComponent 实例\n\n**分类**:缺实例\n**引用**:§1.2 五层架构 + §2.1\n\n## 现状\n\n0 实例\n\n## 应有\n\n5 层 × 30+ 组件 ≈ 60+ 组件实例\n\n## 影响\n\n架构组件图谱空白\n\n## 抽取说明\n\n在「ArchitectureComponent」类型下补充 §1.2 五层架构 + §2.1 的 30+ 组件实例(如低代码引擎、工作流引擎、隐私计算框架、TEE、MCP Router、统一认证网关等),标注所属层级。\n" + }, + { + "id": 14, + "category": "missing-instance", + "severity": "amber", + "name": "Service 核心服务实例", + "ref": "§2.1 8 大服务类别", + "description": "在「Service」类型下补充 §2.1 八大服务类别的实例:低代码服务、工作流服务、隐私计算服务、TEE 服务、MCP 服务、LLM 服务、SSWFlow、dacli,标注服务职责与依赖。", + "status": "pending", + "kind": "document", + "title": "导入文档 Service 核心服务实例", + "rationale": "服务能力目录空白", + "filename": "架构/v1.1.2/B-14-Service.md", + "markdown": "# Service 核心服务实例\n\n**分类**:缺实例\n**引用**:§2.1 8 大服务类别\n\n## 现状\n\n0 实例\n\n## 应有\n\n低代码/工作流/隐私计算/TEE/MCP/LLM/SSWFlow/dacli 等\n\n## 影响\n\n服务能力目录空白\n\n## 抽取说明\n\n在「Service」类型下补充 §2.1 八大服务类别的实例:低代码服务、工作流服务、隐私计算服务、TEE 服务、MCP 服务、LLM 服务、SSWFlow、dacli,标注服务职责与依赖。\n" + }, + { + "id": 15, + "category": "missing-instance", + "severity": "amber", + "name": "InterfaceSpec 接口规范实例", + "ref": "§8.2 14 个核心接口", + "description": "在「InterfaceSpec」类型下补充 §8.2 的 14 个核心接口实例(/saop/flow/create、/tdc/connector/register、/trd/product/publish 等),含请求方法、路径、请求/响应契约、所属系统。", + "status": "pending", + "kind": "document", + "title": "导入文档 InterfaceSpec 接口规范实例", + "rationale": "接口契约无法被查询与治理", + "filename": "架构/v1.1.2/B-15-InterfaceSpec.md", + "markdown": "# InterfaceSpec 接口规范实例\n\n**分类**:缺实例\n**引用**:§8.2 14 个核心接口\n\n## 现状\n\n0 实例\n\n## 应有\n\n/saop/flow/create、/tdc/connector/register、/trd/product/publish 等\n\n## 影响\n\n接口契约无法被查询与治理\n\n## 抽取说明\n\n在「InterfaceSpec」类型下补充 §8.2 的 14 个核心接口实例(/saop/flow/create、/tdc/connector/register、/trd/product/publish 等),含请求方法、路径、请求/响应契约、所属系统。\n" + }, + { + "id": 16, + "category": "missing-instance", + "severity": "amber", + "name": "UsageControlInterface 实例", + "ref": "§8.2 接口列表", + "description": "在「UsageControlInterface」类型下补充 TDS/SAOP/Trading 三大系统的使用控制接口实例,标注接口能力、调用方、策略约束。", + "status": "pending", + "kind": "document", + "title": "导入文档 UsageControlInterface 实例", + "rationale": "接入面语义缺失", + "filename": "架构/v1.1.2/B-16-UsageControlInterface.md", + "markdown": "# UsageControlInterface 实例\n\n**分类**:缺实例\n**引用**:§8.2 接口列表\n\n## 现状\n\n0 实例\n\n## 应有\n\n使用控制接口实例\n\n## 影响\n\n接入面语义缺失\n\n## 抽取说明\n\n在「UsageControlInterface」类型下补充 TDS/SAOP/Trading 三大系统的使用控制接口实例,标注接口能力、调用方、策略约束。\n" + }, + { + "id": 17, + "category": "missing-instance", + "severity": "amber", + "name": "ComplianceStandard 合规标准", + "ref": "战略 10 + §1.4", + "description": "在「ComplianceStandard」类型下补充公司直接相关的合规标准实例:GB/T 35273 个人信息安全规范、TC260 数据安全能力成熟度、TC601 数据要素流通等,标注适用范围与强制级别。", + "status": "pending", + "kind": "document", + "title": "导入文档 ComplianceStandard 合规标准", + "rationale": "合规能力无法被检索与审计", + "filename": "架构/v1.1.2/B-17-ComplianceStandard.md", + "markdown": "# ComplianceStandard 合规标准\n\n**分类**:缺实例\n**引用**:战略 10 + §1.4\n\n## 现状\n\n少量通用标准\n\n## 应有\n\nGB/T 35273、TC260 数据安全能力成熟度、TC601 数据要素流通等\n\n## 影响\n\n合规能力无法被检索与审计\n\n## 抽取说明\n\n在「ComplianceStandard」类型下补充公司直接相关的合规标准实例:GB/T 35273 个人信息安全规范、TC260 数据安全能力成熟度、TC601 数据要素流通等,标注适用范围与强制级别。\n" + }, + { + "id": 18, + "category": "missing-instance", + "severity": "amber", + "name": "IPAsset 知识产权", + "ref": "§1.4 专利/技术方案", + "description": "在「IPAsset」类型下补充 §1.4 提及的知识产权实例:FPGA TPM 软核、Nax 框架、SAOP 编排引擎等专利/软著,标注类型、归属、状态。", + "status": "applied", + "appliedAt": "2026-08-21T05:56:35.817Z", + "kind": "document", + "title": "导入文档 IPAsset 知识产权", + "rationale": "知识产权资产不可见", + "filename": "架构/v1.1.2/B-18-IPAsset.md", + "markdown": "# IPAsset 知识产权\n\n**分类**:缺实例\n**引用**:§1.4 专利/技术方案\n\n## 现状\n\n0 实例\n\n## 应有\n\nFPGA TPM 软核、Nax 框架、SAOP 等专利/软著\n\n## 影响\n\n知识产权资产不可见\n\n## 抽取说明\n\n在「IPAsset」类型下补充 §1.4 提及的知识产权实例:FPGA TPM 软核、Nax 框架、SAOP 编排引擎等专利/软著,标注类型、归属、状态。\n" + }, + { + "id": 19, + "category": "missing-instance", + "severity": "amber", + "name": "NewsArticle 新闻动态", + "ref": "§1.4 11 项能力更新", + "description": "在「NewsArticle」类型下补充 §1.4 的 11 项能力更新对应的新闻动态实例,标注标题、日期、关联产品/能力。", + "status": "applied", + "appliedAt": "2026-08-21T05:57:03.580Z", + "kind": "document", + "title": "导入文档 NewsArticle 新闻动态", + "rationale": "公司动态无法被本体记录", + "filename": "架构/v1.1.2/B-19-NewsArticle.md", + "markdown": "# NewsArticle 新闻动态\n\n**分类**:缺实例\n**引用**:§1.4 11 项能力更新\n\n## 现状\n\n0 实例\n\n## 应有\n\n每项能力更新对应一条新闻\n\n## 影响\n\n公司动态无法被本体记录\n\n## 抽取说明\n\n在「NewsArticle」类型下补充 §1.4 的 11 项能力更新对应的新闻动态实例,标注标题、日期、关联产品/能力。\n" + }, + { + "id": 20, + "category": "missing-instance", + "severity": "amber", + "name": "MemberOrg 会员单位", + "ref": "§1.3 战略 14", + "description": "在「MemberOrg」类型下补充战略 14 招募的区域行业代理商、行业合作伙伴实例,标注区域、行业、合作模式。", + "status": "applied", + "appliedAt": "2026-08-21T05:57:13.133Z", + "kind": "document", + "title": "导入文档 MemberOrg 会员单位", + "rationale": "生态合作网络空白", + "filename": "架构/v1.1.2/B-20-MemberOrg.md", + "markdown": "# MemberOrg 会员单位\n\n**分类**:缺实例\n**引用**:§1.3 战略 14\n\n## 现状\n\n0 实例\n\n## 应有\n\n区域代理商、行业合作伙伴\n\n## 影响\n\n生态合作网络空白\n\n## 抽取说明\n\n在「MemberOrg」类型下补充战略 14 招募的区域行业代理商、行业合作伙伴实例,标注区域、行业、合作模式。\n" + }, + { + "id": 21, + "category": "missing-instance", + "severity": "amber", + "name": "DataExchange 数据交易所", + "ref": "§1.1 战略 8", + "description": "在「DataExchange」类型下补充 §1.1 战略 8 综合性门户中的交易所模块实例,标注名称、接入产品、结算方式。", + "status": "applied", + "appliedAt": "2026-08-21T05:57:20.134Z", + "kind": "document", + "title": "导入文档 DataExchange 数据交易所", + "rationale": "交易所战略无数据载体", + "filename": "架构/v1.1.2/B-21-DataExchange.md", + "markdown": "# DataExchange 数据交易所\n\n**分类**:缺实例\n**引用**:§1.1 战略 8\n\n## 现状\n\n0 实例\n\n## 应有\n\n交易所模块实例\n\n## 影响\n\n交易所战略无数据载体\n\n## 抽取说明\n\n在「DataExchange」类型下补充 §1.1 战略 8 综合性门户中的交易所模块实例,标注名称、接入产品、结算方式。\n" + }, + { + "id": 22, + "category": "stale", + "severity": "orange", + "name": "Connector 角色枚举", + "ref": "§1.5/§4.4 区块链存证", + "description": "修订「Connector」的 role 枚举,新增 §1.5/§4.4 区块链存证引入的经纪人/登记机构/中央数据机构等角色。需 schema 迁移或管理员 SQL,不能仅靠 AI 抽取。", + "status": "pending", + "kind": "operation", + "title": "修订枚举 Connector.role", + "rationale": "区块链存证角色无法建模", + "method": "update_enum", + "params": { + "type": "Connector", + "property": "role", + "add_values": [ + "broker", + "registry", + "central_data_authority" + ] + } + }, + { + "id": 23, + "category": "stale", + "severity": "orange", + "name": "TrustedDataSpace 部署方式", + "ref": "§1.6 五层架构", + "description": "修订「TrustedDataSpace」deploy_mode 枚举,新增 §1.6 的运营 SaaS 模式。需 schema 迁移或管理员 SQL。", + "status": "pending", + "kind": "operation", + "title": "修订枚举 TrustedDataSpace.deploy_mode", + "rationale": "SaaS 部署实例无法准确分类", + "method": "update_enum", + "params": { + "type": "TrustedDataSpace", + "property": "deploy_mode", + "add_values": [ + "saas" + ] + } + }, + { + "id": 24, + "category": "stale", + "severity": "orange", + "name": "Connector 能力清单", + "ref": "§2.1 + §4.5 策略引擎", + "description": "修订「Connector」capabilities,将使用控制策略引擎(§2.1/§4.5)作为独立结构化能力而非 text 字段。需 schema 迁移或管理员 SQL。", + "status": "pending", + "kind": "document", + "title": "导入文档 Connector 能力清单", + "rationale": "连接器能力不可查询、不可比较", + "filename": "架构/v1.1.2/C-24-ConnectorCapabilities.md", + "markdown": "# Connector 能力清单\n\n**分类**:过期不一致\n**引用**:§2.1 + §4.5 策略引擎\n\n## 现状\n\ncapabilities text 字段\n\n## 应有\n\n策略引擎作为独立结构化能力\n\n## 影响\n\n连接器能力不可查询、不可比较\n\n## 抽取说明\n\n修订「Connector」capabilities,将使用控制策略引擎(§2.1/§4.5)作为独立结构化能力而非 text 字段。需 schema 迁移或管理员 SQL。\n" + }, + { + "id": 25, + "category": "stale", + "severity": "orange", + "name": "DataProduct 计费模式", + "ref": "§6.1.5 SAOP 自动扣费", + "description": "修订「DataProduct」billing_mode 枚举,新增 §6.1.5 SAOP 的计量计费/智能合约扣费模式。需 schema 迁移或管理员 SQL。", + "status": "pending", + "kind": "operation", + "title": "修订枚举 DataProduct.billing_mode", + "rationale": "新计费模式无法表达", + "method": "update_enum", + "params": { + "type": "DataProduct", + "property": "billing_mode", + "add_values": [ + "smart_contract", + "metered" + ] + } + }, + { + "id": 26, + "category": "stale", + "severity": "orange", + "name": "AppStore 状态枚举", + "ref": "§1.4 OPC 试点/技能演练", + "description": "修订「AppStore」status 枚举,新增 §1.4 OPC 试点/技能演练所需的 incubating/pilot/archived 中间态。需 schema 迁移或管理员 SQL。", + "status": "pending", + "kind": "operation", + "title": "修订枚举 AppStore.status", + "rationale": "OPC 与技能演练状态无法表达", + "method": "update_enum", + "params": { + "type": "AppStore", + "property": "status", + "add_values": [ + "incubating", + "pilot", + "archived" + ] + } + }, + { + "id": 27, + "category": "stale", + "severity": "orange", + "name": "TDS 安全执行层关联", + "ref": "§1.6 第 3/4 层", + "description": "新增 link_type 表达「TrustedDataSpace」与 TEE/区块链/Nax 等安全执行层能力的绑定关系(§1.6 第 3/4 层),如 tds_uses_tee / tds_uses_blockchain。", + "status": "pending", + "kind": "operation", + "title": "新建关系类型 SpaceUsesSecurityLayer", + "rationale": "安全能力绑定关系不可见", + "method": "create_link_type", + "params": { + "api_name": "SpaceUsesSecurityLayer", + "display_name": "TDS绑定安全执行层", + "source_type": "TrustedDataSpace", + "target_type": "ArchitectureComponent", + "cardinality": "many_to_many", + "description": "表达 TrustedDataSpace 与 TEE/区块链/Nax 等安全执行层能力的绑定(§1.6 第3/4层),如 tds_uses_tee / tds_uses_blockchain。" + } + }, + { + "id": 28, + "category": "stale", + "severity": "orange", + "name": "Marking 合规分级", + "ref": "§1.4 信创合规", + "description": "修订全局 Marking 分类,在 L0-L4 安全分级之外新增 §1.4 信创合规约束对应的信创级/国密级/等保级。需 schema 迁移或管理员 SQL。", + "status": "pending", + "kind": "document", + "title": "导入文档 Marking 合规分级", + "rationale": "合规约束无法进入访问控制策略", + "filename": "架构/v1.1.2/C-28-ComplianceMarking.md", + "markdown": "# Marking 合规分级\n\n**分类**:过期不一致\n**引用**:§1.4 信创合规\n\n## 现状\n\n仅 L0-L4 安全分级\n\n## 应有\n\n新增信创级/国密级/等保级 marking\n\n## 影响\n\n合规约束无法进入访问控制策略\n\n## 抽取说明\n\n修订全局 Marking 分类,在 L0-L4 安全分级之外新增 §1.4 信创合规约束对应的信创级/国密级/等保级。需 schema 迁移或管理员 SQL。\n" + }, + { + "id": 29, + "category": "relation", + "severity": "emerald", + "name": "下游消费本体语义关系", + "ref": "§1.5 闭环图", + "description": "新增 link_type(如 consumes_ontology / extends_schema),表达 §1.5 闭环图中 ssw-ontology 与 SAOP/jnpf-lite/算子集市之间的消费/扩展关系,并创建代表性实例。", + "status": "manual", + "kind": "operation", + "title": "新建关系类型 consumes_ontology", + "rationale": "本体价值闭环无法被追踪", + "method": "create_link_type", + "params": { + "api_name": "consumes_ontology", + "display_name": "消费/扩展本体", + "source_type": "Service", + "target_type": "ArchitectureComponent", + "cardinality": "many_to_many", + "description": "表达 ssw-ontology 与 SAOP/jnpf-lite/算子集市之间的消费/扩展关系(§1.5 闭环图),如 consumes_ontology / extends_schema。" + } + } + ] +} \ No newline at end of file diff --git a/web/src/App.vue b/web/src/App.vue index 03cb030..0990e88 100644 --- a/web/src/App.vue +++ b/web/src/App.vue @@ -1,5 +1,6 @@ + \ No newline at end of file diff --git a/web/src/api.js b/web/src/api.js index 1ef1a38..9b9c213 100644 --- a/web/src/api.js +++ b/web/src/api.js @@ -4,7 +4,8 @@ const BASE = '/api/v1' async function request(method, path, body) { const opts = { method, - headers: { 'Content-Type': 'application/json' } + headers: { 'Content-Type': 'application/json' }, + credentials: 'include' // 携带 cookie 用于 session 鉴权 } if (body !== undefined) { opts.body = JSON.stringify(body) @@ -124,5 +125,72 @@ export const api = { const q = new URLSearchParams(params).toString() return request('GET', '/access/log' + (q ? '?' + q : '')) }, - accessLogStats: () => request('GET', '/access/log/stats') + accessLogStats: () => request('GET', '/access/log/stats'), + + // ---- 账号密码登录与会话 ---- + // dev 模式下也支持登录(与 X-API-Key 并存)。登录后浏览器自动带 cookie; + // 后端 principalFromRequest 优先识别 cookie → 命名主体。 + authLogin: (name, password) => request('POST', '/auth/login', { name, password }), + authLogout: () => request('POST', '/auth/logout'), + authMe: () => request('GET', '/auth/me'), + changePassword: (body) => request('POST', '/auth/change-password', body), + + // ---- MCP JSON-RPC over SSE(供 ReviewView 等前端组件调用)---- + // 用法:api.mcpCall('tools/call', { name, arguments }) + // 端点默认走当前 SPA 同源(window.location.origin + '/api/v1/mcp'), + // 必要时可通过 api.setMcpEndpoint(url) 覆盖;apiKey 走同源管理器(暂不持久化)。 + _mcp: { endpoint: null, apiKey: '' }, + setMcpEndpoint(url) { api._mcp.endpoint = url }, + setMcpApiKey(key) { api._mcp.apiKey = key }, + _mcpEndpoint() { + if (api._mcp.endpoint) return api._mcp.endpoint + return (typeof location !== 'undefined' ? location.origin : '') + '/api/v1/mcp' + }, + async mcpCall(method, params, opts = {}) { + const endpoint = opts.endpoint || api._mcpEndpoint() + const headers = { 'Content-Type': 'application/json', 'Accept': 'application/json, text/event-stream' } + if (opts.apiKey || api._mcp.apiKey) headers['X-API-Key'] = opts.apiKey || api._mcp.apiKey + let res + try { + res = await fetch(endpoint, { method: 'POST', headers, body: JSON.stringify({ jsonrpc: '2.0', id: Date.now(), method, params }) }) + } catch (netErr) { + throw new Error(`网络层失败:${netErr.message}。请检查 MCP 可达 / 是否经代理(见 ReviewView 使用说明)。`) + } + if (!res.ok) { + let body = ''; try { body = await res.text() } catch (e) {} + throw new Error(`HTTP ${res.status} ${res.statusText}${body ? ' | ' + body.slice(0, 200) : ''}`) + } + const text = await res.text() + const lines = text.split(/\r?\n/) + for (const line of lines) { + const t = line.trim() + if (t.startsWith('data:')) { + const data = t.slice(5).trim() + if (data === '[DONE]') continue + try { return JSON.parse(data) } catch (e) { throw new Error(`SSE data 非有效 JSON: ${data.slice(0, 120)}... (${e.message})`) } + } + } + try { return JSON.parse(text) } catch (e) { throw new Error('响应不是有效 JSON-RPC') } + }, + async mcpTools(opts) { + const r = await api.mcpCall('tools/list', {}, opts) + if (r.error) throw new Error(JSON.stringify(r.error)) + return r.result?.tools || [] + }, + async mcpWhoami(opts) { + const tools = await api.mcpTools(opts) + if (!tools.find(t => t.name === 'whoami')) return { hasWhoami: false } + const r = await api.mcpCall('tools/call', { name: 'whoami', arguments: {} }, opts) + if (r.error) throw new Error(JSON.stringify(r.error)) + const text = (r.result?.content?.[0]?.text) || JSON.stringify(r.result) + const info = JSON.parse(text) + return { hasWhoami: true, principal: info.principal, can_write: !!info.can_write, clearances: info.clearances } + }, + mcpUnwrapText(r) { + const c = r?.result?.content + if (Array.isArray(c) && c.length) return c[0].text + if (typeof r?.result === 'string') return r.result + if (r?.result) return JSON.stringify(r.result) + return JSON.stringify(r?.error ?? r) + } } diff --git a/web/src/components/ReviewWorkbench.vue b/web/src/components/ReviewWorkbench.vue new file mode 100644 index 0000000..2b4909c --- /dev/null +++ b/web/src/components/ReviewWorkbench.vue @@ -0,0 +1,301 @@ + + + + + \ No newline at end of file diff --git a/web/src/composables/useReviewWorkbench.js b/web/src/composables/useReviewWorkbench.js new file mode 100644 index 0000000..fc2ddb9 --- /dev/null +++ b/web/src/composables/useReviewWorkbench.js @@ -0,0 +1,267 @@ +import { ref, reactive, computed } from 'vue' +import { api } from '../api.js' + +const STORAGE_KEY = 'mcp-review-items-v2' +const METHOD_LABEL = { + create_object_type: '新建类型', + create_link_type: '新建关系类型', + create_object: '补充实例', + create_link: '新增关系', + update_enum: '修订枚举' +} + +function lsGet(k) { try { return JSON.parse(localStorage.getItem(k)) } catch (e) { return null } } +function lsSet(k, v) { try { localStorage.setItem(k, JSON.stringify(v)) } catch (e) {} } +function pad(n) { return String(n).padStart(2, '0') } +function methodLabel(m) { return METHOD_LABEL[m] || m } +function esc(s) { return String(s == null ? '' : s).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"') } + +/** + * 导入核对工作台 composable。 + * 共享于:(1) 主站「导入核对」tab(cookie session, is_manager=manager) + * (2) /import-review.html 独立页(X-API-Key,可任意主体) + * + * opts.endpoint 可覆盖默认同源 URL(独立页用) + * opts.apiKey 可覆盖默认无 Key(独立页用) + */ +export function useReviewWorkbench(opts = {}) { + // 连接配置:主站用同源 + cookie session;独立页让用户填 URL/Key + const mcpUrl = ref(opts.endpoint || (typeof location !== 'undefined' ? location.origin + '/api/v1/mcp' : '')) + const mcpKey = ref(opts.apiKey || '') + + const items = ref([]) + const checkedIds = ref(new Set()) + const expandedDetails = ref(new Set()) + const currentFilter = ref('all') + const currentStatus = ref('all') + const logs = ref([]) + const conn = reactive({ principal: null, canWrite: null, hasWhoami: false }) + const connState = ref('idle') + const fileInput = ref(null) + + const counts = computed(() => { + const c = { all: items.value.length, 'missing-type': 0, 'missing-instance': 0, stale: 0, relation: 0, '__other': 0, '__op': 0, '__doc': 0, applied: 0, pending: 0 } + for (const it of items.value) { + if (['missing-type', 'missing-instance', 'stale', 'relation', '__other'].includes(it.category)) c[it.category]++ + else c['__other']++ + if (it.kind === 'operation') c['__op']++; else c['__doc']++ + if (it.status === 'applied') c.applied++; else c.pending++ + } + return c + }) + const progressApplied = computed(() => counts.value.applied) + const progressPct = computed(() => items.value.length ? Math.round(progressApplied.value / items.value.length * 100) : 0) + const progressOffset = computed(() => 326.73 - 326.73 * progressPct.value / 100) + const statusCounts = computed(() => { + const sc = { pending: 0, reviewing: 0, applied: 0, skipped: 0, failed: 0, manual: 0 } + for (const it of items.value) sc[it.status] = (sc[it.status] || 0) + 1 + return sc + }) + const statRate = computed(() => progressPct.value) + const statTodo = computed(() => statusCounts.value.pending + statusCounts.value.reviewing) + const statDone = computed(() => statusCounts.value.applied) + const statFail = computed(() => statusCounts.value.failed + statusCounts.value.manual) + const pageSub = computed(() => `共 ${items.value.length} 项 · ${progressApplied.value} 已应用`) + const banner = computed(() => { + if (!items.value.length) return null + if (conn.canWrite === true) return { cls: 'exec', html: `✓ 可执行模式(身份:${esc(conn.principal || '未知')})— 操作项直接调 MCP 应用;文档项上传 Markdown 抽取导入。无需任何 SQL。` } + if (conn.canWrite === false) return { cls: 'export', html: `⚠ 只读模式(身份:${esc(conn.principal || '未知')})— 无写权限,核对后请「导出执行清单 JSON / 报告 MD」交管理员统一执行。` } + return { cls: 'info', html: `ℹ 尚未探测写权限,点「测试连接」后将自动判断可执行 / 只读导出。` } + }) + const filteredItems = computed(() => items.value.filter(it => { + if (currentFilter.value !== 'all') { + if (currentFilter.value === '__op' && it.kind !== 'operation') return false + if (currentFilter.value === '__doc' && it.kind !== 'document') return false + if (currentFilter.value !== '__op' && currentFilter.value !== '__doc' && it.category !== currentFilter.value) return false + } + if (currentStatus.value !== 'all' && it.status !== currentStatus.value) return false + return true + })) + + function loadBuiltin() { + fetch('/builtin-review-manifest.json').then(r => r.json()).then(obj => { importItems(obj, true); log('已载入内置核对清单', 'ok') }) + .catch(e => { log('内置清单载入失败(可能经代理):' + e.message + '。可改用代理或导入 JSON。', 'err') }) + } + function importItems(obj, silent) { + if (!obj || typeof obj !== 'object') { log('导入失败:JSON 结构异常', 'err'); return } + let raw = [] + if (Array.isArray(obj.items) && obj.items.length) raw = obj.items + else if (Array.isArray(obj.findings) && obj.findings.length) raw = obj.findings.map(findingToItem) + else if (Array.isArray(obj) && obj.length) raw = obj + if (!raw.length) { log('导入失败:未找到 items / findings 数组', 'err'); return } + items.value = raw.map((it, idx) => normalizeItem(it, idx)) + saveItems() + if (!silent) log(`已导入 ${items.value.length} 项,开始核对`, 'ok') + } + function findingToItem(f) { + const term = f.term || '(未命名)' + const refs = Array.isArray(f.source_refs) ? f.source_refs.join('、') : '' + const desc = `资料提及「${term}」(${refs || '见原文'}),本体命中 ${f.ontology_hits || 0} 条。建议补充为本体实例/类型。` + return { kind: 'document', name: term, category: '__other', severity: 'blue', ref: refs, description: desc, filename: `核对/${term}.md`, markdown: `# ${term}\n\n${desc}\n`, status: 'pending' } + } + function normalizeItem(it, idx) { + let kind = it.kind + if (!kind) { + if (it.method && it.params) kind = 'operation' + else if (it.markdown || (it.archive_path && it.description)) kind = 'document' + else if (it.action === 'create_type') kind = 'operation' + else kind = 'document' + } + const out = { + id: (it.id != null ? it.id : idx + 1), + name: it.name || it.term || ('项' + (idx + 1)), + category: it.category || '__other', + severity: it.severity || 'blue', + kind, + ref: it.ref || it.source || it.source_refs || '', + description: it.description || it.summary || '', + rationale: it.rationale || '', + status: it.status || 'pending', result: it.result || null, error: it.error || null, appliedAt: it.appliedAt || null, + now: it.now || '', + should: it.should || '' + } + if (typeof out.ref === 'object') out.ref = out.ref.join('、') + if (kind === 'operation') { + out.method = it.method || ({ create_type: 'create_object_type', update_enum: 'update_enum', add_relation: 'create_link_type' }[it.action] || 'create_object_type') + out.params = it.params || {} + } else { + out.filename = it.filename || it.archive_path || (`核对/${out.name}.md`) + out.markdown = it.markdown || buildMarkdownFallback(out) + } + return out + } + function buildMarkdownFallback(it) { + return `# ${it.name}\n\n**引用**:${it.ref || ''}\n\n## 抽取说明\n\n${it.description || ''}\n` + } + function saveItems() { lsSet(STORAGE_KEY, items.value) } + function log(msg, type = 'info') { const t = new Date().toLocaleTimeString(); logs.value.push({ t, msg, type }) } + + function toggleSelect(id) { if (checkedIds.value.has(id)) checkedIds.value.delete(id); else checkedIds.value.add(id) } + function toggleDetail(id) { const k = 'detail-' + id; if (expandedDetails.value.has(k)) expandedDetails.value.delete(k); else expandedDetails.value.add(k) } + function setStatus(id, status) { const it = items.value.find(x => x.id === id); if (!it) return; it.status = status; if (status === 'applied') it.appliedAt = new Date().toISOString(); saveItems() } + function selectAll() { const s = new Set(); items.value.forEach(it => s.add(it.id)); checkedIds.value = s } + function clearSelection() { checkedIds.value = new Set() } + function resetStatus() { if (!confirm('重置所有状态到初始值?')) return; items.value.forEach(it => { it.status = 'pending'; it.result = null; it.error = null; it.appliedAt = null }); expandedDetails.value = new Set(); checkedIds.value = new Set(); saveItems() } + + // MCP 调用:opts.endpoint / opts.apiKey 覆盖默认值 + async function callMcp(method, params) { + const o = {} + if (mcpUrl.value.trim()) o.endpoint = mcpUrl.value.trim() + if (mcpKey.value.trim()) o.apiKey = mcpKey.value.trim() + return await api.mcpCall(method, params, o) + } + async function testConnection() { + connState.value = 'idle' + log('测试 MCP 连接 …', 'info') + const o = {} + if (mcpUrl.value.trim()) o.endpoint = mcpUrl.value.trim() + if (mcpKey.value.trim()) o.apiKey = mcpKey.value.trim() + try { + const tools = await api.mcpTools(o) + const names = tools.map(t => t.name) + log(`连接成功,tools:${names.slice(0, 8).join(', ')}${names.length > 8 ? ' 等' : ''}`, 'ok') + connState.value = 'ok' + const info = await api.mcpWhoami(o) + if (info.hasWhoami) { + conn.principal = info.principal; conn.canWrite = !!info.can_write; conn.hasWhoami = true + log(`身份探测:${info.principal} · ${info.can_write ? '可写(可执行)' : '只读(导出模式)'}`, info.can_write ? 'ok' : 'warn') + } else { + conn.canWrite = false; log('未提供 whoami 工具,默认只读导出模式。', 'warn') + } + } catch (err) { + connState.value = 'err' + log(`连接失败:${err.message}`, 'err') + } + } + async function applyItem(id) { + const it = items.value.find(x => x.id === id); if (!it) return + if (conn.canWrite !== true) { log(`[#${it.id}] 当前身份无写权限,已禁用。请导出清单交管理员执行。`, 'warn'); return } + it.status = 'reviewing'; saveItems(); log(`[#${it.id}] 开始应用 = ${it.name}(${it.kind === 'operation' ? '操作' : '文档'})`, 'info') + try { + if (it.kind === 'operation') { + const r = await callMcp('tools/call', { name: it.method, arguments: it.params || {} }) + if (r.error) throw new Error(JSON.stringify(r.error)) + it.result = r.result; it.status = 'applied'; it.appliedAt = new Date().toISOString(); it.error = null + log(`[#${it.id}] ${it.method} 应用成功 → ${api.mcpUnwrapText(r).slice(0, 120)}`, 'ok') + } else { + const folder = it.filename.split('/').slice(0, -1).join('/') + const filename = it.filename.split('/').pop() + log(`[#${it.id}] 上传 ${folder || '/'}/${filename} …`, 'info') + const up = await callMcp('tools/call', { name: 'km_upload_markdown', arguments: { folder, filename, content: it.markdown } }) + if (up.error) throw new Error(JSON.stringify(up.error)) + log(`[#${it.id}] 上传成功,抽取中 …`, 'info') + const ex = await callMcp('tools/call', { name: 'km_extract', arguments: { rel_paths: [it.filename], directive: it.description, mode: 'auto' } }) + if (ex.error) throw new Error(JSON.stringify(ex.error)) + it.result = ex.result || ex; it.status = 'applied'; it.appliedAt = new Date().toISOString(); it.error = null + log(`[#${it.id}] 文档导入成功`, 'ok') + } + } catch (err) { it.error = err.message; it.status = 'failed'; log(`[#${it.id}] 失败:${err.message}`, 'err') } + saveItems() + } + async function batchApply() { + const ids = [...checkedIds.value].filter(k => typeof k === 'number') + if (ids.length === 0) { log('未选中任何项目', 'warn'); return } + if (conn.canWrite !== true) { log('当前身份无写权限,无法直连 Apply。请导出清单交管理员执行。', 'warn'); return } + const todo = ids.filter(id => { const it = items.value.find(x => x.id === id); return it && it.status !== 'applied' }) + if (todo.length === 0) { log('选中项已全部应用', 'info'); return } + log(`直连 Apply ${todo.length} 项 …`, 'info') + for (const id of todo) { await applyItem(id); await new Promise(r => setTimeout(r, 500)) } + log('批量执行结束', 'ok') + } + function exportJson() { + const payload = { + meta: { + title: '尚数网导入核对执行清单', + exportedAt: new Date().toISOString(), + totalItems: items.value.length, + operationCount: items.value.filter(i => i.kind === 'operation').length, + documentCount: items.value.filter(i => i.kind === 'document').length, + defaultMode: conn.canWrite === true ? '当前主体具备写权限,可直接 Apply;也可导出交他人执行' : '导出后由管理员统一执行(当前身份只读)', + mcpEndpoint: mcpUrl.value.trim(), + auth: mcpKey.value.trim() ? 'X-API-Key: ***(已隐藏,避免泄漏)' : '当前 cookie session(管理员/ingest 身份)', + schema: '每条 items[].kind ∈ {operation, document}。operation={method,params} 直接调对应 MCP 工具应用(无需 AI 再解析,无需 SQL);document={filename,markdown} 调 km_upload_markdown+km_extract 导入。', + methodLegend: METHOD_LABEL + }, + items: items.value.map(it => { + const o = { id: it.id, category: it.category, severity: it.severity, name: it.name, kind: it.kind, ref: it.ref, description: it.description, rationale: it.rationale, status: it.status, appliedAt: it.appliedAt } + if (it.kind === 'operation') { o.method = it.method; o.params = it.params } else { o.filename = it.filename; o.markdown = it.markdown } + return o + }) + } + const b = new Blob([JSON.stringify(payload, null, 2)], { type: 'text/plain;charset=utf-8' }) + const a = document.createElement('a'); a.href = URL.createObjectURL(b); a.download = 'ontology-execution-list.json'; a.click(); URL.revokeObjectURL(a.href) + log(`已导出执行清单 JSON(${payload.meta.operationCount} 操作项 / ${payload.meta.documentCount} 文档项)`, 'ok') + } + function exportMd() { + const statusText = (s) => ({ pending: '待核对', reviewing: '修订/补充', applied: '已应用', skipped: '已跳过', failed: '失败', manual: '需手工' })[s] || s + let md = '# 尚数网本体核对报告\n\n| # | 名称 | 分类 | 执行方式 | 方法/文件 | 状态 | 备注 |\n|---|---|---|---|---|---|---|\n' + items.value.forEach(it => { + const note = it.error ? `失败:${it.error}` : (it.appliedAt ? `完成于 ${it.appliedAt}` : (it.status === 'skipped' ? '已跳过' : '')) + const how = it.kind === 'operation' ? ('操作·' + (METHOD_LABEL[it.method] || it.method)) : ('文档·' + it.filename) + const cat = { 'missing-type': '缺失元原语', 'missing-instance': '缺实例', stale: '过期不一致', relation: '缺关系' }[it.category] || it.category + md += `| ${it.id} | ${it.name} | ${cat} | ${it.kind === 'operation' ? '操作' : '文档'} | ${how} | ${statusText(it.status)} | ${note} |\n` + }) + const b = new Blob([md], { type: 'text/plain;charset=utf-8' }) + const a = document.createElement('a'); a.href = URL.createObjectURL(b); a.download = 'ontology-apply-report.md'; a.click(); URL.revokeObjectURL(a.href) + } + function onFile(e) { + const f = e.target.files[0]; if (!f) return + const rd = new FileReader() + rd.onload = () => { try { importItems(JSON.parse(rd.result)) } catch (err) { log('JSON 解析失败:' + err.message, 'err') } } + rd.readAsText(f) + } + function reloadBuiltin() { items.value = []; saveItems(); loadBuiltin() } + + return { + // state + items, checkedIds, expandedDetails, currentFilter, currentStatus, logs, conn, connState, + mcpUrl, mcpKey, fileInput, + // computed + counts, progressPct, progressOffset, statRate, statTodo, statDone, statFail, pageSub, banner, filteredItems, + // methods + loadBuiltin, importItems, saveItems, log, + toggleSelect, toggleDetail, setStatus, selectAll, clearSelection, resetStatus, + testConnection, applyItem, batchApply, exportJson, exportMd, onFile, reloadBuiltin, + methodLabel, pad + } +} \ No newline at end of file diff --git a/web/src/entry-review.js b/web/src/entry-review.js new file mode 100644 index 0000000..12c6818 --- /dev/null +++ b/web/src/entry-review.js @@ -0,0 +1,6 @@ +import { createApp } from 'vue' +import ElementPlus from 'element-plus' +import 'element-plus/dist/index.css' +import ReviewWorkbench from './components/ReviewWorkbench.vue' + +createApp(ReviewWorkbench).use(ElementPlus).mount('#app') \ No newline at end of file diff --git a/web/src/views/LoginView.vue b/web/src/views/LoginView.vue new file mode 100644 index 0000000..5a2a785 --- /dev/null +++ b/web/src/views/LoginView.vue @@ -0,0 +1,60 @@ + + + + + \ No newline at end of file diff --git a/web/src/views/ReviewView.vue b/web/src/views/ReviewView.vue new file mode 100644 index 0000000..c829243 --- /dev/null +++ b/web/src/views/ReviewView.vue @@ -0,0 +1,7 @@ + + + \ No newline at end of file diff --git a/web/vite.config.js b/web/vite.config.js index 4a9cd87..87e7cbb 100644 --- a/web/vite.config.js +++ b/web/vite.config.js @@ -1,5 +1,6 @@ import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' +import { resolve } from 'path' // 构建产物使用相对路径,便于被 Go 以 embed 方式在根路径下提供。 export default defineConfig({ @@ -8,7 +9,13 @@ export default defineConfig({ build: { outDir: 'dist', assetsDir: 'assets', - chunkSizeWarningLimit: 1500 + chunkSizeWarningLimit: 1500, + rollupOptions: { + input: { + main: resolve(__dirname, 'index.html'), + 'import-review': resolve(__dirname, 'import-review.html') + } + } }, server: { port: 5173,