Files
memoryweave/go/internal/governance/graph_auto.go
T
小唯 e91ca91367 fix(security): 写入侧凭证过滤 — 密钥不再进记忆/图谱/Obsidian 镜像
背景(2026-09-10 mc P0 事故):某轮蒸馏把含真 Tailscale 预授权 key 的原始对话
当事实入库 → 知识图谱按其文本建实体 → ObsidianSyncer 用实体标题当文件名/正文,
把 tskey-auth-… 落成可读镜像文件,又被 git 跟踪并推送 Gitea。
本提交在三个写入边界统一加脱敏。

新增 internal/redact(唯一真源):
- SecretPattern 覆盖 sk- / tskey- / github_pat_ / ghp_ / nvapi- / AKIA
- Go RE2 不支持 lookbehind,故"前一字符是否属于更长标识符"手工判定(isTokenByte)
- sk- 段只吃 [A-Za-z0-9],避免误伤 URL 里的 task-driven 片段(事故中的假阳性来源)
- RedactSecrets 幂等;ContainsSecret 供"直接丢弃"场景用

四处接入:
- distill/quality.go       IsQualityFact 判定前脱敏 + FilterQualityFacts 返回值脱敏
- governance/graph_auto.go cleanEntityName 命中→空串;UpdateFromDistill 只对有效实体
                           建节点/建边;extractEntitiesFromText 过滤;含凭证的 fact 不建节点
- api/routes/obsidian.go   sanitizeFilename 入参脱敏 + PushToObsidian 镜像正文脱敏
- api/server.go            蒸馏直写记忆库路径(绕过 FilterQualityFacts 的那条)同步脱敏

测试:13 条新用例(redact 5 / distill 3 / governance 4 / routes 1),
含 URL 假阳性回归与幂等性断言。全部使用构造的假密钥,不含任何真实凭证。
证据:go build ./... OK;
go test -count=1 ./internal/redact/ ./internal/distill/ ./internal/governance/ ./internal/api/routes/ 全绿。

顺带修既有 test 腐化(否则 governance 包根本无法编译测试,非本任务引入):
governance_test.go isContradiction→IsContradiction、Navigate 补 relFilter 参数;
bench_test.go 同。仅测试文件,无生产行为改动。
2026-09-11 00:41:59 +08:00

