Files
小唯 7f7171ac14 feat(recall): 召回契约字段 + trace 回溯 + 生命周期/实体质量判据(工作树收口)
这批是 10-26~27 已在生产二进制(zhiyid-protectrails-20261027)里运行、
但一直留在工作树未提交的改动。收口原因:三件改造要开分支,工作树脏 =
分支基准与回滚点都不存在。

主要内容:
- api/routes/contract.go + trace.go:召回响应契约字段(trace_id/status/scope/
  continuation/channel)与 /api/v1/trace 回溯端点
- governance/entity_quality.go:实体质量闸
- storage/trace.go + recall.go/recall_write_buffer.go:召回写入缓冲与轨迹
- 测试:contract/recall_contract_fields/recall_lifecycle/stale_lifecycle/
  entity_quality/trace

同时修一个 flaky:recall_lifecycle_test 原本硬编码「今天 11:00 已过」,
凌晨跑就会把「已失效」fixture 当成仍有效。改成相对时间(过期=now-1h),
生命周期判据与运行时刻无关。修完 go test ./internal/api/routes ./internal/storage 全绿。
2026-10-28 02:09:19 +08:00

246 lines
16 KiB
Go
Raw Permalink 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.
// Package models 定义织忆 MemoryWeave 的核心数据模型。
package models
import "time"
// Time 是 time.Time 的安全版本,支持空字符串解析
type Time struct{ time.Time }
// UnmarshalJSON 实现 json.Unmarshaler:空字符串解析为当前时间(而非报错)
func (t *Time) UnmarshalJSON(data []byte) error {
s := string(data)
if s == `""` || s == `"0001-01-01T00:00:00Z"` {
t.Time = time.Time{}
return nil
}
// 去掉前后引号
if len(s) >= 2 && s[0] == '"' && s[len(s)-1] == '"' {
s = s[1 : len(s)-1]
}
if s == "" || s == "null" {
t.Time = time.Time{}
return nil
}
return t.Time.UnmarshalJSON(data)
}
// VersionRecord 记忆版本记录(溯源链中的单次修改)
type VersionRecord struct {
Version int `json:"version"`
Content string `json:"content"`
UpdatedBy string `json:"updated_by"`
Source string `json:"source"`
Trigger string `json:"trigger"`
Reason string `json:"reason"`
Timestamp time.Time `json:"timestamp"`
}
// MemoryRecord 织忆中的单条记忆(存储在 LanceDB memories 表中)。
// v3.8 完整 Schema — 23 字段,与设计文档一致。
type MemoryRecord struct {
ID string `json:"id"`
AgentID string `json:"agent_id"`
Namespace string `json:"namespace"`
Content string `json:"content"`
ContentMD5 string `json:"content_md5"` // content 的 MD5 前 12 字符,用于精确去重
Category string `json:"category"` // system_fact, user_pref, proj_context, tool_usage, code_snippet
Vector []float32 `json:"vector"` // bge-m3 1024维,L2归一化
Tier string `json:"tier"` // normal, core(core永不衰减)
Importance float64 `json:"importance"` // 档位重要性:写入侧决定(storage/importance_rule.go,t_789898bd:规则关恒 1.0;开则 core=0.9/wiki,llm_distill=0.7/legacy,unknown=0.4/recovery=0.3)。注意:排序用的「运行时 importance」另算(quality_fusion.computeImportance = recency × (1+log(1+recall_seen))),两者是不同量
QualityScore float64 `json:"quality_score"`
UsefulCount int `json:"useful_count"` // 被标记 useful 的次数
// GA-P0-1 (t_718d8707):not_useful_count 曾把两种语义混写——
// 用户人工点「没用」(feedback.go MarkNotUseful) 与 dedup/合并流程自动降权
// (core.go Dedup demote) 都写同一个字段。现拆分为 human_not_useful_count
// 与 dedup_downweight_count,两个写入点各写各的。not_useful_count 保留为
// 历史列(deprecated),新代码不再读它(见 AC#3)。
HumanNotUsefulCount int `json:"human_not_useful_count"` // 用户人工点「没用」的次数
DedupDownweightCount int `json:"dedup_downweight_count"` // dedup/合并流程自动降权的次数
// A10 (t_d618dc7c):把「人工有用」从 UsefulCount(人工+机器混写)拆出单独计数。
// 指针类型:nil = NULL(存量行/从未被人工点过),非 nil = 真实整数。
// 统计口径用时分母必须 WHERE human_useful_count IS NOT NULL(NULL≠0)。
// 只有人工 feedback(/api/v1/feedback/useful → IncrementUseful)会 ++,机器自评/
// 蒸馏质量路径走别的方法(IncrementDedupDownweight/IncrementHumanNotUseful/...)不写此列。
HumanUsefulCount *int `json:"human_useful_count"` // nil=NULL(从未被人工点过);非 nil=真实计数
NotUsefulCount int `json:"not_useful_count"` // [DEPRECATED] 历史混写列,勿再读
Version int `json:"version"` // 当前版本号
VersionHistory []VersionRecord `json:"version_history,omitempty"` // 完整修改链
Source string `json:"source"` // 来源:牧尘口头 / 配置解析 / Agent推断 / LLM蒸馏
VolatileFlag bool `json:"volatile_flag"` // 频繁变更标记(≥3次修正自动设置)
RecallCount int `json:"recall_count"`
// GA-P0-2 (t_c6d41ac6):拆分 recall_count 的两种语义(「出现在结果里」/「被验证使用」)。
// recall_count 曾把两种语义混写 —— 每次召回命中都 ++,被当成 V 值喂给衰减/遗忘逻辑,
// 造成「被召回 500+ 次所以永不遗忘」的虚高保命。现拆分为:
// RecallSeenCount 出现即 ++(只用于观测/排序去偏,不参与 V 值/衰减权重)
// RecallVerifiedCount有正反馈(IncrementUseful)或下游引用才 ++(唯一参与 V 值/衰减)
// RecallCount 保留为历史列(deprecated),冻结不再增长,仅向后兼容读取历史值(AC#3)。
RecallSeenCount int `json:"recall_seen_count"` // 出现在召回结果里即 ++(观测/排序去偏用)
RecallVerifiedCount int `json:"recall_verified_count"` // 有正反馈或下游引用才 ++(V 值/衰减唯一来源)
Freshness string `json:"freshness"` // fresh, stale, verified
// 2026-10-08 (t_7e3577c5):血缘字段。embedding_model=实际嵌入模型(bge-m3);
// script_version=写入脚本版本标识。写入方经 metadata 携带,server 蒸馏落库。
EmbeddingModel string `json:"embedding_model"`
ScriptVersion string `json:"script_version"`
// 2026-10-08 (Gap#2 来源加权):confidence=写入方显式声明的信任等级(0.4~1.0),
// 不从 source 反推(source 是「哪条管道进来」,confidence 是「内容可不可信」,两者正交)。
// 指针类型:nil ⇒ JSON null ⇒ Rust 写 NULL ⇒ 读路径 COALESCE→1.0(加权首日 no-op)。
// ConfidenceSource=authoritative(写入时声明) | estimated(事后回填猜测),用于日后定向纠偏。
Confidence *float64 `json:"confidence,omitempty"`
ConfidenceSource string `json:"confidence_source,omitempty"`
// 2026-10-11 (t_631ab13d):DB 原值直通通道。json:"-" 不参与任何 JSON 传输:
// Rust IPC Search 会把 QualityScore 融合成 0.4*importance+0.6*raw(排序用),
// 但 recall 响应需要展示 LanceDB 原始列值("响应值==库值"判据)。
// 只在进程内携带,不落库、不序列化。
RawQualityScore *float64 `json:"-"`
LastRecalledAt time.Time `json:"last_recalled_at"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
IsDeleted bool `json:"is_deleted"`
// GA-P0-3 (t_f785d7f2):删除原因枚举(merge_dup|contradiction|manual|retention|unknown)。
// is_deleted=true 不再「不可分辨」—— 坏记忆被删 与 合并/整理被删 现可分列。additive 列。
DeleteReason string `json:"delete_reason,omitempty"`
DependsOn []string `json:"depends_on,omitempty"` // 依赖的记忆 ID 列表
DerivedFrom string `json:"derived_from,omitempty"` // 蒸馏来源 episode ID
// 2026-10-13 (t_e9a4d18f P1) 证据链:一条蒸馏结论记录**全部**来源 episode ID(多证据)。
// DerivedFrom 保留为单亲兼容字段;SourceEvents 是 superset。ProofCount 由它派生
// (len(distinct),不单独存避免不同步)。存量行缺省 nil(无证据链)。
SourceEvents []string `json:"source_events,omitempty"`
// 2026-10-13 (t_e9a4d18f P1) 矛盾保留:被本条「取代」的旧记忆 ID 列表。
// 新证据到来时不静默覆盖旧条目——写 supersedes 保留历史(Hindsight 原则)。
// 反向语义:旧条目不删,标 fresh/被取代;本字段是「我取代了谁」。
// 具体写时四操作的判定逻辑由 t_3e98b65a(写时 ADD/UPDATE/NOOP/CONFLICT)落地,
// 本卡只加 schema 列 + 保留语义(不静默覆盖)。
Supersedes []string `json:"supersedes,omitempty"`
// 2026-10-14 (t_3e98b65a):被取代方标记 —— 本记忆被哪些新记忆取代(反向指针)。
// 与 Supersedes 对称:新记忆.Supersedes=[旧ID],旧记忆.SupersededBy=[新ID]。
// 写时 UPDATE 判定时在旧记忆上写本列;存量行缺省 nil(无取代方)。
SupersededBy []string `json:"superseded_by,omitempty"`
// 2026-10-14 (t_3ada332b) bi-temporal 有效期(Zep/Graphiti 血统,遗忘研究方案C「长期正确性」):
// 时间敏感事实用【有效区间】而非删除。双时间线:episode T'(CreatedAt,何时说的)+ 语义 T(本区间,事实有效范围)。
// ValidFrom 生效起点(RFC3339;空 = 永久有效)
// ValidTo 失效终点(RFC3339;空 = 永久有效,永不失效)
// Provenance 来源类型枚举:user|inferred|import —— 新语句不自动覆盖旧的(来源权威性)。
// 读路径降权判据:valid_to < now 的事实不入 top-k 但可查(non-lossy,不删,历史可追溯)。
// 开关默认关:ZHIYI_BITEMPORAL=0 ⇒ 行为零变化。存量行三列缺省空串/空(等同永久有效)。
ValidFrom string `json:"valid_from,omitempty"`
ValidTo string `json:"valid_to,omitempty"`
Provenance string `json:"provenance,omitempty"`
}
// HitEvent 真实 outcome 的 append-only 事件(GA-P0-4 t_bb10e8bc)。
// 与计数列(useful_count / human_not_useful_count 等)不同:这是「按时间戳追加」
// 的事件日志,**不覆盖式累加** —— 每次真实 outcome 追加一行,带 created_at 时间戳,
// 便于 P2 自适应阈值按周窗口聚合(WHERE created_at > 本周起点)。语义定义见
// internal/storage/hit_event.go(什么算 hits+ / hits− / 什么不算)。
type HitEvent struct {
ID int64 `json:"id"`
MemoryID string `json:"memory_id"`
Outcome string `json:"outcome"` // pos | neg(HitOutcome 枚举)
Reason string `json:"reason"` // HitReason 枚举:human_feedback|contradiction|replacement|downstream_use
Source string `json:"source,omitempty"` // 记录方标识(如端点名)
CreatedAt time.Time `json:"created_at"`
}
// EpisodeRecord 原始对话/任务日志(存储在 LanceDB episodes 表中)。
type EpisodeRecord struct {
ID string `json:"id"`
AgentID string `json:"agent_id"`
Namespace string `json:"namespace"`
Content string `json:"content"`
Category string `json:"category"`
CreatedAt time.Time `json:"created_at"`
}
// TombstoneRecord 已删除/废弃记忆的墓碑记录。
type TombstoneRecord struct {
ID string `json:"id"`
OriginalID string `json:"original_id"`
Reason string `json:"reason"` // deprecated, merged, corrected, evicted
CreatedAt time.Time `json:"created_at"`
}
// RecallResult recall 接口返回的单条结果。
type RecallResult struct {
ID string `json:"id"`
Content string `json:"content"`
Category string `json:"category"`
Score float64 `json:"score"`
Timestamp string `json:"timestamp"`
// 2026-09-22 新增:全库召回(namespace="" 时)调用方无法分辨记忆来源域,
// 会把分身的私有记忆当成自己的用。带上来源便于调用方按需过滤/标注。
// omitempty:旧调用方无感;图谱扩展路径(graph_*.go)无 ns 概念,留空。
Namespace string `json:"namespace,omitempty"`
AgentID string `json:"agent_id,omitempty"`
Source string `json:"source,omitempty"`
// 2026-10-14 (t_2afae95e FTS 词面通道):本条是否由词面检索通道补入
// (rerank+MMR 之后尾部保证位)。true ⇒ 该内容命中了查询的词面特征
// (稀有 ASCII 词/标识符/数字/中文二元组,TF-IDF 分 0..1 在 QualityScore 里),
// 但向量相似度不足以进主候选池。调用方可据此展示「词面命中」来源标注。
// 门控关(ZHIYI_RECALL_FTS 默认)⇒ 恒 false 不输出(omitempty)。
FtsBoosted bool `json:"fts_boosted,omitempty"`
// 2026-10-08 (Gap#2):把信任等级直通给调用方。此前加列但不动本结构 ⇒
// confidence 对排序/调用方零影响(「字段加了没接线」的经典静默 no-op)。
// Confidence=nil 表示该条未声明(存量),调用方按 1.0 处理。
Confidence *float64 `json:"confidence,omitempty"`
ConfidenceSource string `json:"confidence_source,omitempty"`
// 2026-10-11 (t_631ab13d):把库里的 quality_score / v_value 直通给调用方。
// 此前 RecallResult 缺这两个字段 ⇒ JSON 序列化不带出 ⇒ 插件 `r.get("quality_score", 0)`
// 恒得默认 0("显示 0"),与库里 74.88% 记忆有真实值矛盾。排序不受影响(排序用内存
// candidates[i].QualityScore=库值,见 recall.go),本字段仅补"响应值==库值"的显示缺口。
// quality_score 恒输出(含 0);v_value 为 VValueProvider 提供,未注入时 0。
QualityScore float64 `json:"quality_score"`
// QualityScoreReliable:上面的 quality_score 是否可信。
// 2026-10-12:存量 54.2% 的 quality_score 不可信(0=未打分 / 0.755=历史常量 bug),
// 该值原样返回供审计,但**不应被当作真实质量判断**。调用方须看本字段。
QualityScoreReliable bool `json:"quality_score_reliable"`
VValue float64 `json:"v_value"`
// 2026-10-13 时间维检索(t_e9a4d18f P0):该条目是否可能过期。
// 仅当 stale 标记开启(ZHIYI_STALE_AFTER_HOURS>0)且 updated_at 超期时为 true;
// 默认关闭 ⇒ 恒 false 且 omitempty 不输出 ⇒ 行为零变化(向后兼容)。
// 2026-10-26(t_contract_p0):默认阈值改为 720h(30 天)——**只做展示标记,
// 不参与排序**(排序侧的有效期判据走 valid_to,见 ValidTo);环境变量仍可覆盖/关闭。
Stale bool `json:"stale,omitempty"`
// 2026-10-26(t_trace_p0):本条结果的来源通道(vector|fts|graph|shared|wiki|
// standing|pattern|peer)。此前「为什么被召回」不可答,调参只能盲修(CS249r Ch14)。
Channel string `json:"channel,omitempty"`
// 2026-10-26(P1 supersede 读侧暴露):版本与取代关系。
// 写入侧一直有 supersedes / superseded_by / valid_from / valid_to / version,
// 但 RecallResult 不带出 ⇒ 读侧永远看不见「这条已被谁取代 / 是否过期」。
// 存量行零值(Version=0=未记录版本),omitempty 保持旧响应兼容。
Version int `json:"generation,omitempty"` // 记忆版本号(DB version 列,语义=第几代)
ValidFrom string `json:"valid_from,omitempty"` // 语义有效期起点(RFC3339,空=永久)
ValidTo string `json:"valid_to,omitempty"` // 语义有效期终点(空=永久)
Supersedes []string `json:"supersedes,omitempty"` // 我取代了谁
SupersededBy []string `json:"superseded_by,omitempty"` // 我被谁取代(反向指针)
// Superseded 便捷布尔:SupersededBy 非空 ⇒ 已有更新版本存在(读侧一个字段可判)。
Superseded bool `json:"superseded,omitempty"`
// A10 (t_d618dc7c):把「人工有用」单独计数直通给调用方。此前 RecallResult 缺它 ⇒
// 插件/调用方读不到(t_4c810e02「加列不接 IPC=静默 no-op」同款坑)。
// nil=该条从未被人工点过(库里 NULL);非 nil=真实人工 useful 次数(NULL≠0)。
// 仅观测口径,不进排序(AC#6 排序零变化)。
HumanUsefulCount *int `json:"human_useful_count"`
}
// RerankResult rerank 重排后的单条结果。
type RerankResult struct {
Index int `json:"index"`
Score float64 `json:"score"`
Text string `json:"text"`
}
// GraphBFSResult BFS 图谱扩展结果(含汇总语句)
type GraphBFSResult struct {
ExpandedRelations []ExpandedRelation `json:"expanded_relations"`
Summary string `json:"summary"`
}
// ExpandedRelation 单条扩展关系
type ExpandedRelation struct {
From string `json:"from"`
To string `json:"to"`
Relation string `json:"relation"`
Hops int `json:"hops"`
Weight float64 `json:"weight"`
Score float64 `json:"score"`
}