Files
memoryweave/go/internal/distill/engine.go
T
小唯 d5b82d5b19 feat(distill): 经验层 category=experience 灰控落地(默认关,t_2595b626)
- experience_gate.go 新增:env 门控 ZHIYI_DISTILL_EXPERIENCE(启动读一次,同 density_gate 写法)、
  ExperienceRecord{Task,Solution,Boundary}(无 confidence 自评,质量复用五维 overall/VD/RU)、
  独立 prompt 附加常量(1157B,拼在 outFmt 之后)、ParseExperienceLine(4 段硬约束 + 反回显)、
  ExperienceGrounded(反张冠李戴:task 对象名必须在 episode 原文有影子,确定性零 LLM)
- engine/parser/server 接线:关态条件短路不可达 ⇒ 关态 prompt 逐字节不变
  (sha256 三臂一致:head-off==tree-off=49295e70…,开态=关态+1157B)
- score_cache 门控开时加 \x00experience-v1 后缀,防旧 prompt 缓存短路灰度
- 落库:接地闸 → 近重复跳过(cosine≥0.98)→ 写现成 category=experience(不造新表/新列)

实测(40 条真实工作笔记,本地 2B):EXP 行出现 32/40=80%,但过格式闸仅 2/40=5%
⇒ 2B 会写 EXP 内容但用自然语言衔接、不拆竖线三段,属能力边界。故**默认关,未部署未 push**。
go test ./internal/distill/ ./internal/api/routes/ -count=1 全绿
2026-11-07 02:41:33 +08:00