234 lines
7.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 织忆 MemoryWeave — 知识图谱自动更新引擎
package governance
import (
"fmt"
"strings"
"time"
"unicode"
"github.com/xiaoxue/memoryweave/internal/redact"
)
// AutoGraphUpdater 自动维护知识图谱
type AutoGraphUpdater struct {
graph GraphStore
}
func NewAutoGraphUpdater(g GraphStore) *AutoGraphUpdater {
return &AutoGraphUpdater{graph: g}
}
// UpdateFromDistill 从蒸馏产物自动更新图谱(§3.4)
func (agu *AutoGraphUpdater) UpdateFromDistill(distilled *DistillInput) {
// 0. 密钥过滤(2026-09-10 P0,见 internal/redact):含凭证形状的实体不进图,
// 否则实体名会被 ObsidianSync 当文件名,把密钥落成可读镜像文件
// (实例:小唯/07-Wiki/织忆/未找到命令.md 的文件名与正文含 tskey-auth-…)。
validEnts := make([]string, 0, len(distilled.Entities))
for _, entity := range distilled.Entities {
if redact.ContainsSecret(entity) || cleanEntityName(entity) == "" {
continue
}
validEnts = append(validEnts, entity)
}
// 1. 提取实体并创建节点(ID 和 name 都清洗)
for _, entity := range validEnts {
nodeID := entityID(entity)
cleanName := cleanEntityName(entity)
agu.graph.AddNode(nodeID, cleanName, detectNodeType(entity), distilled.Namespace)
}
// 2. 创建实体间关系 + CO_OCCURS 共访边
entityCount := len(validEnts)
for i := 0; i < entityCount; i++ {
for j := i + 1; j < entityCount; j++ {
eidI := entityID(validEnts[i])
eidJ := entityID(validEnts[j])
// 2a. 语义关系边(inferRelation)
edgeID := fmt.Sprintf("e_%s_%s_%d", eidI, eidJ, time.Now().UnixNano())
relation := inferRelation(validEnts[i], validEnts[j], distilled.Content)
agu.graph.AddEdge(edgeID, eidI, eidJ,
relation, distilled.Namespace, 0.5)
// 2b. CO_OCCURS 共访边(§2.5.2 来源 2)
// 权重 = 1 / sqrt(entityCount) — 实体越多单对权重越低
coWeight := 1.0
if entityCount > 2 {
coWeight = 1.0 / sqrtFloat(float64(entityCount))
}
coEdgeID := fmt.Sprintf("co_%s_%s_%d", eidI, eidJ, time.Now().UnixNano())
agu.graph.AddEdge(coEdgeID, eidI, eidJ,
"CO_OCCURS", distilled.Namespace, coWeight)
}
}
// 3. 按内容类别创建冲突检测边 → 使用设计规范的 CONFLICTS_WITH 类型
for _, fact := range distilled.Facts {
entities := extractEntitiesFromText(fact)
for i := 0; i < len(entities); i++ {
for j := i + 1; j < len(entities); j++ {
if conflictPossible(entities[i], entities[j], fact) {
eidI := entityID(entities[i])
eidJ := entityID(entities[j])
edgeID := fmt.Sprintf("cw_%s_%s_%d", eidI, eidJ, time.Now().UnixNano())
agu.graph.AddEdge(edgeID, eidI, eidJ,
"CONFLICTS_WITH", distilled.Namespace, 0.3)
}
}
}
}
// 4. DERIVED_FROM 边:蒸馏产物 → 原始 episode
if distilled.EpisodeID != "" {
for _, entity := range validEnts {
eid := entityID(entity)
derivedEdgeID := fmt.Sprintf("df_%s_%s_%d", eid, distilled.EpisodeID, time.Now().UnixNano())
agu.graph.AddEdge(derivedEdgeID, eid, distilled.EpisodeID,
"DERIVED_FROM", distilled.Namespace, 0.9)
}
for _, fact := range distilled.Facts {
if redact.ContainsSecret(fact) {
continue // 含凭证的事实不建节点(2026-09-10 P0)
}
factNodeID := "f_" + strings.ReplaceAll(entityID(fact), "n_", "")
derivedEdgeID := fmt.Sprintf("df_%s_%s_%d", factNodeID, distilled.EpisodeID, time.Now().UnixNano())
agu.graph.AddEdge(derivedEdgeID, factNodeID, distilled.EpisodeID,
"DERIVED_FROM", distilled.Namespace, 0.9)
}
}
}
// RecordCoOccurrence record recall 后的共访关系
func (agu *AutoGraphUpdater) RecordCoOccurrence(query, namespace string, resultIDs []string) {
// 在知识图谱中创建 CO_OCCURS 关系
for i := 0; i < len(resultIDs); i++ {
for j := i + 1; j < len(resultIDs); j++ {
edgeID := fmt.Sprintf("co_%s_%s_%s", resultIDs[i], resultIDs[j], query[:minz(len(query), 20)])
agu.graph.AddEdge(edgeID, resultIDs[i], resultIDs[j], "CO_OCCURS", namespace, 1.0)
}
}
}
// ─── 辅助 ─────────────────────────────────────────────
type DistillInput struct {
EpisodeID string
Content string
Facts []string
Decisions []string
Entities []string
Namespace string
}
func entityID(name string) string {
// 保留 Unicode 字母、数字、下划线、中横线、空格(转下划线)
clean := strings.Map(func(r rune) rune {
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '_' || r == '-' || r == ' ' {
return r
}
// 保留 Unicode 字母(如中文)
if unicode.IsLetter(r) {
return r
}
return '_' // 特殊字符→下划线
}, strings.ToLower(strings.TrimSpace(name)))
// 空格转下划线
clean = strings.ReplaceAll(clean, " ", "_")
// 合并连续下划线
for strings.Contains(clean, "__") {
clean = strings.ReplaceAll(clean, "__", "_")
}
return "n_" + strings.Trim(clean, "_")
}
// cleanEntityName 清洗实体名用于展示(保留 Unicode 字符)
func cleanEntityName(raw string) string {
clean := strings.Map(func(r rune) rune {
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == ' ' || r == '-' || r == '_' {
return r
}
// 保留 Unicode 字母(中文、韩文、日文等)
if unicode.IsLetter(r) || unicode.IsDigit(r) {
return r
}
return ' '
}, strings.TrimSpace(raw))
clean = strings.Join(strings.Fields(clean), " ")
if len(clean) > 80 {
clean = clean[:77] + "..."
}
if clean == "" {
clean = "unknown"
}
// 含凭证形状 → 返回空串,调用方 skip(2026-09-10 P0)
if redact.ContainsSecret(clean) {
return ""
}
return clean
}
func detectNodeType(name string) string {
if strings.Contains(strings.ToLower(name), "docker") || strings.Contains(strings.ToLower(name), "nginx") {
return "software"
}
if strings.Contains(name, "牧尘") {
return "person"
}
return "concept"
}
func inferRelation(a, b, content string) string {
contentLower := strings.ToLower(content)
if strings.Contains(contentLower, "使用") || strings.Contains(contentLower, "used_by") || strings.Contains(contentLower, "用") {
return "uses"
}
if strings.Contains(contentLower, "配置") || strings.Contains(contentLower, "config") {
return "configures"
}
return "related_to"
}
func conflictPossible(a, b, fact string) bool {
return strings.Contains(strings.ToLower(fact), "not") ||
strings.Contains(strings.ToLower(fact), "不") ||
strings.Contains(strings.ToLower(fact), "false")
}
func extractEntitiesFromText(text string) []string {
words := strings.Fields(text)
var entities []string
for _, w := range words {
if len(w) > 1 && (w[0] >= 'A' && w[0] <= 'Z') {
if redact.ContainsSecret(w) {
continue // 2026-09-10 P0:凭证形状的 token 不当实体
}
entities = append(entities, w)
}
}
return entities
}
func minz(a, b int) int {
if a < b {
return a
}
return b
}
func sqrtFloat(x float64) float64 {
if x <= 0 {
return 0
}
// Newton's method for sqrt
z := x / 2.0
for i := 0; i < 10; i++ {
z -= (z*z - x) / (2 * z)
}
if z < 0 {
return 0
}
return z
}