Merge branch 'feat/m45-extracttemporal-extractor-temporal-m' into dev
This commit is contained in:
commit
2702777950
16 files changed
+995
-34
No files matched your search
@@ -0,0 +1,18 @@
|
||||
-- 0027 的回滚:只撤结构(删列),**不改写任何一行的数据**。
|
||||
--
|
||||
-- 回滚的代价(如实登记):`temporal` 这一列的值全部丢失。它对本迁移之前写入的行
|
||||
-- 本来就恒为 `''`(未分型),因此丢的只是「本迁移之后提取器标出的时间性位」。
|
||||
--
|
||||
-- 真正需要说明的是**判定行为**:`retention_tier` / `expires_at` 是另两列,本回滚
|
||||
-- **刻意不动它们**。
|
||||
-- - 已被判成 temp 的行(其中一部分是 `temporal=one_off` 带来的)保持原状:读侧
|
||||
-- 时效闸与后台清扫都只认 `expires_at`(纯 SQL,不依赖本列),因此回滚后它们的
|
||||
-- 行为**逐字不变**,到期照旧消失、照旧被清扫;
|
||||
-- - 若回滚时顺手把那些行的 `expires_at` 清空,那是一次 schema 回滚**改数据**,
|
||||
-- 会把已经判定的临时记忆全部升回永久,同时还留在 `retention_tier='temp'` 上
|
||||
-- —— 那正是「temp ⇔ 非空 expires_at」这条不变量的反面。
|
||||
-- 要重判档位就重跑判定:列会以默认值 `''` 重建,历史行回到「未分型」。
|
||||
--
|
||||
-- SQLite 的 DROP COLUMN 要求该列不被索引/视图/触发器引用:本列没有索引(见 up),
|
||||
-- 因此无需先删索引(0026 的 down 因为带索引才要以 DROP INDEX 开头)。
|
||||
ALTER TABLE memory_items DROP COLUMN temporal;
|
||||
@@ -0,0 +1,43 @@
|
||||
-- 0027_memory_temporal:提取器产出侧的**时间性元数据位**(切片 M45)。
|
||||
--
|
||||
-- 为什么需要这一列(而不是再调一次词项阈值):M37 复审的量化结论是「defer 命中
|
||||
-- 2/500 = 0.4%」不是阈值太严,而是**判定链缺信息位** —— 真正卡住上游的是提取器的
|
||||
-- 改写:一次性事件被写成 30~80 字的第三人称长期陈述,规则闸只看落库正文,因此
|
||||
-- 看不见「这是今天的一次性事件」这一位。实测反证:把 N6 的时点词窗口从 12 放宽到
|
||||
-- 24 字,命中 2→14,多出的 11 条逐条都是**同一长期约定的重复陈述**(「一起晒太阳」
|
||||
-- 暂时搁置 ×5、「傍晚出门走十分钟…今天没走成明天补上」×6)—— 放宽阈值等于 7 天后
|
||||
-- 把约定本身删掉,违背 fail-safe。所以补的是信息位,不是阈值。
|
||||
--
|
||||
-- 为什么是**列**而不是新增一种 kind:`kind`(关于什么)、`scope`(谁的)、
|
||||
-- `retention_tier`(留多久)、本条 `temporal`(**说的是一次发生的事,还是反复/长期
|
||||
-- 成立的事**)是四根正交的轴。时间性是**提取器对原始对话的判断结果**,它必须能被
|
||||
-- 单独存下来(事后巡检「模型当时标了什么」、以及将来回填),塞进 kind 就丢了这条
|
||||
-- 观测线;靠提示词里的自然语言描述则违反 AGENTS §9「判据靠元数据,不靠提示词」。
|
||||
--
|
||||
-- 列值闭集(代码侧定义:internal/runtime/memory/temporal.go 的 TemporalKind):
|
||||
-- one_off 一次性事件(今天 / 这次 / 某一次)⇒ 判定为 temp + 非空 expires_at
|
||||
-- recurring 反复发生的规律(每天 / 每周 / 每次都…)⇒ long
|
||||
-- durable 长期成立的事实 / 偏好 / 约定 / 称呼 / 身份 ⇒ long
|
||||
-- unknown 模型拿不准或没给出合法值 ⇒ **没有结论**,交给既有 N1~N7 规则判
|
||||
-- '' 尚未分型:本迁移之前的历史行,以及非提取器的写入路径(默认值)
|
||||
--
|
||||
-- 🔴 默认值 `''` 而**不是** `unknown`:两者在判定上走同一条路(都落到旧规则),但
|
||||
-- 含义不同 —— `''` 是「没问过」,`unknown` 是「问过,模型拿不准」。把历史行写成
|
||||
-- `unknown` 会让「模型答了什么」这个观测面从第一行起就掺假。本迁移**刻意不回填**:
|
||||
-- 历史行没有对应的提取器输出,拿正文反推「它当时是不是一次性事件」正是本片要消灭
|
||||
-- 的那种猜测。
|
||||
--
|
||||
-- 幂等性:`ALTER TABLE ADD COLUMN` 在 SQLite 里**没有** IF NOT EXISTS 形式,因此本
|
||||
-- 迁移与 0019 / 0026 同一手法 —— 依赖启动顺序「先 MigrateUp、后 NewStore」
|
||||
-- (cmd/cyrene/wire.go):生产库里这一步先跑,随后 NewStore 的自举前滚
|
||||
-- (internal/runtime/memory/temporal_schema.go 的 ensureTemporalSchema)走到
|
||||
-- "duplicate column name" 是预期路径。列的形状必须与自举 DDL
|
||||
-- (internal/runtime/memory/store_schema.go)**逐字同形**,由
|
||||
-- internal/runtime/memory/temporal_migration_test.go 钉住。
|
||||
--
|
||||
-- 本列**不建索引**:目前没有任何按时间性位的读路径(它是写入时的判定输入 +
|
||||
-- 事后巡检的留痕列)。将来整理侧真要按它筛,再补索引不迟(两条路径一起加)。
|
||||
--
|
||||
-- 命名口径:表名复数(AGENTS §10 已登记例外)、列名与代码的 JSON 键同名
|
||||
-- (`temporal`),与 0026 的 `retention_tier` 同族。
|
||||
ALTER TABLE memory_items ADD COLUMN temporal TEXT NOT NULL DEFAULT '';
|
||||
@@ -103,6 +103,8 @@ const (
|
||||
//
|
||||
// 它**不读任何状态、不写任何东西、零模型调用**:入参只有正文,出参只有规则码,
|
||||
// 因此在写路径上是微秒级且可完全单测(design/03 §10.3 A 级的「零成本」要求)。
|
||||
// 🔴 时间性元数据位(temporal,迁移 0027)**不是**它的入参:r1 复审裁决 D 之后
|
||||
// 这一位只观测、不参与判定(见 retention.go 的 resolveRetention 头注与 temporal.go)。
|
||||
// 🔴 全仓**唯一**调用点是 `resolveRetention`(retention.go):任何地方再跑一遍
|
||||
// 就是「两套规则各判一遍」—— 那正是 M27 体检发现缺口(1082 次只判出 1 条)的成因,
|
||||
// retention_test.go 有一条源码级断言钉住这个唯一性。
|
||||
@@ -259,6 +261,9 @@ func judgeRetentionOneOff(text string) retentionRule {
|
||||
// ~0:`用户是上班族,需要上班(曾说明天要上班并感到不开心)`、`睡前会道晚安…
|
||||
// 并约好「明天中午见」` 这类「时点词只出现在引语/从句里」的长期事实,锚点
|
||||
// 不是那个时点,因此不许开火;而 `昨天用户发来…`、`用户近期在看…` 的锚点就是它。
|
||||
// 🆕 **M45 曾把这一条接到时间性元数据位上,r1 复审裁决 D 又撤掉了**(原因见
|
||||
// temporal.go 头注:位置放宽能翻的行逐条都是长期约定)。因此位置判据对**每一行**
|
||||
// 无条件生效,与 0027 之前逐字相同。
|
||||
//
|
||||
// **N7(进行中状态)** 是同一时效轴的第二形态:「正在/暂时/眼下」说的事情有始有终
|
||||
// (正在测通道、暂时搁置、正在慢慢想),安全阀与 N6 完全一致,并且**位置判据也一致**
|
||||
|
||||
@@ -29,6 +29,15 @@ import (
|
||||
//
|
||||
// 「允许返回 `[]`」是 Mem0 官方口径(design/23 §2:官方原话「Include examples
|
||||
// that should produce []」)—— 不写这一句,模型会为了「有产出」而硬凑。
|
||||
//
|
||||
// 🆕 2026-10-27(切片 M45):prompt 里追加**时间性位** `temporal`(四个枚举值)。
|
||||
// 它**不是**「又一段靠自然语言描述判据」的提示词加固:模型只负责**标注**一个值为
|
||||
// 四个枚举之一,落库是 `temporal` 列(迁移 0027)。
|
||||
//
|
||||
// 🔴 **这一位目前不参与判定**(r1 复审裁决 D):`resolveRetention` 不读它,判定的
|
||||
// 结论集与没有它逐字相同 —— 保留它只为积累「模型到底怎么标」的证据(temporal.go
|
||||
// 头注记着两次被生产重放否掉的接线方案与接线前必须看的那份分布)。因此这段 prompt
|
||||
// 的**唯一**作用是让观测面有数据;即便模型完全不听,判定的行为与今天一致。
|
||||
const extractSystemPrompt = `你是记忆提取器。从对话中提取**值得长期记住**的记忆项。
|
||||
|
||||
只保留这些(正向清单):
|
||||
@@ -49,18 +58,31 @@ const extractSystemPrompt = `你是记忆提取器。从对话中提取**值得
|
||||
**允许返回空数组 []**:一轮对话里没有值得长期记住的内容时,正确做法就是回
|
||||
[],不要为了凑数而提取。
|
||||
|
||||
每条还要标一个**时间性位** "temporal",只能取下面四个英文值之一:
|
||||
- "one_off":这条说的是**某一次**发生的事(今天 / 昨天 / 这次 / 某个具体日子),
|
||||
即使你已经把它写成「用户……」这样的陈述句;
|
||||
- "recurring":说的是**反复发生**的规律(每天 / 每周 / 每次都…);
|
||||
- "durable":说的是**长期成立**的事实 / 偏好 / 约定 / 称呼 / 身份;
|
||||
- "unknown":拿不准,或者上面三个都不贴切。
|
||||
|
||||
temporal 只许填这四个英文值之一(不要换成中文、不要自造新值);拿不准就填
|
||||
"unknown"。这个标记会被记录下来供以后核对用途,如实标注即可,不要为了省字省掉它。
|
||||
|
||||
只输出一个 JSON 数组,不要任何其他文字。每个元素形如:
|
||||
{"content":"记忆内容","scope":"user|persona|project","kind":"relationship|world_event","tags":["标签"],"confidence":0.9,"project_id":"可选项目id"}
|
||||
去噪去重:只保留值得长期记住的,忽略寒暄与临时信息。`
|
||||
{"content":"记忆内容","scope":"user|persona|project","kind":"relationship|world_event","temporal":"one_off|recurring|durable|unknown","tags":["标签"],"confidence":0.9,"project_id":"可选项目id"}
|
||||
去噪去重:只保留值得长期记住的,忽略寒暄与临时信息;确实发生过的**一次性事件**
|
||||
如果值得记,也照实提取,并把 temporal 标成 one_off。`
|
||||
|
||||
// llmCandidate 是提取器要求 LLM 输出的线上形状:每条候选
|
||||
// 记忆一个 JSON 对象。模型未给出合法值时,Scope/Kind 取提取器配置的
|
||||
// 默认值。不含 source_conversation:
|
||||
// 默认值;Temporal 则**一律归 unknown**(temporal.go 的 normalizeTemporal,
|
||||
// 绝不猜:猜成 one_off 的方向是把该留的记忆删掉)。不含 source_conversation:
|
||||
// 模型即使回填该键也会被忽略(结构化溯源只来自持久化层)。
|
||||
type llmCandidate struct {
|
||||
Content string `json:"content"`
|
||||
Scope string `json:"scope"`
|
||||
Kind string `json:"kind"`
|
||||
Temporal string `json:"temporal"`
|
||||
Tags []string `json:"tags"`
|
||||
Confidence float64 `json:"confidence"`
|
||||
ProjectID string `json:"project_id"`
|
||||
@@ -240,6 +262,10 @@ func (e *LLMExtractor) dedupeAndBuild(cands []llmCandidate) []MemoryItem {
|
||||
Content: content,
|
||||
Tags: c.Tags,
|
||||
Confidence: c.Confidence,
|
||||
// 时间性位(迁移 0027)在**产出侧**归一:模型只能选四个值之一,
|
||||
// 其余(空 / 非法 / 自造)一律归 unknown —— 解析失败绝不报错,
|
||||
// 也不拖累同批的其他候选(见 temporal.go 的 normalizeTemporal)。
|
||||
Temporal: normalizeTemporal(c.Temporal),
|
||||
}
|
||||
if !it.Scope.valid() || !it.Kind.valid() {
|
||||
continue
|
||||
|
||||
@@ -97,7 +97,14 @@ const (
|
||||
// 规则。**规则内容与阈值未改**(同一份 N1~N7),但**判据的作用范围变了**:
|
||||
// 档位与 `expires_at` 现在对**每一行**在同一笔 INSERT 里落下,且不再依赖同步闸
|
||||
// 是否开启 —— 同一对条目在 d3.3 与 d3.4 下的落库形态因此可能不同,按规矩升版。
|
||||
const IngestRuleVersion = "d3.4"
|
||||
// - `d3.5`(切片 M45)**记录 `temporal` 信号,但不参与判定**:提取器在产出侧多
|
||||
// 标了一维时间性位(`one_off` / `recurring` / `durable` / `unknown`,迁移 0027),
|
||||
// 随同一笔 INSERT 落库。**判定的结论集与 d3.4 逐字相同**(`resolveRetention`
|
||||
// 不读这一位,见 retention.go 头注:复审裁决 D —— 两次候选接线都被生产重放否掉)。
|
||||
// 那为什么仍升版?因为**留痕面变了**:同一对条目在 d3.4 与 d3.5 下虽然结论相同,
|
||||
// 但 d3.5 的库里多了「模型当时标了什么」这一维可供事后归因;不升版,新旧留痕会
|
||||
// 混在同一版本号下,将来接线时无法区分「接线前的结论」与「接线后的结论」。
|
||||
const IngestRuleVersion = "d3.5"
|
||||
|
||||
// 调优旋钮(ReviewConfig)与它们的默认值常量在 preinsert_config.go。
|
||||
|
||||
|
||||
@@ -19,7 +19,8 @@ import (
|
||||
// 2. 写进去的 `expires_at` 与读侧时效闸**同一套规范文本**
|
||||
// (定宽 30 字节 UTC —— 写错布局会让闸静默判错,本仓有历史事故);
|
||||
// 3. TTL 坏值(≤0)**绝不放行**:回落代码默认 7 天 + WARN;
|
||||
// 4. `IngestRuleVersion` 升到 `d3.4`(改判定规则必升版,否则新旧留痕无法区分);
|
||||
// 4. `IngestRuleVersion` 随判定变更升版(改判定规则必升版,否则新旧留痕无法区分;
|
||||
// 当前是 `d3.5`,M37 合入时是 `d3.4`);
|
||||
// 5. defer 是**软动作**:回滚 = 清空 `expires_at`,行与正文一字不动。
|
||||
|
||||
// readIngestExpiry 直读一行记忆的 `expires_at`(该列不在 Store.Get 的读侧面上:
|
||||
@@ -107,8 +108,8 @@ func TestIngestGateDeferWritesShortExpiresAt(t *testing.T) {
|
||||
if rev.Decision != IngestDefer || rev.Reason != retentionLowValueReason {
|
||||
t.Fatalf("闸留痕 = %+v, want decision=defer reason=%q", rev, retentionLowValueReason)
|
||||
}
|
||||
if rev.RuleVer != "d3.4" {
|
||||
t.Fatalf("闸留痕规则版本 = %q, want d3.4", rev.RuleVer)
|
||||
if rev.RuleVer != IngestRuleVersion {
|
||||
t.Fatalf("闸留痕规则版本 = %q, want %q(留痕版本必须与常量同源,不写死)", rev.RuleVer, IngestRuleVersion)
|
||||
}
|
||||
if s := r.Stats(); s.GateDeferred != 1 {
|
||||
t.Fatalf("闸计数 = %+v, want gate_deferred=1", s)
|
||||
@@ -268,16 +269,22 @@ func TestIngestGatePlanExpiresAtUsesSameLayoutAsTimeGate(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestIngestRuleVersionIsD34 钉住任务书验收点④:改判定规则必升版
|
||||
// TestIngestRuleVersionIsD35 钉住任务书验收点④:改判定规则必升版
|
||||
// (design/23 §18.4),否则新旧留痕无法区分。
|
||||
//
|
||||
// d3.4(切片 M37)把「判 defer」与「判 retention_tier=temp」合并成同一个判定,
|
||||
// 规则内容未改但判据的作用范围变了(每一行都在同一笔 INSERT 里落档位与有效期,
|
||||
// 且不再依赖同步闸是否开启),因此按规矩升版。
|
||||
func TestIngestRuleVersionIsD34(t *testing.T) {
|
||||
//
|
||||
// d3.5(切片 M45)**记录 `temporal` 信号,但不参与判定**:提取器产出侧多标了一维
|
||||
// 时间性位(迁移 0027),随同一笔 INSERT 落库;`resolveRetention` 不读它,因此
|
||||
// 判定的结论集与 d3.4 逐字相同。仍升版是因为**留痕面变了**(库里多了「模型当时标了
|
||||
// 什么」这一维),将来接线时要能区分「接线前/后」的结论 —— 理由见 preinsert.go
|
||||
// 的版本史。
|
||||
func TestIngestRuleVersionIsD35(t *testing.T) {
|
||||
t.Parallel()
|
||||
if IngestRuleVersion != "d3.4" {
|
||||
t.Fatalf("IngestRuleVersion = %q, want d3.4(档位与 defer 合并为同一判定)", IngestRuleVersion)
|
||||
if IngestRuleVersion != "d3.5" {
|
||||
t.Fatalf("IngestRuleVersion = %q, want d3.5(记录 temporal 信号,但不参与判定)", IngestRuleVersion)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -52,6 +52,41 @@ func migrateUp(t *testing.T, d *sql.DB) {
|
||||
}
|
||||
}
|
||||
|
||||
// migrateDownToBefore 把库回滚到 id **之前**(即 id 与它之后已应用的每条都撤掉)。
|
||||
//
|
||||
// 步数从 `schema_migrations` 账本现算,而不是写死一个常数:写死的口径每加一条
|
||||
// 迁移就要改一次(0026 加进来时本文件的 0025 用例的 `MigrateDown(2)`、0027 加进来时
|
||||
// 0026 用例的 `MigrateDown(1)` 都是这么被打红的)—— 而「回滚到某条之前」这个
|
||||
// 语义本身与后面还压着几条无关。
|
||||
func migrateDownToBefore(t *testing.T, d *sql.DB, id string) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
rows, err := d.QueryContext(ctx, `SELECT id FROM schema_migrations ORDER BY id`)
|
||||
if err != nil {
|
||||
t.Fatalf("list applied migrations: %v", err)
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
steps := 0
|
||||
for rows.Next() {
|
||||
var got string
|
||||
if err := rows.Scan(&got); err != nil {
|
||||
t.Fatalf("scan applied migration: %v", err)
|
||||
}
|
||||
if got >= id {
|
||||
steps++
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
t.Fatalf("iterate applied migrations: %v", err)
|
||||
}
|
||||
if steps == 0 {
|
||||
t.Fatalf("迁移 %s 不在账本里,无法回滚到它之前", id)
|
||||
}
|
||||
if err := db.MigrateDown(ctx, d, steps, testLogger()); err != nil {
|
||||
t.Fatalf("MigrateDown(%d) 回到 %s 之前: %v", steps, id, err)
|
||||
}
|
||||
}
|
||||
|
||||
// tableExists 报告表是否存在。
|
||||
func tableExists(t *testing.T, d *sql.DB, name string) bool {
|
||||
t.Helper()
|
||||
@@ -141,7 +176,6 @@ func countRawReviewRows(t *testing.T, d *sql.DB) int {
|
||||
// 索引、down 删表、再 up 能重建(回滚不留半状态)。
|
||||
func TestMigration0025CreatesAndRollsBackIngestReviewTable(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := context.Background()
|
||||
d := openRawMemoryDB(t)
|
||||
migrateUp(t, d)
|
||||
|
||||
@@ -162,11 +196,10 @@ func TestMigration0025CreatesAndRollsBackIngestReviewTable(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// 回滚:本表之上还压着一条 0026(`memory_retention_tier`,切片 M37),因此这里
|
||||
// 回滚**两条**才轮到 0025 —— 迁移账本按 id 升序、down 按降序撤,这是既有语义。
|
||||
if err := db.MigrateDown(ctx, d, 2, testLogger()); err != nil {
|
||||
t.Fatalf("MigrateDown(2): %v", err)
|
||||
}
|
||||
// 回滚:0025 之上还压着 0026(`memory_retention_tier`,切片 M37)与 0027
|
||||
// (`temporal`,切片 M45),因此要回到 0025 **之前**才轮得到它 —— 步数由
|
||||
// migrateDownToBefore 从账本现算,不写死常数(见该 helper 的注释)。
|
||||
migrateDownToBefore(t, d, ingestReviewMigrationID)
|
||||
if tableExists(t, d, ingestReviewTable) {
|
||||
t.Fatalf("回滚后 %s 应已被删除", ingestReviewTable)
|
||||
}
|
||||
|
||||
@@ -98,6 +98,14 @@ type retentionVerdict struct {
|
||||
// 4. **留存规则命中**(design/03 §10.5 的 N1~N7)⇒ temp,并带回规则码。
|
||||
// 5. 其余 ⇒ long(默认落点,fail-safe)。
|
||||
//
|
||||
// 🔴 **`temporal`(迁移 0027 的时间性元数据位)不在这个列表里**(r1 复审裁决 D,
|
||||
// 2026-10-27):这一位目前**只落库、只观测,不参与任何判定**。它被接进判定的两个
|
||||
// 候选设计都已被生产重放否掉 —— ①无条件 `one_off ⇒ temp` 会当天删掉 21 条长期约定;
|
||||
// ②只放开 N6 位置判据,最近 500 条里能翻的 13 条**逐条都是约定**、而复审点名的
|
||||
// 三条目标行 0/3 救得了(详见 temporal.go 头注)。因此判定的结论集与「没有这一位」
|
||||
// 逐字相同;temporal_test.go 有一条正断言钉住「喂 one_off 不影响任何结论」,
|
||||
// 另有一条变异靶子(把这一位重新接进本函数 ⇒ 那条正断言必红)。
|
||||
//
|
||||
// 🔴 「判第五态 `defer`」与「判 `retention_tier=temp`」**就是这一步**:闸与异步审查
|
||||
// 都只读 `item.RetentionTier`(preinsert_judge.go),不再各自跑一遍规则。M27/M37 的
|
||||
// 实测缺口正是「两处各判一遍、上游几乎不触发」,合并之后只有一个判据。
|
||||
|
||||
@@ -7,8 +7,6 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/db"
|
||||
)
|
||||
|
||||
// 本文件钉住**迁移 0026(`memory_retention_tier`)与 Store 自举 DDL 的同形与可回滚**,
|
||||
@@ -69,10 +67,9 @@ func TestMigration0026AddsColumnOverExistingRows(t *testing.T) {
|
||||
d := openRawMemoryDB(t)
|
||||
migrateUp(t, d)
|
||||
|
||||
// 造出「既有部署」:把 0026 撤掉(列与索引消失),再按**旧形态**写入两行。
|
||||
if err := db.MigrateDown(ctx, d, 1, testLogger()); err != nil {
|
||||
t.Fatalf("MigrateDown(1): %v", err)
|
||||
}
|
||||
// 造出「既有部署」:回到 0026 **之前**(列与索引消失),再按**旧形态**写入两行。
|
||||
// 步数由账本现算:0027(`temporal`,切片 M45)压在上面,写死 1 会撤错那条。
|
||||
migrateDownToBefore(t, d, retentionMigrationID)
|
||||
if hasMemoryColumn(t, d, retentionTierColumn) || hasMemoryIndex(t, d, retentionTierIndex) {
|
||||
t.Fatalf("0026 回滚后 %s / %s 应已消失", retentionTierColumn, retentionTierIndex)
|
||||
}
|
||||
@@ -111,9 +108,7 @@ func TestMigration0026AddsColumnOverExistingRows(t *testing.T) {
|
||||
}
|
||||
|
||||
// 回滚:只撤结构,不改写任何一行的其它数据。
|
||||
if err := db.MigrateDown(ctx, d, 1, testLogger()); err != nil {
|
||||
t.Fatalf("MigrateDown(1, 二次): %v", err)
|
||||
}
|
||||
migrateDownToBefore(t, d, retentionMigrationID)
|
||||
if hasMemoryColumn(t, d, retentionTierColumn) || hasMemoryIndex(t, d, retentionTierIndex) {
|
||||
t.Fatalf("二次回滚后 %s / %s 应已消失", retentionTierColumn, retentionTierIndex)
|
||||
}
|
||||
@@ -181,11 +176,18 @@ func TestMigration0026ShapeMatchesStoreBootstrap(t *testing.T) {
|
||||
t.Fatalf("%s 侧的 %s 列形状不是 TEXT NOT NULL DEFAULT 空串:%v", name, retentionTierColumn, cols)
|
||||
}
|
||||
}
|
||||
// 自举 DDL 里新列写在最后一列(新建库的期望形状)——迁移路径上它后面可能还有
|
||||
// 自举追加的 project_id,因此只对自举侧断言顺序。
|
||||
// 自举 DDL 的尾序(新建库的期望形状):`… retention_tier, temporal`。
|
||||
// 迁移路径上这两列之后可能还有自举追加的 project_id,因此只对自举侧断言顺序。
|
||||
// (0027 之后 retention_tier **不再是**最后一列 —— temporal 追加在它之后。)
|
||||
bootCols := tableColumns(t, bootstrapped, "memory_items")
|
||||
if last := bootCols[len(bootCols)-1]; !strings.Contains(last, "|"+retentionTierColumn+"|") {
|
||||
t.Fatalf("自举建的 memory_items 最后一列 = %q, want %s", last, retentionTierColumn)
|
||||
if len(bootCols) < 2 {
|
||||
t.Fatalf("自举建的 memory_items 列数 = %d, want ≥ 2", len(bootCols))
|
||||
}
|
||||
tail := bootCols[len(bootCols)-2:]
|
||||
if !strings.Contains(tail[0], "|"+retentionTierColumn+"|") ||
|
||||
!strings.Contains(tail[1], "|"+temporalColumn+"|") {
|
||||
t.Fatalf("自举建的 memory_items 尾两列 = %v, want …, %s, %s",
|
||||
tail, retentionTierColumn, temporalColumn)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -135,6 +135,21 @@ type MemoryItem struct {
|
||||
// 非空 = 调用方的显式断言,判据不许推翻它。读回来时:
|
||||
// **空串 = 尚未分型**(0026 之前的历史行 / 受限来源新行),绝不是某一档。
|
||||
RetentionTier RetentionTier
|
||||
|
||||
// Temporal 是**提取器给出的时间性元数据位**(迁移 0027、temporal.go):
|
||||
// one_off / recurring / durable / unknown,空串 = 未分型(历史行与没做时间性
|
||||
// 判断的写入路径,口径见 temporal.go 头注)。
|
||||
//
|
||||
// 🔴 **它目前只观测、不参与判定**(r1 复审裁决 D):`resolveRetention` 不读它,
|
||||
// 判定的结论集与「没有这一位」逐字相同。保留它是为了积累「模型到底怎么标」的
|
||||
// 证据 —— 接线前必须先看那份分布(temporal.go 头注里给了查询)。
|
||||
//
|
||||
// ⚠️ **与 ExpiresAt 同样是「只写不读」的列**:`Add` 把它写进 `temporal` 列,
|
||||
// 但四条列表读路径的 SELECT 与 scanItem 都不读它 —— 改扫描口径要动全部读点
|
||||
// (rules.go / store_list.go / tidy_store.go / preinsert_store.go,共 14→15 列),
|
||||
// 那是另一件事,不在本片授权范围。要按时间性位巡检/回填时直读该列即可;
|
||||
// 写入侧的校验/编码见 store_temporal.go。
|
||||
Temporal TemporalKind
|
||||
}
|
||||
|
||||
// 区分 memory 包各类失败的哨兵错误。每个都在
|
||||
@@ -246,6 +261,10 @@ func NewStore(ctx context.Context, db *sql.DB, log *slog.Logger) (*Store, error)
|
||||
if err := ensureRetentionSchema(ctx, db); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 时间性元数据位(迁移 0027):只补列、不建索引、不回填(见 temporal_schema.go)。
|
||||
if err := ensureTemporalSchema(ctx, db); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := normalizeMemoryTimestamps(ctx, db); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -284,6 +303,12 @@ func NewStore(ctx context.Context, db *sql.DB, log *slog.Logger) (*Store, error)
|
||||
// 「档位 → expires_at」换算。两列因此**同一个判定、同一笔 INSERT**落下,
|
||||
// 不存在「判了 temp 却没写有效期」的中间态 —— M2 时代登记过的「INSERT 与补写
|
||||
// expires_at 之间的短窗口」在本片被结构性关闭(不再有第二笔 UPDATE)。
|
||||
//
|
||||
// 🆕 切片 M45:`item.Temporal`(时间性元数据位,迁移 0027)也随**这一笔** INSERT
|
||||
// 落下(`temporal` 列)。**它只落库、不参与判定**(r1 复审裁决 D):`resolveRetention`
|
||||
// 不读这一位,因此档位/有效期与「没有这一位」逐字相同;列值的作用是**观测**——
|
||||
// 事后能按它分组统计、抽样看模型把哪些行标成了 `one_off`(这是将来决定要不要接线
|
||||
// 的唯一证据来源,见 temporal.go 头注的查询)。
|
||||
func (s *Store) Add(ctx context.Context, item MemoryItem) (MemoryItem, error) {
|
||||
if err := item.normalize(); err != nil {
|
||||
return MemoryItem{}, err
|
||||
@@ -315,12 +340,13 @@ func (s *Store) Add(ctx context.Context, item MemoryItem) (MemoryItem, error) {
|
||||
_, err = s.db.ExecContext(ctx, `INSERT INTO memory_items
|
||||
(id, persona_id, role_id, project_id, scope, kind, content, tags, confidence,
|
||||
source_conversation, created_at, updated_at, decay_weight, status, merged_into,
|
||||
expires_at, retention_tier)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
expires_at, retention_tier, temporal)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
item.ID, item.PersonaID, item.RoleID, item.ProjectID, string(item.Scope), string(item.Kind),
|
||||
item.Content, string(tagsJSON), item.Confidence, item.SourceConversation,
|
||||
formatTime(item.CreatedAt), formatTime(item.UpdatedAt), item.DecayWeight,
|
||||
plan.insertStatus(), plan.absorbedID(), plan.expiresAt(), plan.retention())
|
||||
plan.insertStatus(), plan.absorbedID(), plan.expiresAt(), plan.retention(),
|
||||
item.temporalColumn())
|
||||
if err != nil {
|
||||
return MemoryItem{}, fmt.Errorf("memory: insert item: %w", err)
|
||||
}
|
||||
@@ -428,6 +454,9 @@ func (it *MemoryItem) validate() error {
|
||||
if !it.RetentionTier.valid() {
|
||||
return fmt.Errorf("%w: %q", ErrInvalidRetentionTier, it.RetentionTier)
|
||||
}
|
||||
if err := it.validateTemporal(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,8 @@ CREATE TABLE IF NOT EXISTS memory_items (
|
||||
occurred_at TEXT NOT NULL DEFAULT '',
|
||||
valid_to TEXT NOT NULL DEFAULT '',
|
||||
expires_at TEXT NOT NULL DEFAULT '',
|
||||
retention_tier TEXT NOT NULL DEFAULT ''
|
||||
retention_tier TEXT NOT NULL DEFAULT '',
|
||||
temporal TEXT NOT NULL DEFAULT ''
|
||||
)`
|
||||
|
||||
const createMemoryItemsPersonaIndex = `
|
||||
@@ -43,6 +44,11 @@ CREATE INDEX IF NOT EXISTS idx_memory_items_persona_id_created_at
|
||||
// (回填分型的入口)都吃它。列**必须**排在 CREATE TABLE 的最后:迁移的
|
||||
// `ALTER TABLE ADD COLUMN` 也把新列追加在末尾,两份 DDL 才逐列同形
|
||||
// (retention_migration_test.go 钉住这条同形,少一列就是「新库有、老库无」的漂移)。
|
||||
//
|
||||
// ⚠️ 0027 之后 `retention_tier` **不再是最后一列**:`temporal`(迁移 0027)追加在
|
||||
// 它之后,两条路径的尾序都是 `… expires_at, retention_tier, temporal`。新列一律
|
||||
// 追加在末尾这条口径不变,只是「末尾」会随迁移推进(那条同形断言比对**列集合**,
|
||||
// 另外对尾序做一条显式断言)。
|
||||
const createMemoryItemsRetentionTierIndex = `
|
||||
CREATE INDEX IF NOT EXISTS idx_memory_items_retention_tier
|
||||
ON memory_items (retention_tier)`
|
||||
@@ -0,0 +1,46 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// 本文件是 `memory_items.temporal`(迁移 0027)在**写入路径**上的那一半:哨兵错误、
|
||||
// 字段校验、以及落库时的列值编码。
|
||||
//
|
||||
// 🔴 其余三处的归属(别在这条链上另开一份实现):
|
||||
// - **字段与语义**在 store.go 的 MemoryItem 上(结构体的字段不能跨文件声明),
|
||||
// 闭集与归一化在 temporal.go;
|
||||
// - **判定**仍是 `resolveRetention`(retention.go)里的 N1~N7 —— `temporal`
|
||||
// **只被记录,不参与判定**(r1 复审裁决 D),因此 `resolveRetention` 里
|
||||
// **没有、也不许有**「第 4 步看 temporal」这种东西;
|
||||
// - **DDL** 在 migrations/0027 + store_schema.go + temporal_schema.go。
|
||||
//
|
||||
// 要把 `temporal` 接进判定,前置条件写在 temporal.go 头注:先拿到模型真实标签分布
|
||||
// (那里给了两条只读 SQL),再改 `temporal_test.go` 的 temporalFieldSites 白名单 ——
|
||||
// 那张表是**有意的接线决定**的唯一入口,不许绕过它。
|
||||
//
|
||||
// 拆出本文件只为守 AGENTS §10 的文件行数上限(store.go 已到 500 行)与「模块按职责
|
||||
// 拆源文件」那条规范 —— 口径逐字未变。
|
||||
|
||||
// ErrInvalidTemporal 在条目的 Temporal(时间性元数据位,迁移 0027)不是闭集内的
|
||||
// 值时返回。空串**不在**此列:它是「尚未分型」这一合法状态。
|
||||
var ErrInvalidTemporal = errors.New("memory: invalid temporal kind")
|
||||
|
||||
// validateTemporal 只接受闭集内的值:时间性位是**枚举元数据**,一个自造的值
|
||||
// ("sometimes")既判不出档位、又不该静默落库 —— 提取器已经把模型输出归一成
|
||||
// unknown(temporal.go 的 normalizeTemporal),走到这里还是非法值只能是程序错误,
|
||||
// 因此直接拒,而不是替它挑一个值。
|
||||
func (it *MemoryItem) validateTemporal() error {
|
||||
if !it.Temporal.valid() {
|
||||
return fmt.Errorf("%w: %q", ErrInvalidTemporal, it.Temporal)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// temporalColumn 返回要写进 `temporal` 列的值(与 `ingestGatePlan.retention()` /
|
||||
// `expiresAt()` 同族:把「条目 → 落库值」这一步收在类型自己身上,插入语句里不留
|
||||
// 裸转换,也就不可能出现两处各转一次、口径分叉)。
|
||||
func (it MemoryItem) temporalColumn() string {
|
||||
return string(it.Temporal)
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package memory
|
||||
|
||||
import "strings"
|
||||
|
||||
// 本文件是**提取器产出侧的时间性元数据位**(`temporal`,迁移 0027):它记录模型对
|
||||
// 「这条记忆说的是**一次发生的事**,还是**反复 / 长期成立的事**」的判断。
|
||||
//
|
||||
// 当初为什么要这一位(M37 复审的结论,逐字):「真正卡住上游的是**提取器的改写**:
|
||||
// 一次性事件被写成 30~80 字的第三人称长期陈述(同时带『近期/目前』和持久词),
|
||||
// 规则闸看不到『这是今天的一次性事件』这一位。这不是阈值问题,是**判定链缺信息位**。」
|
||||
//
|
||||
// 🔴 **当前状态:只观测,不参与判定**(r1 复审裁决 D,2026-10-27)。`resolveRetention`
|
||||
// **不读**这一位,判定的结论集与「没有这一位」逐字相同。保留它的唯一目的是**积累
|
||||
// 证据**:等真实提取跑出一批标签之后,再回答「模型到底怎么标」以及「接进判定是赚
|
||||
// 还是亏」。
|
||||
//
|
||||
// 为什么撤(两次候选接线都被生产重放否掉,别再凭直觉改回去):
|
||||
//
|
||||
// ① **无条件 `one_off ⇒ temp`**(任务书初版口径):最近 500 条 active 里人工按
|
||||
// 提取器口径标出的 23 条 `one_off`,其中 21 条是「约定 + 某一次没走成」形态 ⇒
|
||||
// 7 天后**把约定本身物理删掉**(不可撤回)。
|
||||
// ② **只放开 N6 的位置判据**(r1 复审给的改法):能翻的行在窗口内 13 条、**逐条都是
|
||||
// 约定**(`约定/约好 + 今天没走成`),而复审点名的三条目标行 **0/3** 救得了
|
||||
// (`…睡得比平时早` 被习惯词、`…以后不用再惦记` 被永久化标记、`自行车链条` 那条
|
||||
// 没有时点词)⇒ 收益为 0、风险集中在长期约定。
|
||||
//
|
||||
// 还有一层方法论上的理由:以上两轮数字**全部**建立在「对历史改写正文**人工**标注」
|
||||
// 上 —— 生产库里 `temporal` 列当时还不存在,模型从未在这批正文上产出过标签。
|
||||
// 用人工标签去决定一条「模型标签驱动」的接线,证据链是断的。
|
||||
//
|
||||
// 将来真要接线,前置条件是**这份数据**(不是又一次重放):
|
||||
//
|
||||
// SELECT temporal, COUNT(*) FROM memory_items GROUP BY temporal;
|
||||
// SELECT created_at, retention_tier, content FROM memory_items
|
||||
// WHERE temporal = 'one_off' ORDER BY created_at DESC LIMIT 10;
|
||||
//
|
||||
// 🔴 上面两条是**运维分析用的 SQL,不属于读侧代码路径**,别把它们抄进查询层:
|
||||
// timegate.go(以及任何读侧 SQL)明令**不许**对 `created_at` / `expires_at` 用
|
||||
// `datetime()` 之类的 SQLite 时间函数 —— 读侧闸是**定宽文本比较**,一旦有人按这两条
|
||||
// 的写法去写查询,时间格式一变就会静默判错(timegate_test.go 钉着那条反证)。
|
||||
// 这里出现 `datetime(created_at)` 只是因为「人工一次性分析、离线跑、不需要精确到
|
||||
// 纳秒」——**恰好**是读侧不许用的那个形态。
|
||||
//
|
||||
// 看 `one_off` 那 10 条里有多少是长期约定 —— 那才是「这一位能不能用」的判据。
|
||||
//
|
||||
// 闭集(与迁移 0027 的列值口径逐字一致):
|
||||
//
|
||||
// one_off 一次性事件(今天 / 这次 / 某一次发生的事)
|
||||
// recurring 反复发生的规律(每天 / 每周 / 每次都…)
|
||||
// durable 长期成立的事实 / 偏好 / 约定 / 称呼 / 身份
|
||||
// unknown 模型拿不准,或没给出合法值
|
||||
// '' 尚未分型:0027 之前的历史行 + 没做时间性判断的写入路径
|
||||
// (`ManualExtractor` 的「记住 X」、网关/管理面手写、整理侧回填 ——
|
||||
// 它们本来就由调用方显式给档位)
|
||||
//
|
||||
// 🔴 `unknown` 与 `”` 是两件事:`unknown` 是「问过模型了,它拿不准」;`”` 是
|
||||
// 「这条路径没问过」。把两者折成一个值会让「模型到底答了什么」这个观测面当场消失,
|
||||
// 而那正是保留这一位的全部意义。
|
||||
type TemporalKind string
|
||||
|
||||
const (
|
||||
// TemporalUnset 是「尚未分型」:历史行与没做时间性判断的写入路径(见文件头注)。
|
||||
// **它不是业务取值**,也**不是**「unknown」的同义词。
|
||||
TemporalUnset TemporalKind = ""
|
||||
|
||||
// TemporalOneOff 是一次性事件。它目前**不改变任何判定**:写入时只落库,
|
||||
// 供事后统计「模型把哪些行标成了某一次发生的事」。
|
||||
TemporalOneOff TemporalKind = "one_off"
|
||||
|
||||
// TemporalRecurring 是反复发生的规律(「每天散步十分钟」「每周三开会」)。
|
||||
TemporalRecurring TemporalKind = "recurring"
|
||||
|
||||
// TemporalDurable 是长期成立的事实 / 偏好 / 约定 / 称呼 / 身份。
|
||||
TemporalDurable TemporalKind = "durable"
|
||||
|
||||
// TemporalUnknown 是「问过模型了,它拿不准」。
|
||||
TemporalUnknown TemporalKind = "unknown"
|
||||
)
|
||||
|
||||
// valid 报告 t 是否落在闭集内(**含**未分型的空串:它是合法的列值,不是错误)。
|
||||
func (t TemporalKind) valid() bool {
|
||||
switch t {
|
||||
case TemporalUnset, TemporalOneOff, TemporalRecurring, TemporalDurable, TemporalUnknown:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// assigned 报告 t 是否**已由提取器分型**(即非空串)。它是「未分型」的唯一判据,
|
||||
// 与 RetentionTier.assigned 同族,调用方不许用 `t == TemporalUnknown` 之类的
|
||||
// 比较去替代它(那是「问过但拿不准」,不是「没问过」)。
|
||||
func (t TemporalKind) assigned() bool { return t != TemporalUnset }
|
||||
|
||||
// normalizeTemporal 把模型输出的自由文本归一到上面四个值。
|
||||
//
|
||||
// 🔴 **只做大小写折叠与首尾空白裁剪,绝不做同义词猜测**(「一次性」「once」→ 都不认):
|
||||
// 认不出来的答案就是解析失败,一律落 TemporalUnknown —— 这正是任务书
|
||||
// 「模型只能选那四个值,解析失败一律归 unknown(绝不猜)」的字面实现。将来接线时
|
||||
// 这条尤其重要:猜同义词的代价是单向的(猜成 one_off 就删记忆)。
|
||||
func normalizeTemporal(s string) TemporalKind {
|
||||
switch TemporalKind(strings.ToLower(strings.TrimSpace(s))) {
|
||||
case TemporalOneOff:
|
||||
return TemporalOneOff
|
||||
case TemporalRecurring:
|
||||
return TemporalRecurring
|
||||
case TemporalDurable:
|
||||
return TemporalDurable
|
||||
default:
|
||||
// 空值、非法值、拼写错误、模型自造的新值:全部归 unknown(**不报错**)。
|
||||
// 一条候选记忆的价值不取决于它的时间性位是否写对,因此解析失败绝不
|
||||
// 让整批提取失败(那会静默丢掉同批的其他候选)。
|
||||
return TemporalUnknown
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 本文件钉住**迁移 0027(`memory_temporal`)与 Store 自举 DDL 的同形与可回滚**,
|
||||
// 手法照 retention_migration_test.go 对 0026 的那一套(同一批 helpers)。
|
||||
//
|
||||
// 真实启动顺序是「先 MigrateUp、后 NewStore」(cmd/cyrene/wire.go),因此新列有两份
|
||||
// 真源:迁移(权威)与 NewStore 的幂等前滚(任意 *sql.DB 上的自举,temporal_schema.go)。
|
||||
// 少一列就是「新库有、老库无」的漂移,因此两条判据都必须有:
|
||||
//
|
||||
// 1. TestMigration0027AddsColumnOverExistingRows —— 迁移落在**已有数据**上:行不丢、
|
||||
// 列补上、默认值是空串(未分型);down 真的把列删掉且**不改写任何一行的其它
|
||||
// 数据**(尤其是 `retention_tier` / `expires_at`,见 down 文件的口径);再 up 能重建。
|
||||
// 2. TestMigration0027ShapeMatchesStoreBootstrap —— 新列在两份 DDL 里**逐字同形**
|
||||
// (TEXT NOT NULL DEFAULT 空串),且自举侧尾序是 `… retention_tier, temporal`。
|
||||
|
||||
// temporalColumn 是被测列名(迁移与自举 DDL 里的字面量)。
|
||||
const temporalColumn = "temporal"
|
||||
|
||||
// temporalMigrationID 是 0027 在 schema_migrations 里的记账 id(= 文件名去掉 .up.sql)。
|
||||
const temporalMigrationID = "0027_memory_temporal"
|
||||
|
||||
// TestMigration0027AddsColumnOverExistingRows 钉住迁移本体落在**既有数据**上的两条:
|
||||
// 行不丢、默认值是空串(未分型);以及再 up 后历史行回到「未分型」。
|
||||
func TestMigration0027AddsColumnOverExistingRows(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := context.Background()
|
||||
d := openRawMemoryDB(t)
|
||||
migrateUp(t, d)
|
||||
if !hasMemoryColumn(t, d, temporalColumn) {
|
||||
t.Fatalf("迁移后 memory_items 应带 %s 列", temporalColumn)
|
||||
}
|
||||
|
||||
// 造出「0027 之前的既有部署」:回到 0027 之前,按旧形态写入两行。
|
||||
migrateDownToBefore(t, d, temporalMigrationID)
|
||||
if hasMemoryColumn(t, d, temporalColumn) {
|
||||
t.Fatalf("0027 回滚后 %s 应已消失", temporalColumn)
|
||||
}
|
||||
insertLegacyMemoryRow(t, d, "legacy-1", "一条 0027 之前就存在的记忆")
|
||||
insertLegacyMemoryRow(t, d, "legacy-2", "另一条 0027 之前就存在的记忆")
|
||||
|
||||
// 升级:0027 落在**已有数据**上。
|
||||
migrateUp(t, d)
|
||||
if !hasMemoryColumn(t, d, temporalColumn) {
|
||||
t.Fatalf("迁移后 memory_items 应带 %s 列", temporalColumn)
|
||||
}
|
||||
var rows int
|
||||
if err := d.QueryRowContext(ctx, `SELECT COUNT(*) FROM memory_items`).Scan(&rows); err != nil {
|
||||
t.Fatalf("count rows: %v", err)
|
||||
}
|
||||
if rows != 2 {
|
||||
t.Fatalf("迁移后行数 = %d, want 2(既有行一行都不能丢)", rows)
|
||||
}
|
||||
for _, id := range []string{"legacy-1", "legacy-2"} {
|
||||
var nat, content string
|
||||
if err := d.QueryRowContext(ctx,
|
||||
`SELECT temporal, content FROM memory_items WHERE id = ?`, id).
|
||||
Scan(&nat, &content); err != nil {
|
||||
t.Fatalf("read %s: %v", id, err)
|
||||
}
|
||||
if nat != "" {
|
||||
t.Fatalf("既有行 %s 的时间性位 = %q, want 空串(历史行必须是「未分型」)", id, nat)
|
||||
}
|
||||
if content == "" {
|
||||
t.Fatalf("既有行 %s 的正文丢了", id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestMigration0027DownKeepsRowData 钉住 down 的**唯一**语义:只撤结构。判成 temp 的
|
||||
// 行在回滚之后档位与时效必须**一个字节都没变**(回滚改数据 = 把已判定的临时记忆升回
|
||||
// 永久,正是 down 文件里登记的那条反面)。
|
||||
func TestMigration0027DownKeepsRowData(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := context.Background()
|
||||
d := openRawMemoryDB(t)
|
||||
migrateUp(t, d)
|
||||
|
||||
if _, err := d.ExecContext(ctx, `INSERT INTO memory_items
|
||||
(id, persona_id, scope, kind, content, created_at, updated_at,
|
||||
retention_tier, expires_at, temporal)
|
||||
VALUES ('temp-1', 'persona.a', 'persona', 'relationship', '一条临时记忆',
|
||||
`+legacyTimeLiteral+`, `+legacyTimeLiteral+`, 'temp', ?, 'one_off')`,
|
||||
formatTime(time.Date(2026, 10, 30, 0, 0, 0, 0, time.UTC))); err != nil {
|
||||
t.Fatalf("seed temp row: %v", err)
|
||||
}
|
||||
|
||||
migrateDownToBefore(t, d, temporalMigrationID)
|
||||
if hasMemoryColumn(t, d, temporalColumn) {
|
||||
t.Fatalf("回滚后 %s 应已消失", temporalColumn)
|
||||
}
|
||||
var tier, expires string
|
||||
if err := d.QueryRowContext(ctx,
|
||||
`SELECT retention_tier, expires_at FROM memory_items WHERE id = 'temp-1'`).
|
||||
Scan(&tier, &expires); err != nil {
|
||||
t.Fatalf("read retention columns after down: %v", err)
|
||||
}
|
||||
if tier != string(RetentionTemp) || expires == "" {
|
||||
t.Fatalf("down 改写了档位/时效 = (%q, %q), want (%q, 非空) —— 回滚只撤结构",
|
||||
tier, expires, RetentionTemp)
|
||||
}
|
||||
|
||||
// 再 up:列以默认值重建,既有行回到「未分型」。
|
||||
migrateUp(t, d)
|
||||
if !hasMemoryColumn(t, d, temporalColumn) {
|
||||
t.Fatalf("再次迁移后应重建 %s 列", temporalColumn)
|
||||
}
|
||||
var untyped int
|
||||
if err := d.QueryRowContext(ctx,
|
||||
`SELECT COUNT(*) FROM memory_items WHERE temporal = ''`).Scan(&untyped); err != nil {
|
||||
t.Fatalf("count untyped: %v", err)
|
||||
}
|
||||
if untyped != 1 {
|
||||
t.Fatalf("重建后未分型行 = %d, want 1", untyped)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMigration0027ShapeMatchesStoreBootstrap 是**漂移护栏**:迁移建出的
|
||||
// memory_items(列集合)与自举 DDL 建出的必须一致,且新列在两份 DDL 里的形状
|
||||
// 逐字相同(TEXT NOT NULL DEFAULT 空串)。
|
||||
//
|
||||
// 列集合的等价性由 0026 的 TestMigration0026ShapeMatchesStoreBootstrap 一并覆盖
|
||||
// (它比对整表列集合);这里只钉本列自己的形状与自举侧的尾序。
|
||||
func TestMigration0027ShapeMatchesStoreBootstrap(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := context.Background()
|
||||
|
||||
migrated := openRawMemoryDB(t)
|
||||
migrateUp(t, migrated)
|
||||
|
||||
bootstrapped := openRawMemoryDB(t)
|
||||
if _, err := NewStore(ctx, bootstrapped, testLogger()); err != nil {
|
||||
t.Fatalf("NewStore: %v", err)
|
||||
}
|
||||
|
||||
for name, d := range map[string]*sql.DB{"迁移": migrated, "自举": bootstrapped} {
|
||||
cols := sortedColumns(tableColumns(t, d, "memory_items"))
|
||||
if !slices.Contains(cols, temporalColumn+"|TEXT|1|''|0") {
|
||||
t.Fatalf("%s 侧的 %s 列形状不是 TEXT NOT NULL DEFAULT 空串:%v", name, temporalColumn, cols)
|
||||
}
|
||||
}
|
||||
bootCols := tableColumns(t, bootstrapped, "memory_items")
|
||||
if len(bootCols) < 2 {
|
||||
t.Fatalf("自举建的 memory_items 列数 = %d, want ≥ 2", len(bootCols))
|
||||
}
|
||||
tail := bootCols[len(bootCols)-2:]
|
||||
if !strings.Contains(tail[0], "|"+retentionTierColumn+"|") ||
|
||||
!strings.Contains(tail[1], "|"+temporalColumn+"|") {
|
||||
t.Fatalf("自举建的 memory_items 尾两列 = %v, want …, %s, %s",
|
||||
tail, retentionTierColumn, temporalColumn)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMigration0027ThenStoreBootstrapIsARegularPath 覆盖**真实启动顺序**
|
||||
// (cmd/cyrene/wire.go:先 MigrateUp、后 NewStore):0027 先建好列,随后 Store 的
|
||||
// 自举前滚走到 "duplicate column name" —— 那是**预期路径**,必须无害;重复建 Store
|
||||
// 同样幂等,且写入路径可用(时间性位随同一笔 INSERT 落下)。
|
||||
func TestMigration0027ThenStoreBootstrapIsARegularPath(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := context.Background()
|
||||
d := openRawMemoryDB(t)
|
||||
migrateUp(t, d)
|
||||
|
||||
store, err := NewStore(ctx, d, testLogger())
|
||||
if err != nil {
|
||||
t.Fatalf("NewStore(列已由迁移建好): %v", err)
|
||||
}
|
||||
after := tableColumns(t, d, "memory_items")
|
||||
if !hasMemoryColumn(t, d, temporalColumn) {
|
||||
t.Fatalf("自举之后 %s 列消失了", temporalColumn)
|
||||
}
|
||||
if _, err := NewStore(ctx, d, testLogger()); err != nil {
|
||||
t.Fatalf("NewStore(第二次): %v", err)
|
||||
}
|
||||
if got := tableColumns(t, d, "memory_items"); !slices.Equal(got, after) {
|
||||
t.Fatalf("第二次自举改变了表结构:\n got=%v\nwant=%v", got, after)
|
||||
}
|
||||
|
||||
item := habitItem("主人有一条真实落库的观测样本", tidyTestTime(t), 0.9)
|
||||
item.Temporal = TemporalOneOff
|
||||
got, err := store.Add(ctx, item)
|
||||
if err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
if nat := readTemporalColumn(t, store, got.ID); nat != TemporalOneOff {
|
||||
t.Fatalf("迁移建列后经 Store 落库的时间性位 = %q, want %q", nat, TemporalOneOff)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// 本文件是「时间性元数据位」轴(迁移 0027)的 schema 前滚:给**既有**的
|
||||
// memory_items 补 `temporal` 列。
|
||||
//
|
||||
// 与 retention_schema.go 同一手法、同一原因:`createMemoryItemsTable` 是
|
||||
// `CREATE TABLE IF NOT EXISTS`,只对**新库**生效 —— 既有部署的表早就建好了,
|
||||
// 新列不会自己长出来。记忆存储必须自包含、能在任意 *sql.DB 上使用,因此这条
|
||||
// 前滚不能只靠 `internal/db/migrations`。
|
||||
//
|
||||
// 🔴 与迁移的分工(两份真源,必须同形):权威机制是
|
||||
// `internal/db/migrations/0027_memory_temporal`;这里是「任意 *sql.DB」的前滚。
|
||||
// 启动顺序是「先 MigrateUp、后 NewStore」(cmd/cyrene/wire.go),因此生产库里
|
||||
// 0027 先落地、这里走到 `duplicate column name` 是**预期路径**。
|
||||
//
|
||||
// 本列**不建索引**:目前没有任何按时间性位的读路径(它是写入侧的判定输入 +
|
||||
// 事后巡检用的留痕列),提前建索引只是给每笔写入加一份没人用的维护成本。
|
||||
// 将来整理侧真要按它筛(例如「把 one_off 的行捞出来复核」)再加索引不迟,
|
||||
// 那时两条路径(迁移 + 本文件)一起加。
|
||||
|
||||
// ensureTemporalSchema 幂等地给 memory_items 补上时间性位列(列缺失时 ALTER,
|
||||
// 已存在时忽略 SQLite 的 "duplicate column name" —— 那是预期路径,不是错误)。
|
||||
//
|
||||
// 默认值 = 空串 = 尚未分型:既有行因此**行为逐字不变**(resolveRetention 对
|
||||
// 未分型的处理与 0027 之前完全一样,只跑 N1~N7)。本前滚刻意**不做**任何回填
|
||||
// 判定:历史行没有对应的提取器输出,拿正文反推「它当时是一次性事件吗」正是
|
||||
// 本片要消灭的那种猜测。
|
||||
func ensureTemporalSchema(ctx context.Context, db *sql.DB) error {
|
||||
_, err := db.ExecContext(ctx, `ALTER TABLE memory_items
|
||||
ADD COLUMN temporal TEXT NOT NULL DEFAULT ''`)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if strings.Contains(err.Error(), "duplicate column name") {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("memory: roll forward temporal column: %w", err)
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/model"
|
||||
)
|
||||
|
||||
// 本文件是**时间性元数据位**(迁移 0027、temporal.go)的验收用例集。
|
||||
//
|
||||
// 🔴 当前契约(r1 复审裁决 D,2026-10-27):**这一位只观测,不参与判定。**
|
||||
// `resolveRetention` 不读它,判定的结论集与「没有这一位」逐字相同。因此本文件最重要
|
||||
// 的一条断言是**零影响**(TestTemporalBitDoesNotAffectRetention):同一段正文,
|
||||
// 无论 `temporal` 是 five 个取值里的哪一个,档位与规则码都必须完全相同。
|
||||
//
|
||||
// 变异靶子与之配套:谁把这一位重新接进 `resolveRetention`(例如先加一句
|
||||
// `if item.Temporal == TemporalOneOff { return temp }`),那条正断言必红 ——
|
||||
// 这不是「测试太严」,而是「接线前必须先有模型真实标签分布」这个裁决的守卫。
|
||||
|
||||
// temporalObservationCorpus 覆盖三类正文,每类都必须对 temporal 免疫:
|
||||
//
|
||||
// ① 旧规则判 long 的行(接线的「收益」候选);
|
||||
// ② 旧规则判 temp 的行(`durable` 也不能把它们救回来 —— 零影响是双向的);
|
||||
// ③ 受限来源 / 显式档位这类「更早的分支」(它们更不该被这一位碰到)。
|
||||
func temporalObservationCorpus() []string {
|
||||
return []string{
|
||||
"和主人有一个出门走十分钟的约定;今天没走成,明天要补上。",
|
||||
"主人有每天吃早餐的习惯,几乎不会省略早餐。",
|
||||
"今天下雨了",
|
||||
"谢谢啦",
|
||||
}
|
||||
}
|
||||
|
||||
// temporalAllKinds 是「业务上可能出现的全部取值」+ 未分型。
|
||||
func temporalAllKinds() []TemporalKind {
|
||||
return []TemporalKind{
|
||||
TemporalUnset, TemporalOneOff, TemporalRecurring, TemporalDurable, TemporalUnknown,
|
||||
}
|
||||
}
|
||||
|
||||
// TestTemporalBitDoesNotAffectRetention 是本文件的核心断言:**temporal 对留存判定零影响**
|
||||
// ——对同一段正文,五个取值的 `(档位, 规则码)` 必须逐字相同(且都以未分型为基准)。
|
||||
func TestTemporalBitDoesNotAffectRetention(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, content := range temporalObservationCorpus() {
|
||||
content := content
|
||||
t.Run(content, func(t *testing.T) {
|
||||
base, err := resolveRetention(habitItem(content, tidyTestTime(t), 0.9))
|
||||
if err != nil {
|
||||
t.Fatalf("resolveRetention(base): %v", err)
|
||||
}
|
||||
for _, temporal := range temporalAllKinds() {
|
||||
item := habitItem(content, tidyTestTime(t), 0.9)
|
||||
item.Temporal = temporal
|
||||
got, err := resolveRetention(item)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveRetention(temporal=%q): %v", temporal, err)
|
||||
}
|
||||
if got != base {
|
||||
t.Fatalf("%q with temporal=%q 判成 %+v, want %+v(这一位必须零影响;"+
|
||||
"接线前必须先拿到模型真实标签分布,见 temporal.go 头注)",
|
||||
content, temporal, got, base)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestTemporalOneOffDoesNotMakeAnythingTemporary 是上一条的正向版本,单独成例是为了
|
||||
// 让「接线会怎样」在失败信息里一眼可见:它只喂 `one_off`,并点名断言「旧规则判 long
|
||||
// 的行仍然 long」。
|
||||
func TestTemporalOneOffDoesNotMakeAnythingTemporary(t *testing.T) {
|
||||
t.Parallel()
|
||||
const content = "和主人有一个出门走十分钟的约定;今天没走成,明天要补上。"
|
||||
base, err := resolveRetention(habitItem(content, tidyTestTime(t), 0.9))
|
||||
if err != nil {
|
||||
t.Fatalf("resolveRetention(base): %v", err)
|
||||
}
|
||||
if base.Tier != RetentionLong {
|
||||
t.Fatalf("前提不成立:%q 旧规则判 %q(want long)", content, base.Tier)
|
||||
}
|
||||
item := habitItem(content, tidyTestTime(t), 0.9)
|
||||
item.Temporal = TemporalOneOff
|
||||
got, err := resolveRetention(item)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveRetention(one_off): %v", err)
|
||||
}
|
||||
if got.Tier != RetentionLong || got.Rule != retentionNone {
|
||||
t.Fatalf("temporal=one_off 把 %q 判成 %+v —— 这一位不得参与判定(裁决 D)", content, got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTemporalIsStillRecorded 钉住「撤接线不等于撤观测」:`temporal` 仍随同一笔
|
||||
// INSERT 落库(迁移 0027 的列),而档位/有效期保持旧规则的结论 —— 这正是 D 要的
|
||||
// 数据来源:全库按 temporal 分组统计、抽样看 one_off 到底长什么样。
|
||||
func TestTemporalIsStillRecorded(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := context.Background()
|
||||
store := newTestStore(t)
|
||||
const content = "和主人有一个出门走十分钟的约定;今天没走成,明天要补上。"
|
||||
item := habitItem(content, tidyTestTime(t), 0.9)
|
||||
item.Temporal = TemporalOneOff
|
||||
got, err := store.Add(ctx, item)
|
||||
if err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
if nat := readTemporalColumn(t, store, got.ID); nat != TemporalOneOff {
|
||||
t.Fatalf("temporal 列 = %q, want %q(观测面必须保留)", nat, TemporalOneOff)
|
||||
}
|
||||
tier, expires := readRetentionColumns(t, store, got.ID)
|
||||
if tier != RetentionLong || expires != "" {
|
||||
t.Fatalf("落库档位/时效 = (%q, %q), want (long, 空) —— 观测不得改变判定",
|
||||
tier, expires)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTemporalDoesNotRescueRuleHitRows 钉住零影响是**双向**的:`durable` 曾经(M45
|
||||
// 初版)能把规则判 temp 的行救回 long;裁决 D 之后这条也取消 —— 判定只由 N1~N7 决定。
|
||||
func TestTemporalDoesNotRescueRuleHitRows(t *testing.T) {
|
||||
t.Parallel()
|
||||
const content = "今天下雨了"
|
||||
base, err := resolveRetention(habitItem(content, tidyTestTime(t), 0.9))
|
||||
if err != nil {
|
||||
t.Fatalf("resolveRetention(base): %v", err)
|
||||
}
|
||||
if base.Tier != RetentionTemp {
|
||||
t.Fatalf("前提不成立:%q 旧规则判 %q(want temp)", content, base.Tier)
|
||||
}
|
||||
for _, temporal := range []TemporalKind{TemporalDurable, TemporalRecurring} {
|
||||
item := habitItem(content, tidyTestTime(t), 0.9)
|
||||
item.Temporal = temporal
|
||||
got, err := resolveRetention(item)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveRetention(%q): %v", temporal, err)
|
||||
}
|
||||
if got != base {
|
||||
t.Fatalf("%q with temporal=%q 判成 %+v, want %+v(这一位不得推翻规则)",
|
||||
content, temporal, got, base)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestTemporalDoesNotTouchExplicitTierOrRestrictedSource 钉住「更早的分支」不被这一位
|
||||
// 影响:显式档位(人工入口)与受限来源(群聊/陌生人)都排在第 1/3 步。
|
||||
func TestTemporalDoesNotTouchExplicitTierOrRestrictedSource(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := context.Background()
|
||||
store := newTestStore(t)
|
||||
|
||||
explicit := habitItem("谢谢啦", tidyTestTime(t), 0.9)
|
||||
explicit.RetentionTier = RetentionLong
|
||||
explicit.Temporal = TemporalOneOff
|
||||
got, err := store.Add(ctx, explicit)
|
||||
if err != nil {
|
||||
t.Fatalf("Add(explicit long): %v", err)
|
||||
}
|
||||
if tier, _ := readRetentionColumns(t, store, got.ID); tier != RetentionLong {
|
||||
t.Fatalf("显式 long + one_off 落库 = %q, want long(调用方显式档位不许被推翻)", tier)
|
||||
}
|
||||
|
||||
restricted := habitItem("今天下雨了", tidyTestTime(t), 0.9)
|
||||
restricted.Temporal = TemporalOneOff
|
||||
restricted.SourceConversation = FormatSourceConversation("sess-group-1", "msg-1")
|
||||
got, err = store.Add(ctx, restricted)
|
||||
if err != nil {
|
||||
t.Fatalf("Add(restricted): %v", err)
|
||||
}
|
||||
tier, expires := readRetentionColumns(t, store, got.ID)
|
||||
if tier != RetentionTierUnset || expires != "" {
|
||||
t.Fatalf("受限来源 + one_off 落库 = (%q, %q), want (未分型, 空)", tier, expires)
|
||||
}
|
||||
}
|
||||
|
||||
// readTemporalColumn 直读一行的 `temporal` 列(该列与 expires_at 一样是**只写不读**
|
||||
// 的列:四条列表读路径的 SELECT 不带它,见 store.go 的 Temporal 注释)。
|
||||
func readTemporalColumn(t *testing.T, store *Store, id string) TemporalKind {
|
||||
t.Helper()
|
||||
var raw string
|
||||
if err := store.db.QueryRowContext(context.Background(),
|
||||
`SELECT temporal FROM memory_items WHERE id = ?`, id).Scan(&raw); err != nil {
|
||||
t.Fatalf("read temporal column %s: %v", id, err)
|
||||
}
|
||||
return TemporalKind(raw)
|
||||
}
|
||||
|
||||
// temporalFieldSites 是**允许**读取 `.Temporal` 的全部生产代码位置(文件 + 行内片段)。
|
||||
//
|
||||
// 只有四类,缺一不可、多一不许(多出来的那条就是「接线」):
|
||||
//
|
||||
// ① 写入侧的字段校验(store_temporal.go 的 validateTemporal,两行);
|
||||
// ② 写入侧的列值编码(store_temporal.go 的 temporalColumn);
|
||||
// ③ 产出侧的构造(llmextractor.go 把模型输出归一后放进候选条目)。
|
||||
//
|
||||
// 为什么用「片段」而不是「文件」做粒度:按文件放行会让**同一文件里**新写的接线悄悄
|
||||
// 溜过去(例如在 store_temporal.go 里加一句 `if item.Temporal == …`)。按片段放行则
|
||||
// 任何新表达式都必须先改这张表 —— 而改这张表就是一次自觉的接线决定。
|
||||
func temporalFieldSites() []struct{ file, snippet string } {
|
||||
return []struct{ file, snippet string }{
|
||||
{"store_temporal.go", "it.Temporal.valid()"},
|
||||
{"store_temporal.go", "ErrInvalidTemporal, it.Temporal"},
|
||||
{"store_temporal.go", "string(it.Temporal)"},
|
||||
{"llmextractor.go", "normalizeTemporal(c.Temporal)"},
|
||||
}
|
||||
}
|
||||
|
||||
// TestTemporalIsNotWiredIntoJudgement 是**源码级断言**:`temporal` 只许被记录,
|
||||
// **不许被判定读**。它回答的是「零影响」能不能被后来人无声破坏 ——
|
||||
// retention_test.go 的同类断言只钉住 `judgeExtractionRetention` 的调用点,管不到
|
||||
// 「在异步审查侧拿 `item.Temporal` 改判」这种接线方式。
|
||||
//
|
||||
// 复现的缺口(r1 复审变异 C 实测):在 `preinsert.go` 的 `applyVerdict` 入口插一句
|
||||
// `if item.Temporal == TemporalOneOff { …setIngestRetention(temp)… }`,**整个 memory
|
||||
// 包全绿** —— 那时没有任何用例察觉。异步侧恰恰是最容易被随手接线的地方(它拿到的
|
||||
// 是**已落库**的行),因此这条断言必须存在。
|
||||
//
|
||||
// 判据:扫生产代码(非 `_test.go`、非注释行)里所有含 `.Temporal` 的行,逐行要求
|
||||
// 命中 temporalFieldSites 的某一条;否则报**文件 + 行号 + 表达式片段**(不只报个数)。
|
||||
// 同时校验 allowlist 的每一条**确实命中过**,防止它老化成一张空头许可证。
|
||||
func TestTemporalIsNotWiredIntoJudgement(t *testing.T) {
|
||||
t.Parallel()
|
||||
files, err := os.ReadDir(".")
|
||||
if err != nil {
|
||||
t.Fatalf("read package dir: %v", err)
|
||||
}
|
||||
allowed := temporalFieldSites()
|
||||
hit := make([]bool, len(allowed))
|
||||
var violations []string
|
||||
for _, f := range files {
|
||||
name := f.Name()
|
||||
if f.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
|
||||
continue
|
||||
}
|
||||
src, err := os.ReadFile(name)
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", name, err)
|
||||
}
|
||||
for i, line := range strings.Split(string(src), "\n") {
|
||||
trimmed := strings.TrimSpace(line)
|
||||
if strings.HasPrefix(trimmed, "//") || !strings.Contains(trimmed, ".Temporal") {
|
||||
continue
|
||||
}
|
||||
ok := false
|
||||
for j, site := range allowed {
|
||||
if name == site.file && strings.Contains(trimmed, site.snippet) {
|
||||
hit[j] = true
|
||||
ok = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
violations = append(violations, fmt.Sprintf("%s:%d: %s", name, i+1, trimmed))
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(violations) > 0 {
|
||||
t.Fatalf("temporal 被接进了判定(裁决 D:它只许被记录,不许被判定读)。"+
|
||||
"若这是有意的接线,先拿到模型真实标签分布并改 temporal.go 头注、再改本断言的 allowlist:\n%s",
|
||||
strings.Join(violations, "\n"))
|
||||
}
|
||||
for j, site := range allowed {
|
||||
if !hit[j] {
|
||||
t.Fatalf("allowlist 项 %s: %q 已不存在 —— 这张表老化了,请同步更新"+
|
||||
"(否则它只是一张空头许可证)", site.file, site.snippet)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestNormalizeTemporal 钉住归一化口径:**只认四个字面值**,其余(空 / 中文 / 自造 /
|
||||
// 拼写变体)一律 unknown。
|
||||
//
|
||||
// 不做同义词映射是刻意的:将来接线时猜同义词的代价是单向的(猜成 one_off 就删记忆),
|
||||
// 而「拿不准一律 unknown」才是 fail-safe。
|
||||
func TestNormalizeTemporal(t *testing.T) {
|
||||
t.Parallel()
|
||||
cases := []struct {
|
||||
raw string
|
||||
want TemporalKind
|
||||
}{
|
||||
{"one_off", TemporalOneOff},
|
||||
{"ONE_OFF", TemporalOneOff},
|
||||
{" durable \n", TemporalDurable},
|
||||
{"recurring", TemporalRecurring},
|
||||
{"unknown", TemporalUnknown},
|
||||
{"", TemporalUnknown},
|
||||
{" ", TemporalUnknown},
|
||||
{"一次性", TemporalUnknown},
|
||||
{"one-off", TemporalUnknown},
|
||||
{"oneoff", TemporalUnknown},
|
||||
{"forever", TemporalUnknown},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := normalizeTemporal(tc.raw); got != tc.want {
|
||||
t.Fatalf("normalizeTemporal(%q) = %q, want %q", tc.raw, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestTemporalKindClosedSet 钉住闭集本身:四个业务值 + 未分型都合法,其他都不合法
|
||||
// (Add 的 validate 会拒掉它们 —— 那是程序错误,不是模型输出)。
|
||||
func TestTemporalKindClosedSet(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, ok := range temporalAllKinds() {
|
||||
if !ok.valid() {
|
||||
t.Fatalf("%q 应在闭集内", ok)
|
||||
}
|
||||
}
|
||||
for _, bad := range []TemporalKind{"one-off", "sometimes", "ONE_OFF", "float"} {
|
||||
if bad.valid() {
|
||||
t.Fatalf("%q 不应在闭集内", bad)
|
||||
}
|
||||
}
|
||||
if TemporalUnknown.assigned() != true || TemporalUnset.assigned() != false {
|
||||
t.Fatal("assigned() 只应对非空串为真(「未分型」的唯一判据)")
|
||||
}
|
||||
// 非法值必须被写入路径拒掉(不是静默落库成脏列值)。
|
||||
item := habitItem("一条正文", tidyTestTime(t), 0.9)
|
||||
item.Temporal = TemporalKind("sometimes")
|
||||
if err := item.normalize(); err == nil {
|
||||
t.Fatal("validate 接受了非法的时间性位(应返回 ErrInvalidTemporal)")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLLMExtractorReadsTemporal 钉住产出侧:提取器**真的**在读模型给的这一位,
|
||||
// 且非法 / 缺失值不产生错误、只归 unknown(不拖累同批其他候选)。观测面的数据
|
||||
// 质量由这条用例守住。
|
||||
func TestLLMExtractorReadsTemporal(t *testing.T) {
|
||||
t.Parallel()
|
||||
adapter := &mockAdapter{fn: func(_ context.Context, _ model.Request, _ model.Options) (model.Response, error) {
|
||||
return model.Response{Content: `[
|
||||
{"content":"候选一","temporal":"one_off"},
|
||||
{"content":"候选二","temporal":"durable"},
|
||||
{"content":"候选三","temporal":"Recurring"},
|
||||
{"content":"候选四","temporal":"forever"},
|
||||
{"content":"候选五"}
|
||||
]`}, nil
|
||||
}}
|
||||
ex := NewLLMExtractor(adapter, "persona.a", "role.1")
|
||||
items, err := ex.Extract(context.Background(), []model.Message{
|
||||
model.TextMessage(model.RoleUser, "随便聊两句"),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Extract: %v(非法 temporal 绝不能让整批提取失败)", err)
|
||||
}
|
||||
want := map[string]TemporalKind{
|
||||
"候选一": TemporalOneOff,
|
||||
"候选二": TemporalDurable,
|
||||
"候选三": TemporalRecurring,
|
||||
"候选四": TemporalUnknown,
|
||||
"候选五": TemporalUnknown,
|
||||
}
|
||||
if len(items) != len(want) {
|
||||
t.Fatalf("候选数 = %d, want %d", len(items), len(want))
|
||||
}
|
||||
for _, it := range items {
|
||||
if it.Temporal != want[it.Content] {
|
||||
t.Fatalf("%q 的 temporal = %q, want %q", it.Content, it.Temporal, want[it.Content])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestExtractionPromptCarriesTemporalEnum 钉住「提示词与闭集不漂移」:模型能看到的
|
||||
// 取值必须与 normalizeTemporal 认的四个值逐字一致(提示词只是辅助,但取值口径漂了
|
||||
// 就会让每条候选都被归成 unknown,观测面等于白留)。
|
||||
func TestExtractionPromptCarriesTemporalEnum(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, want := range []string{"temporal", "one_off", "recurring", "durable", "unknown"} {
|
||||
if !strings.Contains(extractSystemPrompt, want) {
|
||||
t.Fatalf("提取提示词里缺 %q —— 模型无从给出这一位", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user