fix: Z35 map Chinese display names to stable physical DB names

Keep Chinese on Binding for UI; Agents use user_{id} or db{hash}; sanitize on attach/heal/publish.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
whm
2026-08-07 02:12:55 +08:00
parent 7290f91d3a
commit 4b6c90904b
8 changed files with 146 additions and 32 deletions

View File

@@ -2,11 +2,14 @@ package schema
import (
"context"
"crypto/sha256"
"database/sql"
"encoding/hex"
"fmt"
"net/url"
"regexp"
"strings"
"unicode"
)
var dbNameRe = regexp.MustCompile(`^[a-z][a-z0-9_]{1,47}$`)
@@ -108,3 +111,52 @@ func SafePhysicalDBName(preferred, fallback string) string {
}
return "appdb_default"
}
// SafeSyncDatabaseName Z35智能体同步落点的 Postgres 物理库名。
// - 已是合法 ASCII → 原样
// - 中文/非法串:有 userID → user_{id}(昵称可变仍稳定);否则对标签做稳定哈希 db{hex}
// - 展示中文请写 Binding.DisplayName / Binding.DatabaseName可读名勿把物理名当展示名
func SafeSyncDatabaseName(preferred string, agentID, userID int64) string {
p := strings.TrimSpace(preferred)
if ValidDBName(p) {
return p
}
// 有登录用户:物理名跟用户稳定绑定;中文昵称只作展示
if userID > 0 {
n := fmt.Sprintf("user_%d", userID)
if ValidDBName(n) {
return n
}
}
if p != "" {
return HashLabelDBName(p, agentID)
}
if agentID > 0 {
n := fmt.Sprintf("agent_%d", agentID)
if ValidDBName(n) {
return n
}
}
return "appdb_default"
}
// HashLabelDBName 将任意标签含中文稳定映射为合法物理库名db + 16 hex。
func HashLabelDBName(label string, agentID int64) string {
label = strings.TrimSpace(label)
sum := sha256.Sum256([]byte(fmt.Sprintf("ajz-db:%d:%s", agentID, label)))
return "db" + hex.EncodeToString(sum[:8])
}
// IsDisplayLabel 是否更像「展示名」而非物理库名(含非 ASCII / 大写 / 连字符等)。
func IsDisplayLabel(s string) bool {
s = strings.TrimSpace(s)
if s == "" || ValidDBName(s) {
return false
}
for _, r := range s {
if r > unicode.MaxASCII || unicode.Is(unicode.Han, r) {
return true
}
}
return true
}