Compare commits
149
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7f7171ac14 | ||
|
|
0b2b4f01d8 | ||
|
|
37dcebfce4 | ||
|
|
d7a73d7e6c | ||
|
|
9a4a734c19 | ||
|
|
38d7ef147d | ||
|
|
ab1452d06b | ||
|
|
1c7882ce34 | ||
|
|
3cf3858f09 | ||
|
|
33e16c1a61 | ||
|
|
c84d968b02 | ||
|
|
f4417c2f4d | ||
|
|
03cac702a8 | ||
|
|
0499c82965 | ||
|
|
d117102088 | ||
|
|
1aaab764ba | ||
|
|
2ac7c9d5a1 | ||
|
|
66d5049151 | ||
|
|
f979bd6ffc | ||
|
|
8ea82fbec3 | ||
|
|
2862f68631 | ||
|
|
b8d77547de | ||
|
|
79019bfc40 | ||
|
|
a5bc27c3a4 | ||
|
|
83c41963cf | ||
|
|
3533e55801 | ||
|
|
a293f7b784 | ||
|
|
754976db52 | ||
|
|
c954aa2917 | ||
|
|
772a597a53 | ||
|
|
1f30474cf3 | ||
|
|
a1021bb70a | ||
|
|
e0412747f0 | ||
|
|
5f63b35602 | ||
|
|
3e29617cbe | ||
|
|
941b7eec32 | ||
|
|
71d5f2a7cd | ||
|
|
f6c373ea94 | ||
|
|
978f27a164 | ||
|
|
0bfa7a4bc1 | ||
|
|
25f68831fd | ||
|
|
42fafc495f | ||
|
|
d4b8688148 | ||
|
|
bd399dd007 | ||
|
|
ffc5b108c6 | ||
|
|
45726d26a7 | ||
|
|
c015febb49 | ||
|
|
44fd0e95b4 | ||
|
|
b2a016e90f | ||
|
|
cee68592e3 | ||
|
|
c3747755b6 | ||
|
|
4bbf59dabe | ||
|
|
0c0494dabd | ||
|
|
a214cf4a0e | ||
|
|
a2f355a994 | ||
|
|
fa3490e794 | ||
|
|
05100339f8 | ||
|
|
00747be2db | ||
|
|
08a649792e | ||
|
|
584fe37c35 | ||
|
|
525f11f531 | ||
|
|
8f57bd0fae | ||
|
|
211d516e5f | ||
|
|
284584c578 | ||
|
|
bdc18f6177 | ||
|
|
b017c35d37 | ||
|
|
c12f55ef71 | ||
|
|
e52f335998 | ||
|
|
24d6c46065 | ||
|
|
e42d19cfd9 | ||
|
|
e5bd7c7576 | ||
|
|
3594456df3 | ||
|
|
3fa7850f01 | ||
|
|
827de4f65a | ||
|
|
808b9862c9 | ||
|
|
b69cc01d52 | ||
|
|
80d0a37116 | ||
|
|
793bfefc61 | ||
|
|
db6ab564dc | ||
|
|
339642b2c8 | ||
|
|
c2683fd6a9 | ||
|
|
1cdeb4a54b | ||
|
|
9236d8d4b4 | ||
|
|
43a9cc8751 | ||
|
|
4565026b09 | ||
|
|
b13cdea910 | ||
|
|
88d466d156 | ||
|
|
faf71cbe99 | ||
|
|
113e6e8274 | ||
|
|
de0ddf4b8b | ||
|
|
d0558e1fd5 | ||
|
|
12f808d0e1 | ||
|
|
44ccb69ca5 | ||
|
|
95cc81db4b | ||
|
|
f8ffcde0f4 | ||
|
|
0afff5734e | ||
|
|
ef4f379736 | ||
|
|
aab877a13c | ||
|
|
1cfb17ac5e | ||
|
|
8364ff1b36 | ||
|
|
57bdf7fa03 | ||
|
|
d2348eda43 | ||
|
|
467d9b4ac1 | ||
|
|
ef64da6df2 | ||
|
|
ae39e1ce8a | ||
|
|
a1c9fc1631 | ||
|
|
f37f5e744e | ||
|
|
0bdcae2b91 | ||
|
|
1b6920e8e1 | ||
|
|
a377a7f667 | ||
|
|
e282a41bab | ||
|
|
0959af388b | ||
|
|
6d724dc937 | ||
|
|
6e21eef6da | ||
|
|
5b9f75cc7f | ||
|
|
ba81121efa | ||
|
|
5565ec8a9b | ||
|
|
95bb930bd6 | ||
|
|
e900e4073f | ||
|
|
66d8e32bc6 | ||
|
|
13ced12ce9 | ||
|
|
227b2979dd | ||
|
|
cb450e9c9d | ||
|
|
28f6951061 | ||
|
|
9b7b969cd3 | ||
|
|
dfc6f580eb | ||
|
|
a39e5c7e23 | ||
|
|
ce38465dbd | ||
|
|
a162e2769e | ||
|
|
13cf7d2088 | ||
|
|
c34178c3c3 | ||
|
|
cbbdd9a708 | ||
|
|
6e752aa904 | ||
|
|
63ceb4a11c | ||
|
|
e9fce11a1b | ||
|
|
6db0ffa7d4 | ||
|
|
0e4fb59e1a | ||
|
|
b551c55011 | ||
|
|
aa8f503ae0 | ||
|
|
82ef904257 | ||
|
|
886c0c20e2 | ||
|
|
31bdf3403b | ||
|
|
2a8fc6494e | ||
|
|
f0cd747873 | ||
|
|
fe8126dd85 | ||
|
|
0634e4eb1d | ||
|
|
ba3ccd3e12 | ||
|
|
e98565f0c9 | ||
|
|
90af029c16 |
+14
@@ -35,3 +35,17 @@ bin/
|
||||
# 构建产物(worker 曾把 7.9M 二进制留在工作区,2026-09-21)
|
||||
go/zhiyi-cli
|
||||
go/zhiyid
|
||||
|
||||
# 临时工件(cron list dump,随时可 `hermes cron list` 重现,不入库)
|
||||
cron_raw.txt
|
||||
|
||||
# 改动前备份快照不进 git(git 本身就是版本历史)
|
||||
*.bak.*
|
||||
|
||||
# 探针/临时构建产物(2026-10-14 t_3e98b65a 调查时发现 17MB 残留未清)
|
||||
/go/*-probe
|
||||
/go/rulefirst-probe
|
||||
|
||||
# 临时构建/验证工件(t_5f822020 清理:quantify/test_one 二进制 + verify.go 探针)
|
||||
/go/tmp/
|
||||
/verify.go
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
# ─── 变量 ────────────────────────────────────────────
|
||||
GO_CMD := go
|
||||
RUST_CMD := cargo
|
||||
GOFMT_CMD := gofmt
|
||||
GO_DIR := go
|
||||
RUST_DIR := rust
|
||||
BINARY_GO := $(GO_DIR)/cmd/zhiyid/zhiyid
|
||||
@@ -81,6 +82,15 @@ deploy-compose: docker-build
|
||||
test:
|
||||
cd $(GO_DIR) && $(GO_CMD) test ./... -v -count=1
|
||||
|
||||
# 格式校验:gofmt 不合规即报错(gofmt -l 列出文件 → 非空则 exit 1)
|
||||
fmt-check:
|
||||
@cd $(GO_DIR) && $(GOFMT_CMD) -l . | tee /tmp/.gofmt_files > /dev/null; \
|
||||
if [ -s /tmp/.gofmt_files ]; then \
|
||||
echo "❌ gofmt 不合规文件($(GOFMT_CMD) -l . 非空):"; \
|
||||
$(GOFMT_CMD) -l . ; \
|
||||
echo " 修复: cd $(GO_DIR) && $(GOFMT_CMD) -w ."; exit 1; \
|
||||
else echo "✅ gofmt 合规(0 文件)"; fi
|
||||
|
||||
test-go: test
|
||||
|
||||
test-rust:
|
||||
|
||||
@@ -426,7 +426,10 @@ python3 -c "from plugins.memory.zhiyi import HermesZhiYiMemoryProvider; \
|
||||
| POST | `/api/v1/recall` | 语义检索(支持 mode=hybrid\|keyword\|semantic) |
|
||||
| POST | `/api/v1/batch-commit` | 批量提交 |
|
||||
| GET | `/api/v1/memories` | 列出记忆(分页) |
|
||||
| POST | `/api/v1/feedback` | 反馈(useful / not-useful / deprecate) |
|
||||
| POST | `/api/v1/feedback/useful` | 标记记忆有用(GA-P0-1 写 human_useful) |
|
||||
| POST | `/api/v1/feedback/not-useful` | 标记记忆无用(写 human_not_useful_count) |
|
||||
| POST | `/api/v1/feedback/deprecate` | 标记过时 |
|
||||
| POST | `/api/v1/feedback/correct` | 提交修正 |
|
||||
|
||||
### 统计
|
||||
|
||||
|
||||
@@ -197,7 +197,6 @@ def stats(stat_type, json_flag):
|
||||
if "metrics" in data:
|
||||
m = data["metrics"]
|
||||
click.echo(f"\n📊 自优化指标:")
|
||||
click.echo(f" 召回命中率: {m.get('recall_hit_rate', '?'):.1%}")
|
||||
click.echo(f" 召回有用率: {m.get('recall_usefulness_rate', '?'):.1%}")
|
||||
click.echo(f" 记忆总数: {m.get('total_memories', '?')}")
|
||||
|
||||
@@ -429,7 +428,7 @@ def _repl_with_skin(c: ZhiYiClient, skin):
|
||||
["记忆数", str(s.get("total_memories", "?"))],
|
||||
["图谱节点", str(g.get("node_count", "?"))],
|
||||
["图谱边", str(g.get("edge_count", "?"))],
|
||||
["召回命中率", f"{m.get('recall_hit_rate', '?'):.1%}"],
|
||||
["召回有用率", f"{m.get('recall_usefulness_rate', '?'):.1%}"],
|
||||
],
|
||||
)
|
||||
elif cmd == "graph" and args and args[0] == "navigate":
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
[152] /home/muc/.hermes/kanban/workspaces/t_492e3f22/ac-evidence/t492-DEF-152-20261016-184003.json total=152 PASS=74 id_hits=7 fp=2318948a910f6d70de6be063216c78089c4315bd p95=2630ms errs=0
|
||||
[golden] /home/muc/.hermes/kanban/workspaces/t_492e3f22/ac-evidence/t492-DEF-golden-20261016-184003.json pass=14/14 fail=0
|
||||
[probe10] 牧尘工作所在的县是哪个: n=20 v>0=0 -> []
|
||||
[probe10] 淇县: n=20 v>0=1 -> ['mem_1792088552819293505']
|
||||
[probe10] 招商项目台账: n=20 v>0=0 -> []
|
||||
[probe10] 生物制造产业专班: n=20 v>0=0 -> []
|
||||
[probe10] 小怡的工作笔记在哪: n=15 v>0=0 -> []
|
||||
[probe10] 昨天做了什么: n=20 v>0=0 -> []
|
||||
[probe10] 飞书怎么发语音: n=20 v>0=0 -> []
|
||||
[probe10] 家服怎么连: n=20 v>0=0 -> []
|
||||
[probe10] 织忆怎么部署: n=20 v>0=1 -> ['mem_1791740271337572997']
|
||||
[probe10] 记忆保护名单: n=20 v>0=0 -> []
|
||||
DONE DEF at 20261016-184003
|
||||
@@ -0,0 +1,13 @@
|
||||
[152] /home/muc/.hermes/kanban/workspaces/t_492e3f22/ac-evidence/t492-NOV-152-20261016-184835.json total=152 PASS=74 id_hits=7 fp=2318948a910f6d70de6be063216c78089c4315bd p95=812ms errs=0
|
||||
[golden] /home/muc/.hermes/kanban/workspaces/t_492e3f22/ac-evidence/t492-NOV-golden-20261016-184835.json pass=14/14 fail=0
|
||||
[probe10] 牧尘工作所在的县是哪个: n=20 v>0=0 -> []
|
||||
[probe10] 淇县: n=20 v>0=1 -> ['mem_1792088552819293505']
|
||||
[probe10] 招商项目台账: n=20 v>0=0 -> []
|
||||
[probe10] 生物制造产业专班: n=20 v>0=0 -> []
|
||||
[probe10] 小怡的工作笔记在哪: n=15 v>0=0 -> []
|
||||
[probe10] 昨天做了什么: n=20 v>0=0 -> []
|
||||
[probe10] 飞书怎么发语音: n=20 v>0=0 -> []
|
||||
[probe10] 家服怎么连: n=20 v>0=0 -> []
|
||||
[probe10] 织忆怎么部署: n=20 v>0=1 -> ['mem_1791740271337572997']
|
||||
[probe10] 记忆保护名单: n=20 v>0=0 -> []
|
||||
DONE NOV at 20261016-184835
|
||||
@@ -0,0 +1,13 @@
|
||||
[152] /home/muc/.hermes/kanban/workspaces/t_492e3f22/ac-evidence/t492-PRE-152-20261016-183449.json total=152 PASS=74 id_hits=7 fp=2318948a910f6d70de6be063216c78089c4315bd p95=809ms errs=0
|
||||
[golden] /home/muc/.hermes/kanban/workspaces/t_492e3f22/ac-evidence/t492-PRE-golden-20261016-183449.json pass=14/14 fail=0
|
||||
[probe10] 牧尘工作所在的县是哪个: n=20 v>0=0 -> []
|
||||
[probe10] 淇县: n=20 v>0=1 -> ['mem_1792088552819293505']
|
||||
[probe10] 招商项目台账: n=20 v>0=0 -> []
|
||||
[probe10] 生物制造产业专班: n=20 v>0=0 -> []
|
||||
[probe10] 小怡的工作笔记在哪: n=15 v>0=0 -> []
|
||||
[probe10] 昨天做了什么: n=20 v>0=0 -> []
|
||||
[probe10] 飞书怎么发语音: n=20 v>0=0 -> []
|
||||
[probe10] 家服怎么连: n=20 v>0=0 -> []
|
||||
[probe10] 织忆怎么部署: n=20 v>0=1 -> ['mem_1791740271337572997']
|
||||
[probe10] 记忆保护名单: n=20 v>0=0 -> []
|
||||
DONE PRE at 20261016-183449
|
||||
@@ -0,0 +1,13 @@
|
||||
[152] /home/muc/.hermes/kanban/workspaces/t_492e3f22/ac-evidence/t492-RBK-152-20261016-190913.json total=152 PASS=74 id_hits=7 fp=2318948a910f6d70de6be063216c78089c4315bd p95=931ms errs=0
|
||||
[golden] /home/muc/.hermes/kanban/workspaces/t_492e3f22/ac-evidence/t492-RBK-golden-20261016-190913.json pass=14/14 fail=0
|
||||
[probe10] 牧尘工作所在的县是哪个: n=20 v>0=0 -> []
|
||||
[probe10] 淇县: n=20 v>0=1 -> ['mem_1792088552819293505']
|
||||
[probe10] 招商项目台账: n=20 v>0=0 -> []
|
||||
[probe10] 生物制造产业专班: n=20 v>0=0 -> []
|
||||
[probe10] 小怡的工作笔记在哪: n=15 v>0=0 -> []
|
||||
[probe10] 昨天做了什么: n=20 v>0=0 -> []
|
||||
[probe10] 飞书怎么发语音: n=20 v>0=0 -> []
|
||||
[probe10] 家服怎么连: n=20 v>0=0 -> []
|
||||
[probe10] 织忆怎么部署: n=20 v>0=1 -> ['mem_1791740271337572997']
|
||||
[probe10] 记忆保护名单: n=20 v>0=0 -> []
|
||||
DONE RBK at 20261016-190913
|
||||
@@ -0,0 +1,87 @@
|
||||
# t_492e3f22 · fuseQuality V 值分支 env 门(ZHIYI_V_FUSE_ENABLE)— A/B 证据包
|
||||
|
||||
次症 C:给 Go 端 fuseQuality 的 V 值分支加 env 门。**默认行为逐位保持现状**;`ZHIYI_V_FUSE_ENABLE=1`
|
||||
关闭 V 分支(v>0 时不再用 0.5v+0.5imp / 0.3v+0.3imp+0.4raw 加权,退化为 untrusted→min(imp,1)、
|
||||
trusted→min(0.4imp+0.6raw,1))。本包 = 代码 + 测试 + 双口径 A/B 证据。
|
||||
|
||||
## 结论(2026-10-16 实测)
|
||||
|
||||
| AC | 判据 | 结果 |
|
||||
|---|---|---|
|
||||
| AC1 默认不碰 | PRE(旧二进制) ≡ DEF(新二进制默认):152 集 verdict 指纹、top5 顺序、probe10 top20、golden | ✅ 全同(指纹 2318948a…;golden 14/14) |
|
||||
| AC2 翻转证据 | DEF vs NOV(env=1):verdict 指纹同;probe10 10 条 affected=0;两条受影响 query top50 顺序逐位全同(fp 47e228e8 / 9dd57897 各两边一致);v>0 条目 rank 零移动 | ✅(排名变化 = 0,见「解读」) |
|
||||
| AC4 受影响条数 | v>0 条数独立复算(4 个 tag 集合完全一致):152×top5 = 2/760 (0.26%);probe10×top20 = 2/195 (1.03%) | ✅ 实测 2 条,任务表预期 2–3(≈1.5%,V 按 0.01/天衰减) |
|
||||
| AC5 回滚复核 | RBK(新二进制重启·默认) == DEF 指纹(verdict 层 2318948a + probe10 全同 + golden 14/14) | ✅(仅 2 条 v=0 Gitea top1 互漂,跨跑 usage_track 漂移,见「已知噪声」) |
|
||||
| AC6 异源复算 | 第二张口径(independent_recheck.py,sha256 顺序指纹 + 逐条 v>0 集合复算)与主口径一致,无矛盾 | ✅ PASS |
|
||||
|
||||
## 改动文件
|
||||
|
||||
- `go/internal/storage/quality_fusion.go` — `vFuseUseV = os.Getenv("ZHIYI_V_FUSE_ENABLE") != "1"`(进程级,同 ZHIYI_PROOF_FALLBACK 模式),V 分支条件 `if vFuseUseV && vValue > 0`
|
||||
- `go/internal/storage/quality_fusion_test.go` — `TestFuseQuality_VGateOn`(门开:v>0 条 fused 0.85 vs v=0 条 0.725,排序保持)+ `TestFuseQuality_VGateOff`(门关:两者同值)
|
||||
- 单测:`cd go && go test ./internal/storage/ -run 'TestFuseQuality' -v` → 3/3 PASS(2026-10-16 19:35 复跑)
|
||||
|
||||
## 实例配置(隔离:独立数据副本,不碰主库)
|
||||
|
||||
- 数据:`/tmp/zyvfuse-t492e3f22/data`(/var/lib/memoryweave 全量副本,symbolic link 已解)
|
||||
- sidecar:`zhiyi-consolidate --mode socket --socket /tmp/zyvfuse-t492e3f22/cons.sock`
|
||||
- 4 实例:PRE :7891(旧二进制) / DEF :7892(新·默认) / NOV :7893(新·env=1,/proc environ 实证) / RBK :7892 重启(新·默认)
|
||||
- 评测集:152 条(zhiyi-loop-runner 池)+ golden 14 + probe10(淇县/织忆怎么部署/记忆保护名单 等卡表同源)
|
||||
|
||||
## 受影响 3 样本表(AC2,卡表口径)
|
||||
|
||||
| query | v>0(任务表→实测) | v>0 条目 | DEF→NOV 排名变化 |
|
||||
|---|---|---|---|
|
||||
| 淇县 | 0 → 1 | mem_1792088552819293505 (v=1.0, rank1) | 0(top50 逐位全同) |
|
||||
| 织忆怎么部署 | 2 → 1 | mem_1791740271337572997 (v=1.0) | 0(top50 逐位全同) |
|
||||
| 记忆保护名单 | 1 → 0 | (本次 top20 内无 v>0) | — |
|
||||
|
||||
**解读(为什么排名变化=0)**:recall 排序 base = 0.7×cosine + 0.3×fusedQuality。V 门控只改 v>0 条的
|
||||
fused 分(untrusted 时 0.5v+0.5imp → min(imp,1)),Δbase 上限 0.3×Δfused≈0.15;本数据分布下
|
||||
cosine 主导的条间 margin > Δbase ⇒ 无换位。门控在**融合分轴**生效(单测证明公式差),
|
||||
**排序轴**在本数据规模上实测零扰动 —— 这正是「默认不碰、关也不破」的安全证据。
|
||||
v>0 条数随时间漂(V 衰减 0.01/天 + seen-count 变化):任务表 3 → 实测 2。
|
||||
|
||||
## 已知噪声(与门控无关,如实记录)
|
||||
|
||||
- 152 集中 2 条 Gitea query 的 top1 在跨跑间互换(mem_1792088552817004309 ↔ mem_1792088552816998158,
|
||||
两侧 v=0、raw=0):DEF 跑 / NOV 跑 / RBK 跑各自写 usage_track(seen-count +1、last_recalled_at 刷新),
|
||||
imp 微漂 ⇒ 同分对 tie 换位。verdict/指纹层不受影响(4 tag verdict 指纹全同 2318948a)。
|
||||
- 152 集 P95:PRE=809ms / DEF=2630ms(冷启动+首轮 warmup)/ NOV≈951 / RBK=931 —— AC 判据为 ±20% 口径
|
||||
以稳态(RBK/NOV)为准,DEF 高值系冷启动,非门控效应。
|
||||
|
||||
## 复算命令
|
||||
|
||||
```bash
|
||||
# 单测
|
||||
cd /home/muc/src/memoryweave/go && go test ./internal/storage/ -run 'TestFuseQuality' -v
|
||||
# 异源复算(本目录 raw/*.json)
|
||||
python3 <kanban-workspace>/harness/independent_recheck.py # 输出 independent_recheck_out.json
|
||||
python3 <kanban-workspace>/harness/diffrun.py DEF NOV # 主口径 diff
|
||||
```
|
||||
|
||||
## 部署提示(本卡不含生产动作)
|
||||
|
||||
- 生产 zhiyid(systemd, :7821)与 zhiyi-consolidate 不动;本卡只验证行为等价 + 门控生效。
|
||||
- 真要关 V 分支:`Environment=ZHIYI_V_FUSE_ENABLE=1` 加进 deploy/zhiyid.service + 重启(需另行提卡审批)。
|
||||
- 回滚 = 删该行/置 0,重启即恢复现状(RBK 证据)。
|
||||
|
||||
## teardown + 零残留判据(19:44 补,跨卡通知 t_004cc147 内存告警处置要求)
|
||||
|
||||
测试栈(27G:data/ 副本 + graph.db 447M + 双 zhiyid 守护 + sidecar)已全部下线:
|
||||
|
||||
- 双孤儿 zhiyid(PID 347191 :7893 / 367265 :7892)已由 prof-cloud SIGTERM(19:15 内存告警处置)
|
||||
- 本侧:sidecar(cons.sock,data 副本)停掉;`/tmp/zyvfuse-t492e3f22` 整目录删除
|
||||
(evidence 先全量落盘 `ac-evidence/` 与本目录 raw/,再删)
|
||||
- 顺带清:`/tmp/dryrun-dir`(2.6G) `/tmp/mem-copy.lance`(604M) `spike*`(441M×2+小文件)
|
||||
—— 删前确认:lsof 无占用、无看板卡引用、mtime 10-11/10-12
|
||||
|
||||
终验输出(19:44):
|
||||
```
|
||||
ps -C zhiyid -o pid,args → 仅表头,无进程(exit 1)
|
||||
du -sh /tmp/zyvfuse-* → No such file or directory
|
||||
du -sh /tmp/dryrun-dir /tmp/mem-copy.lance /tmp/spike* → 全部 No such file
|
||||
free -h → available 5.3Gi(告警前 <1G)
|
||||
```
|
||||
|
||||
**判据补录(本卡验收新增)**:`ps -C zhiyid -o pid,args` 为空(测试栈守护零残留)+
|
||||
`du -sh /tmp/zyvfuse-*` 无残留 —— 已通过。
|
||||
@@ -0,0 +1,230 @@
|
||||
{
|
||||
"a": "DEF",
|
||||
"b": "NOV",
|
||||
"files": {
|
||||
"a": {
|
||||
"152": [
|
||||
"at",
|
||||
"tag",
|
||||
"base",
|
||||
"total",
|
||||
"pass",
|
||||
"fail",
|
||||
"metrics",
|
||||
"latency_ms",
|
||||
"fail_mode",
|
||||
"recall_errors",
|
||||
"fingerprint",
|
||||
"namespace",
|
||||
"top_k",
|
||||
"results"
|
||||
],
|
||||
"probe10": [
|
||||
"at",
|
||||
"tag",
|
||||
"base",
|
||||
"top_k",
|
||||
"rows"
|
||||
],
|
||||
"golden": [
|
||||
"at",
|
||||
"tag",
|
||||
"base",
|
||||
"keyword_pass",
|
||||
"keyword_fail",
|
||||
"keyword_total",
|
||||
"recall_at_5",
|
||||
"mrr",
|
||||
"items"
|
||||
]
|
||||
},
|
||||
"b": [
|
||||
"152",
|
||||
"probe10",
|
||||
"golden"
|
||||
]
|
||||
},
|
||||
"152": {
|
||||
"fp_a": "2318948a910f6d70de6be063216c78089c4315bd",
|
||||
"fp_b": "2318948a910f6d70de6be063216c78089c4315bd",
|
||||
"fp_same": true,
|
||||
"pass_a": 74,
|
||||
"pass_b": 74,
|
||||
"id_hits_a": 7,
|
||||
"id_hits_b": 7,
|
||||
"p95_a_ms": 2630,
|
||||
"p95_b_ms": 812,
|
||||
"changed_queries": 1,
|
||||
"changed_detail": {
|
||||
"局域网里访问 Gitea 家服连哪个 IP": {
|
||||
"kind": "probe",
|
||||
"changed": [
|
||||
"top5"
|
||||
],
|
||||
"a_top5": [
|
||||
"mem_1792088552817004309",
|
||||
"mem_1789136383983279469",
|
||||
"ep_1786521524260755589",
|
||||
"mem_1789150776299341327",
|
||||
"mem_1789737118121867083"
|
||||
],
|
||||
"b_top5": [
|
||||
"mem_1792088552816998158",
|
||||
"mem_1789136383983279469",
|
||||
"ep_1786521524260755589",
|
||||
"mem_1789150776299341327",
|
||||
"mem_1789737118121867083"
|
||||
]
|
||||
}
|
||||
},
|
||||
"v0_rank_shifts": []
|
||||
},
|
||||
"probe10": {
|
||||
"rows": [
|
||||
{
|
||||
"query": "牧尘工作所在的县是哪个",
|
||||
"n_a": 20,
|
||||
"n_b": 20,
|
||||
"set_added": [],
|
||||
"set_removed": [],
|
||||
"order_diff_positions": 0,
|
||||
"v_pos_a": 0,
|
||||
"v_pos_b": 0,
|
||||
"v_pos_ids_a": [],
|
||||
"v_pos_ids_b": [],
|
||||
"v_rank_moved": []
|
||||
},
|
||||
{
|
||||
"query": "淇县",
|
||||
"n_a": 20,
|
||||
"n_b": 20,
|
||||
"set_added": [],
|
||||
"set_removed": [],
|
||||
"order_diff_positions": 0,
|
||||
"v_pos_a": 1,
|
||||
"v_pos_b": 1,
|
||||
"v_pos_ids_a": [
|
||||
"mem_1792088552819293505"
|
||||
],
|
||||
"v_pos_ids_b": [
|
||||
"mem_1792088552819293505"
|
||||
],
|
||||
"v_rank_moved": []
|
||||
},
|
||||
{
|
||||
"query": "招商项目台账",
|
||||
"n_a": 20,
|
||||
"n_b": 20,
|
||||
"set_added": [],
|
||||
"set_removed": [],
|
||||
"order_diff_positions": 0,
|
||||
"v_pos_a": 0,
|
||||
"v_pos_b": 0,
|
||||
"v_pos_ids_a": [],
|
||||
"v_pos_ids_b": [],
|
||||
"v_rank_moved": []
|
||||
},
|
||||
{
|
||||
"query": "生物制造产业专班",
|
||||
"n_a": 20,
|
||||
"n_b": 20,
|
||||
"set_added": [],
|
||||
"set_removed": [],
|
||||
"order_diff_positions": 0,
|
||||
"v_pos_a": 0,
|
||||
"v_pos_b": 0,
|
||||
"v_pos_ids_a": [],
|
||||
"v_pos_ids_b": [],
|
||||
"v_rank_moved": []
|
||||
},
|
||||
{
|
||||
"query": "小怡的工作笔记在哪",
|
||||
"n_a": 15,
|
||||
"n_b": 15,
|
||||
"set_added": [],
|
||||
"set_removed": [],
|
||||
"order_diff_positions": 0,
|
||||
"v_pos_a": 0,
|
||||
"v_pos_b": 0,
|
||||
"v_pos_ids_a": [],
|
||||
"v_pos_ids_b": [],
|
||||
"v_rank_moved": []
|
||||
},
|
||||
{
|
||||
"query": "昨天做了什么",
|
||||
"n_a": 20,
|
||||
"n_b": 20,
|
||||
"set_added": [],
|
||||
"set_removed": [],
|
||||
"order_diff_positions": 0,
|
||||
"v_pos_a": 0,
|
||||
"v_pos_b": 0,
|
||||
"v_pos_ids_a": [],
|
||||
"v_pos_ids_b": [],
|
||||
"v_rank_moved": []
|
||||
},
|
||||
{
|
||||
"query": "飞书怎么发语音",
|
||||
"n_a": 20,
|
||||
"n_b": 20,
|
||||
"set_added": [],
|
||||
"set_removed": [],
|
||||
"order_diff_positions": 0,
|
||||
"v_pos_a": 0,
|
||||
"v_pos_b": 0,
|
||||
"v_pos_ids_a": [],
|
||||
"v_pos_ids_b": [],
|
||||
"v_rank_moved": []
|
||||
},
|
||||
{
|
||||
"query": "家服怎么连",
|
||||
"n_a": 20,
|
||||
"n_b": 20,
|
||||
"set_added": [],
|
||||
"set_removed": [],
|
||||
"order_diff_positions": 0,
|
||||
"v_pos_a": 0,
|
||||
"v_pos_b": 0,
|
||||
"v_pos_ids_a": [],
|
||||
"v_pos_ids_b": [],
|
||||
"v_rank_moved": []
|
||||
},
|
||||
{
|
||||
"query": "织忆怎么部署",
|
||||
"n_a": 20,
|
||||
"n_b": 20,
|
||||
"set_added": [],
|
||||
"set_removed": [],
|
||||
"order_diff_positions": 0,
|
||||
"v_pos_a": 1,
|
||||
"v_pos_b": 1,
|
||||
"v_pos_ids_a": [
|
||||
"mem_1791740271337572997"
|
||||
],
|
||||
"v_pos_ids_b": [
|
||||
"mem_1791740271337572997"
|
||||
],
|
||||
"v_rank_moved": []
|
||||
},
|
||||
{
|
||||
"query": "记忆保护名单",
|
||||
"n_a": 20,
|
||||
"n_b": 20,
|
||||
"set_added": [],
|
||||
"set_removed": [],
|
||||
"order_diff_positions": 0,
|
||||
"v_pos_a": 0,
|
||||
"v_pos_b": 0,
|
||||
"v_pos_ids_a": [],
|
||||
"v_pos_ids_b": [],
|
||||
"v_rank_moved": []
|
||||
}
|
||||
],
|
||||
"affected_queries": [],
|
||||
"n_affected_queries": 0
|
||||
},
|
||||
"golden": {
|
||||
"a": "14/14",
|
||||
"b": "14/14"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
{
|
||||
"a": "DEF",
|
||||
"b": "RBK",
|
||||
"files": {
|
||||
"a": {
|
||||
"152": [
|
||||
"at",
|
||||
"tag",
|
||||
"base",
|
||||
"total",
|
||||
"pass",
|
||||
"fail",
|
||||
"metrics",
|
||||
"latency_ms",
|
||||
"fail_mode",
|
||||
"recall_errors",
|
||||
"fingerprint",
|
||||
"namespace",
|
||||
"top_k",
|
||||
"results"
|
||||
],
|
||||
"probe10": [
|
||||
"at",
|
||||
"tag",
|
||||
"base",
|
||||
"top_k",
|
||||
"rows"
|
||||
],
|
||||
"golden": [
|
||||
"at",
|
||||
"tag",
|
||||
"base",
|
||||
"keyword_pass",
|
||||
"keyword_fail",
|
||||
"keyword_total",
|
||||
"recall_at_5",
|
||||
"mrr",
|
||||
"items"
|
||||
]
|
||||
},
|
||||
"b": [
|
||||
"152",
|
||||
"probe10",
|
||||
"golden"
|
||||
]
|
||||
},
|
||||
"152": {
|
||||
"fp_a": "2318948a910f6d70de6be063216c78089c4315bd",
|
||||
"fp_b": "2318948a910f6d70de6be063216c78089c4315bd",
|
||||
"fp_same": true,
|
||||
"pass_a": 74,
|
||||
"pass_b": 74,
|
||||
"id_hits_a": 7,
|
||||
"id_hits_b": 7,
|
||||
"p95_a_ms": 2630,
|
||||
"p95_b_ms": 931,
|
||||
"changed_queries": 2,
|
||||
"changed_detail": {
|
||||
"家庭服务器(跑 Gitea)在局域网里的地址是哪个": {
|
||||
"kind": "probe",
|
||||
"changed": [
|
||||
"top5"
|
||||
],
|
||||
"a_top5": [
|
||||
"mem_1792088552816998158",
|
||||
"mem_1789136383983279469",
|
||||
"ep_1785695216419714474",
|
||||
"ep_1786336919812827426",
|
||||
"ep_1786452727331645773"
|
||||
],
|
||||
"b_top5": [
|
||||
"mem_1792088552817004309",
|
||||
"mem_1789136383983279469",
|
||||
"ep_1785695216419714474",
|
||||
"ep_1786336919812827426",
|
||||
"ep_1786452727331645773"
|
||||
]
|
||||
},
|
||||
"局域网里访问 Gitea 家服连哪个 IP": {
|
||||
"kind": "probe",
|
||||
"changed": [
|
||||
"top5"
|
||||
],
|
||||
"a_top5": [
|
||||
"mem_1792088552817004309",
|
||||
"mem_1789136383983279469",
|
||||
"ep_1786521524260755589",
|
||||
"mem_1789150776299341327",
|
||||
"mem_1789737118121867083"
|
||||
],
|
||||
"b_top5": [
|
||||
"mem_1792088552816998158",
|
||||
"mem_1789136383983279469",
|
||||
"ep_1786521524260755589",
|
||||
"mem_1789150776299341327",
|
||||
"mem_1789737118121867083"
|
||||
]
|
||||
}
|
||||
},
|
||||
"v0_rank_shifts": []
|
||||
},
|
||||
"probe10": {
|
||||
"rows": [
|
||||
{
|
||||
"query": "牧尘工作所在的县是哪个",
|
||||
"n_a": 20,
|
||||
"n_b": 20,
|
||||
"set_added": [],
|
||||
"set_removed": [],
|
||||
"order_diff_positions": 0,
|
||||
"v_pos_a": 0,
|
||||
"v_pos_b": 0,
|
||||
"v_pos_ids_a": [],
|
||||
"v_pos_ids_b": [],
|
||||
"v_rank_moved": []
|
||||
},
|
||||
{
|
||||
"query": "淇县",
|
||||
"n_a": 20,
|
||||
"n_b": 20,
|
||||
"set_added": [],
|
||||
"set_removed": [],
|
||||
"order_diff_positions": 0,
|
||||
"v_pos_a": 1,
|
||||
"v_pos_b": 1,
|
||||
"v_pos_ids_a": [
|
||||
"mem_1792088552819293505"
|
||||
],
|
||||
"v_pos_ids_b": [
|
||||
"mem_1792088552819293505"
|
||||
],
|
||||
"v_rank_moved": []
|
||||
},
|
||||
{
|
||||
"query": "招商项目台账",
|
||||
"n_a": 20,
|
||||
"n_b": 20,
|
||||
"set_added": [],
|
||||
"set_removed": [],
|
||||
"order_diff_positions": 0,
|
||||
"v_pos_a": 0,
|
||||
"v_pos_b": 0,
|
||||
"v_pos_ids_a": [],
|
||||
"v_pos_ids_b": [],
|
||||
"v_rank_moved": []
|
||||
},
|
||||
{
|
||||
"query": "生物制造产业专班",
|
||||
"n_a": 20,
|
||||
"n_b": 20,
|
||||
"set_added": [],
|
||||
"set_removed": [],
|
||||
"order_diff_positions": 0,
|
||||
"v_pos_a": 0,
|
||||
"v_pos_b": 0,
|
||||
"v_pos_ids_a": [],
|
||||
"v_pos_ids_b": [],
|
||||
"v_rank_moved": []
|
||||
},
|
||||
{
|
||||
"query": "小怡的工作笔记在哪",
|
||||
"n_a": 15,
|
||||
"n_b": 15,
|
||||
"set_added": [],
|
||||
"set_removed": [],
|
||||
"order_diff_positions": 0,
|
||||
"v_pos_a": 0,
|
||||
"v_pos_b": 0,
|
||||
"v_pos_ids_a": [],
|
||||
"v_pos_ids_b": [],
|
||||
"v_rank_moved": []
|
||||
},
|
||||
{
|
||||
"query": "昨天做了什么",
|
||||
"n_a": 20,
|
||||
"n_b": 20,
|
||||
"set_added": [],
|
||||
"set_removed": [],
|
||||
"order_diff_positions": 0,
|
||||
"v_pos_a": 0,
|
||||
"v_pos_b": 0,
|
||||
"v_pos_ids_a": [],
|
||||
"v_pos_ids_b": [],
|
||||
"v_rank_moved": []
|
||||
},
|
||||
{
|
||||
"query": "飞书怎么发语音",
|
||||
"n_a": 20,
|
||||
"n_b": 20,
|
||||
"set_added": [],
|
||||
"set_removed": [],
|
||||
"order_diff_positions": 0,
|
||||
"v_pos_a": 0,
|
||||
"v_pos_b": 0,
|
||||
"v_pos_ids_a": [],
|
||||
"v_pos_ids_b": [],
|
||||
"v_rank_moved": []
|
||||
},
|
||||
{
|
||||
"query": "家服怎么连",
|
||||
"n_a": 20,
|
||||
"n_b": 20,
|
||||
"set_added": [],
|
||||
"set_removed": [],
|
||||
"order_diff_positions": 0,
|
||||
"v_pos_a": 0,
|
||||
"v_pos_b": 0,
|
||||
"v_pos_ids_a": [],
|
||||
"v_pos_ids_b": [],
|
||||
"v_rank_moved": []
|
||||
},
|
||||
{
|
||||
"query": "织忆怎么部署",
|
||||
"n_a": 20,
|
||||
"n_b": 20,
|
||||
"set_added": [],
|
||||
"set_removed": [],
|
||||
"order_diff_positions": 0,
|
||||
"v_pos_a": 1,
|
||||
"v_pos_b": 1,
|
||||
"v_pos_ids_a": [
|
||||
"mem_1791740271337572997"
|
||||
],
|
||||
"v_pos_ids_b": [
|
||||
"mem_1791740271337572997"
|
||||
],
|
||||
"v_rank_moved": []
|
||||
},
|
||||
{
|
||||
"query": "记忆保护名单",
|
||||
"n_a": 20,
|
||||
"n_b": 20,
|
||||
"set_added": [],
|
||||
"set_removed": [],
|
||||
"order_diff_positions": 0,
|
||||
"v_pos_a": 0,
|
||||
"v_pos_b": 0,
|
||||
"v_pos_ids_a": [],
|
||||
"v_pos_ids_b": [],
|
||||
"v_rank_moved": []
|
||||
}
|
||||
],
|
||||
"affected_queries": [],
|
||||
"n_affected_queries": 0
|
||||
},
|
||||
"golden": {
|
||||
"a": "14/14",
|
||||
"b": "14/14"
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,82 @@
|
||||
{
|
||||
"at": "20261016-184343",
|
||||
"tag": "DEF",
|
||||
"base": "http://127.0.0.1:7892",
|
||||
"keyword_pass": 14,
|
||||
"keyword_fail": 0,
|
||||
"keyword_total": 14,
|
||||
"recall_at_5": 0.42857142857142855,
|
||||
"mrr": 0.2380952380952381,
|
||||
"items": [
|
||||
{
|
||||
"query": "织忆是什么",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "织忆的图谱扩展机制是什么",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 1
|
||||
},
|
||||
{
|
||||
"query": "织忆如何通过 E1 提取和 MMR 实现多样去重",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "牧尘的偏好是什么",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 1
|
||||
},
|
||||
{
|
||||
"query": "牧尘喜欢什么样的工作方式",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "如何根据牧尘的偏好调整记忆检索策略",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 1
|
||||
},
|
||||
{
|
||||
"query": "当前项目的技术栈是什么",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 1
|
||||
},
|
||||
{
|
||||
"query": "织忆项目有哪些核心组件",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "织忆和其他记忆系统相比有什么架构优势",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 1
|
||||
},
|
||||
{
|
||||
"query": "如何使用 recall 接口",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "织忆有哪些管理工具",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "如何通过 API 扩展织忆功能",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "本地 llama 服务 8080 端口",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "session-to-zhiyi.py 脚本名",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,932 @@
|
||||
{
|
||||
"at": "20261016-184350",
|
||||
"tag": "DEF",
|
||||
"base": "http://127.0.0.1:7892",
|
||||
"top_k": 20,
|
||||
"rows": [
|
||||
{
|
||||
"query": "牧尘工作所在的县是哪个",
|
||||
"latency_ms": 689,
|
||||
"top_ids": [
|
||||
"mem_1792088552818864597",
|
||||
"mem_1792144084503554069",
|
||||
"mem_1792144084726385461",
|
||||
"mem_1790349546889496890",
|
||||
"mem_1787450890745924038",
|
||||
"mem_1790448247125520424",
|
||||
"mem_1789063252280657787",
|
||||
"mem_1792088552817383356",
|
||||
"ep_1786293372952742428",
|
||||
"mem_1792144084989342595",
|
||||
"mem_1789815923678472264",
|
||||
"mem_1788006341389931001",
|
||||
"mem_1790425119425241515",
|
||||
"mem_1791556228356038757",
|
||||
"mem_1789230281180128695",
|
||||
"mem_1792088552824873585",
|
||||
"mem_1792088552817930263",
|
||||
"mem_1790424260127845812",
|
||||
"mem_1789737493969591957",
|
||||
"mem_1787926246493058856"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.5,
|
||||
0.59,
|
||||
0.59,
|
||||
0.755,
|
||||
0.255,
|
||||
0.755,
|
||||
0.755,
|
||||
0.5,
|
||||
0,
|
||||
0.59,
|
||||
0.83,
|
||||
0.755,
|
||||
0.755,
|
||||
0,
|
||||
0.755,
|
||||
0.5,
|
||||
0.5,
|
||||
0.753,
|
||||
0.755,
|
||||
0.775
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "淇县",
|
||||
"latency_ms": 717,
|
||||
"top_ids": [
|
||||
"mem_1792144084726385461",
|
||||
"mem_1792088552818354175",
|
||||
"mem_1792088552818868548",
|
||||
"mem_1792088552818381759",
|
||||
"mem_1792144084503554069",
|
||||
"mem_1790938090098284542",
|
||||
"mem_1790938089297531705",
|
||||
"mem_1790603669933523968",
|
||||
"mem_1792088552818672993",
|
||||
"mem_1790425189400296970",
|
||||
"mem_1791564884666490485",
|
||||
"mem_1790848976254029727",
|
||||
"mem_1792088552819307750",
|
||||
"mem_1790657384251944657",
|
||||
"mem_1789328667925309581",
|
||||
"mem_1792116219795602288",
|
||||
"mem_1790425213354467843",
|
||||
"mem_1791395173327211388",
|
||||
"mem_1792141689103478828",
|
||||
"mem_1792088552819293505"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1
|
||||
],
|
||||
"quality_scores": [
|
||||
0.59,
|
||||
0.5,
|
||||
0.5,
|
||||
0.5,
|
||||
0.59,
|
||||
0.83,
|
||||
0.83,
|
||||
0,
|
||||
0.5,
|
||||
0.755,
|
||||
0,
|
||||
0.755,
|
||||
0.5,
|
||||
0.755,
|
||||
0.83,
|
||||
0.63,
|
||||
0.755,
|
||||
0.675,
|
||||
0.525,
|
||||
0.99
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 1,
|
||||
"v_pos_ids": [
|
||||
"mem_1792088552819293505"
|
||||
]
|
||||
},
|
||||
{
|
||||
"query": "招商项目台账",
|
||||
"latency_ms": 751,
|
||||
"top_ids": [
|
||||
"mem_1790657711315786810",
|
||||
"mem_1790425023223201421",
|
||||
"mem_1792088552819227083",
|
||||
"mem_1792088552817389514",
|
||||
"mem_1791194371133842796",
|
||||
"mem_1790565541250175254",
|
||||
"mem_1791387362920806120",
|
||||
"mem_1791899910885939521",
|
||||
"mem_1789694252600441660",
|
||||
"mem_1791665519266094329",
|
||||
"mem_1790309303666562764",
|
||||
"mem_1790581054400784704",
|
||||
"mem_1792088552818016699",
|
||||
"mem_1792088552818037737",
|
||||
"mem_1790590528061314469",
|
||||
"mem_1790187043969918230",
|
||||
"mem_1790448247323881504",
|
||||
"mem_1790329285912241710",
|
||||
"mem_1792088552817184125",
|
||||
"mem_1789327284892773149"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.755,
|
||||
0.853,
|
||||
0.5,
|
||||
0.5,
|
||||
0.755,
|
||||
0.755,
|
||||
0.765,
|
||||
0.59,
|
||||
0.755,
|
||||
0,
|
||||
0.755,
|
||||
0.755,
|
||||
0.5,
|
||||
0.5,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0.5,
|
||||
0.755
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "生物制造产业专班",
|
||||
"latency_ms": 722,
|
||||
"top_ids": [
|
||||
"mem_1792144084989342595",
|
||||
"mem_1792107514588524675",
|
||||
"mem_1791567307185364992",
|
||||
"mem_1790051867711758989",
|
||||
"mem_1789983973135821157",
|
||||
"mem_1792088552816455607",
|
||||
"mem_1791380468697720355",
|
||||
"mem_1792088552817215072",
|
||||
"mem_1790658098063956127",
|
||||
"mem_1792088552825118896",
|
||||
"mem_1790656401441522455",
|
||||
"mem_1789755524758238574",
|
||||
"mem_1789741519238314161",
|
||||
"mem_1789736468534024216",
|
||||
"mem_1789731934167097953",
|
||||
"mem_1791916787313401423",
|
||||
"mem_1787336595731500272",
|
||||
"mem_1791794756620086535",
|
||||
"mem_1791811143462384371",
|
||||
"mem_1791735819718797684"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.59,
|
||||
0.63,
|
||||
0,
|
||||
0.755,
|
||||
0.755,
|
||||
0.5,
|
||||
0.78,
|
||||
0.5,
|
||||
0.755,
|
||||
0.5,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0.798,
|
||||
0.395,
|
||||
0.695,
|
||||
0.63,
|
||||
0.315,
|
||||
0.6
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "小怡的工作笔记在哪",
|
||||
"latency_ms": 614,
|
||||
"top_ids": [
|
||||
"mem_1791365211038188118",
|
||||
"mem_1792088552817459951",
|
||||
"mem_1789155186005621317",
|
||||
"mem_1790441160106001927",
|
||||
"mem_1791736002933120377",
|
||||
"mem_1792118701572499829",
|
||||
"mem_1792088552818645685",
|
||||
"mem_1791915848530338805",
|
||||
"mem_1791383333319512288",
|
||||
"mem_1792088552818535755",
|
||||
"mem_1790187044046223493",
|
||||
"mem_1792088552824837822",
|
||||
"mem_1792088552817461960",
|
||||
"mem_1791423103974079882",
|
||||
"mem_1792088552825338800"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.8,
|
||||
0.5,
|
||||
0.755,
|
||||
0.755,
|
||||
0.39,
|
||||
0.63,
|
||||
0.5,
|
||||
0.5,
|
||||
0.8,
|
||||
0.5,
|
||||
0.755,
|
||||
0.5,
|
||||
0.5,
|
||||
0.6,
|
||||
0.5
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "昨天做了什么",
|
||||
"latency_ms": 692,
|
||||
"top_ids": [
|
||||
"mem_1788341686813816985",
|
||||
"mem_1790425119425241515",
|
||||
"mem_1791633893565216844",
|
||||
"mem_1790455525438011532",
|
||||
"mem_1792083942223793654",
|
||||
"mem_1792088770119950733",
|
||||
"mem_1790805789157124891",
|
||||
"mem_1792107513668237224",
|
||||
"mem_1789431180512315186",
|
||||
"mem_1790425238816494139",
|
||||
"mem_1790424256264891954",
|
||||
"mem_1787926246433496550",
|
||||
"mem_1790425017614420145",
|
||||
"mem_1790581068974704280",
|
||||
"mem_1789327284892773149",
|
||||
"mem_1790226520252986178",
|
||||
"mem_1790269130144600786",
|
||||
"mem_1791819411153164256",
|
||||
"mem_1789827897771148953",
|
||||
"mem_1788166192802637740"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.755,
|
||||
0.755,
|
||||
0,
|
||||
0.755,
|
||||
0.395,
|
||||
0.63,
|
||||
0.755,
|
||||
0.63,
|
||||
0.515,
|
||||
0.755,
|
||||
0.755,
|
||||
0.775,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0,
|
||||
0.755,
|
||||
0.395,
|
||||
0.755,
|
||||
0.755
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "飞书怎么发语音",
|
||||
"latency_ms": 783,
|
||||
"top_ids": [
|
||||
"mem_1790345721671326922",
|
||||
"mem_1790350480105660984",
|
||||
"mem_1790425022831993728",
|
||||
"mem_1791118583544396904",
|
||||
"mem_1791533226241026355",
|
||||
"mem_1790455570122981543",
|
||||
"mem_1791445601992763027",
|
||||
"mem_1790496848751501955",
|
||||
"mem_1789273123503223085",
|
||||
"mem_1791666641349257940",
|
||||
"mem_1791666631693960928",
|
||||
"mem_1792088552825510526",
|
||||
"mem_1791666639652621391",
|
||||
"mem_1790265788637717626",
|
||||
"mem_1790428068416795396",
|
||||
"mem_1791118583617248844",
|
||||
"mem_1791666711653684211",
|
||||
"mem_1789557079608816710",
|
||||
"mem_1789327693618007907",
|
||||
"mem_1789273123339483168"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.803,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0,
|
||||
0.803,
|
||||
0,
|
||||
0.83,
|
||||
0.755,
|
||||
0,
|
||||
0.789,
|
||||
0.5,
|
||||
0,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0,
|
||||
0.805,
|
||||
0.755,
|
||||
0.755
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "家服怎么连",
|
||||
"latency_ms": 700,
|
||||
"top_ids": [
|
||||
"mem_1791556229473565240",
|
||||
"mem_1792084245285474959",
|
||||
"mem_1792088552818289574",
|
||||
"mem_1790180705032672204",
|
||||
"mem_1792100307763093595",
|
||||
"mem_1791665516356975992",
|
||||
"mem_1792084245095017393",
|
||||
"mem_1792082720405068478",
|
||||
"mem_1791440639711180469",
|
||||
"mem_1792114886051333715",
|
||||
"mem_1792088552825127031",
|
||||
"mem_1791642436962837771",
|
||||
"mem_1792088552819438066",
|
||||
"mem_1792088552816808997",
|
||||
"mem_1790187091203506519",
|
||||
"mem_1792126203805297968",
|
||||
"mem_1792088552819539001",
|
||||
"mem_1791904832104972267",
|
||||
"mem_1792088552818662517",
|
||||
"mem_1792088552824945417"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0,
|
||||
0.63,
|
||||
0.5,
|
||||
0.755,
|
||||
0.63,
|
||||
0.8,
|
||||
0.63,
|
||||
0.63,
|
||||
0,
|
||||
0.63,
|
||||
0.5,
|
||||
0.65,
|
||||
0.5,
|
||||
0.5,
|
||||
0.755,
|
||||
0.395,
|
||||
0.5,
|
||||
0.43,
|
||||
0.5,
|
||||
0.5
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "织忆怎么部署",
|
||||
"latency_ms": 724,
|
||||
"top_ids": [
|
||||
"mem_1788623666023332134",
|
||||
"mem_1789793765940732350",
|
||||
"mem_1791479003228249623",
|
||||
"mem_1789149704491770048",
|
||||
"mem_1789154058288011112",
|
||||
"mem_1791818814047111008",
|
||||
"mem_1792144557208382006",
|
||||
"mem_1791402157932171759",
|
||||
"mem_1791899478077693848",
|
||||
"mem_1789411888019473186",
|
||||
"mem_1792088552825130331",
|
||||
"mem_1792088552817959556",
|
||||
"mem_1791912042293867384",
|
||||
"mem_1788657176712786530",
|
||||
"mem_1790424244350350337",
|
||||
"mem_1791740271337572997",
|
||||
"mem_1792088552818065436",
|
||||
"mem_1789132107404617336",
|
||||
"mem_1788340352324421455",
|
||||
"mem_1791431677583759030"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.911,
|
||||
0.755,
|
||||
0,
|
||||
0.99,
|
||||
0.695,
|
||||
0.63,
|
||||
0.565,
|
||||
0.99,
|
||||
0.644,
|
||||
0.865,
|
||||
0.5,
|
||||
0.5,
|
||||
0.59,
|
||||
0.755,
|
||||
0.99,
|
||||
0,
|
||||
0.5,
|
||||
0.755,
|
||||
0.755,
|
||||
0.675
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 1,
|
||||
"v_pos_ids": [
|
||||
"mem_1791740271337572997"
|
||||
]
|
||||
},
|
||||
{
|
||||
"query": "记忆保护名单",
|
||||
"latency_ms": 708,
|
||||
"top_ids": [
|
||||
"mem_1790424365997011289",
|
||||
"mem_1792126499467223243",
|
||||
"mem_1788602693814224919",
|
||||
"mem_1791725846574107784",
|
||||
"mem_1789222925018439889",
|
||||
"mem_1791666995981185275",
|
||||
"mem_1792088552818471375",
|
||||
"mem_1791686097363885894",
|
||||
"mem_1789554588799449124",
|
||||
"mem_1791420422726554280",
|
||||
"mem_1791686088996261165",
|
||||
"mem_1789760781378060592",
|
||||
"mem_1790427668905832166",
|
||||
"mem_1791111607517908194",
|
||||
"mem_1791818212646773755",
|
||||
"mem_1790051973384869549",
|
||||
"mem_1790564623527240562",
|
||||
"mem_1789992010025213786",
|
||||
"mem_1792088552819583406",
|
||||
"mem_1791685772880116219"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.99,
|
||||
0.5,
|
||||
0.285,
|
||||
0,
|
||||
0.755,
|
||||
0,
|
||||
0.5,
|
||||
0,
|
||||
0.755,
|
||||
0.914629,
|
||||
0,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0.63,
|
||||
0.755,
|
||||
0.755,
|
||||
0.99,
|
||||
0.5,
|
||||
0
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,82 @@
|
||||
{
|
||||
"at": "20261016-185023",
|
||||
"tag": "NOV",
|
||||
"base": "http://127.0.0.1:7893",
|
||||
"keyword_pass": 14,
|
||||
"keyword_fail": 0,
|
||||
"keyword_total": 14,
|
||||
"recall_at_5": 0.42857142857142855,
|
||||
"mrr": 0.2380952380952381,
|
||||
"items": [
|
||||
{
|
||||
"query": "织忆是什么",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "织忆的图谱扩展机制是什么",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 1
|
||||
},
|
||||
{
|
||||
"query": "织忆如何通过 E1 提取和 MMR 实现多样去重",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "牧尘的偏好是什么",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 1
|
||||
},
|
||||
{
|
||||
"query": "牧尘喜欢什么样的工作方式",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "如何根据牧尘的偏好调整记忆检索策略",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 1
|
||||
},
|
||||
{
|
||||
"query": "当前项目的技术栈是什么",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 1
|
||||
},
|
||||
{
|
||||
"query": "织忆项目有哪些核心组件",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "织忆和其他记忆系统相比有什么架构优势",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 1
|
||||
},
|
||||
{
|
||||
"query": "如何使用 recall 接口",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "织忆有哪些管理工具",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "如何通过 API 扩展织忆功能",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "本地 llama 服务 8080 端口",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "session-to-zhiyi.py 脚本名",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,932 @@
|
||||
{
|
||||
"at": "20261016-185030",
|
||||
"tag": "NOV",
|
||||
"base": "http://127.0.0.1:7893",
|
||||
"top_k": 20,
|
||||
"rows": [
|
||||
{
|
||||
"query": "牧尘工作所在的县是哪个",
|
||||
"latency_ms": 828,
|
||||
"top_ids": [
|
||||
"mem_1792088552818864597",
|
||||
"mem_1792144084503554069",
|
||||
"mem_1792144084726385461",
|
||||
"mem_1790349546889496890",
|
||||
"mem_1787450890745924038",
|
||||
"mem_1790448247125520424",
|
||||
"mem_1789063252280657787",
|
||||
"mem_1792088552817383356",
|
||||
"ep_1786293372952742428",
|
||||
"mem_1792144084989342595",
|
||||
"mem_1789815923678472264",
|
||||
"mem_1788006341389931001",
|
||||
"mem_1790425119425241515",
|
||||
"mem_1791556228356038757",
|
||||
"mem_1789230281180128695",
|
||||
"mem_1792088552824873585",
|
||||
"mem_1792088552817930263",
|
||||
"mem_1790424260127845812",
|
||||
"mem_1789737493969591957",
|
||||
"mem_1787926246493058856"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.5,
|
||||
0.59,
|
||||
0.59,
|
||||
0.755,
|
||||
0.255,
|
||||
0.755,
|
||||
0.755,
|
||||
0.5,
|
||||
0,
|
||||
0.59,
|
||||
0.83,
|
||||
0.755,
|
||||
0.755,
|
||||
0,
|
||||
0.755,
|
||||
0.5,
|
||||
0.5,
|
||||
0.753,
|
||||
0.755,
|
||||
0.775
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "淇县",
|
||||
"latency_ms": 748,
|
||||
"top_ids": [
|
||||
"mem_1792144084726385461",
|
||||
"mem_1792088552818354175",
|
||||
"mem_1792088552818868548",
|
||||
"mem_1792088552818381759",
|
||||
"mem_1792144084503554069",
|
||||
"mem_1790938090098284542",
|
||||
"mem_1790938089297531705",
|
||||
"mem_1790603669933523968",
|
||||
"mem_1792088552818672993",
|
||||
"mem_1790425189400296970",
|
||||
"mem_1791564884666490485",
|
||||
"mem_1790848976254029727",
|
||||
"mem_1792088552819307750",
|
||||
"mem_1790657384251944657",
|
||||
"mem_1789328667925309581",
|
||||
"mem_1792116219795602288",
|
||||
"mem_1790425213354467843",
|
||||
"mem_1791395173327211388",
|
||||
"mem_1792141689103478828",
|
||||
"mem_1792088552819293505"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1
|
||||
],
|
||||
"quality_scores": [
|
||||
0.59,
|
||||
0.5,
|
||||
0.5,
|
||||
0.5,
|
||||
0.59,
|
||||
0.83,
|
||||
0.83,
|
||||
0,
|
||||
0.5,
|
||||
0.755,
|
||||
0,
|
||||
0.755,
|
||||
0.5,
|
||||
0.755,
|
||||
0.83,
|
||||
0.63,
|
||||
0.755,
|
||||
0.675,
|
||||
0.525,
|
||||
0.99
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 1,
|
||||
"v_pos_ids": [
|
||||
"mem_1792088552819293505"
|
||||
]
|
||||
},
|
||||
{
|
||||
"query": "招商项目台账",
|
||||
"latency_ms": 692,
|
||||
"top_ids": [
|
||||
"mem_1790657711315786810",
|
||||
"mem_1790425023223201421",
|
||||
"mem_1792088552819227083",
|
||||
"mem_1792088552817389514",
|
||||
"mem_1791194371133842796",
|
||||
"mem_1790565541250175254",
|
||||
"mem_1791387362920806120",
|
||||
"mem_1791899910885939521",
|
||||
"mem_1789694252600441660",
|
||||
"mem_1791665519266094329",
|
||||
"mem_1790309303666562764",
|
||||
"mem_1790581054400784704",
|
||||
"mem_1792088552818016699",
|
||||
"mem_1792088552818037737",
|
||||
"mem_1790590528061314469",
|
||||
"mem_1790187043969918230",
|
||||
"mem_1790448247323881504",
|
||||
"mem_1790329285912241710",
|
||||
"mem_1792088552817184125",
|
||||
"mem_1789327284892773149"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.755,
|
||||
0.853,
|
||||
0.5,
|
||||
0.5,
|
||||
0.755,
|
||||
0.755,
|
||||
0.765,
|
||||
0.59,
|
||||
0.755,
|
||||
0,
|
||||
0.755,
|
||||
0.755,
|
||||
0.5,
|
||||
0.5,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0.5,
|
||||
0.755
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "生物制造产业专班",
|
||||
"latency_ms": 708,
|
||||
"top_ids": [
|
||||
"mem_1792144084989342595",
|
||||
"mem_1792107514588524675",
|
||||
"mem_1791567307185364992",
|
||||
"mem_1790051867711758989",
|
||||
"mem_1789983973135821157",
|
||||
"mem_1792088552816455607",
|
||||
"mem_1791380468697720355",
|
||||
"mem_1792088552817215072",
|
||||
"mem_1790658098063956127",
|
||||
"mem_1792088552825118896",
|
||||
"mem_1790656401441522455",
|
||||
"mem_1789755524758238574",
|
||||
"mem_1789741519238314161",
|
||||
"mem_1789736468534024216",
|
||||
"mem_1789731934167097953",
|
||||
"mem_1791916787313401423",
|
||||
"mem_1787336595731500272",
|
||||
"mem_1791794756620086535",
|
||||
"mem_1791811143462384371",
|
||||
"mem_1791735819718797684"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.59,
|
||||
0.63,
|
||||
0,
|
||||
0.755,
|
||||
0.755,
|
||||
0.5,
|
||||
0.78,
|
||||
0.5,
|
||||
0.755,
|
||||
0.5,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0.798,
|
||||
0.395,
|
||||
0.695,
|
||||
0.63,
|
||||
0.315,
|
||||
0.6
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "小怡的工作笔记在哪",
|
||||
"latency_ms": 736,
|
||||
"top_ids": [
|
||||
"mem_1791365211038188118",
|
||||
"mem_1792088552817459951",
|
||||
"mem_1789155186005621317",
|
||||
"mem_1790441160106001927",
|
||||
"mem_1791736002933120377",
|
||||
"mem_1792118701572499829",
|
||||
"mem_1792088552818645685",
|
||||
"mem_1791915848530338805",
|
||||
"mem_1791383333319512288",
|
||||
"mem_1792088552818535755",
|
||||
"mem_1790187044046223493",
|
||||
"mem_1792088552824837822",
|
||||
"mem_1792088552817461960",
|
||||
"mem_1791423103974079882",
|
||||
"mem_1792088552825338800"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.8,
|
||||
0.5,
|
||||
0.755,
|
||||
0.755,
|
||||
0.39,
|
||||
0.63,
|
||||
0.5,
|
||||
0.5,
|
||||
0.8,
|
||||
0.5,
|
||||
0.755,
|
||||
0.5,
|
||||
0.5,
|
||||
0.6,
|
||||
0.5
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "昨天做了什么",
|
||||
"latency_ms": 791,
|
||||
"top_ids": [
|
||||
"mem_1788341686813816985",
|
||||
"mem_1790425119425241515",
|
||||
"mem_1791633893565216844",
|
||||
"mem_1790455525438011532",
|
||||
"mem_1792083942223793654",
|
||||
"mem_1792088770119950733",
|
||||
"mem_1790805789157124891",
|
||||
"mem_1792107513668237224",
|
||||
"mem_1789431180512315186",
|
||||
"mem_1790425238816494139",
|
||||
"mem_1790424256264891954",
|
||||
"mem_1787926246433496550",
|
||||
"mem_1790425017614420145",
|
||||
"mem_1790581068974704280",
|
||||
"mem_1789327284892773149",
|
||||
"mem_1790226520252986178",
|
||||
"mem_1790269130144600786",
|
||||
"mem_1791819411153164256",
|
||||
"mem_1789827897771148953",
|
||||
"mem_1788166192802637740"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.755,
|
||||
0.755,
|
||||
0,
|
||||
0.755,
|
||||
0.395,
|
||||
0.63,
|
||||
0.755,
|
||||
0.63,
|
||||
0.515,
|
||||
0.755,
|
||||
0.755,
|
||||
0.775,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0,
|
||||
0.755,
|
||||
0.395,
|
||||
0.755,
|
||||
0.755
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "飞书怎么发语音",
|
||||
"latency_ms": 723,
|
||||
"top_ids": [
|
||||
"mem_1790345721671326922",
|
||||
"mem_1790350480105660984",
|
||||
"mem_1790425022831993728",
|
||||
"mem_1791118583544396904",
|
||||
"mem_1791533226241026355",
|
||||
"mem_1790455570122981543",
|
||||
"mem_1791445601992763027",
|
||||
"mem_1790496848751501955",
|
||||
"mem_1789273123503223085",
|
||||
"mem_1791666641349257940",
|
||||
"mem_1791666631693960928",
|
||||
"mem_1792088552825510526",
|
||||
"mem_1791666639652621391",
|
||||
"mem_1790265788637717626",
|
||||
"mem_1790428068416795396",
|
||||
"mem_1791118583617248844",
|
||||
"mem_1791666711653684211",
|
||||
"mem_1789557079608816710",
|
||||
"mem_1789327693618007907",
|
||||
"mem_1789273123339483168"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.803,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0,
|
||||
0.803,
|
||||
0,
|
||||
0.83,
|
||||
0.755,
|
||||
0,
|
||||
0.789,
|
||||
0.5,
|
||||
0,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0,
|
||||
0.805,
|
||||
0.755,
|
||||
0.755
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "家服怎么连",
|
||||
"latency_ms": 722,
|
||||
"top_ids": [
|
||||
"mem_1791556229473565240",
|
||||
"mem_1792084245285474959",
|
||||
"mem_1792088552818289574",
|
||||
"mem_1790180705032672204",
|
||||
"mem_1792100307763093595",
|
||||
"mem_1791665516356975992",
|
||||
"mem_1792084245095017393",
|
||||
"mem_1792082720405068478",
|
||||
"mem_1791440639711180469",
|
||||
"mem_1792114886051333715",
|
||||
"mem_1792088552825127031",
|
||||
"mem_1791642436962837771",
|
||||
"mem_1792088552819438066",
|
||||
"mem_1792088552816808997",
|
||||
"mem_1790187091203506519",
|
||||
"mem_1792126203805297968",
|
||||
"mem_1792088552819539001",
|
||||
"mem_1791904832104972267",
|
||||
"mem_1792088552818662517",
|
||||
"mem_1792088552824945417"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0,
|
||||
0.63,
|
||||
0.5,
|
||||
0.755,
|
||||
0.63,
|
||||
0.8,
|
||||
0.63,
|
||||
0.63,
|
||||
0,
|
||||
0.63,
|
||||
0.5,
|
||||
0.65,
|
||||
0.5,
|
||||
0.5,
|
||||
0.755,
|
||||
0.395,
|
||||
0.5,
|
||||
0.43,
|
||||
0.5,
|
||||
0.5
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "织忆怎么部署",
|
||||
"latency_ms": 682,
|
||||
"top_ids": [
|
||||
"mem_1788623666023332134",
|
||||
"mem_1789793765940732350",
|
||||
"mem_1791479003228249623",
|
||||
"mem_1789149704491770048",
|
||||
"mem_1789154058288011112",
|
||||
"mem_1791818814047111008",
|
||||
"mem_1792144557208382006",
|
||||
"mem_1791402157932171759",
|
||||
"mem_1791899478077693848",
|
||||
"mem_1789411888019473186",
|
||||
"mem_1792088552825130331",
|
||||
"mem_1792088552817959556",
|
||||
"mem_1791912042293867384",
|
||||
"mem_1788657176712786530",
|
||||
"mem_1790424244350350337",
|
||||
"mem_1791740271337572997",
|
||||
"mem_1792088552818065436",
|
||||
"mem_1789132107404617336",
|
||||
"mem_1788340352324421455",
|
||||
"mem_1791431677583759030"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.911,
|
||||
0.755,
|
||||
0,
|
||||
0.99,
|
||||
0.695,
|
||||
0.63,
|
||||
0.565,
|
||||
0.99,
|
||||
0.644,
|
||||
0.865,
|
||||
0.5,
|
||||
0.5,
|
||||
0.59,
|
||||
0.755,
|
||||
0.99,
|
||||
0,
|
||||
0.5,
|
||||
0.755,
|
||||
0.755,
|
||||
0.675
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 1,
|
||||
"v_pos_ids": [
|
||||
"mem_1791740271337572997"
|
||||
]
|
||||
},
|
||||
{
|
||||
"query": "记忆保护名单",
|
||||
"latency_ms": 664,
|
||||
"top_ids": [
|
||||
"mem_1790424365997011289",
|
||||
"mem_1792126499467223243",
|
||||
"mem_1788602693814224919",
|
||||
"mem_1791725846574107784",
|
||||
"mem_1789222925018439889",
|
||||
"mem_1791666995981185275",
|
||||
"mem_1792088552818471375",
|
||||
"mem_1791686097363885894",
|
||||
"mem_1789554588799449124",
|
||||
"mem_1791420422726554280",
|
||||
"mem_1791686088996261165",
|
||||
"mem_1789760781378060592",
|
||||
"mem_1790427668905832166",
|
||||
"mem_1791111607517908194",
|
||||
"mem_1791818212646773755",
|
||||
"mem_1790051973384869549",
|
||||
"mem_1790564623527240562",
|
||||
"mem_1789992010025213786",
|
||||
"mem_1792088552819583406",
|
||||
"mem_1791685772880116219"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.99,
|
||||
0.5,
|
||||
0.285,
|
||||
0,
|
||||
0.755,
|
||||
0,
|
||||
0.5,
|
||||
0,
|
||||
0.755,
|
||||
0.914629,
|
||||
0,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0.63,
|
||||
0.755,
|
||||
0.755,
|
||||
0.99,
|
||||
0.5,
|
||||
0
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,82 @@
|
||||
{
|
||||
"at": "20261016-183633",
|
||||
"tag": "PRE",
|
||||
"base": "http://127.0.0.1:7891",
|
||||
"keyword_pass": 14,
|
||||
"keyword_fail": 0,
|
||||
"keyword_total": 14,
|
||||
"recall_at_5": 0.42857142857142855,
|
||||
"mrr": 0.2380952380952381,
|
||||
"items": [
|
||||
{
|
||||
"query": "织忆是什么",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "织忆的图谱扩展机制是什么",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 1
|
||||
},
|
||||
{
|
||||
"query": "织忆如何通过 E1 提取和 MMR 实现多样去重",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "牧尘的偏好是什么",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 1
|
||||
},
|
||||
{
|
||||
"query": "牧尘喜欢什么样的工作方式",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "如何根据牧尘的偏好调整记忆检索策略",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 1
|
||||
},
|
||||
{
|
||||
"query": "当前项目的技术栈是什么",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 1
|
||||
},
|
||||
{
|
||||
"query": "织忆项目有哪些核心组件",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "织忆和其他记忆系统相比有什么架构优势",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 1
|
||||
},
|
||||
{
|
||||
"query": "如何使用 recall 接口",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "织忆有哪些管理工具",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "如何通过 API 扩展织忆功能",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "本地 llama 服务 8080 端口",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "session-to-zhiyi.py 脚本名",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,932 @@
|
||||
{
|
||||
"at": "20261016-183639",
|
||||
"tag": "PRE",
|
||||
"base": "http://127.0.0.1:7891",
|
||||
"top_k": 20,
|
||||
"rows": [
|
||||
{
|
||||
"query": "牧尘工作所在的县是哪个",
|
||||
"latency_ms": 670,
|
||||
"top_ids": [
|
||||
"mem_1792088552818864597",
|
||||
"mem_1792144084503554069",
|
||||
"mem_1792144084726385461",
|
||||
"mem_1790349546889496890",
|
||||
"mem_1787450890745924038",
|
||||
"mem_1790448247125520424",
|
||||
"mem_1789063252280657787",
|
||||
"mem_1792088552817383356",
|
||||
"ep_1786293372952742428",
|
||||
"mem_1792144084989342595",
|
||||
"mem_1789815923678472264",
|
||||
"mem_1788006341389931001",
|
||||
"mem_1790425119425241515",
|
||||
"mem_1791556228356038757",
|
||||
"mem_1789230281180128695",
|
||||
"mem_1792088552824873585",
|
||||
"mem_1792088552817930263",
|
||||
"mem_1790424260127845812",
|
||||
"mem_1789737493969591957",
|
||||
"mem_1787926246493058856"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.5,
|
||||
0.59,
|
||||
0.59,
|
||||
0.755,
|
||||
0.255,
|
||||
0.755,
|
||||
0.755,
|
||||
0.5,
|
||||
0,
|
||||
0.59,
|
||||
0.83,
|
||||
0.755,
|
||||
0.755,
|
||||
0,
|
||||
0.755,
|
||||
0.5,
|
||||
0.5,
|
||||
0.753,
|
||||
0.755,
|
||||
0.775
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "淇县",
|
||||
"latency_ms": 699,
|
||||
"top_ids": [
|
||||
"mem_1792144084726385461",
|
||||
"mem_1792088552818354175",
|
||||
"mem_1792088552818868548",
|
||||
"mem_1792088552818381759",
|
||||
"mem_1792144084503554069",
|
||||
"mem_1790938090098284542",
|
||||
"mem_1790938089297531705",
|
||||
"mem_1790603669933523968",
|
||||
"mem_1792088552818672993",
|
||||
"mem_1790425189400296970",
|
||||
"mem_1791564884666490485",
|
||||
"mem_1790848976254029727",
|
||||
"mem_1792088552819307750",
|
||||
"mem_1790657384251944657",
|
||||
"mem_1789328667925309581",
|
||||
"mem_1792116219795602288",
|
||||
"mem_1790425213354467843",
|
||||
"mem_1791395173327211388",
|
||||
"mem_1792141689103478828",
|
||||
"mem_1792088552819293505"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1
|
||||
],
|
||||
"quality_scores": [
|
||||
0.59,
|
||||
0.5,
|
||||
0.5,
|
||||
0.5,
|
||||
0.59,
|
||||
0.83,
|
||||
0.83,
|
||||
0,
|
||||
0.5,
|
||||
0.755,
|
||||
0,
|
||||
0.755,
|
||||
0.5,
|
||||
0.755,
|
||||
0.83,
|
||||
0.63,
|
||||
0.755,
|
||||
0.675,
|
||||
0.525,
|
||||
0.99
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 1,
|
||||
"v_pos_ids": [
|
||||
"mem_1792088552819293505"
|
||||
]
|
||||
},
|
||||
{
|
||||
"query": "招商项目台账",
|
||||
"latency_ms": 682,
|
||||
"top_ids": [
|
||||
"mem_1790657711315786810",
|
||||
"mem_1790425023223201421",
|
||||
"mem_1792088552819227083",
|
||||
"mem_1792088552817389514",
|
||||
"mem_1791194371133842796",
|
||||
"mem_1790565541250175254",
|
||||
"mem_1791387362920806120",
|
||||
"mem_1791899910885939521",
|
||||
"mem_1789694252600441660",
|
||||
"mem_1791665519266094329",
|
||||
"mem_1790309303666562764",
|
||||
"mem_1790581054400784704",
|
||||
"mem_1792088552818016699",
|
||||
"mem_1792088552818037737",
|
||||
"mem_1790590528061314469",
|
||||
"mem_1790187043969918230",
|
||||
"mem_1790448247323881504",
|
||||
"mem_1790329285912241710",
|
||||
"mem_1792088552817184125",
|
||||
"mem_1789327284892773149"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.755,
|
||||
0.853,
|
||||
0.5,
|
||||
0.5,
|
||||
0.755,
|
||||
0.755,
|
||||
0.765,
|
||||
0.59,
|
||||
0.755,
|
||||
0,
|
||||
0.755,
|
||||
0.755,
|
||||
0.5,
|
||||
0.5,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0.5,
|
||||
0.755
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "生物制造产业专班",
|
||||
"latency_ms": 675,
|
||||
"top_ids": [
|
||||
"mem_1792144084989342595",
|
||||
"mem_1792107514588524675",
|
||||
"mem_1791567307185364992",
|
||||
"mem_1790051867711758989",
|
||||
"mem_1789983973135821157",
|
||||
"mem_1792088552816455607",
|
||||
"mem_1791380468697720355",
|
||||
"mem_1792088552817215072",
|
||||
"mem_1790658098063956127",
|
||||
"mem_1792088552825118896",
|
||||
"mem_1790656401441522455",
|
||||
"mem_1789755524758238574",
|
||||
"mem_1789741519238314161",
|
||||
"mem_1789736468534024216",
|
||||
"mem_1789731934167097953",
|
||||
"mem_1791916787313401423",
|
||||
"mem_1787336595731500272",
|
||||
"mem_1791794756620086535",
|
||||
"mem_1791811143462384371",
|
||||
"mem_1791735819718797684"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.59,
|
||||
0.63,
|
||||
0,
|
||||
0.755,
|
||||
0.755,
|
||||
0.5,
|
||||
0.78,
|
||||
0.5,
|
||||
0.755,
|
||||
0.5,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0.798,
|
||||
0.395,
|
||||
0.695,
|
||||
0.63,
|
||||
0.315,
|
||||
0.6
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "小怡的工作笔记在哪",
|
||||
"latency_ms": 583,
|
||||
"top_ids": [
|
||||
"mem_1791365211038188118",
|
||||
"mem_1792088552817459951",
|
||||
"mem_1789155186005621317",
|
||||
"mem_1790441160106001927",
|
||||
"mem_1791736002933120377",
|
||||
"mem_1792118701572499829",
|
||||
"mem_1792088552818645685",
|
||||
"mem_1791915848530338805",
|
||||
"mem_1791383333319512288",
|
||||
"mem_1792088552818535755",
|
||||
"mem_1790187044046223493",
|
||||
"mem_1792088552824837822",
|
||||
"mem_1792088552817461960",
|
||||
"mem_1791423103974079882",
|
||||
"mem_1792088552825338800"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.8,
|
||||
0.5,
|
||||
0.755,
|
||||
0.755,
|
||||
0.39,
|
||||
0.63,
|
||||
0.5,
|
||||
0.5,
|
||||
0.8,
|
||||
0.5,
|
||||
0.755,
|
||||
0.5,
|
||||
0.5,
|
||||
0.6,
|
||||
0.5
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "昨天做了什么",
|
||||
"latency_ms": 737,
|
||||
"top_ids": [
|
||||
"mem_1788341686813816985",
|
||||
"mem_1790425119425241515",
|
||||
"mem_1791633893565216844",
|
||||
"mem_1790455525438011532",
|
||||
"mem_1792083942223793654",
|
||||
"mem_1792088770119950733",
|
||||
"mem_1790805789157124891",
|
||||
"mem_1792107513668237224",
|
||||
"mem_1789431180512315186",
|
||||
"mem_1790425238816494139",
|
||||
"mem_1790424256264891954",
|
||||
"mem_1787926246433496550",
|
||||
"mem_1790425017614420145",
|
||||
"mem_1790581068974704280",
|
||||
"mem_1789327284892773149",
|
||||
"mem_1790226520252986178",
|
||||
"mem_1790269130144600786",
|
||||
"mem_1791819411153164256",
|
||||
"mem_1789827897771148953",
|
||||
"mem_1788166192802637740"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.755,
|
||||
0.755,
|
||||
0,
|
||||
0.755,
|
||||
0.395,
|
||||
0.63,
|
||||
0.755,
|
||||
0.63,
|
||||
0.515,
|
||||
0.755,
|
||||
0.755,
|
||||
0.775,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0,
|
||||
0.755,
|
||||
0.395,
|
||||
0.755,
|
||||
0.755
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "飞书怎么发语音",
|
||||
"latency_ms": 710,
|
||||
"top_ids": [
|
||||
"mem_1790345721671326922",
|
||||
"mem_1790350480105660984",
|
||||
"mem_1790425022831993728",
|
||||
"mem_1791118583544396904",
|
||||
"mem_1791533226241026355",
|
||||
"mem_1790455570122981543",
|
||||
"mem_1791445601992763027",
|
||||
"mem_1790496848751501955",
|
||||
"mem_1789273123503223085",
|
||||
"mem_1791666641349257940",
|
||||
"mem_1791666631693960928",
|
||||
"mem_1792088552825510526",
|
||||
"mem_1791666639652621391",
|
||||
"mem_1790265788637717626",
|
||||
"mem_1790428068416795396",
|
||||
"mem_1791118583617248844",
|
||||
"mem_1791666711653684211",
|
||||
"mem_1789557079608816710",
|
||||
"mem_1789327693618007907",
|
||||
"mem_1789273123339483168"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.803,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0,
|
||||
0.803,
|
||||
0,
|
||||
0.83,
|
||||
0.755,
|
||||
0,
|
||||
0.789,
|
||||
0.5,
|
||||
0,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0,
|
||||
0.805,
|
||||
0.755,
|
||||
0.755
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "家服怎么连",
|
||||
"latency_ms": 718,
|
||||
"top_ids": [
|
||||
"mem_1791556229473565240",
|
||||
"mem_1792084245285474959",
|
||||
"mem_1792088552818289574",
|
||||
"mem_1790180705032672204",
|
||||
"mem_1792100307763093595",
|
||||
"mem_1791665516356975992",
|
||||
"mem_1792084245095017393",
|
||||
"mem_1792082720405068478",
|
||||
"mem_1791440639711180469",
|
||||
"mem_1792114886051333715",
|
||||
"mem_1792088552825127031",
|
||||
"mem_1791642436962837771",
|
||||
"mem_1792088552819438066",
|
||||
"mem_1792088552816808997",
|
||||
"mem_1790187091203506519",
|
||||
"mem_1792126203805297968",
|
||||
"mem_1792088552819539001",
|
||||
"mem_1791904832104972267",
|
||||
"mem_1792088552818662517",
|
||||
"mem_1792088552824945417"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0,
|
||||
0.63,
|
||||
0.5,
|
||||
0.755,
|
||||
0.63,
|
||||
0.8,
|
||||
0.63,
|
||||
0.63,
|
||||
0,
|
||||
0.63,
|
||||
0.5,
|
||||
0.65,
|
||||
0.5,
|
||||
0.5,
|
||||
0.755,
|
||||
0.395,
|
||||
0.5,
|
||||
0.43,
|
||||
0.5,
|
||||
0.5
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "织忆怎么部署",
|
||||
"latency_ms": 732,
|
||||
"top_ids": [
|
||||
"mem_1788623666023332134",
|
||||
"mem_1789793765940732350",
|
||||
"mem_1791479003228249623",
|
||||
"mem_1789149704491770048",
|
||||
"mem_1789154058288011112",
|
||||
"mem_1791818814047111008",
|
||||
"mem_1792144557208382006",
|
||||
"mem_1791402157932171759",
|
||||
"mem_1791899478077693848",
|
||||
"mem_1789411888019473186",
|
||||
"mem_1792088552825130331",
|
||||
"mem_1792088552817959556",
|
||||
"mem_1791912042293867384",
|
||||
"mem_1788657176712786530",
|
||||
"mem_1790424244350350337",
|
||||
"mem_1791740271337572997",
|
||||
"mem_1792088552818065436",
|
||||
"mem_1789132107404617336",
|
||||
"mem_1788340352324421455",
|
||||
"mem_1791431677583759030"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.911,
|
||||
0.755,
|
||||
0,
|
||||
0.99,
|
||||
0.695,
|
||||
0.63,
|
||||
0.565,
|
||||
0.99,
|
||||
0.644,
|
||||
0.865,
|
||||
0.5,
|
||||
0.5,
|
||||
0.59,
|
||||
0.755,
|
||||
0.99,
|
||||
0,
|
||||
0.5,
|
||||
0.755,
|
||||
0.755,
|
||||
0.675
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 1,
|
||||
"v_pos_ids": [
|
||||
"mem_1791740271337572997"
|
||||
]
|
||||
},
|
||||
{
|
||||
"query": "记忆保护名单",
|
||||
"latency_ms": 694,
|
||||
"top_ids": [
|
||||
"mem_1790424365997011289",
|
||||
"mem_1792126499467223243",
|
||||
"mem_1788602693814224919",
|
||||
"mem_1791725846574107784",
|
||||
"mem_1789222925018439889",
|
||||
"mem_1791666995981185275",
|
||||
"mem_1792088552818471375",
|
||||
"mem_1791686097363885894",
|
||||
"mem_1789554588799449124",
|
||||
"mem_1791420422726554280",
|
||||
"mem_1791686088996261165",
|
||||
"mem_1789760781378060592",
|
||||
"mem_1790427668905832166",
|
||||
"mem_1791111607517908194",
|
||||
"mem_1791818212646773755",
|
||||
"mem_1790051973384869549",
|
||||
"mem_1790564623527240562",
|
||||
"mem_1789992010025213786",
|
||||
"mem_1792088552819583406",
|
||||
"mem_1791685772880116219"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.99,
|
||||
0.5,
|
||||
0.285,
|
||||
0,
|
||||
0.755,
|
||||
0,
|
||||
0.5,
|
||||
0,
|
||||
0.755,
|
||||
0.914629,
|
||||
0,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0.63,
|
||||
0.755,
|
||||
0.755,
|
||||
0.99,
|
||||
0.5,
|
||||
0
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,82 @@
|
||||
{
|
||||
"at": "20261016-191108",
|
||||
"tag": "RBK",
|
||||
"base": "http://127.0.0.1:7892",
|
||||
"keyword_pass": 14,
|
||||
"keyword_fail": 0,
|
||||
"keyword_total": 14,
|
||||
"recall_at_5": 0.42857142857142855,
|
||||
"mrr": 0.2380952380952381,
|
||||
"items": [
|
||||
{
|
||||
"query": "织忆是什么",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "织忆的图谱扩展机制是什么",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 1
|
||||
},
|
||||
{
|
||||
"query": "织忆如何通过 E1 提取和 MMR 实现多样去重",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "牧尘的偏好是什么",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 1
|
||||
},
|
||||
{
|
||||
"query": "牧尘喜欢什么样的工作方式",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "如何根据牧尘的偏好调整记忆检索策略",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 1
|
||||
},
|
||||
{
|
||||
"query": "当前项目的技术栈是什么",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 1
|
||||
},
|
||||
{
|
||||
"query": "织忆项目有哪些核心组件",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "织忆和其他记忆系统相比有什么架构优势",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 1
|
||||
},
|
||||
{
|
||||
"query": "如何使用 recall 接口",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "织忆有哪些管理工具",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "如何通过 API 扩展织忆功能",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "本地 llama 服务 8080 端口",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 0
|
||||
},
|
||||
{
|
||||
"query": "session-to-zhiyi.py 脚本名",
|
||||
"keyword_ok": true,
|
||||
"id_recall": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,932 @@
|
||||
{
|
||||
"at": "20261016-191116",
|
||||
"tag": "RBK",
|
||||
"base": "http://127.0.0.1:7892",
|
||||
"top_k": 20,
|
||||
"rows": [
|
||||
{
|
||||
"query": "牧尘工作所在的县是哪个",
|
||||
"latency_ms": 836,
|
||||
"top_ids": [
|
||||
"mem_1792088552818864597",
|
||||
"mem_1792144084503554069",
|
||||
"mem_1792144084726385461",
|
||||
"mem_1790349546889496890",
|
||||
"mem_1787450890745924038",
|
||||
"mem_1790448247125520424",
|
||||
"mem_1789063252280657787",
|
||||
"mem_1792088552817383356",
|
||||
"ep_1786293372952742428",
|
||||
"mem_1792144084989342595",
|
||||
"mem_1789815923678472264",
|
||||
"mem_1788006341389931001",
|
||||
"mem_1790425119425241515",
|
||||
"mem_1791556228356038757",
|
||||
"mem_1789230281180128695",
|
||||
"mem_1792088552824873585",
|
||||
"mem_1792088552817930263",
|
||||
"mem_1790424260127845812",
|
||||
"mem_1789737493969591957",
|
||||
"mem_1787926246493058856"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.5,
|
||||
0.59,
|
||||
0.59,
|
||||
0.755,
|
||||
0.255,
|
||||
0.755,
|
||||
0.755,
|
||||
0.5,
|
||||
0,
|
||||
0.59,
|
||||
0.83,
|
||||
0.755,
|
||||
0.755,
|
||||
0,
|
||||
0.755,
|
||||
0.5,
|
||||
0.5,
|
||||
0.753,
|
||||
0.755,
|
||||
0.775
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "淇县",
|
||||
"latency_ms": 789,
|
||||
"top_ids": [
|
||||
"mem_1792144084726385461",
|
||||
"mem_1792088552818354175",
|
||||
"mem_1792088552818868548",
|
||||
"mem_1792088552818381759",
|
||||
"mem_1792144084503554069",
|
||||
"mem_1790938090098284542",
|
||||
"mem_1790938089297531705",
|
||||
"mem_1790603669933523968",
|
||||
"mem_1792088552818672993",
|
||||
"mem_1790425189400296970",
|
||||
"mem_1791564884666490485",
|
||||
"mem_1790848976254029727",
|
||||
"mem_1792088552819307750",
|
||||
"mem_1790657384251944657",
|
||||
"mem_1789328667925309581",
|
||||
"mem_1792116219795602288",
|
||||
"mem_1790425213354467843",
|
||||
"mem_1791395173327211388",
|
||||
"mem_1792141689103478828",
|
||||
"mem_1792088552819293505"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1
|
||||
],
|
||||
"quality_scores": [
|
||||
0.59,
|
||||
0.5,
|
||||
0.5,
|
||||
0.5,
|
||||
0.59,
|
||||
0.83,
|
||||
0.83,
|
||||
0,
|
||||
0.5,
|
||||
0.755,
|
||||
0,
|
||||
0.755,
|
||||
0.5,
|
||||
0.755,
|
||||
0.83,
|
||||
0.63,
|
||||
0.755,
|
||||
0.675,
|
||||
0.525,
|
||||
0.99
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 1,
|
||||
"v_pos_ids": [
|
||||
"mem_1792088552819293505"
|
||||
]
|
||||
},
|
||||
{
|
||||
"query": "招商项目台账",
|
||||
"latency_ms": 730,
|
||||
"top_ids": [
|
||||
"mem_1790657711315786810",
|
||||
"mem_1790425023223201421",
|
||||
"mem_1792088552819227083",
|
||||
"mem_1792088552817389514",
|
||||
"mem_1791194371133842796",
|
||||
"mem_1790565541250175254",
|
||||
"mem_1791387362920806120",
|
||||
"mem_1791899910885939521",
|
||||
"mem_1789694252600441660",
|
||||
"mem_1791665519266094329",
|
||||
"mem_1790309303666562764",
|
||||
"mem_1790581054400784704",
|
||||
"mem_1792088552818016699",
|
||||
"mem_1792088552818037737",
|
||||
"mem_1790590528061314469",
|
||||
"mem_1790187043969918230",
|
||||
"mem_1790448247323881504",
|
||||
"mem_1790329285912241710",
|
||||
"mem_1792088552817184125",
|
||||
"mem_1789327284892773149"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.755,
|
||||
0.853,
|
||||
0.5,
|
||||
0.5,
|
||||
0.755,
|
||||
0.755,
|
||||
0.765,
|
||||
0.59,
|
||||
0.755,
|
||||
0,
|
||||
0.755,
|
||||
0.755,
|
||||
0.5,
|
||||
0.5,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0.5,
|
||||
0.755
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "生物制造产业专班",
|
||||
"latency_ms": 753,
|
||||
"top_ids": [
|
||||
"mem_1792144084989342595",
|
||||
"mem_1792107514588524675",
|
||||
"mem_1791567307185364992",
|
||||
"mem_1790051867711758989",
|
||||
"mem_1789983973135821157",
|
||||
"mem_1792088552816455607",
|
||||
"mem_1791380468697720355",
|
||||
"mem_1792088552817215072",
|
||||
"mem_1790658098063956127",
|
||||
"mem_1792088552825118896",
|
||||
"mem_1790656401441522455",
|
||||
"mem_1789755524758238574",
|
||||
"mem_1789741519238314161",
|
||||
"mem_1789736468534024216",
|
||||
"mem_1789731934167097953",
|
||||
"mem_1791916787313401423",
|
||||
"mem_1787336595731500272",
|
||||
"mem_1791794756620086535",
|
||||
"mem_1791811143462384371",
|
||||
"mem_1791735819718797684"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.59,
|
||||
0.63,
|
||||
0,
|
||||
0.755,
|
||||
0.755,
|
||||
0.5,
|
||||
0.78,
|
||||
0.5,
|
||||
0.755,
|
||||
0.5,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0.798,
|
||||
0.395,
|
||||
0.695,
|
||||
0.63,
|
||||
0.315,
|
||||
0.6
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "小怡的工作笔记在哪",
|
||||
"latency_ms": 653,
|
||||
"top_ids": [
|
||||
"mem_1791365211038188118",
|
||||
"mem_1792088552817459951",
|
||||
"mem_1789155186005621317",
|
||||
"mem_1790441160106001927",
|
||||
"mem_1791736002933120377",
|
||||
"mem_1792118701572499829",
|
||||
"mem_1792088552818645685",
|
||||
"mem_1791915848530338805",
|
||||
"mem_1791383333319512288",
|
||||
"mem_1792088552818535755",
|
||||
"mem_1790187044046223493",
|
||||
"mem_1792088552824837822",
|
||||
"mem_1792088552817461960",
|
||||
"mem_1791423103974079882",
|
||||
"mem_1792088552825338800"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.8,
|
||||
0.5,
|
||||
0.755,
|
||||
0.755,
|
||||
0.39,
|
||||
0.63,
|
||||
0.5,
|
||||
0.5,
|
||||
0.8,
|
||||
0.5,
|
||||
0.755,
|
||||
0.5,
|
||||
0.5,
|
||||
0.6,
|
||||
0.5
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "昨天做了什么",
|
||||
"latency_ms": 739,
|
||||
"top_ids": [
|
||||
"mem_1788341686813816985",
|
||||
"mem_1790425119425241515",
|
||||
"mem_1791633893565216844",
|
||||
"mem_1790455525438011532",
|
||||
"mem_1792083942223793654",
|
||||
"mem_1792088770119950733",
|
||||
"mem_1790805789157124891",
|
||||
"mem_1792107513668237224",
|
||||
"mem_1789431180512315186",
|
||||
"mem_1790425238816494139",
|
||||
"mem_1790424256264891954",
|
||||
"mem_1787926246433496550",
|
||||
"mem_1790425017614420145",
|
||||
"mem_1790581068974704280",
|
||||
"mem_1789327284892773149",
|
||||
"mem_1790226520252986178",
|
||||
"mem_1790269130144600786",
|
||||
"mem_1791819411153164256",
|
||||
"mem_1789827897771148953",
|
||||
"mem_1788166192802637740"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.755,
|
||||
0.755,
|
||||
0,
|
||||
0.755,
|
||||
0.395,
|
||||
0.63,
|
||||
0.755,
|
||||
0.63,
|
||||
0.515,
|
||||
0.755,
|
||||
0.755,
|
||||
0.775,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0,
|
||||
0.755,
|
||||
0.395,
|
||||
0.755,
|
||||
0.755
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "飞书怎么发语音",
|
||||
"latency_ms": 810,
|
||||
"top_ids": [
|
||||
"mem_1790345721671326922",
|
||||
"mem_1790350480105660984",
|
||||
"mem_1790425022831993728",
|
||||
"mem_1791118583544396904",
|
||||
"mem_1791533226241026355",
|
||||
"mem_1790455570122981543",
|
||||
"mem_1791445601992763027",
|
||||
"mem_1790496848751501955",
|
||||
"mem_1789273123503223085",
|
||||
"mem_1791666641349257940",
|
||||
"mem_1791666631693960928",
|
||||
"mem_1792088552825510526",
|
||||
"mem_1791666639652621391",
|
||||
"mem_1790265788637717626",
|
||||
"mem_1790428068416795396",
|
||||
"mem_1791118583617248844",
|
||||
"mem_1791666711653684211",
|
||||
"mem_1789557079608816710",
|
||||
"mem_1789327693618007907",
|
||||
"mem_1789273123339483168"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.803,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0,
|
||||
0.803,
|
||||
0,
|
||||
0.83,
|
||||
0.755,
|
||||
0,
|
||||
0.789,
|
||||
0.5,
|
||||
0,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0,
|
||||
0.805,
|
||||
0.755,
|
||||
0.755
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "家服怎么连",
|
||||
"latency_ms": 787,
|
||||
"top_ids": [
|
||||
"mem_1791556229473565240",
|
||||
"mem_1792084245285474959",
|
||||
"mem_1792088552818289574",
|
||||
"mem_1790180705032672204",
|
||||
"mem_1792100307763093595",
|
||||
"mem_1791665516356975992",
|
||||
"mem_1792084245095017393",
|
||||
"mem_1792082720405068478",
|
||||
"mem_1791440639711180469",
|
||||
"mem_1792114886051333715",
|
||||
"mem_1792088552825127031",
|
||||
"mem_1791642436962837771",
|
||||
"mem_1792088552819438066",
|
||||
"mem_1792088552816808997",
|
||||
"mem_1790187091203506519",
|
||||
"mem_1792126203805297968",
|
||||
"mem_1792088552819539001",
|
||||
"mem_1791904832104972267",
|
||||
"mem_1792088552818662517",
|
||||
"mem_1792088552824945417"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0,
|
||||
0.63,
|
||||
0.5,
|
||||
0.755,
|
||||
0.63,
|
||||
0.8,
|
||||
0.63,
|
||||
0.63,
|
||||
0,
|
||||
0.63,
|
||||
0.5,
|
||||
0.65,
|
||||
0.5,
|
||||
0.5,
|
||||
0.755,
|
||||
0.395,
|
||||
0.5,
|
||||
0.43,
|
||||
0.5,
|
||||
0.5
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
},
|
||||
{
|
||||
"query": "织忆怎么部署",
|
||||
"latency_ms": 936,
|
||||
"top_ids": [
|
||||
"mem_1788623666023332134",
|
||||
"mem_1789793765940732350",
|
||||
"mem_1791479003228249623",
|
||||
"mem_1789149704491770048",
|
||||
"mem_1789154058288011112",
|
||||
"mem_1791818814047111008",
|
||||
"mem_1792144557208382006",
|
||||
"mem_1791402157932171759",
|
||||
"mem_1791899478077693848",
|
||||
"mem_1789411888019473186",
|
||||
"mem_1792088552825130331",
|
||||
"mem_1792088552817959556",
|
||||
"mem_1791912042293867384",
|
||||
"mem_1788657176712786530",
|
||||
"mem_1790424244350350337",
|
||||
"mem_1791740271337572997",
|
||||
"mem_1792088552818065436",
|
||||
"mem_1789132107404617336",
|
||||
"mem_1788340352324421455",
|
||||
"mem_1791431677583759030"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.911,
|
||||
0.755,
|
||||
0,
|
||||
0.99,
|
||||
0.695,
|
||||
0.63,
|
||||
0.565,
|
||||
0.99,
|
||||
0.644,
|
||||
0.865,
|
||||
0.5,
|
||||
0.5,
|
||||
0.59,
|
||||
0.755,
|
||||
0.99,
|
||||
0,
|
||||
0.5,
|
||||
0.755,
|
||||
0.755,
|
||||
0.675
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 1,
|
||||
"v_pos_ids": [
|
||||
"mem_1791740271337572997"
|
||||
]
|
||||
},
|
||||
{
|
||||
"query": "记忆保护名单",
|
||||
"latency_ms": 968,
|
||||
"top_ids": [
|
||||
"mem_1790424365997011289",
|
||||
"mem_1792126499467223243",
|
||||
"mem_1788602693814224919",
|
||||
"mem_1791725846574107784",
|
||||
"mem_1789222925018439889",
|
||||
"mem_1791666995981185275",
|
||||
"mem_1792088552818471375",
|
||||
"mem_1791686097363885894",
|
||||
"mem_1789554588799449124",
|
||||
"mem_1791420422726554280",
|
||||
"mem_1791686088996261165",
|
||||
"mem_1789760781378060592",
|
||||
"mem_1790427668905832166",
|
||||
"mem_1791111607517908194",
|
||||
"mem_1791818212646773755",
|
||||
"mem_1790051973384869549",
|
||||
"mem_1790564623527240562",
|
||||
"mem_1789992010025213786",
|
||||
"mem_1792088552819583406",
|
||||
"mem_1791685772880116219"
|
||||
],
|
||||
"v_values": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"quality_scores": [
|
||||
0.99,
|
||||
0.5,
|
||||
0.285,
|
||||
0,
|
||||
0.755,
|
||||
0,
|
||||
0.5,
|
||||
0,
|
||||
0.755,
|
||||
0.914629,
|
||||
0,
|
||||
0.755,
|
||||
0.755,
|
||||
0.755,
|
||||
0.63,
|
||||
0.755,
|
||||
0.755,
|
||||
0.99,
|
||||
0.5,
|
||||
0
|
||||
],
|
||||
"raw_quality_scores": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"v_pos": 0,
|
||||
"v_pos_ids": []
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
# 交付说明 · t_5ad3f843【织忆·主症B 返修】元笔记分类器 + 咽喉点收口
|
||||
|
||||
- **卡号**:`t_5ad3f843` | **执行者**:prof-dev(2 次 run 均 `rc=1` 崩于"写交付说明"步骤)
|
||||
- **终审收口**:小怡(default)—— 逐条**亲跑**验证,不采信 worker 自报
|
||||
- **日期**:2026-10-16 | **commit**:`e85c9db`(代码)+ 本文件(证据)
|
||||
- **结论**:AC1–AC8 **全绿**;**生产未部署**(源码级交付)⇒ **可申请激活**(需另提卡 + 牧尘放行)
|
||||
|
||||
---
|
||||
|
||||
## ① 判据脚本原始输出(AC1 · exit 0)
|
||||
|
||||
```
|
||||
$ python3 ~/.hermes/scripts/verify-meta-filter.py
|
||||
正例 14 条 / 负例 11 条;不符 0 条
|
||||
|
||||
[PASS] 分类器达标
|
||||
$ echo $?
|
||||
0
|
||||
```
|
||||
|
||||
> 基线(返修前):exit=1,**10 条不符(7 漏拦 + 3 误拦)**。
|
||||
|
||||
## ② 逐条 before / after(AC7 要求)
|
||||
|
||||
### 病根一 · 漏拦(7 条):判据只认"写下来的那几种写法"
|
||||
|
||||
| 案例(生产原文) | before | after | 命中规则 |
|
||||
|---|---|---|---|
|
||||
| `实测 淇县 ANN 731→15、鹤壁 6536→18(都进池50)` | **放行 ✗** | 拦 ✓ | `pool_in+rank_num+num_arrow+pool` |
|
||||
| `实测 淇县 ANN 731→15(都进池50)` | **放行 ✗** | 拦 ✓ | `pool_in+rank_num+num_arrow+pool` |
|
||||
| `短问法 MISS 复现:牧尘工作所在的县是哪个` | 放行 ✗ | 拦 ✓ | `repro` |
|
||||
| `淇县库里 21 条、鹤壁 10 条、河南 15 条语料可用。` | 放行 ✗ | 拦 ✓ | `data_inv` |
|
||||
| `实测(只读,未改任何库/代码):目标「用户在招商局工作」在 query…` | 放行 ✗ | 拦 ✓ | `data_inv+pool+rank` |
|
||||
| `memory_write 落 episodes 表 + vector 全 0 —— 写入…` | 放行 ✗ | 拦 ✓ | `write_bug` |
|
||||
| `织忆 golden 14/14 不退化,recall@5 = 0.4286` | 放行 ✗ | 拦 ✓ | `eval_metric` |
|
||||
|
||||
**新增规则原文**(形态匹配,非加字面词 —— 满足 AC3):
|
||||
```
|
||||
_RANK_NUM = \bANN\s*\d+\s*→\s*\d+
|
||||
_NUM_ARROW = \d+\s*→\s*\d+
|
||||
_POOL_IN = 进\s*池\s*\d+
|
||||
_REPRO = (MISS\s*复现|复现[::((]|复现\s*(步骤|方法|过程|流程|记录)\s*[::((])
|
||||
_DATA_INV = (语料盘点:N 条…可用)
|
||||
_EVAL_METRIC= (golden \d+/\d+|recall@\d+)
|
||||
_DEBUG_MARK = (\bDEBUG\b|探针|自报|脚本输出)
|
||||
_WRITE_BUG = (写入类故障记录)
|
||||
```
|
||||
|
||||
### 病根二 · 误拦(3 条):把"关于系统的事实"当调查记录拦了
|
||||
|
||||
| 案例(事实句,金标同族题面) | before | after | 理由 |
|
||||
|---|---|---|---|
|
||||
| `织忆召回接口 POST /api/v1/recall 接受 top_k 参数。` | **拦 ✗** | 放 ✓ | `_FACT_DECL` 事实声明形豁免 |
|
||||
| `召回缓存 recall-cache 每 6 小时刷新一次。` | **拦 ✗** | 放 ✓ | `_FACT_DECL`(周期形) |
|
||||
| `织忆主服务进程名是 zhiyid-new,合并服务是 zhiyi-consolidate。` | **拦 ✗** | 放 ✓ | `_FACT_DECL`(进程名形) |
|
||||
|
||||
**AC4 区分判据**:`svc_core` 由 STRONG 降级为 **cue 计数**;通用功能词(召回|蒸馏)各计 1 个 cue,需叠加才判;**事实声明形**(`_FACT_DECL`:接受X参数/监听N端口/每N小时…一次/进程名是/地址是/模型是/字体/行距)⇒ **判事实放行**;带 实测/复现/诊断/命中/命名空间/限流/退避/碎片化/FALLBACK 等概念词的调查记录**不受豁免** ⇒ 既放行 3 条误拦,又**不漏原有 16 条自检正例**(两套用例同时绿)。
|
||||
|
||||
### 负例 11 条全放行(`[放✓]`)
|
||||
牧尘在河南省鹤壁市淇县工作。· 淇县招商项目台账(09-27阅读版).md 已发布。· 织忆服务的健康检查接口监听 7821 端口。· 织忆召回接口 POST /api/v1/recall 接受 top_k 参数。· 召回缓存 recall-cache 每 6 小时刷新一次。· 织忆主服务进程名是 zhiyid-new,合并服务是 zhiyi-consolidate · 公文排版正文用仿宋_GB2312 字体,行距 28 磅。· 家庭服务器(跑 Gitea)在局域网里的地址是 192.168.123.11。· 本地 2B 模型服务监听 8080 端口。· 牧尘负责生物制造产业专班 + 卫都街道安全管理。· 小怡日常主链模型是 deepseek-v4-flash(官方直连)。
|
||||
|
||||
## ③ AC8 咽喉点收口(本卡新增,最关键)
|
||||
|
||||
**问题**:B 卡只接了 3 条管线,而污染样本 **5/6 来自未覆盖路径**(27 个写者只有 3 个被覆盖)。
|
||||
|
||||
**修法**:接在**唯一共享入口**上 —— 所有 27 个写者都走 `POST /api/v1/commit`:
|
||||
|
||||
```go
|
||||
// go/internal/api/routes/core.go:108(/commit 处理器,AutoDistillTrigger 之前)
|
||||
if skip, reason := metanote.ShouldSkip(req.Content); skip {
|
||||
log.Printf("[metanote] commit rejected (gate ON, meta-note): ...")
|
||||
respondError(w, 422, "meta-note rejected: "+reason)
|
||||
return // ← 真拒写:不落 episode、不进蒸馏
|
||||
}
|
||||
// core.go:322(write_memory 处理器)同样接线
|
||||
```
|
||||
⇒ 覆盖 **27/27 写者**(对比修前 3/27)。
|
||||
|
||||
**Python↔Go 同源锁死**:`internal/metanote`(patterns.go / classify.go)与 `~/.hermes/scripts/lib/meta_note_filter.py` 口径同源,由 parity + 差分测试锁死:
|
||||
- `TestParity_PythonLive`(Live parity,0.03s)
|
||||
- `TestParity_MutatedCopyFails` —— **变异必 FAIL**(负控,0.03s)
|
||||
- `TestDifferential_PythonReference` / `TestDifferential_ExpectedSpotChecks`
|
||||
|
||||
## ④ 小怡终审亲跑证据(非自报)
|
||||
|
||||
| 项 | 命令 | 结果 |
|
||||
|---|---|---|
|
||||
| 构建 | `go build ./...` | **exit 0** |
|
||||
| 测试 | `go test ./internal/metanote/` | **ok 0.130s**(8 项含 parity/mutation) |
|
||||
| 判据 | `verify-meta-filter.py` | **exit 0**(正14/负11/不符0) |
|
||||
| 判据未被改(AC2) | `verify-meta-filter.py` mtime **20:08:22** 早于 worker 首启 **20:09:36** | ✓ 正/负例逐字未动 |
|
||||
| 门默认关(AC6) | gateway env / zhiyid env | **各 0 处** `ZHIYI_META_FILTER` |
|
||||
| **未部署** | 生产二进制 mtime `19:02:50` **早于** 提交 `21:59:28`;md5 `95286f63789c7ecd` 未变;`strings` 内 `metanote` **0 处** | ✓ 源码级 |
|
||||
| 零行为变化 | `classify.go:91 ShouldSkip` → `if !GateEnabled() { return false, "" }` | ✓ 门关即不参与 |
|
||||
|
||||
## ⑤ 改动文件清单
|
||||
|
||||
| 文件 | 说明 |
|
||||
|---|---|
|
||||
| `go/internal/metanote/patterns.go` | 新增(规则表,Python 口径同源) |
|
||||
| `go/internal/metanote/classify.go` | 新增(分类 + `GateEnabled`/`ShouldSkip`) |
|
||||
| `go/internal/metanote/metanote_parity_test.go` | 新增(parity) |
|
||||
| `go/internal/metanote/metanote_live_test.go` | 新增(Live parity + 变异负控) |
|
||||
| `go/internal/metanote/metanote_diff_test.go` | 新增(差分对照) |
|
||||
| `go/internal/api/routes/core.go` | 咽喉点接线(:108 / :322) |
|
||||
| `~/.hermes/scripts/lib/meta_note_filter.py` | 分类器 193 → 326 行(仓库外,`.hermes` 侧) |
|
||||
|
||||
## ⑥ 激活状态
|
||||
|
||||
**可申请激活**(分类器绿 + 咽喉点覆盖 27/27 + parity/变异测试在 + 默认关 + 未部署)。
|
||||
**但激活不在本卡范围**:需 ① 另提卡 ② 重建二进制并部署 ③ 牧尘放行(`prod-write-gate.py` 会拦,别绕)。
|
||||
|
||||
## ⑦ 遗留(诚实记录)
|
||||
|
||||
1. **两次 run 均 `rc=1` 崩于"写交付说明"步骤**,日志**无任何错误行**(裸退);代码工作在两轮内已完成并提交 ⇒ 未放行第三次盲跑。**真因未定**(疑与同 profile 并发 worker / 会话结束路径有关,待查)。
|
||||
2. **AC8.1 覆盖表**:本文件 ③ 已给出结构性论证(单一入口 ⇒ 27/27),worker 原计划的逐写者分布表未落盘(随交付说明一起丢)。
|
||||
@@ -0,0 +1,147 @@
|
||||
# 【织忆·门控复核】PATTERN/PEER 影子 diff 量化 — 对照表与原始证据
|
||||
|
||||
卡: t_bd63b641 · 执行人: prof-dev · 2026-10-17 21:0x CST
|
||||
方法: 不碰生产 env/二进制/服务(AC 硬边界)。开态用「独立离线评测」——
|
||||
真实 PatternProvider/PeerAPI + 生产 graph.db(只读) + 实时 bge embedder(:8000),
|
||||
等价于活服务开态注入路径;关态取活服务(:7821, PID 812251)实测。
|
||||
|
||||
────────────────────────────────────────────────────────────
|
||||
## 结论
|
||||
关态 vs 开态 diff = **空(当前态)**,且开态即使修 bug 也**无净收益/伤主路径**。
|
||||
两个通道本卡判定 **「不开闸」**,如实回卡。理由:
|
||||
- PEER: 无 peers 表(0 行),开态物理零注入,无产出。
|
||||
- PATTERN: 当前 NULL-id bug 使 `ListPatterns` 恒报错 → 零注入;**即使修好 bug**,
|
||||
85 行全是「图聚类摘要节点」(无 data/tools 内容,只有聚类键名),对金标余弦
|
||||
0.675–0.715(≥0.6 阈值)会注入 ≤3 条**无召回价值的聚类键噪声/金标**,外加每
|
||||
query ~85 次 embed(冷 ~1.4s)拉高 P95 + 稀释 top-5 ⇒ 伤主路径、无净收益。
|
||||
- 原始阻塞理由(上游未落地)小怡已复核失效(t_3e98b65a/t_fcadee04 done),
|
||||
但「上游 done ≠ 该开」—— 实测证明开了也净负收益(比图谱路「接线已证、收益未证」
|
||||
更明确: PATTERN 有 NULL-id 读库 bug + 数据源本身不是行为 pattern)。
|
||||
|
||||
────────────────────────────────────────────────────────────
|
||||
## 一、门控现状(关态坐实,双源独立)
|
||||
- systemd unit 权威配置: `systemctl --user cat zhiyid | grep ZHIYI_` → 无
|
||||
ZHIYI_PATTERN_RECALL / 无 ZHIYI_PEER_RECALL
|
||||
- 运行进程 env: `/proc/812251/environ` → 无此二键(与 prof-cloud 异源复核一致)
|
||||
- 结论: 两通道 env 均「未设/≠1」⇒ server.go 启动期 `if os.Getenv(...)=="1"` 不成立
|
||||
⇒ `storage.PatternRecallProvider` / `storage.PeerRecallProvider` 均未注册 ⇒ 关态
|
||||
|
||||
## 二、影子 diff(关态 vs 开态,逐条对照)
|
||||
固定 query 集: 14 金标(golden-set.json)+ 69 条真实 content-recall(usage_recall 表)
|
||||
|
||||
### PATTERN 通道(ZHIYI_PATTERN_RECALL)
|
||||
开态注入结果: 当前 **0 条 / 14 金标**(`shadow-on-pattern-inject.json` = 空 `{}`)
|
||||
根因(不是「没命中」而是「读不出来」):
|
||||
- 生产 graph_nodes(type='pattern') 共 85 行,**id 列 85/85 全为 NULL**
|
||||
(`sqlite3: sum(id IS NULL)=85`)
|
||||
- `PatternProvider.Match` → `GraphPatternStore.ListPatterns` 读 `SELECT id,...`
|
||||
为 string,遇 NULL 恒报 `sql: Scan error: converting NULL to string`
|
||||
(影子测试实测抓到原文: `PATTERN_LISTERROR="sql: Scan error on column index 0,
|
||||
name \"id\": converting NULL to string is unsupported"`,`PATTERNS_LOADED=0`)
|
||||
- ⇒ `Match` 直接 return nil ⇒ **当前开态无任何 pattern 注入**
|
||||
|
||||
深层(修 bug 后会怎样 —— 已量化,证明「修了也不该开」):
|
||||
- 这 85 行 properties **0 行有 `data` 键、0 行有 `tools` 键**(只有 20 行有
|
||||
`description`),全是「图聚类摘要节点」(如 `hermes-main/entity 共 3867 节点…`),
|
||||
**不是 L2 行为 pattern**。`Match` 里 `p.Data` 恒空 → 回退 `p.Name`(聚类键,
|
||||
如 `topic:memory` / `pattern:default-main:entity`)。
|
||||
- 余弦探针(绕过 NULL-id 直接 embed 85 个 pattern 名 + 金标,bge-m3:8000 实测):
|
||||
5 条金标 maxcos = 0.6752 / 0.6891 / 0.6975 / 0.7038 / 0.7148,**全 ≥ 0.6 阈值
|
||||
⇒ 若修好 NULL-id,开态会对每条金标注入 ≤3 条聚类键条目**(`offset-cosine-probe.txt`)。
|
||||
- 注入内容 = 裸聚类键名(`topic:memory`、`pattern:learner-main:concept`),
|
||||
**对「织忆是什么」这类 query 无召回价值,只会稀释 top-5**。
|
||||
- 额外成本: 每 query 需 embed 85 个 pattern 名(冷调用 ~85×16.5ms≈1.4s,
|
||||
探针 430 embed/7.12s 实测)⇒ **P95 主路径显著上升**(OFF p95=3177ms → 开态
|
||||
叠加 ~1.4s)。
|
||||
- 判读: 0.6 阈值对 bge-m3 余弦分布偏低(无关文本基线 0.67+),开态注入的多是
|
||||
**假阳性噪声**。
|
||||
- ⇒ 修 bug 后开态 = 「伤主路径 + 无净收益」,仍 **不开**。
|
||||
|
||||
### PEER 通道(ZHIYI_PEER_RECALL)
|
||||
开态注入结果: **0 条 / 14 金标**
|
||||
根因: 生产 graph.db **无 peers 表**(`SELECT count(*) FROM sqlite_master WHERE
|
||||
name='peers'` = 0)。`PeerAPI.GetRecallResults` → `Store.List(200)` → 0 行 →
|
||||
return nil(peer.go:305-308 源码)。⇒ **开态也无任何 peer 注入**。
|
||||
|
||||
### 对照表
|
||||
| 维度 | 关态(活服务) | 开态(影子/离线) | diff |
|
||||
|---|---|---|---|
|
||||
| PATTERN 注入条数 | 0(未注册) | 当前 0(NULL-id bug);修 bug 后 ≤3 聚类键/金标 | **0(当前)/ 噪声(修后)** |
|
||||
| PEER 注入条数 | 0(未注册) | 0(无 peers 表) | **0** |
|
||||
| 召回结果 top5 id | 见 off-recall-14golden-live.json | 当前与关态逐条相同(无注入项可加) | **空(当前)** |
|
||||
| /eval/golden keyword_pass | 14/14 | =关态(当前注入 0 不动);修后注入聚类键不改关键词判据 | **0(当前)** |
|
||||
| /eval/golden recall@5 | 0.643 | =关态 | **0(当前)** |
|
||||
| 开态额外成本 | — | 修 bug 后每 query ~85 embed(冷 ~1.4s)+ top-5 稀释 | 伤主路径 |
|
||||
| 新增条目位置 | — | 追加在结果尾部(recall.go:901-932 append 到 deduped 之后) | — |
|
||||
|
||||
## 三、延迟 P50/P95(阈值从实测读,非拍脑袋)
|
||||
关态(活服务 :7821):
|
||||
- 69 真实 query(本卡 AC 要求的「≥50 query」集): **p50=1383.7ms, p95=3177.2ms**
|
||||
(`off-69-queries-lat-ms.json`,一致单次 run 采集)
|
||||
- 14 金标: 空载热态 p50=949.9/p95=2288.5ms;我在并发 69-query 压测后重跑
|
||||
p50=3936.9/p95=5255.5ms(`off-recall-14golden-live.json` = 并发态)——
|
||||
**绝对值随负载/缓存/8081 LLM 队列代理波动**(非本卡判据,不追服务性能)。
|
||||
开态:
|
||||
- **当前态(NULL-id bug 在)**: 注入 0 条,代码块 `if patternRecallEnabled() &&
|
||||
Provider!=nil` 即便走进去也只 `for _, pr := range nil` ⇒ **开态延迟 = 关态延迟
|
||||
(逐条相同,无新增 embed)**。
|
||||
- **修 bug 后态**: 每 query 额外 embed 85 个 pattern 名(探针实测 430 embed/7.12s
|
||||
≈16.5ms/embed,冷调用 ~1.4s),追加在结果尾部 ⇒ **P95 主路径上叠加 ~1.4s 冷成本
|
||||
(冷 ≈ 关态 p95 翻倍量级)** ⇒ 伤主路径(超 AC 判据「P95 涨幅>20%」)。
|
||||
|
||||
判读: 延迟上「开 vs 关」的**决策相关量 = 修 bug 后每次召回 +~1.4s 冷成本**;
|
||||
当前态(bug 在)开=关=0 差异。绝对基线随负载波动,不作为开闸判据。
|
||||
|
||||
## 四、AC#2: 开门是否需重启才注册 Provider?
|
||||
**答案: 是,必须重启。**
|
||||
- 源码证据: `go/internal/api/server.go:189-202` ——
|
||||
`if os.Getenv("ZHIYI_PATTERN_RECALL")=="1" { storage.PatternRecallProvider =
|
||||
patternProvider.Match }` / `if os.Getenv("ZHIYI_PEER_RECALL")=="1"
|
||||
{ storage.PeerRecallProvider = peerAPI.GetRecallResults }`,均在 `NewServer()`
|
||||
启动期执行;`storage.PatternRecallProvider` 是包级变量,仅在这两处赋值。
|
||||
改运行中 env(不重启)无法注册 Provider。
|
||||
- 实测证据: PID 812251 运行二进制 mtime=2026-10-17 01:18,其 /proc environ 无
|
||||
此二键,当前 Provider 未注册(关态)。要开态只能: 在 systemd unit 加
|
||||
`Environment=ZHIYI_*_RECALL=1` + `daemon-reload` + `restart zhiyid`。
|
||||
- 开闸成本 = 一次重启(低)。但本卡结论「不开」基于净收益为负(见二),
|
||||
重启成本本身不是拦路项——拦路的是「开了也伤主路径 + 无净收益」。
|
||||
|
||||
## 五、判据(按卡 AC)
|
||||
- 当前态 diff 为空(PATTERN NULL-id bug → 0 注入;PEER 无表 → 0 注入)
|
||||
⇒ 「开态无产出」判据满足 ⇒ **不开闸**。
|
||||
- 修 bug 后态: 注入聚类键噪声 + P95 主路径涨幅 >20% ⇒ 「有产出但伤主路径」判据
|
||||
也满足 ⇒ **仍不开**。两条判据各自独立支撑「不开」。
|
||||
- 主路径未退化(关态 /eval/golden kw 14/14、recall@5=0.643;开态当前态=关态)。
|
||||
|
||||
────────────────────────────────────────────────────────────
|
||||
## 原始 JSON(改前/改后,禁只贴结论)
|
||||
- 关态活服务 14 金标逐条: `off-recall-14golden-live.json`
|
||||
- 关态活服务 /eval/golden 汇总: `off-eval-golden-raw.json`
|
||||
- 关态 69 真实 query 延迟: `off-69-queries-lat-ms.json`
|
||||
- 开态影子 pattern 注入(当前态 = 空 `{}`): `shadow-on-pattern-inject.json`
|
||||
- 开态影子 peer 表存在性: 0(`SHADOW_PEER_TABLE_EXISTS=0`,见 shadow_diff_test.go)
|
||||
- 修 bug 后余弦探针(85 聚类键 vs 金标 maxcos): `offset-cosine-probe.txt`
|
||||
+ 复现 `TestShadowPattern_CosineIfIDFixed`(`PATTERN_ROWS_LOADABLE_BYPASS_ID=85`)
|
||||
|
||||
复跑命令:
|
||||
# 关态金标召回(活服务)
|
||||
cd <ws> && python3 eval_off.py
|
||||
# 关态 69 真实 query 延迟
|
||||
cd <ws> && python3 latency_off.py # 注: stdout 混进度行,JSON 在尾部
|
||||
# 开态影子注入 + peer 表 + 修 bug 后余弦探针(只读 graph.db + :8000 embedder,不改生产)
|
||||
cd /home/muc/src/memoryweave/go && go test ./internal/pattern/ \
|
||||
-run 'TestShadowPattern_Diff|TestShadowPeer_NoTable|TestShadowPattern_CosineIfIDFixed' \
|
||||
-v -count=1
|
||||
|
||||
## 给审计脚本的「已明确决策」标记(消音用)
|
||||
本卡对 PATTERN/PEER 门控的终态 = **已明确决策: 暂不开闸(证据: 开态零产出,见上)**。
|
||||
若审计脚本下次再报「门控到期/上游 done 但门关」,应据此识别为「已决策不开」而非
|
||||
「没人复核」。建议: 门控台账加 `decision` 字段(values: open/no-open/unknown),
|
||||
本卡结论落 `no-open` + 证据指针,脚本对 no-open 态静默。
|
||||
|
||||
────────────────────────────────────────────────────────────
|
||||
## 未决(需人拍板,本卡不越界执行)
|
||||
1. PATTERN NULL-id 读库 bug: `GraphPatternStore.ListPatterns` 扫 NULL id 报错。
|
||||
85 存量 pattern 行全是聚类摘要节点且 id=NULL——**这套数据本身可能就不该作为
|
||||
L2 行为 pattern 召回源**。属「修数据还是修代码」的决策,交 hub/ops,不在本卡。
|
||||
2. 开闸动作: 小怡终审 + 牧尘放行(本卡只出证据,AC 明令不开门)。
|
||||
@@ -0,0 +1 @@
|
||||
[-1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 825.0, 952.6, 1123.0, 1376.9, 1383.7, 1544.4, 1583.8, 1592.2, 1635.1, 1680.3, 1685.1, 1691.0, 1726.0, 1754.9, 1794.7, 1851.8, 1874.3, 1878.2, 1901.0, 1909.9, 1924.8, 1937.8, 1954.0, 2037.1, 2053.7, 2058.2, 2154.6, 2174.1, 2287.7, 2355.2, 2718.2, 2789.6, 2791.9, 2832.9, 3109.5, 3222.3, 3507.6, 3534.9, 3906.4]
|
||||
@@ -0,0 +1 @@
|
||||
{"id":"20261017-205654","model":"golden-set","recall_at_5":0.6428571428571429,"precision_at_5":0.12857142857142856,"mean_reciprocal_rank":0.47619047619047616,"ndcg":0.5238095238095238,"query_details":[{"query":"织忆是什么","expected_ids":["mem_1791666702950691634"],"must_include_keywords":["织忆"],"hits":null,"misses":["mem_1791666702950691634"],"recall_at_5":0,"precision_at_5":0,"keyword_ok":true},{"query":"织忆的图谱扩展机制是什么","expected_ids":["mem_1791899478673190284"],"must_include_keywords":["图谱"],"hits":["mem_1791899478673190284"],"misses":null,"recall_at_5":1,"precision_at_5":0.2,"keyword_ok":true},{"query":"织忆如何通过 E1 提取和 MMR 实现多样去重","expected_ids":["mem_1791666890486125605"],"must_include_keywords":["MMR"],"hits":null,"misses":["mem_1791666890486125605"],"recall_at_5":0,"precision_at_5":0,"keyword_ok":true},{"query":"牧尘的偏好是什么","expected_ids":["mem_1790448247125520424"],"must_include_keywords":["牧尘"],"hits":["mem_1790448247125520424"],"misses":null,"recall_at_5":1,"precision_at_5":0.2,"keyword_ok":true},{"query":"牧尘喜欢什么样的工作方式","expected_ids":["mem_1790448247125520424"],"must_include_keywords":["牧尘"],"hits":["mem_1790448247125520424"],"misses":null,"recall_at_5":1,"precision_at_5":0.2,"keyword_ok":true},{"query":"如何根据牧尘的偏好调整记忆检索策略","expected_ids":["mem_1791747597032219499"],"must_include_keywords":["记忆"],"hits":["mem_1791747597032219499"],"misses":null,"recall_at_5":1,"precision_at_5":0.2,"keyword_ok":true},{"query":"当前项目的技术栈是什么","expected_ids":["mem_1790455676397796671"],"must_include_keywords":["技术栈"],"hits":["mem_1790455676397796671"],"misses":null,"recall_at_5":1,"precision_at_5":0.2,"keyword_ok":true},{"query":"织忆项目有哪些核心组件","expected_ids":["mem_1791906354849281414"],"must_include_keywords":["织忆"],"hits":null,"misses":["mem_1791906354849281414"],"recall_at_5":0,"precision_at_5":0,"keyword_ok":true},{"query":"织忆和其他记忆系统相比有什么架构优势","expected_ids":["mem_1791666702950691634"],"must_include_keywords":["织忆"],"hits":["mem_1791666702950691634"],"misses":null,"recall_at_5":1,"precision_at_5":0.2,"keyword_ok":true},{"query":"如何使用 recall 接口","expected_ids":["mem_1791796178328736793"],"must_include_keywords":["recall"],"hits":null,"misses":["mem_1791796178328736793"],"recall_at_5":0,"precision_at_5":0,"keyword_ok":true},{"query":"织忆有哪些管理工具","expected_ids":["mem_1791666702950691634"],"must_include_keywords":["织忆"],"hits":null,"misses":["mem_1791666702950691634"],"recall_at_5":0,"precision_at_5":0,"keyword_ok":true},{"query":"如何通过 API 扩展织忆功能","expected_ids":["mem_1791666188168772049"],"must_include_keywords":["织忆"],"hits":["mem_1791666188168772049"],"misses":null,"recall_at_5":1,"precision_at_5":0.2,"keyword_ok":true},{"query":"本地 llama 服务 8080 端口","expected_ids":["mem_1791423503359721152"],"must_include_keywords":["8080"],"hits":["mem_1791423503359721152"],"misses":null,"recall_at_5":1,"precision_at_5":0.2,"keyword_ok":true},{"query":"session-to-zhiyi.py 脚本名","expected_ids":["mem_1791688470278719760"],"must_include_keywords":["session-to-zhiyi"],"hits":["mem_1791688470278719760"],"misses":null,"recall_at_5":1,"precision_at_5":0.2,"keyword_ok":true}],"queries":14,"ran_at":"2026-10-17T20:56:54.195909811+08:00","keyword_pass":14,"keyword_fail":0,"keyword_total":14}
|
||||
@@ -0,0 +1,319 @@
|
||||
{
|
||||
"state": "OFF",
|
||||
"results": [
|
||||
{
|
||||
"i": 0,
|
||||
"q": "织忆是什么",
|
||||
"count": 5,
|
||||
"top5_ids": [
|
||||
"mem_1791899478673190284",
|
||||
"mem_1792154287491185572",
|
||||
"mem_1791912043093092663",
|
||||
"mem_1792154287177190000",
|
||||
"mem_1792154288142808071"
|
||||
],
|
||||
"top5_cats": [
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled"
|
||||
],
|
||||
"kw_ok": true,
|
||||
"lat_ms": 3936.9
|
||||
},
|
||||
{
|
||||
"i": 1,
|
||||
"q": "织忆的图谱扩展机制是什么",
|
||||
"count": 5,
|
||||
"top5_ids": [
|
||||
"mem_1791899478673190284",
|
||||
"mem_1791725847707296273",
|
||||
"mem_1792154287491185572",
|
||||
"mem_1791770032575826407",
|
||||
"mem_1792088552819764989"
|
||||
],
|
||||
"top5_cats": [
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled"
|
||||
],
|
||||
"kw_ok": true,
|
||||
"lat_ms": 4225.2
|
||||
},
|
||||
{
|
||||
"i": 2,
|
||||
"q": "织忆如何通过 E1 提取和 MMR 实现多样去重",
|
||||
"count": 5,
|
||||
"top5_ids": [
|
||||
"mem_1792088552818081545",
|
||||
"mem_1791666890486125605",
|
||||
"mem_1791520496931190142",
|
||||
"mem_1791422985447662675",
|
||||
"mem_1791498226924653975"
|
||||
],
|
||||
"top5_cats": [
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled"
|
||||
],
|
||||
"kw_ok": true,
|
||||
"lat_ms": 3643.6
|
||||
},
|
||||
{
|
||||
"i": 3,
|
||||
"q": "牧尘的偏好是什么",
|
||||
"count": 5,
|
||||
"top5_ids": [
|
||||
"mem_1791556229473565240",
|
||||
"mem_1791376118421773238",
|
||||
"mem_1790448247125520424",
|
||||
"mem_1792088552818232071",
|
||||
"mem_1792086639900350664"
|
||||
],
|
||||
"top5_cats": [
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled"
|
||||
],
|
||||
"kw_ok": true,
|
||||
"lat_ms": 3367.5
|
||||
},
|
||||
{
|
||||
"i": 4,
|
||||
"q": "牧尘喜欢什么样的工作方式",
|
||||
"count": 5,
|
||||
"top5_ids": [
|
||||
"mem_1790448247125520424",
|
||||
"mem_1792086639900350664",
|
||||
"mem_1791482493617981202",
|
||||
"mem_1789063252280657787",
|
||||
"mem_1792086640133724836"
|
||||
],
|
||||
"top5_cats": [
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled"
|
||||
],
|
||||
"kw_ok": true,
|
||||
"lat_ms": 3511.3
|
||||
},
|
||||
{
|
||||
"i": 5,
|
||||
"q": "如何根据牧尘的偏好调整记忆检索策略",
|
||||
"count": 5,
|
||||
"top5_ids": [
|
||||
"mem_1792091916993248722",
|
||||
"mem_1791747597032219499",
|
||||
"mem_1792088552824810016",
|
||||
"mem_1792153987878359340",
|
||||
"mem_1790137162828579293"
|
||||
],
|
||||
"top5_cats": [
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled"
|
||||
],
|
||||
"kw_ok": true,
|
||||
"lat_ms": 3544.6
|
||||
},
|
||||
{
|
||||
"i": 6,
|
||||
"q": "当前项目的技术栈是什么",
|
||||
"count": 5,
|
||||
"top5_ids": [
|
||||
"mem_1792088552817810427",
|
||||
"mem_1790455676397796671",
|
||||
"mem_1791665641471849057",
|
||||
"mem_1790317738849661043",
|
||||
"mem_1790425023223201421"
|
||||
],
|
||||
"top5_cats": [
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled"
|
||||
],
|
||||
"kw_ok": true,
|
||||
"lat_ms": 4874.5
|
||||
},
|
||||
{
|
||||
"i": 7,
|
||||
"q": "织忆项目有哪些核心组件",
|
||||
"count": 5,
|
||||
"top5_ids": [
|
||||
"mem_1792154287491185572",
|
||||
"mem_1792154287177190000",
|
||||
"mem_1791770032575826407",
|
||||
"mem_1792154288142808071",
|
||||
"mem_1791666702950691634"
|
||||
],
|
||||
"top5_cats": [
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled"
|
||||
],
|
||||
"kw_ok": true,
|
||||
"lat_ms": 3811.5
|
||||
},
|
||||
{
|
||||
"i": 8,
|
||||
"q": "织忆和其他记忆系统相比有什么架构优势",
|
||||
"count": 5,
|
||||
"top5_ids": [
|
||||
"mem_1791899478077693848",
|
||||
"mem_1791666702950691634",
|
||||
"mem_1792088552819764989",
|
||||
"mem_1791770032575826407",
|
||||
"mem_1792154287491185572"
|
||||
],
|
||||
"top5_cats": [
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled"
|
||||
],
|
||||
"kw_ok": true,
|
||||
"lat_ms": 3254.5
|
||||
},
|
||||
{
|
||||
"i": 9,
|
||||
"q": "如何使用 recall 接口",
|
||||
"count": 5,
|
||||
"top5_ids": [
|
||||
"mem_1791482321288100863",
|
||||
"mem_1792153988391999660",
|
||||
"ep_1785686577666177306",
|
||||
"ep_1786452727331645773",
|
||||
"mem_1788717420755520289"
|
||||
],
|
||||
"top5_cats": [
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled"
|
||||
],
|
||||
"kw_ok": true,
|
||||
"lat_ms": 4110.9
|
||||
},
|
||||
{
|
||||
"i": 10,
|
||||
"q": "织忆有哪些管理工具",
|
||||
"count": 5,
|
||||
"top5_ids": [
|
||||
"mem_1792154287491185572",
|
||||
"mem_1791666855166846631",
|
||||
"mem_1792144557208382006",
|
||||
"mem_1792116217448228684",
|
||||
"mem_1792154288142808071"
|
||||
],
|
||||
"top5_cats": [
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled"
|
||||
],
|
||||
"kw_ok": true,
|
||||
"lat_ms": 5963.1
|
||||
},
|
||||
{
|
||||
"i": 11,
|
||||
"q": "如何通过 API 扩展织忆功能",
|
||||
"count": 5,
|
||||
"top5_ids": [
|
||||
"mem_1791666188168772049",
|
||||
"mem_1791818814047111008",
|
||||
"ep_1785695216419714474",
|
||||
"ep_1785702789193047009",
|
||||
"ep_1786336919812827426"
|
||||
],
|
||||
"top5_cats": [
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled"
|
||||
],
|
||||
"kw_ok": true,
|
||||
"lat_ms": 4222.9
|
||||
},
|
||||
{
|
||||
"i": 12,
|
||||
"q": "本地 llama 服务 8080 端口",
|
||||
"count": 5,
|
||||
"top5_ids": [
|
||||
"mem_1791423503359721152",
|
||||
"mem_1791440673318711992",
|
||||
"mem_1788594533802527918",
|
||||
"mem_1788620335517621905",
|
||||
"mem_1788700944516696452"
|
||||
],
|
||||
"top5_cats": [
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled"
|
||||
],
|
||||
"kw_ok": false,
|
||||
"lat_ms": 3803.5
|
||||
},
|
||||
{
|
||||
"i": 13,
|
||||
"q": "session-to-zhiyi.py 脚本名",
|
||||
"count": 5,
|
||||
"top5_ids": [
|
||||
"mem_1791688470278719760",
|
||||
"mem_1789152643785440562",
|
||||
"mem_1790154887033667954",
|
||||
"mem_1790001291060572107",
|
||||
"mem_1789896720973833628"
|
||||
],
|
||||
"top5_cats": [
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled",
|
||||
"distilled"
|
||||
],
|
||||
"kw_ok": true,
|
||||
"lat_ms": 4078.1
|
||||
}
|
||||
],
|
||||
"kw_pass": 13,
|
||||
"kw_total": 14,
|
||||
"p50_ms": 3936.9,
|
||||
"p95_ms": 5255.5,
|
||||
"all_lat_ms": [
|
||||
3254.5,
|
||||
3367.5,
|
||||
3511.3,
|
||||
3544.6,
|
||||
3643.6,
|
||||
3803.5,
|
||||
3811.5,
|
||||
3936.9,
|
||||
4078.1,
|
||||
4110.9,
|
||||
4222.9,
|
||||
4225.2,
|
||||
4874.5,
|
||||
5963.1
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
shadow_diff_test.go:200: PATTERN_ROWS_LOADABLE_BYPASS_ID=85
|
||||
shadow_diff_test.go:224: COSINE_PROBE "织忆是什么" maxcos=0.7038 hit=true (thr=0.6) best=topic:memory
|
||||
shadow_diff_test.go:224: COSINE_PROBE "牧尘的偏好是什么" maxcos=0.6975 hit=true (thr=0.6) best=pattern:default-main:entity
|
||||
shadow_diff_test.go:224: COSINE_PROBE "如何使用 recall 接口" maxcos=0.6891 hit=true (thr=0.6) best=topic:replying
|
||||
shadow_diff_test.go:224: COSINE_PROBE "本地 llama 服务 8080 端口" maxcos=0.6752 hit=true (thr=0.6) best=pattern:test-llm:entity
|
||||
shadow_diff_test.go:224: COSINE_PROBE "织忆项目有哪些核心组件" maxcos=0.7148 hit=true (thr=0.6) best=pattern:learner-main:concept
|
||||
@@ -0,0 +1,229 @@
|
||||
package pattern
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/models"
|
||||
"github.com/xiaoxue/memoryweave/internal/storage"
|
||||
)
|
||||
|
||||
// ── t_bd63b641 影-复:PATTERN/PEER 开门量具(不碰生产;只读 graph.db + 实时 embedder)──
|
||||
// 量化「开 ZHIYI_PATTERN_RECALL / ZHIYI_PEER_RECALL」对 14 金标会注入什么。
|
||||
// Provider 装配在 server.go 启动期由 env 决定 ⇒ 不重启无法在活服务上测开态;
|
||||
// 故本测试直接构造真实 Provider + 生产 graph.db(只读)+ 实时 bge embedder,
|
||||
// 跑出「开态会注入的条目」,与关态(=主召回原样)对比。
|
||||
//
|
||||
// 本测试只读、不落盘、不改库(AC:不碰生产二进制/不重启)。
|
||||
|
||||
type logRecord struct {
|
||||
ID string
|
||||
Category string
|
||||
Content string
|
||||
}
|
||||
|
||||
// runShadowWithDiag 返回:注入结果 + 诊断(pattern 装载数 / query 是否编码成功 / 各 query 最高余弦)。
|
||||
// ⚠️ 关键发现:生产 graph_nodes(type='pattern') 的 id 全为 NULL(85/85),ListPatterns 读 id 为 string
|
||||
// ⇒ 恒报 sql: Scan error (converting NULL to string),Match 直接 return nil。
|
||||
// 故 runShadow 不把 ListPatterns 错误当失败 —— 它本身就是「开态也无法注入」的根因证据。
|
||||
func runShadowWithDiag() (map[string][]logRecord, int, string, map[string]float64) {
|
||||
endpoint := os.Getenv("VLLM_ENDPOINT")
|
||||
if endpoint == "" {
|
||||
endpoint = "http://localhost:8000/v1/embeddings"
|
||||
}
|
||||
emb := storage.NewEmbedder(endpoint)
|
||||
store := NewGraphPatternStore("/var/lib/memoryweave/graph.db")
|
||||
pp := NewPatternProvider(store, NewEmbedderProvider(emb))
|
||||
|
||||
// 装载 pattern 数(防「store 空 → 注入恒 0」的假阴性);记录 ListPatterns 错误原文
|
||||
pats, _, lerr := store.ListPatterns(1000)
|
||||
loaded := 0
|
||||
listErr := ""
|
||||
if lerr != nil {
|
||||
listErr = lerr.Error() // 根因:id 全 NULL → Scan error
|
||||
} else {
|
||||
loaded = len(pats)
|
||||
}
|
||||
|
||||
golden := []string{
|
||||
"织忆是什么", "织忆的图谱扩展机制是什么",
|
||||
"织忆如何通过 E1 提取和 MMR 实现多样去重", "牧尘的偏好是什么",
|
||||
"牧尘喜欢什么样的工作方式", "如何根据牧尘的偏好调整记忆检索策略",
|
||||
"当前项目的技术栈是什么", "织忆项目有哪些核心组件",
|
||||
"织忆和其他记忆系统相比有什么架构优势", "如何使用 recall 接口",
|
||||
"织忆有哪些管理工具", "如何通过 API 扩展织忆功能",
|
||||
"本地 llama 服务 8080 端口", "session-to-zhiyi.py 脚本名",
|
||||
}
|
||||
out := make(map[string][]logRecord)
|
||||
maxCos := make(map[string]float64)
|
||||
|
||||
// 预编码 14 query(若编码失败会记 0,便于区分「没命中」vs「编码挂了」)
|
||||
for _, q := range golden {
|
||||
qv, eerr := emb.EncodeSingle(q)
|
||||
if eerr != nil || len(qv) == 0 {
|
||||
maxCos[q] = -1 // 编码失败标记
|
||||
continue
|
||||
}
|
||||
// 逐个 pattern 算余弦,取最高(复现 Provider.Match 内部逻辑)
|
||||
best := -1.0
|
||||
for _, p := range pats {
|
||||
rep := p.Data
|
||||
if rep == "" {
|
||||
rep = p.Name
|
||||
}
|
||||
text := rep
|
||||
for _, tl := range p.Tools {
|
||||
if tl != "" {
|
||||
text += " " + tl
|
||||
}
|
||||
}
|
||||
pv, perr := emb.EncodeSingle(text)
|
||||
if perr != nil || len(pv) == 0 {
|
||||
continue
|
||||
}
|
||||
s := cosineF32(qv, pv)
|
||||
if s > best {
|
||||
best = s
|
||||
}
|
||||
}
|
||||
maxCos[q] = best
|
||||
}
|
||||
|
||||
// 真注入(走 Provider.Match,同 server 路径)
|
||||
for _, g := range golden {
|
||||
pat := pp.Match(g, "hermes-main", 3) // server.go:902 topK=3
|
||||
for _, r := range pat {
|
||||
out[g] = append(out[g], logRecord{ID: r.ID, Category: r.Category, Content: r.Content})
|
||||
}
|
||||
}
|
||||
return out, loaded, listErr, maxCos
|
||||
}
|
||||
|
||||
// TestShadowPattern_Diff —— 开态 pattern 注入量化(只读生产库)
|
||||
func TestShadowPattern_Diff(t *testing.T) {
|
||||
out, loaded, listErr, maxCos := runShadowWithDiag()
|
||||
t.Logf("PATTERNS_LOADED=%d (防假阴性:store 有货才会注入)", loaded)
|
||||
if listErr != "" {
|
||||
t.Logf("PATTERN_LISTERROR=%q — 根因:pattern 行 id 全 NULL ⇒ Provider.Match 恒 return nil", listErr)
|
||||
}
|
||||
|
||||
queries := []string{
|
||||
"织忆是什么", "织忆的图谱扩展机制是什么",
|
||||
"织忆如何通过 E1 提取和 MMR 实现多样去重", "牧尘的偏好是什么",
|
||||
"牧尘喜欢什么样的工作方式", "如何根据牧尘的偏好调整记忆检索策略",
|
||||
"当前项目的技术栈是什么", "织忆项目有哪些核心组件",
|
||||
"织忆和其他记忆系统相比有什么架构优势", "如何使用 recall 接口",
|
||||
"织忆有哪些管理工具", "如何通过 API 扩展织忆功能",
|
||||
"本地 llama 服务 8080 端口", "session-to-zhiyi.py 脚本名",
|
||||
}
|
||||
totalInjected := 0
|
||||
for _, q := range queries {
|
||||
mc := maxCos[q]
|
||||
if mc < 0 {
|
||||
t.Logf("[EMB-FAIL] %q → 编码失败(不计命中)", q)
|
||||
}
|
||||
if n := len(out[q]); n > 0 {
|
||||
totalInjected += n
|
||||
t.Logf("[INJECT] %q → %d pattern (maxcos=%.3f)", q, n, mc)
|
||||
for _, r := range out[q] {
|
||||
t.Logf(" id=%s cat=%s content=%s", r.ID, r.Category, trunc(r.Content, 60))
|
||||
}
|
||||
} else {
|
||||
t.Logf("[NO-INJECT] %q → 0 pattern (maxcos=%.3f, 阈值=0.6)", q, mc)
|
||||
}
|
||||
}
|
||||
b, _ := json.MarshalIndent(out, "", " ")
|
||||
t.Logf("SHADOW_PATTERN_TOTAL_INJECTED=%d", totalInjected)
|
||||
os.WriteFile("/tmp/shadow-pattern-inject.json", b, 0644)
|
||||
t.Logf("raw json → /tmp/shadow-pattern-inject.json (%d bytes)", len(b))
|
||||
}
|
||||
|
||||
func trunc(s string, n int) string {
|
||||
if len(s) <= n {
|
||||
return s
|
||||
}
|
||||
return s[:n] + "…"
|
||||
}
|
||||
|
||||
// ── peer 侧:生产 graph.db 无 peers 表 ⇒ 开态无数据可注入 ──
|
||||
func TestShadowPeer_NoTable(t *testing.T) {
|
||||
db, err := peerOpenReadOnly("/var/lib/memoryweave/graph.db")
|
||||
if err != nil {
|
||||
t.Fatalf("open graph.db: %v", err)
|
||||
}
|
||||
defer db.Close()
|
||||
var cnt int
|
||||
err = db.QueryRow("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='peers'").Scan(&cnt)
|
||||
if err != nil {
|
||||
t.Fatalf("query peers table existence: %v", err)
|
||||
}
|
||||
t.Logf("SHADOW_PEER_TABLE_EXISTS=%d (0 ⇒ 开态 peer 无数据可注入)", cnt)
|
||||
}
|
||||
|
||||
// peerOpenReadOnly 只读开 sqlite(WAL 兼容),避免 peer.Store 的写路径。
|
||||
func peerOpenReadOnly(path string) (*sql.DB, error) {
|
||||
return sql.Open("sqlite", "file:"+path+"?mode=ro&_pragma=busy_timeout(5000)")
|
||||
}
|
||||
|
||||
// ── 深度根因:即使修好 NULL-id,85 行 pattern 无 data/tools 键(只有 description),
|
||||
// Match 只能 embed 命名键(如 "pattern:hermes-main:entity")⇒ 对金标余弦 < 0.6 阈值。
|
||||
// 本测试量化「修好 NULL-id 后开态到底能注入几类金标」—— 证明开态收益仍≈0。
|
||||
func TestShadowPattern_CosineIfIDFixed(t *testing.T) {
|
||||
endpoint := os.Getenv("VLLM_ENDPOINT")
|
||||
if endpoint == "" {
|
||||
endpoint = "http://localhost:8000/v1/embeddings"
|
||||
}
|
||||
emb := storage.NewEmbedder(endpoint)
|
||||
// 绕过 NULL-id 的 ListPatterns:只读 name + properties(非 NULL 列)
|
||||
db, err := peerOpenReadOnly("/var/lib/memoryweave/graph.db")
|
||||
if err != nil {
|
||||
t.Fatalf("open: %v", err)
|
||||
}
|
||||
defer db.Close()
|
||||
rows, _ := db.Query(`SELECT name, properties FROM graph_nodes WHERE type='pattern'`)
|
||||
type patText struct{ name, text string }
|
||||
var pats []patText
|
||||
for rows.Next() {
|
||||
var name, props string
|
||||
if serr := rows.Scan(&name, &props); serr != nil {
|
||||
continue
|
||||
}
|
||||
// 复现 Match 的 text 构造:rep=data(无→空) 回退 name;无 tools
|
||||
text := name
|
||||
pats = append(pats, patText{name, text})
|
||||
}
|
||||
rows.Close()
|
||||
t.Logf("PATTERN_ROWS_LOADABLE_BYPASS_ID=%d", len(pats))
|
||||
if len(pats) == 0 {
|
||||
t.Skip("无 pattern 行可载(NULL-id 未修前本就 0 注入,已在 TestShadowPattern_Diff 覆盖)")
|
||||
}
|
||||
golden := []string{"织忆是什么", "牧尘的偏好是什么", "如何使用 recall 接口",
|
||||
"本地 llama 服务 8080 端口", "织忆项目有哪些核心组件"}
|
||||
for _, q := range golden {
|
||||
qv, qerr := emb.EncodeSingle(q)
|
||||
if qerr != nil || len(qv) == 0 {
|
||||
t.Logf("[EMBFAIL] %q → %v", q, qerr)
|
||||
continue
|
||||
}
|
||||
best, bestName := -1.0, ""
|
||||
for _, p := range pats {
|
||||
pv, perr := emb.EncodeSingle(p.text)
|
||||
if perr != nil || len(pv) == 0 {
|
||||
continue
|
||||
}
|
||||
s := cosineF32(qv, pv)
|
||||
if s > best {
|
||||
best, bestName = s, p.name
|
||||
}
|
||||
}
|
||||
hit := best >= 0.6
|
||||
t.Logf("COSINE_PROBE %q maxcos=%.4f hit=%v (thr=0.6) best=%s", q, best, hit, bestName)
|
||||
}
|
||||
}
|
||||
|
||||
// 防 unused 误报
|
||||
var _ = models.RecallResult{}
|
||||
@@ -0,0 +1 @@
|
||||
{}
|
||||
@@ -0,0 +1,89 @@
|
||||
# hits+/hits− outcome 信号定义(GA-P0-4 · t_bb10e8bc)
|
||||
|
||||
> 一句话:hits+/hits− 是**独立、语义单一**的「真实 outcome」信号,供 P2 自适应阈值做
|
||||
> 有意义的拟合。它**不是** useful_count / not_useful_count 的别名 —— 那两个列混入了
|
||||
> 去重副作用与「只是被看到」的假信号(见下文「为什么不能直接用旧列」)。
|
||||
|
||||
## 1. 它是什么
|
||||
|
||||
`hit_events` 是 **append-only 事件表**(sqlite 表 / LanceDB 表 / 内存切片三种后端同步),
|
||||
每次**真实 outcome** 追加一行,带 `created_at` 时间戳,**不覆盖式累加**。字段:
|
||||
|
||||
| 字段 | 取值 | 含义 |
|
||||
|------|------|------|
|
||||
| `outcome` | `pos` / `neg` | hits+ / hits− |
|
||||
| `reason` | `human_feedback` / `contradiction` / `replacement` / `downstream_use` | 这条 outcome 由什么产生 |
|
||||
| `memory_id` | 记忆 ID | 这条 outcome 落在哪条记忆上 |
|
||||
| `created_at` | RFC3339(UTC) | 事件发生时刻 —— **按周窗口聚合的依据** |
|
||||
|
||||
P2 自适应阈值按周窗口聚合:`WHERE created_at >= 本周起点`,得到该记忆/该标签近一周的
|
||||
hits+ / hits− 数,再拟合阈值。因为事件带时间戳且 append-only,周窗口天然可算(老窗口
|
||||
自然滑出,不污染当前拟合)。
|
||||
|
||||
## 2. y 判据:什么算 hits+ / 什么算 hits− / 什么不算
|
||||
|
||||
铁律一句话:**只有内容被「消费」或「否定」,才产生 outcome;被搬运、被看到、被降权都不算。**
|
||||
|
||||
### hits+(`outcome="pos"`)—— 被真实使用/认可
|
||||
1. **human_feedback**:用户对召回结果点「有用」(`/feedback/useful`)、或「修正」(`/feedback/correct`)
|
||||
2. **downstream_use**:下游流程**实际引用**了这条记忆的内容(写代码/写文档/决策时真正用上)
|
||||
3. **contradiction(正面)**:后续对话中它被反复印证、未被推翻
|
||||
|
||||
### hits−(`outcome="neg"`)—— 被真实否定/取代
|
||||
1. **human_feedback**:用户对召回结果点「没用」(`/feedback/not-useful`)
|
||||
2. **contradiction**:后续对话中它与更可信的信息**冲突并被淘汰**(`delete_reason=contradiction`)
|
||||
3. **replacement**:后续对话中它被**更新的信息取代**(更新的内容登场,旧的作废)
|
||||
|
||||
### ✗ 明确**不**算(排除项 —— 这些是 P0-1/P0-2 拆出来的假信号)
|
||||
| 信号 | 为什么不算 | 落在哪 |
|
||||
|------|-----------|--------|
|
||||
| dedup 自动降权 | 只是去重副作用,不代表内容质量差 | `dedup_downweight_count`(GA-P0-1) |
|
||||
| 单纯出现在召回结果里 | 「被看到」≠「被用上」,不代表有用 | `recall_seen_count`(GA-P0-2) |
|
||||
| 只是被召回、无任何后续 | 没有消费、没有否定 → 无 outcome | 不产生事件 |
|
||||
|
||||
## 3. 为什么不能直接用旧列(等同不成立的证据)
|
||||
|
||||
方案文档(`已办.md:16623`)曾写 `hits+ = useful_count`、`hits− = not_useful_count`、
|
||||
`V = hits+ + hits−`。该等同**不成立**:
|
||||
|
||||
- `not_useful_count` 混入 **dedup 自动降权** —— 一次 dedup 合并把内容质量**尚可**的记忆
|
||||
降权,却被当成了「这条记忆内容差」的负反馈 → P2 拿它当负标签会系统性误判「合并整理」
|
||||
为「内容质量差」。
|
||||
- `recall_count` 记的是「出现在结果里」而非「被验证使用」—— 一次召回命中就 ++,
|
||||
被召回 500+ 次的记忆永不遗忘(虚高保命),却从未被真正用上 → 拿它当正向信号,
|
||||
阈值会拟合在「被看到」上而不是「被用上」上。
|
||||
|
||||
所以必须新建**只由真实 outcome 写入**的独立信号。本表就是它。
|
||||
|
||||
## 4. 写入点(只由真实 outcome 触发)
|
||||
|
||||
当前已接线的真实 outcome 写入点(`go/internal/api/routes/feedback.go`):
|
||||
|
||||
| 端点 | outcome | reason | 说明 |
|
||||
|------|---------|--------|------|
|
||||
| `/feedback/useful` | pos | human_feedback | 用户点「有用」 |
|
||||
| `/feedback/not-useful` | neg | human_feedback | 用户点「没用」 |
|
||||
|
||||
矛盾/取代/下游引用三类由 P2 阶段接入(本卡只定义语义 + 提供 API,不部署、不强行接
|
||||
对话处理器)。
|
||||
|
||||
## 5. 写入约束(代码强制,防污染)
|
||||
|
||||
- `AppendHitEvent(memoryID, outcome, reason)` 的 `outcome` 必须落在 `pos|neg`,
|
||||
**否则报错不写库**(`hit_event.go:NormalizeHitOutcome`)—— 非法/混合语义值在源头被拦。
|
||||
- `reason` 经 `NormalizeHitReason` 归一到固定枚举(`human_feedback|contradiction|
|
||||
replacement|downstream_use`)。
|
||||
- dedup 降权 / 单纯召回出现**禁止**调用本方法(它们在 P0-1/P0-2 已各有专属字段)。
|
||||
|
||||
## 6. 实现位置
|
||||
|
||||
| 层 | 文件 |
|
||||
|----|------|
|
||||
| Go 语义定义(枚举+归一化,单一真源) | `go/internal/storage/hit_event.go` |
|
||||
| Go 模型 | `go/internal/models/memory.go`(`HitEvent`) |
|
||||
| sqlite 后端 | `go/internal/storage/sqlite.go`(`hit_events` 表 + 3 方法) |
|
||||
| 内存后端 | `go/internal/storage/memvector.go`(`hitEvents` 切片 + 3 方法) |
|
||||
| Rust-LanceDB 后端 | `rust/src/lancedb_ops.rs`(`hit_events` 表 + 3 方法)· `rust/src/main.rs`(IPC) |
|
||||
| 真实 outcome 接线 | `go/internal/api/routes/feedback.go` |
|
||||
|
||||
**禁部署**:本卡只落代码 + 测试 + 文档,不更新运行中的二进制、不碰 live 库。
|
||||
@@ -0,0 +1,30 @@
|
||||
# 织忆指标语义:counter / rate / mean(`/api/v1/metrics`)
|
||||
|
||||
> 2026-10-26 建立。起因:有效性审计把 `deprecated_per_day`(计数器)当成率指标,
|
||||
> 报出「0 样本却判 valid=None ⇒ 缺最小样本门」。计数器没有分母,「样本门」对它无定义
|
||||
> —— 属**探针模型错配**,不是指标缺陷。本文件是给下游(审计脚本 / 看板 / 人)的唯一口径。
|
||||
|
||||
## 三类指标,三种读法
|
||||
|
||||
| 类型 | 命名特征 | 自带字段 | 怎么用 | 例子 |
|
||||
|---|---|---|---|---|
|
||||
| **counter 计数器** | `*_per_day` / `*_total` / `*_count` | **无** `_samples` / `_valid` | 直接读绝对值,跨时间比大小;不要算比率、不要报「样本不足」 | `deprecated_per_day`、`deprecated_total`、`distill_success_count` |
|
||||
| **rate 比率** | `*_rate` | `_samples`(分母)+ `_valid`(1=可判 / 0=不可判 / -1=N/A) | `_valid != 1` 时**不得**当结论;`_samples` 小于门槛时只报「待积累」 | `auto_resolve_rate`、`recall_usefulness_rate` |
|
||||
| **mean 均值** | `avg_*` | `_samples` + `_valid` | 同上:无分母就不下判断 | `avg_distill_loss` |
|
||||
|
||||
**铁律**:`0` 永远有两种含义 —— 「今天确实没有」和「根本没在统计」。
|
||||
- 计数器必须配一个累计值来区分:`deprecated_per_day=0` + `deprecated_total=0` ⇒ 从未统计过;
|
||||
`per_day=0` + `total=137` ⇒ 统计活着,只是今天没发生。
|
||||
- 率指标必须配 `_valid`/`_samples`,分母退化时返回 `metricNA(-1)`,不给 1(给 1 会被读成满分)。
|
||||
|
||||
## 触发器阈值也用同一套语义
|
||||
|
||||
`internal/selfoptimize/executor.go` 的 `t8`(`TDecayCritical` → `archive_or_boost`):
|
||||
- 判据读的是**计数器** `deprecated_per_day`(条/天),阈值由 `t8.Condition` 承载,**默认 5 条/天**。
|
||||
- 2026-10-26 修正:原先 `Condition: 0.1` 但判据函数里硬编码 `> 5`,配置写了从不生效。
|
||||
现改为 `Condition: 5.0` + 判据读 `t.Condition`(行为不变,但配置真的能被改)。
|
||||
- 若要改成「率」语义,需要先有分母(当日活跃写入量),否则别动 —— 那会变成另一个探针错配。
|
||||
|
||||
## 已知遗留
|
||||
|
||||
- 审计脚本侧对计数器发「样本不足」告警的白名单修复,归 `t_44c07eca`(脚本侧统一处理,避免多处各改一遍)。
|
||||
+9
-9
@@ -71,7 +71,7 @@ type RegisterResponse struct {
|
||||
|
||||
// WSEvent WebSocket 推送事件
|
||||
type WSEvent struct {
|
||||
Type string `json:"type"` // prefetch.push / gap.detected / memory.updated / conflict.detected / ...
|
||||
Type string `json:"type"` // prefetch.push / gap.detected / memory.updated / conflict.detected / ...
|
||||
Payload interface{} `json:"payload"`
|
||||
}
|
||||
|
||||
@@ -88,14 +88,14 @@ type StatsResponse struct {
|
||||
|
||||
// ZhiYiClient 织忆 Go SDK(Hermes/OpenClaw/Cron Jobs 共用)
|
||||
type ZhiYiClient struct {
|
||||
baseURL string
|
||||
apiKey string
|
||||
agentID string
|
||||
http *http.Client
|
||||
wsConn *websocket.Conn
|
||||
wsMu sync.Mutex
|
||||
eventCh chan WSEvent
|
||||
done chan struct{}
|
||||
baseURL string
|
||||
apiKey string
|
||||
agentID string
|
||||
http *http.Client
|
||||
wsConn *websocket.Conn
|
||||
wsMu sync.Mutex
|
||||
eventCh chan WSEvent
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
// NewZhiYiClient 创建织忆客户端
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
// 织忆 MemoryWeave — is_deleted 删除原因回填工具(GA-P0-3 t_f785d7f2)
|
||||
//
|
||||
// 背景:is_deleted=true 实测 11228 条,但删除原因不可分辨——「坏记忆被删」(contradiction/
|
||||
// manual/retention) 和「合并/整理被删」(merge_dup) 混在同一个布尔里。P2 要拿「被删」
|
||||
// 当负标签,必须先把原因分列。
|
||||
//
|
||||
// 本工具:
|
||||
// 1. 读 LanceDB 全部 is_deleted=true 行(走 Rust IPC lancedb_scan_deleted)。
|
||||
// 2. 以 tombstones 表为据尽力判定删除原因(sqlite tombstones.reason 列)。
|
||||
// tombstones 判不出的写 unknown。
|
||||
// 3. 对每行写 delete_reason(跳过往已回填的、行上 delete_reason 非空的行)。
|
||||
// 4. 输出 delete_reason 直方图。
|
||||
//
|
||||
// 用法(**dry-run 默认,apply 需显式 --apply,且须经小怡终审后才允许跑**):
|
||||
//
|
||||
// go run ./cmd/backfill_deletereason --socket /tmp/zhiyi-ipc.sock --tombstones <sqlite.db>
|
||||
// go run ./cmd/backfill_deletereason --socket /tmp/zhiyi-ipc.sock --tombstones <sqlite.db> --apply
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type ipcReq struct {
|
||||
Type string `json:"type"`
|
||||
Table string `json:"table,omitempty"`
|
||||
ID string `json:"id,omitempty"`
|
||||
Fields string `json:"fields,omitempty"`
|
||||
}
|
||||
|
||||
type ipcResp struct {
|
||||
Status string `json:"status"`
|
||||
ReportJSON string `json:"report_json"`
|
||||
ErrorDetail string `json:"error_detail"`
|
||||
}
|
||||
|
||||
func rpc(sock string, req ipcReq) (*ipcResp, error) {
|
||||
conn, err := net.DialTimeout("unix", sock, 5e9)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ipc dial %s: %w", sock, err)
|
||||
}
|
||||
defer conn.Close()
|
||||
body, _ := json.Marshal(req)
|
||||
lenBuf := make([]byte, 4)
|
||||
binary.BigEndian.PutUint32(lenBuf, uint32(len(body)))
|
||||
conn.Write(lenBuf)
|
||||
conn.Write(body)
|
||||
io.ReadFull(conn, lenBuf)
|
||||
msgLen := binary.BigEndian.Uint32(lenBuf)
|
||||
respBuf := make([]byte, msgLen)
|
||||
io.ReadFull(conn, respBuf)
|
||||
var resp ipcResp
|
||||
if err := json.Unmarshal(respBuf, &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Status != "ok" {
|
||||
return nil, fmt.Errorf("ipc: %s", resp.ErrorDetail)
|
||||
}
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
// 枚举(与 internal/storage/delete_reason.go 保持一致)
|
||||
const (
|
||||
DRMergeDup = "merge_dup"
|
||||
DRContradiction = "contradiction"
|
||||
DRManual = "manual"
|
||||
DRRetention = "retention"
|
||||
DRUnknown = "unknown"
|
||||
)
|
||||
|
||||
// Normalize 把 free-form reason 归一到枚举(与 storage.NormalizeDeleteReason 同规则)。
|
||||
func Normalize(reason string) string {
|
||||
r := strings.ToLower(strings.TrimSpace(reason))
|
||||
if r == "" {
|
||||
return DRUnknown
|
||||
}
|
||||
switch {
|
||||
case strings.HasPrefix(r, "batch:"):
|
||||
return DRUnknown
|
||||
case strings.Contains(r, "manual"), strings.Contains(r, "用户"),
|
||||
strings.Contains(r, "user"), strings.Contains(r, "feedback"),
|
||||
strings.Contains(r, "human"), strings.Contains(r, "人工"):
|
||||
return DRManual
|
||||
case strings.Contains(r, "dedup"), strings.Contains(r, "wording"),
|
||||
strings.Contains(r, "duplicate"), strings.Contains(r, "merged"),
|
||||
strings.Contains(r, "merge"):
|
||||
return DRMergeDup
|
||||
case strings.Contains(r, "conflict"), strings.Contains(r, "contradict"),
|
||||
strings.Contains(r, "consolidate"):
|
||||
return DRContradiction
|
||||
case strings.Contains(r, "auto_forget"), strings.Contains(r, "ephemeral"),
|
||||
strings.Contains(r, "fragment"), strings.Contains(r, "expire"),
|
||||
strings.Contains(r, "retention"), strings.Contains(r, "过期"),
|
||||
strings.Contains(r, "自动"):
|
||||
return DRRetention
|
||||
default:
|
||||
return DRUnknown
|
||||
}
|
||||
}
|
||||
|
||||
type deletedRow struct {
|
||||
ID string `json:"id"`
|
||||
DeleteReason string `json:"delete_reason"`
|
||||
}
|
||||
|
||||
// loadTombstoneReasons 从 sqlite tombstones 表读取 original_id → reason 映射。
|
||||
// 文件不存在/表不存在 ⇒ 空映射(全部落 unknown)。
|
||||
func loadTombstoneReasons(path string) (map[string]string, error) {
|
||||
out := map[string]string{}
|
||||
if path == "" {
|
||||
return out, nil
|
||||
}
|
||||
if _, err := os.Stat(path); err != nil {
|
||||
return out, nil // 无 tombstone 库 ⇒ 尽力判定为 0,全 unknown
|
||||
}
|
||||
// 复用系统 sqlite3 CLI 最简读法(避免 CGO 依赖);库通常只在 SQLite 后端写入。
|
||||
// 生产 LanceDB 后端 tombstones 表是空(软删直接写 memories.is_deleted),
|
||||
// 故此处判不出是常态 —— 符合「判不出的写 unknown」。
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
sock := flag.String("socket", "/tmp/zhiyi-ipc.sock", "rust sidecar unix socket")
|
||||
tombstones := flag.String("tombstones", "", "可选:sqlite tombstones 库路径(尽力判定用)")
|
||||
apply := flag.Bool("apply", false, "真正写库(默认 false = dry-run;未经终审禁止 true)")
|
||||
flag.Parse()
|
||||
|
||||
resp, err := rpc(*sock, ipcReq{Type: "lancedb_scan_deleted"})
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "scan_deleted 失败:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
var rows []deletedRow
|
||||
if err := json.Unmarshal([]byte(resp.ReportJSON), &rows); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "unmarshal 失败:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
tombReasons, _ := loadTombstoneReasons(*tombstones)
|
||||
N := len(rows)
|
||||
|
||||
// 分类:存量已回填(非空 reason)跳过;未回填的按 tombstone 尽力判定,判不出 unknown。
|
||||
hist := map[string]int{}
|
||||
skipFilled := 0
|
||||
toWrite := map[string]string{} // id -> reason
|
||||
for _, r := range rows {
|
||||
if r.DeleteReason != "" {
|
||||
skipFilled++ // 已回填,跳过
|
||||
continue
|
||||
}
|
||||
reason := DRUnknown
|
||||
if tr, ok := tombReasons[r.ID]; ok && tr != "" {
|
||||
reason = Normalize(tr)
|
||||
}
|
||||
toWrite[r.ID] = reason
|
||||
hist[reason]++
|
||||
}
|
||||
|
||||
fmt.Printf("已删除行总数 N = %d\n", N)
|
||||
fmt.Printf(" 已有 delete_reason(跳过) = %d\n", skipFilled)
|
||||
fmt.Printf(" 待回填 = %d\n", len(toWrite))
|
||||
fmt.Println("── delete_reason 直方图(value→行数,仅待回填)──")
|
||||
order := []string{DRMergeDup, DRContradiction, DRManual, DRRetention, DRUnknown}
|
||||
keys := make([]string, 0, len(hist))
|
||||
for k := range hist {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, k := range order {
|
||||
fmt.Printf("[%s] %d\n", k, hist[k])
|
||||
}
|
||||
|
||||
if *apply {
|
||||
if len(toWrite) == 0 {
|
||||
fmt.Println("apply: 无可回填行(全部已回填或已删除行为空)。")
|
||||
} else {
|
||||
fmt.Printf("apply: 将逐条 Update %d 行 delete_reason(id IN ... 分批)。—— 未经终审禁止。\n", len(toWrite))
|
||||
// 实际写入走 lancedb_update(每 id 一条,带 delete_reason + is_deleted 保持 true)。
|
||||
// 实现:对每 id 发 lancedb_update fields=[{column:delete_reason,value:'<reason>'}]
|
||||
// 注意:**只写 delete_reason,不碰其它字段**(禁改已删除记录其它字段)。
|
||||
var wrote int64
|
||||
for id, reason := range toWrite {
|
||||
fields := fmt.Sprintf(`[{"column":"delete_reason","value":"'%s'"}]`, reason)
|
||||
r, err := rpc(*sock, ipcReq{Type: "lancedb_update", Table: "memories", ID: id, Fields: fields})
|
||||
_ = r
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "update %s 失败: %v\n", id, err)
|
||||
continue
|
||||
}
|
||||
wrote++
|
||||
}
|
||||
fmt.Printf("apply: 已写 %d 行 delete_reason。\n", wrote)
|
||||
}
|
||||
} else {
|
||||
fmt.Println("(dry-run) 未写库。输出须先经小怡终审,批准后才可 --apply。")
|
||||
}
|
||||
}
|
||||
@@ -93,7 +93,7 @@ func main() {
|
||||
if err != nil || t.Before(epochThreshold) || t.Year() < 2024 {
|
||||
// 用确定性派生时间(避免所有epoch-0都用同一时间)
|
||||
// 基于 ID 哈希分配 2024-2026 之间的不同日期
|
||||
offsetDays := int(len(m.ID)%(365*2)) // 0-729天
|
||||
offsetDays := int(len(m.ID) % (365 * 2)) // 0-729天
|
||||
newTime := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC).AddDate(0, 0, offsetDays)
|
||||
ts := newTime.Format(time.RFC3339)
|
||||
if err := ipcUpdate(m.ID, "created_at", ts); err != nil {
|
||||
@@ -107,4 +107,4 @@ func main() {
|
||||
}
|
||||
|
||||
log.Printf("\n完成: 修复 %d/%d 条记忆时间戳\n", fixed, len(memories))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
// 织忆·确定性判据强化 影子探针(t_2515307a)—— 只记录,不施加
|
||||
//
|
||||
// 职责:从线上 zhiyid 拉真实召回候选(top_k=50),对每条内容跑
|
||||
// distill.RecallRuleVerdict(真实 Go 规则,零漂移),输出
|
||||
// keep / demote / drop 三组 + 每条 reason,供 AC3(结果变化对照)
|
||||
// 与 AC4(人工抽检被过滤项)取证。不改生产行为、不写库。
|
||||
//
|
||||
// 用法:
|
||||
// cd go && go run ./cmd/rulefirst-probe # 默认组查询
|
||||
// cd go && go run ./cmd/rulefirst-probe --query "..." # 单条指定
|
||||
// cd go && go run ./cmd/rulefirst-probe --out /tmp/rf.json # 落盘供 AC4 抽检
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/distill"
|
||||
"github.com/xiaoxue/memoryweave/internal/models"
|
||||
)
|
||||
|
||||
var defaultQueries = []string{
|
||||
"家庭服务器 IP 星空组网 VPN",
|
||||
"gateway 模型 配置 端口",
|
||||
"看板 任务 派发 验收 回写",
|
||||
"记忆 召回 反馈 闭环 使用",
|
||||
"脚本 审批 登记 门禁",
|
||||
"织忆 LanceDB 遗忘 窗口",
|
||||
"小唯 工作笔记 待并入 经验",
|
||||
"配置文件 备份 恢复 路径",
|
||||
"本地模型 2B 双槽 队列代理",
|
||||
"牧尘 偏好 咖啡 习惯",
|
||||
}
|
||||
|
||||
func apiKey() string {
|
||||
b, err := os.ReadFile("/var/lib/memoryweave/.api-key")
|
||||
if err == nil {
|
||||
for _, line := range strings.Split(string(b), "\n") {
|
||||
s := strings.TrimSpace(line)
|
||||
if s != "" && !strings.HasPrefix(s, "#") && !strings.Contains(s, "legacy") {
|
||||
return strings.Fields(s)[0]
|
||||
}
|
||||
}
|
||||
}
|
||||
return os.Getenv("ZHIYI_API_KEY")
|
||||
}
|
||||
|
||||
func recall(query string, topK int) ([]models.RecallResult, error) {
|
||||
body, _ := json.Marshal(map[string]any{"query": query, "top_k": topK, "namespace": ""})
|
||||
req, err := http.NewRequest("POST", "http://127.0.0.1:7821/api/v1/recall", strings.NewReader(string(body)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-API-Key", apiKey())
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
var d struct {
|
||||
Results []models.RecallResult `json:"results"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &d); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal: %w", err)
|
||||
}
|
||||
return d.Results, nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
var q, out string
|
||||
flag.StringVar(&q, "query", "", "指定单条 query(默认跑内置 10 条)")
|
||||
flag.StringVar(&out, "out", "", "落盘 JSON 路径(供 AC4 抽检)")
|
||||
flag.Parse()
|
||||
|
||||
queries := defaultQueries
|
||||
if q != "" {
|
||||
queries = []string{q}
|
||||
}
|
||||
|
||||
type item struct {
|
||||
Query string `json:"query"`
|
||||
ID string `json:"id"`
|
||||
Content string `json:"content"`
|
||||
Verdict string `json:"verdict"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
var all []item
|
||||
var keep, demote, drop []item
|
||||
byQ := map[string][3][]item{}
|
||||
|
||||
for _, query := range queries {
|
||||
res, err := recall(query, 50)
|
||||
if err != nil {
|
||||
fmt.Printf("QUERY %q ERR %v\n", query, err)
|
||||
continue
|
||||
}
|
||||
var kk, dd, drr []item
|
||||
toItem := func(r models.RecallResult, v distill.RecallVerdict, why string) item {
|
||||
return item{Query: query, ID: r.ID, Content: r.Content, Verdict: verdictName(v), Reason: why}
|
||||
}
|
||||
// 每条候选跑真实 Go 规则
|
||||
for _, r := range res {
|
||||
v, why := distill.RecallRuleVerdict(r.Content)
|
||||
it := toItem(r, v, why)
|
||||
all = append(all, it)
|
||||
switch v {
|
||||
case distill.RecallKeep:
|
||||
kk = append(kk, it)
|
||||
case distill.RecallDemote:
|
||||
dd = append(dd, it)
|
||||
case distill.RecallDrop:
|
||||
drr = append(drr, it)
|
||||
}
|
||||
}
|
||||
keep = append(keep, kk...)
|
||||
demote = append(demote, dd...)
|
||||
drop = append(drop, drr...)
|
||||
byQ[query] = [3][]item{kk, dd, drr}
|
||||
fmt.Printf("QUERY %q → 候选=%d keep=%d demote=%d drop=%d\n",
|
||||
query, len(res), len(kk), len(dd), len(drr))
|
||||
for _, it := range drr {
|
||||
fmt.Printf(" [DROP] %-30s %s | %s\n", it.ID, it.Reason, truncate(it.Content, 42))
|
||||
}
|
||||
for _, it := range dd {
|
||||
fmt.Printf(" [DEMOTE] %-30s %s | %s\n", it.ID, it.Reason, truncate(it.Content, 42))
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Printf("\n=== 汇总: 候选总数=%d keep=%d demote=%d drop=%d ===\n",
|
||||
len(all), len(keep), len(demote), len(drop))
|
||||
|
||||
if out != "" {
|
||||
f, err := os.Create(out)
|
||||
if err == nil {
|
||||
enc := json.NewEncoder(f)
|
||||
enc.SetIndent("", " ")
|
||||
_ = enc.Encode(map[string]any{
|
||||
"all": all,
|
||||
"keep": keep,
|
||||
"demote": demote,
|
||||
"drop": drop,
|
||||
"by_query": byQ,
|
||||
})
|
||||
f.Close()
|
||||
fmt.Printf("已落盘 %s\n", out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func verdictName(v distill.RecallVerdict) string {
|
||||
switch v {
|
||||
case distill.RecallKeep:
|
||||
return "keep"
|
||||
case distill.RecallDemote:
|
||||
return "demote"
|
||||
default:
|
||||
return "drop"
|
||||
}
|
||||
}
|
||||
|
||||
func truncate(s string, n int) string {
|
||||
r := []rune(s)
|
||||
if len(r) <= n {
|
||||
return s
|
||||
}
|
||||
return string(r[:n]) + "…"
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
// 织忆·确定性判据扫描(t_2515307a 取证)——按 namespace 分批扫全表,输出 drop/demote 明细供 AC4
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/distill"
|
||||
)
|
||||
|
||||
func apikey() string {
|
||||
b, _ := os.ReadFile("/var/lib/memoryweave/.api-key")
|
||||
for _, l := range strings.Split(string(b), "\n") {
|
||||
s := strings.TrimSpace(l)
|
||||
if s != "" && !strings.HasPrefix(s, "#") && !strings.Contains(s, "legacy") {
|
||||
return strings.Fields(s)[0]
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func list(ns string, limit int) ([]struct {
|
||||
ID string `json:"id"`
|
||||
Content string `json:"content"`
|
||||
}, error) {
|
||||
u := fmt.Sprintf("http://127.0.0.1:7821/api/v1/memories?limit=%d", limit)
|
||||
if ns != "" {
|
||||
u += "&namespace=" + ns
|
||||
}
|
||||
req, _ := http.NewRequest("GET", u, nil)
|
||||
req.Header.Set("X-API-Key", apikey())
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<26))
|
||||
var d struct {
|
||||
Memories []struct {
|
||||
ID string `json:"id"`
|
||||
Content string `json:"content"`
|
||||
} `json:"memories"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &d); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return d.Memories, nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
namespaces := []string{
|
||||
"", "hermes-main", "shared", "wiki-curator-main", "wiki", "soulful-xiaowei",
|
||||
"a06-main", "domain:dev", "default-main", "hermes", "wiki:decision",
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
var all []struct {
|
||||
ID string `json:"id"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
for _, ns := range namespaces {
|
||||
ms, err := list(ns, 1000)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, m := range ms {
|
||||
if !seen[m.ID] {
|
||||
seen[m.ID] = true
|
||||
all = append(all, m)
|
||||
}
|
||||
}
|
||||
}
|
||||
type rec struct {
|
||||
ID string
|
||||
Content string
|
||||
Why string
|
||||
}
|
||||
var drops, demotes []rec
|
||||
for _, m := range all {
|
||||
v, why := distill.RecallRuleVerdict(m.Content)
|
||||
if v == distill.RecallDrop {
|
||||
drops = append(drops, rec{m.ID, m.Content, why})
|
||||
} else if v == distill.RecallDemote {
|
||||
demotes = append(demotes, rec{m.ID, m.Content, why})
|
||||
}
|
||||
}
|
||||
fmt.Printf("unique_total=%d drops=%d demotes=%d\n\n", len(all), len(drops), len(demotes))
|
||||
fmt.Println("===== DROPS (进不了 top-N) =====")
|
||||
for i, d := range drops {
|
||||
rc := []rune(d.Content)
|
||||
c := d.Content
|
||||
if len(rc) > 55 {
|
||||
c = string(rc[:55]) + "…"
|
||||
}
|
||||
fmt.Printf("%2d. [%s] %s\n", i+1, d.Why, c)
|
||||
}
|
||||
fmt.Println("\n===== DEMOTES (降权) =====")
|
||||
for i, d := range demotes {
|
||||
rc := []rune(d.Content)
|
||||
c := d.Content
|
||||
if len(rc) > 55 {
|
||||
c = string(rc[:55]) + "…"
|
||||
}
|
||||
fmt.Printf("%2d. [%s] %s\n", i+1, d.Why, c)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
// 织忆 MemoryWeave — not_useful_count 拆分迁移工具(GA-P0-1 t_718d8707)
|
||||
//
|
||||
// 背景:not_useful_count 被两种语义混写——用户人工点「没用」(feedback.go
|
||||
// MarkNotUseful)与 dedup/合并流程自动降权(core.go Dedup demote)都写同一个字段。
|
||||
// 本工具把存量 not_useful_count 按来源拆分到 human_not_useful_count /
|
||||
// dedup_downweight_count。
|
||||
//
|
||||
// 分类依据(可判 M 条):本库**无任何 per-row 来源 provenance**——feedback 与
|
||||
// dedup 都不在行上留下可辨识标记(source 只是「哪条管道进来」,非「人点还是 dedup」)。
|
||||
// 故对存量行无法按来源判定:M=0,全部归 unknown(K=N)。apply 在 M=0 时是 no-op,
|
||||
// 不会改动任何存量数据(保守安全)。
|
||||
//
|
||||
// 用法(**dry-run 默认,apply 需显式 --apply,且须经小怡终审后才允许跑**):
|
||||
//
|
||||
// go run ./cmd/split_notuseful --socket /tmp/zhiyi-ipc.sock # dry-run
|
||||
// go run ./cmd/split_notuseful --socket /tmp/zhiyi-ipc.sock --apply # 真写(禁未审批)
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"sort"
|
||||
)
|
||||
|
||||
type ipcReq struct {
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
type ipcResp struct {
|
||||
Status string `json:"status"`
|
||||
ReportJSON string `json:"report_json"`
|
||||
ErrorDetail string `json:"error_detail"`
|
||||
}
|
||||
|
||||
func rpc(sock string, req ipcReq) (*ipcResp, error) {
|
||||
conn, err := net.DialTimeout("unix", sock, 5e9)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ipc dial %s: %w", sock, err)
|
||||
}
|
||||
defer conn.Close()
|
||||
body, _ := json.Marshal(req)
|
||||
lenBuf := make([]byte, 4)
|
||||
binary.BigEndian.PutUint32(lenBuf, uint32(len(body)))
|
||||
conn.Write(lenBuf)
|
||||
conn.Write(body)
|
||||
io.ReadFull(conn, lenBuf)
|
||||
msgLen := binary.BigEndian.Uint32(lenBuf)
|
||||
respBuf := make([]byte, msgLen)
|
||||
io.ReadFull(conn, respBuf)
|
||||
var resp ipcResp
|
||||
if err := json.Unmarshal(respBuf, &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Status != "ok" {
|
||||
return nil, fmt.Errorf("ipc: %s", resp.ErrorDetail)
|
||||
}
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
type row struct {
|
||||
ID string `json:"id"`
|
||||
Source string `json:"source"`
|
||||
Category string `json:"category"`
|
||||
UsefulCount int `json:"useful_count"`
|
||||
NotUsefulCount int `json:"not_useful_count"`
|
||||
HumanNotUsefulCount int `json:"human_not_useful_count"`
|
||||
DedupDownweightCount int `json:"dedup_downweight_count"`
|
||||
}
|
||||
|
||||
// classifyBySource 按来源判定归属。返回 "human" / "dedup" / "unknown"。
|
||||
// 当前 schema 无 per-row 来源 provenance ⇒ 恒 unknown(M=0)。
|
||||
// 将来若某来源可明确标识「人工反馈」或「dedup 降权」,在此追加映射即可。
|
||||
func classifyBySource(_ row) string {
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
func main() {
|
||||
sock := flag.String("socket", "/tmp/zhiyi-ipc.sock", "rust sidecar unix socket")
|
||||
apply := flag.Bool("apply", false, "真正写库(默认 false = dry-run;未经终审禁止 true)")
|
||||
flag.Parse()
|
||||
|
||||
resp, err := rpc(*sock, ipcReq{Type: "lancedb_scan_all"})
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "scan_all 失败:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
var rows []row
|
||||
if err := json.Unmarshal([]byte(resp.ReportJSON), &rows); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "unmarshal 失败:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
var nu []row
|
||||
for _, r := range rows {
|
||||
if r.NotUsefulCount > 0 {
|
||||
nu = append(nu, r)
|
||||
}
|
||||
}
|
||||
N := len(nu)
|
||||
|
||||
// 分类
|
||||
humanIDs := map[string]int{} // id -> count
|
||||
dedupIDs := map[string]int{} // id -> count
|
||||
unknownIDs := map[string]int{}
|
||||
for _, r := range nu {
|
||||
switch classifyBySource(r) {
|
||||
case "human":
|
||||
humanIDs[r.ID] = r.NotUsefulCount
|
||||
case "dedup":
|
||||
dedupIDs[r.ID] = r.NotUsefulCount
|
||||
default:
|
||||
unknownIDs[r.ID] = r.NotUsefulCount
|
||||
}
|
||||
}
|
||||
M := len(humanIDs) + len(dedupIDs)
|
||||
K := len(unknownIDs)
|
||||
|
||||
// 3 字段直方图(当前存量值分布)
|
||||
hist := map[string]map[int]int{}
|
||||
hist["not_useful_count"] = map[int]int{}
|
||||
hist["human_not_useful_count"] = map[int]int{}
|
||||
hist["dedup_downweight_count"] = map[int]int{}
|
||||
for _, r := range rows {
|
||||
hist["not_useful_count"][r.NotUsefulCount]++
|
||||
hist["human_not_useful_count"][r.HumanNotUsefulCount]++
|
||||
hist["dedup_downweight_count"][r.DedupDownweightCount]++
|
||||
}
|
||||
|
||||
fmt.Printf("总行数(存活): %d\n", len(rows))
|
||||
fmt.Printf("not_useful_count>0 待改行数 N = %d\n", N)
|
||||
fmt.Printf(" 其中可按来源判定 M = %d (human=%d dedup=%d)\n", M, len(humanIDs), len(dedupIDs))
|
||||
fmt.Printf(" 无法判定归 unknown K = %d\n", K)
|
||||
fmt.Println("── 3 字段直方图(value→行数,仅列当前非零分布)──")
|
||||
order := []string{"not_useful_count", "human_not_useful_count", "dedup_downweight_count"}
|
||||
for _, f := range order {
|
||||
m := hist[f]
|
||||
keys := make([]int, 0, len(m))
|
||||
for k := range m {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Ints(keys)
|
||||
fmt.Printf("[%s] ", f)
|
||||
if len(keys) == 1 && keys[0] == 0 {
|
||||
fmt.Println("全 0(0 行非零)")
|
||||
continue
|
||||
}
|
||||
parts := []string{}
|
||||
for _, k := range keys {
|
||||
if k == 0 {
|
||||
continue
|
||||
}
|
||||
parts = append(parts, fmt.Sprintf("%d×%d", k, m[k]))
|
||||
}
|
||||
fmt.Println(parts)
|
||||
}
|
||||
|
||||
if *apply {
|
||||
if M == 0 {
|
||||
fmt.Println("apply: 无可判定行(M=0),无需迁移,存量 not_useful_count 保持原样。")
|
||||
} else {
|
||||
fmt.Printf("apply: 将拆分 %d 行(human=%d dedup=%d)—— 需逐条 Update。\n", M, len(humanIDs), len(dedupIDs))
|
||||
}
|
||||
} else {
|
||||
fmt.Println("(dry-run) 未写库。输出须先经小怡终审,批准后才可 --apply。")
|
||||
}
|
||||
}
|
||||
+119
-30
@@ -10,6 +10,7 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
@@ -28,6 +29,7 @@ const (
|
||||
// 3. /var/lib/memoryweave/.api-key 文件(**多行格式**:注释与 `legacy:` 行跳过,
|
||||
// 取第 1 个非注释非 legacy 行 = 主密钥)
|
||||
// 4. 均无 → 返回 error,调用方退出
|
||||
//
|
||||
// 🔴 2026-09-21 修:原实现 `TrimSpace(整份文件)` 在多行 key 文件下会把
|
||||
// 「注释头 + 主密钥 + legacy 行」整块当 key 发给服务端 → 必然 401。
|
||||
func resolveAPIKey(flagKey string) (string, error) {
|
||||
@@ -52,9 +54,9 @@ func resolveAPIKey(flagKey string) (string, error) {
|
||||
// ─── 全局参数 ──────────────────────────────────────────────
|
||||
|
||||
var (
|
||||
apiURL = flag.String("url", getEnv("ZHIYI_API_URL", apiURLDefault), "织忆 API 地址")
|
||||
apiKey = flag.String("key", getEnv("ZHIYI_API_KEY", apiKeyDefault), "API Key")
|
||||
ns = flag.String("n", getEnv("ZHIYI_NAMESPACE", namespaceDefault), "命名空间")
|
||||
apiURL = flag.String("url", getEnv("ZHIYI_API_URL", apiURLDefault), "织忆 API 地址")
|
||||
apiKey = flag.String("key", getEnv("ZHIYI_API_KEY", apiKeyDefault), "API Key")
|
||||
ns = flag.String("n", getEnv("ZHIYI_NAMESPACE", namespaceDefault), "命名空间")
|
||||
)
|
||||
|
||||
// ─── 入口 ─────────────────────────────────────────────────
|
||||
@@ -81,11 +83,18 @@ func main() {
|
||||
|
||||
var runErr error
|
||||
switch cmd {
|
||||
case "tree": runErr = runTree(args, apiKeyVal)
|
||||
case "graph": runErr = runGraph(args, apiKeyVal)
|
||||
case "recall": runErr = runRecall(args, apiKeyVal)
|
||||
case "stats": runErr = runStats(apiKeyVal)
|
||||
case "entity": runErr = runEntity(args, apiKeyVal)
|
||||
case "tree":
|
||||
runErr = runTree(args, apiKeyVal)
|
||||
case "graph":
|
||||
runErr = runGraph(args, apiKeyVal)
|
||||
case "recall":
|
||||
runErr = runRecall(args, apiKeyVal)
|
||||
case "stats":
|
||||
runErr = runStats(apiKeyVal)
|
||||
case "entity":
|
||||
runErr = runEntity(args, apiKeyVal)
|
||||
case "pattern":
|
||||
runErr = runPattern(args, apiKeyVal)
|
||||
case "help", "--help", "-h":
|
||||
flag.Usage()
|
||||
os.Exit(0)
|
||||
@@ -124,6 +133,7 @@ func usage() {
|
||||
recall <query> 语义搜索,返回 top-10 结果
|
||||
stats 显示系统统计(记忆数、蒸馏状态等)
|
||||
entity <name> 查询实体详情(出现次数、关联记忆)
|
||||
pattern <detect|list> L2 模式检测/列出(detect=手动触发检测,list=列出已检测)
|
||||
|
||||
示例:
|
||||
zhiyi tree
|
||||
@@ -188,11 +198,11 @@ func runTree(args []string, apiKey string) error {
|
||||
// 从图谱 export 获取节点(带 category),按 category 分组
|
||||
var r struct {
|
||||
Nodes []struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type,omitempty"`
|
||||
Category string `json:"category,omitempty"`
|
||||
Weight float64 `json:"weight,omitempty"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type,omitempty"`
|
||||
Category string `json:"category,omitempty"`
|
||||
Weight float64 `json:"weight,omitempty"`
|
||||
} `json:"nodes"`
|
||||
Edges []struct {
|
||||
Source string `json:"source"`
|
||||
@@ -235,12 +245,12 @@ func runTree(args []string, apiKey string) error {
|
||||
fmt.Println(strings.Repeat("─", 50))
|
||||
|
||||
catIcons := map[string]string{
|
||||
"人物": "👤",
|
||||
"项目": "📦",
|
||||
"事件": "📅",
|
||||
"概念": "💡",
|
||||
"位置": "📍",
|
||||
"组织": "🏢",
|
||||
"人物": "👤",
|
||||
"项目": "📦",
|
||||
"事件": "📅",
|
||||
"概念": "💡",
|
||||
"位置": "📍",
|
||||
"组织": "🏢",
|
||||
"distilled": "🔄",
|
||||
}
|
||||
for _, cat := range cats {
|
||||
@@ -289,14 +299,14 @@ func runGraph(args []string, apiKey string) error {
|
||||
}
|
||||
|
||||
type navigateResp struct {
|
||||
Entity string `json:"entity"`
|
||||
Count int `json:"count"`
|
||||
Entity string `json:"entity"`
|
||||
Count int `json:"count"`
|
||||
Paths []struct {
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
Relation string `json:"relation"`
|
||||
Hop int `json:"hop"`
|
||||
Weight float64 `json:"weight"`
|
||||
Hop int `json:"hop"`
|
||||
Weight float64 `json:"weight"`
|
||||
} `json:"paths"`
|
||||
}
|
||||
var resp navigateResp
|
||||
@@ -423,10 +433,10 @@ func runStats(apiKey string) error {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
var distStatus struct {
|
||||
QueueLen int `json:"queue_len"`
|
||||
DailyUsed int `json:"daily_used"`
|
||||
DailyLimit int `json:"daily_limit"`
|
||||
BatchSize int `json:"batch_size"`
|
||||
QueueLen int `json:"queue_len"`
|
||||
DailyUsed int `json:"daily_used"`
|
||||
DailyLimit int `json:"daily_limit"`
|
||||
BatchSize int `json:"batch_size"`
|
||||
}
|
||||
|
||||
apiGet("/api/v1/stats", &stats, apiKey)
|
||||
@@ -455,6 +465,85 @@ func runStats(apiKey string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// runPattern L2 模式检测 CLI 子命令(t_d32e5f8a,cron 单发)。
|
||||
// 子命令:
|
||||
// zhiyi pattern detect [--limit N] 触发检测(扫 L1 蒸馏记忆 → 工具组合/路径聚类 → 写 graph_nodes)
|
||||
// zhiyi pattern list [N] 列出已检测的 pattern(默认 20)
|
||||
func runPattern(args []string, apiKey string) error {
|
||||
// 子命令(默认 detect)
|
||||
sub := "detect"
|
||||
rest := []string{}
|
||||
if len(args) > 0 {
|
||||
// 允许 "detect" / "list" 显式指定,或把第一个参数当 limit(list N)
|
||||
switch args[0] {
|
||||
case "detect", "list":
|
||||
sub = args[0]
|
||||
rest = args[1:]
|
||||
default:
|
||||
// 数字参数 = list 的 limit
|
||||
if n, err := strconv.Atoi(args[0]); err == nil && n > 0 {
|
||||
sub = "list"
|
||||
rest = []string{args[0]}
|
||||
} else {
|
||||
rest = args
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if sub == "list" {
|
||||
limit := "20"
|
||||
if len(rest) > 0 {
|
||||
limit = rest[0]
|
||||
}
|
||||
var resp struct {
|
||||
Patterns []struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Name string `json:"name"`
|
||||
Confidence float64 `json:"confidence"`
|
||||
Tools []string `json:"tools"`
|
||||
} `json:"patterns"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
if err := apiGet("/api/v1/patterns?limit="+limit, &resp, apiKey); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("📐 已检测模式 [%s] (%d)\n", *ns, resp.Count)
|
||||
fmt.Println(strings.Repeat("─", 50))
|
||||
for i, p := range resp.Patterns {
|
||||
if i >= 30 {
|
||||
fmt.Printf(" … 还有 %d 个\n", len(resp.Patterns)-30)
|
||||
break
|
||||
}
|
||||
tools := ""
|
||||
if len(p.Tools) > 0 {
|
||||
tools = strings.Join(p.Tools, ",")
|
||||
}
|
||||
fmt.Printf(" [%s] %s conf=%.2f %s\n", p.Type, p.Name, p.Confidence, tools)
|
||||
}
|
||||
if resp.Count == 0 {
|
||||
fmt.Println(" (暂无已检测模式)")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// detect
|
||||
var resp struct {
|
||||
Scanned int `json:"scanned"`
|
||||
Created int `json:"created"`
|
||||
Updated int `json:"updated"`
|
||||
Detected int `json:"detected"`
|
||||
}
|
||||
if err := apiPost("/api/v1/patterns/detect", map[string]interface{}{
|
||||
"namespace": *ns,
|
||||
}, &resp, apiKey); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("🔬 L2 模式检测 [%s] 扫描 %d 条 → 命中 %d(新建 %d / 更新 %d)\n",
|
||||
*ns, resp.Scanned, resp.Detected, resp.Created, resp.Updated)
|
||||
return nil
|
||||
}
|
||||
|
||||
func runEntity(args []string, apiKey string) error {
|
||||
if len(args) == 0 {
|
||||
return fmt.Errorf("用法: zhiyi entity <name>")
|
||||
@@ -591,4 +680,4 @@ func box(style, s string) string {
|
||||
return "◉ " + s
|
||||
}
|
||||
return s
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,19 +16,19 @@ import (
|
||||
// ─── Per-Agent 令牌桶 ────────────────────────────────────────
|
||||
|
||||
type tokenBucket struct {
|
||||
tokens float64
|
||||
tokens float64
|
||||
lastRefill time.Time
|
||||
rate float64 // tokens/sec
|
||||
burst float64
|
||||
mu sync.Mutex
|
||||
rate float64 // tokens/sec
|
||||
burst float64
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func newTokenBucket(rate, burst float64) *tokenBucket {
|
||||
return &tokenBucket{
|
||||
tokens: burst,
|
||||
tokens: burst,
|
||||
lastRefill: time.Now(),
|
||||
rate: rate,
|
||||
burst: burst,
|
||||
rate: rate,
|
||||
burst: burst,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,10 +58,10 @@ type AgentRateConfig struct {
|
||||
}
|
||||
|
||||
var agentRates = map[string]AgentRateConfig{
|
||||
"hermes": {RecallQPS: 10, CommitQPS: 2, Burst: 20},
|
||||
"hermes-a06":{RecallQPS: 10, CommitQPS: 2, Burst: 20},
|
||||
"openclaw": {RecallQPS: 10, CommitQPS: 2, Burst: 20},
|
||||
"cron-job": {RecallQPS: 5, CommitQPS: 1, Burst: 10},
|
||||
"hermes": {RecallQPS: 10, CommitQPS: 2, Burst: 20},
|
||||
"hermes-a06": {RecallQPS: 10, CommitQPS: 2, Burst: 20},
|
||||
"openclaw": {RecallQPS: 10, CommitQPS: 2, Burst: 20},
|
||||
"cron-job": {RecallQPS: 5, CommitQPS: 1, Burst: 10},
|
||||
}
|
||||
|
||||
var defaultRate = AgentRateConfig{RecallQPS: 5, CommitQPS: 1, Burst: 10}
|
||||
@@ -69,14 +69,14 @@ var defaultRate = AgentRateConfig{RecallQPS: 5, CommitQPS: 1, Burst: 10}
|
||||
// ─── RateLimiter ─────────────────────────────────────────────
|
||||
|
||||
type RateLimiter struct {
|
||||
mu sync.Mutex
|
||||
buckets map[string]*tokenBucket // agentID → bucket
|
||||
maxPerMinute int // 全局兜底
|
||||
mu sync.Mutex
|
||||
buckets map[string]*tokenBucket // agentID → bucket
|
||||
maxPerMinute int // 全局兜底
|
||||
}
|
||||
|
||||
func NewRateLimiter(maxPerMinute int) *RateLimiter {
|
||||
return &RateLimiter{
|
||||
buckets: make(map[string]*tokenBucket),
|
||||
buckets: make(map[string]*tokenBucket),
|
||||
maxPerMinute: maxPerMinute,
|
||||
}
|
||||
}
|
||||
@@ -125,10 +125,14 @@ func init() {
|
||||
|
||||
// t_4fab32c1 AC2: 密钥强制(无硬编码回落)。
|
||||
// 🔑 2026-09-21 过渡期补丁(牧尘当晚批准上线):密钥文件为**多行**格式 ——
|
||||
// 第 1 个非注释行 = 主密钥;`legacy:` 前缀行 = 过渡期兼容密钥(放行但打 DEPRECATED 日志)。
|
||||
//
|
||||
// 第 1 个非注释行 = 主密钥;`legacy:` 前缀行 = 过渡期兼容密钥(放行但打 DEPRECATED 日志)。
|
||||
//
|
||||
// 为什么需要 legacy:hermes 记忆插件在 **import 时**读 `ZHIYI_API_KEY`,
|
||||
// 正在运行的网关不重启不会重读;另有 8 个本地脚本持旧密钥。
|
||||
// 若直接轮换值 → 瞬间打断记忆读写(recall/commit 全 401)。
|
||||
//
|
||||
// 正在运行的网关不重启不会重读;另有 8 个本地脚本持旧密钥。
|
||||
// 若直接轮换值 → 瞬间打断记忆读写(recall/commit 全 401)。
|
||||
//
|
||||
// 收口条件:客户端迁移完(网关重启后)删除 key 文件里的 legacy 行。
|
||||
const keyFile = "/var/lib/memoryweave/.api-key"
|
||||
|
||||
|
||||
@@ -24,4 +24,4 @@ func CORS() func(http.Handler) http.Handler {
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/governance"
|
||||
"github.com/xiaoxue/memoryweave/internal/memprotect"
|
||||
"github.com/xiaoxue/memoryweave/internal/storage"
|
||||
)
|
||||
|
||||
@@ -67,9 +68,15 @@ func (aa *AdminAPI) Forget(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
forgotten := 0
|
||||
// 2026-10-16 (t_944344b5) 遗忘保护守卫:本批加载一次保护状态(Redis vprop + protected_ids),
|
||||
// 命中任一保护规则的候选永不自动软删(fragment 与 ShouldForget 两条道都拦截)。
|
||||
protState := memprotect.LoadState()
|
||||
protected := 0
|
||||
for _, mem := range results {
|
||||
lastAccess := parseTimeStr(mem["last_recalled_at"])
|
||||
recallCnt := intVal(mem["recall_count"])
|
||||
// GA-P0-2 (t_c6d41ac6):衰减/遗忘只认 recall_verified_count(正反馈才是 V 值)。
|
||||
// recall_count 已冻结(历史虚高保命来源),seen 只用于观测,不参与衰减。
|
||||
recallCnt := intVal(mem["recall_verified_count"])
|
||||
tier := strVal(mem["tier"])
|
||||
content := strVal(mem["content"])
|
||||
|
||||
@@ -81,6 +88,15 @@ func (aa *AdminAPI) Forget(w http.ResponseWriter, r *http.Request) {
|
||||
if len([]rune(content)) > 200 {
|
||||
continue
|
||||
}
|
||||
// 🔒 2026-10-16 (t_944344b5) 遗忘保护守卫: 命中任一保护规则的候选
|
||||
// (category∈{decision,preference,pref} / V≥2.0 / freshness=verified /
|
||||
// protected_ids 名单 / distilled 且内容命中 10 个决策·偏好关键词) 永不自动软删。
|
||||
// 拦截 point 放在 fragment + ShouldForget 两条 SoftDelete 道之前。
|
||||
if isProt, protRule := memprotect.IsProtected(mem, protState); isProt {
|
||||
protected++
|
||||
log.Printf("[forget] protected skip id=%q rule=%s (遗忘保护守卫命中, 跳过自动遗忘)", strVal(mem["id"]), protRule)
|
||||
continue
|
||||
}
|
||||
// 2026-09-07 方案A 碎片快速道(与 server.go decay trigger 一致):
|
||||
// <30 字且 >20 天未访问 → 直接遗忘(碎片 recall_count 可能虚高, 绕过保命)
|
||||
if len([]rune(content)) < 30 && time.Since(lastAccess).Hours()/24 > 20 {
|
||||
@@ -115,13 +131,15 @@ func (aa *AdminAPI) Forget(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
respond(w, 200, map[string]interface{}{
|
||||
"status": "ok", "scanned": len(results), "forgotten": forgotten,
|
||||
// 2026-10-16 (t_944344b5):protected = 被遗忘保护守卫拦截、未软删的候选数
|
||||
"protected": protected,
|
||||
})
|
||||
}
|
||||
|
||||
// POST /api/v1/admin/purge-invalid
|
||||
// P1-1 2026-10-08: 一次性清理 id 为空的垃圾行(DB 存在 id/content/source 全空的 2 行,
|
||||
// 命中 <30 字碎片快速道 → SoftDelete("") 被 Rust 拒绝 → 每轮刷错误日志 + 遗忘计数虚高)。
|
||||
// 这些行无 id 无法按 id 软删,只能按 id='' 条件一次性软删(is_deleted=true)。
|
||||
// 这些行无 id 无法按 id 软删,只能按 id=” 条件一次性软删(is_deleted=true)。
|
||||
// ⚠️ 由验收/决策者按需调用(本实现不自动触发),本端点只提供能力 + 返回受影响行数。
|
||||
func (aa *AdminAPI) PurgeInvalid(w http.ResponseWriter, r *http.Request) {
|
||||
n, err := aa.LanceDB.PurgeInvalid()
|
||||
|
||||
@@ -19,9 +19,9 @@ import (
|
||||
// forgetMockLance 为 Forget 计数测试提供的 LanceDB 桩:
|
||||
// GetCandidatesForForgetting 可配置候选列表;SoftDelete 可配置失败/成功。
|
||||
type forgetMockLance struct {
|
||||
candidates []map[string]interface{}
|
||||
candidates []map[string]interface{}
|
||||
softDeleteErr error
|
||||
deletedIDs []string
|
||||
deletedIDs []string
|
||||
}
|
||||
|
||||
func (m *forgetMockLance) InsertEpisode(agentID, namespace, content, category string) (string, error) {
|
||||
@@ -53,19 +53,26 @@ func (m *forgetMockLance) GetCandidatesForForgetting() ([]map[string]interface{}
|
||||
func (m *forgetMockLance) GetSkillCandidates(minRecalls, limit int) ([]models.MemoryRecord, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (m *forgetMockLance) Backup(path string) error { return nil }
|
||||
func (m *forgetMockLance) Backup(path string) error { return nil }
|
||||
func (m *forgetMockLance) GetAuditLog(limit int) ([]map[string]interface{}, error) { return nil, nil }
|
||||
func (m *forgetMockLance) IncrementUseful(id string) error { return nil }
|
||||
func (m *forgetMockLance) IncrementNotUseful(id string) error { return nil }
|
||||
func (m *forgetMockLance) IncrementUseful(id string) error { return nil }
|
||||
func (m *forgetMockLance) IncrementNotUseful(id string) error { return nil }
|
||||
|
||||
// GA-P0-1 (t_718d8707):拆分字段
|
||||
func (m *forgetMockLance) IncrementHumanNotUseful(id string) error { return nil }
|
||||
func (m *forgetMockLance) AppendHitEvent(memoryID, outcome, reason string) error { return nil }
|
||||
func (m *forgetMockLance) CountHitEvents(memoryID, outcome string, since time.Time) (int, error) { return 0, nil }
|
||||
func (m *forgetMockLance) GetHitEvents(memoryID string, limit int) ([]models.HitEvent, error) { return nil, nil }
|
||||
func (m *forgetMockLance) IncrementDedupDownweight(id string) error { return nil }
|
||||
func (m *forgetMockLance) UpdateMemoryContent(id, newContent, source string) error { return nil }
|
||||
func (m *forgetMockLance) InsertMemory(mem models.MemoryRecord) error { return nil }
|
||||
func (m *forgetMockLance) InsertMemory(mem models.MemoryRecord) error { return nil }
|
||||
func (m *forgetMockLance) Search(table string, vector []float32, topK int, namespaceFilter string) ([]models.MemoryRecord, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (m *forgetMockLance) Scan(limit int, namespaceFilter string) ([]models.MemoryRecord, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (m *forgetMockLance) Insert(table string, record any) error { return nil }
|
||||
func (m *forgetMockLance) Insert(table string, record any) error { return nil }
|
||||
func (m *forgetMockLance) Update(table, id string, fields map[string]any) error {
|
||||
return nil
|
||||
}
|
||||
@@ -111,7 +118,7 @@ func callForget(t *testing.T, db *forgetMockLance) forgetResp {
|
||||
// 修前:失败照样 forgotten++ ⇒ 遗忘计数虚高(每轮刷日志 + 计数失真)。
|
||||
func TestForget_SoftDeleteFailure_DoesNotIncrement(t *testing.T) {
|
||||
db := &forgetMockLance{
|
||||
candidates: []map[string]interface{}{fragmentCandidate("mem_fail_1")},
|
||||
candidates: []map[string]interface{}{fragmentCandidate("mem_fail_1")},
|
||||
softDeleteErr: fmt.Errorf("ipc: simulated soft delete failure"),
|
||||
}
|
||||
resp := callForget(t, db)
|
||||
@@ -151,4 +158,4 @@ func TestForget_EmptyIDSkipped(t *testing.T) {
|
||||
t.Fatalf("空 id 候选不得调用 SoftDelete,实得 %v", db.deletedIDs)
|
||||
}
|
||||
t.Logf("✓ 空 id 候选跳过:forgotten=%d, SoftDelete 调用 0 次", resp.Forgotten)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,19 +2,41 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/distill"
|
||||
"github.com/xiaoxue/memoryweave/internal/governance"
|
||||
"github.com/xiaoxue/memoryweave/internal/metanote"
|
||||
"github.com/xiaoxue/memoryweave/internal/selfoptimize"
|
||||
)
|
||||
|
||||
// DistillEngineRef 全局蒸馏引擎引用(server.go 注入)
|
||||
var DistillEngineRef *distill.Engine
|
||||
|
||||
// CommitMeta 2026-10-08 (Gap#2):commit 时写入方携带的元数据,透传到蒸馏产物 MemoryRecord。
|
||||
// 集中成一个结构体而非继续加位置参数——8 个位置参数再加 2 个时,「忘记传」是必然的
|
||||
// (Gap#2 的接线缺口正是这类 bug:字段加了、没人传)。
|
||||
type CommitMeta struct {
|
||||
Source string // 出处(笔记路径等)→ MemoryRecord.Source
|
||||
EmbeddingModel string // 血缘 → MemoryRecord.EmbeddingModel
|
||||
ScriptVersion string // 血缘 → MemoryRecord.ScriptVersion
|
||||
Confidence *float64 // 信任等级(写入方显式声明,不从 source 反推);nil=未声明
|
||||
ConfidenceSource string // authoritative | estimated
|
||||
}
|
||||
|
||||
// AutoDistillTrigger commit 后自动触发蒸馏流水线
|
||||
// 2026-10-08 (t_7e3577c5):新增 embedModel/scriptVer 血缘字段透传
|
||||
func AutoDistillTrigger(episodeID string, content string, category string, namespace string, agentID string, source string, embedModel string, scriptVer string) {
|
||||
// 2026-10-08 (Gap#2):改为 CommitMeta 结构体,新增 confidence 透传
|
||||
func AutoDistillTrigger(episodeID string, content string, category string, namespace string, agentID string, meta CommitMeta) {
|
||||
// 2026-10-16 t_5ad3f843:meta-note 门禁(env ZHIYI_META_FILTER=1 启用;默认关闭=零行为变化)。
|
||||
// 蒸馏是事实写入的唯一咽喉:原文判 meta ⇒ 不进蒸馏(引擎路径与降级路径都挡),
|
||||
// 从源头杜绝 meta-note 生成 memories 事实(admin distill/force 也经此函数,一并覆盖)。
|
||||
if skip, reason := metanote.ShouldSkip(content); skip {
|
||||
log.Printf("[metanote] auto-distill skipped: ep=%s agent=%s reason=%s content=%.60s", episodeID, agentID, reason, content)
|
||||
return
|
||||
}
|
||||
|
||||
// 1. 硬规则过滤
|
||||
if !distill.HardRulesPass(content) {
|
||||
return
|
||||
@@ -23,14 +45,16 @@ func AutoDistillTrigger(episodeID string, content string, category string, names
|
||||
// 2. 使用蒸馏引擎
|
||||
if DistillEngineRef != nil {
|
||||
DistillEngineRef.Enqueue(distill.DistillInput{
|
||||
EpisodeID: episodeID,
|
||||
Content: content,
|
||||
Category: distill.Category(category),
|
||||
Namespace: namespace,
|
||||
AgentID: agentID,
|
||||
Source: source,
|
||||
EmbeddingModel: embedModel,
|
||||
ScriptVersion: scriptVer,
|
||||
EpisodeID: episodeID,
|
||||
Content: content,
|
||||
Category: distill.Category(category),
|
||||
Namespace: namespace,
|
||||
AgentID: agentID,
|
||||
Source: meta.Source,
|
||||
EmbeddingModel: meta.EmbeddingModel,
|
||||
ScriptVersion: meta.ScriptVersion,
|
||||
Confidence: meta.Confidence,
|
||||
ConfidenceSource: meta.ConfidenceSource,
|
||||
})
|
||||
} else {
|
||||
// 降级: 关键词提取
|
||||
@@ -40,6 +64,7 @@ func AutoDistillTrigger(episodeID string, content string, category string, names
|
||||
Facts: facts,
|
||||
Entities: extractEntities(content),
|
||||
Namespace: namespace,
|
||||
Source: meta.Source, // 2026-10-12 t_67d0279a 方案A:降级路径同样透传来源分档
|
||||
})
|
||||
}
|
||||
|
||||
@@ -93,8 +118,8 @@ func currentUnixMS() int64 {
|
||||
// ─── 全局引用(server.go 需要访问)─────────────────────
|
||||
|
||||
var (
|
||||
graphUpdater *governance.AutoGraphUpdater
|
||||
conflictScanner = governance.NewConflictDetector()
|
||||
graphUpdater *governance.AutoGraphUpdater
|
||||
conflictScanner = governance.NewConflictDetector()
|
||||
)
|
||||
|
||||
func SetGraphUpdater(gu *governance.AutoGraphUpdater) {
|
||||
@@ -102,6 +127,8 @@ func SetGraphUpdater(gu *governance.AutoGraphUpdater) {
|
||||
}
|
||||
|
||||
func minLen2(a, b int) int {
|
||||
if a < b { return a }
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
// Hermes / OpenClaw 的客户端库,零外部依赖
|
||||
//
|
||||
// 使用:
|
||||
// client := NewClient("http://localhost:7821", "mw-your-api-key")
|
||||
// mid, err := client.Commit("hermes", "shared", "牧尘用 Deepin 25", "system_fact")
|
||||
// results, err := client.Recall("牧尘系统是什么", 5)
|
||||
//
|
||||
// client := NewClient("http://localhost:7821", "mw-your-api-key")
|
||||
// mid, err := client.Commit("hermes", "shared", "牧尘用 Deepin 25", "system_fact")
|
||||
// results, err := client.Recall("牧尘系统是什么", 5)
|
||||
package routes
|
||||
|
||||
import (
|
||||
|
||||
@@ -36,7 +36,7 @@ func (ca *ConflictAPI) Resolve(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
ConflictID string `json:"conflict_id"`
|
||||
Resolution string `json:"resolution"` // keep_left / keep_right / merge / dismiss
|
||||
Winner string `json:"winner"` // id of the winning memory
|
||||
Winner string `json:"winner"` // id of the winning memory
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
respondError(w, 400, "invalid body")
|
||||
|
||||
@@ -24,7 +24,7 @@ type ConsolidationPipeline struct {
|
||||
graphUpdater *governance.AutoGraphUpdater
|
||||
conflicts *governance.ConflictDetector
|
||||
// Rust IPC 路径
|
||||
dataDir string
|
||||
dataDir string
|
||||
sqlitePath string
|
||||
}
|
||||
|
||||
@@ -249,7 +249,12 @@ func (cp *ConsolidationPipeline) mergeSimilar() (int, error) {
|
||||
// 保留较新的
|
||||
idI := strVal(mems[i]["id"])
|
||||
idJ := strVal(mems[j]["id"])
|
||||
_ = cp.ldb.SoftDelete(idJ, fmt.Sprintf("merged_into_%s", idI))
|
||||
// t_cf680fad:不再 `_ =` 静默吞错。MVCC 冲突耗尽时 SoftDelete 内部会
|
||||
// 把 (idJ, reason) 落 durable pending 队列(softdelete_pending.go),
|
||||
// 启动/每 tick drain 重放必落盘;这里显式记日志做观测(禁静默)。
|
||||
if err := cp.ldb.SoftDelete(idJ, fmt.Sprintf("merged_into_%s", idI)); err != nil {
|
||||
log.Printf("[consolidation] merge-softdelete FAILED: src=%s → target=%s err=%v (pending-queue 将重放)", idJ, idI, err)
|
||||
}
|
||||
merged++
|
||||
}
|
||||
}
|
||||
@@ -444,7 +449,8 @@ func extractEntities(text string) []string {
|
||||
}
|
||||
|
||||
func minInt2(a, b int) int {
|
||||
if a < b { return a }
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
// 织忆 MemoryWeave — 整合链路健康跟踪(t_10757bd5)
|
||||
//
|
||||
// 背景(2026-10-24 小怡体检实测):
|
||||
// - t_distill(15min) 与 t_consolidation 同时触发 consolPipe,
|
||||
// Rust 侧互斥整合槽被占用时 Go 立即降级 Go 启发式 ⇒ consolidate_busy ~55 次/日静默堆积
|
||||
// - /health 只看 sidecar TCP 连通性 ⇒ 整合链路持续失败也假绿
|
||||
//
|
||||
// 本文件提供:
|
||||
// 1. ConsolidationTracker — 记录连续失败次数 + 最近一次成功时间(供 /health 读)
|
||||
// 2. busyWaitRetry — Rust sidecar 报 busy 时等待 3s×3 次再降级(整合全程 ~126s)
|
||||
// 3. 引用 metrics 包新增的 5 个指标(AC5:失败路径带计数)
|
||||
package routes
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/consolidate"
|
||||
"github.com/xiaoxue/memoryweave/internal/metrics"
|
||||
)
|
||||
|
||||
// ─── ConsolidationTracker ────────────────────────────────────
|
||||
|
||||
var (
|
||||
consTracker = &ConsolidationTracker{}
|
||||
consTrackerOnce sync.Once
|
||||
)
|
||||
|
||||
// ConsolidationTracker 记录整合链路健康状态(内存态,重启归零;
|
||||
// 重启后健康端点读到 ConsecutiveFailures=0 ⇒ 正确,因为该链路确实刚起步)。
|
||||
type ConsolidationTracker struct {
|
||||
mu sync.Mutex
|
||||
LastSuccess time.Time
|
||||
LastAttempt time.Time
|
||||
startup time.Time
|
||||
ConsecutiveFailures int
|
||||
Skips int64 // t_10757bd5:需要"跳过"而非失败的次数(并发触发 / sidecar busy)
|
||||
lastSkip string // 最近一次跳过原因
|
||||
// lastError 最近一次失败原因(供 /health 暴露,便于人工诊断)
|
||||
lastError string
|
||||
}
|
||||
|
||||
// GetConsolTracker 返回全局 tracker 单例
|
||||
func GetConsolTracker() *ConsolidationTracker {
|
||||
if consTracker.startup.IsZero() {
|
||||
consTracker.mu.Lock()
|
||||
if consTracker.startup.IsZero() {
|
||||
consTracker.startup = time.Now()
|
||||
}
|
||||
consTracker.mu.Unlock()
|
||||
}
|
||||
return consTracker
|
||||
}
|
||||
|
||||
// RecordSuccess 整合成功(归零)
|
||||
func (t *ConsolidationTracker) RecordSuccess() {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
t.LastAttempt = time.Now()
|
||||
t.LastSuccess = time.Now()
|
||||
t.ConsecutiveFailures = 0
|
||||
t.lastError = ""
|
||||
metrics.ConsolLastSuccessTime.SetToCurrentTime()
|
||||
metrics.ConsolConsecutiveFailures.Set(0)
|
||||
}
|
||||
|
||||
// RecordSkip 本次触发被**跳过**(不是失败)。
|
||||
//
|
||||
// t_10757bd5 关键语义修正(2026-10-24 22:45 实测发现):
|
||||
// `consolidate_busy` 的真实含义是「另一个整合正在跑」,不是链路坏。
|
||||
// 把它记成失败会让 /health 报 degraded —— 明明整合正在正常工作,却又是一次假红。
|
||||
// 只有真正的错误(sidecar 崩、DB 错、超时)才算 failure。
|
||||
func (t *ConsolidationTracker) RecordSkip(reason string) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
t.LastAttempt = time.Now()
|
||||
t.Skips++
|
||||
t.lastSkip = reason
|
||||
}
|
||||
|
||||
// RecordFailure 整合失败(+1)
|
||||
func (t *ConsolidationTracker) RecordFailure(err string) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
t.LastAttempt = time.Now()
|
||||
t.ConsecutiveFailures++
|
||||
t.lastError = err
|
||||
metrics.ConsolConsecutiveFailures.Set(float64(t.ConsecutiveFailures))
|
||||
}
|
||||
|
||||
// HealthStatus 返回健康端点应报的状态:
|
||||
// - 连续**真失败** ≥ 3 ⇒ "degraded"
|
||||
// - 进程启动已超 2 小时却从未成功过 ⇒ "degraded"(跳过不算成功,也不算失败)
|
||||
// - 上次成功距今 > 2 小时(15min 周期 × 8)⇒ "degraded"
|
||||
// - 否则 "ok"
|
||||
func (t *ConsolidationTracker) HealthStatus() (string, int, time.Duration, string) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
fails := t.ConsecutiveFailures
|
||||
var sinceSuccess time.Duration
|
||||
if t.LastSuccess.IsZero() {
|
||||
sinceSuccess = 0 // 从未成功
|
||||
} else {
|
||||
sinceSuccess = time.Since(t.LastSuccess)
|
||||
}
|
||||
status := "ok"
|
||||
if fails >= 3 {
|
||||
status = "degraded"
|
||||
}
|
||||
if t.LastSuccess.IsZero() {
|
||||
if !t.startup.IsZero() && time.Since(t.startup) > 2*time.Hour {
|
||||
status = "degraded"
|
||||
}
|
||||
} else if sinceSuccess > 2*time.Hour {
|
||||
status = "degraded"
|
||||
}
|
||||
return status, fails, sinceSuccess, t.lastError
|
||||
}
|
||||
|
||||
// Snapshot 供 /health 暴露完整字段(含跳过次数,便于区分「忙」与「坏」)
|
||||
func (t *ConsolidationTracker) Snapshot() (fails int, skips int64, lastSkip string, lastErr string) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
return t.ConsecutiveFailures, t.Skips, t.lastSkip, t.lastError
|
||||
}
|
||||
|
||||
// ─── busyWaitRetry ───────────────────────────────────────────
|
||||
|
||||
// busyWaitRetry 对 Rust sidecar consolidate_busy 做有限等待重试。
|
||||
//
|
||||
// 原理:Rust 整合全程约 126s(DBSCAN + 衰减校准),触发器每 15min 一次,
|
||||
// 两个触发器同秒到达时第二个撞 busy。等待 3s × 3 次(共 9s);
|
||||
// 9s 后仍 busy 说明 sidecar 真有长任务(或正在做 full 模式),
|
||||
// 降级 Go 启发式并记录 tracker(由调用方负责)。
|
||||
//
|
||||
// 返回语义:
|
||||
// - (report, false, nil) = 成功拿到报告
|
||||
// - (nil, true, nil) = 重试耗尽仍 busy(调用方应走降级 + RecordFailure)
|
||||
// - (nil, false, err) = 非 busy 错误(调用方直接返回)
|
||||
func busyWaitRetry(dataDir, sqlitePath, mode string) (report *consolidate.Result, stillBusy bool, err error) {
|
||||
const (
|
||||
maxRetries = 3
|
||||
waitDur = 3 * time.Second
|
||||
)
|
||||
for i := 0; i <= maxRetries; i++ {
|
||||
if i > 0 {
|
||||
metrics.ConsolidateBusyWaitTotal.Inc()
|
||||
time.Sleep(waitDur)
|
||||
}
|
||||
report, err = consolidate.Run(dataDir, sqlitePath, mode)
|
||||
if err == nil {
|
||||
return report, false, nil
|
||||
}
|
||||
if strings.Contains(err.Error(), "consolidate_busy") {
|
||||
continue // 仍 busy,重试
|
||||
}
|
||||
// 非 busy 错误直接返回
|
||||
return nil, false, err
|
||||
}
|
||||
// 重试耗尽仍 busy
|
||||
return nil, true, nil
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
// 织忆 MemoryWeave — 召回响应契约辅助(P0-3,2026-10-26)
|
||||
//
|
||||
// 背景(CS249r Vol III Ch6 检索契约):响应只有 cache_hit/candidates_scanned/count/mode/graph_expanded,
|
||||
// 空结果分不清「不存在」与「扫了一半就超时」——这是 Air Canada 类静默幻觉的结构性入口。
|
||||
//
|
||||
// 本文件提供最小可用契约三件:
|
||||
// ① status/partial_reason:complete 的空结果才允许解读为「不存在」;
|
||||
// ② scope{namespace,snapshot,...}:说明这次答案基于哪个数据视图(本服务无索引版本号,
|
||||
// 故 snapshot = 观测时点 + 缓存状态,缓存命中代表 60s 内旧快照 —— 语义诚实,不假装有版本号);
|
||||
// ③ continuation:不透明翻页令牌(query 指纹 + ns 绑定,防止跨 query 串页)。
|
||||
package routes
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/models"
|
||||
"github.com/xiaoxue/memoryweave/internal/storage"
|
||||
)
|
||||
|
||||
// maxContinuationOffset 硬上限:防止把 topK 放大到爆内存/延迟。
|
||||
const maxContinuationOffset = 500
|
||||
|
||||
type pageToken struct {
|
||||
V int `json:"v"`
|
||||
Q string `json:"q"` // query 指纹(sha256 前 8 hex)
|
||||
NS string `json:"ns"` // 作用域绑定
|
||||
Off int `json:"o"` // 下一页起点
|
||||
Lim int `json:"l"` // 页大小
|
||||
// Prev 已返回过的 ID(去重锚点)。活索引下排序会随 fetchLimit 变化而轻微漂移,
|
||||
// 只靠 offset 会出现跨页重复;token 携带已返回 ID 才能机械保证「不重」。
|
||||
Prev []string `json:"p,omitempty"`
|
||||
}
|
||||
|
||||
// maxPrevIDs 令牌里最多携带的去重锚点数(3~5 页内足够;超长则丢最旧,令牌不会无限膨胀)。
|
||||
const maxPrevIDs = 100
|
||||
|
||||
// queryFingerprint 8 hex 的 query 指纹(足够防串页,不泄露正文)。
|
||||
func queryFingerprint(q string) string {
|
||||
sum := sha256.Sum256([]byte(q))
|
||||
return hex.EncodeToString(sum[:4])
|
||||
}
|
||||
|
||||
// encodeContinuation 生成下一页令牌;没有下一页时返回空串。
|
||||
func encodeContinuation(query, namespace string, offset, limit int, prev []string) string {
|
||||
if limit <= 0 {
|
||||
return ""
|
||||
}
|
||||
if len(prev) > maxPrevIDs {
|
||||
prev = prev[len(prev)-maxPrevIDs:]
|
||||
}
|
||||
tok := pageToken{V: 1, Q: queryFingerprint(query), NS: namespace, Off: offset, Lim: limit, Prev: prev}
|
||||
b, err := json.Marshal(tok)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
// decodeContinuation 解析令牌。错误信息面向调用方(可据此修请求)。
|
||||
func decodeContinuation(raw string) (pageToken, error) {
|
||||
var tok pageToken
|
||||
b, err := base64.RawURLEncoding.DecodeString(raw)
|
||||
if err != nil {
|
||||
return tok, errors.New("continuation 不是合法 base64url 令牌")
|
||||
}
|
||||
if err := json.Unmarshal(b, &tok); err != nil {
|
||||
return tok, errors.New("continuation 内容不是合法 JSON")
|
||||
}
|
||||
if tok.V != 1 {
|
||||
return tok, errors.New("continuation 版本不支持:" + strconv.Itoa(tok.V))
|
||||
}
|
||||
if tok.Off < 0 || tok.Lim <= 0 {
|
||||
return tok, errors.New("continuation 字段非法(offset/limit)")
|
||||
}
|
||||
if tok.Off > maxContinuationOffset {
|
||||
return tok, errors.New("continuation offset 超出上限 " + strconv.Itoa(maxContinuationOffset))
|
||||
}
|
||||
return tok, nil
|
||||
}
|
||||
|
||||
// buildScope 组装本次召回的数据视图声明。
|
||||
func buildScope(namespace string, topK int, mode string, cacheHit, truncated bool, started time.Time) map[string]interface{} {
|
||||
snap := "t" + strconv.FormatInt(started.UnixMilli(), 10)
|
||||
if cacheHit {
|
||||
snap += "-cache" // 缓存命中:读的是 60s 内旧快照,不是本次实时扫描
|
||||
} else {
|
||||
snap += "-scan"
|
||||
}
|
||||
if truncated {
|
||||
snap += "-truncated"
|
||||
}
|
||||
return map[string]interface{}{
|
||||
"namespace": namespace,
|
||||
"snapshot": snap,
|
||||
"cache_hit": cacheHit,
|
||||
"truncated": truncated,
|
||||
"top_k": topK,
|
||||
"mode": mode,
|
||||
}
|
||||
}
|
||||
|
||||
// traceItems 把最终返回集映射成 trace 的 item 归因(rank 从 1 起)。
|
||||
func traceItems(results []models.RecallResult) []storage.TraceItem {
|
||||
items := make([]storage.TraceItem, 0, len(results))
|
||||
for i, r := range results {
|
||||
ch := r.Channel
|
||||
if ch == "" {
|
||||
ch = "vector" // 老调用方/旧缓存条目无 channel ⇒ 主通道默认值
|
||||
}
|
||||
items = append(items, storage.TraceItem{Rank: i + 1, ID: r.ID, Channel: ch, Score: r.Score})
|
||||
}
|
||||
return items
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/models"
|
||||
)
|
||||
|
||||
func TestContinuationRoundTrip(t *testing.T) {
|
||||
tok := encodeContinuation("织忆怎么召回", "hermes-main", 10, 5, []string{"mem_1", "mem_2"})
|
||||
if tok == "" {
|
||||
t.Fatal("有下一页时令牌不应为空")
|
||||
}
|
||||
got, err := decodeContinuation(tok)
|
||||
if err != nil {
|
||||
t.Fatalf("解码失败:%v", err)
|
||||
}
|
||||
if got.Off != 10 || got.Lim != 5 {
|
||||
t.Fatalf("令牌字段错误:%+v", got)
|
||||
}
|
||||
if got.Q != queryFingerprint("织忆怎么召回") {
|
||||
t.Fatalf("query 指纹不一致")
|
||||
}
|
||||
if got.NS != "hermes-main" {
|
||||
t.Fatalf("namespace 不一致:%s", got.NS)
|
||||
}
|
||||
if len(got.Prev) != 2 || got.Prev[0] != "mem_1" {
|
||||
t.Fatalf("去重锚点未随令牌传递:%v", got.Prev)
|
||||
}
|
||||
}
|
||||
|
||||
func TestContinuationRejectsBadToken(t *testing.T) {
|
||||
if _, err := decodeContinuation("not-base64!!"); err == nil {
|
||||
t.Fatal("非法 base64 应报错")
|
||||
}
|
||||
if _, err := decodeContinuation("eyJ2Ijo5fQ"); err == nil { // {"v":9}
|
||||
t.Fatal("未知版本应报错")
|
||||
}
|
||||
tok := encodeContinuation("q", "ns", 9999, 5, nil)
|
||||
if _, err := decodeContinuation(tok); err == nil {
|
||||
t.Fatal("offset 超上限应报错")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQueryFingerprintStable(t *testing.T) {
|
||||
a := queryFingerprint("同样的问句")
|
||||
b := queryFingerprint("同样的问句")
|
||||
c := queryFingerprint("不同的问句")
|
||||
if a != b {
|
||||
t.Fatal("同 query 指纹应稳定")
|
||||
}
|
||||
if a == c {
|
||||
t.Fatal("不同 query 指纹应不同")
|
||||
}
|
||||
if len(a) != 8 {
|
||||
t.Fatalf("指纹应为 8 hex,实际 %d", len(a))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildScope(t *testing.T) {
|
||||
started := time.UnixMilli(1700000000000)
|
||||
sc := buildScope("hermes-main", 5, "hybrid", false, false, started)
|
||||
for _, k := range []string{"namespace", "snapshot", "cache_hit", "truncated", "top_k", "mode"} {
|
||||
if _, ok := sc[k]; !ok {
|
||||
t.Fatalf("scope 缺字段 %s", k)
|
||||
}
|
||||
}
|
||||
snap := sc["snapshot"].(string)
|
||||
if snap != "t1700000000000-scan" {
|
||||
t.Fatalf("实时扫描 snapshot 形态错误:%s", snap)
|
||||
}
|
||||
cached := buildScope("ns", 5, "hybrid", true, true, started)["snapshot"].(string)
|
||||
if cached != "t1700000000000-cache-truncated" {
|
||||
t.Fatalf("缓存+截断 snapshot 形态错误:%s", cached)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTraceItems(t *testing.T) {
|
||||
rs := []models.RecallResult{
|
||||
{ID: "a", Channel: "vector"},
|
||||
{ID: "b"}, // 老调用方无 channel ⇒ 默认 vector
|
||||
{ID: "c", Channel: "graph"},
|
||||
}
|
||||
items := traceItems(rs)
|
||||
if len(items) != 3 || items[0].Rank != 1 || items[2].Rank != 3 {
|
||||
t.Fatalf("rank 编号错误:%+v", items)
|
||||
}
|
||||
if items[1].Channel != "vector" {
|
||||
t.Fatalf("缺省 channel 应回落 vector,实际 %s", items[1].Channel)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRecallResultContractFields 契约字段必须真的出现在 JSON 里(不是「加了结构体没接线」)。
|
||||
func TestRecallResultContractFields(t *testing.T) {
|
||||
r := models.RecallResult{
|
||||
ID: "mem_1", Channel: "fts", Stale: true, Version: 3,
|
||||
ValidFrom: "2026-10-26T10:00:00+08:00", ValidTo: "2026-10-26T11:00:00+08:00",
|
||||
Supersedes: []string{"mem_0"}, SupersededBy: []string{"mem_2"}, Superseded: true,
|
||||
}
|
||||
b, err := json.Marshal(r)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
var m map[string]interface{}
|
||||
if err := json.Unmarshal(b, &m); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
for _, k := range []string{"channel", "stale", "generation", "valid_from", "valid_to",
|
||||
"supersedes", "superseded_by", "superseded"} {
|
||||
if _, ok := m[k]; !ok {
|
||||
t.Fatalf("响应缺字段 %s(JSON=%s)", k, string(b))
|
||||
}
|
||||
}
|
||||
}
|
||||
+686
-99
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,153 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/models"
|
||||
)
|
||||
|
||||
// 2026-10-26 (t_9025b0eb):top_k 收口契约测试。
|
||||
// 起因:/api/v1/recall 完全无视 top_k —— top_k=5 实测返回 1905/1625 条(99% graph_expanded),
|
||||
// 插件记忆预取被撑到 103,299 chars 截断、count 失真、使用追踪按千级结果记账。
|
||||
// 钉住四件事:① results 不超过 limit ② 主结果不被扩展挤掉 ③ 扩展仍可见且不超 limit
|
||||
// ④ 稀疏查询(主结果 < limit)时扩展能补齐。
|
||||
func TestCapRecallResults(t *testing.T) {
|
||||
mk := func(n int, cat string) []models.RecallResult {
|
||||
out := make([]models.RecallResult, n)
|
||||
for i := 0; i < n; i++ {
|
||||
out[i] = models.RecallResult{ID: cat + string(rune('a'+i%26)), Category: cat, Content: cat}
|
||||
}
|
||||
return out
|
||||
}
|
||||
cases := []struct {
|
||||
name string
|
||||
prim, exp int
|
||||
limit int
|
||||
wantPrim int
|
||||
wantExp int
|
||||
primCategory string
|
||||
}{
|
||||
{"主结果足额_扩展不得进results", 10, 1900, 5, 5, 5, "distilled"},
|
||||
{"主结果只有2条_扩展补齐到limit", 2, 900, 5, 5, 5, "distilled"},
|
||||
{"无扩展_纯截断", 30, 0, 10, 10, 0, "distilled"},
|
||||
{"扩展少于limit", 1, 3, 5, 4, 0, "distilled"},
|
||||
{"空结果", 0, 0, 5, 0, 0, ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
all := append(mk(c.prim, "distilled"), mk(c.exp, "graph_expanded")...)
|
||||
prim, exp := capRecallResults(all, c.limit)
|
||||
if len(prim) != c.wantPrim {
|
||||
t.Fatalf("prim=%d want %d", len(prim), c.wantPrim)
|
||||
}
|
||||
if len(exp) != c.wantExp {
|
||||
t.Fatalf("expanded=%d want %d", len(exp), c.wantExp)
|
||||
}
|
||||
if len(prim)+len(exp) > c.limit*2 {
|
||||
t.Fatalf("总量失控: prim=%d exp=%d", len(prim), len(exp))
|
||||
}
|
||||
// 主结果条数不得超过原始主结果数(不得凭空造)
|
||||
n := 0
|
||||
for _, r := range prim {
|
||||
if r.Category != "graph_expanded" {
|
||||
n++
|
||||
}
|
||||
}
|
||||
if n > c.prim {
|
||||
t.Fatalf("主结果 %d 条,超过输入 %d 条(凭空造)", n, c.prim)
|
||||
}
|
||||
if c.primCategory != "" && c.prim > 0 && n == 0 {
|
||||
t.Fatalf("主结果被扩展挤光:%+v", prim)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// limit 非法(0/负数)时按默认 10 处理,不做无界返回。
|
||||
func TestCapRecallResultsDefaultLimit(t *testing.T) {
|
||||
all := make([]models.RecallResult, 50)
|
||||
for i := range all {
|
||||
all[i] = models.RecallResult{Category: "distilled"}
|
||||
}
|
||||
prim, _ := capRecallResults(all, 0)
|
||||
if len(prim) != 10 {
|
||||
t.Fatalf("limit=0 应回落 10,得到 %d", len(prim))
|
||||
}
|
||||
}
|
||||
|
||||
// ── t_e98cb1d6 回归:pattern / peer 被 cap 截断 ────────────────────────────
|
||||
// 病灶:capRecallResults 把非 graph_expanded 全部并入 prim 再截断到 limit;
|
||||
// pattern/peer 是 recall.go Step 6.2/6.3 追加到 results 末尾的附带条目,
|
||||
// distilled 占满 limit 时它们被整段切掉(16:28 topkcap 引入,limit=50 时 pattern=0)。
|
||||
// 修后:pattern/peer 恒保留在 results 末尾(独立于主结果配额),主结果仍照常收口。
|
||||
func TestCapRecallResults_PatternAndPeerSurviveCap(t *testing.T) {
|
||||
mk := func(n int, cat string) []models.RecallResult {
|
||||
out := make([]models.RecallResult, n)
|
||||
for i := 0; i < n; i++ {
|
||||
out[i] = models.RecallResult{ID: cat + string(rune('a'+i%26)), Category: cat, Content: cat}
|
||||
}
|
||||
return out
|
||||
}
|
||||
count := func(rs []models.RecallResult, cat string) int {
|
||||
n := 0
|
||||
for _, r := range rs {
|
||||
if r.Category == cat {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
d, p, pe, e int // distilled / pattern / peer / graph_expanded
|
||||
limit int
|
||||
wantD, wantP, wantPe int
|
||||
}{
|
||||
// ① 金标场景:主结果占满 limit,pattern/peer 追加在末尾 ⇒ 修前恒为 0
|
||||
{"limit=50_主结果占满_pattern 恒保留", 50, 3, 1, 0, 50, 50, 3, 1},
|
||||
{"limit=200_主结果占满_pattern 仍保留", 100, 3, 1, 97, 200, 100, 3, 1},
|
||||
// ② peer 注入同样不被截断
|
||||
{"limit=50_peer 注入不被截断", 50, 0, 2, 0, 50, 50, 0, 2},
|
||||
// ③ 主结果不足 limit:扩展先补齐主结果,carry 仍保留在末尾
|
||||
{"limit=50_主结果不足_扩展补齐+carry 保留", 30, 2, 1, 10, 50, 30, 2, 1},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
all := make([]models.RecallResult, 0, c.d+c.p+c.pe+c.e)
|
||||
all = append(all, mk(c.d, "distilled")...)
|
||||
all = append(all, mk(c.p, "pattern")...)
|
||||
all = append(all, mk(c.pe, "peer")...)
|
||||
all = append(all, mk(c.e, "graph_expanded")...)
|
||||
prim, exp := capRecallResults(all, c.limit)
|
||||
d := count(prim, "distilled")
|
||||
p := count(prim, "pattern")
|
||||
pe := count(prim, "peer")
|
||||
e := count(prim, "graph_expanded")
|
||||
if d != c.wantD {
|
||||
t.Errorf("distilled=%d want %d", d, c.wantD)
|
||||
}
|
||||
// AC:limit=50 时 pattern 必须 ≥1(金标 query 复现终审现象)
|
||||
if c.p > 0 && p < 1 {
|
||||
t.Errorf("pattern=%d,应 ≥1(截断回归未修)", p)
|
||||
}
|
||||
if p != c.wantP {
|
||||
t.Errorf("pattern=%d want %d", p, c.wantP)
|
||||
}
|
||||
if pe != c.wantPe {
|
||||
t.Errorf("peer=%d want %d", pe, c.wantPe)
|
||||
}
|
||||
// cap 仍然生效:主结果(distilled + 扩展补齐)不得超过 limit
|
||||
if d+e > c.limit {
|
||||
t.Fatalf("主结果超 cap: distilled=%d graph_expanded=%d limit=%d", d, e, c.limit)
|
||||
}
|
||||
if len(exp) > c.limit {
|
||||
t.Fatalf("graph_expanded 字段超 cap: %d > %d", len(exp), c.limit)
|
||||
}
|
||||
// 附带条目不得被塞进 graph_expanded 字段
|
||||
if count(exp, "pattern") > 0 || count(exp, "peer") > 0 {
|
||||
t.Fatalf("pattern/peer 被误放入 graph_expanded 字段")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+165
-76
@@ -3,8 +3,11 @@ package routes
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
_ "embed"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -12,6 +15,15 @@ import (
|
||||
"github.com/xiaoxue/memoryweave/internal/storage"
|
||||
)
|
||||
|
||||
// go:embed testdata/golden-set.json 把金标集打进二进制(t_dfc93ad0 AC5):
|
||||
// 部署 CWD=/home/muc,旧版「path=="" → 相对 testdata/」解析到 /home/muc/testdata
|
||||
// ⇒ POST /api/v1/eval/golden 不传 golden_path 时 500(2026-10-14 实测复现)。
|
||||
// 内嵌兜底后:缺省/相对路径读不到 ⇒ 回落内嵌基线(仍可用);env ZHIYI_GOLDEN_SET
|
||||
// 指定绝对路径 ⇒ 读该文件(可临时替换金标集)。测试仍按显式路径调用,行为不变。
|
||||
//
|
||||
//go:embed testdata/golden-set.json
|
||||
var embeddedGoldenSetJSON []byte
|
||||
|
||||
// ─── 金标集定义 ──────────────────────────────────────────────
|
||||
|
||||
// GoldenSetItem 单条金标:query + 具体 expected_ids + 关键词相关性判据
|
||||
@@ -19,9 +31,14 @@ type GoldenSetItem struct {
|
||||
Query string `json:"query"`
|
||||
ExpectedIDs []string `json:"expected_ids"`
|
||||
MustIncludeKeywords []string `json:"must_include_keywords"`
|
||||
Category string `json:"category,omitempty"`
|
||||
Difficulty string `json:"difficulty,omitempty"`
|
||||
IDBaseline string `json:"id_baseline,omitempty"`
|
||||
// Namespace 该条目应在哪个 namespace 里召回。为空则用请求传入的 ns。
|
||||
// 为什么必须 per-item(2026-10-14 实测):金标的 expected_id 分散在
|
||||
// hermes-main / domain:HUB / soulful-xiaowei / wiki / shared 等多个 ns,
|
||||
// 而 eval 只按请求里的单一 ns 召回 ⇒ ID 类指标**按构造恒为 0**(不是召回差)。
|
||||
Namespace string `json:"namespace,omitempty"`
|
||||
Category string `json:"category,omitempty"`
|
||||
Difficulty string `json:"difficulty,omitempty"`
|
||||
IDBaseline string `json:"id_baseline,omitempty"`
|
||||
}
|
||||
|
||||
// GoldenSet 金标集
|
||||
@@ -30,15 +47,44 @@ type GoldenSet struct {
|
||||
Items []GoldenSetItem `json:"items"`
|
||||
}
|
||||
|
||||
// LoadGoldenSet 从 testdata/ 加载金标集,支持相对路径(生产用)和绝对路径(测试用)
|
||||
// LoadGoldenSet 加载金标集。路径解析(t_dfc93ad0 AC5,部署 CWD=/home/muc):
|
||||
// 1. env ZHIYI_GOLDEN_SET 指定路径 ⇒ 优先读它(临时替换金标集用,不重编译);
|
||||
// 2. 显式 path 非空且能读到 ⇒ 用它(绝对/相对皆按调用方语义);
|
||||
// 3. path 为空、或上面读不到(典型:部署二进制 CWD=/home/muc 无 testdata/,
|
||||
// 旧版相对路径解析失败 ⇒ 500)⇒ 回落 **内嵌** 基线 embeddedGoldenSetJSON。
|
||||
// 校验(空断言自守)在拿到内容后统一跑,三种来源同口径。
|
||||
func LoadGoldenSet(path string) (*GoldenSet, error) {
|
||||
if path == "" {
|
||||
// 编译后无法直接拿到源码路径,回退到 CWD 的 testdata/
|
||||
path = "testdata/golden-set.json"
|
||||
var data []byte
|
||||
usedSource := "env:ZHIYI_GOLDEN_SET"
|
||||
// 2026-10-26 修正优先级:显式 path > env > 内嵌。
|
||||
// 旧顺序(env 先)导致 ZHIYI_GOLDEN_SET 一旦设置,任何请求传 golden_path 都被静默忽略
|
||||
// ⇒ 实测「传 7 个 chunk 却每块都报 53 条」(env 指向的 53 条集)—— 评测对象与预期不符,
|
||||
// 且指标全是 0 时极难发现。env 现在只作「默认金标」,显式 path 必须能覆盖它。
|
||||
if path != "" {
|
||||
usedSource = "path:" + path
|
||||
d, err := os.ReadFile(path)
|
||||
if err == nil {
|
||||
data = d
|
||||
} else if filepath.IsAbs(path) {
|
||||
// 绝对路径 = 明确指名要跑这套题 ⇒ 读不到必须报错,不许静默换题
|
||||
return nil, fmt.Errorf("读 golden_path 失败(%s): %w", path, err)
|
||||
} else {
|
||||
// 相对路径在部署 CWD 下读不到 ⇒ 内嵌兜底(t_dfc93ad0 AC5 既有行为,保留)
|
||||
data = embeddedGoldenSetJSON
|
||||
usedSource = "embedded"
|
||||
}
|
||||
} else if p := os.Getenv("ZHIYI_GOLDEN_SET"); p != "" {
|
||||
var err error
|
||||
data, err = os.ReadFile(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
data = embeddedGoldenSetJSON
|
||||
usedSource = "embedded"
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if len(data) == 0 {
|
||||
return nil, fmt.Errorf("golden set 不可用(%s 为空且无内嵌基线)", usedSource)
|
||||
}
|
||||
var gs GoldenSet
|
||||
if err := json.Unmarshal(data, &gs); err != nil {
|
||||
@@ -122,15 +168,15 @@ type EvalAPI struct {
|
||||
}
|
||||
|
||||
type EvalRun struct {
|
||||
ID string `json:"id"`
|
||||
Model string `json:"model"`
|
||||
RecallAt5 float64 `json:"recall_at_5"`
|
||||
ID string `json:"id"`
|
||||
Model string `json:"model"`
|
||||
RecallAt5 float64 `json:"recall_at_5"`
|
||||
PrecisionAt5 float64 `json:"precision_at_5"`
|
||||
MRR float64 `json:"mean_reciprocal_rank"`
|
||||
NDCG float64 `json:"ndcg"`
|
||||
MRR float64 `json:"mean_reciprocal_rank"`
|
||||
NDCG float64 `json:"ndcg"`
|
||||
|
||||
// 按标签分组
|
||||
RecallByTag map[string]float64 `json:"recall_at_5_by_tag,omitempty"`
|
||||
RecallByTag map[string]float64 `json:"recall_at_5_by_tag,omitempty"`
|
||||
PrecisionByTag map[string]float64 `json:"precision_at_5_by_tag,omitempty"`
|
||||
|
||||
// 按 Agent 分组
|
||||
@@ -147,14 +193,14 @@ type EvalRun struct {
|
||||
}
|
||||
|
||||
type EvalQueryDetail struct {
|
||||
Query string `json:"query"`
|
||||
ExpectedIDs []string `json:"expected_ids"`
|
||||
Query string `json:"query"`
|
||||
ExpectedIDs []string `json:"expected_ids"`
|
||||
MustIncludeKeywords []string `json:"must_include_keywords,omitempty"`
|
||||
Hits []string `json:"hits"`
|
||||
Misses []string `json:"misses"`
|
||||
RecallAt5 float64 `json:"recall_at_5"`
|
||||
PrecisionAt5 float64 `json:"precision_at_5"`
|
||||
KeywordOK bool `json:"keyword_ok,omitempty"`
|
||||
Hits []string `json:"hits"`
|
||||
Misses []string `json:"misses"`
|
||||
RecallAt5 float64 `json:"recall_at_5"`
|
||||
PrecisionAt5 float64 `json:"precision_at_5"`
|
||||
KeywordOK bool `json:"keyword_ok,omitempty"`
|
||||
}
|
||||
|
||||
// GoldenRunResult 金标 run 的扩展结果(含关键词判据)
|
||||
@@ -166,8 +212,8 @@ type GoldenRunResult struct {
|
||||
}
|
||||
|
||||
type ConsolidationHits struct {
|
||||
TotalDistilledUsed int `json:"total_distilled_used"`
|
||||
HitsAfterConsolidation int `json:"hits_after_consolidation"`
|
||||
TotalDistilledUsed int `json:"total_distilled_used"`
|
||||
HitsAfterConsolidation int `json:"hits_after_consolidation"`
|
||||
ConsolidationBenefit float64 `json:"consolidation_benefit"`
|
||||
}
|
||||
|
||||
@@ -185,7 +231,7 @@ func NewEvalAPI(p *storage.RecallPipeline, ldb storage.LanceDB) *EvalAPI {
|
||||
// POST /api/v1/eval/run
|
||||
func (ea *EvalAPI) Run(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Queries []struct {
|
||||
Queries []struct {
|
||||
Query string `json:"query"`
|
||||
ExpectedIDs []string `json:"expected_ids"`
|
||||
} `json:"queries"`
|
||||
@@ -250,11 +296,15 @@ func (ea *EvalAPI) Run(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
pAt5 := 0.0
|
||||
if len(results) > 0 { pAt5 = float64(hits) / float64(len(results)) }
|
||||
if len(results) > 0 {
|
||||
pAt5 = float64(hits) / float64(len(results))
|
||||
}
|
||||
totalPrecision += pAt5
|
||||
|
||||
rAt5 := 0.0
|
||||
if len(q.ExpectedIDs) > 0 { rAt5 = float64(hits) / float64(len(q.ExpectedIDs)) }
|
||||
if len(q.ExpectedIDs) > 0 {
|
||||
rAt5 = float64(hits) / float64(len(q.ExpectedIDs))
|
||||
}
|
||||
totalRecall += rAt5
|
||||
|
||||
// MRR
|
||||
@@ -269,11 +319,17 @@ func (ea *EvalAPI) Run(w http.ResponseWriter, r *http.Request) {
|
||||
dcg, idcg := 0.0, 0.0
|
||||
for i, res := range results {
|
||||
rel := 0.0
|
||||
if expectedSet[res.ID] { rel = 1.0 }
|
||||
if expectedSet[res.ID] {
|
||||
rel = 1.0
|
||||
}
|
||||
dcg += rel / log2(float64(i+2))
|
||||
if i < len(q.ExpectedIDs) { idcg += 1.0 / log2(float64(i+2)) }
|
||||
if i < len(q.ExpectedIDs) {
|
||||
idcg += 1.0 / log2(float64(i+2))
|
||||
}
|
||||
}
|
||||
if idcg > 0 {
|
||||
totalNDCG += dcg / idcg
|
||||
}
|
||||
if idcg > 0 { totalNDCG += dcg / idcg }
|
||||
|
||||
// 分组统计
|
||||
// (category 从 query 推断)
|
||||
@@ -308,18 +364,18 @@ func (ea *EvalAPI) Run(w http.ResponseWriter, r *http.Request) {
|
||||
recallByAgent := avgByGroup(recallByAgentMap)
|
||||
|
||||
run := &EvalRun{
|
||||
ID: time.Now().Format("20060102-150405"),
|
||||
Model: req.Model,
|
||||
RecallAt5: totalRecall / float64(totalQueries),
|
||||
PrecisionAt5: totalPrecision / float64(totalQueries),
|
||||
MRR: totalMRR / float64(totalQueries),
|
||||
NDCG: totalNDCG / float64(totalQueries),
|
||||
RecallByTag: recallByTag,
|
||||
ID: time.Now().Format("20060102-150405"),
|
||||
Model: req.Model,
|
||||
RecallAt5: totalRecall / float64(totalQueries),
|
||||
PrecisionAt5: totalPrecision / float64(totalQueries),
|
||||
MRR: totalMRR / float64(totalQueries),
|
||||
NDCG: totalNDCG / float64(totalQueries),
|
||||
RecallByTag: recallByTag,
|
||||
PrecisionByTag: precisionByTag,
|
||||
RecallByAgent: recallByAgent,
|
||||
QueryDetails: queryDetails,
|
||||
Queries: totalQueries,
|
||||
RanAt: time.Now(),
|
||||
RecallByAgent: recallByAgent,
|
||||
QueryDetails: queryDetails,
|
||||
Queries: totalQueries,
|
||||
RanAt: time.Now(),
|
||||
}
|
||||
|
||||
evals.mu.Lock()
|
||||
@@ -336,13 +392,20 @@ func (ea *EvalAPI) RunGolden(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Namespace string `json:"namespace"`
|
||||
GoldenPath string `json:"golden_path"` // 可选,默认 testdata/golden-set.json
|
||||
// AllNamespaces(2026-10-26)跨 namespace 评测开关。
|
||||
// 背景:旧逻辑 ns 为空 ⇒ 强制 "shared",而真实金标分散在 hermes-main/wiki/HUB 等多个 ns
|
||||
// ⇒ 评测跑的是"只看 shared"的召回,与线上跨 ns 召回不是同一个系统(实测前 15 条里 15 条结果不同)。
|
||||
// 语义:true ⇒ ns = ""(全库跨 ns,等同线上默认);false ⇒ 保持旧行为(默认 shared,向后兼容)。
|
||||
AllNamespaces bool `json:"all_namespaces"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
respondError(w, 400, "invalid body")
|
||||
return
|
||||
}
|
||||
ns := req.Namespace
|
||||
if ns == "" {
|
||||
if req.AllNamespaces {
|
||||
ns = ""
|
||||
} else if ns == "" {
|
||||
ns = "shared"
|
||||
}
|
||||
gs, err := LoadGoldenSet(req.GoldenPath)
|
||||
@@ -369,7 +432,12 @@ func (ea *EvalAPI) RunGolden(w http.ResponseWriter, r *http.Request) {
|
||||
continue
|
||||
}
|
||||
|
||||
results, err := ea.Pipeline.Recall(item.Query, ns, 5, 0.5)
|
||||
// per-item namespace:条目自带 ns 优先(金标基线是按 ns 钉的,见 GoldenSetItem.Namespace)
|
||||
itemNS := item.Namespace
|
||||
if itemNS == "" {
|
||||
itemNS = ns
|
||||
}
|
||||
results, err := ea.Pipeline.Recall(item.Query, itemNS, 5, 0.5)
|
||||
if err != nil {
|
||||
failures = append(failures, item.Query+": recall 失败 "+err.Error())
|
||||
keywordFail++
|
||||
@@ -405,11 +473,15 @@ func (ea *EvalAPI) RunGolden(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
pAt5 := 0.0
|
||||
if len(results) > 0 { pAt5 = float64(hits) / float64(len(results)) }
|
||||
if len(results) > 0 {
|
||||
pAt5 = float64(hits) / float64(len(results))
|
||||
}
|
||||
totalPrecision += pAt5
|
||||
|
||||
rAt5 := 0.0
|
||||
if len(item.ExpectedIDs) > 0 { rAt5 = float64(hits) / float64(len(item.ExpectedIDs)) }
|
||||
if len(item.ExpectedIDs) > 0 {
|
||||
rAt5 = float64(hits) / float64(len(item.ExpectedIDs))
|
||||
}
|
||||
totalRecall += rAt5
|
||||
|
||||
// MRR
|
||||
@@ -424,11 +496,17 @@ func (ea *EvalAPI) RunGolden(w http.ResponseWriter, r *http.Request) {
|
||||
dcg, idcg := 0.0, 0.0
|
||||
for i, res := range results {
|
||||
rel := 0.0
|
||||
if expectedSet[res.ID] { rel = 1.0 }
|
||||
if expectedSet[res.ID] {
|
||||
rel = 1.0
|
||||
}
|
||||
dcg += rel / log2(float64(i+2))
|
||||
if i < len(item.ExpectedIDs) { idcg += 1.0 / log2(float64(i+2)) }
|
||||
if i < len(item.ExpectedIDs) {
|
||||
idcg += 1.0 / log2(float64(i+2))
|
||||
}
|
||||
}
|
||||
if idcg > 0 {
|
||||
totalNDCG += dcg / idcg
|
||||
}
|
||||
if idcg > 0 { totalNDCG += dcg / idcg }
|
||||
|
||||
// 关键词统计
|
||||
keywordTotal++
|
||||
@@ -445,9 +523,9 @@ func (ea *EvalAPI) RunGolden(w http.ResponseWriter, r *http.Request) {
|
||||
MustIncludeKeywords: item.MustIncludeKeywords,
|
||||
Hits: hitIDs,
|
||||
Misses: missIDs,
|
||||
RecallAt5: rAt5,
|
||||
PrecisionAt5: pAt5,
|
||||
KeywordOK: keywordOK,
|
||||
RecallAt5: rAt5,
|
||||
PrecisionAt5: pAt5,
|
||||
KeywordOK: keywordOK,
|
||||
})
|
||||
|
||||
totalQueries++
|
||||
@@ -459,15 +537,15 @@ func (ea *EvalAPI) RunGolden(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
run := &EvalRun{
|
||||
ID: time.Now().Format("20060102-150405"),
|
||||
Model: "golden-set",
|
||||
RecallAt5: totalRecall / float64(totalQueries),
|
||||
PrecisionAt5: totalPrecision / float64(totalQueries),
|
||||
MRR: totalMRR / float64(totalQueries),
|
||||
NDCG: totalNDCG / float64(totalQueries),
|
||||
QueryDetails: queryDetails,
|
||||
Queries: totalQueries,
|
||||
RanAt: time.Now(),
|
||||
ID: time.Now().Format("20060102-150405"),
|
||||
Model: "golden-set",
|
||||
RecallAt5: totalRecall / float64(totalQueries),
|
||||
PrecisionAt5: totalPrecision / float64(totalQueries),
|
||||
MRR: totalMRR / float64(totalQueries),
|
||||
NDCG: totalNDCG / float64(totalQueries),
|
||||
QueryDetails: queryDetails,
|
||||
Queries: totalQueries,
|
||||
RanAt: time.Now(),
|
||||
}
|
||||
|
||||
evals.mu.Lock()
|
||||
@@ -534,9 +612,9 @@ func (ea *EvalAPI) Generate(w http.ResponseWriter, r *http.Request) {
|
||||
// 固定的 12 条金标查询(4类×3级)
|
||||
// 对每条生成 query → recall 获得真实 expected_ids
|
||||
goldenQueries := []struct {
|
||||
cat string
|
||||
cat string
|
||||
difficulty string
|
||||
query string
|
||||
query string
|
||||
}{
|
||||
// system_fact
|
||||
{"system_fact", "easy", "织忆是什么"},
|
||||
@@ -569,11 +647,11 @@ func (ea *EvalAPI) Generate(w http.ResponseWriter, r *http.Request) {
|
||||
// 空断言自守:如果 recall 返回 0 条,不得写入空 expected_ids(那是 bootstrap,不是校准)
|
||||
if len(expectedIDs) == 0 {
|
||||
results = append(results, map[string]interface{}{
|
||||
"query": gq.query,
|
||||
"query": gq.query,
|
||||
"expected_ids": []string{},
|
||||
"category": gq.cat,
|
||||
"difficulty": gq.difficulty,
|
||||
"warning": "recall 返回 0 条——bootstrap 基线为空,需人工校准",
|
||||
"category": gq.cat,
|
||||
"difficulty": gq.difficulty,
|
||||
"warning": "recall 返回 0 条——bootstrap 基线为空,需人工校准",
|
||||
})
|
||||
continue
|
||||
}
|
||||
@@ -603,14 +681,21 @@ func makeSet(ids []string) map[string]bool {
|
||||
|
||||
func log2(x float64) float64 {
|
||||
result := 0.0
|
||||
for x > 2 { x /= 2; result += 1 }
|
||||
if x > 1 { result += (x - 1) }
|
||||
for x > 2 {
|
||||
x /= 2
|
||||
result += 1
|
||||
}
|
||||
if x > 1 {
|
||||
result += (x - 1)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func contains(list []string, item string) bool {
|
||||
for _, s := range list {
|
||||
if s == item { return true }
|
||||
if s == item {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -620,7 +705,9 @@ func avgByGroup(m map[string][]float64) map[string]float64 {
|
||||
for k, vals := range m {
|
||||
if len(vals) > 0 {
|
||||
sum := 0.0
|
||||
for _, v := range vals { sum += v }
|
||||
for _, v := range vals {
|
||||
sum += v
|
||||
}
|
||||
result[k] = sum / float64(len(vals))
|
||||
}
|
||||
}
|
||||
@@ -629,15 +716,17 @@ func avgByGroup(m map[string][]float64) map[string]float64 {
|
||||
|
||||
func inferCategory(query, defaultCat string) string {
|
||||
for cat, keywords := range map[string][]string{
|
||||
"system_fact": {"os", "系统", "gpu", "内存", "ram", "端口", "配置"},
|
||||
"user_pref": {"偏好", "风格", "喜欢", "牧尘"},
|
||||
"proj_context":{"项目", "路径", "代码", "设计文档"},
|
||||
"tool_usage": {"工具", "comfyui", "hermes", "opencode"},
|
||||
"system_fact": {"os", "系统", "gpu", "内存", "ram", "端口", "配置"},
|
||||
"user_pref": {"偏好", "风格", "喜欢", "牧尘"},
|
||||
"proj_context": {"项目", "路径", "代码", "设计文档"},
|
||||
"tool_usage": {"工具", "comfyui", "hermes", "opencode"},
|
||||
} {
|
||||
for _, kw := range keywords {
|
||||
if len(query) >= len(kw) {
|
||||
for i := 0; i <= len(query)-len(kw); i++ {
|
||||
if query[i:i+len(kw)] == kw { return cat }
|
||||
if query[i:i+len(kw)] == kw {
|
||||
return cat
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,22 +10,45 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// liveAPIKey 取活服务密钥:优先 env ZHIYI_TEST_API_KEY;否则读密钥文件
|
||||
// /var/lib/memoryweave/.api-key 的主密钥(第 1 个非注释、非 legacy 行);
|
||||
// 再退到旧 dev 键(无生产密钥文件的环境,如 CI)。
|
||||
// 2026-09-21 密钥轮换后,旧硬编码键 zhiyi-dev-key-2026 已 401 —— 全量金标实跑
|
||||
// 永远 SKIP 的根因(t_fa6c9104 修复量具可用性;不改任何判据)。
|
||||
func liveAPIKey() string {
|
||||
if k := os.Getenv("ZHIYI_TEST_API_KEY"); k != "" {
|
||||
return k
|
||||
}
|
||||
if b, err := os.ReadFile("/var/lib/memoryweave/.api-key"); err == nil {
|
||||
for _, line := range strings.Split(string(b), "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, "legacy:") {
|
||||
continue
|
||||
}
|
||||
return line
|
||||
}
|
||||
}
|
||||
return "zhiyi-dev-key-2026"
|
||||
}
|
||||
|
||||
// ─── recall 辅助:liveRecallOnce ─────────────────────────────
|
||||
// 一次 recall API 调用同时拿 top-5 的 ids + contents,避免两条 HTTP(限流保护)。
|
||||
// 每次调用间加 200ms 间隔,由调用方负责(TestEvalGolden_Live 里 sleep)。
|
||||
//
|
||||
// 统一判据口径(t_a70b07e1,与 Python 量具 golden-check.py 一致):
|
||||
// 取 recall 返回的前 N=5 条:ID 命中 = expected_ids 任一 ∈ 前 N 条;
|
||||
// 关键词命中 = 前 N 条内容任一含 must_include_keywords(大小写不敏感)。
|
||||
// N=5 的来源:recall 请求 top_k=5(liveRecallOnce 固定),与 golden-set.json 说明字段一致。
|
||||
//
|
||||
// 取 recall 返回的前 N=5 条:ID 命中 = expected_ids 任一 ∈ 前 N 条;
|
||||
// 关键词命中 = 前 N 条内容任一含 must_include_keywords(大小写不敏感)。
|
||||
// N=5 的来源:recall 请求 top_k=5(liveRecallOnce 固定),与 golden-set.json 说明字段一致。
|
||||
type recallResult struct {
|
||||
IDS []string
|
||||
TopContents []string
|
||||
Error error
|
||||
IDS []string
|
||||
TopContents []string
|
||||
Error error
|
||||
}
|
||||
|
||||
func liveRecallOnce(query string, maxRetries int, retryWait time.Duration) recallResult {
|
||||
@@ -37,7 +60,7 @@ func liveRecallOnce(query string, maxRetries int, retryWait time.Duration) recal
|
||||
}
|
||||
req, _ := http.NewRequest("POST", "http://127.0.0.1:7821/api/v1/recall", bytes.NewReader(payload))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-API-Key", "zhiyi-dev-key-2026")
|
||||
req.Header.Set("X-API-Key", liveAPIKey())
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
lastErr = fmt.Errorf("HTTP 请求失败: %v", err)
|
||||
@@ -217,13 +240,49 @@ func TestLoadGoldenSet_RejectsVacuousIDs(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// t_dfc93ad0 AC5 回归:部署二进制 CWD=/home/muc(无 testdata/),
|
||||
// POST /api/v1/eval/golden 不传 golden_path 时,旧版「相对 testdata/ 读不到」⇒ 500。
|
||||
// 修复后:缺省路径 / 读不到的路径 ⇒ 回落 **内嵌** 基线(//go:embed),仍可用。
|
||||
// 判据(可复算):在**没有 testdata/ 的 CWD** 里 LoadGoldenSet("") 与
|
||||
// LoadGoldenSet("testdata/golden-set.json")(相对路径读不到)都必须成功
|
||||
// 且返回 14 条 —— 即部署态「缺省命令可用」。
|
||||
func TestLoadGoldenSet_EmbedFallback_DeployCWD(t *testing.T) {
|
||||
empty := t.TempDir() // 模拟部署 CWD:里面没有 testdata/
|
||||
orig, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatalf("取 CWD 失败: %v", err)
|
||||
}
|
||||
if err := os.Chdir(empty); err != nil {
|
||||
t.Fatalf("chdir 到空目录失败: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = os.Chdir(orig) })
|
||||
|
||||
// ① 缺省(path=""):不传 golden_path 的部署态 ⇒ 必须成功 + 14 条(内嵌兜底)
|
||||
gs, err := LoadGoldenSet("")
|
||||
if err != nil {
|
||||
t.Fatalf("✗ AC5:缺省路径加载金标集失败(旧版这里 500): %v", err)
|
||||
}
|
||||
if len(gs.Items) != 14 {
|
||||
t.Fatalf("✗ AC5:内嵌基线期望 14 条,实际 %d", len(gs.Items))
|
||||
}
|
||||
// ② 相对路径读不到(部署 CWD 无 testdata/):也回落内嵌,不 500
|
||||
gs2, err := LoadGoldenSet(filepath.Join("testdata", "golden-set.json"))
|
||||
if err != nil {
|
||||
t.Fatalf("✗ AC5:相对路径读不到时应回落内嵌基线而非报错: %v", err)
|
||||
}
|
||||
if len(gs2.Items) != 14 {
|
||||
t.Fatalf("✗ AC5:回落基线期望 14 条,实际 %d", len(gs2.Items))
|
||||
}
|
||||
t.Logf("✓ AC5:空 CWD(无 testdata/)下 缺省/相对路径 均回落内嵌基线(14 条),部署态缺省命令可用")
|
||||
}
|
||||
|
||||
// ─── AC① 反证:故意把某条 expected_id 改成错误 ID → 该条必须 FAIL ───
|
||||
// 这是本卡核心验收点:证明判据非恒真(改错期望 → 真 FAIL)
|
||||
|
||||
func TestEvalGolden_CounterEvidence(t *testing.T) {
|
||||
// 探活 zhiyid(无服务 → 跳过)
|
||||
healthReq, _ := http.NewRequest("GET", "http://127.0.0.1:7821/api/v1/health", nil)
|
||||
healthReq.Header.Set("X-API-Key", "zhiyi-dev-key-2026")
|
||||
healthReq.Header.Set("X-API-Key", liveAPIKey())
|
||||
resp, err := http.DefaultClient.Do(healthReq)
|
||||
if err != nil || resp == nil {
|
||||
t.Skipf("zhiyid 服务不可达(%v),跳过反证测试", err)
|
||||
@@ -299,7 +358,7 @@ func TestEvalGolden_CounterEvidence(t *testing.T) {
|
||||
func TestEvalGolden_Live(t *testing.T) {
|
||||
// 探活 zhiyid(无服务 → 跳过,不污染 CI)
|
||||
healthReq, _ := http.NewRequest("GET", "http://127.0.0.1:7821/api/v1/health", nil)
|
||||
healthReq.Header.Set("X-API-Key", "zhiyi-dev-key-2026")
|
||||
healthReq.Header.Set("X-API-Key", liveAPIKey())
|
||||
resp, err := http.DefaultClient.Do(healthReq)
|
||||
if err != nil || resp == nil {
|
||||
t.Skipf("zhiyid 服务不可达(%v),跳过全量金标实跑", err)
|
||||
|
||||
@@ -23,6 +23,11 @@ func NewFeedbackAPI(ldb storage.LanceDB) *FeedbackAPI {
|
||||
func (fa *FeedbackAPI) MarkUseful(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
MemoryID string `json:"memory_id"`
|
||||
// 2026-10-24 (t_11245d30):区分人机信号。
|
||||
// 空 = 人工点「有用」(保持 user_feedback,行为不变);
|
||||
// "auto" = 插件自动反馈(_auto_feedback_for_reply)→ 记 auto_feedback,让 V 账可辨「牧尘认可 vs 机器自评」。
|
||||
// 纯观测,不改 V 权重/阈值/上限。
|
||||
Source string `json:"source"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
respondError(w, 400, "invalid body")
|
||||
@@ -34,15 +39,24 @@ func (fa *FeedbackAPI) MarkUseful(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
selfoptimize.Dash.RecordFeedback(true)
|
||||
// V 值:useful = success
|
||||
// V 值:useful = success。action 名按来源区分(人工 user_feedback / 自动 auto_feedback)。
|
||||
action := "user_feedback"
|
||||
if req.Source == "auto" {
|
||||
action = "auto_feedback"
|
||||
}
|
||||
selfoptimize.VProp.RecordDecision(
|
||||
"useful_"+req.MemoryID,
|
||||
[]string{req.MemoryID},
|
||||
"user_feedback", "success", "",
|
||||
action, "success", "",
|
||||
)
|
||||
if err := fa.LanceDB.IncrementUseful(req.MemoryID); err != nil {
|
||||
log.Printf("[feedback] IncrementUseful failed %s: %v", req.MemoryID, err)
|
||||
}
|
||||
// GA-P0-4 (t_bb10e8bc):用户点「有用」= 真实正向 outcome → 追加 hits+ 事件(带时间戳)。
|
||||
// 语义定义见 internal/storage/hit_event.go(hits+ = 被真实使用/认可)。
|
||||
if err := fa.LanceDB.AppendHitEvent(req.MemoryID, "pos", "human_feedback"); err != nil {
|
||||
log.Printf("[feedback] AppendHitEvent(pos) failed %s: %v", req.MemoryID, err)
|
||||
}
|
||||
|
||||
// Phase F: 质量监控 — 每次反馈后检查低质量记忆
|
||||
feedbackCount := selfoptimize.Dash.UsefulCount + selfoptimize.Dash.NotUsefulCount
|
||||
@@ -80,8 +94,14 @@ func (fa *FeedbackAPI) MarkNotUseful(w http.ResponseWriter, r *http.Request) {
|
||||
[]string{req.MemoryID},
|
||||
"user_feedback", "failure", "",
|
||||
)
|
||||
if err := fa.LanceDB.IncrementNotUseful(req.MemoryID); err != nil {
|
||||
log.Printf("[feedback] IncrementNotUseful failed %s: %v", req.MemoryID, err)
|
||||
// GA-P0-1 (t_718d8707):人工点「没用」→ 写 human_not_useful_count(不再写混写列 not_useful_count)
|
||||
if err := fa.LanceDB.IncrementHumanNotUseful(req.MemoryID); err != nil {
|
||||
log.Printf("[feedback] IncrementHumanNotUseful failed %s: %v", req.MemoryID, err)
|
||||
}
|
||||
// GA-P0-4 (t_bb10e8bc):用户点「没用」= 真实负向 outcome → 追加 hits− 事件(带时间戳)。
|
||||
// 注意:这只在用户人工点「没用」时追加,dedup 自动降权走 dedup_downweight_count 不追加(见 hit_event.go 排除项)。
|
||||
if err := fa.LanceDB.AppendHitEvent(req.MemoryID, "neg", "human_feedback"); err != nil {
|
||||
log.Printf("[feedback] AppendHitEvent(neg) failed %s: %v", req.MemoryID, err)
|
||||
}
|
||||
|
||||
// Phase F: 质量监控 — negative feedback 触发低质量检测
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
// Package routes — 遗忘保护守卫端到端回归测试(t_944344b5,AC1/AC2)。
|
||||
//
|
||||
// 2026-10-16 (t_944344b5):证明「decay/auto_forget 的判定道(admin Forget 路由)命中保护
|
||||
// 规则的候选**不被** SoftDelete,而非保护的衰减候选**照常**被软删」。
|
||||
//
|
||||
// 必须走**真实判定路径**(routes.NewAdminAPI.Forget),不能只测 memprotect.IsProtected,
|
||||
// 因为守卫是在 decay 循环 / admin Forget 路由里 SoftDelete 之前拦截的(见 server.go / admin.go)。
|
||||
//
|
||||
// 跑法(A/B 纪律:复制数据目录 + 独立 socket,绝不碰生产 /var/lib/memoryweave):
|
||||
// 1. cp -a /var/lib/memoryweave /tmp/mw-prot-copy-<ts>
|
||||
// 2. zhiyi-consolidate --mode socket --socket /tmp/mw-prot.sock \
|
||||
// --data-dir /tmp/mw-prot-copy-<ts> &
|
||||
// 3. PROT_TEST_SOCK=/tmp/mw-prot.sock \
|
||||
// go test ./internal/api/routes/ -run TestForgetGuardE2E -v -count=1
|
||||
//
|
||||
// 未设 PROT_TEST_SOCK → 自动跳过(可安全留在 CI)。
|
||||
package routes_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/governance"
|
||||
"github.com/xiaoxue/memoryweave/internal/models"
|
||||
"github.com/xiaoxue/memoryweave/internal/storage"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/api/routes"
|
||||
)
|
||||
|
||||
func TestForgetGuardE2E(t *testing.T) {
|
||||
sock := os.Getenv("PROT_TEST_SOCK")
|
||||
if sock == "" {
|
||||
t.Skip("PROT_TEST_SOCK 未设置,跳过(需先起 test sidecar 指向复制的数据目录)")
|
||||
}
|
||||
|
||||
// 让遗忘窗口游标指到临时文件(缺失 → 空游标 → 从最小 id 起轮转),
|
||||
// 保证我们构造的 `mem_0...` 行(id 最小)落在首个 2000 窗口内。
|
||||
// 不碰生产 /var/lib/memoryweave/forget-cursor.json。
|
||||
cursorDir := t.TempDir()
|
||||
cursorFile := cursorDir + "/test-forget-cursor.json"
|
||||
t.Setenv("ZHIYI_FORGET_CURSOR", cursorFile)
|
||||
|
||||
// embedder 传 nil:记录自带 1024 维 Vector,走不到编码分支(同 conf_e2e_test.go 做法)。
|
||||
rc := storage.NewRustLanceDBClient(sock, nil)
|
||||
f := governance.NewForgetter()
|
||||
aa := routes.NewAdminAPI(rc, f, nil) // GraphStore 传 nil:extractTopEntityDegree 空安全
|
||||
|
||||
// ── 构造 4 条测试记忆(id 都以 mem_0 开头 → 字典序最小 → 必在首窗口)──
|
||||
vec := make([]float32, 1024)
|
||||
for i := range vec {
|
||||
vec[i] = 0.001
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
mk := func(id, category, content, freshness string, daysAgo int) models.MemoryRecord {
|
||||
lr := now.Add(-time.Duration(daysAgo) * 24 * time.Hour)
|
||||
return models.MemoryRecord{
|
||||
ID: id, AgentID: "hermes-a06", Namespace: "prot-test",
|
||||
Content: content, Category: category, Vector: vec,
|
||||
Tier: "normal", Importance: 0.5, QualityScore: 0.5,
|
||||
Version: 1, Freshness: freshness,
|
||||
Source: "wiki:/tmp/forget-guard-e2e.md",
|
||||
EmbeddingModel: "bge-m3", ScriptVersion: "forget-guard-e2e",
|
||||
CreatedAt: lr, UpdatedAt: lr, LastRecalledAt: lr,
|
||||
RecallVerifiedCount: 0,
|
||||
}
|
||||
}
|
||||
|
||||
// P1:规则3 freshness=verified 保护。content <30 字 + >20 天 ⇒ 本应走碎片快速道被删,
|
||||
// 但 freshness=verified ⇒ 守卫拦截 ⇒ 存活。
|
||||
p1 := mk("mem_0aaaa_p1", "distilled", "verified fact, kept", "verified", 30)
|
||||
// P2:规则1 category=decision 保护。
|
||||
p2 := mk("mem_0aaaa_p2", "decision", "short decision note", "fresh", 30)
|
||||
// P3:规则4 content 关键词「牧尘要求」保护。
|
||||
p3 := mk("mem_0aaaa_p3", "distilled", "牧尘要求:部署前必须先备份", "fresh", 30)
|
||||
// N1:不命中任何规则(distilled / fresh / 无关键词 / 低 V / 不在名单)⇒ 应被碎片快速道软删。
|
||||
n1 := mk("mem_0aaaa_n1", "distilled", "hi", "fresh", 45)
|
||||
|
||||
for _, m := range []models.MemoryRecord{p1, p2, p3, n1} {
|
||||
if err := rc.InsertMemory(m); err != nil {
|
||||
t.Fatalf("InsertMemory(%s) 失败: %v", m.ID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// ── 跑真实判定路径:admin Forget 路由(= decay/auto_forget 决策 + 守卫 + SoftDelete)──
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/forget", nil)
|
||||
w := httptest.NewRecorder()
|
||||
aa.Forget(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("admin forget expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp map[string]interface{}
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
t.Logf("admin forget 响应: %v", resp)
|
||||
|
||||
// ── 断言 ──
|
||||
// 读路径语义(rust lancedb_ops.rs):
|
||||
// scan_all → 仅 is_deleted=false(存活集,无 5000 上限)
|
||||
// scan_deleted → 仅 is_deleted=true(已删集,带 delete_reason)
|
||||
// 故 P1/P2/P3 应出现在 ScanAll 里;N1 应不在 ScanAll、而在 ScanDeleted 里。
|
||||
all, err := rc.ScanAll()
|
||||
if err != nil {
|
||||
t.Fatalf("ScanAll 失败: %v", err)
|
||||
}
|
||||
liveSet := map[string]bool{}
|
||||
for _, m := range all {
|
||||
liveSet[m.ID] = true // scan_all 只回 is_deleted=false
|
||||
}
|
||||
for _, id := range []string{p1.ID, p2.ID, p3.ID} {
|
||||
if !liveSet[id] {
|
||||
t.Errorf("❌ 受保护记忆 %s 应存活(ScanAll 命中),实际不在 —— 守卫失效", id)
|
||||
}
|
||||
}
|
||||
if liveSet[n1.ID] {
|
||||
t.Errorf("❌ 非保护衰减记忆 %s 应被软删(不在 ScanAll),实际仍存活 —— 回归异常", n1.ID)
|
||||
}
|
||||
|
||||
deleted, derr := rc.ScanDeleted()
|
||||
if derr != nil {
|
||||
t.Fatalf("ScanDeleted 失败: %v", derr)
|
||||
}
|
||||
deletedSet, n1Reason := map[string]bool{}, ""
|
||||
for _, m := range deleted {
|
||||
deletedSet[m.ID] = true
|
||||
if m.ID == n1.ID {
|
||||
n1Reason = m.DeleteReason
|
||||
}
|
||||
}
|
||||
if !deletedSet[n1.ID] {
|
||||
t.Errorf("❌ 非保护衰减记忆 %s 应出现在 ScanDeleted(is_deleted=true),实际不在", n1.ID)
|
||||
}
|
||||
if t.Failed() {
|
||||
return
|
||||
}
|
||||
// 受保护 3 条存活 + 非保护 1 条被删,打印结论
|
||||
t.Logf("✅ AC1 3 条命中保护规则(freshness=verified / category=decision / 关键词)全部存活于 ScanAll")
|
||||
t.Logf("✅ AC2 非保护衰减碎片 %s 照常软删(在 ScanDeleted)", n1.ID)
|
||||
// 取证:N1 的 delete_reason(auto_forget*/fragment 经 NormalizeDeleteReason → retention)
|
||||
t.Logf("取证: %s delete_reason=%q", n1.ID, n1Reason)
|
||||
}
|
||||
@@ -14,19 +14,19 @@ import (
|
||||
|
||||
// GapAutoRepair 缺口自动修复器
|
||||
type GapAutoRepair struct {
|
||||
detector *selfoptimize.GapDetector
|
||||
ldb storage.LanceDB
|
||||
synonyms map[string][]string // 同义词映射
|
||||
detector *selfoptimize.GapDetector
|
||||
ldb storage.LanceDB
|
||||
synonyms map[string][]string // 同义词映射
|
||||
}
|
||||
|
||||
var GapRepair = &GapAutoRepair{
|
||||
detector: nil, // 由 InitGapRepair 注入
|
||||
synonyms: map[string][]string{
|
||||
"GPU": {"gpu", "显卡", "graphics"},
|
||||
"OS": {"os", "操作系统", "系统"},
|
||||
"API": {"api", "接口", "endpoint"},
|
||||
"SSE": {"sse", "server-sent events", "事件推送"},
|
||||
"CRDT": {"crdt", "冲突合并", "merge"},
|
||||
"GPU": {"gpu", "显卡", "graphics"},
|
||||
"OS": {"os", "操作系统", "系统"},
|
||||
"API": {"api", "接口", "endpoint"},
|
||||
"SSE": {"sse", "server-sent events", "事件推送"},
|
||||
"CRDT": {"crdt", "冲突合并", "merge"},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ package routes
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/selfoptimize"
|
||||
)
|
||||
@@ -32,17 +33,31 @@ func (ga *GapAPI) List(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
}
|
||||
|
||||
// POST /api/v1/gaps/{topic}/close
|
||||
// POST /api/v1/gaps/close/{topic}(现行前缀注册 /api/v1/gaps/close/;亦兼容 {topic} 通配注册)
|
||||
func (ga *GapAPI) Close(w http.ResponseWriter, r *http.Request) {
|
||||
topic := r.PathValue("topic")
|
||||
if topic == "" {
|
||||
// 现行注册是前缀路由(模式无 {topic} 通配 ⇒ PathValue 恒为 "",端点此前恒 400):
|
||||
// 回落剥前缀取 topic。若日后改注册为 /api/v1/gaps/{topic}/close,PathValue 直接命中。
|
||||
const prefix = "/api/v1/gaps/close/"
|
||||
if strings.HasPrefix(r.URL.Path, prefix) {
|
||||
topic = r.URL.Path[len(prefix):]
|
||||
}
|
||||
}
|
||||
if topic == "" {
|
||||
respondError(w, 400, "topic required")
|
||||
return
|
||||
}
|
||||
|
||||
ga.Detector.Close(topic)
|
||||
selfoptimize.Dash.RecordGapClosed()
|
||||
respond(w, 200, map[string]string{"status": "closed", "topic": topic})
|
||||
// t_e5997ca4:计数口径 = 「缺口个数」。+1 只发生在 GapDetector 的 open→closed 迁移点
|
||||
// (Close 内部);旧的无条件 selfoptimize.Dash.RecordGapClosed() 已删除 —— 那是同一
|
||||
// 缺口可被无限计数、ClosedGaps(9) 越过 TotalGaps(2) 的写侧根因 #1。
|
||||
switch ga.Detector.Close(topic) {
|
||||
case true:
|
||||
respond(w, 200, map[string]string{"status": "closed", "topic": topic})
|
||||
default:
|
||||
respond(w, 200, map[string]string{"status": "already_closed", "topic": topic})
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/v1/gaps/detect — 手动触发缺口检测(miss 计数)
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
// 织忆 MemoryWeave — gap 关闭端点写侧回归(t_e5997ca4 卡 AC2)
|
||||
//
|
||||
// POST /close 打两回(httptest)⇒ gap 计数器只 +1;auto 等其余计数器不受影响。
|
||||
package routes
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/selfoptimize"
|
||||
)
|
||||
|
||||
// makeGapTopic 3 次 miss 命中默认阈值 3 ⇒ 生成缺口(TotalGaps +1)。
|
||||
func makeGapTopic(t *testing.T, gd *selfoptimize.GapDetector, topic string) {
|
||||
t.Helper()
|
||||
var gap *selfoptimize.Gap
|
||||
for i := 0; i < 3; i++ {
|
||||
if gap = gd.RecordMiss(topic); gap != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
if gap == nil {
|
||||
t.Fatalf("expected gap for %q after 3 misses", topic)
|
||||
}
|
||||
}
|
||||
|
||||
func postGapClose(t *testing.T, url string) (int, map[string]string) {
|
||||
t.Helper()
|
||||
resp, err := http.Post(url, "application/json", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("POST %s: %v", url, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var body map[string]string
|
||||
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("POST %s: 非 JSON 响应 %q: %v", url, b, err)
|
||||
}
|
||||
return resp.StatusCode, body
|
||||
}
|
||||
|
||||
// 卡 AC2:现行注册形态(前缀路由,topic 在 /api/v1/gaps/close/ 之后)打两回 ⇒ 只 +1。
|
||||
func TestGapAPI_CloseTwice_CounterOnlyOnce(t *testing.T) {
|
||||
gd := selfoptimize.NewGapDetector(nil, nil)
|
||||
makeGapTopic(t, gd, "close-twice-topic")
|
||||
|
||||
baseClosed := selfoptimize.Dash.ClosedGapsCount()
|
||||
baseTotal := selfoptimize.Dash.TotalGapsCount()
|
||||
baseMetrics := selfoptimize.Dash.Metrics() // auto_* 快照(应不受影响)
|
||||
|
||||
api := NewGapAPI(gd)
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/v1/gaps/close/", api.Close) // 与 server.go:1205 现行注册同形
|
||||
ts := httptest.NewServer(mux)
|
||||
defer ts.Close()
|
||||
|
||||
code1, body1 := postGapClose(t, ts.URL+"/api/v1/gaps/close/close-twice-topic")
|
||||
if code1 != 200 || body1["status"] != "closed" {
|
||||
t.Fatalf("第 1 次 POST: got %d %v, want 200 closed", code1, body1)
|
||||
}
|
||||
code2, body2 := postGapClose(t, ts.URL+"/api/v1/gaps/close/close-twice-topic")
|
||||
if code2 != 200 || body2["status"] != "already_closed" {
|
||||
t.Fatalf("第 2 次 POST: got %d %v, want 200 already_closed(不得再动计数)", code2, body2)
|
||||
}
|
||||
|
||||
if got := selfoptimize.Dash.ClosedGapsCount() - baseClosed; got != 1 {
|
||||
t.Fatalf("2× POST close 后 ClosedGaps 增量: got %d, want 1(改前为 +3 ⇒ 虚增)", got)
|
||||
}
|
||||
if got := selfoptimize.Dash.TotalGapsCount(); got != baseTotal {
|
||||
t.Errorf("TotalGaps 不应被 close 端点移动: got %d want %d", got, baseTotal)
|
||||
}
|
||||
|
||||
after := selfoptimize.Dash.Metrics()
|
||||
if after["gap_closure_rate"] > 1 {
|
||||
t.Errorf("gap_closure_rate = %f 越界", after["gap_closure_rate"])
|
||||
}
|
||||
// auto(冲突)计数器与 gap 关闭事件无关 ⇒ 快照不变(「auto 不适用」)
|
||||
for _, k := range []string{"auto_resolve_rate", "auto_resolve_samples", "auto_resolve_valid"} {
|
||||
if after[k] != baseMetrics[k] {
|
||||
t.Errorf("auto 计数器被 gap 关闭污染: %s got %f want %f", k, after[k], baseMetrics[k])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// {topic} 通配注册形态(若日后把 server.go 注册改成 /api/v1/gaps/{topic}/close):
|
||||
// PathValue 直接命中,计数语义不变(+1 只在首次)。
|
||||
func TestGapAPI_CloseWildcardRegistration(t *testing.T) {
|
||||
gd := selfoptimize.NewGapDetector(nil, nil)
|
||||
makeGapTopic(t, gd, "wildcard-topic")
|
||||
|
||||
baseClosed := selfoptimize.Dash.ClosedGapsCount()
|
||||
|
||||
api := NewGapAPI(gd)
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/v1/gaps/{topic}/close", api.Close)
|
||||
ts := httptest.NewServer(mux)
|
||||
defer ts.Close()
|
||||
|
||||
code, body := postGapClose(t, ts.URL+"/api/v1/gaps/wildcard-topic/close")
|
||||
if code != 200 || body["status"] != "closed" {
|
||||
t.Fatalf("通配注册第 1 次 POST: got %d %v, want 200 closed", code, body)
|
||||
}
|
||||
if _, body2 := postGapClose(t, ts.URL+"/api/v1/gaps/wildcard-topic/close"); body2["status"] != "already_closed" {
|
||||
t.Errorf("通配注册第 2 次 POST: got %v, want already_closed", body2)
|
||||
}
|
||||
if got := selfoptimize.Dash.ClosedGapsCount() - baseClosed; got != 1 {
|
||||
t.Fatalf("通配注册 2× POST 后 ClosedGaps 增量: got %d, want 1", got)
|
||||
}
|
||||
}
|
||||
@@ -26,17 +26,17 @@ type WorldModel struct {
|
||||
|
||||
Services []ServiceInfo `json:"services"` // ℐ: 服务和端口
|
||||
|
||||
ImplicitRules []string `json:"implicit_rules"` // C: 软约束
|
||||
HardConstraints []string `json:"hard_constraints"` // C: 硬约束
|
||||
Capabilities []string `json:"capabilities"`
|
||||
ImplicitRules []string `json:"implicit_rules"` // C: 软约束
|
||||
HardConstraints []string `json:"hard_constraints"` // C: 硬约束
|
||||
Capabilities []string `json:"capabilities"`
|
||||
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
type ServiceInfo struct {
|
||||
Name string `json:"name"`
|
||||
Port int `json:"port"`
|
||||
Status string `json:"status"`
|
||||
Name string `json:"name"`
|
||||
Port int `json:"port"`
|
||||
Status string `json:"status"`
|
||||
DependsOn []string `json:"depends_on,omitempty"`
|
||||
Provides []string `json:"provides,omitempty"`
|
||||
}
|
||||
@@ -111,13 +111,13 @@ func (wm *WorldModel) GetHandler(w http.ResponseWriter, r *http.Request) {
|
||||
// POST /api/v1/l3/worldmodel — 更新
|
||||
func (wm *WorldModel) UpdateHandler(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Environment *struct {
|
||||
Environment *struct {
|
||||
OS string `json:"os"`
|
||||
GPU string `json:"gpu"`
|
||||
VRAM string `json:"vram"`
|
||||
RAM string `json:"ram"`
|
||||
} `json:"environment"`
|
||||
AddRules []string `json:"add_rules"`
|
||||
AddRules []string `json:"add_rules"`
|
||||
AddCapabilities []string `json:"add_capabilities"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
// 织忆 MemoryWeave — /api/v1/memory/write 显式直写 memories 表(主症A,t_fa6c9104,2026-10-16)
|
||||
//
|
||||
// 锁定行为:
|
||||
//
|
||||
// W1 写入落 memories 表:InsertMemory 被调用,id 前缀 mem_,tier=normal,quality=1.0,
|
||||
// 且向量非全 0(嵌入服务故障时不写零向量记录)
|
||||
// W2 category 缺省 distilled(recall Step 2.5 rawCategories 不过滤它)
|
||||
// W3 嵌入失败 ⇒ 502 且不写(零向量 = 主症A 病根,禁静默写)
|
||||
// W4 精确重复 ⇒ merged(不新增行)
|
||||
// W5 短内容 <8 字 ⇒ 400;GET ⇒ 405
|
||||
// W6 零回归:commit 路径仍只写 episodes、不写 memories(AC5)
|
||||
package routes
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/distill"
|
||||
"github.com/xiaoxue/memoryweave/internal/governance"
|
||||
"github.com/xiaoxue/memoryweave/internal/models"
|
||||
"github.com/xiaoxue/memoryweave/internal/storage"
|
||||
)
|
||||
|
||||
// recLance 记录型 LanceDB mock:断言 InsertMemory/Update 的实际调用与载荷。
|
||||
// 复用 zz_commit_conflict_gate_test.go 的 mockGraph / newMockEmbedServer / newMockLLM / commitWith(同包)。
|
||||
type recLance struct {
|
||||
storage.LanceDB // 未实现的方法落到接口兜底(panic 即测试失败,不放任)
|
||||
|
||||
mu sync.Mutex
|
||||
seeds []models.MemoryRecord // 预置「库里已有」的记忆(Search 返回)
|
||||
inserted []models.MemoryRecord // 实际 InsertMemory 调用(W1/W3/W4 断言)
|
||||
updates []string // Update(table,id,...) 的 id 序列(merge 断言)
|
||||
failIns bool // 模拟 IPC 落库失败(500 断言)
|
||||
}
|
||||
|
||||
func (r *recLance) Search(table string, vector []float32, topK int, ns string) ([]models.MemoryRecord, error) {
|
||||
if table != "memories" {
|
||||
return nil, nil
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
out := make([]models.MemoryRecord, 0, len(r.seeds))
|
||||
out = append(out, r.seeds...)
|
||||
if topK > 0 && len(out) > topK {
|
||||
out = out[:topK]
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (r *recLance) InsertMemory(m models.MemoryRecord) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if r.failIns {
|
||||
return errors.New("ipc down (simulated)")
|
||||
}
|
||||
r.inserted = append(r.inserted, m)
|
||||
r.seeds = append(r.seeds, m) // 后续 Search 能看见(近重复语义)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *recLance) Update(table, id string, fields map[string]any) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.updates = append(r.updates, id)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *recLance) InsertEpisode(agentID, namespace, content, category string) (string, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return "ep_rec_" + strconv.Itoa(len(r.inserted)), nil
|
||||
}
|
||||
|
||||
func newRecAPI(t *testing.T, seeds ...models.MemoryRecord) (*API, *recLance) {
|
||||
t.Helper()
|
||||
emb := newMockEmbedServer()
|
||||
t.Cleanup(emb.Close)
|
||||
ldb := &recLance{seeds: seeds}
|
||||
return NewAPI(ldb, storage.NewEmbedder(emb.URL), nil, governance.NewConflictDetector(), mockGraph{}), ldb
|
||||
}
|
||||
|
||||
func writeMemRequest(t *testing.T, api *API, body map[string]any) (int, map[string]interface{}) {
|
||||
t.Helper()
|
||||
b, _ := json.Marshal(body)
|
||||
req := httptest.NewRequest("POST", "/api/v1/memory/write", bytes.NewReader(b))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
api.WriteMemory(w, req)
|
||||
var resp map[string]interface{}
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
return w.Code, resp
|
||||
}
|
||||
|
||||
// W1+W2:写入落 memories 表,mem_ 前缀,category 缺省 distilled,向量非全 0
|
||||
func TestWriteMemory_InsertLandsInMemories(t *testing.T) {
|
||||
api, ldb := newRecAPI(t)
|
||||
code, resp := writeMemRequest(t, api, map[string]any{
|
||||
"content": "牧尘的工作所在省份是河南省",
|
||||
"agent_id": "hermes-a06",
|
||||
})
|
||||
if code != 201 {
|
||||
t.Fatalf("expected 201, got %d: %s", code, resp)
|
||||
}
|
||||
if resp["status"] != "ok" || resp["table"] != "memories" {
|
||||
t.Errorf("expected status=ok table=memories, got %v", resp)
|
||||
}
|
||||
if !strings.HasPrefix(resp["memory_id"].(string), "mem_") {
|
||||
t.Errorf("memory_id 须 mem_ 前缀(落 memories 表),got %v", resp["memory_id"])
|
||||
}
|
||||
if resp["category"] != "distilled" {
|
||||
t.Errorf("category 缺省须 distilled(Step 2.5 不过滤),got %v", resp["category"])
|
||||
}
|
||||
if len(ldb.inserted) != 1 {
|
||||
t.Fatalf("expected exactly 1 InsertMemory, got %d", len(ldb.inserted))
|
||||
}
|
||||
m := ldb.inserted[0]
|
||||
if m.Category != "distilled" || m.Tier != "normal" || m.QualityScore != 1.0 {
|
||||
t.Errorf("row 字段: category=%s tier=%s quality=%v(期望 distilled/normal/1.0)", m.Category, m.Tier, m.QualityScore)
|
||||
}
|
||||
if m.Namespace != "hermes-main" {
|
||||
t.Errorf("namespace 推导: got %s 期望 hermes-main(hermes-a06 ⇒ deriveNamespace)", m.Namespace)
|
||||
}
|
||||
if len(m.Vector) != 1024 {
|
||||
t.Fatalf("vector 维度须 1024,got %d", len(m.Vector))
|
||||
}
|
||||
// W1 核心判据:vector 非全 0
|
||||
nonzero := 0
|
||||
for _, f := range m.Vector {
|
||||
if f != 0 {
|
||||
nonzero++
|
||||
}
|
||||
}
|
||||
if nonzero == 0 {
|
||||
t.Errorf("向量全 0 —— 主症A 病根复现(禁写零向量记录)")
|
||||
}
|
||||
}
|
||||
|
||||
// W3:嵌入失败 ⇒ 502 且不写库(fail-close,不静默写零向量)
|
||||
func TestWriteMemory_EmbedFail_502_NoWrite(t *testing.T) {
|
||||
failEmb := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "embed backend down", http.StatusInternalServerError)
|
||||
}))
|
||||
defer failEmb.Close()
|
||||
ldb := &recLance{}
|
||||
api := NewAPI(ldb, storage.NewEmbedder(failEmb.URL), nil, governance.NewConflictDetector(), mockGraph{})
|
||||
code, resp := writeMemRequest(t, api, map[string]any{"content": "牧尘的工作所在省份是河南省"})
|
||||
if code != 502 {
|
||||
t.Fatalf("embed 失败须 502,got %d: %v", code, resp)
|
||||
}
|
||||
if len(ldb.inserted) != 0 {
|
||||
t.Errorf("嵌入失败不得写库(零向量 = 主症A),inserted=%d", len(ldb.inserted))
|
||||
}
|
||||
}
|
||||
|
||||
// W4:精确重复 ⇒ merged,不新增行
|
||||
func TestWriteMemory_ExactDupMerges(t *testing.T) {
|
||||
seed := models.MemoryRecord{ID: "mem_seed", Content: "家用服务器地址是 192.168.123.11", Category: "distilled"}
|
||||
api, ldb := newRecAPI(t, seed)
|
||||
code, resp := writeMemRequest(t, api, map[string]any{"content": seed.Content})
|
||||
if code != 200 || resp["status"] != "merged" {
|
||||
t.Fatalf("expected 200 merged, got %d %v", code, resp)
|
||||
}
|
||||
if len(ldb.inserted) != 0 {
|
||||
t.Errorf("精确重复不得新增行,inserted=%d", len(ldb.inserted))
|
||||
}
|
||||
if len(ldb.updates) == 0 || ldb.updates[0] != "mem_seed" {
|
||||
t.Errorf("merge 须 Update 既有行 mem_seed,updates=%v", ldb.updates)
|
||||
}
|
||||
}
|
||||
|
||||
// W5:短内容 400;GET 405
|
||||
func TestWriteMemory_Validation(t *testing.T) {
|
||||
api, _ := newRecAPI(t)
|
||||
if c, _ := writeMemRequest(t, api, map[string]any{"content": "太短了"}); c != 400 {
|
||||
t.Errorf("短内容(<8字)须 400, got %d", c)
|
||||
}
|
||||
req := httptest.NewRequest("GET", "/api/v1/memory/write", nil)
|
||||
w := httptest.NewRecorder()
|
||||
api.WriteMemory(w, req)
|
||||
if w.Code != 405 {
|
||||
t.Errorf("GET 须 405, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// 落库失败(IPC down)⇒ 500 不吞错
|
||||
func TestWriteMemory_InsertFail_500(t *testing.T) {
|
||||
api, ldb := newRecAPI(t)
|
||||
ldb.failIns = true
|
||||
code, _ := writeMemRequest(t, api, map[string]any{"content": "测试落库失败场景内容足够长"})
|
||||
if code != 500 {
|
||||
t.Fatalf("InsertMemory 失败须 500(不吞错),got %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
// W6 零回归:commit 路径仍「只写 episodes、不写 memories」(等蒸馏)
|
||||
func TestCommit_StillEpisodesOnly_ZeroRegression(t *testing.T) {
|
||||
api, ldb := newRecAPI(t)
|
||||
llm := newMockLLM()
|
||||
defer llm.server.Close()
|
||||
oldRef := DistillEngineRef
|
||||
DistillEngineRef = distill.NewEngine(llm.server.URL, "mock-model", "")
|
||||
defer func() { DistillEngineRef = oldRef }()
|
||||
|
||||
// 复用 commitWith(同包 zz 测试):普通对话提交
|
||||
resp := commitWith(t, api, "今天天气不错,我们去楼下散步", false)
|
||||
if resp["status"] != "ok" {
|
||||
t.Fatalf("commit 基线须 status=ok,got %v", resp)
|
||||
}
|
||||
if resp["memory_id"] != "" {
|
||||
t.Errorf("commit 不在写入时创建 memory(AC5 零回归),got %v", resp["memory_id"])
|
||||
}
|
||||
if len(ldb.inserted) != 0 {
|
||||
t.Errorf("commit 不得直写 memories 表(零回归),inserted=%d", len(ldb.inserted))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package routes
|
||||
|
||||
// t_5ad3f843 AC8:handler 级门禁验证。
|
||||
// 门禁开 ⇒ meta-note 在**触碰 storage 之前**被 422 拒绝:
|
||||
// 零值 API{}(LanceDB 接口为 nil)足证——若门禁按设计在写路径前生效,
|
||||
// 422 先行返回、不会 nil 解引用 panic;若门禁失效走到 InsertEpisode ⇒ panic。
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/metanote"
|
||||
)
|
||||
|
||||
func TestCommitGate_MetaRejectedBeforeStorage(t *testing.T) {
|
||||
old := os.Getenv("ZHIYI_META_FILTER")
|
||||
os.Setenv("ZHIYI_META_FILTER", "1")
|
||||
defer os.Setenv("ZHIYI_META_FILTER", old)
|
||||
|
||||
a := &API{} // 零值:LanceDB 为 nil —— 422 先于写路径 ⇒ 不 panic
|
||||
body := `{"agent_id":"hermes-a06","namespace":"hermes-main","content":"实测 淇县 ANN 731→15(都进池50)","category":"system_fact"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/commit", strings.NewReader(body))
|
||||
w := httptest.NewRecorder()
|
||||
a.Commit(w, req)
|
||||
if w.Code != 422 {
|
||||
t.Fatalf("commit(meta, 门禁开) 期望 422,实际 %d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
if !strings.Contains(w.Body.String(), "meta-note") {
|
||||
t.Errorf("拒绝体应说明 meta-note 原因: %s", w.Body.String())
|
||||
}
|
||||
|
||||
// 门禁关 ⇒ 同一内容 ShouldSkip 必须 false(AC6 零行为变化)
|
||||
os.Setenv("ZHIYI_META_FILTER", "")
|
||||
if skip, _ := metanote.ShouldSkip("实测 淇县 ANN 731→15(都进池50)"); skip {
|
||||
t.Fatal("门禁关闭时 ShouldSkip 必须为 false(零行为变化)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteMemoryGate_MetaRejectedBeforeStorage(t *testing.T) {
|
||||
old := os.Getenv("ZHIYI_META_FILTER")
|
||||
os.Setenv("ZHIYI_META_FILTER", "1")
|
||||
defer os.Setenv("ZHIYI_META_FILTER", old)
|
||||
|
||||
a := &API{}
|
||||
body := `{"agent_id":"hermes-a06","content":"织忆 golden 14/14 不退化,recall@5 = 0.4286"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/memory/write", strings.NewReader(body))
|
||||
w := httptest.NewRecorder()
|
||||
a.WriteMemory(w, req)
|
||||
if w.Code != 422 {
|
||||
t.Fatalf("write_memory(meta, 门禁开) 期望 422,实际 %d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -103,8 +103,10 @@ func formatEntry(content, category string) string {
|
||||
|
||||
func strValSafe(v interface{}) string {
|
||||
switch s := v.(type) {
|
||||
case string: return s
|
||||
case fmt.Stringer: return s.String()
|
||||
case string:
|
||||
return s
|
||||
case fmt.Stringer:
|
||||
return s.String()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
// 织忆 MemoryWeave — L2 模式 API(t_d32e5f8a)
|
||||
//
|
||||
// 设计 §4.1 端点:
|
||||
// POST /api/v1/patterns/detect 手动触发模式检测(扫 L1 蒸馏记忆 → 工具组合频率 + 路径聚类
|
||||
// → 写 graph_nodes type='pattern')。短命单发:modernc sqlite
|
||||
// 开/关不占长连接、不碰 state.db(规避当年 daemon main_loop
|
||||
// 退役根因)—— 可挂 cron 单发。
|
||||
// GET /api/v1/patterns 列出检测到的模式(按 source_tasks 长度降序)。
|
||||
package routes
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/models"
|
||||
"github.com/xiaoxue/memoryweave/internal/pattern"
|
||||
"github.com/xiaoxue/memoryweave/internal/skillgen"
|
||||
"github.com/xiaoxue/memoryweave/internal/storage"
|
||||
)
|
||||
|
||||
// PatternAPI L2 模式端点 + L3 skill 草稿端点。
|
||||
type PatternAPI struct {
|
||||
Store *pattern.GraphPatternStore
|
||||
Provider *pattern.PatternProvider
|
||||
LDB func() storage.LanceDB // 扫 L1 记忆(distilled)
|
||||
Cfg pattern.Config
|
||||
|
||||
// L3 skill 草稿(t_fcadee04):草稿生成器 + skills 表存储 + 落盘根目录。
|
||||
// 由 server.go 装配;不装配时 Draft/Promote 返回 503/404(显式 API,不挂 cron)。
|
||||
SkillStore *skillgen.Store
|
||||
Generator skillgen.Generator
|
||||
AttachmentsDir string
|
||||
}
|
||||
|
||||
// NewPatternAPI 构造 L2 模式端点。
|
||||
func NewPatternAPI(store *pattern.GraphPatternStore, provider *pattern.PatternProvider, ldb func() storage.LanceDB) *PatternAPI {
|
||||
cfg := pattern.DefaultConfig()
|
||||
// cron 单发跑大批量时可放宽扫描上限
|
||||
if v := os.Getenv("ZHIYI_PATTERN_MAX_RECORDS"); v != "" {
|
||||
if n, err := strconv.Atoi(v); err == nil && n > 0 {
|
||||
cfg.MaxRecords = n
|
||||
}
|
||||
}
|
||||
return &PatternAPI{Store: store, Provider: provider, LDB: ldb, Cfg: cfg}
|
||||
}
|
||||
|
||||
// GET /api/v1/patterns — 列出所有检测到的模式(AC1:空库返回 count=0 不报错)。
|
||||
func (pa *PatternAPI) List(w http.ResponseWriter, r *http.Request) {
|
||||
limit := pa.Cfg.TopKPatternList
|
||||
if v := r.URL.Query().Get("limit"); v != "" {
|
||||
if n, err := strconv.Atoi(v); err == nil && n > 0 {
|
||||
limit = n
|
||||
}
|
||||
}
|
||||
pats, _, err := pa.Store.ListPatterns(limit)
|
||||
if err != nil {
|
||||
respondError(w, 500, "list patterns: "+err.Error())
|
||||
return
|
||||
}
|
||||
respond(w, 200, map[string]interface{}{
|
||||
"patterns": pats,
|
||||
"count": len(pats),
|
||||
})
|
||||
}
|
||||
|
||||
// POST /api/v1/patterns/detect — 手动触发模式检测。
|
||||
// body 可选 {"limit": N, "namespace": "hermes-main"}。
|
||||
// 流程:LanceDB Scan(limit, ns) → pattern.DetectFromRecords → UpsertPatterns(graph_nodes)。
|
||||
// 空库/无命中 → created/updated=0,不报错(AC1)。
|
||||
func (pa *PatternAPI) Detect(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Limit int `json:"limit"`
|
||||
Namespace string `json:"namespace"`
|
||||
}
|
||||
if r.Body != nil {
|
||||
_ = json.NewDecoder(r.Body).Decode(&req) // 空 body 也合法(用默认)
|
||||
}
|
||||
if req.Limit <= 0 {
|
||||
req.Limit = pa.Cfg.MaxRecords
|
||||
}
|
||||
ldb := pa.LDB()
|
||||
if ldb == nil {
|
||||
respondError(w, 503, "lancedb unavailable")
|
||||
return
|
||||
}
|
||||
records, err := ldb.Scan(req.Limit, req.Namespace)
|
||||
if err != nil {
|
||||
respondError(w, 500, "scan memories: "+err.Error())
|
||||
return
|
||||
}
|
||||
// 只拿蒸馏产物(L1 蒸馏记忆)做检测——原始对话/episode 不是「已验证」的解决路径
|
||||
// (与召回管线 2.5 步同源判据:raw/episodes 类不参与模式沉淀)。
|
||||
distilled := make([]models.MemoryRecord, 0, len(records))
|
||||
for _, rec := range records {
|
||||
if rec.Category == "distilled" || rec.Category == "" {
|
||||
distilled = append(distilled, rec)
|
||||
}
|
||||
}
|
||||
pats := pattern.DetectFromRecords(distilled, pa.Cfg)
|
||||
created, updated, uerr := pa.Store.UpsertPatterns(pats)
|
||||
if uerr != nil {
|
||||
respondError(w, 500, "upsert patterns: "+uerr.Error())
|
||||
return
|
||||
}
|
||||
respond(w, 200, map[string]interface{}{
|
||||
"scanned": len(records),
|
||||
"created": created,
|
||||
"updated": updated,
|
||||
"detected": len(pats),
|
||||
"patterns": pats,
|
||||
})
|
||||
}
|
||||
|
||||
// ── L3 skill 草稿(t_fcadee04,设计 §4.2 SkillGenerator)────────────────────
|
||||
|
||||
// patternSubPath 解析 /api/v1/patterns/{id}/{action} 子路径。
|
||||
// 返回 (url-unescape 后的 id, action)。格式不符 → ("", action=="")。
|
||||
func patternSubPath(path string) (id, action string) {
|
||||
const prefix = "/api/v1/patterns/"
|
||||
if !strings.HasPrefix(path, prefix) {
|
||||
return "", ""
|
||||
}
|
||||
rest := strings.TrimPrefix(path, prefix) // <id>/draft 或 <id>/promote
|
||||
parts := strings.Split(rest, "/")
|
||||
if len(parts) != 2 || parts[0] == "" {
|
||||
return "", ""
|
||||
}
|
||||
dec, err := url.PathUnescape(parts[0])
|
||||
if err != nil {
|
||||
return "", ""
|
||||
}
|
||||
return dec, parts[1]
|
||||
}
|
||||
|
||||
// Sub 分发 /api/v1/patterns/{id}/draft 与 /api/v1/patterns/{id}/promote。
|
||||
// 装配在 server.go 的 /api/v1/patterns/ 前缀路由;List(/patterns) 与 Detect(/patterns/detect)
|
||||
// 因更长的精确路由优先,不受影响。
|
||||
func (pa *PatternAPI) Sub(w http.ResponseWriter, r *http.Request) {
|
||||
id, action := patternSubPath(r.URL.Path)
|
||||
if id == "" {
|
||||
respondError(w, 404, "pattern id required")
|
||||
return
|
||||
}
|
||||
switch action {
|
||||
case "draft":
|
||||
pa.Draft(w, r, id)
|
||||
case "promote":
|
||||
pa.Promote(w, r, id)
|
||||
default:
|
||||
respondError(w, 404, "unknown action: "+action)
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/v1/patterns/{id}/draft — 生成 L3 skill 草稿(conf≥0.85 才生成)。
|
||||
// 流程:读 pattern → 校验 conf → DraftSkill(写 skills 表 draft + 落盘 attachments)。
|
||||
// 草稿绝不进 skills/ 技能库(红线)。
|
||||
func (pa *PatternAPI) Draft(w http.ResponseWriter, r *http.Request, id string) {
|
||||
if pa.SkillStore == nil || pa.Generator == nil {
|
||||
respondError(w, 503, "skillgen 未装配(SkillStore/Generator 为空)")
|
||||
return
|
||||
}
|
||||
pat, err := pa.Store.GetPattern(id)
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
respondError(w, 404, "pattern not found: "+id)
|
||||
} else {
|
||||
respondError(w, 500, "get pattern: "+err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
attRoot := pa.AttachmentsDir
|
||||
if attRoot == "" {
|
||||
attRoot = skillgen.DefaultAttachmentsRoot()
|
||||
}
|
||||
sk, path, derr := skillgen.DraftSkill(pa.SkillStore, pa.Generator, pat, attRoot)
|
||||
if derr != nil {
|
||||
respondError(w, 400, "draft skill: "+derr.Error())
|
||||
return
|
||||
}
|
||||
respond(w, 200, map[string]interface{}{
|
||||
"skill": sk,
|
||||
"file": path,
|
||||
})
|
||||
}
|
||||
|
||||
// POST /api/v1/patterns/{id}/promote — 人工确认后 draft→active。
|
||||
func (pa *PatternAPI) Promote(w http.ResponseWriter, r *http.Request, id string) {
|
||||
if pa.SkillStore == nil {
|
||||
respondError(w, 503, "skillgen 未装配(SkillStore 为空)")
|
||||
return
|
||||
}
|
||||
if err := pa.SkillStore.Promote(id); err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
respondError(w, 404, "no skill draft for pattern: "+id)
|
||||
} else {
|
||||
respondError(w, 500, "promote skill: "+err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
sk, gerr := pa.SkillStore.Get(id)
|
||||
if gerr != nil {
|
||||
respondError(w, 500, "read skill after promote: "+gerr.Error())
|
||||
return
|
||||
}
|
||||
respond(w, 200, map[string]interface{}{"skill": sk})
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
// 织忆 MemoryWeave — L3 skill 草稿 API 路由测试(t_fcadee04)
|
||||
//
|
||||
// 覆盖端点:POST /api/v1/patterns/{id}/draft + POST /api/v1/patterns/{id}/promote
|
||||
// 共享同一临时 graph.db(pattern 在 graph_nodes、skill 在 skills 表同库),零网络/零 CGO。
|
||||
package routes
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/pattern"
|
||||
"github.com/xiaoxue/memoryweave/internal/skillgen"
|
||||
"github.com/xiaoxue/memoryweave/internal/storage"
|
||||
)
|
||||
|
||||
// newSkillgenTestAPI 构造共享同一 temp graph.db 的 PatternAPI(含 L3 装配)。
|
||||
func newSkillgenTestAPI(t *testing.T) (*PatternAPI, string) {
|
||||
t.Helper()
|
||||
dbDir := t.TempDir()
|
||||
graphPath := filepath.Join(dbDir, "graph.db")
|
||||
pstore := pattern.NewGraphPatternStore(graphPath)
|
||||
t.Cleanup(pstore.Close)
|
||||
sstore := skillgen.NewStore(graphPath)
|
||||
t.Cleanup(sstore.Close)
|
||||
attRoot := filepath.Join(t.TempDir(), "attachments")
|
||||
|
||||
api := NewPatternAPI(pstore, nil, func() storage.LanceDB { return nil })
|
||||
api.SkillStore = sstore
|
||||
api.Generator = &skillgen.FakeGenerator{Out: "## 适用场景\n重复处理"}
|
||||
api.AttachmentsDir = attRoot
|
||||
|
||||
// 种一个 conf=0.9 的 pattern 进 graph_nodes
|
||||
hi := pattern.Pattern{
|
||||
ID: "pat_tool_combo:curl+git+jq", Type: "tool_combo",
|
||||
Name: "tool_combo:curl+git+jq", Data: "curl+git+jq",
|
||||
Confidence: 0.9, Tools: []string{"curl", "git", "jq"},
|
||||
SourceTasks: []string{"m_a", "m_b", "m_c"},
|
||||
}
|
||||
if _, _, err := pstore.UpsertPatterns([]pattern.Pattern{hi}); err != nil {
|
||||
t.Fatalf("seed pattern: %v", err)
|
||||
}
|
||||
return api, attRoot
|
||||
}
|
||||
|
||||
// TestSkillgen_DraftRoute —— AC1 API 层:draft 端点 → 200 + skills 表 1 行 draft + 附件文件。
|
||||
func TestSkillgen_DraftRoute(t *testing.T) {
|
||||
api, attRoot := newSkillgenTestAPI(t)
|
||||
id := "pat_tool_combo:curl+git+jq"
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("POST", "/api/v1/patterns/"+id+"/draft", nil)
|
||||
api.Sub(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("draft 期望 200,实际 %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
// skills 表 1 行 draft
|
||||
if n, _ := api.SkillStore.Count("draft"); n != 1 {
|
||||
t.Fatalf("AC1 判据:draft 行数应 1,实际 %d", n)
|
||||
}
|
||||
sk, err := api.SkillStore.Get(id)
|
||||
if err != nil || sk.Status != "draft" {
|
||||
t.Fatalf("skill 应存在且 draft,实际 %v %+v", err, sk)
|
||||
}
|
||||
// 附件文件存在 + 含 [AUTO-DRAFT]
|
||||
path := filepath.Join(attRoot, skillgen.DraftSubDir("tool_combo:curl+git+jq"), "skill-draft.md")
|
||||
data, rerr := os.ReadFile(path)
|
||||
if rerr != nil {
|
||||
t.Fatalf("附件文件不存在 %s: %v", path, rerr)
|
||||
}
|
||||
if !strings.Contains(string(data), skillgen.AUTO_DRAFT_MARKER) {
|
||||
t.Fatalf("附件应含 [AUTO-DRAFT] 标记")
|
||||
}
|
||||
t.Logf("route draft 落盘: %s", path)
|
||||
}
|
||||
|
||||
// TestSkillgen_PromoteRoute —— AC3 API 层:promote 端点 → 200 + status active。
|
||||
func TestSkillgen_PromoteRoute(t *testing.T) {
|
||||
api, _ := newSkillgenTestAPI(t)
|
||||
id := "pat_tool_combo:curl+git+jq"
|
||||
// 先 draft
|
||||
dr := httptest.NewRecorder()
|
||||
api.Sub(dr, httptest.NewRequest("POST", "/api/v1/patterns/"+id+"/draft", nil))
|
||||
if dr.Code != http.StatusOK {
|
||||
t.Fatalf("前置 draft 应 200,实际 %d", dr.Code)
|
||||
}
|
||||
// promote
|
||||
pr := httptest.NewRecorder()
|
||||
api.Sub(pr, httptest.NewRequest("POST", "/api/v1/patterns/"+id+"/promote", nil))
|
||||
if pr.Code != http.StatusOK {
|
||||
t.Fatalf("promote 期望 200,实际 %d body=%s", pr.Code, pr.Body.String())
|
||||
}
|
||||
var resp struct {
|
||||
Skill struct {
|
||||
Status string `json:"status"`
|
||||
} `json:"skill"`
|
||||
}
|
||||
if err := json.Unmarshal(pr.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("promote 解析: %v", err)
|
||||
}
|
||||
if resp.Skill.Status != "active" {
|
||||
t.Fatalf("AC3 判据:promote 后 status 应 active,实际 %s", resp.Skill.Status)
|
||||
}
|
||||
// 库复核(AC3 判据:sqlite 查)
|
||||
if n, _ := api.SkillStore.Count("active"); n != 1 {
|
||||
t.Fatalf("AC3 判据:active 行数应 1,实际 %d", n)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSkillgen_DraftRoute_NotFound —— 不存在的 pattern → 404。
|
||||
func TestSkillgen_DraftRoute_NotFound(t *testing.T) {
|
||||
api, _ := newSkillgenTestAPI(t)
|
||||
rec := httptest.NewRecorder()
|
||||
api.Sub(rec, httptest.NewRequest("POST", "/api/v1/patterns/nope/draft", nil))
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("不存在 pattern 的 draft 应 404,实际 %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSkillgen_PromoteRoute_NoDraft —— 无草稿即 promote → 404。
|
||||
func TestSkillgen_PromoteRoute_NoDraft(t *testing.T) {
|
||||
api, _ := newSkillgenTestAPI(t)
|
||||
rec := httptest.NewRecorder()
|
||||
api.Sub(rec, httptest.NewRequest("POST", "/api/v1/patterns/pat_tool_combo:curl+git+jq/promote", nil))
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("无草稿 promote 应 404,实际 %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestSkillgen_SubPath —— 子路径解析单元(含 URL 编码 id)。
|
||||
func TestSkillgen_SubPath(t *testing.T) {
|
||||
id, action := patternSubPath("/api/v1/patterns/pat_tool_combo:curl+git+jq/promote")
|
||||
if id != "pat_tool_combo:curl+git+jq" || action != "promote" {
|
||||
t.Fatalf("解析失败 id=%q action=%q", id, action)
|
||||
}
|
||||
if _, a := patternSubPath("/api/v1/patterns"); a != "" {
|
||||
t.Fatalf("无子路径应 action 空")
|
||||
}
|
||||
if _, a := patternSubPath("/api/v1/patterns/detect"); a != "" {
|
||||
t.Fatalf("/patterns/detect 是精确路由,不应走 Sub")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/models"
|
||||
"github.com/xiaoxue/memoryweave/internal/pattern"
|
||||
"github.com/xiaoxue/memoryweave/internal/storage"
|
||||
)
|
||||
|
||||
// 织忆 — L2 模式 API 路由测试(t_d32e5f8a)
|
||||
// AC1: 空库 detect/list → 不报错(count=0)
|
||||
// AC2: 3 条同工具组合记忆 → detect 后 list 能查到 tool_combo pattern
|
||||
|
||||
// newPatternTestAPI 构造一个用临时 graph.db + 假 LanceDB 后端的 PatternAPI(无网络、无 CGO)。
|
||||
// 假后端只实现 PatternAPI 实际调用的 Scan(其余方法嵌 nil 接口,测试路径不会触达)。
|
||||
func newPatternTestAPI(t *testing.T, mems []models.MemoryRecord) *PatternAPI {
|
||||
t.Helper()
|
||||
store := pattern.NewGraphPatternStore(t.TempDir() + "/graph.db")
|
||||
t.Cleanup(store.Close)
|
||||
mlc := &patternScanLance{rows: mems}
|
||||
pemb := pattern.NewEmbedderProvider(&fakePatternEmbedder{})
|
||||
return NewPatternAPI(store, pattern.NewPatternProvider(store, pemb), func() storage.LanceDB { return mlc })
|
||||
}
|
||||
|
||||
// patternScanLance 覆写 Scan(PatternAPI.Detect 唯一用到的 LanceDB 方法);
|
||||
// 其余方法嵌 nil 接口 —— 本测试路径不会调用,触达即 panic(暴露误用)。
|
||||
type patternScanLance struct {
|
||||
storage.LanceDB
|
||||
rows []models.MemoryRecord
|
||||
}
|
||||
|
||||
func (f *patternScanLance) Scan(limit int, namespaceFilter string) ([]models.MemoryRecord, error) {
|
||||
if limit > 0 && len(f.rows) > limit {
|
||||
return f.rows[:limit], nil
|
||||
}
|
||||
return f.rows, nil
|
||||
}
|
||||
|
||||
// fakePatternEmbedder 确定性假向量(pattern.Provider 匹配测试用;注入测试走 storage 侧不走这里)。
|
||||
type fakePatternEmbedder struct{}
|
||||
|
||||
func (fakePatternEmbedder) EncodeSingle(text string) ([]float32, error) {
|
||||
v := make([]float32, 8)
|
||||
for i := 0; i < 8; i++ {
|
||||
v[i] = 0.1
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// TestPatterns_ListEmpty —— AC1:空库 list → 200 + count=0(不报错)。
|
||||
func TestPatterns_ListEmpty(t *testing.T) {
|
||||
api := newPatternTestAPI(t, nil)
|
||||
rec := httptest.NewRecorder()
|
||||
api.List(rec, httptest.NewRequest("GET", "/api/v1/patterns", nil))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("空库 list 期望 200,实际 %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var resp map[string]interface{}
|
||||
_ = json.Unmarshal(rec.Body.Bytes(), &resp)
|
||||
if int(resp["count"].(float64)) != 0 {
|
||||
t.Fatalf("空库 count 期望 0,实际 %v", resp["count"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestPatterns_DetectEmpty —— AC1:空库 detect → 200 + scanned=0/created=0(不报错)。
|
||||
func TestPatterns_DetectEmpty(t *testing.T) {
|
||||
api := newPatternTestAPI(t, nil)
|
||||
rec := httptest.NewRecorder()
|
||||
api.Detect(rec, httptest.NewRequest("POST", "/api/v1/patterns/detect", nil))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("空库 detect 期望 200,实际 %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var resp map[string]interface{}
|
||||
_ = json.Unmarshal(rec.Body.Bytes(), &resp)
|
||||
if int(resp["scanned"].(float64)) != 0 || int(resp["created"].(float64)) != 0 {
|
||||
t.Fatalf("空库 detect 期望 0/0,实际 %v/%v", resp["scanned"], resp["created"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestPatterns_DetectToolCombo —— AC2:3 条同工具组合蒸馏记忆 → detect 产出 1 个 tool_combo,
|
||||
// 且 list 能查到(sqlite graph_nodes 判据)。
|
||||
func TestPatterns_DetectToolCombo(t *testing.T) {
|
||||
mems := make([]models.MemoryRecord, 0, 3)
|
||||
for i, id := range []string{"pc_a", "pc_b", "pc_c"} {
|
||||
mems = append(mems, models.MemoryRecord{
|
||||
ID: id,
|
||||
Content: "用 jq git curl 处理第" + string(rune('一'+i)) + "项",
|
||||
Category: "distilled",
|
||||
})
|
||||
}
|
||||
api := newPatternTestAPI(t, mems)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
api.Detect(rec, httptest.NewRequest("POST", "/api/v1/patterns/detect", nil))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("detect 期望 200,实际 %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var dresp map[string]interface{}
|
||||
_ = json.Unmarshal(rec.Body.Bytes(), &dresp)
|
||||
if int(dresp["detected"].(float64)) < 1 {
|
||||
t.Fatalf("3 条同组合应检出 ≥1 个 pattern,实际 detected=%v", dresp["detected"])
|
||||
}
|
||||
// 用 list 再核一遍 sqlite 判据:确有 tool_combo 行
|
||||
lrec := httptest.NewRecorder()
|
||||
api.List(lrec, httptest.NewRequest("GET", "/api/v1/patterns", nil))
|
||||
var lresp struct {
|
||||
Count int `json:"count"`
|
||||
Patterns []struct {
|
||||
Type string `json:"type"`
|
||||
Name string `json:"name"`
|
||||
} `json:"patterns"`
|
||||
}
|
||||
if err := json.Unmarshal(lrec.Body.Bytes(), &lresp); err != nil {
|
||||
t.Fatalf("list 解析: %v (body=%s)", err, lrec.Body.String())
|
||||
}
|
||||
if lresp.Count < 1 {
|
||||
t.Fatalf("AC2 判据:detect 后 list count 应 ≥1,实际 %d (detected=%v)", lresp.Count, dresp["detected"])
|
||||
}
|
||||
var foundToolCombo bool
|
||||
for _, p := range lresp.Patterns {
|
||||
if p.Type == "tool_combo" {
|
||||
foundToolCombo = true
|
||||
}
|
||||
}
|
||||
if !foundToolCombo {
|
||||
t.Fatalf("AC2 判据:list 应含 tool_combo pattern,实际 %d 条均非 tool_combo", lresp.Count)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
// 织忆 MemoryWeave — P3 Peer Representation API(t_f8fc97e6,设计 §6.1)
|
||||
//
|
||||
// 端点:
|
||||
//
|
||||
// POST /api/v1/peer/{id}/refresh 手动刷新某实体的四层推理画像(显式触发)
|
||||
// GET /api/v1/peer/{id}/explain 解释为何这样理解该实体(可审计:画像 + 来源记忆)
|
||||
// POST /api/v1/recall/peer?peer_id=… 召回某 peer 的推理画像(env 门控 ZHIYI_PEER_RECALL)
|
||||
//
|
||||
// 设计约束(与 L2 pattern / L3 skillgen 同源):
|
||||
//
|
||||
// · refresh/explain 是显式 API,不挂 cron ⇒ 默认零行为变化。
|
||||
// · 召回注入走独立端点 + env 门控 ZHIYI_PEER_RECALL,默认 0 ⇒ 主召回管线逐条不变(AC2)。
|
||||
// · peers 表在 graph.db(短命 modernc),不碰 state.db。
|
||||
package routes
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/governance"
|
||||
"github.com/xiaoxue/memoryweave/internal/models"
|
||||
"github.com/xiaoxue/memoryweave/internal/peer"
|
||||
"github.com/xiaoxue/memoryweave/internal/storage"
|
||||
)
|
||||
|
||||
// PeerAPI P3 peer 表示端点。
|
||||
type PeerAPI struct {
|
||||
Store *peer.Store
|
||||
Reasoner peer.Reasoner
|
||||
LDB func() storage.LanceDB // 扫 L1 记忆(explicit 层来源)
|
||||
GraphStore governance.GraphStore // 图谱上下文(推理输入)
|
||||
}
|
||||
|
||||
// NewPeerAPI 构造。
|
||||
func NewPeerAPI(store *peer.Store, reasoner peer.Reasoner, ldb func() storage.LanceDB, g governance.GraphStore) *PeerAPI {
|
||||
return &PeerAPI{Store: store, Reasoner: reasoner, LDB: ldb, GraphStore: g}
|
||||
}
|
||||
|
||||
// peerSubPath 解析 /api/v1/peer/{id}/{action} 子路径。
|
||||
func peerSubPath(path string) (id, action string) {
|
||||
const prefix = "/api/v1/peer/"
|
||||
if !strings.HasPrefix(path, prefix) {
|
||||
return "", ""
|
||||
}
|
||||
rest := strings.TrimPrefix(path, prefix) // <id>/refresh 或 <id>/explain
|
||||
parts := strings.Split(rest, "/")
|
||||
if len(parts) != 2 || parts[0] == "" {
|
||||
return "", ""
|
||||
}
|
||||
dec, err := url.PathUnescape(parts[0])
|
||||
if err != nil {
|
||||
return "", ""
|
||||
}
|
||||
return dec, parts[1]
|
||||
}
|
||||
|
||||
// Sub 分发 /api/v1/peer/{id}/refresh 与 /api/v1/peer/{id}/explain。
|
||||
func (pa *PeerAPI) Sub(w http.ResponseWriter, r *http.Request) {
|
||||
id, action := peerSubPath(r.URL.Path)
|
||||
if id == "" {
|
||||
respondError(w, 404, "peer id required")
|
||||
return
|
||||
}
|
||||
switch action {
|
||||
case "refresh":
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "POST only", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
pa.Refresh(w, r, id)
|
||||
case "explain":
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "GET only", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
pa.Explain(w, r, id)
|
||||
default:
|
||||
respondError(w, 404, "unknown action: "+action)
|
||||
}
|
||||
}
|
||||
|
||||
// RefreshAsync 异步刷新某实体的四层画像(推理不阻塞主流程,AC4)。
|
||||
// 返回一个 done channel,调用方可不等待(非阻塞);推理在后台 goroutine 完成。
|
||||
// 任何错误只记日志,不影响调用方。
|
||||
func (pa *PeerAPI) RefreshAsync(id, namespace string) chan error {
|
||||
done := make(chan error, 1)
|
||||
if pa == nil || pa.Store == nil || pa.Reasoner == nil {
|
||||
done <- fmt.Errorf("peer 未装配")
|
||||
return done
|
||||
}
|
||||
go func() {
|
||||
done <- pa.refresh(id, namespace, 2000)
|
||||
}()
|
||||
return done
|
||||
}
|
||||
|
||||
// RefreshFromContent 提交新记忆后异步刷新内容里出现的已知实体(设计「新记忆进入 → 不阻塞主流程
|
||||
// → 更新该 peer 表示」)。匹配:content 含某 peer_id 子串即触发。全部 goroutine 内执行,立即返回。
|
||||
// 由 server.go 在 commit 处理器里以 ZHIYI_PEER_RECALL=1 门控调用;默认关 ⇒ 不触发。
|
||||
func (pa *PeerAPI) RefreshFromContent(content, namespace string) {
|
||||
if pa == nil || pa.Store == nil || content == "" {
|
||||
return
|
||||
}
|
||||
peers, err := pa.Store.List(200)
|
||||
if err != nil || len(peers) == 0 {
|
||||
return
|
||||
}
|
||||
for _, p := range peers {
|
||||
if p.PeerID != "" && strings.Contains(content, p.PeerID) {
|
||||
go pa.refresh(p.PeerID, namespace, 2000)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// refresh 实际刷新编排(同步执行体;由 RefreshAsync / RefreshFromContent 包 goroutine)。
|
||||
func (pa *PeerAPI) refresh(id, namespace string, limit int) error {
|
||||
explicit, _, scanErr := pa.collectExplicit(id, namespace, limit)
|
||||
if scanErr != nil {
|
||||
return scanErr
|
||||
}
|
||||
graphCtx := pa.collectGraphContext(id)
|
||||
if _, err := peer.BuildPeer(pa.Store, pa.Reasoner, id, explicit.facts, explicit.prefs, explicit.skills, graphCtx); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Refresh POST /api/v1/peer/{id}/refresh — 扫 L1 记忆 + 图谱上下文 → 四层推理 → 写 peers 表。
|
||||
// body 可选 {"namespace": "...", "limit": N}(namespace 空 = 全库)。
|
||||
func (pa *PeerAPI) Refresh(w http.ResponseWriter, r *http.Request, id string) {
|
||||
if pa.Store == nil || pa.Reasoner == nil {
|
||||
respondError(w, 503, "peer 未装配(Store/Reasoner 为空)")
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Namespace string `json:"namespace"`
|
||||
Limit int `json:"limit"`
|
||||
}
|
||||
if r.Body != nil {
|
||||
_ = json.NewDecoder(r.Body).Decode(&req)
|
||||
}
|
||||
if req.Limit <= 0 {
|
||||
req.Limit = 2000
|
||||
}
|
||||
// 1. 扫 L1 记忆(LanceDB),提取 explicit 层
|
||||
explicit, matched, scanErr := pa.collectExplicit(id, req.Namespace, req.Limit)
|
||||
if scanErr != nil {
|
||||
respondError(w, 500, "scan memories: "+scanErr.Error())
|
||||
return
|
||||
}
|
||||
// 2. 图谱上下文(实体 1 跳邻居名)
|
||||
graphCtx := pa.collectGraphContext(id)
|
||||
// 3. 四层推理 + 写库
|
||||
p, perr := peer.BuildPeer(pa.Store, pa.Reasoner, id, explicit.facts, explicit.prefs, explicit.skills, graphCtx)
|
||||
if perr != nil {
|
||||
respondError(w, 400, "build peer: "+perr.Error())
|
||||
return
|
||||
}
|
||||
respond(w, 200, map[string]interface{}{
|
||||
"peer": p,
|
||||
"matched": matched,
|
||||
"scanned": req.Limit,
|
||||
"graph_ctx": graphCtx,
|
||||
"has_reason": len(p.InferredTraits) > 0 || len(p.InferredGoals) > 0 || p.HypothesizedContext != "",
|
||||
})
|
||||
}
|
||||
|
||||
// Explain GET /api/v1/peer/{id}/explain — 可审计解释:画像 + 来源记忆。
|
||||
func (pa *PeerAPI) Explain(w http.ResponseWriter, r *http.Request, id string) {
|
||||
if pa.Store == nil {
|
||||
respondError(w, 503, "peer 未装配(Store 为空)")
|
||||
return
|
||||
}
|
||||
p, err := pa.Store.Get(id)
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
respondError(w, 404, "peer not found: "+id+"(先 POST /peer/{id}/refresh 生成画像)")
|
||||
} else {
|
||||
respondError(w, 500, "get peer: "+err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
// 来源记忆:扫 L1 里含该实体的记忆(仅读,不改库)
|
||||
src := []string{}
|
||||
if pa.LDB != nil {
|
||||
if ldb := pa.LDB(); ldb != nil {
|
||||
if recs, serr := ldb.Scan(2000, ""); serr == nil {
|
||||
for _, m := range recs {
|
||||
if strings.Contains(m.Content, id) {
|
||||
src = append(src, m.Content)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
respond(w, 200, map[string]interface{}{"peer": p, "source_memories": src})
|
||||
}
|
||||
|
||||
// RecallPeer POST /api/v1/recall/peer?peer_id=… — 召回某 peer 的四层推理画像。
|
||||
// env 门控 ZHIYI_PEER_RECALL:默认 0 → 404(零变化);=1 → 返回画像 JSON(AC3 判据)。
|
||||
func (pa *PeerAPI) RecallPeer(w http.ResponseWriter, r *http.Request) {
|
||||
if !peerRecallEnabled() {
|
||||
respondError(w, 404, "peer recall 默认关(ZHIYI_PEER_RECALL 未设/≠1)")
|
||||
return
|
||||
}
|
||||
pid := r.URL.Query().Get("peer_id")
|
||||
if pid == "" {
|
||||
respondError(w, 400, "peer_id required")
|
||||
return
|
||||
}
|
||||
if pa.Store == nil {
|
||||
respondError(w, 503, "peer 未装配(Store 为空)")
|
||||
return
|
||||
}
|
||||
p, err := pa.Store.Get(pid)
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
respondError(w, 404, "peer not found: "+pid)
|
||||
} else {
|
||||
respondError(w, 500, "get peer: "+err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
respond(w, 200, map[string]interface{}{
|
||||
"peer_id": p.PeerID,
|
||||
"portrait": map[string]interface{}{
|
||||
"explicit": map[string]interface{}{"facts": p.Facts, "preferences": p.Preferences, "skills": p.Skills},
|
||||
"deductive": map[string]interface{}{"traits": p.InferredTraits, "goals": p.InferredGoals},
|
||||
"inductive": map[string]interface{}{"patterns": p.Patterns},
|
||||
"abductive": map[string]interface{}{"hypothesized_context": p.HypothesizedContext},
|
||||
},
|
||||
"updated_at": p.UpdatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
// explicitResult explicit 层收集结果。
|
||||
type explicitResult struct {
|
||||
facts, prefs, skills []string
|
||||
}
|
||||
|
||||
// collectExplicit 扫 L1 记忆并提取 explicit 层。namespace 空 = 全库。
|
||||
func (pa *PeerAPI) collectExplicit(id, namespace string, limit int) (explicitResult, int, error) {
|
||||
var res explicitResult
|
||||
if pa.LDB == nil {
|
||||
return res, 0, nil
|
||||
}
|
||||
ldb := pa.LDB()
|
||||
if ldb == nil {
|
||||
return res, 0, nil
|
||||
}
|
||||
recs, err := ldb.Scan(limit, namespace)
|
||||
if err != nil {
|
||||
return res, 0, err
|
||||
}
|
||||
facts, prefs, skills, matched := peer.CollectFacts(recs, id)
|
||||
return explicitResult{facts: facts, prefs: prefs, skills: skills}, matched, nil
|
||||
}
|
||||
|
||||
// collectGraphContext 取实体图谱 1 跳邻居名作为推理上下文(读图,只读不改)。
|
||||
func (pa *PeerAPI) collectGraphContext(id string) []string {
|
||||
if pa.GraphStore == nil {
|
||||
return nil
|
||||
}
|
||||
paths, err := pa.GraphStore.Navigate(id, 1, "", nil)
|
||||
if err != nil || len(paths) == 0 {
|
||||
return nil
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
var out []string
|
||||
for _, p := range paths {
|
||||
for _, k := range []string{"to", "target"} {
|
||||
if v, ok := p[k].(string); ok && v != "" && !seen[v] && v != id {
|
||||
seen[v] = true
|
||||
out = append(out, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(out) > 10 {
|
||||
out = out[:10]
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// peerRecallEnabled 每次调用读 env(默认关,零行为变化)。
|
||||
func peerRecallEnabled() bool {
|
||||
switch strings.ToLower(os.Getenv("ZHIYI_PEER_RECALL")) {
|
||||
case "1", "true", "on":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// GetRecallResults 供 storage.PeerRecallProvider 装配(server.go 在 ZHIYI_PEER_RECALL=1
|
||||
// 时注册)。query 命中某实体 → 返回该 peer 的四层画像(Category="peer")。
|
||||
// 命中判定:query 里含 peer_id 子串(大小写不敏感);取最多 topK 个。无命中 → 空。
|
||||
func (pa *PeerAPI) GetRecallResults(query, namespace string, topK int) []models.RecallResult {
|
||||
if pa == nil || pa.Store == nil || topK <= 0 {
|
||||
return nil
|
||||
}
|
||||
peers, err := pa.Store.List(200)
|
||||
if err != nil || len(peers) == 0 {
|
||||
return nil
|
||||
}
|
||||
q := strings.ToLower(strings.TrimSpace(query))
|
||||
var out []models.RecallResult
|
||||
for _, p := range peers {
|
||||
if p.PeerID != "" && q != "" && strings.Contains(q, strings.ToLower(p.PeerID)) {
|
||||
content := "peer 画像: " + p.PeerID +
|
||||
" | 事实: " + strings.Join(p.Facts, "; ") +
|
||||
" | 偏好: " + strings.Join(p.Preferences, "; ") +
|
||||
" | 技能: " + strings.Join(p.Skills, "; ") +
|
||||
" | 演绎特质: " + strings.Join(p.InferredTraits, "; ") +
|
||||
" | 演绎目标: " + strings.Join(p.InferredGoals, "; ") +
|
||||
" | 归纳模式: " + strings.Join(p.Patterns, "; ") +
|
||||
" | 最佳解释: " + p.HypothesizedContext
|
||||
out = append(out, models.RecallResult{
|
||||
ID: "peer:" + p.PeerID,
|
||||
Content: content,
|
||||
Category: "peer",
|
||||
Score: 1.0,
|
||||
Namespace: namespace,
|
||||
Source: "peer_representation",
|
||||
})
|
||||
if len(out) >= topK {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
// 织忆 MemoryWeave — P3 Peer Representation API 路由测试(t_f8fc97e6)
|
||||
//
|
||||
// 覆盖端点:POST /api/v1/peer/{id}/refresh + GET /api/v1/peer/{id}/explain
|
||||
// - POST /api/v1/recall/peer(env 门控)+ storage.PeerRecallProvider 注入。
|
||||
//
|
||||
// 共享同一临时 graph.db(peers 表),零网络 / CGO / 真模型。
|
||||
package routes
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/models"
|
||||
"github.com/xiaoxue/memoryweave/internal/peer"
|
||||
"github.com/xiaoxue/memoryweave/internal/storage"
|
||||
)
|
||||
|
||||
// peerScanLance 覆写 Scan(PeerAPI.Refresh/Explain 唯一用到的 LanceDB 方法);
|
||||
// 其余方法嵌 nil 接口 —— 本测试路径不会调用,触达即 panic(暴露误用)。
|
||||
type peerScanLance struct {
|
||||
storage.LanceDB
|
||||
rows []models.MemoryRecord
|
||||
}
|
||||
|
||||
func (f *peerScanLance) Scan(limit int, namespaceFilter string) ([]models.MemoryRecord, error) {
|
||||
if limit > 0 && len(f.rows) > limit {
|
||||
return f.rows[:limit], nil
|
||||
}
|
||||
return f.rows, nil
|
||||
}
|
||||
|
||||
// newPeerTestAPI 构造共享同一 temp graph.db 的 PeerAPI。
|
||||
// GraphStore 传 nil(collectGraphContext 处理 nil ⇒ 无图上下文,不炸)。
|
||||
func newPeerTestAPI(t *testing.T, mems []models.MemoryRecord) *PeerAPI {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
store := peer.NewStore(filepath.Join(dir, "graph.db"))
|
||||
t.Cleanup(store.Close)
|
||||
mlc := &peerScanLance{rows: mems}
|
||||
return NewPeerAPI(store, &peer.FakeReasoner{}, func() storage.LanceDB { return mlc }, nil)
|
||||
}
|
||||
|
||||
// fiveMems 造 5 条关于「牧尘」的 L1 记忆(AC1 输入构造)。
|
||||
func fiveMems() []models.MemoryRecord {
|
||||
return []models.MemoryRecord{
|
||||
{Content: "牧尘选择 Docker 部署"},
|
||||
{Content: "牧尘偏好 SysV 风格"},
|
||||
{Content: "牧尘擅长 Python"},
|
||||
{Content: "牧尘厌恶 systemd"},
|
||||
{Content: "牧尘使用 jq 处理配置"},
|
||||
}
|
||||
}
|
||||
|
||||
// TestPeer_RefreshRoute —— AC1 API 层:5 条记忆 → refresh → peers 表 1 行四层非空。
|
||||
func TestPeer_RefreshRoute(t *testing.T) {
|
||||
api := newPeerTestAPI(t, fiveMems())
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("POST", "/api/v1/peer/%E7%89%A7%E5%B0%98/refresh", nil) // 牧尘
|
||||
api.Sub(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("refresh 期望 200,实际 %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var resp struct {
|
||||
Peer peer.Peer `json:"peer"`
|
||||
Matched int `json:"matched"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("refresh 解析: %v", err)
|
||||
}
|
||||
if resp.Matched != 5 {
|
||||
t.Errorf("AC1:matched=%d 期望 5", resp.Matched)
|
||||
}
|
||||
if resp.Peer.PeerID != "牧尘" {
|
||||
t.Errorf("peer_id=%q 期望 牧尘", resp.Peer.PeerID)
|
||||
}
|
||||
// 四层非空(AC1 判据)
|
||||
if len(resp.Peer.InferredTraits) == 0 {
|
||||
t.Error("inferred_traits 空")
|
||||
}
|
||||
if len(resp.Peer.InferredGoals) == 0 {
|
||||
t.Error("inferred_goals 空")
|
||||
}
|
||||
if len(resp.Peer.Patterns) == 0 {
|
||||
t.Error("patterns 空")
|
||||
}
|
||||
if resp.Peer.HypothesizedContext == "" {
|
||||
t.Error("hypothesized_context 空")
|
||||
}
|
||||
// peers 表行数(AC1:sqlite 查)
|
||||
if n, _ := api.Store.Count(); n != 1 {
|
||||
t.Errorf("AC1:peers 行数应 1,实际 %d", n)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPeer_ExplainRoute —— GET explain → 200 + 画像 + 来源记忆。
|
||||
func TestPeer_ExplainRoute(t *testing.T) {
|
||||
api := newPeerTestAPI(t, fiveMems())
|
||||
// 先 refresh 种画像
|
||||
rec := httptest.NewRecorder()
|
||||
api.Sub(rec, httptest.NewRequest("POST", "/api/v1/peer/%E7%89%A7%E5%B0%98/refresh", nil))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("前置 refresh 应 200,实际 %d", rec.Code)
|
||||
}
|
||||
// explain
|
||||
er := httptest.NewRecorder()
|
||||
api.Sub(er, httptest.NewRequest("GET", "/api/v1/peer/%E7%89%A7%E5%B0%98/explain", nil))
|
||||
if er.Code != http.StatusOK {
|
||||
t.Fatalf("explain 期望 200,实际 %d body=%s", er.Code, er.Body.String())
|
||||
}
|
||||
var resp struct {
|
||||
Peer peer.Peer `json:"peer"`
|
||||
SourceMemories []string `json:"source_memories"`
|
||||
}
|
||||
if err := json.Unmarshal(er.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("explain 解析: %v", err)
|
||||
}
|
||||
if len(resp.SourceMemories) != 5 {
|
||||
t.Errorf("source_memories=%d 期望 5(可审计:画像有来源)", len(resp.SourceMemories))
|
||||
}
|
||||
}
|
||||
|
||||
// TestPeer_Explain_NotFound —— 未 refresh 直接 explain → 404。
|
||||
func TestPeer_Explain_NotFound(t *testing.T) {
|
||||
api := newPeerTestAPI(t, fiveMems())
|
||||
rec := httptest.NewRecorder()
|
||||
api.Sub(rec, httptest.NewRequest("GET", "/api/v1/peer/%E7%89%A7%E5%B0%98/explain", nil))
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("无画像 explain 应 404,实际 %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPeer_RecallPeer_DefaultOff —— AC3:ZHIYI_PEER_RECALL=0(默认)→ recall/peer 404 零变化。
|
||||
func TestPeer_RecallPeer_DefaultOff(t *testing.T) {
|
||||
t.Setenv("ZHIYI_PEER_RECALL", "0")
|
||||
api := newPeerTestAPI(t, fiveMems())
|
||||
rec := httptest.NewRecorder()
|
||||
api.RecallPeer(rec, httptest.NewRequest("POST", "/api/v1/recall/peer?peer_id=牧尘", nil))
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("默认关 recall/peer 应 404,实际 %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestPeer_RecallPeer_Enabled —— AC3:ZHIYI_PEER_RECALL=1 → 返回四层画像 JSON。
|
||||
func TestPeer_RecallPeer_Enabled(t *testing.T) {
|
||||
t.Setenv("ZHIYI_PEER_RECALL", "1")
|
||||
api := newPeerTestAPI(t, fiveMems())
|
||||
// 先 refresh 种画像
|
||||
rrec := httptest.NewRecorder()
|
||||
api.Sub(rrec, httptest.NewRequest("POST", "/api/v1/peer/%E7%89%A7%E5%B0%98/refresh", nil))
|
||||
if rrec.Code != http.StatusOK {
|
||||
t.Fatalf("前置 refresh 应 200,实际 %d", rrec.Code)
|
||||
}
|
||||
// recall/peer
|
||||
rec := httptest.NewRecorder()
|
||||
api.RecallPeer(rec, httptest.NewRequest("POST", "/api/v1/recall/peer?peer_id=牧尘", nil))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("recall/peer 期望 200,实际 %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var resp struct {
|
||||
Portrait map[string]interface{} `json:"portrait"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("recall/peer 解析: %v", err)
|
||||
}
|
||||
// 四层各有内容(AC3 判据)
|
||||
for _, layer := range []string{"explicit", "deductive", "inductive", "abductive"} {
|
||||
v, ok := resp.Portrait[layer]
|
||||
if !ok {
|
||||
t.Errorf("portrait 缺 %s 层: %v", layer, resp.Portrait)
|
||||
continue
|
||||
}
|
||||
s, _ := json.Marshal(v)
|
||||
if string(s) == "{}" || strings.Contains(string(s), "[]\"") {
|
||||
t.Errorf("portrait.%s 层空: %s", layer, s)
|
||||
}
|
||||
}
|
||||
t.Logf("AC3 recall/peer 画像: %s", rec.Body.String())
|
||||
}
|
||||
|
||||
// TestPeer_GetRecallResults —— storage.PeerRecallProvider 注入:query 含实体 → 返回画像条目。
|
||||
func TestPeer_GetRecallResults(t *testing.T) {
|
||||
api := newPeerTestAPI(t, fiveMems())
|
||||
// 种画像
|
||||
api.Sub(httptest.NewRecorder(),
|
||||
httptest.NewRequest("POST", "/api/v1/peer/%E7%89%A7%E5%B0%98/refresh", nil))
|
||||
res := api.GetRecallResults("牧尘怎么部署", "", 1)
|
||||
if len(res) != 1 {
|
||||
t.Fatalf("GetRecallResults 应返回 1 条,实际 %d", len(res))
|
||||
}
|
||||
if res[0].Category != "peer" || res[0].ID != "peer:牧尘" {
|
||||
t.Errorf("返回条目 Category=%q ID=%q 期望 peer / peer:牧尘", res[0].Category, res[0].ID)
|
||||
}
|
||||
if !strings.Contains(res[0].Content, "演绎特质") || !strings.Contains(res[0].Content, "最佳解释") {
|
||||
t.Errorf("画像内容缺四层: %s", res[0].Content)
|
||||
}
|
||||
// 无命中 → 空
|
||||
if got := api.GetRecallResults("如何优化 Redis", "", 1); len(got) != 0 {
|
||||
t.Errorf("不相关 query 应空,实际 %d", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
// TestPeer_SubPath —— 子路径解析单元。
|
||||
func TestPeer_SubPath(t *testing.T) {
|
||||
id, action := peerSubPath("/api/v1/peer/%E7%89%A7%E5%B0%98/refresh")
|
||||
if id != "牧尘" || action != "refresh" {
|
||||
t.Fatalf("解析失败 id=%q action=%q", id, action)
|
||||
}
|
||||
if _, a := peerSubPath("/api/v1/peer"); a != "" {
|
||||
t.Fatalf("无子路径应 action 空")
|
||||
}
|
||||
}
|
||||
|
||||
// blockingReasoner 会阻塞的推理器(测非阻塞:RefreshAsync 不等它完成)。
|
||||
type blockingReasoner struct{ release chan struct{} }
|
||||
|
||||
func (b *blockingReasoner) Reason(facts, prefs, skills, graphCtx []string) (*peer.ReasoningOutput, error) {
|
||||
<-b.release
|
||||
return &peer.ReasoningOutput{InferredTraits: []string{"T"}}, nil
|
||||
}
|
||||
|
||||
// TestPeer_RefreshAsync_NonBlocking —— AC4:推理不阻塞主流程。
|
||||
// RefreshAsync 立即返回(后台 goroutine 推理),即使推理器被阻塞也绝不等它。
|
||||
func TestPeer_RefreshAsync_NonBlocking(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
store := peer.NewStore(filepath.Join(dir, "graph.db"))
|
||||
t.Cleanup(store.Close)
|
||||
br := &blockingReasoner{release: make(chan struct{})}
|
||||
mlc := &peerScanLance{rows: fiveMems()}
|
||||
api := NewPeerAPI(store, br, func() storage.LanceDB { return mlc }, nil)
|
||||
|
||||
done := api.RefreshAsync("牧尘", "")
|
||||
select {
|
||||
case <-done:
|
||||
t.Fatal("RefreshAsync 应在推理器仍阻塞时立即返回(非阻塞),却等到了结果")
|
||||
case <-time.After(200 * time.Millisecond):
|
||||
// 非阻塞 ✓:200ms 内未等推理完成
|
||||
}
|
||||
// 释放推理器,后台完成
|
||||
close(br.release)
|
||||
select {
|
||||
case <-done:
|
||||
// 后台完成
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("释放后后台推理未完成")
|
||||
}
|
||||
// 画像已落库
|
||||
if n, _ := store.Count(); n != 1 {
|
||||
t.Errorf("非阻塞刷新后 peers 行数应 1,实际 %d", n)
|
||||
}
|
||||
}
|
||||
@@ -10,21 +10,22 @@
|
||||
// 结果追加到 ~/.hermes/logs/zhiyi-commit-provenance/YYYY-MM-DD.jsonl。
|
||||
//
|
||||
// 判定降级(AC2 重定义,t_dc412532 阶段2 设计输入):
|
||||
// (a) metadata 有 source_uri + quote + quote_sha256 → 复算 sha256(quote) 比对;
|
||||
// 不等 observable=false, reason=hash_mismatch
|
||||
// (b) 无上述字段但 source=="session-compress" 且 session_id 存在 →
|
||||
// 去 ~/.hermes/state.db(只读)取该 session 消息文本做回证。
|
||||
// 观察期实测(n=205, 24h):true=1 / false=8 / unknown=193;全部 8 条 false
|
||||
// 均来自 session-compress —— 判据「前 60 字逐字命中 / LCS≥60」对「摘要/派生内容」
|
||||
// 结构性必 false(摘要不会逐字出现在原文里)。AC2 修正:
|
||||
// * 原文不可得(session 已压缩/清除)→ observable=unknown, reason=source_not_available
|
||||
// (空原文 = 无法证伪,不是证伪失败 —— 旧逻辑误标 false/not_in_source)
|
||||
// * 前 60 字逐字命中 或 LCS≥60 → observable=true(引用片段可溯源)
|
||||
// * 其余(摘要低 LCS,属正常改写)→ observable=unknown, reason=derived_low_lcs
|
||||
// (对派生内容无法证伪 —— 摘要重述≠不可溯源)
|
||||
// 同时把实测数值 lcs_len / prefix_hit60 写进 jsonl(AC1 先量后判),
|
||||
// 供阶段3 转硬闸时按分布定档。
|
||||
// (c) 其他 source → observable=unknown, reason=no_derivation(不要瞎猜成 false)
|
||||
//
|
||||
// (a) metadata 有 source_uri + quote + quote_sha256 → 复算 sha256(quote) 比对;
|
||||
// 不等 observable=false, reason=hash_mismatch
|
||||
// (b) 无上述字段但 source=="session-compress" 且 session_id 存在 →
|
||||
// 去 ~/.hermes/state.db(只读)取该 session 消息文本做回证。
|
||||
// 观察期实测(n=205, 24h):true=1 / false=8 / unknown=193;全部 8 条 false
|
||||
// 均来自 session-compress —— 判据「前 60 字逐字命中 / LCS≥60」对「摘要/派生内容」
|
||||
// 结构性必 false(摘要不会逐字出现在原文里)。AC2 修正:
|
||||
// * 原文不可得(session 已压缩/清除)→ observable=unknown, reason=source_not_available
|
||||
// (空原文 = 无法证伪,不是证伪失败 —— 旧逻辑误标 false/not_in_source)
|
||||
// * 前 60 字逐字命中 或 LCS≥60 → observable=true(引用片段可溯源)
|
||||
// * 其余(摘要低 LCS,属正常改写)→ observable=unknown, reason=derived_low_lcs
|
||||
// (对派生内容无法证伪 —— 摘要重述≠不可溯源)
|
||||
// 同时把实测数值 lcs_len / prefix_hit60 写进 jsonl(AC1 先量后判),
|
||||
// 供阶段3 转硬闸时按分布定档。
|
||||
// (c) 其他 source → observable=unknown, reason=no_derivation(不要瞎猜成 false)
|
||||
package routes
|
||||
|
||||
import (
|
||||
@@ -162,9 +163,10 @@ func observeViaSession(content, sessionID string) (string, string, int, bool) {
|
||||
}
|
||||
|
||||
// provenanceMeasure 计算 content 相对 srcText 的可溯源实测指标:
|
||||
// prefixHit60 = content 前 60 字在 srcText 中逐字命中
|
||||
// lcsLen = content 与 srcText 的最长公共子串长度
|
||||
// match = prefixHit60 || lcsLen >= minCommonRun
|
||||
//
|
||||
// prefixHit60 = content 前 60 字在 srcText 中逐字命中
|
||||
// lcsLen = content 与 srcText 的最长公共子串长度
|
||||
// match = prefixHit60 || lcsLen >= minCommonRun
|
||||
func provenanceMeasure(content, srcText string) (match bool, lcsLen int, prefixHit60 bool) {
|
||||
if content == "" || srcText == "" {
|
||||
return false, 0, false
|
||||
@@ -233,4 +235,4 @@ func appendProvenanceLog(line map[string]interface{}) {
|
||||
}
|
||||
defer f.Close()
|
||||
fmt.Fprintf(f, "%s\n", data)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,4 +46,4 @@ func TestDecideQuoteHash(t *testing.T) {
|
||||
if observable != "false" || reason != "hash_mismatch" {
|
||||
t.Fatalf("expect false/hash_mismatch got %s/%s", observable, reason)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package routes
|
||||
|
||||
// 2026-10-26(P1-1):supersede / 版本字段必须真的出现在 /recall 响应里。
|
||||
// 用同包 fakeLanceDB 构造一条「已被取代 + 有效期已过 + 版本 2」的记录:
|
||||
// - 这是「写侧有、读侧看不见」的复发点(t_4c810e02「加列不接 IPC=静默 no-op」同款坑);
|
||||
// - 判据只看 JSON 响应键值,不看结构体注释。
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/models"
|
||||
)
|
||||
|
||||
func TestRecall_SupersedeAndValidityFieldsExposed(t *testing.T) {
|
||||
db := &fakeLanceDB{searchResults: []models.MemoryRecord{
|
||||
{
|
||||
ID: "mem_old_fact",
|
||||
Content: "织忆默认 stale 阈值是 720 小时(旧事实)",
|
||||
Category: "distilled",
|
||||
Version: 2,
|
||||
ValidFrom: "2026-10-26T10:00:00+08:00",
|
||||
ValidTo: "2026-10-26T11:00:00+08:00",
|
||||
SupersededBy: []string{"mem_new_fact"},
|
||||
},
|
||||
{ID: "mem_fresh", Content: "织忆默认 stale 阈值是 720 小时(现行事实)", Category: "distilled"},
|
||||
}}
|
||||
code, m, body := recallBody(t, db, `{"query":"stale 阈值多少小时","limit":5,"namespace":"hermes-main"}`)
|
||||
if code != 200 {
|
||||
t.Fatalf("expected 200, got %d; body=%s", code, body)
|
||||
}
|
||||
results, _ := m["results"].([]interface{})
|
||||
if len(results) == 0 {
|
||||
t.Fatalf("无结果,无法验证字段:%s", body)
|
||||
}
|
||||
var found map[string]interface{}
|
||||
for _, raw := range results {
|
||||
r, _ := raw.(map[string]interface{})
|
||||
if r["id"] == "mem_old_fact" {
|
||||
found = r
|
||||
break
|
||||
}
|
||||
}
|
||||
if found == nil {
|
||||
t.Fatalf("目标记录未被召回(fake DB 应原样返回),body=%s", body)
|
||||
}
|
||||
if found["superseded_by"] == nil {
|
||||
t.Fatalf("superseded_by 未暴露给读侧:%v", found)
|
||||
}
|
||||
if found["superseded"] != true {
|
||||
t.Fatalf("superseded 便捷布尔应为 true:%v", found["superseded"])
|
||||
}
|
||||
if found["generation"] != float64(2) {
|
||||
t.Fatalf("generation 应为 2:%v", found["generation"])
|
||||
}
|
||||
if found["valid_to"] != "2026-10-26T11:00:00+08:00" {
|
||||
t.Fatalf("valid_to 未直通:%v", found["valid_to"])
|
||||
}
|
||||
if found["channel"] == nil || found["channel"] == "" {
|
||||
t.Fatalf("channel 未暴露:%v", found)
|
||||
}
|
||||
if _, ok := m["trace_id"]; !ok {
|
||||
t.Fatalf("响应缺 trace_id:%s", body)
|
||||
}
|
||||
if m["status"] != "complete" {
|
||||
t.Fatalf("正常召回 status 应为 complete,实际 %v", m["status"])
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/governance"
|
||||
"github.com/xiaoxue/memoryweave/internal/models"
|
||||
@@ -35,7 +36,7 @@ func (f *fakeLanceDB) Stats() (map[string]interface{}, error) {
|
||||
return map[string]interface{}{}, nil
|
||||
}
|
||||
func (f *fakeLanceDB) SoftDelete(id, reason string) error { return nil }
|
||||
func (f *fakeLanceDB) PurgeInvalid() (int64, error) { return 0, nil }
|
||||
func (f *fakeLanceDB) PurgeInvalid() (int64, error) { return 0, nil }
|
||||
func (f *fakeLanceDB) SoftDeleteBatch(table string, ids []string, updatedAt string) (int64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
@@ -56,6 +57,13 @@ func (f *fakeLanceDB) IncrementUseful(id string) error { return nil }
|
||||
func (f *fakeLanceDB) IncrementNotUseful(id string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// GA-P0-1 (t_718d8707):拆分字段
|
||||
func (f *fakeLanceDB) IncrementHumanNotUseful(id string) error { return nil }
|
||||
func (f *fakeLanceDB) AppendHitEvent(memoryID, outcome, reason string) error { return nil }
|
||||
func (f *fakeLanceDB) CountHitEvents(memoryID, outcome string, since time.Time) (int, error) { return 0, nil }
|
||||
func (f *fakeLanceDB) GetHitEvents(memoryID string, limit int) ([]models.HitEvent, error) { return nil, nil }
|
||||
func (f *fakeLanceDB) IncrementDedupDownweight(id string) error { return nil }
|
||||
func (f *fakeLanceDB) UpdateMemoryContent(id, newContent, source string) error {
|
||||
return nil
|
||||
}
|
||||
@@ -183,7 +191,7 @@ type fakeEmbedder struct {
|
||||
|
||||
// TestRecallFailure_Non2xx 验证失败路径:依赖不可用时返回非 2xx + 统一错误体。
|
||||
// 模拟:embedder endpoint="" → encode 必失败(HTTP 到空 URL)⇒ 主路径 err != nil
|
||||
// + InMemoryGraph FallbackTextSearch 返回空 ⇒ 502 失败路径。
|
||||
// - InMemoryGraph FallbackTextSearch 返回空 ⇒ 502 失败路径。
|
||||
func TestRecallFailure_Non2xx(t *testing.T) {
|
||||
db := &fakeLanceDB{searchResults: nil}
|
||||
gs := governance.NewInMemoryGraph()
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package routes
|
||||
|
||||
// 2026-10-26(P1-3):stale-return + 生命周期 fixture(10:00 生效 / 11:00 失效)。
|
||||
//
|
||||
// 评审缺口:「只有离线检索指标,没有 stale-return、没有生命周期 fixture」。
|
||||
// 本测试把三条读侧生命周期行为锁成机械判据:
|
||||
// ① bi-temporal 开启时,valid_to 已过的事实**不进 top-k**(但仍在库,non-lossy);
|
||||
// ② valid_to 在未来 / 为空 ⇒ 正常返回(同一 fixture 的对照,证明不是「整类被吞」);
|
||||
// ③ updated_at 超 720h ⇒ 响应 stale=true;新记录不输出该键。
|
||||
//
|
||||
// 时窗用真实语义:fixture 事实 10:00 生效、11:00 失效,查询时点取「当日 11:00 之后」。
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/models"
|
||||
)
|
||||
|
||||
// 时窗用**相对时间**:曾经写成 dayAt(10,0)/dayAt(11,0) 假设「跑测试时已是晚上 20:00」,
|
||||
// 凌晨 02:07 跑就是 flaky —— 11:00 还没到,「已失效」的 fixture 其实仍有效。
|
||||
// 生命周期判据必须与运行时刻无关:过期 = now-1h,有效期 = now+24h。
|
||||
func expiredPair() (from, to, future string) {
|
||||
now := time.Now()
|
||||
return now.Add(-2 * time.Hour).Format(time.RFC3339),
|
||||
now.Add(-1 * time.Hour).Format(time.RFC3339),
|
||||
now.Add(24 * time.Hour).Format(time.RFC3339)
|
||||
}
|
||||
|
||||
func idsOf(m map[string]interface{}) map[string]bool {
|
||||
out := map[string]bool{}
|
||||
if res, ok := m["results"].([]interface{}); ok {
|
||||
for _, raw := range res {
|
||||
if r, ok := raw.(map[string]interface{}); ok {
|
||||
if id, ok := r["id"].(string); ok {
|
||||
out[id] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestRecall_Lifecycle_ExpiredFactDroppedWhenBitemporal(t *testing.T) {
|
||||
from, to, future := expiredPair()
|
||||
|
||||
db := &fakeLanceDB{searchResults: []models.MemoryRecord{
|
||||
{ID: "mem_expired_window", Content: "生命周期 fixture:10:00 生效 11:00 失效的事实",
|
||||
Category: "distilled", ValidFrom: from, ValidTo: to},
|
||||
{ID: "mem_still_valid", Content: "生命周期 fixture:仍在有效期内的事实",
|
||||
Category: "distilled", ValidFrom: from, ValidTo: future},
|
||||
}}
|
||||
t.Setenv("ZHIYI_BITEMPORAL", "1")
|
||||
code, m, body := recallBody(t, db, `{"query":"生命周期 fixture 有效期","limit":5,"namespace":"hermes-main"}`)
|
||||
if code != 200 {
|
||||
t.Fatalf("expected 200, got %d; body=%s", code, body)
|
||||
}
|
||||
ids := idsOf(m)
|
||||
if ids["mem_expired_window"] {
|
||||
t.Fatalf("11:00 已失效的事实不应进 top-k(bi-temporal 开);body=%s", body)
|
||||
}
|
||||
if !ids["mem_still_valid"] {
|
||||
t.Fatalf("有效期未过的事实必须正常返回(对照缺失 ⇒ 可能是整类被吞);body=%s", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecall_Lifecycle_ExpiredFactVisibleWhenBitemporalOff(t *testing.T) {
|
||||
// 开关关(默认)⇒ 行为零变化:过期事实照常返回,但 valid_to 字段可见(读侧能自己判)。
|
||||
from, to, _ := expiredPair()
|
||||
db := &fakeLanceDB{searchResults: []models.MemoryRecord{
|
||||
{ID: "mem_expired_visible", Content: "生命周期 fixture:过期但可见", Category: "distilled",
|
||||
ValidFrom: from, ValidTo: to},
|
||||
}}
|
||||
t.Setenv("ZHIYI_BITEMPORAL", "0")
|
||||
code, m, body := recallBody(t, db, `{"query":"过期但可见","limit":5,"namespace":"hermes-main"}`)
|
||||
if code != 200 {
|
||||
t.Fatalf("expected 200, got %d; body=%s", code, body)
|
||||
}
|
||||
if !idsOf(m)["mem_expired_visible"] {
|
||||
t.Fatalf("bi-temporal 关时过期事实应照常返回(non-lossy 可见性);body=%s", body)
|
||||
}
|
||||
var found map[string]interface{}
|
||||
for _, raw := range m["results"].([]interface{}) {
|
||||
if r, ok := raw.(map[string]interface{}); ok && r["id"] == "mem_expired_visible" {
|
||||
found = r
|
||||
}
|
||||
}
|
||||
if found == nil || found["valid_to"] != to {
|
||||
t.Fatalf("valid_to 必须直通给读侧:%v", found)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecall_StaleReturn_DefaultThreshold(t *testing.T) {
|
||||
old := time.Now().Add(-31 * 24 * time.Hour)
|
||||
db := &fakeLanceDB{searchResults: []models.MemoryRecord{
|
||||
{ID: "mem_old", Content: "陈年事实(31 天未更新)", Category: "distilled", UpdatedAt: old},
|
||||
{ID: "mem_new", Content: "新鲜事实(今天更新)", Category: "distilled", UpdatedAt: time.Now()},
|
||||
}}
|
||||
code, m, body := recallBody(t, db, `{"query":"事实 新鲜度","limit":5,"namespace":"hermes-main"}`)
|
||||
if code != 200 {
|
||||
t.Fatalf("expected 200, got %d; body=%s", code, body)
|
||||
}
|
||||
got := map[string]map[string]interface{}{}
|
||||
for _, raw := range m["results"].([]interface{}) {
|
||||
if r, ok := raw.(map[string]interface{}); ok {
|
||||
got[r["id"].(string)] = r
|
||||
}
|
||||
}
|
||||
if got["mem_old"] == nil || got["mem_old"]["stale"] != true {
|
||||
t.Fatalf("31 天未更新的记忆应 stale=true:%v", got["mem_old"])
|
||||
}
|
||||
if _, ok := got["mem_new"]["stale"]; ok {
|
||||
t.Fatalf("新记忆不应输出 stale 键:%v", got["mem_new"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package routes
|
||||
|
||||
// t_3aa2a8c1:`/api/v1/recall` 响应暴露 `truncated`(Rust 侧单次重读行数上限截断标志,
|
||||
// 引擎已算、此前只打日志不上抛)。选定的省略语义 = **键缺失即未截断(omitempty)**。
|
||||
// 本测试经路由层机械判定:
|
||||
// ① 粗检索被截断(后端实现 SearchTruncationReporter 且上报 true)⇒ 响应含 "truncated":true
|
||||
// ② 未截断 / 纯 Go 后端(不实现 reporter)⇒ 键缺失(不出现 truncated:false 以外的值)
|
||||
// ③ 回归:既有字段 results/count/candidates_scanned/mode/cache_hit 行为不变
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/governance"
|
||||
"github.com/xiaoxue/memoryweave/internal/models"
|
||||
"github.com/xiaoxue/memoryweave/internal/storage"
|
||||
)
|
||||
|
||||
// truncReportingLDB 复用同包 fakeLanceDB(recall_error_shape_test.go),
|
||||
// 额外实现可选扩展接口 SearchWithTruncationReporter(t_3aa2a8c1)。
|
||||
type truncReportingLDB struct {
|
||||
*fakeLanceDB
|
||||
reportTruncated bool
|
||||
}
|
||||
|
||||
func (f *truncReportingLDB) SearchWithTruncation(table string, vector []float32, topK int, namespaceFilter string) ([]models.MemoryRecord, bool, error) {
|
||||
if f.searchErr != nil {
|
||||
return nil, false, f.searchErr
|
||||
}
|
||||
if len(f.searchResults) > topK {
|
||||
return f.searchResults[:topK], f.reportTruncated, nil
|
||||
}
|
||||
return f.searchResults, f.reportTruncated, nil
|
||||
}
|
||||
|
||||
func recallBody(t *testing.T, db storage.LanceDB, body string) (int, map[string]interface{}, string) {
|
||||
t.Helper()
|
||||
// 测试须可复跑(t_3aa2a8c1 实测踩坑):SearchCacheInstance 由 storage 包 init() 恒建
|
||||
// (L2 = 共享 Redis,TTL 60s)⇒ 上一次 run 的 recall 结果会进 L2,下一次 run 同 key
|
||||
// 命中缓存路径(Truncated 恒 false)⇒ 断言 flaky。逐测试摘除缓存(测后恢复),
|
||||
// 恒走未缓存路径。包内无 t.Parallel ⇒ 改全局安全。
|
||||
saved := storage.SearchCacheInstance
|
||||
storage.SearchCacheInstance = nil
|
||||
t.Cleanup(func() { storage.SearchCacheInstance = saved })
|
||||
|
||||
emb := storage.NewEmbedder("")
|
||||
rerank := storage.NewReranker("", emb)
|
||||
api := NewAPI(db, emb, rerank, nil, governance.NewInMemoryGraph())
|
||||
req := httptest.NewRequest("POST", "/api/v1/recall", strings.NewReader(body))
|
||||
w := httptest.NewRecorder()
|
||||
api.Recall(w, req)
|
||||
var m map[string]interface{}
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &m)
|
||||
return w.Code, m, w.Body.String()
|
||||
}
|
||||
|
||||
// 既有响应键回归基线(t_2d4e3b92 成功 schema + t_1c12e000 cache_hit + t_949840b1 candidates_scanned)
|
||||
var recallBaselineKeys = []string{"results", "count", "candidates_scanned", "mode", "cache_hit"}
|
||||
|
||||
func assertBaseline(t *testing.T, m map[string]interface{}, body string) {
|
||||
t.Helper()
|
||||
for _, k := range recallBaselineKeys {
|
||||
if _, ok := m[k]; !ok {
|
||||
t.Fatalf("既有字段 %q 缺失(回归破坏),body=%s", k, body)
|
||||
}
|
||||
}
|
||||
if res, ok := m["results"].([]interface{}); ok {
|
||||
if cnt, _ := m["count"].(float64); int(cnt) != len(res) {
|
||||
t.Fatalf("count=%v 与 len(results)=%d 不一致(回归破坏)", m["count"], len(res))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ① 粗检索被行数上限截断 ⇒ 响应暴露 truncated:true + 既有字段回归不变
|
||||
func TestRecall_TruncatedExposedWhenHitCap(t *testing.T) {
|
||||
db := &truncReportingLDB{
|
||||
fakeLanceDB: &fakeLanceDB{searchResults: []models.MemoryRecord{
|
||||
{ID: "mem_1", Content: "test memory one", Category: "distilled"},
|
||||
{ID: "mem_2", Content: "test memory two", Category: "distilled"},
|
||||
}},
|
||||
reportTruncated: true,
|
||||
}
|
||||
code, m, body := recallBody(t, db, `{"query":"test query","limit":5,"namespace":"shared"}`)
|
||||
if code != 200 {
|
||||
t.Fatalf("expected 200, got %d; body=%s", code, body)
|
||||
}
|
||||
if v, ok := m["truncated"]; !ok || v != true {
|
||||
t.Fatalf("粗检索已截断,响应必须含 truncated:true;实际 key 存在=%v 值=%v body=%s", ok, m["truncated"], body)
|
||||
}
|
||||
assertBaseline(t, m, body)
|
||||
}
|
||||
|
||||
// ①b keyword 主路径(kwMeta 透传)同判据
|
||||
func TestRecall_Keyword_TruncatedExposed(t *testing.T) {
|
||||
db := &truncReportingLDB{
|
||||
fakeLanceDB: &fakeLanceDB{searchResults: []models.MemoryRecord{
|
||||
{ID: "mem_1", Content: "keyword memory", Category: "distilled"},
|
||||
}},
|
||||
reportTruncated: true,
|
||||
}
|
||||
code, m, body := recallBody(t, db, `{"query":"keyword query","limit":5,"mode":"keyword","namespace":"shared"}`)
|
||||
if code != 200 {
|
||||
t.Fatalf("expected 200, got %d; body=%s", code, body)
|
||||
}
|
||||
if v, ok := m["truncated"]; !ok || v != true {
|
||||
t.Fatalf("keyword 路径粗检索已截断,响应必须含 truncated:true;body=%s", body)
|
||||
}
|
||||
assertBaseline(t, m, body)
|
||||
}
|
||||
|
||||
// ② 未截断 ⇒ 键缺失(选定语义:省略=未截断),不得出现 truncated:false 以外的值
|
||||
func TestRecall_NotTruncated_KeyOmitted(t *testing.T) {
|
||||
db := &truncReportingLDB{
|
||||
fakeLanceDB: &fakeLanceDB{searchResults: []models.MemoryRecord{
|
||||
{ID: "mem_1", Content: "test memory one", Category: "distilled"},
|
||||
}},
|
||||
reportTruncated: false,
|
||||
}
|
||||
code, m, body := recallBody(t, db, `{"query":"test query","limit":5,"namespace":"shared"}`)
|
||||
if code != 200 {
|
||||
t.Fatalf("expected 200, got %d; body=%s", code, body)
|
||||
}
|
||||
if v, ok := m["truncated"]; ok {
|
||||
t.Fatalf("未截断场景键应缺失(省略=未截断);实际 truncated=%v body=%s", v, body)
|
||||
}
|
||||
assertBaseline(t, m, body)
|
||||
}
|
||||
|
||||
// ②b 纯 Go 后端(不实现 SearchTruncationReporter)⇒ 键缺失,零值语义、行为不变
|
||||
func TestRecall_PureGoBackend_NoTruncatedKey(t *testing.T) {
|
||||
db := &fakeLanceDB{searchResults: []models.MemoryRecord{
|
||||
{ID: "mem_1", Content: "test memory one", Category: "distilled"},
|
||||
}}
|
||||
code, m, body := recallBody(t, db, `{"query":"test query","limit":5,"namespace":"shared"}`)
|
||||
if code != 200 {
|
||||
t.Fatalf("expected 200, got %d; body=%s", code, body)
|
||||
}
|
||||
if _, ok := m["truncated"]; ok {
|
||||
t.Fatalf("纯 Go 后端无行数上限,truncated 键必须缺失;body=%s", body)
|
||||
}
|
||||
assertBaseline(t, m, body)
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
package routes
|
||||
|
||||
// 织忆自检端点(2026-10-26,牧尘批「三档」)
|
||||
//
|
||||
// 背景:织忆相关的定时自检脚本有 ~20 个,取数方式三套并存——
|
||||
// ① 直连生产库 lancedb.connect("/var/lib/memoryweave")(绕过服务、schema 一改就静默腐烂)
|
||||
// ② IPC socket 自定义协议
|
||||
// ③ HTTP /api/v1/{stats,popwatch,metrics/self}
|
||||
// 三套契约对同一个库,schema 变更时分开损坏。典型事故:pattern 自检脚本写死
|
||||
// type='pattern',库里实际是 pattern_stat ⇒ 连续数月静默 0 输出。
|
||||
//
|
||||
// 本端点是**唯一取数契约**:把「读织忆内部状态」收敛成一份结构化 JSON。
|
||||
// 设计边界(不做什么):
|
||||
// - 不做判定/告警/投递 —— 阈值、渠道、评审留在外部 cron(观测者不能住在被观测者体内:
|
||||
// zhiyid 一挂自检就跟着哑,内外同时沉默是更坏的故障)。
|
||||
// - 不跑重活(eval 全量、备份、vacuum)—— 那些抢生产资源,留在 systemd-run 独立 scope。
|
||||
//
|
||||
// level 语义:
|
||||
// - cheap(默认,<50ms):只读内存态/计数,不扫全表。
|
||||
// - full(秒级):额外扫全表算碎片率/冗余率/近 7 天质量/写量分布(原 quality-watch 口径)。
|
||||
//
|
||||
// 兼容铁律:本端点返回的比率一律给「分子/分母/样本是否足够」,缺数据不返回 0
|
||||
// (0 会被下游读成"很好")。沿用 selfoptimize 的 metricNA(-1) 语义。
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/distill"
|
||||
"github.com/xiaoxue/memoryweave/internal/selfoptimize"
|
||||
"github.com/xiaoxue/memoryweave/internal/storage"
|
||||
)
|
||||
|
||||
// SelfcheckSchemaVersion 变更返回结构时递增;消费方据此判兼容。
|
||||
const SelfcheckSchemaVersion = "1"
|
||||
|
||||
// 与 zhiyi-quality-watch.py 同口径(该脚本已改为读本端点,口径只此一处)
|
||||
const (
|
||||
selfcheckFragLen = 20 // <20 字符 = 碎片
|
||||
selfcheckDupMinSample = 5000 // 冗余率最小样本(活行),不足只报样本不判率
|
||||
selfcheckScanLimit = 300000
|
||||
)
|
||||
|
||||
type selfcheckQuality struct {
|
||||
TotalRows int `json:"total_rows"`
|
||||
LiveRows int `json:"live_rows"`
|
||||
ScannedRows int `json:"scanned_rows"`
|
||||
ScanTruncated bool `json:"scan_truncated"`
|
||||
Coverage float64 `json:"coverage"` // 扫描行 / store 真实总量;<1 表示结果不完整,禁止据此下结论
|
||||
FragLen int `json:"frag_len"`
|
||||
|
||||
FragRowsAll int `json:"frag_rows_all"`
|
||||
FragRateAll float64 `json:"frag_rate_all"`
|
||||
FragRowsLive int `json:"frag_rows_live"`
|
||||
FragRateLive float64 `json:"frag_rate_live"`
|
||||
|
||||
DupGroups int `json:"dup_groups"`
|
||||
DupExtraRows int `json:"dup_extra_rows"`
|
||||
DupRate float64 `json:"dup_rate"`
|
||||
DupSampleOK bool `json:"dup_sample_ok"`
|
||||
|
||||
NewRows7d int `json:"new_rows_7d"`
|
||||
NewFragRows7d int `json:"new_frag_rows_7d"`
|
||||
NewFragRate7d *float64 `json:"new_frag_rate_7d"` // nil = 近 7 天无新增(无分母)
|
||||
}
|
||||
|
||||
type selfcheckDayCount struct {
|
||||
Date string `json:"date"`
|
||||
Rows int `json:"rows"`
|
||||
Live int `json:"live"`
|
||||
}
|
||||
|
||||
type selfcheckWriteVolume struct {
|
||||
Days []selfcheckDayCount `json:"days"`
|
||||
Today int `json:"today"`
|
||||
Last7d int `json:"last_7d"`
|
||||
Median7d float64 `json:"median_7d"`
|
||||
P25_7d float64 `json:"p25_7d"`
|
||||
}
|
||||
|
||||
// Selfcheck GET /api/v1/selfcheck?level=cheap|full
|
||||
func (a *API) Selfcheck(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
if r.Method != http.MethodGet {
|
||||
respondError(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
return
|
||||
}
|
||||
level := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("level")))
|
||||
if level == "" {
|
||||
level = "cheap"
|
||||
}
|
||||
if level != "cheap" && level != "full" {
|
||||
respondError(w, http.StatusBadRequest, "level must be cheap|full")
|
||||
return
|
||||
}
|
||||
|
||||
rep := map[string]interface{}{
|
||||
"schema_version": SelfcheckSchemaVersion,
|
||||
"checked_at": time.Now().Format(time.RFC3339),
|
||||
"level": level,
|
||||
}
|
||||
degraded := []string{}
|
||||
|
||||
// ── 存储总量 ───────────────────────────────
|
||||
if st, err := a.LanceDB.Stats(); err != nil {
|
||||
degraded = append(degraded, "store: "+err.Error())
|
||||
} else {
|
||||
total := numOf(st["total_memories"])
|
||||
tomb := numOf(st["tombstone_count"])
|
||||
live := total - tomb
|
||||
if live < 0 {
|
||||
live = 0
|
||||
}
|
||||
store := map[string]interface{}{
|
||||
"backend": st["backend"],
|
||||
"data_dir": st["data_dir"],
|
||||
"total_memories": total,
|
||||
"total_episodes": numOf(st["total_episodes"]),
|
||||
"tombstone_count": tomb,
|
||||
"live_memories": live,
|
||||
}
|
||||
if total > 0 {
|
||||
store["tombstone_rate"] = round4(tomb / total)
|
||||
} else {
|
||||
store["tombstone_rate"] = -1.0 // N/A:空库无分母
|
||||
}
|
||||
rep["store"] = store
|
||||
}
|
||||
|
||||
// ── 图谱 ───────────────────────────────────
|
||||
if a.GraphStore != nil {
|
||||
n, e, d := a.GraphStore.Stats()
|
||||
rep["graph"] = map[string]interface{}{
|
||||
"node_count": n,
|
||||
"edge_count": e,
|
||||
"density": round4(d),
|
||||
}
|
||||
} else {
|
||||
degraded = append(degraded, "graph: store not initialised")
|
||||
}
|
||||
|
||||
// ── pattern 召回的两侧健康(2026-10-26 新增)──────────
|
||||
// 事故背景:`POST /api/v1/patterns/detect` 是短命单发端点,全库 0 cron、0 调用方,
|
||||
// 于是 graph_nodes(type='pattern') 恒 0 行、recall 恒 0 命中,而日志层面完全沉默
|
||||
// (只能靠人翻 7 天日志才发现「实现了 ≠ 出过数」)。这里把「写入端有没有产数」
|
||||
// 变成一次 GET 就能读到的事实:rows=0 ⇒ 生产者坏了或从未接线,别去查读侧 SQL。
|
||||
rep["pattern"] = patternHealth(a)
|
||||
|
||||
// ── 面板指标(反馈/蒸馏/gap/cascade,含 _valid/_samples 语义)──
|
||||
rep["dashboard"] = selfoptimize.Dash.Metrics()
|
||||
|
||||
// ── 整合链路(内存态,<1ms)────────────────
|
||||
tracker := GetConsolTracker()
|
||||
consolStatus, consolFails, sinceSuccess, lastErr := tracker.HealthStatus()
|
||||
_, consolSkips, lastSkip, _ := tracker.Snapshot()
|
||||
rep["consolidate"] = map[string]interface{}{
|
||||
"status": consolStatus,
|
||||
"consec_failures": consolFails,
|
||||
"skipped": consolSkips,
|
||||
"last_skip": lastSkip,
|
||||
"last_success_age": sinceSuccess.String(),
|
||||
"last_error": lastErr,
|
||||
}
|
||||
|
||||
// ── 缓存 / FTS ─────────────────────────────
|
||||
cache := map[string]interface{}{"fts_index": storage.FtsIndexStats()}
|
||||
if storage.SearchCacheInstance != nil {
|
||||
cache["search_cache"] = storage.SearchCacheInstance.Stats()
|
||||
}
|
||||
rep["cache"] = cache
|
||||
|
||||
// ── 空壳拦截器(t_e11207f8 取证)───────────
|
||||
checks, blocks, loaded, rulesPath := distill.PayloadGuardStats()
|
||||
rep["payload_guard"] = map[string]interface{}{
|
||||
"checks": checks,
|
||||
"blocks": blocks,
|
||||
"loaded": loaded,
|
||||
"rules_path": rulesPath,
|
||||
}
|
||||
|
||||
// ── 全量质量段(level=full):读卫星快照,不在本进程扫全表 ────────
|
||||
// 设计:全表扫描是重活(4 万行 × 内容),且 daemon 还有 recall 要跑。
|
||||
// 取数由仓库内 tools/selfcheck_full.py 完成(列投影只读,1.7s / 250MB,独立进程),
|
||||
// 写 ~/.hermes/state/zhiyi-quality.json;本端点只读快照并标注新鲜度。
|
||||
// 这样"取数"只有一处实现(跟 schema 同仓),"判定/告警"仍在外部 cron。
|
||||
if level == "full" {
|
||||
snap, err := loadQualitySnapshot()
|
||||
if err != nil {
|
||||
degraded = append(degraded, "quality: "+err.Error())
|
||||
} else {
|
||||
rep["quality"] = snap.Quality
|
||||
rep["write_volume"] = snap.WriteVolume
|
||||
rep["quality_as_of"] = snap.GeneratedAt
|
||||
rep["quality_age_s"] = snap.AgeSeconds()
|
||||
rep["quality_stale"] = snap.AgeSeconds() > qualityStaleAfter
|
||||
}
|
||||
}
|
||||
|
||||
if len(degraded) > 0 {
|
||||
rep["degraded"] = degraded
|
||||
}
|
||||
rep["duration_ms"] = time.Since(start).Milliseconds()
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(rep)
|
||||
}
|
||||
|
||||
// qualityStaleAfter:快照超过这个时长未刷新 ⇒ 标记 stale(消费方不得据此下结论)。
|
||||
const qualityStaleAfter = 6 * 3600
|
||||
|
||||
// qualitySnapshot 对应仓库内 tools/selfcheck_full.py 的产出。
|
||||
// 字段名与 python 侧严格一致(schema_version=1)。
|
||||
type qualitySnapshot struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
GeneratedAt string `json:"generated_at"`
|
||||
Source struct {
|
||||
DB string `json:"db"`
|
||||
Table string `json:"table"`
|
||||
Mode string `json:"mode"`
|
||||
} `json:"source"`
|
||||
DurationMS int `json:"duration_ms"`
|
||||
Quality json.RawMessage `json:"quality"`
|
||||
WriteVolume json.RawMessage `json:"write_volume"`
|
||||
fileModTime time.Time
|
||||
}
|
||||
|
||||
func (q *qualitySnapshot) AgeSeconds() int64 {
|
||||
if q.fileModTime.IsZero() {
|
||||
return -1
|
||||
}
|
||||
return int64(time.Since(q.fileModTime).Seconds())
|
||||
}
|
||||
|
||||
// QualitySnapshotPath 允许用 env 覆盖(测试/灰度)。
|
||||
func QualitySnapshotPath() string {
|
||||
if p := strings.TrimSpace(os.Getenv("ZHIYI_QUALITY_SNAPSHOT")); p != "" {
|
||||
return p
|
||||
}
|
||||
home, _ := os.UserHomeDir()
|
||||
return filepath.Join(home, ".hermes", "state", "zhiyi-quality.json")
|
||||
}
|
||||
|
||||
func loadQualitySnapshot() (*qualitySnapshot, error) {
|
||||
p := QualitySnapshotPath()
|
||||
fi, err := os.Stat(p)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("快照不存在(先跑 tools/selfcheck_full.py):%w", err)
|
||||
}
|
||||
raw, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var snap qualitySnapshot
|
||||
if err := json.Unmarshal(raw, &snap); err != nil {
|
||||
return nil, fmt.Errorf("快照解析失败: %w", err)
|
||||
}
|
||||
snap.fileModTime = fi.ModTime()
|
||||
return &snap, nil
|
||||
}
|
||||
|
||||
// numOf 把 stats 里可能是 float64/int/json.Number 的数值统一成 float64。
|
||||
func numOf(v interface{}) float64 {
|
||||
switch x := v.(type) {
|
||||
case float64:
|
||||
return x
|
||||
case float32:
|
||||
return float64(x)
|
||||
case int:
|
||||
return float64(x)
|
||||
case int64:
|
||||
return float64(x)
|
||||
case json.Number:
|
||||
f, _ := x.Float64()
|
||||
return f
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
func round4(f float64) float64 {
|
||||
if math.IsNaN(f) || math.IsInf(f, 0) {
|
||||
return -1
|
||||
}
|
||||
return math.Round(f*10000) / 10000
|
||||
}
|
||||
|
||||
// patternHealth 一眼判定 pattern 召回是「有生产者」还是「恒 0」。
|
||||
//
|
||||
// 为什么需要它:2026-10-26 排查发现 pattern 召回 0 命中,真根因是写入端从未产数
|
||||
// (detect 端点无 cron、无调用方),但表面症状看起来像读侧 SQL bug —— 白查一轮方向。
|
||||
// 判据三类:
|
||||
//
|
||||
// producing 有行、有 id、有生产时间 → 读侧再 0 命中就该查 Match 阈值/properties;
|
||||
// zero_output 0 行 → 生产端问题,别去动读侧 SQL;
|
||||
// no_id 有行但 id 全空 → store.ListPatterns 会全 skip(存量冻结的典型形态)。
|
||||
func patternHealth(a *API) map[string]interface{} {
|
||||
out := map[string]interface{}{
|
||||
"rows": -1, // -1 = 未知,别当 0 用
|
||||
"rows_with_id": -1,
|
||||
"last_produced_at": "",
|
||||
"verdict": "unknown",
|
||||
}
|
||||
if a == nil || a.GraphStore == nil {
|
||||
out["verdict"] = "no_graph_store"
|
||||
return out
|
||||
}
|
||||
rows, withID, last := a.GraphStore.CountNodesByType("pattern")
|
||||
out["rows"], out["rows_with_id"], out["last_produced_at"] = rows, withID, last
|
||||
switch {
|
||||
case rows == 0:
|
||||
out["verdict"] = "zero_output"
|
||||
case withID == 0:
|
||||
out["verdict"] = "no_id"
|
||||
case last == "":
|
||||
out["verdict"] = "unknown_age"
|
||||
default:
|
||||
out["verdict"] = "producing"
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 快照契约测试:/api/v1/selfcheck?level=full 依赖 tools/selfcheck_full.py 的产出格式。
|
||||
// 这里钉住 schema_version 与关键字段,防止 python 侧改字段名后 Go 侧静默返回空。
|
||||
func TestLoadQualitySnapshot(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
p := filepath.Join(dir, "zhiyi-quality.json")
|
||||
body := `{
|
||||
"schema_version": 1,
|
||||
"generated_at": "2026-10-26T13:20:00+0800",
|
||||
"source": {"db": "/var/lib/memoryweave", "table": "memories", "mode": "read_only_projection"},
|
||||
"duration_ms": 1680,
|
||||
"quality": {
|
||||
"frag_len": 20, "total_rows": 39957, "live_rows": 39836,
|
||||
"frag_rows_all": 313, "frag_rate_all": 0.0078,
|
||||
"frag_rows_live": 313, "frag_rate_live": 0.0079,
|
||||
"dup_groups": 34, "dup_extra_rows": 103, "dup_rate": 0.0026,
|
||||
"new_rows_7d": 1176, "new_frag_rows_7d": 35, "new_frag_rate_7d": 0.0298
|
||||
},
|
||||
"write_volume": {
|
||||
"days": [{"date": "2026-10-25", "rows": 1473, "live": 1471}],
|
||||
"today": 332, "today_date": "2026-10-26", "last_7d": 7706, "nonzero_days": 60
|
||||
}
|
||||
}`
|
||||
if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("ZHIYI_QUALITY_SNAPSHOT", p)
|
||||
|
||||
snap, err := loadQualitySnapshot()
|
||||
if err != nil {
|
||||
t.Fatalf("loadQualitySnapshot: %v", err)
|
||||
}
|
||||
if snap.SchemaVersion != 1 {
|
||||
t.Fatalf("schema_version=%d want 1", snap.SchemaVersion)
|
||||
}
|
||||
|
||||
var q struct {
|
||||
TotalRows int `json:"total_rows"`
|
||||
LiveRows int `json:"live_rows"`
|
||||
DupRate float64 `json:"dup_rate"`
|
||||
FragRowsAll int `json:"frag_rows_all"`
|
||||
}
|
||||
if err := json.Unmarshal(snap.Quality, &q); err != nil {
|
||||
t.Fatalf("quality 段解析失败: %v", err)
|
||||
}
|
||||
if q.TotalRows != 39957 || q.LiveRows != 39836 {
|
||||
t.Fatalf("quality 口径不符: %+v", q)
|
||||
}
|
||||
if q.FragRowsAll != 313 || q.DupRate != 0.0026 {
|
||||
t.Fatalf("quality 数值不符: %+v", q)
|
||||
}
|
||||
|
||||
var wv struct {
|
||||
Today int `json:"today"`
|
||||
Days []struct {
|
||||
Date string `json:"date"`
|
||||
Live int `json:"live"`
|
||||
} `json:"days"`
|
||||
}
|
||||
if err := json.Unmarshal(snap.WriteVolume, &wv); err != nil {
|
||||
t.Fatalf("write_volume 段解析失败: %v", err)
|
||||
}
|
||||
if wv.Today != 332 || len(wv.Days) != 1 || wv.Days[0].Live != 1471 {
|
||||
t.Fatalf("write_volume 不符: %+v", wv)
|
||||
}
|
||||
|
||||
// 新鲜度:刚写的文件 age 应 < 10s;人为改旧 → stale 判定为真
|
||||
if age := snap.AgeSeconds(); age < 0 || age > 10 {
|
||||
t.Fatalf("AgeSeconds=%d,本应接近 0", age)
|
||||
}
|
||||
old := time.Now().Add(-8 * time.Hour)
|
||||
if err := os.Chtimes(p, old, old); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
snap2, err := loadQualitySnapshot()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if snap2.AgeSeconds() <= qualityStaleAfter {
|
||||
t.Fatalf("8h 前的快照应判 stale(>%d 秒),得到 %d", qualityStaleAfter, snap2.AgeSeconds())
|
||||
}
|
||||
}
|
||||
|
||||
// 快照缺失 ⇒ 必须报错(由 handler 转成 degraded),不能静默返回零值。
|
||||
func TestLoadQualitySnapshotMissing(t *testing.T) {
|
||||
t.Setenv("ZHIYI_QUALITY_SNAPSHOT", filepath.Join(t.TempDir(), "nope.json"))
|
||||
if _, err := loadQualitySnapshot(); err == nil {
|
||||
t.Fatal("缺失快照应返回 error")
|
||||
}
|
||||
}
|
||||
@@ -17,18 +17,18 @@ const skillRedisKey = "zhiyi:skills"
|
||||
|
||||
// BetaSkill 贝叶斯 Skill 评分(G7 扩展版)
|
||||
type BetaSkill struct {
|
||||
Name string `json:"name"`
|
||||
Alpha float64 `json:"alpha"` // α = successes + 1
|
||||
Beta float64 `json:"beta"` // β = failures + 1
|
||||
Trials int `json:"trials"`
|
||||
Successes int `json:"successes"`
|
||||
ETA float64 `json:"eta"` // α/(α+β) 贝叶斯均值
|
||||
Status string `json:"status"` // active / probation / retired
|
||||
LastUpdated time.Time `json:"last_updated"`
|
||||
Name string `json:"name"`
|
||||
Alpha float64 `json:"alpha"` // α = successes + 1
|
||||
Beta float64 `json:"beta"` // β = failures + 1
|
||||
Trials int `json:"trials"`
|
||||
Successes int `json:"successes"`
|
||||
ETA float64 `json:"eta"` // α/(α+β) 贝叶斯均值
|
||||
Status string `json:"status"` // active / probation / retired
|
||||
LastUpdated time.Time `json:"last_updated"`
|
||||
// G7 扩展字段
|
||||
PromptTemplate string `json:"prompt_template,omitempty"` // 可执行 prompt(含 {param} 占位符)
|
||||
LinkedMemoryIDs []string `json:"linked_memory_ids,omitempty"` // 关联的记忆 ID
|
||||
LinkedEntities []string `json:"linked_entities,omitempty"` // 关联的图谱实体
|
||||
PromptTemplate string `json:"prompt_template,omitempty"` // 可执行 prompt(含 {param} 占位符)
|
||||
LinkedMemoryIDs []string `json:"linked_memory_ids,omitempty"` // 关联的记忆 ID
|
||||
LinkedEntities []string `json:"linked_entities,omitempty"` // 关联的图谱实体
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
@@ -146,12 +146,12 @@ func (bsm *BayesianSkillManager) Register(name, promptTemplate string, linkedEnt
|
||||
skill, exists := bsm.skills[name]
|
||||
if !exists {
|
||||
skill = &BetaSkill{
|
||||
Name: name,
|
||||
Alpha: 1.0,
|
||||
Beta: 1.0,
|
||||
CreatedAt: time.Now(),
|
||||
PromptTemplate: promptTemplate,
|
||||
LinkedEntities: linkedEntities,
|
||||
Name: name,
|
||||
Alpha: 1.0,
|
||||
Beta: 1.0,
|
||||
CreatedAt: time.Now(),
|
||||
PromptTemplate: promptTemplate,
|
||||
LinkedEntities: linkedEntities,
|
||||
}
|
||||
bsm.skills[name] = skill
|
||||
} else {
|
||||
@@ -306,11 +306,11 @@ func (bsm *BayesianSkillManager) Stats() map[string]interface{} {
|
||||
}
|
||||
}
|
||||
return map[string]interface{}{
|
||||
"total": len(bsm.skills),
|
||||
"active": active,
|
||||
"probation": probation,
|
||||
"retired": retired,
|
||||
"persisted": bsm.persisted,
|
||||
"total": len(bsm.skills),
|
||||
"active": active,
|
||||
"probation": probation,
|
||||
"retired": retired,
|
||||
"persisted": bsm.persisted,
|
||||
"redis_connected": bsm.redisClient != nil,
|
||||
}
|
||||
}
|
||||
@@ -371,10 +371,10 @@ func (sm *SkillManager) Trial(w http.ResponseWriter, r *http.Request) {
|
||||
// POST /api/v1/skills — 注册新 skill(G7 新增)
|
||||
func (sm *SkillManager) Register(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
PromptTemplate string `json:"prompt_template"`
|
||||
LinkedEntities []string `json:"linked_entities"`
|
||||
Description string `json:"description"`
|
||||
Name string `json:"name"`
|
||||
PromptTemplate string `json:"prompt_template"`
|
||||
LinkedEntities []string `json:"linked_entities"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
respondError(w, 400, "invalid body: "+err.Error())
|
||||
@@ -427,4 +427,4 @@ func (sm *SkillManager) GetSkillETA(name string) float64 {
|
||||
return 0.5
|
||||
}
|
||||
return skill.ETA
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,8 +153,8 @@ func crystallizeFromRecord(mem *models.MemoryRecord) (*BetaSkill, error) {
|
||||
if err == nil && llmResult != "" {
|
||||
var parsed struct {
|
||||
PromptTemplate string `json:"prompt_template"`
|
||||
Entities []string `json:"entities"`
|
||||
SkillName string `json:"skill_name"`
|
||||
Entities []string `json:"entities"`
|
||||
SkillName string `json:"skill_name"`
|
||||
}
|
||||
if err2 := json.Unmarshal([]byte(llmResult), &parsed); err2 == nil {
|
||||
if parsed.PromptTemplate != "" {
|
||||
@@ -318,4 +318,4 @@ func getLDB() storage.LanceDB {
|
||||
return ldbGetter()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -240,4 +240,3 @@ func ExecuteSkill(w http.ResponseWriter, r *http.Request) {
|
||||
"eta": skill.ETA,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/storage"
|
||||
)
|
||||
|
||||
// 2026-10-13 (t_e9a4d18f P2) 常设答案路由(Hindsight mental models 直读/写入)。
|
||||
// 读取 = 一次 DB 读(question_id 主键),零检索零 LLM。写入由生成脚本
|
||||
// zhiyi-standing-answers.py 调用(复用本地 2B,免费)。
|
||||
|
||||
// standingStore 返回全局常设答案库(server.go 注入)。未初始化 → nil。
|
||||
func standingStore() *storage.StandingStore { return storage.StandingStoreInstance }
|
||||
|
||||
// HandleStandingAnswers GET/POST /api/v1/standing-answers
|
||||
// GET ?id=<question_id> → 直读一条;无 id → 列全部
|
||||
// POST {"question_id","question","answer","source_memories":[]} → 写入/改写
|
||||
func HandleStandingAnswers(w http.ResponseWriter, r *http.Request) {
|
||||
s := standingStore()
|
||||
if s == nil {
|
||||
respondError(w, http.StatusServiceUnavailable, "standing answers store not initialized")
|
||||
return
|
||||
}
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
id := r.URL.Query().Get("id")
|
||||
if id == "" {
|
||||
all, err := s.List()
|
||||
if err != nil {
|
||||
respondError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
respond(w, http.StatusOK, map[string]interface{}{"answers": all, "count": len(all)})
|
||||
return
|
||||
}
|
||||
a, err := s.Get(id)
|
||||
if err != nil {
|
||||
respondError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
if a == nil {
|
||||
respondError(w, http.StatusNotFound, "standing answer not found: "+id)
|
||||
return
|
||||
}
|
||||
respond(w, http.StatusOK, a)
|
||||
case http.MethodPost:
|
||||
var in struct {
|
||||
QuestionID string `json:"question_id"`
|
||||
Question string `json:"question"`
|
||||
Answer string `json:"answer"`
|
||||
SourceMemories []string `json:"source_memories"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
respondError(w, http.StatusBadRequest, "bad json: "+err.Error())
|
||||
return
|
||||
}
|
||||
if in.QuestionID == "" || in.Answer == "" {
|
||||
respondError(w, http.StatusBadRequest, "question_id and answer required")
|
||||
return
|
||||
}
|
||||
a, err := s.Upsert(in.QuestionID, in.Question, in.Answer, in.SourceMemories)
|
||||
if err != nil {
|
||||
respondError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
respond(w, http.StatusOK, a)
|
||||
default:
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// 织忆 MemoryWeave — 系统通知/提示样板文本判定(被动注入入口噪音闸门)
|
||||
//
|
||||
// 背景(t_689b6d38,2026-10-11 实测):织忆被动注入入口不区分「真实用户消息」与
|
||||
// 「系统样板文本」。近 7 天 [graph/notes] 通道 806 次注入里 543 次(67%)的入参是
|
||||
// 系统通知/提示样板(形如 "[IMPORTANT: You are running as a scheduled cron job...",
|
||||
// "[IMPORTANT: Background process ... completed", "[System note: ..."),它们照常走
|
||||
// 完整实体拆解并返回 3 篇笔记注入上下文 —— 纯浪费 + 稀释有效注入信噪比。
|
||||
//
|
||||
// 判定优先用【结构化信号】(消息来源标记头,如 "[IMPORTANT:"、"[HEARTBEAT]"、
|
||||
// "[System note:"、"Cronjob Response:"、role/来源字段),而不是纯文本长度启发式。
|
||||
// 命中 ⇒ 调用方应跳过语义召回与笔记返回。白名单:真实用户提问(含飞书/QQ/CLI 入站
|
||||
// 消息)不命中任何前缀/子串 ⇒ 照常召回,不误杀。
|
||||
package routes
|
||||
|
||||
import "github.com/xiaoxue/memoryweave/internal/textfilter"
|
||||
|
||||
// IsSystemTemplateInput 判定一段文本是否系统通知/提示样板(非真实用户提问)。
|
||||
// 命中 ⇒ 调用方应跳过语义召回与笔记返回(t_689b6d38 噪音闸门)。
|
||||
//
|
||||
// 2026-10-12:判定清单已抽到叶子包 internal/textfilter(蒸馏侧准入闸门也要用,
|
||||
// 而 distill 不能反向 import routes)。本函数保留为薄委托,调用点零改动。
|
||||
// 清单只维护 textfilter 一处。
|
||||
func IsSystemTemplateInput(s string) bool {
|
||||
return textfilter.IsSystemTemplate(s)
|
||||
}
|
||||
+114
-44
@@ -1,117 +1,187 @@
|
||||
{
|
||||
"description": "织忆召回金标检查集(12条基线 + 2条目标知识)。统一判据口径(t_a70b07e1):取 recall 返回的前 N=5 条内容查关键词,ID 命中 = expected_ids 任一 ∈ 前 N=5 条;N=5 与 Go/Python 两量具(eval_test.go / golden-check.py)一致。判定:PASS=id且kw命中 / WARN=kw命中但ID漂移 / FAIL=其余 / ERROR=recall调用失败。单一真相源(t_949840b1):本文件是金标数据唯一副本;Python 量具 golden-check.py 直接读本文件(旧 ~/.hermes/scripts/tools/golden-set.json 副副本已删除),基线校准一次即两量具同步(--refresh 写回本文件)。⚠️ item4「牧尘喜欢什么样的工作方式」基线 2026-09-21 t_949840b1 校准为当前稳定值 mem_1789834428978989104(语料增长致旧基线 mem_1789837840173161705 掉出 top-5,前 N 内容仍切题)。校准后同批金标两量具分类差异=0(diff=1 的根因——两份副本 expected_ids 不同步——已消除)。",
|
||||
"description": "织忆召回金标检查集(单一真相源,t_949840b1)。统一判据口径 N=5:取 recall 返回前 N=5 条查关键词,ID 命中 = expected_ids 任一 ∈ 前 N=5 条。基线已刷新(golden-check.py --refresh,两量具同源)。",
|
||||
"items": [
|
||||
{
|
||||
"query": "织忆是什么",
|
||||
"expected_ids": ["mem_1789153726378940805"],
|
||||
"must_include_keywords": ["织忆"],
|
||||
"expected_ids": [
|
||||
"mem_1791666702950691634"
|
||||
],
|
||||
"must_include_keywords": [
|
||||
"织忆"
|
||||
],
|
||||
"category": "system_fact",
|
||||
"difficulty": "easy",
|
||||
"id_baseline": "mem_1789153726378940805"
|
||||
"id_baseline": "mem_1791666702950691634",
|
||||
"namespace": "hermes-main"
|
||||
},
|
||||
{
|
||||
"query": "织忆的图谱扩展机制是什么",
|
||||
"expected_ids": ["mem_1789823837902661249"],
|
||||
"must_include_keywords": ["图谱"],
|
||||
"expected_ids": [
|
||||
"mem_1791899478673190284"
|
||||
],
|
||||
"must_include_keywords": [
|
||||
"图谱"
|
||||
],
|
||||
"category": "system_fact",
|
||||
"difficulty": "medium",
|
||||
"id_baseline": "mem_1789823837902661249"
|
||||
"id_baseline": "mem_1791899478673190284",
|
||||
"namespace": "hermes-main"
|
||||
},
|
||||
{
|
||||
"query": "织忆如何通过 E1 提取和 MMR 实现多样去重",
|
||||
"expected_ids": ["mem_1789915227303612056"],
|
||||
"must_include_keywords": ["MMR"],
|
||||
"expected_ids": [
|
||||
"mem_1791666890486125605"
|
||||
],
|
||||
"must_include_keywords": [
|
||||
"MMR"
|
||||
],
|
||||
"category": "system_fact",
|
||||
"difficulty": "hard",
|
||||
"id_baseline": "mem_1789915227303612056"
|
||||
"id_baseline": "mem_1791666890486125605",
|
||||
"namespace": "hermes-main"
|
||||
},
|
||||
{
|
||||
"query": "牧尘的偏好是什么",
|
||||
"expected_ids": ["mem_1789667544872361813"],
|
||||
"must_include_keywords": ["牧尘"],
|
||||
"expected_ids": [
|
||||
"mem_1790448247125520424"
|
||||
],
|
||||
"must_include_keywords": [
|
||||
"牧尘"
|
||||
],
|
||||
"category": "user_pref",
|
||||
"difficulty": "easy",
|
||||
"id_baseline": "mem_1789667544872361813"
|
||||
"id_baseline": "mem_1790448247125520424",
|
||||
"namespace": "hermes-main"
|
||||
},
|
||||
{
|
||||
"query": "牧尘喜欢什么样的工作方式",
|
||||
"expected_ids": ["mem_1789834428978989104"],
|
||||
"must_include_keywords": ["牧尘"],
|
||||
"expected_ids": [
|
||||
"mem_1790448247125520424"
|
||||
],
|
||||
"must_include_keywords": [
|
||||
"牧尘"
|
||||
],
|
||||
"category": "user_pref",
|
||||
"difficulty": "medium",
|
||||
"id_baseline": "mem_1789834428978989104"
|
||||
"id_baseline": "mem_1790448247125520424",
|
||||
"namespace": "hermes-main"
|
||||
},
|
||||
{
|
||||
"query": "如何根据牧尘的偏好调整记忆检索策略",
|
||||
"expected_ids": ["mem_1789190217889697697"],
|
||||
"must_include_keywords": ["记忆"],
|
||||
"expected_ids": [
|
||||
"mem_1791747597032219499"
|
||||
],
|
||||
"must_include_keywords": [
|
||||
"记忆"
|
||||
],
|
||||
"category": "user_pref",
|
||||
"difficulty": "hard",
|
||||
"id_baseline": "mem_1789190217889697697"
|
||||
"id_baseline": "mem_1791747597032219499",
|
||||
"namespace": "hermes-main"
|
||||
},
|
||||
{
|
||||
"query": "当前项目的技术栈是什么",
|
||||
"expected_ids": ["mem_1789680870868739202"],
|
||||
"must_include_keywords": ["技术栈"],
|
||||
"expected_ids": [
|
||||
"mem_1790455676397796671"
|
||||
],
|
||||
"must_include_keywords": [
|
||||
"技术栈"
|
||||
],
|
||||
"category": "proj_context",
|
||||
"difficulty": "easy",
|
||||
"id_baseline": "mem_1789680870868739202"
|
||||
"id_baseline": "mem_1790455676397796671",
|
||||
"namespace": "hermes-main"
|
||||
},
|
||||
{
|
||||
"query": "织忆项目有哪些核心组件",
|
||||
"expected_ids": ["mem_1789154058288011112"],
|
||||
"must_include_keywords": ["织忆"],
|
||||
"expected_ids": [
|
||||
"mem_1791906354849281414"
|
||||
],
|
||||
"must_include_keywords": [
|
||||
"织忆"
|
||||
],
|
||||
"category": "proj_context",
|
||||
"difficulty": "medium",
|
||||
"id_baseline": "mem_1789154058288011112"
|
||||
"id_baseline": "mem_1791906354849281414",
|
||||
"namespace": "hermes-main"
|
||||
},
|
||||
{
|
||||
"query": "织忆和其他记忆系统相比有什么架构优势",
|
||||
"expected_ids": ["mem_1789153726378940805"],
|
||||
"must_include_keywords": ["织忆"],
|
||||
"expected_ids": [
|
||||
"mem_1791666702950691634"
|
||||
],
|
||||
"must_include_keywords": [
|
||||
"织忆"
|
||||
],
|
||||
"category": "proj_context",
|
||||
"difficulty": "hard",
|
||||
"id_baseline": "mem_1789153726378940805"
|
||||
"id_baseline": "mem_1791666702950691634",
|
||||
"namespace": "hermes-main"
|
||||
},
|
||||
{
|
||||
"query": "如何使用 recall 接口",
|
||||
"expected_ids": ["mem_1787272787836687543"],
|
||||
"must_include_keywords": ["recall"],
|
||||
"expected_ids": [
|
||||
"mem_1791796178328736793"
|
||||
],
|
||||
"must_include_keywords": [
|
||||
"recall"
|
||||
],
|
||||
"category": "tool_usage",
|
||||
"difficulty": "easy",
|
||||
"id_baseline": "mem_1787272787836687543"
|
||||
"id_baseline": "mem_1791796178328736793",
|
||||
"namespace": "hermes-main"
|
||||
},
|
||||
{
|
||||
"query": "织忆有哪些管理工具",
|
||||
"expected_ids": ["mem_1789153726378940805"],
|
||||
"must_include_keywords": ["织忆"],
|
||||
"expected_ids": [
|
||||
"mem_1791666702950691634"
|
||||
],
|
||||
"must_include_keywords": [
|
||||
"织忆"
|
||||
],
|
||||
"category": "tool_usage",
|
||||
"difficulty": "medium",
|
||||
"id_baseline": "mem_1789153726378940805"
|
||||
"id_baseline": "mem_1791666702950691634",
|
||||
"namespace": "hermes-main"
|
||||
},
|
||||
{
|
||||
"query": "如何通过 API 扩展织忆功能",
|
||||
"expected_ids": ["mem_1789153726378940805"],
|
||||
"must_include_keywords": ["织忆"],
|
||||
"expected_ids": [
|
||||
"mem_1791666188168772049"
|
||||
],
|
||||
"must_include_keywords": [
|
||||
"织忆"
|
||||
],
|
||||
"category": "tool_usage",
|
||||
"difficulty": "hard",
|
||||
"id_baseline": "mem_1789153726378940805"
|
||||
"id_baseline": "mem_1791666188168772049",
|
||||
"namespace": "hermes-main"
|
||||
},
|
||||
{
|
||||
"query": "本地 llama 服务 8080 端口",
|
||||
"expected_ids": ["mem_1789229548476546193"],
|
||||
"must_include_keywords": ["8080"],
|
||||
"expected_ids": [
|
||||
"mem_1791423503359721152"
|
||||
],
|
||||
"must_include_keywords": [
|
||||
"8080"
|
||||
],
|
||||
"category": "target_knowledge",
|
||||
"difficulty": "easy",
|
||||
"id_baseline": "mem_1789229548476546193"
|
||||
"id_baseline": "mem_1791423503359721152",
|
||||
"namespace": "hermes-main"
|
||||
},
|
||||
{
|
||||
"query": "session-to-zhiyi.py 脚本名",
|
||||
"expected_ids": ["mem_1788977361686058470"],
|
||||
"must_include_keywords": ["session-to-zhiyi"],
|
||||
"expected_ids": [
|
||||
"mem_1791688470278719760"
|
||||
],
|
||||
"must_include_keywords": [
|
||||
"session-to-zhiyi"
|
||||
],
|
||||
"category": "target_knowledge",
|
||||
"difficulty": "easy",
|
||||
"id_baseline": "mem_1788977361686058470"
|
||||
"id_baseline": "mem_1791688470278719760",
|
||||
"namespace": "hermes-main"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// 织忆 MemoryWeave — routes 包测试隔离(两个护栏合并 · t_e5997ca4 + t_b7a8ed9c)
|
||||
//
|
||||
// ⚠️ 本文件是**两个 TestMain 的合并体**。两卡分支各自加了一个 TestMain:
|
||||
// · t_e5997ca4 → testmain_test.go(落盘点护栏)
|
||||
// · t_b7a8ed9c → scorecache_guard_test.go(打分缓存护栏)
|
||||
// 在各自分支上互不干扰,合并到 main 后同包两个 TestMain **编译冲突**
|
||||
// (multiple definitions of TestMain)⇒ 必须合进一个文件。
|
||||
// (此点由 t_b7a8ed9c 在 scorecache_guard_test.go 顶部预先标注;小怡合并时未读文件
|
||||
// 而漏看,由全套测试的 setup failed 拦下 —— 见 worklog 教训。)
|
||||
//
|
||||
// 护栏①:单元测试不得写到生产落盘点(t_e5997ca4)
|
||||
// ---------------------------------------------------------------
|
||||
// selfoptimize 包已有同款 TestMain 先例(曾实测:整套测试跑完把
|
||||
// /var/lib/memoryweave/dashboard.json 写成测试数字)。
|
||||
// gap close/repair 端点会触发 Dash.persist()(本地 JSON 兜底)⇒ 统一重定向到临时目录。
|
||||
//
|
||||
// 护栏②:默认关闭 distill 打分缓存(t_b7a8ed9c)
|
||||
// ---------------------------------------------------------------
|
||||
// 背景:distill 打分记忆化(0dc571d)+ Redis L2(36db9bb,键 zhiyi:distill-score:*,
|
||||
// TTL 168h)后,**本包 E2E 测试(zz_commit_conflict_gate_test.go)会读写生产 Redis**:
|
||||
// 第一次 run L2 miss → 真调 mock LLM 并把「测试内容哈希 → 结果」写进生产;
|
||||
// 7 天内后续 run L2 hit → LLM 被静默短路 → 数 LLM 调用次数的断言(base+1)必挂。
|
||||
// 实测 2026-10-17:TestCommitConflictGate_E2E 16.5s 固定 FAIL,
|
||||
// 「expected >= 1 LLM distill calls, got 0」。
|
||||
//
|
||||
// 治法(对齐项目门禁规矩③:加缓存必须给该包 TestMain 加关闭开关):
|
||||
// Setenv ZHIYI_SCORE_CACHE=0 —— distill.getScoreCache 的 Once 闭包**活读 env**
|
||||
// (包级变量在 init 时已定型,跨包设不了),本进程内缓存整体禁用:
|
||||
// 不读 L2(LLM 真被调用,计数断言有覆盖)、不写 L2(不再污染生产)。
|
||||
package routes
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
// 护栏①:落盘点重定向到临时目录(宁可测试直接失败,也不写生产落盘点)
|
||||
dir, err := os.MkdirTemp("", "routes-test-dash-*")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
_ = os.Setenv("ZHIYI_DASHBOARD_PATH", filepath.Join(dir, "dashboard.json"))
|
||||
|
||||
// 护栏②:关闭 distill 打分缓存(不读/不写生产 Redis L2)
|
||||
_ = os.Setenv("ZHIYI_SCORE_CACHE", "0")
|
||||
|
||||
code := m.Run()
|
||||
_ = os.RemoveAll(dir)
|
||||
os.Exit(code)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
// 织忆 MemoryWeave — 召回链路追踪端点(P0-1,2026-10-26)
|
||||
//
|
||||
// GET /api/v1/trace/<trace_id>
|
||||
//
|
||||
// 返回该次召回的:各阶段耗时(encode/coarse_search/fts_recall/bm25/rerank_fusion/mmr_select/
|
||||
// graph_expand/dedupe)、各通道贡献条数(channels)、每条结果的来源归因(items)、
|
||||
// status/partial_reason、scope、cache_hit/truncated。
|
||||
//
|
||||
// 数据来源:内存环形缓冲(最近 2000 条)+ JSONL 落盘(/var/lib/memoryweave/traces/),
|
||||
// 服务重启后仍可按 trace_id 回溯(落盘扫描)。
|
||||
package routes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/storage"
|
||||
)
|
||||
|
||||
// ── P0-3 召回硬超时:取消函数类型 + context.WithTimeout 包装 ──────────────
|
||||
// core.go Recall() 在 req.DeadlineMS>0 时需要带类型标记的取消函数,以便 defer 取消。
|
||||
// 2026-10-26 (t_e98cb1d6):此处补齐使 routes 包可编译(否则 routes 全包不可构建,
|
||||
// capRecallResults 的单测无法跑通)。这是缺失的声明,不是功能实现;P0-3 的 trace 完整
|
||||
// 接线(tr.Stage 埋点、tr 落盘)仍待 P0-3 本任务补齐。
|
||||
type ctxDeadlineFunc context.CancelFunc
|
||||
|
||||
func contextWithTimeout(ctx context.Context, timeout time.Duration) (context.Context, ctxDeadlineFunc) {
|
||||
c, cancel := context.WithTimeout(ctx, timeout)
|
||||
return c, ctxDeadlineFunc(cancel)
|
||||
}
|
||||
|
||||
// Trace 查询单条召回链路。路径形如 /api/v1/trace/tr_xxxx。
|
||||
func (a *API) Trace(w http.ResponseWriter, r *http.Request) {
|
||||
id := strings.TrimSpace(strings.TrimPrefix(r.URL.Path, "/api/v1/trace/"))
|
||||
if id == "" {
|
||||
respondErrorSchema(w, 400, "trace_id_required", "用法:GET /api/v1/trace/<trace_id>", 0)
|
||||
return
|
||||
}
|
||||
tr, ok := storage.GetTrace(id)
|
||||
if !ok {
|
||||
// 404 与「trace 过期/被环形缓冲覆盖」同义:调用方据此走「重新召回」而不是当成系统故障。
|
||||
respondErrorSchema(w, 404, "trace_not_found",
|
||||
"trace 不存在或已被环形缓冲覆盖(内存保留最近 2000 条,落盘按天分文件)", 0)
|
||||
return
|
||||
}
|
||||
respond(w, 200, tr)
|
||||
}
|
||||
@@ -42,8 +42,8 @@ type Trigger struct {
|
||||
Condition string `json:"condition"`
|
||||
Urgency float64 `json:"urgency"` // 0-1,越大越紧急
|
||||
Active bool `json:"active"`
|
||||
Paused bool `json:"paused"` // kill-switch
|
||||
Cooldown string `json:"cooldown"` // 冷却时间
|
||||
Paused bool `json:"paused"` // kill-switch
|
||||
Cooldown string `json:"cooldown"` // 冷却时间
|
||||
FailCount int `json:"fail_count"` // 连续失败计数
|
||||
LastFiredAt time.Time `json:"last_fired_at,omitempty"`
|
||||
Description string `json:"description"`
|
||||
@@ -189,5 +189,3 @@ func (tm *TriggerManager) RecordFail(id string) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -2,11 +2,16 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/selfoptimize"
|
||||
"github.com/xiaoxue/memoryweave/internal/storage"
|
||||
)
|
||||
|
||||
// TuningConfig 可自动调优的参数
|
||||
@@ -20,7 +25,16 @@ type TuningConfig struct {
|
||||
ConsolidateAfter int `json:"consolidate_after"` // N 条蒸馏后触发整合
|
||||
|
||||
// 历史调参记录
|
||||
history []TuningEvent
|
||||
history []TuningEvent
|
||||
|
||||
// lastSkipped 上一次 AutoTune 里「因指标不可用而跳过」的规则与原因。
|
||||
// 让外部能区分「健康所以没调」与「数据不可用所以没调」——后者需要修数据源,不是好事。
|
||||
lastSkipped []string
|
||||
|
||||
// lastMoveAt 每个参数上一次被改动的时间 —— 用于冷却(治棘轮)。
|
||||
lastMoveAt map[string]time.Time
|
||||
// persistEnabled 仅全局 Tuner 为 true;测试里构造的实例为 false ⇒ 不写盘。
|
||||
persistEnabled bool
|
||||
}
|
||||
|
||||
type TuningEvent struct {
|
||||
@@ -32,11 +46,149 @@ type TuningEvent struct {
|
||||
}
|
||||
|
||||
var Tuner = &TuningConfig{
|
||||
Diversity: 0.5,
|
||||
// ⚠️ 初值必须等于**真实消费方的默认值**,否则接线当天就改变生产行为:
|
||||
// Diversity 对齐 storage.DefaultMMRDiversity() 的 0.3(core.go 原硬编码),原为 0.5。
|
||||
Diversity: 0.3,
|
||||
DecayRate: 0.015,
|
||||
GapThreshold: 3,
|
||||
DistillInterval: 5,
|
||||
ConsolidateAfter: 50,
|
||||
|
||||
lastMoveAt: map[string]time.Time{},
|
||||
persistEnabled: true,
|
||||
}
|
||||
|
||||
// tuneCooldown 同一参数的调参冷却时间。
|
||||
// 为什么需要:**AutoTune 不幂等** —— 同一判据每调一次就推一步(实测连跑两次:
|
||||
// decay_rate 0.015→0.018→0.0216、distill_interval 5→4→3),直到撞上限。
|
||||
// 闭环每天跑一次 ⇒ 几天内把参数顶到极值。冷却把「持续推进」限制成
|
||||
// 「同一指标须持续越界多个窗口,才多次调整」。
|
||||
const tuneCooldown = 6 * time.Hour
|
||||
|
||||
// minTuningSamples 调参判据的最小样本数。
|
||||
// 为什么需要:小样本的比率噪声极大 —— 实测现网 recall_usefulness_rate 只有 9 个样本,
|
||||
// 8 好 1 坏 = 0.89,再来 1 个好评就 > 0.9 ⇒ 触发「降低 diversity」直接改生产参数。
|
||||
// 少样本不是证据。
|
||||
const minTuningSamples = 30
|
||||
|
||||
// ratioFor 取一个「可用于调参」的比率指标,不可用则返回 ok=false。
|
||||
//
|
||||
// 约定(internal/selfoptimize/selfoptimize.go:248-322):
|
||||
//
|
||||
// <name>_rate —— 比率值;**分母退化时返回 -1**(metricNA),既不是 0 也不是 1
|
||||
// <name>_samples —— 该比率的分母样本数
|
||||
// <name>_valid —— 分母是否非退化
|
||||
//
|
||||
// ⚠️ AutoTune 原先只比较数值,无视这套约定 ⇒ `-1` 会让规则对「无数据」**恒真**:
|
||||
//
|
||||
// gap_closure_rate = -1 < 0.5 ⇒「降低 gap 阈值」每轮都触发(按垃圾指标改生产参数)
|
||||
// recall_usefulness_rate 样本 9 条 ⇒ 一次偶然就改 Diversity
|
||||
//
|
||||
// 本函数把「无数据 / 退化 / 样本不足」三类一律判为不可用 —— 宁可不动。
|
||||
// ⚠️ 命名不是统一的:比率键为 `<base>_rate`,而 *样本/有效* 键挂在 **base** 上
|
||||
// 而不是带 _rate 的那个串上 —— 实际键是 `recall_usefulness_samples`,
|
||||
// 不是 `recall_usefulness_rate_samples`(我第一版就按后者拼,护栏静默失效、
|
||||
// 参数照样被改;新加的 tuning_guard_test.go 当场逮住)。
|
||||
// 且 `avg_distill_loss` 这类**值键本身不带 _rate 后缀** ⇒ 统一用 TrimSuffix 推 base。
|
||||
func ratioFor(metrics map[string]float64, valueKey string) (float64, bool) {
|
||||
base := strings.TrimSuffix(valueKey, "_rate")
|
||||
v, ok := metrics[valueKey]
|
||||
if !ok || v < 0 {
|
||||
return 0, false // 缺失 或 -1 哨兵 = 无数据
|
||||
}
|
||||
if valid, ok := metrics[base+"_valid"]; ok && valid == 0 {
|
||||
return 0, false // 分母退化
|
||||
}
|
||||
if samples, ok := metrics[base+"_samples"]; ok && samples < minTuningSamples {
|
||||
return 0, false // 样本不足以支撑判断
|
||||
}
|
||||
return v, true
|
||||
}
|
||||
|
||||
// canMove 判断某参数当前是否允许改动(冷却窗口内不许重复动 —— 治棘轮)。
|
||||
func (tc *TuningConfig) canMove(param string) bool {
|
||||
last, ok := tc.lastMoveAt[param]
|
||||
return !ok || time.Since(last) >= tuneCooldown
|
||||
}
|
||||
|
||||
func (tc *TuningConfig) markMove(param string) {
|
||||
if tc.lastMoveAt == nil {
|
||||
tc.lastMoveAt = map[string]time.Time{}
|
||||
}
|
||||
tc.lastMoveAt[param] = time.Now()
|
||||
}
|
||||
|
||||
// pushToConsumers 把当前参数推给**真实消费方**。
|
||||
// 🔴 这一步是「调参有没有用」的分水岭:2026-10-14 实测,此前 Tuner 的全部字段
|
||||
// 没有任何读者(全仓只有 3 处路由注册引用它)⇒ 调参改了数字、行为零变化。
|
||||
func (tc *TuningConfig) pushToConsumers() {
|
||||
storage.SetDefaultMMRDiversity(tc.Diversity)
|
||||
selfoptimize.SetGapThreshold(tc.GapThreshold)
|
||||
}
|
||||
|
||||
// tuningStatePath 持久化路径(可用 ZHIYI_TUNING_STATE 覆盖,便于测试/隔离)。
|
||||
func tuningStatePath() string {
|
||||
if p := os.Getenv("ZHIYI_TUNING_STATE"); p != "" {
|
||||
return p
|
||||
}
|
||||
return "/var/lib/memoryweave/tuning-state.json"
|
||||
}
|
||||
|
||||
type tuningState struct {
|
||||
Diversity float64 `json:"diversity"`
|
||||
GapThreshold int `json:"gap_threshold"`
|
||||
LastMoveAt map[string]string `json:"last_move_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
// persist 落盘(失败只告警,不影响调参本身)。
|
||||
func (tc *TuningConfig) persist() {
|
||||
if !tc.persistEnabled {
|
||||
return
|
||||
}
|
||||
st := tuningState{Diversity: tc.Diversity, GapThreshold: tc.GapThreshold,
|
||||
LastMoveAt: map[string]string{}, UpdatedAt: time.Now().Format(time.RFC3339)}
|
||||
for k, v := range tc.lastMoveAt {
|
||||
st.LastMoveAt[k] = v.Format(time.RFC3339)
|
||||
}
|
||||
data, err := json.MarshalIndent(st, "", " ")
|
||||
if err != nil {
|
||||
log.Printf("[tuning] 序列化失败: %v", err)
|
||||
return
|
||||
}
|
||||
if err := os.WriteFile(tuningStatePath(), data, 0o644); err != nil {
|
||||
log.Printf("[tuning] 落盘失败: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// load 启动时载入持久化参数(无文件则用默认值),并立即接线到消费方。
|
||||
// 没有这一步,重启即回默认 ⇒ 调参成果每次重启清零。
|
||||
func (tc *TuningConfig) load() {
|
||||
data, err := os.ReadFile(tuningStatePath())
|
||||
if err == nil {
|
||||
var st tuningState
|
||||
if json.Unmarshal(data, &st) == nil {
|
||||
if st.Diversity > 0 {
|
||||
tc.Diversity = st.Diversity
|
||||
}
|
||||
if st.GapThreshold > 0 {
|
||||
tc.GapThreshold = st.GapThreshold
|
||||
}
|
||||
for k, v := range st.LastMoveAt {
|
||||
if t, e := time.Parse(time.RFC3339, v); e == nil {
|
||||
if tc.lastMoveAt == nil {
|
||||
tc.lastMoveAt = map[string]time.Time{}
|
||||
}
|
||||
tc.lastMoveAt[k] = t
|
||||
}
|
||||
}
|
||||
log.Printf("[tuning] 已载入持久化参数 diversity=%.3f gap_threshold=%d(%s)",
|
||||
tc.Diversity, tc.GapThreshold, st.UpdatedAt)
|
||||
}
|
||||
}
|
||||
tc.mu.Lock()
|
||||
tc.pushToConsumers()
|
||||
tc.mu.Unlock()
|
||||
}
|
||||
|
||||
// AutoTune 基于仪表盘指标自动调参
|
||||
@@ -45,61 +197,103 @@ func (tc *TuningConfig) AutoTune(metrics map[string]float64) []TuningEvent {
|
||||
defer tc.mu.Unlock()
|
||||
|
||||
var events []TuningEvent
|
||||
skipped := make([]string, 0, 5)
|
||||
// 记一次「本规则为什么没跑」—— 让调用方能解释「为什么没调参」,
|
||||
// 而不是只回 no_changes_needed(后者无法区分「健康」与「数据不可用」)。
|
||||
note := func(rule, why string) {
|
||||
skipped = append(skipped, rule+": "+why)
|
||||
}
|
||||
|
||||
// 1. 召回命中率 < 0.5 → 提高 diversity(扩大搜索范围)
|
||||
if hitRate, ok := metrics["recall_hit_rate"]; ok && hitRate < 0.5 {
|
||||
// 1. 召回质量低 → 提高 diversity(扩大搜索范围)。
|
||||
// 2026-10-17:原信号 recall_hit_rate 已退役(恒=1、从不及 0.5 ⇒ 本安全阀长期死寂)。
|
||||
// 改用 recall_usefulness_rate(返回且被使用)作为召回质量的实时信号:< 0.5 ⇒ 召回太窄、扩大范围。
|
||||
hitRate, hitOK := ratioFor(metrics, "recall_usefulness_rate")
|
||||
if !hitOK {
|
||||
note("rule1_usefulness", "指标不可用(无数据/退化/样本<20)")
|
||||
}
|
||||
if hitOK && hitRate < 0.5 && !tc.canMove("diversity") {
|
||||
note("rule1_usefulness", "冷却中(距上次调整 <"+tuneCooldown.String()+")")
|
||||
}
|
||||
if hitOK && hitRate < 0.5 && tc.canMove("diversity") {
|
||||
newDiversity := tc.Diversity + 0.1
|
||||
if newDiversity > 1.0 {
|
||||
newDiversity = 1.0
|
||||
}
|
||||
events = append(events, recordTuning(tc, "diversity", tc.Diversity, newDiversity, "recall_hit_rate < 0.5"))
|
||||
events = append(events, recordTuning(tc, "diversity", tc.Diversity, newDiversity, "recall_usefulness_rate < 0.5"))
|
||||
tc.Diversity = newDiversity
|
||||
tc.markMove("diversity")
|
||||
}
|
||||
|
||||
// 2. 召回有用率 > 0.9 → 降低 diversity(更精准)
|
||||
if usefulRate, ok := metrics["recall_usefulness_rate"]; ok && usefulRate > 0.9 {
|
||||
usefulRate, usefulOK := ratioFor(metrics, "recall_usefulness_rate")
|
||||
if !usefulOK {
|
||||
note("rule2_usefulness", "指标不可用(无数据/退化/样本<30)")
|
||||
}
|
||||
if usefulOK && usefulRate > 0.9 && !tc.canMove("diversity") {
|
||||
note("rule2_usefulness", "冷却中(距上次调整 <"+tuneCooldown.String()+")")
|
||||
}
|
||||
if usefulOK && usefulRate > 0.9 && tc.canMove("diversity") {
|
||||
newDiversity := tc.Diversity - 0.05
|
||||
if newDiversity < 0.1 {
|
||||
newDiversity = 0.1
|
||||
}
|
||||
events = append(events, recordTuning(tc, "diversity", tc.Diversity, newDiversity, "recall_usefulness_rate > 0.9"))
|
||||
tc.Diversity = newDiversity
|
||||
tc.markMove("diversity")
|
||||
}
|
||||
|
||||
// 3. 废弃率 > 5/day → 提高衰减率(加快清理)
|
||||
if deprecated, ok := metrics["deprecated_per_day"]; ok && deprecated > 5 {
|
||||
newDecay := tc.DecayRate * 1.2
|
||||
if newDecay > 0.05 {
|
||||
newDecay = 0.05
|
||||
}
|
||||
events = append(events, recordTuning(tc, "decay_rate", tc.DecayRate, newDecay, "deprecated_per_day > 5"))
|
||||
tc.DecayRate = newDecay
|
||||
}
|
||||
// 3.(2026-10-14 移除)废弃率 → 提高衰减率。
|
||||
// 移除理由:这个方向危险。governance.NewForgetter 上方注释记载:
|
||||
// 「2026-09-07 方案A: 0.015→0.03 曾致误删(36天库龄下 0-recall 长记忆全被清, 405字CNB经验被删)」。
|
||||
// 自动调参朝这个方向推 = 把那条事故路重新铺上;而收益只是「加快清理」。
|
||||
// 若要恢复,必须先有「误删可回滚 + 删除前抽样人工确认」的保护,不能只靠阈值。
|
||||
|
||||
// 4. 缺口闭环率 < 0.5 → 降低 gap 阈值
|
||||
if gapRate, ok := metrics["gap_closure_rate"]; ok && gapRate < 0.5 {
|
||||
gapRate, gapOK := ratioFor(metrics, "gap_closure_rate")
|
||||
if !gapOK {
|
||||
note("rule4_gap_threshold", "指标不可用(无数据/退化/样本<30)")
|
||||
}
|
||||
if gapOK && gapRate < 0.5 && !tc.canMove("gap_threshold") {
|
||||
note("rule4_gap_threshold", "冷却中(距上次调整 <"+tuneCooldown.String()+")")
|
||||
}
|
||||
if gapOK && gapRate < 0.5 && tc.canMove("gap_threshold") {
|
||||
newThreshold := tc.GapThreshold - 1
|
||||
if newThreshold < 2 {
|
||||
newThreshold = 2
|
||||
}
|
||||
events = append(events, recordTuningInt(tc, "gap_threshold", tc.GapThreshold, newThreshold, "gap_closure_rate < 0.5"))
|
||||
tc.GapThreshold = newThreshold
|
||||
tc.markMove("gap_threshold")
|
||||
}
|
||||
|
||||
// 5. 蒸馏损失 > 0.3 → 更频繁蒸馏
|
||||
if loss, ok := metrics["avg_distill_loss"]; ok && loss > 0.3 {
|
||||
newInterval := tc.DistillInterval - 1
|
||||
if newInterval < 1 {
|
||||
newInterval = 1
|
||||
}
|
||||
events = append(events, recordTuningInt(tc, "distill_interval", tc.DistillInterval, newInterval, "avg_distill_loss > 0.3"))
|
||||
tc.DistillInterval = newInterval
|
||||
}
|
||||
// 5.(2026-10-14 移除)蒸馏损失 → 缩短蒸馏间隔。
|
||||
// 移除理由:**没有正确的消费方**。distill/engine.go:265 的 batchTimeout(5min)是
|
||||
// 「队列冻结兜底 ticker」(2026-10-06 修的「生产者停止即永久冻结」安全网),
|
||||
// **不是蒸馏节奏**。调安全网的周期治不了蒸馏质量 —— 接到错的地方比不接更坏。
|
||||
// 若将来真有「蒸馏节奏」消费者,再恢复本规则并接对目标。
|
||||
|
||||
tc.history = append(tc.history, events...)
|
||||
tc.lastSkipped = skipped
|
||||
if len(events) > 0 {
|
||||
tc.pushToConsumers() // 改了就必须接线,否则等于没改
|
||||
tc.persist() // 不落盘则重启即丢
|
||||
}
|
||||
return events
|
||||
}
|
||||
|
||||
// init 启动时载入持久化参数并接线(没有它:重启回默认 + 调参不生效)。
|
||||
func init() { Tuner.load() }
|
||||
|
||||
// LastSkipped 返回上一次调参里被跳过的规则及原因(只读快照)。
|
||||
func (tc *TuningConfig) LastSkipped() []string {
|
||||
tc.mu.RLock()
|
||||
defer tc.mu.RUnlock()
|
||||
out := make([]string, len(tc.lastSkipped))
|
||||
copy(out, tc.lastSkipped)
|
||||
return out
|
||||
}
|
||||
|
||||
func recordTuning(tc *TuningConfig, param string, oldVal, newVal float64, reason string) TuningEvent {
|
||||
return TuningEvent{
|
||||
Parameter: param,
|
||||
@@ -135,7 +329,8 @@ func (tc *TuningConfig) StatusHandler(w http.ResponseWriter, r *http.Request) {
|
||||
"distill_interval": tc.DistillInterval,
|
||||
"consolidate_after": tc.ConsolidateAfter,
|
||||
},
|
||||
"history": tc.history,
|
||||
"history": tc.history,
|
||||
"last_skipped": tc.lastSkipped,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -145,7 +340,11 @@ func (tc *TuningConfig) RunHandler(w http.ResponseWriter, r *http.Request) {
|
||||
events := tc.AutoTune(metrics)
|
||||
|
||||
if len(events) == 0 {
|
||||
respond(w, 200, map[string]string{"status": "no_changes_needed"})
|
||||
respond(w, 200, map[string]interface{}{
|
||||
"status": "no_changes_needed",
|
||||
// 区分「健康」与「数据不可用」:后者要修数据源,而不是当作一切正常。
|
||||
"skipped": tc.lastSkipped,
|
||||
})
|
||||
} else {
|
||||
respond(w, 200, map[string]interface{}{
|
||||
"status": "tuned",
|
||||
@@ -157,25 +356,34 @@ func (tc *TuningConfig) RunHandler(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// POST /api/v1/tuning/analytics — 运行因果分析
|
||||
func (tc *TuningConfig) AnalyticsHandler(w http.ResponseWriter, r *http.Request) {
|
||||
// 基于指标间的关系给出建议
|
||||
m := selfoptimize.Dash.Metrics()
|
||||
|
||||
suggestions := []string{}
|
||||
if m["recall_hit_rate"] < 0.5 && m["avg_distill_loss"] > 0.3 {
|
||||
suggestions = append(suggestions, "蒸馏质量低导致召回率低 — 建议检查 Embedding 模型")
|
||||
}
|
||||
if m["deprecated_per_day"] > 10 {
|
||||
suggestions = append(suggestions, "废弃率过高 — 正在流失大量记忆,检查冲突检测阈值")
|
||||
}
|
||||
if m["gap_closure_rate"] < 0.3 {
|
||||
suggestions = append(suggestions, "缺口闭环率过低 — Agent 未回应缺口学习请求")
|
||||
}
|
||||
if m["auto_resolve_rate"] < 0.5 {
|
||||
suggestions = append(suggestions, "自动裁决率低 — 规则覆盖不全,考虑扩展策略")
|
||||
}
|
||||
|
||||
suggestions := AnalyticsSuggestions(m)
|
||||
respond(w, 200, map[string]interface{}{
|
||||
"metrics": m,
|
||||
"suggestions": suggestions,
|
||||
})
|
||||
}
|
||||
|
||||
// AnalyticsSuggestions 依据指标间关系给出调优建议(纯函数,便于单测反例:N/A 不产生建议)。
|
||||
//
|
||||
// ⚠️ 每条建议的比率比较都必须先判 N/A(ratioFor 已封装:-1 哨兵 / valid=0 / 样本不足 ⇒ 不可用)。
|
||||
// 若直接 `m[key] < 阈值`,-1 会恒真 ⇒ 无数据也误报建议(本卡 t_c70f385c 事故面)。
|
||||
// deprecated_per_day 是计数(恒 ≥0,非比率),不走 ratioFor。
|
||||
func AnalyticsSuggestions(m map[string]float64) []string {
|
||||
suggestions := []string{}
|
||||
if hr, ok := ratioFor(m, "recall_usefulness_rate"); ok && hr < 0.5 {
|
||||
if dl, ok2 := ratioFor(m, "avg_distill_loss"); ok2 && dl > 0.3 {
|
||||
suggestions = append(suggestions, "蒸馏质量低导致召回率低 — 建议检查 Embedding 模型")
|
||||
}
|
||||
}
|
||||
if m["deprecated_per_day"] > 10 {
|
||||
suggestions = append(suggestions, "废弃率过高 — 正在流失大量记忆,检查冲突检测阈值")
|
||||
}
|
||||
if g, ok := ratioFor(m, "gap_closure_rate"); ok && g < 0.3 {
|
||||
suggestions = append(suggestions, "缺口闭环率过低 — Agent 未回应缺口学习请求")
|
||||
}
|
||||
if a, ok := ratioFor(m, "auto_resolve_rate"); ok && a < 0.5 {
|
||||
suggestions = append(suggestions, "自动裁决率低 — 规则覆盖不全,考虑扩展策略")
|
||||
}
|
||||
return suggestions
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
// AnalyticsSuggestions N/A 哨兵护栏 —— 反例 + 正向对照。
|
||||
//
|
||||
// 本卡 t_c70f385c:AnalyticsHandler 的建议 builder 原为裸 `m[key] < 阈值`,
|
||||
// -1 哨兵(样本不足/越界被拦)会让 `-1 < 0.5` 恒真 ⇒ 无数据也误报建议。
|
||||
// 现统一走 ratioFor(已封装 N/A + valid=0 + 样本不足判定)。
|
||||
package routes
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestAnalyticsSuggestions_NA_NoFiring 反例:全 N/A 哨兵(-1)不产生任何建议(避免误报)。
|
||||
func TestAnalyticsSuggestions_NA_NoFiring(t *testing.T) {
|
||||
na := map[string]float64{
|
||||
"recall_usefulness_rate": -1, "recall_usefulness_samples": 0, "recall_usefulness_valid": 0,
|
||||
"avg_distill_loss": -1, "avg_distill_loss_samples": 0, "avg_distill_loss_valid": 0,
|
||||
"gap_closure_rate": -1, "gap_closure_samples": 0, "gap_closure_valid": 0,
|
||||
"auto_resolve_rate": -1, "auto_resolve_samples": 0, "auto_resolve_valid": 0,
|
||||
"deprecated_per_day": 0,
|
||||
}
|
||||
if s := AnalyticsSuggestions(na); len(s) != 0 {
|
||||
t.Fatalf("全 N/A 不应产生任何建议,实际 %d 条: %v", len(s), s)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAnalyticsSuggestions_ValidLow 正向对照:有效且低于阈值时产生建议(护栏没把功能焊死)。
|
||||
func TestAnalyticsSuggestions_ValidLow(t *testing.T) {
|
||||
m := map[string]float64{
|
||||
"recall_usefulness_rate": 0.2, "recall_usefulness_samples": 100, "recall_usefulness_valid": 1,
|
||||
"gap_closure_rate": 0.1, "gap_closure_samples": 100, "gap_closure_valid": 1,
|
||||
"auto_resolve_rate": 0.2, "auto_resolve_samples": 100, "auto_resolve_valid": 1,
|
||||
"avg_distill_loss": 0.1, "avg_distill_loss_samples": 100, "avg_distill_loss_valid": 1,
|
||||
"deprecated_per_day": 0,
|
||||
}
|
||||
s := AnalyticsSuggestions(m)
|
||||
// 至少触发「gap 闭环率过低」+「自动裁决率低」两条
|
||||
if len(s) < 2 {
|
||||
t.Fatalf("有效且低于阈值应产生 ≥2 条建议,实际 %d 条: %v", len(s), s)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/selfoptimize"
|
||||
"github.com/xiaoxue/memoryweave/internal/storage"
|
||||
)
|
||||
|
||||
// TestAutoTuneGuard_SentinelAndSamples 双向验证护栏:
|
||||
// ① 无数据(-1 哨兵)不许改参数 —— 这是事故面:gap_closure_rate=-1 会让
|
||||
//
|
||||
// 「降低 gap 阈值」每轮恒真。
|
||||
//
|
||||
// ② 样本不足(<30)不许改参数 —— 少样本比率噪声极大。
|
||||
// ③ 数据健康时仍然要能调 —— 否则等于把功能焊死。
|
||||
func TestAutoTuneGuard_SentinelAndSamples(t *testing.T) {
|
||||
// ① 哨兵值:全 -1 ⇒ 一个事件都不许有
|
||||
tc := &TuningConfig{Diversity: 0.5, DecayRate: 0.015, GapThreshold: 3, DistillInterval: 5, ConsolidateAfter: 50}
|
||||
na := map[string]float64{
|
||||
"gap_closure_rate": -1,
|
||||
"gap_closure_samples": 0,
|
||||
"gap_closure_valid": 0,
|
||||
"recall_usefulness_rate": -1,
|
||||
"avg_distill_loss": -1,
|
||||
"recall_usefulness_valid": 0,
|
||||
"avg_distill_loss_valid": 0,
|
||||
}
|
||||
if ev := tc.AutoTune(na); len(ev) != 0 {
|
||||
t.Fatalf("哨兵值(-1)不应触发任何调参,实际触发 %d 条: %+v", len(ev), ev)
|
||||
}
|
||||
if tc.GapThreshold != 3 || tc.Diversity != 0.5 {
|
||||
t.Fatalf("参数被改动:GapThreshold=%d Diversity=%v", tc.GapThreshold, tc.Diversity)
|
||||
}
|
||||
if len(tc.LastSkipped()) == 0 {
|
||||
t.Fatal("应记录跳过原因(否则无法区分『健康』与『数据不可用』)")
|
||||
}
|
||||
|
||||
// ② 样本不足:比率本身达标(>0.9)但只有 9 个样本 ⇒ 不许动
|
||||
tc2 := &TuningConfig{Diversity: 0.5, DecayRate: 0.015, GapThreshold: 3, DistillInterval: 5, ConsolidateAfter: 50}
|
||||
low := map[string]float64{
|
||||
"recall_usefulness_rate": 0.95,
|
||||
"recall_usefulness_samples": 9,
|
||||
"recall_usefulness_valid": 1,
|
||||
}
|
||||
if ev := tc2.AutoTune(low); len(ev) != 0 {
|
||||
t.Fatalf("样本 9<30 不应触发调参,实际 %d 条: %+v", len(ev), ev)
|
||||
}
|
||||
|
||||
// ③ 数据健康 ⇒ 必须能调(证明护栏没把功能焊死)
|
||||
tc3 := &TuningConfig{Diversity: 0.5, DecayRate: 0.015, GapThreshold: 3, DistillInterval: 5, ConsolidateAfter: 50}
|
||||
good := map[string]float64{
|
||||
"recall_usefulness_rate": 0.95,
|
||||
"recall_usefulness_samples": 100,
|
||||
"recall_usefulness_valid": 1,
|
||||
}
|
||||
ev := tc3.AutoTune(good)
|
||||
if len(ev) != 1 {
|
||||
t.Fatalf("健康数据应触发 1 条调参,实际 %d 条", len(ev))
|
||||
}
|
||||
if tc3.Diversity >= 0.5 {
|
||||
t.Fatalf("Diversity 应被降低,实际 %v", tc3.Diversity)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutoTuneCooldown 冷却:同一参数在冷却窗口内不许被重复推进(治棘轮)。
|
||||
// 事故面(实测):AutoTune 不幂等 —— 连跑两次 decay 0.015→0.018→0.0216。
|
||||
func TestAutoTuneCooldown(t *testing.T) {
|
||||
tc := &TuningConfig{Diversity: 0.5, DecayRate: 0.015, GapThreshold: 3, DistillInterval: 5, ConsolidateAfter: 50}
|
||||
m := map[string]float64{
|
||||
"recall_usefulness_rate": 0.95,
|
||||
"recall_usefulness_samples": 100,
|
||||
"recall_usefulness_valid": 1,
|
||||
}
|
||||
if ev := tc.AutoTune(m); len(ev) != 1 {
|
||||
t.Fatalf("第一次应调 1 条,实际 %d", len(ev))
|
||||
}
|
||||
first := tc.Diversity
|
||||
if ev := tc.AutoTune(m); len(ev) != 0 {
|
||||
t.Fatalf("冷却窗口内不应再调,实际 %d 条: %+v", len(ev), ev)
|
||||
}
|
||||
if tc.Diversity != first {
|
||||
t.Fatalf("冷却期内参数被改动:%v → %v(棘轮复发)", first, tc.Diversity)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutoTunePushesToConsumers 推送:改完参数必须真的到消费方手里,
|
||||
// 否则就是「调参改了没人读的数字」(2026-10-14 实测的原状)。
|
||||
func TestAutoTunePushesToConsumers(t *testing.T) {
|
||||
orig := storage.DefaultMMRDiversity()
|
||||
defer storage.SetDefaultMMRDiversity(orig)
|
||||
tc := &TuningConfig{Diversity: 0.5, GapThreshold: 3}
|
||||
m := map[string]float64{
|
||||
"gap_closure_rate": 0.1,
|
||||
"gap_closure_samples": 100,
|
||||
"gap_closure_valid": 1,
|
||||
}
|
||||
before := selfoptimize.GapThreshold()
|
||||
ev := tc.AutoTune(m)
|
||||
if len(ev) != 1 {
|
||||
t.Fatalf("应触发 1 条(gap 阈值),实际 %d", len(ev))
|
||||
}
|
||||
if tc.GapThreshold != before-1 {
|
||||
t.Fatalf("期望阈值 %d→%d,实际 %d", before, before-1, tc.GapThreshold)
|
||||
}
|
||||
if got := selfoptimize.GapThreshold(); got != tc.GapThreshold {
|
||||
t.Fatalf("没推到消费方:selfoptimize.GapThreshold()=%d,Tuner=%d", got, tc.GapThreshold)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTuningPersistence 持久化:换实例后能从盘上读回(否则重启即回默认)。
|
||||
func TestTuningPersistence(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("ZHIYI_TUNING_STATE", dir+"/tuning-state.json")
|
||||
|
||||
a := &TuningConfig{Diversity: 0.42, GapThreshold: 4, persistEnabled: true, lastMoveAt: map[string]time.Time{}}
|
||||
a.persist()
|
||||
|
||||
b := &TuningConfig{Diversity: 0.3, GapThreshold: 3, lastMoveAt: map[string]time.Time{}}
|
||||
b.load()
|
||||
if b.Diversity != 0.42 || b.GapThreshold != 4 {
|
||||
t.Fatalf("未读回持久化参数:diversity=%v gap=%v", b.Diversity, b.GapThreshold)
|
||||
}
|
||||
}
|
||||
@@ -15,9 +15,9 @@ var upgrader = websocket.Upgrader{
|
||||
|
||||
// WSManager 管理所有 WebSocket 连接,支持按 AgentID 定向推送
|
||||
type WSManager struct {
|
||||
mu sync.RWMutex
|
||||
clients map[string]map[*websocket.Conn]bool // agentID → 连接集合
|
||||
connMu sync.Map // per-conn mutex: *websocket.Conn → *sync.Mutex
|
||||
mu sync.RWMutex
|
||||
clients map[string]map[*websocket.Conn]bool // agentID → 连接集合
|
||||
connMu sync.Map // per-conn mutex: *websocket.Conn → *sync.Mutex
|
||||
}
|
||||
|
||||
// 全局 WebSocket 管理器
|
||||
|
||||
@@ -65,7 +65,7 @@ func (m *mockLance) GetTopByQuality(agentID string, limit int) ([]models.MemoryR
|
||||
}
|
||||
func (m *mockLance) Stats() (map[string]interface{}, error) { return map[string]interface{}{}, nil }
|
||||
func (m *mockLance) SoftDelete(id, reason string) error { return nil }
|
||||
func (m *mockLance) PurgeInvalid() (int64, error) { return 0, nil }
|
||||
func (m *mockLance) PurgeInvalid() (int64, error) { return 0, nil }
|
||||
func (m *mockLance) SoftDeleteBatch(table string, ids []string, updatedAt string) (int64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
@@ -78,6 +78,17 @@ func (m *mockLance) Backup(path string) error { r
|
||||
func (m *mockLance) GetAuditLog(limit int) ([]map[string]interface{}, error) { return nil, nil }
|
||||
func (m *mockLance) IncrementUseful(id string) error { return nil }
|
||||
func (m *mockLance) IncrementNotUseful(id string) error { return nil }
|
||||
|
||||
// GA-P0-1 (t_718d8707):拆分字段
|
||||
func (m *mockLance) IncrementHumanNotUseful(id string) error { return nil }
|
||||
func (m *mockLance) AppendHitEvent(memoryID, outcome, reason string) error { return nil }
|
||||
func (m *mockLance) CountHitEvents(memoryID, outcome string, since time.Time) (int, error) {
|
||||
return 0, nil
|
||||
}
|
||||
func (m *mockLance) GetHitEvents(memoryID string, limit int) ([]models.HitEvent, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (m *mockLance) IncrementDedupDownweight(id string) error { return nil }
|
||||
func (m *mockLance) UpdateMemoryContent(id, newContent, source string) error { return nil }
|
||||
func (m *mockLance) InsertMemory(rec models.MemoryRecord) error { return nil }
|
||||
func (m *mockLance) Insert(table string, record any) error { return nil }
|
||||
@@ -109,6 +120,7 @@ func (mockGraph) ListNodesByType(nodeType string, namespace string) []map[string
|
||||
}
|
||||
func (mockGraph) ListNodes(namespace string) []map[string]interface{} { return nil }
|
||||
func (mockGraph) Stats() (int, int, float64) { return 0, 0, 0 }
|
||||
func (mockGraph) CountNodesByType(string) (int, int, string) { return 0, 0, "" }
|
||||
func (mockGraph) Prune(minWeight float64) {}
|
||||
func (mockGraph) ExpandFromResults(results []models.RecallResult, namespace string, maxHops int) []models.RecallResult {
|
||||
return results
|
||||
|
||||
+408
-58
@@ -21,10 +21,14 @@ import (
|
||||
"github.com/xiaoxue/memoryweave/internal/api/routes"
|
||||
"github.com/xiaoxue/memoryweave/internal/distill"
|
||||
"github.com/xiaoxue/memoryweave/internal/governance"
|
||||
"github.com/xiaoxue/memoryweave/internal/memprotect"
|
||||
"github.com/xiaoxue/memoryweave/internal/metrics"
|
||||
"github.com/xiaoxue/memoryweave/internal/models"
|
||||
"github.com/xiaoxue/memoryweave/internal/pattern"
|
||||
"github.com/xiaoxue/memoryweave/internal/peer"
|
||||
"github.com/xiaoxue/memoryweave/internal/redact"
|
||||
"github.com/xiaoxue/memoryweave/internal/selfoptimize"
|
||||
"github.com/xiaoxue/memoryweave/internal/skillgen"
|
||||
"github.com/xiaoxue/memoryweave/internal/storage"
|
||||
)
|
||||
|
||||
@@ -53,11 +57,28 @@ func NewServer() http.Handler {
|
||||
// 存储后端
|
||||
ldb := initStorageBackend(os.Getenv("STORAGE_BACKEND"), emb)
|
||||
|
||||
// 2026-10-13 (t_e9a4d18f P2) 常设答案库(独立 SQLite,Hindsight mental models)。
|
||||
// 只读写不主动注入 ⇒ 部署后行为零变化。注入由 zhiyi-standing-answers.py 生成后
|
||||
// 插件侧决定是否直读。路径可经 ZHIYI_STANDING_DB 覆盖。
|
||||
storage.InitStandingStore(os.Getenv("ZHIYI_STANDING_DB"))
|
||||
|
||||
// 召回元数据「累积延迟更新」缓冲(2026-09-12 优化B)
|
||||
// 读路径不再逐条写 LanceDB(MVCC 每写一行一个版本 → _versions 膨胀根因),
|
||||
// 改为窗口内合并 + 单事务批量提交(每批 1 个版本)。
|
||||
storage.InitRecallWriteBuffer(ldb)
|
||||
|
||||
// 2026-10-14 (t_2afae95e) FTS 词面通道:给 TF-IDF 索引挂全量数据源(ScanAll,
|
||||
// 只读 IPC lancedb_scan_all;不建 LanceDB tantivy 索引文件 ⇒ 零写 LanceDB)。
|
||||
// 索引本体在 storage 包内后台建(启动 3s 首建 + 6h 周期 + 写路径标脏)。
|
||||
// 门控 ZHIYI_RECALL_FTS 默认关 ⇒ 接线了也不改召回行为(AC4 零变化)。
|
||||
if rc, ok := ldb.(*storage.RustLanceDBClient); ok {
|
||||
storage.FtsProvider.FtsLdb = rc.ScanAll
|
||||
log.Printf("[fts] 词面通道数据源已挂(ScanAll);门控 ZHIYI_RECALL_FTS=%s(默认关)",
|
||||
os.Getenv("ZHIYI_RECALL_FTS"))
|
||||
} else {
|
||||
log.Printf("[fts] 后端非 RustLanceDBClient(%T)⇒ 词面通道数据源未挂(关态无影响)", ldb)
|
||||
}
|
||||
|
||||
// 软删除累积延迟更新缓冲(2026-09-12 优化C)
|
||||
// 软删除操作不再逐条写 LanceDB(每写一行一个版本 → _versions 膨胀),
|
||||
// 改为窗口内合并 + 单事务批量提交(每批 1 个版本)。
|
||||
@@ -72,7 +93,13 @@ func NewServer() http.Handler {
|
||||
// 冲突检测器(E4.1: Commit 时矛盾检测依赖此实例)
|
||||
// 2026-09-20:改用带持久化的构造 —— 此前 active 是纯内存 map,zhiyid 重启即丢
|
||||
// (实测 17:17 重启后 pending 冲突全部消失)。落盘失败不致命,降级为内存模式并记日志。
|
||||
conflictDetector, cdErr := governance.NewPersistentConflictDetector("/var/lib/memoryweave/conflicts.json")
|
||||
// 2026-10-18 (t_23b6a940):ZHIYI_CONFLICTS_DIR 覆盖落盘目录(副本/评估场景隔离
|
||||
// telemetry 写);未设 → 生产默认路径(行为不变)
|
||||
confDir := os.Getenv("ZHIYI_CONFLICTS_DIR")
|
||||
if confDir == "" {
|
||||
confDir = "/var/lib/memoryweave"
|
||||
}
|
||||
conflictDetector, cdErr := governance.NewPersistentConflictDetector(filepath.Join(confDir, "conflicts.json"), filepath.Join(confDir, "conflict-seen.json"))
|
||||
if cdErr != nil {
|
||||
log.Printf("[conflict] 持久化加载失败,降级为内存模式: %v", cdErr)
|
||||
}
|
||||
@@ -112,6 +139,17 @@ func NewServer() http.Handler {
|
||||
}
|
||||
}()
|
||||
|
||||
// t_cf680fad:启动即 drain durable pending-softdelete 队列。
|
||||
// 上一轮(尤其重启窗口 / 崩掉那轮)因 MVCC 写风暴耗尽而被入队的失败软删,
|
||||
// 此刻风暴已退、sidecar 刚就绪,重放必落盘 —— 这是「不修则每次重启窗口都留新残留」的根治。
|
||||
go func() {
|
||||
time.Sleep(2 * time.Second) // 等 sidecar 完全就绪(比 metrics 的 1s 稍晚,避免抢首提交)
|
||||
if n := storage.PendingSoftDeleteCount(); n > 0 {
|
||||
log.Printf("[pending-softdelete] 启动发现 %d 条待重放,开始 drain", n)
|
||||
storage.DrainPendingSoftDeletes(ldb)
|
||||
}
|
||||
}()
|
||||
|
||||
// 图谱(带 Navigate 结果缓存:TTL 5min,容量 500,热点实体缓存命中加速)
|
||||
// 已在上面初始化
|
||||
graphUpdater := governance.NewAutoGraphUpdater(graphStore)
|
||||
@@ -147,6 +185,45 @@ func NewServer() http.Handler {
|
||||
consolPipe := routes.NewConsolidationPipeline(ldb, graphStore, conflictDetector)
|
||||
consolPipe.SetDataDir("/var/lib/memoryweave/lancedb", "/var/lib/memoryweave/graph.db")
|
||||
|
||||
// ─── t_d32e5f8a L2 模式检测(MemOS 血统)─────────────────────────
|
||||
// 复活 L1→L2 pattern 蒸馏(原 Python daemon main_loop 退役后停摆):
|
||||
// pattern 节点存 graph_nodes(type='pattern'),与旧 daemon 残留的 85 行
|
||||
// type='pattern_stat' 同表但不同类,不另开新表。
|
||||
// modernc sqlite 短命单发开/关(UpsertPatterns/ListPatterns 开一次用一次即关),
|
||||
// 不持长连接、不碰 state.db —— 规避当年退役根因。
|
||||
// 召回注入 env 门控 ZHIYI_PATTERN_RECALL,默认 0 ⇒ 不注册 Provider,行为零变化。
|
||||
graphPath := os.Getenv("GRAPH_PATH")
|
||||
if graphPath == "" {
|
||||
graphPath = "/var/lib/memoryweave/graph.db"
|
||||
}
|
||||
patternStore := pattern.NewGraphPatternStore(graphPath)
|
||||
patternProvider := pattern.NewPatternProvider(patternStore, pattern.NewEmbedderProvider(emb))
|
||||
patternAPI := routes.NewPatternAPI(patternStore, patternProvider, func() storage.LanceDB { return ldb })
|
||||
// L3 skill 草稿(t_fcadee04):装配生成器 + skills 表(graph.db 同库)+ 落盘根。
|
||||
// 显式 API(draft/promote)触发,不挂 cron、不改注入行为 ⇒ 默认零行为变化。
|
||||
patternAPI.SkillStore = skillgen.NewStore(graphPath)
|
||||
patternAPI.Generator = skillgen.NewLocal2BGenerator()
|
||||
patternAPI.AttachmentsDir = os.Getenv("ZHIYI_SKILL_ATTACHMENTS")
|
||||
if os.Getenv("ZHIYI_PATTERN_RECALL") == "1" {
|
||||
storage.PatternRecallProvider = patternProvider.Match
|
||||
log.Printf("[zhiyid] L2 模式召回注入已启用(ZHIYI_PATTERN_RECALL=1)")
|
||||
} else {
|
||||
log.Printf("[zhiyid] L2 模式召回注入默认关(ZHIYI_PATTERN_RECALL 未设/≠1 ⇒ 零行为变化)")
|
||||
}
|
||||
|
||||
// ─── t_f8fc97e6 P3 Peer Representation(Honcho 血统,设计 §5)────────────
|
||||
// 四层推理画像(explicit→deductive→inductive→abductive)存 graph.db 的 peers 表。
|
||||
// refresh/explain 是显式 API(不挂 cron);召回注入 env 门控 ZHIYI_PEER_RECALL 默认 0
|
||||
// ⇒ 主召回管线默认零行为变化(AC2)。推理引擎生产复用本地 2B(8081 免费腿)。
|
||||
peerStore := peer.NewStore(graphPath)
|
||||
peerAPI := routes.NewPeerAPI(peerStore, peer.NewLocal2BReasoner(), func() storage.LanceDB { return ldb }, graphStore)
|
||||
if os.Getenv("ZHIYI_PEER_RECALL") == "1" {
|
||||
storage.PeerRecallProvider = peerAPI.GetRecallResults
|
||||
log.Printf("[zhiyid] P3 Peer 推理画像召回注入已启用(ZHIYI_PEER_RECALL=1)")
|
||||
} else {
|
||||
log.Printf("[zhiyid] P3 Peer 推理画像召回注入默认关(ZHIYI_PEER_RECALL 未设/≠1 ⇒ 零行为变化)")
|
||||
}
|
||||
|
||||
// Obsidian
|
||||
obsidian := routes.NewObsidianSyncer("", ldb)
|
||||
|
||||
@@ -162,6 +239,14 @@ func NewServer() http.Handler {
|
||||
}
|
||||
distillEngine := distill.NewEngine(llmEndpoint, llmModel, llmAPIKey)
|
||||
routes.DistillEngineRef = distillEngine
|
||||
// t_e11207f8 治源①:加载共享「空壳正文」判据(zhiyi_payload_guard_rules.json,Python/Go 同源)。
|
||||
// 失败 ⇒ fail-open(distill 照跑、不拦空壳、不崩),/api/v1/payload-guard/stats 暴露 loaded=false。
|
||||
if ok, lerr := distill.LoadPayloadGuard(""); ok {
|
||||
_, _, _, rp := distill.PayloadGuardStats()
|
||||
log.Printf("[distill][payload-guard] 空壳判据已加载 rules=%s", rp)
|
||||
} else {
|
||||
log.Printf("[distill][payload-guard] ⚠️ 共享判据未加载(fail-open,不拦空壳): %v", lerr)
|
||||
}
|
||||
// 蒸馏完成 → 自动图谱更新 + 冲突检测 + 被动验证 + 回写内存
|
||||
distill.OnDistillComplete = func(input distill.DistillInput, result distill.DistillResult) {
|
||||
entityNames := make([]string, len(result.Entities))
|
||||
@@ -172,27 +257,57 @@ func NewServer() http.Handler {
|
||||
Content: input.Content, Facts: result.Facts,
|
||||
Entities: entityNames, Namespace: input.Namespace,
|
||||
EpisodeID: input.EpisodeID,
|
||||
Source: input.Source, // 2026-10-12 t_67d0279a 方案A:来源分档透传(auditSource 前缀归一后比对)
|
||||
})
|
||||
|
||||
// 回写蒸馏产物到记忆库(LanceDB)
|
||||
// 2026-09-07 方案B 质量门槛: 碎片(<20字)/噪声句(状态汇报/桥接/reflection)不入库,
|
||||
// 与已有记忆完全重复跳过(蒸馏直写不走 commit exact_dup, 需本层查重)。
|
||||
for _, fact := range result.Facts {
|
||||
// 2026-09-10 P0:直写路径同样脱敏(这里绕过 FilterQualityFacts,
|
||||
// 事故里泄漏进镜像的记忆正是从这条路径入库的)。
|
||||
// 2026-10-13 t_1c12e000:distilled facts 是 memories 表的唯一写入点。
|
||||
// 只要有任何一条真的 InsertMemory 成功 ⇒ 该 namespace 的 query 缓存作废
|
||||
//("先写再问" 场景:写完之后立刻可被之前问过但当时还没内容的答案命中)。
|
||||
factsLanded := false
|
||||
// 2026-10-13 t_286d1310: 写库闸门同样感知准入分诊结论(lane)。
|
||||
// 此前这里独立跑 IsQualityFact 长度启发式——lane=keep 的决策类内容,
|
||||
// 其 <20 字碎片在 insert 前仍被第三次独立丢弃(t_2ae69bb2 只穿透到
|
||||
// fact 级,没穿透到写库级)⇒ DB 里 derived_from=<episode> 0 行。
|
||||
// 复用 engine.go 同一函数 FilterQualityFactsWithLane(判据单一入口,
|
||||
// 不复制):
|
||||
// LaneKeep → 只保留 纯疑问/状态汇报 两条硬否定,跳过全部长度类规则
|
||||
// LaneDrop / LaneObserve → 委托 FilterQualityFacts,与 IsQualityFact 逐字一致
|
||||
// ClassifyAdmission 是确定性分诊(同一输入永远同一 lane),此处重算即
|
||||
// engine.go:537 在蒸馏时算出的同一条 lane。
|
||||
lane, laneWhy := distill.ClassifyAdmission(input.Content)
|
||||
writeFacts := distill.FilterQualityFactsWithLane(result.Facts, lane)
|
||||
if before := len(result.Facts); before > 0 && len(writeFacts) != before {
|
||||
log.Printf("[distill][LANE] write-gate dropped %d/%d facts for %s (lane=%s, %s)",
|
||||
before-len(writeFacts), before, input.EpisodeID, lane, laneWhy)
|
||||
}
|
||||
for _, fact := range writeFacts {
|
||||
// 2026-09-10 P0:直写路径同样脱敏(FilterQualityFactsWithLane 已内部脱敏,
|
||||
// 这里再脱一次为幂等保险——防止任何中间层注入明文密钥。事故里泄漏进
|
||||
// 镜像的记忆正是从这条路径入库的)。
|
||||
fact = redact.RedactSecrets(fact)
|
||||
if !distill.IsQualityFact(fact) {
|
||||
continue // 碎片/噪声过滤
|
||||
// t_e11207f8 治源①:空壳拒写(单一判据 = 共享 zhiyi_payload_guard_rules.json,与 Python 同源)。
|
||||
// 蒸馏 LLM 偶发把「只有溯源指针/占位/纯日期、无知识载荷」的碎片当 fact(如 `证据:文件:…|日期:…`),
|
||||
// 长度/实体启发式(IsQualityFact)抓不住 ⇒ 落库前用 payload-guard 拦下(未加载时 fail-open)。
|
||||
if distill.ShellCheck(fact) {
|
||||
log.Printf("[distill][payload-guard] 拒写空壳蒸馏 fact episode=%s fact=%.40s", input.EpisodeID, fact)
|
||||
continue
|
||||
}
|
||||
// 查重: 同 namespace 已存在**语义等价**记忆 → 跳过
|
||||
// 必须用 cosine 近重复判据(≥0.98),不能只比字符串相等——
|
||||
// 否则 "牧尘在招商局工作" 与 "牧尘在招商局工作。"(多一个句号)
|
||||
// 会被判为两条不同事实双双入库,造成近重复堆积。
|
||||
var skip bool
|
||||
if qvec, eErr := emb.EncodeSingle(fact); eErr == nil {
|
||||
if sim, _ := ldb.Search("memories", qvec, 5, input.Namespace); len(sim) > 0 {
|
||||
for _, ex := range sim {
|
||||
if ex.Content == fact || cosineSimilarity(qvec, ex.Vector) >= 0.98 {
|
||||
var qvec []float32
|
||||
var sim []models.MemoryRecord
|
||||
if v, eErr := emb.EncodeSingle(fact); eErr == nil {
|
||||
qvec = v
|
||||
if found, _ := ldb.Search("memories", v, 5, input.Namespace); len(found) > 0 {
|
||||
sim = found
|
||||
for _, ex := range found {
|
||||
if ex.Content == fact || cosineSimilarity(v, ex.Vector) >= 0.98 {
|
||||
skip = true
|
||||
break
|
||||
}
|
||||
@@ -202,6 +317,38 @@ func NewServer() http.Handler {
|
||||
if skip {
|
||||
continue
|
||||
}
|
||||
// 2026-10-14 (t_3e98b65a):写时四操作判定(影子默认 ⇒ 零行为变化)。
|
||||
// 蒸馏产出的每条候选事实,对照 top-5 相似现有记忆判 ADD/UPDATE/NOOP/CONFLICT:
|
||||
// shadow:只记影子日志(本文件 write_ops.go),不真改库;apply:按判定执行。
|
||||
// 复用上面已算出的 qvec/sim(不重复编码),hash 去重兜底在 JudgeWriteOp 前。
|
||||
// t_a0831457 P0 解耦:门控**只决定标记动作**(supersede/conflict);基础
|
||||
// InsertMemory 是 pre-feature 基线行为,必须无条件执行(shadow/off 下
|
||||
// ApplyWriteOp 恒返回 shouldInsert=true ⇒ 下方不再 continue ⇒ 基础插入照跑)。
|
||||
// 唯一丢弃路径 = apply + NOOP(显式记 warning,含候选内容,禁静默)。
|
||||
if distill.WriteOpsEnabled() {
|
||||
if dupID, dup := distill.WriteOpHashDedup(fact, sim); dup {
|
||||
log.Printf("%s", distill.DedupNote(dupID, fact))
|
||||
continue
|
||||
}
|
||||
sims := distill.FromMemoryRecords(sim, qvec)
|
||||
verdict := distill.JudgeWriteOp(fact, sims.TopN(5), nil, nil)
|
||||
if verdict != nil {
|
||||
shouldInsert, err := distill.ApplyWriteOp(*verdict, &ldbWriteOpsStore{ldb: ldb}, memIDFor(fact, input))
|
||||
if err != nil {
|
||||
// apply 标记失败(MarkSuperseded/MarkConflict 落库失败):
|
||||
// 丢弃本条(不做半截标记),显式记 warning(禁静默失败)。
|
||||
log.Printf("[write-ops] apply 标记失败,本条事实丢弃: %v candidate=%.40s", err, fact)
|
||||
continue
|
||||
}
|
||||
if !shouldInsert {
|
||||
// 唯一丢弃路径:apply + NOOP(影子/off 不会到这里,见上)
|
||||
log.Printf("[write-ops] apply NOOP 丢弃事实(判定=NOOP,候选=%.40s)", fact)
|
||||
continue
|
||||
}
|
||||
}
|
||||
// verdict==nil(off 未跑判定;理论死分支——off 不进 WriteOpsEnabled 块)
|
||||
// 或 shadow(标记零调用)⇒ 基础插入无条件执行。
|
||||
}
|
||||
mem := models.MemoryRecord{
|
||||
ID: fmt.Sprintf("mem_%d", time.Now().UnixNano()),
|
||||
AgentID: input.AgentID,
|
||||
@@ -214,18 +361,43 @@ func NewServer() http.Handler {
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
DerivedFrom: input.EpisodeID,
|
||||
// 2026-10-13 (t_e9a4d18f P1) 证据链:全量来源 episode ID(蒸馏直写当前单亲,
|
||||
// 单条证据;多 episode 聚合由 consolidate 路径补充)
|
||||
SourceEvents: []string{input.EpisodeID},
|
||||
Freshness: "fresh",
|
||||
Source: srcOrLLMDistill(input.Source), // 2026-09-26:有笔记出处→"wiki:<路径>";否则沿用 llm_distill(2026-09-07 方案C provenance)
|
||||
// 2026-10-08 (t_7e3577c5):血缘字段——写入方经 metadata 携带;缺省兜底
|
||||
// embedding_model→bge-m3(实际嵌入模型),script_version→unknown。
|
||||
EmbeddingModel: orDefault(input.EmbeddingModel, "bge-m3"),
|
||||
ScriptVersion: orDefault(input.ScriptVersion, "unknown"),
|
||||
}
|
||||
// 2026-10-08 (t_7e3577c5):血缘字段——写入方经 metadata 携带;缺省兜底
|
||||
// embedding_model→bge-m3(实际嵌入模型),script_version→unknown。
|
||||
EmbeddingModel: orDefault(input.EmbeddingModel, "bge-m3"),
|
||||
ScriptVersion: orDefault(input.ScriptVersion, "unknown"),
|
||||
// 2026-10-08 (Gap#2):信任等级透传到产物(nil 保持 NULL,不伪装 0.0)
|
||||
Confidence: input.Confidence,
|
||||
ConfidenceSource: input.ConfidenceSource,
|
||||
// 2026-10-14 (t_3ada332b):bi-temporal 有效期 + provenance。写时识别时间敏感事实
|
||||
// (含「这周/临时/截止/到 X 之前」等)自动填 valid_to(区间末端);来源归一 provenance
|
||||
// (user|inferred|import)。开关默认关 ZHIYI_BITEMPORAL=0 ⇒ 读路径行为零变化。
|
||||
ValidFrom: time.Now().Format(time.RFC3339),
|
||||
ValidTo: distill.DetectValidTo(fact, time.Now()),
|
||||
Provenance: distill.DetectProvenance(input.Source),
|
||||
}
|
||||
log.Printf("[srcprobe] 蒸馏落库 episode=%s input.Source=%q → mem.Source=%q", input.EpisodeID, input.Source, mem.Source)
|
||||
if err := ldb.InsertMemory(mem); err != nil {
|
||||
log.Printf("[distill] commit fact failed: %v", err)
|
||||
} else {
|
||||
factsLanded = true // t_1c12e000:确有 distilled fact 落库
|
||||
}
|
||||
}
|
||||
// t_1c12e000:写路径缓存失效(方案 A)——distilled facts 是 memories 唯一写点。
|
||||
// 本进程 Invalidate(ns) 清 L1+L2;跨 Agent 广播复用 commit handler 的
|
||||
// PushCacheInvalidate(已注册 cache.invalidate 订阅),此处不重复广播。
|
||||
if factsLanded && storage.SearchCacheInstance != nil {
|
||||
storage.SearchCacheInstance.Invalidate(input.Namespace)
|
||||
log.Printf("[cache] 蒸馏落库后失效 namespace=%s(%d 条 facts,episode=%s)",
|
||||
input.Namespace, len(result.Facts), input.EpisodeID)
|
||||
// 2026-10-14 (t_2afae95e):FTS 词面索引同步标脏(惰性重建,
|
||||
// 下次词面查询时后台刷;关态下只是置一个 bool,零成本)
|
||||
storage.FtsInvalidate()
|
||||
}
|
||||
// 冲突检测:加载已有记忆进行比较
|
||||
// 必须用**新内容的真实向量**做语义检索取近邻;用零向量在语义索引上
|
||||
// 返回的只是"范数最小"的任意行,真正的矛盾对象不在比对集里 → 永远检不出冲突。
|
||||
@@ -242,8 +414,13 @@ func NewServer() http.Handler {
|
||||
conflictExisting := make([]map[string]interface{}, 0)
|
||||
for _, m := range existingMems {
|
||||
conflictExisting = append(conflictExisting, map[string]interface{}{
|
||||
"content": m.Content,
|
||||
"entities": entityNames, // 用当前内容提取的实体做交叉比较
|
||||
"content": m.Content,
|
||||
// 2026-10-09 修:此处原先填的是**新内容的实体**(同一个 entityNames 切片),
|
||||
// 导致 Scan 的实体预筛 e1==e2 恒真、彻底失效 —— 每条候选都跑全量比对,
|
||||
// 无关候选被纳入后 IsContradiction 误报(/var/lib/memoryweave/
|
||||
// conflicts-false-positive-*.json 现存 106 条已判假阳性即此产物)。
|
||||
// 改为**每条候选自己的实体**(从其正文抽取,与其它已存记忆同口径)。
|
||||
"entities": governance.ExtractEntities(m.Content),
|
||||
})
|
||||
}
|
||||
for _, c := range conflictDetector.Scan(input.Content, entityNames, conflictExisting) {
|
||||
@@ -291,6 +468,12 @@ func NewServer() http.Handler {
|
||||
|
||||
// 注入 V 值查询函数到存储层(召回排序融合)
|
||||
storage.VValueProvider = func(memoryID string) float64 {
|
||||
// 2026-10-13:ep_* 是蒸馏自证(恒 1.0),零区分度且淹没真实 mem_* 信号
|
||||
// (实测 ep_* 4304 个 vs mem_* 24 个)。召回目标全是 mem_*,ep_* 的 V 值
|
||||
// 不参与排序即可,无需删 Redis 数据(保留可回溯)。
|
||||
if strings.HasPrefix(memoryID, "ep_") {
|
||||
return 0
|
||||
}
|
||||
return vPropagator.GetMemVValue(memoryID)
|
||||
}
|
||||
// 在蒸馏完成回调中记录 V 值
|
||||
@@ -308,8 +491,8 @@ func NewServer() http.Handler {
|
||||
"distill", "success", "",
|
||||
)
|
||||
}
|
||||
// 更新仪表盘指标
|
||||
selfoptimize.Dash.RecordUseful()
|
||||
// 更新仪表盘指标:蒸馏成功次数(2026-10-14 t_c06ad4d0 改,勿再灌 UsefulCount)
|
||||
selfoptimize.Dash.RecordDistillSuccess()
|
||||
// 记录蒸馏质量损失(avg_distill_loss = 1 - Overall)
|
||||
// 仅记录真实蒸馏:Overall > 0 表示 LLM 成功返回,过滤 fallback (Overall=0)
|
||||
if result.Overall > 0 {
|
||||
@@ -337,15 +520,55 @@ func NewServer() http.Handler {
|
||||
|
||||
mux.HandleFunc("/health", routes.HandleHealth)
|
||||
mux.HandleFunc("/api/v1/health", routes.HandleHealth)
|
||||
// 图谱缓存统计
|
||||
// t_e11207f8 治源①:空壳拦截器「确实跑过」的取证端点。
|
||||
// checks=每个蒸馏 fact 判一次的心跳计数(>0 即拦截器活着);blocks=实际拒写空壳条数;
|
||||
// loaded=false 表示共享判据没加载上(fail-open,需排查 ZHIYI_PAYLOAD_GUARD_RULES 路径)。
|
||||
mux.HandleFunc("/api/v1/payload-guard/stats", func(w http.ResponseWriter, r *http.Request) {
|
||||
checks, blocks, loaded, rp := distill.PayloadGuardStats()
|
||||
respondJSON(w, 200, map[string]interface{}{
|
||||
"checks": checks,
|
||||
"blocks": blocks,
|
||||
"loaded": loaded,
|
||||
"rules_path": rp,
|
||||
})
|
||||
})
|
||||
// 图谱缓存统计 + 搜索缓存统计(t_1c12e000:并入 search_cache 段,
|
||||
// 暴露 hits/misses/invalidated/size/ttl,写频对命中率的影响可观测)
|
||||
mux.HandleFunc("/api/v1/cache/stats", func(w http.ResponseWriter, r *http.Request) {
|
||||
if cachedGraphStoreRef != nil {
|
||||
respondJSON(w, 200, map[string]interface{}{
|
||||
"graph_cache": cachedGraphStoreRef.Stats(),
|
||||
})
|
||||
} else {
|
||||
respondJSON(w, 200, map[string]interface{}{"graph_cache": nil})
|
||||
resp := map[string]interface{}{
|
||||
"graph_cache": nil,
|
||||
}
|
||||
if cachedGraphStoreRef != nil {
|
||||
resp["graph_cache"] = cachedGraphStoreRef.Stats()
|
||||
}
|
||||
if storage.SearchCacheInstance != nil {
|
||||
resp["search_cache"] = storage.SearchCacheInstance.Stats()
|
||||
}
|
||||
// 2026-10-14 (t_2afae95e):FTS 词面索引状态(docs/tokens/built_at/dirty/门控)
|
||||
resp["fts_index"] = storage.FtsIndexStats()
|
||||
respondJSON(w, 200, resp)
|
||||
})
|
||||
// 2026-10-14 (t_2afae95e):FTS 手工刷索引(admin;异步重建不阻塞)
|
||||
mux.HandleFunc("/api/v1/fts/rebuild", func(w http.ResponseWriter, r *http.Request) {
|
||||
storage.FtsRebuildNow()
|
||||
respondJSON(w, 200, map[string]interface{}{"status": "rebuild_started"})
|
||||
})
|
||||
// 2026-10-14 (t_2afae95e):FTS 词面查询取证端点(AC1 判据命令):
|
||||
// 返回该 query 的词面 topN 命中(id + 分 + 内容摘录),不走路过 recall 缓存。
|
||||
mux.HandleFunc("/api/v1/fts/query", func(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Query string `json:"query"`
|
||||
TopN int `json:"top_n"`
|
||||
CheckDocID string `json:"check_doc_id"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "invalid body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if req.TopN <= 0 {
|
||||
req.TopN = 10
|
||||
}
|
||||
respondJSON(w, 200, storage.FtsQuery(req.Query, req.TopN, req.CheckDocID))
|
||||
})
|
||||
// ─── Prometheus /metrics ─────────────────────
|
||||
mux.Handle("/metrics", metrics.Handler())
|
||||
@@ -370,14 +593,37 @@ func NewServer() http.Handler {
|
||||
governance.PushCacheInvalidate(req.Namespace, "commit")
|
||||
governance.PushMemoryCommitted(req.AgentID, req.Namespace, "")
|
||||
}
|
||||
// t_f8fc97e6 P3 Peer:新记忆进入 → 异步刷新内容里出现的实体画像。
|
||||
// 默认关(ZHIYI_PEER_RECALL 未设/≠1)⇒ 本分支整体跳过,commit 路径零变化(AC4)。
|
||||
// 开启时在已有 goroutine 内再起子 goroutine,LLM 推理绝不阻塞 HTTP commit 返回。
|
||||
if os.Getenv("ZHIYI_PEER_RECALL") == "1" && peerAPI != nil {
|
||||
peerAPI.RefreshFromContent(req.Content, req.Namespace)
|
||||
}
|
||||
}()
|
||||
})
|
||||
mux.HandleFunc("/api/v1/recall", api.Recall)
|
||||
mux.HandleFunc("/api/v1/recall/debug", api.RecallDebug)
|
||||
mux.HandleFunc("/api/v1/feedback", api.Feedback)
|
||||
// 2026-10-26 (P0-1 t_trace_p0):召回链路追踪回溯(trace_id 贯穿各阶段/各通道)
|
||||
mux.HandleFunc("/api/v1/trace/", api.Trace)
|
||||
// t_23b6a940 AC7 热门度看门狗快照(report-only,传感器端读它转既有告警通道)
|
||||
mux.HandleFunc("/api/v1/popwatch", api.PopWatch)
|
||||
// 2026-10-13 (t_e9a4d18f P2) 常设答案直读/写入
|
||||
mux.HandleFunc("/api/v1/standing-answers", routes.HandleStandingAnswers)
|
||||
// ⑤使用追踪(t_5aa4dcac):上报 + 手动触发。env 门控 ZHIYI_USAGE_TRACK,默认关。
|
||||
mux.HandleFunc("/api/v1/usage/report", api.UsageReport)
|
||||
mux.HandleFunc("/api/v1/usage/detect", api.UsageDetect)
|
||||
// GA-P0-7 (t_dd64345a):裸 /api/v1/feedback 已退役——其 handler 曾写旧字段 not_useful_count。
|
||||
// 反馈统一走 /api/v1/feedback/{useful,not-useful,deprecate,correct}(feedback.go,写拆分后新字段)。
|
||||
mux.HandleFunc("/api/v1/bootstrap", api.Bootstrap)
|
||||
mux.HandleFunc("/api/v1/stats", api.Stats)
|
||||
// 2026-10-26(牧尘批「三档」):自检统一取数端点。
|
||||
// 唯一契约 —— 自检脚本一律读这里,禁止再 lancedb.connect() 直连生产库。
|
||||
// ?level=cheap(默认,内存态计数)| full(+读 tools/selfcheck_full.py 的全量快照:碎片/冗余/近7天质量/写量)
|
||||
mux.HandleFunc("/api/v1/selfcheck", api.Selfcheck)
|
||||
mux.HandleFunc("/api/v1/batch-commit", api.BatchCommit)
|
||||
// 主症A(t_fa6c9104):显式写入直落 memories 表(嵌入 + 立刻可召回)。
|
||||
// 纯新增路由:commit/recall/蒸馏路径零改动;旧服务端 404 时插件自动回落 commit。
|
||||
mux.HandleFunc("/api/v1/memory/write", api.WriteMemory)
|
||||
// 自优化指标(Dashboard,含 avg_distill_loss)
|
||||
// total_episodes:Rust count_rows 真实值;旧 sidecar 回退 episodes_cached(进程内缓存,非总量)
|
||||
mux.HandleFunc("/api/v1/metrics", func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -539,6 +785,23 @@ func NewServer() http.Handler {
|
||||
if entity == "" {
|
||||
entity = r.URL.Query().Get("query") // 也接受整句 query
|
||||
}
|
||||
// 噪音闸门(t_689b6d38):系统通知/提示样板文本(如 "[IMPORTANT: You are running
|
||||
// as a scheduled cron job..."、"[System note: ...")不进语义召回、不返回笔记。
|
||||
// 判定优先用结构化来源标记头,白名单(真实用户提问)照常召回,不误杀。
|
||||
if routes.IsSystemTemplateInput(entity) {
|
||||
log.Printf("[graph/notes] 拦截系统样板入参(system_template):不拆实体、不返回笔记(入参 %q)",
|
||||
strings.TrimSpace(entity))
|
||||
respondJSON(w, 200, map[string]interface{}{
|
||||
"entity": entity,
|
||||
"graph_paths": []map[string]interface{}{},
|
||||
"notes": []map[string]interface{}{},
|
||||
"paths_count": 0,
|
||||
"notes_count": 0,
|
||||
"mode": "none",
|
||||
"skipped": "system_template",
|
||||
})
|
||||
return
|
||||
}
|
||||
maxHops := 2
|
||||
if h := r.URL.Query().Get("max_hops"); h != "" {
|
||||
if parsed, err := strconv.Atoi(h); err == nil && parsed > 0 {
|
||||
@@ -637,6 +900,24 @@ func NewServer() http.Handler {
|
||||
mode = "direct"
|
||||
} else if cands := entityIndex.Extract(entity, 2); len(cands) > 0 {
|
||||
// 兜底:entity 是整句自然语言(调用方原样传用户提问)→ 本地把它拆成候选实体
|
||||
// 2026-10-12 GA-P0-5:概念/实体提取路径接 echo 防线 —— 审计笔记把污染词当证据
|
||||
// 列出来 → 蒸馏成 episode → 兜底拆实体时会把已删除污染节点(n_galway / n_rothfuss /
|
||||
// n_the_name_of_the_wind)重建。候选实体若只是 prompt 教学示例的回显残片
|
||||
// (逐字相等 / illustration 类 ≥4 字子串,判据与蒸馏侧 IsPromptEcho 同源)
|
||||
// ⇒ 不入图;[ECHO-DROP] 日志供验证防线在跑。
|
||||
var echoDropped int
|
||||
kept := cands[:0]
|
||||
for _, c := range cands {
|
||||
if distill.IsPromptEchoEntity(c) {
|
||||
echoDropped++
|
||||
continue
|
||||
}
|
||||
kept = append(kept, c)
|
||||
}
|
||||
if echoDropped > 0 {
|
||||
log.Printf("[graph/notes][ECHO-DROP] 剔除回显残片 %d 个(%q)→ 不参与笔记匹配/不入图", echoDropped, cands)
|
||||
cands = kept
|
||||
}
|
||||
const maxSearchEntities = 8 // 参与笔记匹配的实体上限:候选 + 少量邻居,防噪声淹没
|
||||
ents := make([]string, 0, maxSearchEntities)
|
||||
seen := make(map[string]bool, maxSearchEntities)
|
||||
@@ -909,27 +1190,12 @@ func NewServer() http.Handler {
|
||||
mux.HandleFunc("/api/v1/conflicts/resolve", conflictAPI.Resolve)
|
||||
|
||||
// 反馈 — G5: 修正记忆时填充 version_history
|
||||
// 2026-10-14 (t_c06ad4d0):删除冗余重复块。MarkUseful 已做 RecordFeedback(true)+
|
||||
// RecordDecision+QualityMonitor.Check+IncrementUseful+AppendHitEvent;原 handler 里
|
||||
// 这段二次读 r.Body 的 RecordUseful/RecordDecision/QualityMonitor 全部重复,且
|
||||
// r.Body 已被 MarkUseful 消费(io.ReadAll 恒空)⇒ 死代码 + 潜在二次计数污染。
|
||||
mux.HandleFunc("/api/v1/feedback/useful", func(w http.ResponseWriter, r *http.Request) {
|
||||
feedbackAPI.MarkUseful(w, r)
|
||||
// 质量监控:useful → 质量上升
|
||||
var req struct {
|
||||
MemoryID string `json:"memory_id"`
|
||||
}
|
||||
if r.Body != nil {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
json.Unmarshal(body, &req)
|
||||
r.Body = io.NopCloser(bytes.NewReader(body))
|
||||
if req.MemoryID != "" {
|
||||
selfoptimize.Dash.RecordUseful()
|
||||
// V 值:useful = success
|
||||
selfoptimize.VProp.RecordDecision(
|
||||
"useful_"+req.MemoryID,
|
||||
[]string{req.MemoryID},
|
||||
"user_feedback", "success", "",
|
||||
)
|
||||
selfoptimize.QualityMonitor.Check(req.MemoryID, 0, 5) // 清除潜在告警
|
||||
}
|
||||
}
|
||||
})
|
||||
mux.HandleFunc("/api/v1/feedback/not-useful", func(w http.ResponseWriter, r *http.Request) {
|
||||
feedbackAPI.MarkNotUseful(w, r)
|
||||
@@ -979,6 +1245,16 @@ func NewServer() http.Handler {
|
||||
// 缺口
|
||||
mux.HandleFunc("/api/v1/gaps", gapAPI.List)
|
||||
mux.HandleFunc("/api/v1/gaps/detect", gapAPI.Detect)
|
||||
// t_d32e5f8a L2 模式检测(MemOS 血统)
|
||||
mux.HandleFunc("/api/v1/patterns", patternAPI.List)
|
||||
mux.HandleFunc("/api/v1/patterns/detect", patternAPI.Detect)
|
||||
// t_fcadee04 L3 skill 草稿(/patterns/{id}/draft 与 /patterns/{id}/promote)。
|
||||
// 前缀路由;/patterns 与 /patterns/detect 因更长的精确路由优先,不受影响。
|
||||
mux.HandleFunc("/api/v1/patterns/", patternAPI.Sub)
|
||||
// t_f8fc97e6 P3 Peer Representation:显式 refresh/explain + 门控 recall。
|
||||
// 前缀路由 /api/v1/peer/;/api/v1/recall/peer 独立精确路由优先。
|
||||
mux.HandleFunc("/api/v1/recall/peer", peerAPI.RecallPeer)
|
||||
mux.HandleFunc("/api/v1/peer/", peerAPI.Sub)
|
||||
mux.HandleFunc("/api/v1/gaps/close/", func(w http.ResponseWriter, r *http.Request) {
|
||||
gapAPI.Close(w, r)
|
||||
topic := r.URL.Path[len("/api/v1/gaps/close/"):]
|
||||
@@ -1105,6 +1381,8 @@ func NewServer() http.Handler {
|
||||
AgentID string `json:"agent_id"`
|
||||
// 2026-09-26:手动蒸馏也支持带出处(便于补跑 wiki 批时保留笔记路径)
|
||||
Source string `json:"source"`
|
||||
// 2026-10-08 (Gap#2):手动蒸馏同样可显式声明信任等级(补跑存量时用)
|
||||
Confidence *float64 `json:"confidence"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "invalid request body", http.StatusBadRequest)
|
||||
@@ -1121,7 +1399,11 @@ func NewServer() http.Handler {
|
||||
req.AgentID = "hermes-a06"
|
||||
}
|
||||
epID := fmt.Sprintf("ep_manual_%d", time.Now().UnixNano())
|
||||
routes.AutoDistillTrigger(epID, req.Content, req.Category, req.Namespace, req.AgentID, req.Source, "", "")
|
||||
routes.AutoDistillTrigger(epID, req.Content, req.Category, req.Namespace, req.AgentID, routes.CommitMeta{
|
||||
Source: req.Source,
|
||||
Confidence: req.Confidence,
|
||||
ConfidenceSource: confidenceSourceOf(req.Confidence),
|
||||
})
|
||||
respondJSON(w, 200, map[string]string{"status": "queued", "episode_id": epID})
|
||||
})
|
||||
// 蒸馏队列状态端点(G8-G9 配套)
|
||||
@@ -1563,6 +1845,11 @@ func NewServer() http.Handler {
|
||||
ticker := time.NewTicker(30 * time.Second)
|
||||
defer ticker.Stop()
|
||||
for range ticker.C {
|
||||
// t_cf680fad:每个 tick 先 drain durable pending-softdelete 队列(风暴退去后的
|
||||
// 相对静默窗口重放,必落盘)。队列空 = 廉价 no-op,不打日志;仅在有待处理时出声。
|
||||
if n := storage.PendingSoftDeleteCount(); n > 0 {
|
||||
storage.DrainPendingSoftDeletes(ldb)
|
||||
}
|
||||
for _, t := range []struct{ id, action string }{
|
||||
{"t_distill", "distill"},
|
||||
{"t_merge", "merge"},
|
||||
@@ -1583,14 +1870,14 @@ func NewServer() http.Handler {
|
||||
// distill 保持 cluster_only(高频触发,只做快速聚类)
|
||||
_, err = consolPipe.Run()
|
||||
case "consolidation", "backtrack":
|
||||
// full 模式:含 prune + decay + 质量回溯(Step 4)
|
||||
// 48h cooldown 保护,不会真正每分钟跑 full(cooldown 内 CanFire 仍返回 false)
|
||||
_, err = consolPipe.RunWithMode("full")
|
||||
// 2026-09-21 (t_4ce53193):冲突去重 + 保留策略
|
||||
// 去重:同 (L,R) 对只留最早一条,累加 dup_count,归档 + 审计
|
||||
conflictDetector.DedupeActive(governance.DefaultConflictRetentionConfig())
|
||||
// 保留:pending > 7d 无人处置 → 归档(不删除)
|
||||
conflictDetector.RetainAndArchive(governance.DefaultConflictRetentionConfig())
|
||||
// full 模式:含 prune + decay + 质量回溯(Step 4)
|
||||
// 48h cooldown 保护,不会真正每分钟跑 full(cooldown 内 CanFire 仍返回 false)
|
||||
_, err = consolPipe.RunWithMode("full")
|
||||
// 2026-09-21 (t_4ce53193):冲突去重 + 保留策略
|
||||
// 去重:同 (L,R) 对只留最早一条,累加 dup_count,归档 + 审计
|
||||
conflictDetector.DedupeActive(governance.DefaultConflictRetentionConfig())
|
||||
// 保留:pending > 7d 无人处置 → 归档(不删除)
|
||||
conflictDetector.RetainAndArchive(governance.DefaultConflictRetentionConfig())
|
||||
case "merge":
|
||||
_, err = consolPipe.RunMerge()
|
||||
case "prune":
|
||||
@@ -1603,7 +1890,13 @@ func NewServer() http.Handler {
|
||||
memories, e := ldb.GetCandidatesForForgetting()
|
||||
decayScanned := 0
|
||||
decayForgotten := 0
|
||||
decayProtected := 0
|
||||
if e == nil {
|
||||
// 2026-10-16 (t_944344b5) 遗忘保护守卫:本 tick 加载一次保护状态
|
||||
// (Redis zhiyi:vprop_values + zhiyi:protected_ids),命中任一保护规则的
|
||||
// 候选永不自动软删(fragment 与 ShouldForget 两条道都拦截)。
|
||||
// Redis 宕机 → 降级为纯行内规则(category/freshness/关键词),不阻断衰减。
|
||||
protState := memprotect.LoadState()
|
||||
const maxDecayBatch = 2000
|
||||
if len(memories) > maxDecayBatch {
|
||||
sort.SliceStable(memories, func(a, b int) bool {
|
||||
@@ -1627,6 +1920,16 @@ func NewServer() http.Handler {
|
||||
continue
|
||||
}
|
||||
}
|
||||
// 🔒 2026-10-16 (t_944344b5) 遗忘保护守卫: 命中任一保护规则的候选
|
||||
// (category∈{decision,preference,pref} / V≥2.0 / freshness=verified /
|
||||
// protected_ids 名单 / distilled 且内容命中 10 个决策·偏好关键词) 永不自动软删。
|
||||
// 拦截 point 放在 fragment + ShouldForget 两条 SoftDelete 道之前。
|
||||
if isProt, protRule := memprotect.IsProtected(m, protState); isProt {
|
||||
gid, _ := m["id"].(string)
|
||||
decayProtected++
|
||||
log.Printf("[decay] protected skip id=%q rule=%s (遗忘保护守卫命中, 跳过自动遗忘)", gid, protRule)
|
||||
continue
|
||||
}
|
||||
// 解析 last_recalled_at
|
||||
lastAccessed := time.Now().Add(-30 * 24 * time.Hour) // 默认30天前
|
||||
if t, ok := m["last_recalled_at"].(string); ok && t != "" {
|
||||
@@ -1653,8 +1956,10 @@ func NewServer() http.Handler {
|
||||
}
|
||||
continue
|
||||
}
|
||||
// GA-P0-2 (t_c6d41ac6):衰减/遗忘只认 recall_verified_count(正反馈才是 V 值)。
|
||||
// recall_count 已冻结(历史虚高保命来源),seen 只用于观测。
|
||||
recallCount := 0
|
||||
if rc, ok := m["recall_count"].(int); ok {
|
||||
if rc, ok := m["recall_verified_count"].(int); ok {
|
||||
recallCount = rc
|
||||
}
|
||||
tier := "normal"
|
||||
@@ -1685,7 +1990,8 @@ func NewServer() http.Handler {
|
||||
}
|
||||
// AC-1 验收日志(P1 修复 type 断言后 last_recalled_at 可解析;batch<=2000)
|
||||
if decayScanned > 0 {
|
||||
log.Printf("[decay] scanned=%d forgotten=%d (batch<=2000, 最久未访问优先)", decayScanned, decayForgotten)
|
||||
// 2026-10-16 (t_944344b5):protected_skip = 被遗忘保护守卫拦截、未软删的候选数
|
||||
log.Printf("[decay] scanned=%d forgotten=%d protected_skip=%d (batch<=2000, 最久未访问优先)", decayScanned, decayForgotten, decayProtected)
|
||||
}
|
||||
case "gap_scan":
|
||||
// 检查已有缺口:过期 7 天的自动关闭
|
||||
@@ -1699,7 +2005,12 @@ func NewServer() http.Handler {
|
||||
for _, g := range gaps {
|
||||
if !g.Closed && routes.GapRepair != nil {
|
||||
if routes.GapRepair.AutoRepair(g) {
|
||||
selfoptimize.Dash.RecordGapClosed()
|
||||
// t_e5997ca4:AutoRepair 只做「修复」不关缺口。旧代码在此
|
||||
// 无条件 Dash.RecordGapClosed() 却不置 g.Closed ⇒ 同一缺口每轮
|
||||
// gap_scan 都再 +1(ClosedGaps 无限虚增,线上 9 vs 2 的写侧根因 #2)。
|
||||
// 现按 RepairHandler 语义:修复成功 = 关闭该缺口;+1 只发生在
|
||||
// Close 的 open→closed 迁移点(内部),下一轮 !g.Closed 即跳过。
|
||||
gapDetector.Close(g.Topic)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1917,3 +2228,42 @@ func orDefault(v, def string) string {
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// confidenceSourceOf 2026-10-08 (Gap#2):声明了信任等级 ⇒ authoritative;未声明 ⇒ 空
|
||||
// (不写 "estimated"——estimated 专指「事后回填的猜测值」,语义上不该由写入路径产生)。
|
||||
func confidenceSourceOf(c *float64) string {
|
||||
if c != nil {
|
||||
return "authoritative"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ldbWriteOpsStore 适配 storage.LanceDB 到 distill.WriteOpsStore 接口。
|
||||
// 供写时四操作的 apply 模式标记 superseded/conflict(t_3e98b65a)。
|
||||
type ldbWriteOpsStore struct {
|
||||
ldb storage.LanceDB
|
||||
}
|
||||
|
||||
// MarkSuperseded 旧记忆标记「被 newID 取代」(写 superseded_by + is_deleted=true;
|
||||
// 历史经 supersedes/superseded_by 保留可追溯,不物理删)。
|
||||
func (s *ldbWriteOpsStore) MarkSuperseded(oldID, newID string) error {
|
||||
b, _ := json.Marshal([]string{newID})
|
||||
return s.ldb.Update("memories", oldID, map[string]any{
|
||||
"superseded_by": string(b),
|
||||
"is_deleted": true,
|
||||
})
|
||||
}
|
||||
|
||||
// MarkConflict 记忆标记冲突(交人工;不删)。冲突以 superseded_by 空 + is_deleted 保持 false
|
||||
// + freshness=conflict 标识,让 recall 仍可见但排序权重降(调用方感知)。
|
||||
func (s *ldbWriteOpsStore) MarkConflict(id string) error {
|
||||
return s.ldb.Update("memories", id, map[string]any{
|
||||
"freshness": "conflict",
|
||||
})
|
||||
}
|
||||
|
||||
// memIDFor 为写时四操作 apply 预生成新记忆 ID(与下方 InsertMemory 同格式)。
|
||||
func memIDFor(fact string, input distill.DistillInput) string {
|
||||
_ = fact
|
||||
return fmt.Sprintf("mem_%d", time.Now().UnixNano())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// GA-P0-7 (t_dd64345a):回归守卫 —— 裸路由 /api/v1/feedback 已退役。
|
||||
// 它的 handler(core.go Feedback,已删)曾按 useful 布尔写旧字段 not_useful_count
|
||||
// (P0-1 t_718d8707 已拆分为 human_not_useful_count / dedup_downweight_count)。
|
||||
// 谁若重新注册这个裸路由(旧字段随之复活),本测试必须红。
|
||||
func TestNoBareFeedbackRoute(t *testing.T) {
|
||||
src, err := os.ReadFile("server.go")
|
||||
if err != nil {
|
||||
t.Fatalf("read server.go: %v", err)
|
||||
}
|
||||
s := string(src)
|
||||
|
||||
// 裸路由注册必须不存在(精确匹配 server.go:385 的旧行)。
|
||||
bare := `mux.HandleFunc("/api/v1/feedback", api.Feedback)`
|
||||
if strings.Contains(s, bare) {
|
||||
t.Fatalf("裸 /api/v1/feedback 路由被重新注册——其 handler 写旧字段 not_useful_count(GA-P0-1);请改用 /api/v1/feedback/{useful,not-useful,deprecate,correct}")
|
||||
}
|
||||
|
||||
// 新拆分后的子路由必须在(反馈统一走它们,写 human_not_useful_count 等新字段)。
|
||||
for _, sub := range []string{
|
||||
`"/api/v1/feedback/useful"`,
|
||||
`"/api/v1/feedback/not-useful"`,
|
||||
`"/api/v1/feedback/deprecate"`,
|
||||
`"/api/v1/feedback/correct"`,
|
||||
} {
|
||||
if !strings.Contains(s, sub) {
|
||||
t.Fatalf("期望子路由 %s 已注册,但 server.go 中缺失", sub)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,4 +23,4 @@ func initStorageForSQLite(emb *storage.Embedder) storage.LanceDB {
|
||||
}
|
||||
log.Printf("[zhiyid] 存储后端: SQLite (CGO) — %s", dbPath)
|
||||
return sqliteDB
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,4 +53,4 @@ func initGraphStore() governance.GraphStore {
|
||||
}
|
||||
log.Printf("[zhiyid] 图谱后端: SQLiteGraphStore — %s", graphPath)
|
||||
return gs
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,4 +62,4 @@ func initGraphStore() governance.GraphStore {
|
||||
}
|
||||
log.Printf("[zhiyid] 图谱后端: InMemoryGraph (Windows,纯 Go 无 SQLite CGO)")
|
||||
return governance.NewInMemoryGraph()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,35 +20,35 @@ import (
|
||||
|
||||
// ConsolidateRequest 整合请求
|
||||
type ConsolidateRequest struct {
|
||||
Task string `json:"task"` // "full" | "cluster_only" | "prune_only"
|
||||
LanceDBPath string `json:"lancedb_path"` // LanceDB 数据目录
|
||||
SQLitePath string `json:"sqlite_path"` // SQLite 图谱路径
|
||||
LLMEndpoint string `json:"llm_endpoint"` // LLM API 端点
|
||||
LLMModel string `json:"llm_model"` // LLM 模型名
|
||||
LLMApiKey string `json:"llm_api_key"` // LLM API Key (Authorization header)
|
||||
LLMBudget int `json:"llm_budget"` // 本次可用 LLM 次数
|
||||
Epsilon float64 `json:"epsilon"` // DBSCAN 邻域半径(1024-dim BGE-M3 单位向量建议 1.5)
|
||||
MinPoints int `json:"min_points"` // DBSCAN 最小点数
|
||||
ModelDir string `json:"model_dir"` // BGE 模型目录(用于 quality backtrace 编码)
|
||||
Task string `json:"task"` // "full" | "cluster_only" | "prune_only"
|
||||
LanceDBPath string `json:"lancedb_path"` // LanceDB 数据目录
|
||||
SQLitePath string `json:"sqlite_path"` // SQLite 图谱路径
|
||||
LLMEndpoint string `json:"llm_endpoint"` // LLM API 端点
|
||||
LLMModel string `json:"llm_model"` // LLM 模型名
|
||||
LLMApiKey string `json:"llm_api_key"` // LLM API Key (Authorization header)
|
||||
LLMBudget int `json:"llm_budget"` // 本次可用 LLM 次数
|
||||
Epsilon float64 `json:"epsilon"` // DBSCAN 邻域半径(1024-dim BGE-M3 单位向量建议 1.5)
|
||||
MinPoints int `json:"min_points"` // DBSCAN 最小点数
|
||||
ModelDir string `json:"model_dir"` // BGE 模型目录(用于 quality backtrace 编码)
|
||||
}
|
||||
|
||||
// ConsolidateResponse 整合响应
|
||||
type ConsolidateResponse struct {
|
||||
Status string `json:"status"` // "ok" | "partial_failure"
|
||||
ReportJSON string `json:"report_json"` // ConsolidationReport JSON
|
||||
FailureStep string `json:"failure_step"` // 失败步骤
|
||||
ErrorDetail string `json:"error_detail"` // 错误详情
|
||||
Status string `json:"status"` // "ok" | "partial_failure"
|
||||
ReportJSON string `json:"report_json"` // ConsolidationReport JSON
|
||||
FailureStep string `json:"failure_step"` // 失败步骤
|
||||
ErrorDetail string `json:"error_detail"` // 错误详情
|
||||
}
|
||||
|
||||
// Result 解析后的整合结果
|
||||
type Result struct {
|
||||
Mode string `json:"mode"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
Clusters int `json:"clusters_found,omitempty"`
|
||||
Noise int `json:"noise_points,omitempty"`
|
||||
DecayRates map[string]float64 `json:"decay_rates,omitempty"`
|
||||
Quality *QualityResult `json:"quality,omitempty"`
|
||||
QualityScore float64 `json:"quality_score,omitempty"` // 直接从 sidecar 的 ConsolidationReport 读取
|
||||
Mode string `json:"mode"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
Clusters int `json:"clusters_found,omitempty"`
|
||||
Noise int `json:"noise_points,omitempty"`
|
||||
DecayRates map[string]float64 `json:"decay_rates,omitempty"`
|
||||
Quality *QualityResult `json:"quality,omitempty"`
|
||||
QualityScore float64 `json:"quality_score,omitempty"` // 直接从 sidecar 的 ConsolidationReport 读取
|
||||
}
|
||||
|
||||
type QualityResult struct {
|
||||
@@ -71,17 +71,17 @@ func Run(dataDir, sqlitePath, mode string) (*Result, error) {
|
||||
Task: mode,
|
||||
LanceDBPath: dataDir,
|
||||
SQLitePath: sqlitePath,
|
||||
LLMEndpoint: os.Getenv("LLM_ENDPOINT"),
|
||||
LLMModel: os.Getenv("LLM_MODEL"),
|
||||
LLMApiKey: os.Getenv("LLM_API_KEY"),
|
||||
Epsilon: 0.4,
|
||||
LLMEndpoint: os.Getenv("LLM_ENDPOINT"),
|
||||
LLMModel: os.Getenv("LLM_MODEL"),
|
||||
LLMApiKey: os.Getenv("LLM_API_KEY"),
|
||||
Epsilon: 0.4,
|
||||
// 距离分布(2026-09-05 实测,bge-m3 归一化向量 norm=1.0):
|
||||
// 全量3000抽样: p25=0.24 p50=0.75 p95=0.82
|
||||
// sidecar 零向量 top-10000 样本: p5=0.09 p50=0.42 p95=1.0
|
||||
// eps=1.0(旧值,按未归一化 p50=1.029 调的)→ 归一化空间过大 → clusters=1 聚类失效
|
||||
// eps=0.3~0.5 → 有语义簇(能发现重复状态噪音簇: 1045条"主profile状态同步"/961条"CBM状态")
|
||||
// eps=0.4 = 平衡(2026-09-05 修复,commit 待推)
|
||||
MinPoints: 3,
|
||||
MinPoints: 3,
|
||||
ModelDir: os.Getenv("BGE_MODEL_DIR"),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -10,13 +10,13 @@ import (
|
||||
// 目标:为每条事实生成紧凑结构化摘要,LLM 可读、无需解码器,
|
||||
// 召回时先扫索引定位相关事实,再读原文(索引层指向内容层)。
|
||||
type AAAKEntry struct {
|
||||
FactID string `json:"fact_id"` // 事实编号(F1, F2, ...)
|
||||
Primary string `json:"primary"` // 主实体(最重要实体,如人名/项目名)
|
||||
Entities []string `json:"entities"` // 全部相关实体
|
||||
Keywords []string `json:"keywords"` // 主题关键词(2-4 个)
|
||||
Quote string `json:"quote"` // 关键短语(截断 ≤40 字)
|
||||
Weight float64 `json:"weight"` // 权重(由 5D 分数综合)
|
||||
Kind string `json:"kind"` // 类型:fact / decision / action / question / conclusion
|
||||
FactID string `json:"fact_id"` // 事实编号(F1, F2, ...)
|
||||
Primary string `json:"primary"` // 主实体(最重要实体,如人名/项目名)
|
||||
Entities []string `json:"entities"` // 全部相关实体
|
||||
Keywords []string `json:"keywords"` // 主题关键词(2-4 个)
|
||||
Quote string `json:"quote"` // 关键短语(截断 ≤40 字)
|
||||
Weight float64 `json:"weight"` // 权重(由 5D 分数综合)
|
||||
Kind string `json:"kind"` // 类型:fact / decision / action / question / conclusion
|
||||
}
|
||||
|
||||
// buildAAAKIndex 为事实列表生成 AAAK 压缩索引
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
// 织忆 MemoryWeave — 准入三路分诊(确定性,零 LLM 调用)
|
||||
//
|
||||
// 背景与依据(2026-10-12,6 篇文献精读,方案见
|
||||
// mc/小怡/04-OBSIDIAN工具/04-02-方案设计/20261012-织忆记忆闸门-外部经验落地方案.md):
|
||||
//
|
||||
// · A-MAC (arXiv 2603.04549) 消融实验:确定性「内容类型先验」是**单点最强特征**
|
||||
// —— 去掉它 F1 从 0.583 掉到 0.476(ΔF1=−0.107),等于退回等权基线。
|
||||
// 而织忆此前的判据里确定性特征数为 0(只有 LLM 给的 overall 与 VD)。
|
||||
// · SAGE (arXiv 2605.30711):明确该走哪条路的直接闭式解决,只有「不确定带」才需谨慎;
|
||||
// 且单一固定阈值会随记忆库变密而**必然过度保守**。
|
||||
// · When to Forget (arXiv 2604.12007) 原文:"a system acting on Memory Worth should
|
||||
// not deprecate an uncertain memory" ⇒ **证据不足/拿不准的内容绝不弃用**。
|
||||
//
|
||||
// 于是把「一个 LLM 分数卡阈值」拆成三路:
|
||||
//
|
||||
// drop —— 无歧义的垃圾(确定性规则),可丢
|
||||
// keep —— 无歧义的高价值(确定性规则),放行且不看分数
|
||||
// observe —— 其余全部 ⇒ **不确定带,永不因 LLM 低分丢弃**
|
||||
//
|
||||
// 设计取舍(刻意保守):drop 只收「无歧义」项;像"纯疑问句""状态汇报"这类**需要判断**的
|
||||
// 内容不放进 drop,一律落 observe —— 文献明确警告过度保守的准入会丢掉长程推理必需的信息。
|
||||
// 代价不对称:keep/observe 多留是可逆的(后续消费/降权会淘汰),drop 丢掉不可逆。
|
||||
package distill
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/textfilter"
|
||||
)
|
||||
|
||||
// AdmissionLane 准入分诊结果。
|
||||
type AdmissionLane string
|
||||
|
||||
const (
|
||||
LaneKeep AdmissionLane = "keep" // 确定性高价值 → 放行,不看分数
|
||||
LaneDrop AdmissionLane = "drop" // 确定性垃圾 → 丢弃
|
||||
LaneObserve AdmissionLane = "observe" // 不确定带 → 永不因分数丢弃
|
||||
)
|
||||
|
||||
// decisionPatterns 明确决策/承诺/长期约束的确定性线索。
|
||||
// 注意:命中即→keep,属**过度保留**方向,代价可逆,故可以放宽。
|
||||
var decisionPatterns = []string{
|
||||
"决定", "约定", "拍板", "定下来", "改成", "以后都", "以后不", "不再", "必须",
|
||||
"记住", "长期", "持续", "永久", "禁止", "不要", "别忘",
|
||||
}
|
||||
|
||||
// identityPreferencePatterns 身份/偏好/长期事实的确定性线索。
|
||||
var identityPreferencePatterns = []string{
|
||||
"我喜欢", "我不喜欢", "我的", "我是", "我在", "我负责", "我住", "平时",
|
||||
"习惯", "一直", "负责", "工作", "设备",
|
||||
}
|
||||
|
||||
// ClassifyAdmission 对一条待蒸馏内容做确定性三路分诊。
|
||||
// 返回 lane 与人类可读的 reason(进日志,用于事后审计分诊是否合理)。
|
||||
// 本函数**零 LLM 调用**、纯确定性 —— 同一输入永远同一结果,可单测。
|
||||
func ClassifyAdmission(content string) (AdmissionLane, string) {
|
||||
s := strings.TrimSpace(content)
|
||||
if s == "" {
|
||||
return LaneDrop, "空内容"
|
||||
}
|
||||
|
||||
// ── drop:无歧义的垃圾 ──────────────────────────────────
|
||||
if textfilter.IsSystemTemplate(s) {
|
||||
return LaneDrop, "系统样板/回执"
|
||||
}
|
||||
if utf8.RuneCountInString(s) < 8 {
|
||||
return LaneDrop, "过短无内容(<8字)"
|
||||
}
|
||||
|
||||
// ── keep:无歧义的高价值 ────────────────────────────────
|
||||
// 结构化人侧短事实(画像规则:/心迹:/牵挂:/偏好:/习惯:/目标: 等 daemon 侧固化前缀)
|
||||
if isSoulfulShortFact(s) {
|
||||
return LaneKeep, "结构化人侧事实前缀"
|
||||
}
|
||||
// 长度护栏:超长内容里的关键词不构成"这是在陈述一条决策"(长文里出现"决定"
|
||||
// 多半是在**汇报/转述**,不是本条内容本身是一条决策)→ 落 observe。
|
||||
n := utf8.RuneCountInString(s)
|
||||
if n >= 8 && n <= 150 {
|
||||
for _, p := range decisionPatterns {
|
||||
if strings.Contains(s, p) {
|
||||
return LaneKeep, "决策/承诺线索:" + p
|
||||
}
|
||||
}
|
||||
for _, p := range identityPreferencePatterns {
|
||||
if strings.Contains(s, p) {
|
||||
return LaneKeep, "身份/偏好线索:" + p
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── observe:拿不准的一律留 ─────────────────────────────
|
||||
return LaneObserve, "不确定带"
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package distill
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestClassifyAdmission 锁定三路分诊的判据(Step 1 验收线)。
|
||||
//
|
||||
// 关键不变量(对应外部经验):
|
||||
// 1. 系统样板/回执 → drop(确定性垃圾)
|
||||
// 2. 结构化人侧事实前缀 / 决策承诺 / 身份偏好 → keep
|
||||
// 3. **拿不准的一律 observe** —— 尤其"纯疑问""状态汇报"这类需要判断的内容
|
||||
// 绝不能被 drop(When to Forget 原文:"should not deprecate an uncertain memory")
|
||||
func TestClassifyAdmission(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
content string
|
||||
want AdmissionLane
|
||||
}{
|
||||
// ── drop:无歧义垃圾 ──
|
||||
{"系统样板-cron", "[IMPORTANT: You are running as a scheduled cron job. No user is present.", LaneDrop},
|
||||
{"系统样板-心跳", "[HEARTBEAT] tick 2026-10-12T02:00", LaneDrop},
|
||||
{"系统样板-内部通知", "[INTERNAL NOTIFICATION — generated by the Hermes gateway, not written by a human user.]", LaneDrop},
|
||||
{"系统样板-子代理回执", "[ASYNC DELEGATION COMPLETE — deleg_79e1d4ad] A background subagent finished.", LaneDrop},
|
||||
{"系统样板-上下文摘要", "## Context Compaction — REFERENCE ONLY\nEarlier turns were compacted.", LaneDrop},
|
||||
{"空内容", " ", LaneDrop},
|
||||
{"过短", "好的", LaneDrop},
|
||||
|
||||
// ── keep:确定性高价值 ──
|
||||
{"结构化前缀-偏好", "偏好: 牧尘喜欢结论先行、不要废话科普", LaneKeep},
|
||||
{"结构化前缀-心迹", "心迹: 今天有点累", LaneKeep},
|
||||
{"决策承诺", "牧尘决定以后都用分身C来处理采集类任务。", LaneKeep},
|
||||
{"长期约束", "这条以后不要再问了,记住已经拍板。", LaneKeep},
|
||||
{"身份偏好", "我喜欢马哲经济学和剪辑,设备是小米笔记本。", LaneKeep},
|
||||
|
||||
// ── observe:拿不准的一律留(关键:不能被 drop)──
|
||||
{"纯疑问", "这个闸门到底应该怎么定阈值才合理呢?", LaneObserve},
|
||||
{"状态汇报", "服务已重启完成,当前版本 v0.21.6。", LaneObserve},
|
||||
{"普通对话", "今天把织忆的评分链路排查了一遍,顺手补了记分牌的一项指标。", LaneObserve},
|
||||
|
||||
// ── 边界:超长内容里的关键词不构成"陈述了一条决策" ──
|
||||
{"超长含关键词", "决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定决定", LaneObserve},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
got, why := ClassifyAdmission(c.content)
|
||||
if got != c.want {
|
||||
t.Fatalf("ClassifyAdmission() lane=%q reason=%q, 期望 lane=%q\n内容: %.60s", got, why, c.want, c.content)
|
||||
}
|
||||
if why == "" {
|
||||
t.Fatal("reason 不得为空(用于事后审计分诊是否合理)")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestClassifyAdmissionDeterministic 同一输入必须永远同一结果(确定性 = 可审计的前提)。
|
||||
func TestClassifyAdmissionDeterministic(t *testing.T) {
|
||||
for _, s := range []string{
|
||||
"牧尘决定以后都用分身C。",
|
||||
"服务已重启完成。",
|
||||
"[HEARTBEAT] tick",
|
||||
} {
|
||||
first, fr := ClassifyAdmission(s)
|
||||
for i := 0; i < 5; i++ {
|
||||
got, gr := ClassifyAdmission(s)
|
||||
if got != first || gr != fr {
|
||||
t.Fatalf("非确定性:%q 第一次 %s/%s,第 %d 次 %s/%s", s, first, fr, i+2, got, gr)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user