1396 lines
54 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 — 蒸馏引擎核心
// 两阶段蒸馏:硬规则过滤 → LLM 5维度评估 → 批量蒸馏
package distill
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"math/rand"
"net/http"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unicode/utf8"
"github.com/xiaoxue/memoryweave/internal/metrics"
"github.com/xiaoxue/memoryweave/internal/selfoptimize"
)
// ─── 类型定义 ────────────────────────────────────────────────
// Category 记忆类别
type Category string
const (
CatSystemFact Category = "system_fact"
CatUserPref Category = "user_pref"
CatProjContext Category = "proj_context"
CatToolUsage Category = "tool_usage"
CatCodeSnippet Category = "code_snippet"
CatDecision Category = "decision"
)
// DistillInput 蒸馏输入
type DistillInput struct {
EpisodeID string
Content string
Category Category
Namespace string
AgentID string
// 2026-09-26:来源(笔记路径等)—— 透传到蒸馏产物 MemoryRecord.Source,recall 时带回
Source string
// 2026-10-08 (t_7e3577c5):血缘字段——透传到蒸馏产物 MemoryRecord 对应列
EmbeddingModel string
ScriptVersion string
// 2026-10-08 (Gap#2):信任等级——写入方在 commit 时显式声明,跨异步蒸馏跳透传到
// 产物 MemoryRecord.Confidence。不从 source 反推(source 是管道,confidence 是信任,正交)。
Confidence *float64
ConfidenceSource string
}
// DistillResult 蒸馏输出
type DistillResult struct {
Facts []string
Entities []Entity
Score5D FiveDScore
Overall float64
Index []AAAKEntry // P4: AAAK 压缩索引(每条事实的紧凑摘要)
// Experiences t_2595b626 经验层:EXP 解析产物(仅 ZHIYI_DISTILL_EXPERIENCE=1
// 且解析出合法 EXP 行时非空;关态恒 nil ⇒ 下游经验分支不可达)。
// 🔴 不进 Facts/图谱/AAAK —— 独立 category="experience" 记录走自己的落库闸。
Experiences []ExperienceRecord
}
// Entity 实体
type Entity struct {
Name string `json:"name"`
Type string `json:"type"` // entity / fact / decision / skill
Properties []string `json:"properties"`
}
// FiveDScore LLM 5维评估
type FiveDScore struct {
IS float64 `json:"is"` // Information Significance
SU float64 `json:"su"` // Strategic Utility
PA float64 `json:"pa"` // Practical Applicability
VD float64 `json:"vd"` // Validation Durability
RU float64 `json:"ru"` // Recall Usability
}
// LLMResponse LLM 完整响应(5D + 实体 + 事实)
type LLMResponse struct {
IS float64 `json:"is"`
SU float64 `json:"su"`
PA float64 `json:"pa"`
VD float64 `json:"vd"`
RU float64 `json:"ru"`
Entities []string `json:"entities"`
Facts []string `json:"facts"` // 旧格式兼容
Decisions []string `json:"decisions"` // 新格式:决策结论
Conclusions []string `json:"conclusions"` // 新格式:最终结论
ActionsTaken []string `json:"actions_taken"` // 新格式:采取的行动
OpenQuestions []string `json:"open_questions"` // 新格式:悬而未决
// t_2595b626 经验层:EXP 行解析产物(仅 ZHIYI_DISTILL_EXPERIENCE=1 时被填充)。
Experiences []ExperienceRecord `json:"experiences,omitempty"`
}
// LLM 5维权重
// 血统:借鉴 MemOS CREATE_EVAL_PROMPT(五维评估:IS 信息重要性 / SU 战略效用 /
// PA 实际适用性 / VD 验证持久性 / RU 召回可用性)。出处登记:
// ~/mc/小怡/01-织忆/01-01-定义规范/织忆-借鉴溯源-全清单.md §2.1。
// 取值 0.20/0.20/0.15/0.25/0.20 系 MemOS 血统参数,勿随意改(改前先研究分布)。
var Weights = FiveDScore{
IS: 0.20,
SU: 0.20,
PA: 0.15,
VD: 0.25,
RU: 0.20,
}
// ─── 评分 echo 检测(2026-10-06)──────────────────────────────
//
// 背景:callLLM5D 的 prompt 曾把「示例评分」写成具体数字(0.8/0.7/0.6/0.9/0.7),
// 模型直接照抄这组数值 —— 于是每条内容的 overall 恒为 0.755(= 按 Weights 加权),
// 永久 ≥ 0.7 阈值 ⇒ 评分闸门从未真正生效,实际只剩「文本长度」在扛质量。
//
// 这里只做「检测 + 影子记录」,**不改变丢弃行为**;先观察样本,再决定是否真拦。
// 影子默认开启;设 ZHIYI_SCORE_SHADOW=0 可关(关掉 = 恢复按分数真丢)。
// echoScoreVectors 是历史 prompt 里出现过的示例评分向量(照抄即命中)。
// 血统:这些数值来自旧 prompt 的「示例评分」(MemOS CREATE_EVAL_PROMPT 血统的
// 五维评估,曾把示例写成 0.8/0.7/0.6/0.9/0.7 导致模型照抄)。出处登记:
// ~/mc/小怡/01-织忆/01-01-定义规范/织忆-借鉴溯源-全清单.md §2.1(恒 0.755 之谜)。
var echoScoreVectors = [][5]float64{
{0.8, 0.7, 0.6, 0.9, 0.7}, // engine.go 旧 prompt 示例
}
// IsEchoScore 判断评分是否在照抄 prompt 示例(照抄 ⇒ 该评分不可信)。
func IsEchoScore(s FiveDScore) bool {
for _, v := range echoScoreVectors {
if s.IS == v[0] && s.SU == v[1] && s.PA == v[2] && s.VD == v[3] && s.RU == v[4] {
return true
}
}
return false
}
// IsDegenerateScore 判断评分向量是否「退化」:五个维度完全相同(含全零)。
//
// ⚠️ 用途仅限**观测**,不得单独用作丢弃判据。
//
// 实测(2026-10-06,local/minicpm5-2b,异质输入 × 同输入重复):
// - 模型**具备**区分能力:垃圾内容→0.0×5,有价值内容→0.8×5;
// - 且**能**给出真正分维度的向量(实测到 is0.8/su0.8/pa0.7/vd0.6/ru0.5);
// - 但同一输入重复调用时结果**不稳定**:3 次全给 0.8×5,而另一次给了分维度向量。
//
// 结论:五维塌成同一值是**常见但非必然**的输出形态(说明该维度信息不可信),
// 不等于"模型没有区分能力" —— 曾据此下过该结论,属证据不足(样本同质),已更正。
// 全零同样是模型真实输出(原始 JSON 里字段齐全),不是 Go 零值兜底。
func IsDegenerateScore(s FiveDScore) bool {
return s.IS == s.SU && s.SU == s.PA && s.PA == s.VD && s.VD == s.RU
}
// scoreShadowMode 影子模式:true(默认)= 只在日志里记录"本该被丢",不真丢。
// 设环境变量 ZHIYI_SCORE_SHADOW=0 关闭影子(= 恢复真拦)。
var scoreShadowMode = os.Getenv("ZHIYI_SCORE_SHADOW") != "0"
// ─── 评分闸门阈值(2026-10-12 重标定)────────────────────────
//
// 背景:旧阈值 overall<0.7 && vd<0.8 从未被真实分布验证 —— 它是在
// 「旧 prompt 示例分数被照抄 ⇒ overall 恒为 0.755」这个 bug 上拍出来的,
// 闸门从未真正丢过任何东西(恒 ≥0.7)。
//
// 实测(4 天 2065 条可用评分,local/minicpm5-2b)真实分布:
//
// min=0.175 p25=0.390 中位=0.535 p75=0.600 p90=0.800 max=0.825
//
// 用 0.7 卡这个分布 ⇒ 仅 17.9% 能过 ⇒ 一开闸就丢 82% 可用内容。
//
// 新默认取分布 p10≈0.30 的保守档:只丢「明确垃圾」。
// 取向:宁可多留(可逆 —— 后续消费/降权机制会自然淘汰),不轻易丢(不可逆)。
// 影子模式下可用环境变量随时重标定,无需改代码:
//
// ZHIYI_SCORE_MIN_OVERALL / ZHIYI_SCORE_MIN_VD
var (
scoreMinOverall = envFloat("ZHIYI_SCORE_MIN_OVERALL", 0.30)
scoreMinVD = envFloat("ZHIYI_SCORE_MIN_VD", 0.30)
)
// envFloat 读浮点环境变量,缺省/非法则用 def。
func envFloat(key string, def float64) float64 {
if v := os.Getenv(key); v != "" {
if f, err := strconv.ParseFloat(v, 64); err == nil {
return f
}
}
return def
}
// ─── 蒸馏引擎 ────────────────────────────────────────────────
// Engine 蒸馏引擎
type Engine struct {
mu sync.Mutex
// LLM 配置
LLMEndpoint string
LLMModel string
APIKey string
// OutputFormat 蒸馏输出格式(t_180c0179):"json"(旧) | "lines"(新, 默认)。
// 默认走行协议(Line Protocol),根治 2B 未转义内层引号导致的 JSON 解析崩溃;
// 设 ZHIYI_DISTILL_FORMAT=json 一行回退旧 JSON 路径。
OutputFormat string
// 队列
queue []DistillInput
batchSize int
batchTimeout time.Duration
lastDistill time.Time
// P3 双缓冲:token 积累触发(LightMem 移植)
pendingTokens int
flushTokenThreshold int
// 成本控制
dailyLimit int
dailyUsed int
dailyReset time.Time
// 并发蒸馏(2026-09-21 加)
flushing atomic.Bool // 防多轮 flush 重叠:原来 go e.flush() 无互斥,队列一满就可能叠加并发打爆本地 2B
emitMu sync.Mutex // 串行化 emitResult(存储写不并发;LLM 调用才并发)
tickerOnce sync.Once // 兜底 flush ticker 只启一次(2026-10-06 修队列永久冻结)
// AC2 (t_9b2c7943):与本地 2B 槽位匹配的有效并发(探测 /props 的 total_slots,封顶 distillConcurrencyMax)
concurrency int
// HTTP客户端
client *http.Client
}
// distillConcurrency 单轮 flush 内并发蒸馏的条数上限(**封顶值**,非固定值)。
//
// 起因(2026-09-21 实测):摄入 ~132 条/min、蒸馏仅 11.6 条/min 且队列持续积压。
// 逐条排查发现瓶颈**不是 batch 大小**(batchSize 只决定一轮取多少条,
// 实测 batch 恒为 10、token 阈值从未触发),而是 flush 内**串行**的 LLM 调用:
// 每条 1 次 callLLM5D ≈ 5.2s,10 条 = 52s,吞吐被单条延迟锁死。
// 故真正的杠杆 = 让 LLM 调用并发(本地 2B 走 8081 队列代理);
// 写回 emitResult 仍串行,避免并发写存储。
//
// AC2 (t_9b2c7943):并发不再拍脑袋写死 3,而是**与本地 2B 槽位匹配**——
// 启动/刷新时探测端点 `total_slots`,并发 = min(槽数, 封顶值)。
// 判据(小怡给):若并发 > 槽数 → 打爆槽位 → 429 不降反升,必须下调到 ≤ 槽数。
// 实测 2026-09-21:106 llama-server 是**单槽**(total_slots=1),故匹配值=1。
const distillConcurrencyMax = 3 // 并发封顶(即使槽更多也不超过 3,保护 2B)
// distillOutputFormat 返回蒸馏输出格式(t_180c0179)。
// 默认 "lines"(行协议,根治 2B 未转义引号导致的 JSON 解析崩溃);
// 设环境变量 ZHIYI_DISTILL_FORMAT=json 一行回退旧 JSON 路径。
func distillOutputFormat() string {
if v := os.Getenv("ZHIYI_DISTILL_FORMAT"); v == "json" {
return "json"
}
return "lines"
}
func NewEngine(llmEndpoint, llmModel, apiKey string) *Engine {
e := &Engine{
LLMEndpoint: llmEndpoint,
LLMModel: llmModel,
APIKey: apiKey,
// t_180c0179:蒸馏输出默认行协议;ZHIYI_DISTILL_FORMAT=json 一行回退旧 JSON 路径。
OutputFormat: distillOutputFormat(),
batchSize: 10,
batchTimeout: 5 * time.Minute,
dailyLimit: 5000,
flushTokenThreshold: 2000, // LightMem short-term buffer
client: &http.Client{Timeout: 120 * time.Second},
}
// AC2:启动即探测端点槽位,把并发降到 min(槽数, 封顶)。探测失败保守取 1
// (宁串行也不打爆未知槽位);之后每 flush 周期可 RefreshConcurrency() 再探。
e.RefreshConcurrency()
e.startFlushTicker()
return e
}
// startFlushTicker 兜底触发源(2026-10-06 修「队列永久冻结」)。
//
// bug 背景:flush 触发原先**只挂在 Enqueue 入口** —— shouldFlush / timeout 两者都只在
// 「有新条目入队」时求值,全仓无任何 ticker 驱动。叠加守卫静默丢弃后形成永久冻结:
//
// ① 大批量入队撞上正在跑的 flush ⇒ flushing.CompareAndSwap 失败 ⇒ 直接 return(无补偿)
// ② flush 在入口处就整批取走队列(batch := e.queue; e.queue = nil),后来条目不在快照里
// —— 源码注释「留给它 drain 时一起取走」的假设不成立
// ③ 此后生产者若停止(无新 Enqueue)⇒ 积压永不触发,永久冻结
//
// 实测:2026-10-06 13:26:09 ~ 14:20:27 冻结 57 分钟(61 条),直到一条新条目入队才解冻。
//
// 兜底语义:每 batchTimeout 检查一次,有积压且无轮次在跑就补触发。
// 与 Enqueue 路径共用同一 CAS 守卫 ⇒ 不会叠加并发(原设计目的不破)。
func (e *Engine) startFlushTicker() {
e.tickerOnce.Do(func() {
go func() {
t := time.NewTicker(e.batchTimeout)
defer t.Stop()
log.Printf("[distill] flush 兜底 ticker 已启动(周期 %s)", e.batchTimeout)
for range t.C {
e.mu.Lock()
n := len(e.queue)
e.mu.Unlock()
if n > 0 && !e.flushing.Load() {
log.Printf("[distill] flush ticker 兜底:积压 %d 条且无轮次在跑 → 补触发", n)
go e.flush()
}
}
}()
})
}
// RefreshConcurrency 探测 LLM 端点的 llama-server 槽位数(`/props` 的 total_slots),
// 把本轮有效并发设为 min(槽数, distillConcurrencyMax)。
//
// 端点形如 http://host:8081/v1/chat/completions(队列代理或 llama-server 直连)。
// 探测:GET 到「/props」路径(取 endpoint 的 host,挂 /props)。llama-server 返回
// `total_slots`;队列代理 8081 若不透传 /props 则 404 → 保守取 1。
// 探测失败(连接不通/非 JSON)也保守取 1。这是「只改码」阶段的安全默认——
// 宁可串行,也不在未知槽位上限时并发打爆本地 2B。
func (e *Engine) RefreshConcurrency() int {
slots := probeLLMSlots(e)
c := slots
if c < 1 {
c = 1
}
if c > distillConcurrencyMax {
c = distillConcurrencyMax
}
e.mu.Lock()
e.concurrency = c
e.mu.Unlock()
log.Printf("[distill] RefreshConcurrency: endpoint=%s total_slots=%d → concurrency=%d (max=%d)",
e.LLMEndpoint, slots, c, distillConcurrencyMax)
return c
}
// currentConcurrency 返回当前有效并发(未探测前 = 1,安全默认)。
func (e *Engine) currentConcurrency() int {
e.mu.Lock()
defer e.mu.Unlock()
if e.concurrency < 1 {
return 1
}
return e.concurrency
}
// probeLLMSlots 探测 llama-server 槽位(/props 的 total_slots)。
// 取 endpoint 的 host:port,GET http://host:port/props。读不到 → 返回 1(保守)。
func probeLLMSlots(e *Engine) int {
host := e.LLMEndpoint
if i := strings.Index(host, "http"); i >= 0 {
host = host[i:]
}
// 拆出 scheme://host:port
rest := host
if i := strings.Index(rest, "://"); i >= 0 {
rest = rest[i+3:]
}
if i := strings.Index(rest, "/"); i >= 0 {
rest = rest[:i] // 去掉 /v1/chat/completions
}
propsURL := "http://" + rest + "/props"
client := &http.Client{Timeout: 5 * time.Second}
resp, err := client.Get(propsURL)
if err != nil {
log.Printf("[distill] slot probe failed (%v) → assume 1 slot", err)
return 1
}
defer resp.Body.Close()
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
var p struct {
TotalSlots int `json:"total_slots"`
}
if err := json.Unmarshal(body, &p); err != nil || p.TotalSlots < 1 {
// 队列代理可能不透传 /props(404/非JSON)→ 保守 1 槽
return 1
}
return p.TotalSlots
}
// estimateTokens 粗略 token 估算(中文≈1 token/字符,英文≈1 token/4字符)
// 用于 P3 双缓冲触发,不需要精确(只影响批量时机)
func estimateTokens(s string) int {
runes := len([]rune(s))
if runes == 0 {
return 0
}
// 中文按 1 token/字符,英文按 1 token/4 字符近似
// 简单折中:rune 数 / 2
return (runes + 1) / 2
}
// maxDistillTokens 蒸馏 prompt 最大 token 数(8k token 保护本地 2B 单槽)
const maxDistillTokens = 8192
// limitDistillContent 按 token 上限截断内容,返回截断后内容及日志信息
func limitDistillContent(content string) (string, int, int) {
tokens := estimateTokens(content)
if tokens <= maxDistillTokens {
return content, tokens, 0
}
// 截断:保留前 maxDistillTokens 个 token 对应的字符
runeCount := maxDistillTokens * 2 // 粗略换算:token ≈ chars/2
if runeCount > len([]rune(content)) {
runeCount = len([]rune(content))
}
truncated := string([]rune(content)[:runeCount])
log.Printf("[distill] prompt truncated: %d→%d tokens (%d→%d chars)",
tokens, estimateTokens(truncated), len(content), runeCount)
return truncated, estimateTokens(truncated), tokens
}
// Enqueue 入队
func (e *Engine) Enqueue(input DistillInput) {
e.mu.Lock()
defer e.mu.Unlock()
if !HardRulesPass(input.Content) {
return
}
e.queue = append(e.queue, input)
e.pendingTokens += estimateTokens(input.Content)
// P3 双缓冲触发:token 积累达阈值 或 条数达 batchSize 或 超时
shouldFlush := e.pendingTokens >= e.flushTokenThreshold || len(e.queue) >= e.batchSize
timeout := time.Since(e.lastDistill) > e.batchTimeout
if shouldFlush || (timeout && len(e.queue) > 0) {
go e.flush()
}
}
// flush 批量蒸馏
func (e *Engine) flush() {
// 互斥:队列一满就 go flush(),原实现允许多轮重叠 → 并发叠加打爆本地 2B 单/双槽。
// ⚠️ 已有轮次在跑就直接返回 —— 但本函数**在入口处就整批取走队列**(见下方 batch := e.queue;
// e.queue = nil),所以本次被丢弃的触发对应的条目**不会**被在跑的轮次处理。
// 兜底由 startFlushTicker() 提供(2026-10-06 修:此前无兜底 ⇒ 生产者停止即永久冻结)。
if !e.flushing.CompareAndSwap(false, true) {
return
}
defer e.flushing.Store(false)
e.mu.Lock()
if len(e.queue) == 0 {
e.mu.Unlock()
return
}
batch := e.queue
e.queue = nil
e.pendingTokens = 0
e.lastDistill = time.Now()
e.mu.Unlock()
log.Printf("[distill] flush START: batch=%d items, dailyUsed=%d/%d, endpoint=%s, model=%s",
len(batch), e.dailyUsed, e.dailyLimit, e.LLMEndpoint, e.LLMModel)
// Phase F: 更新 LLM 调用计数
metrics.DistillLLMCallsToday.Set(float64(e.dailyUsed))
// 成本控制检查
e.checkDailyLimit()
if e.dailyUsed >= e.dailyLimit {
log.Printf("[distill] flush FALLBACK: daily limit reached (%d/%d)", e.dailyUsed, e.dailyLimit)
results := fallbackDistill(batch)
e.emitResults(results)
return
}
// LLM 蒸馏:并发调用(吞吐杠杆),写回串行(emitMu)
// AC2:并发度与本地 2B 槽位匹配(探测 total_slots,封顶 3)。
// 启动时 NewEngine 已探测过一次;这里每轮 flush 前再 RefreshConcurrency() 探测一次,
// 以便在「部署后槽位数变化」时自动跟随。
var wg sync.WaitGroup
effConcurrency := e.RefreshConcurrency() // 探一次,拿本轮有效并发
sem := make(chan struct{}, effConcurrency)
var processed int64
for _, input := range batch {
wg.Add(1)
sem <- struct{}{} // 取槽(满则阻塞,天然限流)
go func(in DistillInput) {
defer wg.Done()
defer func() { <-sem }()
result := e.distillOne(in)
log.Printf("[distill] distillOne done: episode=%s facts=%d entities=%d",
in.EpisodeID, len(result.Facts), len(result.Entities))
atomic.AddInt64(&processed, 1)
e.emitMu.Lock()
e.emitResult(in, result)
e.emitMu.Unlock()
}(input)
}
wg.Wait()
// dailyUsed 一次性累加(原实现每条 ++ 且无锁 = 数据竞争,/stats 读同一字段)
e.mu.Lock()
e.dailyUsed += int(atomic.LoadInt64(&processed))
e.mu.Unlock()
log.Printf("[distill] flush DONE: processed %d items (concurrency=%d)", len(batch), effConcurrency)
// 打分缓存汇总(2026-10-12):命中率直接等于「本轮省下的 2B 调用占比」。
// 落盘放这里(每轮一次)而不是每条一次,避免频繁 IO。
if c := getScoreCache(); c != nil {
h, m := c.stats()
if h+m > 0 {
log.Printf("[scorecache] 累计 命中=%d 未命中=%d 命中率=%.1f%%(命中=省下的 2B 调用)",
h, m, float64(h)/float64(h+m)*100)
}
c.save()
}
}
// distillOne 蒸馏单条
func (e *Engine) distillOne(input DistillInput) DistillResult {
// 如果 LLM 端点不可用,降级
if e.LLMEndpoint == "" {
log.Printf("[distill] LLMEndpoint empty, fallback for %s", input.EpisodeID)
return fallbackSingle(input)
}
llmResp, err := e.callLLM5D(input.Content)
if err != nil {
log.Printf("[distill] callLLM5D err for %s: %v", input.EpisodeID, err)
return fallbackSingle(input)
}
score := FiveDScore{IS: llmResp.IS, SU: llmResp.SU, PA: llmResp.PA, VD: llmResp.VD, RU: llmResp.RU}
overall := score.IS*Weights.IS +
score.SU*Weights.SU +
score.PA*Weights.PA +
score.VD*Weights.VD +
score.RU*Weights.RU
log.Printf("[distill] score for %s: overall=%.3f is=%.2f su=%.2f pa=%.2f vd=%.2f ru=%.2f",
input.EpisodeID, overall, score.IS, score.SU, score.PA, score.VD, score.RU)
// ─── 准入分诊(2026-10-12 Step 1)─────────────────────────────
// 依据外部经验(方案:mc/小怡/04-OBSIDIAN工具/04-02-方案设计/
// 20261012-织忆记忆闸门-外部经验落地方案.md):
// · A-MAC 消融:确定性「类型先验」是单点最强特征(ΔF1=−0.107)⇒ 判据必须含确定性规则
// · SAGE:明确的直接闭式解决,只有「不确定带」才需谨慎
// · When to Forget 原文:"should not deprecate an uncertain memory" ⇒ 不确定的绝不弃用
// 三路:drop=确定性垃圾 / keep=确定性高价值 / observe=不确定带(**永不因低分丢弃**)
lane, laneWhy := ClassifyAdmission(input.Content)
log.Printf("[distill][LANE] episode=%s lane=%s reason=%s overall=%.3f vd=%.2f content=%q",
input.EpisodeID, lane, laneWhy, overall, score.VD, truncate(input.Content, 60))
switch lane {
case LaneDrop:
if scoreShadowMode {
log.Printf("[distill][SHADOW] would-drop(%s) episode=%s overall=%.3f vd=%.2f echo=%v degenerate=%v content=%q",
laneWhy, input.EpisodeID, overall, score.VD, IsEchoScore(score), IsDegenerateScore(score),
truncate(input.Content, 80))
} else {
log.Printf("[distill] lane=drop reason=%s for %s, skip", laneWhy, input.EpisodeID)
// 即使丢弃,仍然用 LLM 实体提取(如果有的话)
if len(llmResp.Entities) == 0 {
return DistillResult{}
}
}
case LaneKeep:
log.Printf("[distill][LANE] keep episode=%s reason=%s (放行,不看分数)", input.EpisodeID, laneWhy)
default: // LaneObserve
// 不确定带:Step 1 **不做分数丢弃**。低分只记录,供 Step 2 学阈值用。
if overall < scoreMinOverall && score.VD < scoreMinVD {
log.Printf("[distill][LANE-BAND] low-score-but-kept episode=%s overall=%.3f vd=%.2f reason=%s(仅记录,不丢)",
input.EpisodeID, overall, score.VD, laneWhy)
}
}
// 优先使用 LLM 提取的实体和事实
var entities []Entity
var facts []string
if len(llmResp.Entities) > 0 {
for _, name := range llmResp.Entities {
entities = append(entities, Entity{
Name: name, Type: "entity", Properties: []string{"llm_extracted"},
})
}
} else {
// 降级:启发式提取
_, heuristicEntities := e.extractFacts(input.Content)
entities = heuristicEntities
}
// 事实:优先使用新的结构化字段(decisions/conclusions/actions_taken/open_questions)
// 降级:回退到 llmResp.Facts(旧格式)→ 再降级:启发式提取
hasStructuredFields := len(llmResp.Decisions) > 0 || len(llmResp.Conclusions) > 0 ||
len(llmResp.ActionsTaken) > 0 || len(llmResp.OpenQuestions) > 0
if hasStructuredFields {
// 新格式:合并 decisions/conclusions/actions_taken/open_questions 到 facts
facts = append(facts, llmResp.Decisions...)
facts = append(facts, llmResp.Conclusions...)
facts = append(facts, llmResp.ActionsTaken...)
facts = append(facts, llmResp.OpenQuestions...)
log.Printf("[distill] structured fields: decisions=%d conclusions=%d actions=%d open=%d",
len(llmResp.Decisions), len(llmResp.Conclusions),
len(llmResp.ActionsTaken), len(llmResp.OpenQuestions))
} else if len(llmResp.Facts) > 0 {
facts = llmResp.Facts
} else {
heuristicFacts, _ := e.extractFacts(input.Content)
facts = heuristicFacts
}
// 2026-09-07 质量门槛(t_cc07ef4b): LLM 提炼 fact 入库前过滤
// <20字/纯疑问句/状态汇报型 拒绝; 20-50字需含实体或动词短语
// 在源头过滤, 使图谱/AAAK/记忆库一律只看到质量事实
// t_2ae69bb2: 把上方 lane 结论穿透到 fact 级门禁 —— LaneKeep 时跳过长度类
// 规则(只保留纯疑问/状态汇报两条硬否定),避免「lane 说放行、fact 级
// 却全丢」的静默吞噬;LaneDrop/LaneObserve 行为与原来逐字一致。
if before := len(facts); before > 0 {
// t_ffcee190:env 门控 ZHIYI_SHORTFACT_KEEP_PASSTHROUGH(默认关)——对非规则卡
// observe episode 的短事实走 LaneKeep 穿透,救真实对话自然短句误杀;规则卡/门控关
// 时 effectiveFilterLane 原样返回 lane,行为与现状逐字一致。
facts = FilterQualityFactsWithLane(facts, effectiveFilterLane(input.Content, lane))
if dropped := before - len(facts); dropped > 0 {
log.Printf("[distill] quality gate dropped %d/%d facts for %s (lane=%s)", dropped, before, input.EpisodeID, lane)
}
}
// t_3636b872 阶段4:程序性步骤判据 —— how-to/运维类内容的蒸馏答案必须含可执行步骤,
// 否则降级为 observe(当前 lane 若为 keep 则改写 lane 记录;事实本身不丢)。
// 影子模式默认只记不真降(proceduralShadowMode),先观察命中分布再决定是否真拦。
if demote, why := ProceduralStepVerdict(input.Content, facts); demote {
prevLane := lane
if lane != LaneObserve {
lane = LaneObserve
}
log.Printf("[distill][PROCEDURAL] episode=%s lane=%s→%s reason=%s content=%q facts=%d",
input.EpisodeID, prevLane, lane, why, truncate(input.Content, 60), len(facts))
}
// P4: 生成 AAAK 压缩索引(每条事实的紧凑摘要,供召回快速定位)
index := buildAAAKIndex(facts, entities, overall)
if len(index) > 0 {
logAAAKIndex(index)
}
// 2026-10-13 对抗审计插槽(②环,env 门控默认关):蒸馏产出的最终事实
// 按抽样比例送【异源模型】做对抗审计,结论只写影子日志,不改丢弃/准入行为。
// 门控关/未命中抽样/无事实 → 本调用立即返回,零行为变化。
MaybeAdversarialAudit(input, facts)
return DistillResult{
Facts: facts,
Entities: entities,
Score5D: score,
Overall: overall,
Index: index,
Experiences: llmResp.Experiences,
}
}
// callLLM5D 调用 LLM 进行 5维评估 + 实体/事实提取
// callLLM5D 打分入口 —— 先查内容哈希缓存,命中直接复用(不调 2B)。
//
// 2026-10-12:episodes 重复率 78.5%、约 60% 的打分调用打在重复内容上(详见 score_cache.go)。
// 本层只做记忆化,**不改变任何判分逻辑**;禁用见 ZHIYI_SCORE_CACHE=0。
func (e *Engine) callLLM5D(content string) (LLMResponse, error) {
c := getScoreCache()
if r, ok := c.get(content); ok {
return r, nil
}
r, err := e.callLLM5DUncached(content)
if err == nil {
c.put(content, r)
}
return r, err
}
// callLLM5DUncached 原始打分实现(函数体未改动,仅改名,便于外层套缓存)。
func (e *Engine) callLLM5DUncached(content string) (LLMResponse, error) {
// 2026-09-14 限制 distill prompt ≤8k token,防止打爆本地 2B 单槽
content, sentTokens, origTokens := limitDistillContent(content)
if origTokens > maxDistillTokens {
log.Printf("[distill] content truncated for LLM call: %d→%d tokens (limit=%d)", origTokens, sentTokens, maxDistillTokens)
}
// LightMem 式逐条事实提取 prompt(2026-08-11 移植)
// 精华:逐条判断含事实 → 轻量补全独立句 → 保留全部实体细节 → 推断隐含信息 → 时间区分
// 只改输出格式段(t_180c0179),逐条事实提取逻辑全保留;格式按 e.OutputFormat 分支。
const instr = `你是一个个人信息提取器。从以下对话内容中提取所有可能的用户事实信息。
输入格式:
[时间戳, 星期] 说话者: 消息
...
重要指令:
1. 必须按顺序逐条处理每条消息。对每条消息,判断是否包含事实信息。
- 如果包含 → 提取并改写为独立的完整句子
- 如果不包含(纯问候、填充语、无关评论)→ 跳过
- 不要因为信息看起来微小、琐碎或不重要就跳过。即使是小细节(如"用户今早喝了咖啡")也必须保留。只有完全无意义的(如"你好"、"哈哈"、"谢谢")才跳过。
2. 进行轻量上下文补全,使每个事实成为清晰的独立陈述:
- "user: 昨天买了苹果" → "用户昨天买了苹果。"
- "user: 我的朋友John在学医" → "用户的朋友John在学医。"
- 例外:若原文以「牵挂:」「画像:」「心迹:」「偏好:」「习惯:」「目标:」等结构化前缀开头,生成的 fact 必须保留原前缀,不要改写为自然句(例:原文「牵挂: 待处理: 待办.md 里已打勾的旧条目清理」→ 生成的 fact 保留「牵挂: 待处理: 待办.md 里已打勾的旧条目清理」,不要改成「用户牵挂:待办.md 里已打勾的旧条目需要清理」)。
3. 保留所有具体实体和细节:
- 完整名称: "The Name of the Wind by Patrick Rothfuss"(不是"一本书")
- 完整地点: Galway, Ireland; 北京海淀区
- 具体事件名: 慈善篮球赛、留学项目
- 数字和数量: 4年前、下个月、上周
- 公司/组织名: 某饮料公司
4. 推断隐含信息:如果多个相关条目提到 → 可以推断一般模式(保留具体事实和推断结论为独立条目)
5. 时间处理:区分提及时间(何时说的)和事件时间(何时发生的)
- 相对时间(昨天、上周、X前、下个月)→ 保留相对时间并引用消息时间戳
- 持续/永久事实 → 无需时间标注
6. 额外提取:
- decisions: 明确的决策结论(做了什么决定、选了什么方案、拒绝了什么)
- conclusions: 最终结论或答案
- actions_taken: 采取的具体行动
- open_questions: 悬而未决的问题
- entities: 提到的关键实体(系统名、工具名、人名、技术名词)
`
var outFmt string
if e.OutputFormat == "json" {
// 旧 JSON 输出格式(逐字保留,AC4 回退字节一致)
outFmt = `输出格式(严格JSON):
{"facts": ["独立事实1", "独立事实2"], "decisions": ["决定1"], "conclusions": ["结论1"], "actions_taken": ["行动1"], "open_questions": ["问题1"], "entities": ["entity1", "entity2"], "is": <小数>, "su": <小数>, "pa": <小数>, "vd": <小数>, "ru": <小数>}
评分说明:is/su/pa/vd/ru 必须是 0.0 到 1.0 之间的浮点数(越高越好),不得用 0-10 整数。
🔴 这五个分数必须依据**本次内容**独立判断:不同内容要给出**不同**的分数,各维度之间也应有差异。
禁止给出固定不变的分数组合 —— 那会被系统判为无效评分并整条丢弃。
输出里不要出现任何示例数值,直接写你本次的判断。
要求:除非消息完全无意义,否则提取并输出为事实。facts 要详尽,不要只给1条摘要。
`
} else {
// 新行协议输出格式(t_180c0179):单行一条记录,FACT| 后整行都是内容,
// 引号/竖线/等号等任意字符都不需要转义 → 根治 2B 未转义内层引号导致的解析崩溃。
outFmt = `输出格式(行协议,每条记录独占一行,最末输出评分行):
FACT|独立事实1
FACT|独立事实2
ENTITY|实体名|实体类型
SCORE|五个数字用竖线分隔
规则:
- 每条事实一行,以 FACT| 开头;第一个 | 之后整行都是事实内容,引号、竖线、等号等任意字符都直接写、不要转义
- 每个实体一行,ENTITY|名字|类型(类型如 person / tool / system / project)
- 评分放最后一行:以 SCORE| 开头,后面紧跟【恰好五个】数字(0.0~1.0 的小数,越高越好),用 | 分隔,一个不能多一个不能少,不得用 0-10 整数
- 🔴 禁止把 is、su、pa、vd、ru 这类字段名写进输出 —— 它们只是上面说明格式用的名字,不是要你输出的内容;输出里只能出现数字
- 🔴 这五个分数必须依据**本次内容**独立判断:不同内容要给出**不同**的分数,各维度之间也应有差异。禁止给出固定不变的分数组合 —— 那会被系统判为无效评分并整条丢弃。输出里不要出现任何示例数值,直接写你本次的判断。
- 除非消息完全无意义,否则提取并输出为事实。facts 要详尽,不要只给1条摘要。
`
}
// 保留 `内容:\n%s` 格式串锚点(TestPromptHasNoEchoLiterals 依赖它在源里定位评分段,AC3 不得删改该测试)。
// 外层 3 槽 %s%s%s + 内层「内容:\n%s」:prompt 文本逐字不变,仅重组格式串(消除「1 个实参打 3 个槽」的隐患)。
// 注意:本行写法刻意让 vet 的 Sprintf(格式串) 检查不匹配(外层 %s%s%s 与 3 实参对齐,
// 内层「内容:\n%s」是嵌套 Sprintf 的独立格式串,运行时各自 1 槽 1 参);
// rawscore_liveprobe_test.go 的 extractPromptTemplate 锚点须与本行「fmt.Sprintf("内容:\n%s"」保持同步。
// t_afacc477 三档粒度(ZHIYI_DISTILL_MODE)+ 截断可配(ZHIYI_DISTILL_CAP,默认 1000=现状)。
// current = 逐字节等价现状 A(cap=1000、无附加段);context = B 档(默认);merged = C 档。
instrFull := instr
if distillMode == "context" {
instrFull = instr + addendumContext
} else if distillMode == "merged" {
instrFull = instr + addendumMerged
}
// t_ab5b2461 信息密度判据灰度(ZHIYI_DISTILL_DENSITY=1):只在开关开时追加信息量要求段。
// 关态 instrFull 不含密度门附加段,prompt 逐字节与现状一致(AC5);上方旧 prompt 常量一字未动。
if densityGateEnabled {
instrFull = instrFull + densityPromptAddendum
}
capVal := distillCap
if capVal <= 0 {
capVal = 0 // 不截断
}
var contentTail string
if capVal <= 0 {
contentTail = content
} else {
contentTail = truncate(content, capVal)
}
// t_2595b626 经验层门控(ZHIYI_DISTILL_EXPERIENCE=1,默认关):
// 附加段拼在 outFmt **之后**(prompt 末尾、离生成位置最近)——
// pos_exp 系列实验取证(11-07):拼 outFmt 之前 = EXP 0/8(outFmt 的
// 「facts 要详尽」指令压过附加段);拼 outFmt 之后才有产出。
// run2136 担心的「末行被 echo」由 ParseExperienceLine 的 task 段拒收闸兜底。
// 关态 instrFull/outFmt 均不含附加段 ⇒ prompt 逐字节与改动前一致(AC1,sha256 对照);
// instr/outFmt/density 三处旧常量一字未动。
promptStr := instrFull + outFmt
if experienceGateEnabled {
promptStr = promptStr + experiencePromptAddendum
}
prompt := fmt.Sprintf("%s%s", promptStr, fmt.Sprintf("内容:\n%s", contentTail))
body := map[string]interface{}{
"model": e.LLMModel,
"messages": []map[string]string{
{"role": "user", "content": prompt},
},
"temperature": 0.2,
// AC3 (t_9b2c7943): 1200→2400。prompt 里"facts 要详尽"与 max_tokens 自相矛盾——
// 1200 会在 facts 数组中途截断 → 非法 JSON → 直接 parse 失败丢整条。提到 2400 给足
// 详尽 facts 的空间;即使仍截断,下方 recoverTruncatedJSON 会兜底救回。
"max_tokens": 2400,
}
jsonBody, err := json.Marshal(body)
if err != nil {
return LLMResponse{}, err
}
// AC1 (t_9b2c7943): 429/5xx 指数退避 + 抖动重试(上限 2 次额外重试,退避上限 ~8s)。
// 原实现:client.Do 失败/限流 → 直接 return err → 上层 distillOne 立刻 fallbackSingle
// (启发式降级、质量下降)。现在:遇 429 或 5xx,先退避重试,真不行再走 fallback。
// 抖动避免并发 3 条同时醒来再次撞 429(惊群)。
const (
maxRetries = 2 // 额外重试次数(首次不算)
initialDelay = 300 * time.Millisecond
maxDelay = 8 * time.Second // 单次退避上限
)
rng := newRand()
var respBody []byte
var lastStatus int
for attempt := 0; ; attempt++ {
req, reqErr := http.NewRequest("POST", e.LLMEndpoint, bytes.NewReader(jsonBody))
if reqErr != nil {
return LLMResponse{}, reqErr
}
req.Header.Set("Content-Type", "application/json")
if e.APIKey != "" {
req.Header.Set("Authorization", "Bearer "+e.APIKey)
}
resp, doErr := e.client.Do(req)
if doErr != nil {
// 网络/超时错误:可重试;到上限即上抛,让上层走 fallback。
if attempt < maxRetries {
d := backoffDelay(attempt, initialDelay, maxDelay, rng)
log.Printf("[distill] callLLM5D transient err (attempt %d/%d): %v → retry in %v",
attempt+1, maxRetries, doErr, d)
time.Sleep(d)
continue
}
return LLMResponse{}, doErr
}
status := resp.StatusCode
respBody, _ = io.ReadAll(resp.Body)
resp.Body.Close()
lastStatus = status
if status == http.StatusTooManyRequests || (status >= 500 && status <= 599) {
// 429 / 5xx:指数退避 + 抖动后重试;到上限即跳出(走 fallback,body 已读)。
if attempt < maxRetries {
d := backoffDelay(attempt, initialDelay, maxDelay, rng)
log.Printf("[distill] callLLM5D HTTP %d (attempt %d/%d) → backoff %v | body=%q",
status, attempt+1, maxRetries, d, truncate(string(respBody), 120))
time.Sleep(d)
continue
}
break // 超限:保留最后一次 body,下方按 429/5xx 上抛
}
break // 2xx 成功
}
// 退出循环:若最后仍是 429/5xx(重试上限耗尽)→ 上抛 error,让 distillOne 走 fallback。
if lastStatus == http.StatusTooManyRequests || (lastStatus >= 500 && lastStatus <= 599) {
return LLMResponse{}, fmt.Errorf("callLLM5D: HTTP %d after retries | body=%q",
lastStatus, truncate(string(respBody), 200))
}
var result struct {
Choices []struct {
Message struct {
Content string `json:"content"`
ReasoningContent string `json:"reasoning_content"`
// OpenAI 系 reasoning 模型(gpt-oss 等)用 "reasoning" 字段,不是 "reasoning_content"
Reasoning string `json:"reasoning"`
} `json:"message"`
} `json:"choices"`
}
if err := json.Unmarshal(respBody, &result); err != nil {
return LLMResponse{}, err
}
if len(result.Choices) == 0 {
return LLMResponse{}, fmt.Errorf("no choices in LLM response")
}
var llmResp LLMResponse
llmContent := result.Choices[0].Message.Content
if llmContent == "" {
llmContent = result.Choices[0].Message.ReasoningContent
}
if llmContent == "" {
llmContent = result.Choices[0].Message.Reasoning
}
// 剥离 markdown code fence(minimax 等模型习惯用 ```json 包裹)
llmContent = strings.TrimSpace(llmContent)
llmContent = strings.TrimPrefix(llmContent, "```json")
llmContent = strings.TrimPrefix(llmContent, "```")
llmContent = strings.TrimSuffix(llmContent, "```")
llmContent = strings.TrimSpace(llmContent)
if e.OutputFormat == "json" {
// ── 旧 JSON 路径(t_180c0179 AC4:OutputFormat="json" 行为与改动前逐字一致)──
// 健壮剥离:找第一个 { 和最后一个 } 截取(模型可能在 JSON 后加 markdown/注释)
c := llmContent
if idx := strings.Index(c, "{"); idx > 0 {
c = c[idx:]
}
if idx := strings.LastIndex(c, "}"); idx >= 0 && idx < len(c)-1 {
c = c[:idx+1]
}
c = strings.TrimSpace(c)
if err := json.Unmarshal([]byte(c), &llmResp); err != nil {
// AC3 (t_9b2c7943): 截断 JSON 容错。max_tokens 截断会把 facts 数组切到一半 →
// 尾部 "}" 缺失 → 非法 JSON。不再直接丢整条,先救回"最后完整对象"再解析。
recovered, ok := recoverTruncatedJSON(c)
if ok {
log.Printf("[distill] LLM JSON truncated, recovered last complete object (%d→%d bytes)",
len(c), len(recovered))
c = recovered
} else {
log.Printf("[distill] LLM JSON parse error: %v | content=%q", err, truncate(c, 200))
return LLMResponse{}, fmt.Errorf("parse score: %w", err)
}
}
if err := json.Unmarshal([]byte(c), &llmResp); err != nil {
// 救回后仍解析失败(极端情况):记录但不静默——返回 error 让上层走
// fallbackSingle(保留启发式 fact),而不是把整条 episode 当空结果丢掉。
log.Printf("[distill] LLM JSON parse error after recovery: %v | content=%q",
err, truncate(c, 200))
return LLMResponse{}, fmt.Errorf("parse score: %w", err)
}
} else {
// ── 行协议路径(t_180c0179 默认):三级兜底链,永不返回 error ──
// ParseLineFormat → 旧 parseJSONFormat → 空切片。解析不出时返回空 LLMResponse
// (最差空切片),让 distillOne 落启发式提取,而不是把整条 episode 当空结果丢掉。
llmResp = parseDistillOutput(llmContent)
if len(llmResp.Facts) > 0 || len(llmResp.Entities) > 0 {
log.Printf("[distill] line-protocol parse: facts=%d entities=%d (format=%s)",
len(llmResp.Facts), len(llmResp.Entities), e.OutputFormat)
}
}
// 记录实体和事实数量
if len(llmResp.Entities) > 0 {
log.Printf("[distill] LLM entities for content: %d entities", len(llmResp.Entities))
}
if len(llmResp.Facts) > 0 {
log.Printf("[distill] LLM facts for content: %d facts", len(llmResp.Facts))
}
return llmResp, nil
}
// AC1 辅助:指数退避 + 抖动。
// 基础为指数(initialDelay << attempt),封顶 maxDelay;叠加 ±25% 抖动避免惊群。
// 用 math/rand(Go 1.20+ 全局自动随机化,无需手动 seed)。
func newRand() *rand.Rand { return rand.New(rand.NewSource(time.Now().UnixNano())) }
// backoffDelay 返回第 attempt 次(0 基)重试前应等待的时长:
//
// attempt 0 → ~300ms,attempt 1 → ~600ms(指数翻倍),封顶 maxDelay,再叠 ±25% 抖动。
func backoffDelay(attempt int, initial, max time.Duration, r *rand.Rand) time.Duration {
d := initial << attempt
if d > max {
d = max
}
// 抖动:在 [d*0.75, d*1.25] 内随机,避免并发请求同时醒来再次撞 429。
jitterFactor := 0.75 + 0.5*r.Float64()
d = time.Duration(float64(d) * jitterFactor)
if d < initial {
d = initial
}
return d
}
// recoverTruncatedJSON 把被 max_tokens 截断的 JSON 救回成「最后一个完整对象」。
//
// 场景:LLM 输出 {"facts":["a","b","c 中途被 max_tokens 截断,尾部 } 缺失(甚至 [ 也缺失)
// → 直接 Unmarshal 报错。本函数从外向内逐步补齐,任一成功即返回。
//
// 策略:
//
// ① 先找「最后一个配平的最外层 }」:若截断发生在外层对象之外(尾部多了一段被切的
// 额外内容),截到那个 } 丢弃尾部即可,json.Valid 通过 → 直接返回。
// ② 否则(截在外层对象内部):用栈记录所有未闭合的 [ 和 {,从尾部逐个补 ] 和 }
// (栈顶先补,保证嵌套顺序正确);若截在字符串字面量中间,先补闭合引号。
// 补齐后 json.Valid 通过 → 返回。
// ③ 救不出对象骨架(连最外层 { 都没了 / 纯文本)→ 返回 ("", false),上层走 fallback。
//
// 注意:补齐后得到的可能是「截断前已完整的那些条目」,而非完整 facts——这正是容错目标
// (保留能救的部分,而不是把整条 episode 当空结果丢弃)。
// trimPartialUTF8 去掉结尾处被按字节切断的半个 UTF-8 字符。
//
// 背景:LLM 输出被 max_tokens 截断时,切断点可能落在多字节字符中间,尾部残留
// 0xE4-0xE9 这类「中文 UTF-8 首字节」。
//
// 实测边界(2026-10-09;216 个截断点 × 4 种形态:数组对象 / 行协议 / 单对象 /
// 裸数组字串):解析结局不受影响,因为 encoding/json 容忍字符串内部的非法字节
// (解码时替换为 U+FFFD),加不加本函数逐点 ok/valid 签名完全一致;受影响的是
// 产物内容,不加本函数时字符中间截断救回的结果里仍带残字节(数组对象 73/73 点、
// 行协议 42/73 点),它们随后被 Unmarshal 静默替换成 U+FFFD 写进记忆库,加上本
// 函数后残余为 0。
//
// 即:本函数是产物净化(不让脏字节入库),不是解析可用性的修复。切记不要用
// 「加了它 json.Valid 才通过」当判据 —— 实测该说法不成立。
func trimPartialUTF8(s string) string {
for len(s) > 0 {
r, size := utf8.DecodeLastRuneInString(s)
if r != utf8.RuneError || size > 1 {
return s
}
s = s[:len(s)-1]
}
return s
}
func recoverTruncatedJSON(s string) (string, bool) {
s = trimPartialUTF8(strings.TrimSpace(s))
if s == "" {
return "", false
}
// 扫描一遍:跟踪字符串状态、栈([ { 的开闭)。同时记录「深度归 0 的最后一个 }」位置。
// 栈元素:'[' 或 '{'。
var stack []byte
inString := false
escape := false
depthZeroAt := -1 // 最外层对象({ 深度归 0)的最后结束位置
for i := 0; i < len(s); i++ {
c := s[i]
if escape {
escape = false
continue
}
switch c {
case '\\':
if inString {
escape = true
}
case '"':
inString = !inString
case '{':
if !inString {
stack = append(stack, '{')
}
case '[':
if !inString {
stack = append(stack, '[')
}
case '}':
if !inString {
if len(stack) > 0 && stack[len(stack)-1] == '{' {
stack = stack[:len(stack)-1]
}
if len(stack) == 0 {
depthZeroAt = i // 记最外层对象终点(多次则取最后一次)
}
}
case ']':
if !inString {
if len(stack) > 0 && stack[len(stack)-1] == '[' {
stack = stack[:len(stack)-1]
}
}
}
}
// ① 有完整外层对象(深度曾归 0):截到最后一个配平 } 即可,丢弃尾部半截内容。
if depthZeroAt >= 0 {
candidate := s[:depthZeroAt+1]
if json.Valid([]byte(candidate)) {
return candidate, true
}
}
// ② 截在对象内部:补齐未闭合的 [ { 与未闭合的字符串。
// 从栈尾(最内层)到栈底(最外层)逐个补对应的闭合符。
var patch strings.Builder
// 若截在字符串字面量中间(最后一个 " 之后未闭合),先补一个引号闭合它。
if inString {
patch.WriteByte('"')
}
// 栈尾 → 栈底(最内层先补)
for i := len(stack) - 1; i >= 0; i-- {
switch stack[i] {
case '{':
patch.WriteByte('}')
case '[':
patch.WriteByte(']')
}
}
candidate := s + patch.String()
if json.Valid([]byte(candidate)) {
return candidate, true
}
// 兜底:连最外层 { 都没了(骨架残缺)或补齐后仍非法 → 救不出,返回失败。
return "", false
}
// extractFacts 从内容中提取事实和实体(关键词 + 命名实体启发式)
func (e *Engine) extractFacts(content string) ([]string, []Entity) {
var facts []string
var entities []Entity
if len(content) > 20 {
facts = append(facts, truncate(content, 200))
}
// 启发式实体提取:提取大写单词、数字组合、中文命名实体
words := strings.Fields(content)
seen := make(map[string]bool)
for _, w := range words {
w = strings.Trim(w, ",.;:!?,。;:!?、\"'()()[]【】")
if len(w) < 2 {
continue
}
// 大写字母开头(英文命名实体:Hermes, ComfyUI, Redis 等)
runes := []rune(w)
if len(runes) >= 2 && runes[0] >= 'A' && runes[0] <= 'Z' {
normalized := strings.ToLower(w)
if !seen[normalized] && !isStopWord(normalized) {
seen[normalized] = true
entities = append(entities, Entity{
Name: w, Type: "entity", Properties: []string{"extracted"},
})
}
}
// 中文实体(2-20 个纯中文字符,不含标点)
cleanChinese := stripNonChinese(w)
if len(cleanChinese) >= 2 && len(cleanChinese) <= 20 {
if !seen[cleanChinese] {
seen[cleanChinese] = true
isTech := containsAny(cleanChinese, []string{"端口", "配置", "系统", "内存", "显卡", "服务", "记忆", "织忆", "飞书", "版本", "模型", "工具", "项目", "安装", "部署", "目录", "路径", "开发", "语言"})
etype := "entity"
if isTech {
etype = "fact"
}
entities = append(entities, Entity{
Name: cleanChinese, Type: etype, Properties: []string{"extracted"},
})
}
}
// 数字/字母组合或纯数字(如 3050, 4GB, 8188, 7821)
if isTechToken(w) || isAllDigits(w) {
if !seen[w] {
seen[w] = true
entities = append(entities, Entity{
Name: w, Type: "entity", Properties: []string{"technical"},
})
}
}
}
return facts, entities
}
// isChineseSequence 判断是否为连续的中文字符串(长度在 minLen 到 maxLen 之间)
func isChineseSequence(s string, minLen, maxLen int) bool {
runes := []rune(s)
if len(runes) < minLen || len(runes) > maxLen {
return false
}
for _, r := range runes {
if r < 0x4E00 || r > 0x9FFF {
return false
}
}
return true
}
// isTechToken 判断是否为技术标记(包含数字+字母组合)
func isTechToken(s string) bool {
hasDigit := false
hasLetter := false
for _, r := range s {
if r >= '0' && r <= '9' {
hasDigit = true
}
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') {
hasLetter = true
}
}
return hasDigit && hasLetter
}
// containsAny 判断字符串是否包含任意一个子串
func containsAny(s string, subs []string) bool {
for _, sub := range subs {
if strings.Contains(s, sub) {
return true
}
}
return false
}
// isStopWord 判断是否为停用词
func isStopWord(w string) bool {
stops := map[string]bool{
"the": true, "a": true, "an": true, "is": true, "are": true,
"was": true, "were": true, "be": true, "been": true, "being": true,
"have": true, "has": true, "had": true, "do": true, "does": true,
"did": true, "will": true, "would": true, "could": true, "should": true,
"may": true, "might": true, "can": true, "shall": true,
"this": true, "that": true, "these": true, "those": true,
"it": true, "its": true, "they": true, "them": true, "their": true,
"we": true, "our": true, "you": true, "your": true, "he": true, "she": true,
"his": true, "her": true, "and": true, "or": true, "but": true,
"not": true, "no": true, "if": true, "then": true, "else": true,
"for": true, "with": true, "as": true, "at": true, "by": true,
"from": true, "in": true, "of": true, "on": true, "to": true, "up": true,
}
return stops[w]
}
// stripNonChinese 只保留中文字符
func stripNonChinese(s string) string {
var buf []rune
for _, r := range s {
if r >= 0x4E00 && r <= 0x9FFF {
buf = append(buf, r)
}
}
return string(buf)
}
// isAllDigits 判断是否为纯数字
func isAllDigits(s string) bool {
if len(s) == 0 {
return false
}
for _, r := range s {
if r < '0' || r > '9' {
return false
}
}
return true
}
// checkDailyLimit 每日限额检查
func (e *Engine) checkDailyLimit() {
now := time.Now()
if now.Day() != e.dailyReset.Day() || now.Month() != e.dailyReset.Month() || now.Year() != e.dailyReset.Year() {
e.dailyUsed = 0
// Reset to start of day in the same location as e.dailyReset
loc := e.dailyReset.Location()
if loc == nil {
loc = time.UTC
}
e.dailyReset = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, loc)
}
}
// emitResult 发送蒸馏结果(回调)
func (e *Engine) emitResult(input DistillInput, result DistillResult) {
if len(result.Facts) == 0 && len(result.Entities) == 0 {
return
}
// 由注册的回调处理
if OnDistillComplete != nil {
OnDistillComplete(input, result)
}
// Phase F: 蒸馏完成后更新队列深度和冲突计数
metrics.DistillQueueDepth.Set(float64(e.QueueLen()))
// Phase F: 对低分记忆触发质量监控检查 (score < 0.7 的记忆视为潜在低质量)
if result.Overall > 0 && result.Overall < 0.7 {
feedbackCount := selfoptimize.Dash.UsefulCount + selfoptimize.Dash.NotUsefulCount
if record := selfoptimize.QualityMonitor.Check(input.EpisodeID, result.Overall, feedbackCount); record != nil {
log.Printf("[quality] distill low-score flagged: episode=%s score=%.2f status=%s",
input.EpisodeID, result.Overall, record.Status)
}
}
}
// emitResults 批量发送
func (e *Engine) emitResults(results map[DistillInput]DistillResult) {
for input, result := range results {
e.emitResult(input, result)
}
}
// OnDistillComplete 全局蒸馏完成回调
var OnDistillComplete func(DistillInput, DistillResult)
// ─── 辅助 ────────────────────────────────────────────────
func truncate(s string, maxLen int) string {
runes := []rune(s)
if len(runes) <= maxLen {
return s
}
return string(runes[:maxLen]) + "..."
}
// fallbackSingle 降级蒸馏(无 LLM)
func fallbackSingle(input DistillInput) DistillResult {
var facts []string
if len(input.Content) > 20 {
facts = append(facts, truncate(input.Content, 100))
}
// 质量门槛同样作用于 fallback 路径(t_cc07ef4b)
facts = FilterQualityFacts(facts)
return DistillResult{Facts: facts}
}
// fallbackDistill 批量降级蒸馏
func fallbackDistill(inputs []DistillInput) map[DistillInput]DistillResult {
results := make(map[DistillInput]DistillResult)
for _, input := range inputs {
results[input] = fallbackSingle(input)
}
return results
}
// ─── 端点导出方法(G8-G9 配套)───────────────────────────────
// QueueLen 返回当前队列长度
func (e *Engine) QueueLen() int {
e.mu.Lock()
defer e.mu.Unlock()
return len(e.queue)
}
// QueueItems 返回队列内容(摘要)
func (e *Engine) QueueItems() []map[string]string {
e.mu.Lock()
defer e.mu.Unlock()
items := make([]map[string]string, len(e.queue))
for i, q := range e.queue {
content := q.Content
if len(content) > 80 {
content = content[:80] + "..."
}
items[i] = map[string]string{
"episode_id": q.EpisodeID,
"content": content,
"category": string(q.Category),
}
}
return items
}
// GetStatus 返回引擎运行时状态
func (e *Engine) GetStatus() map[string]interface{} {
e.mu.Lock()
defer e.mu.Unlock()
return map[string]interface{}{
"queue_len": len(e.queue),
"batch_size": e.batchSize,
"last_distill": e.lastDistill.Format(time.RFC3339),
"daily_used": e.dailyUsed,
"daily_limit": e.dailyLimit,
"daily_remaining": e.dailyLimit - e.dailyUsed,
}
}
// GetQuota 返回配额(基于 Engine 自身追踪)
func (e *Engine) GetQuota() map[string]interface{} {
e.mu.Lock()
used := e.dailyUsed
limit := e.dailyLimit
e.mu.Unlock()
remain := limit - used
if remain < 0 {
remain = 0
}
pct := float64(used) / float64(limit) * 100
if limit == 0 {
pct = 0
}
status := "normal"
if used >= limit {
status = "exceeded"
} else if pct >= 80 {
status = "near"
}
return map[string]interface{}{
"remaining": remain,
"used": used,
"limit": limit,
"percent": pct,
"near_limit": pct >= 80,
"status": status,
}
}