lingshu-skill 5.0.0 → 5.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,37 @@
1
1
  # 更新日志
2
2
 
3
+ ## v5.2(2026-11-24)
4
+
5
+ > 主题:**盈不足标定水位估算** + 修掉 `shape-audit` 的假阳性。
6
+
7
+ ### 盈不足(双假设法)标定(#93)
8
+
9
+ - 估算模型 `tokens = chars / ratio + overhead` 有**两个**未知数。宿主给出真实 token 时,cron 插件记一组 `(chars, tokens)`,用**最小二乘同时反推 ratio 与 overhead**(不再把 overhead 写死 18000——那才是误差大头)。
10
+ - 记录**限流**(60 秒内且字符差 <2000 不记),热路径不加重负担;拟合写 `<记忆库>/token-calib.json`,估算 `source` 变 `chars+calib`。
11
+ - 合理性闸:ratio 0.5~5、overhead 0~200000、样本 ≥2 且字符跨度 ≥2000,**不过就退回配置默认**(宁用旧的不用错的)。
12
+ - `brain.py token-calib [--refit] [--json]`:看样本,并用**同一公式独立重算**与插件写入值**对账**——两边不一致会明确报错(补"JS 侧没法单元测试"的保险)。
13
+
14
+ ### 修 `shape-audit` 假阳性(#92)
15
+
16
+ - **13 条"幻觉风险"全是假阳性**:逐条打印后确认,全部是 `最近关于「X」的一组事情(N 条)` 的**做梦聚合**(已知噪音)。
17
+ - 根因:聚合条目没有 `confidence` 字段,我拿 `importance`(默认 0.45)当代理 → 全被判"低置信 AI 派生"。
18
+ - 修:`audit()` 跳过聚合并注明跳过数;置信位不再用 importance 当代理。
19
+ - 修后真库:286 条(跳过 24 条聚合),幻觉风险 **0 条**。
20
+ - 顺带:3 条"高置信沉底"里,1 条测试消息 + 1 条正文只有 `list`(退化垃圾)留在淡忘区;1 条**信任事实**("用户怀疑我删了备份、我核实证明没删")已 `dust revive` 拉回 cortex,recall 实测第一条命中。
21
+
22
+ 验证:`tests/test_p19_token_calib.py` 7/7(拟合还原已知参数 / 需≥2样本 / 需跨度 / 拒荒谬值 / 样本读回与渲染 / **JS 与 Python 常量一致** / CLI 冒烟)。
23
+
24
+ ## v5.1(2026-11-24)
25
+
26
+ > 主题:**错卦落地**——`recall` 不再把"不要用 X"当成"要用 X"。
27
+
28
+ - **实测确认的问题**:`recall "用 DiskGenius 恢复分区"` 与 `recall "不要用…"` **结果集 3/3 完全重合**(仅排序不同),且**肯定查询把「不要用」的禁止记忆排到第一位、结果里没有任何标记**——模型看到极易读反。
29
+ - **做法**:新增极性识别 `_polarity_of()` / `_memory_polarity()`(显式 `avoid` 标记优先,其次正文否定词:不要/别用/勿/禁止/避免/不能/不可/禁用/放弃/不推荐…);`recall` 比对查询极性与记忆极性,**方向相反时打 `parts["polarity_conflict"]`**;CLI 输出 `⚠ 这条是禁止/否定方向(avoid),与你的查询方向相反——别读反`。
30
+ - **刻意不静默降权**:把禁令藏起来比标出来更危险(模型可能真去做那件被禁止的事)。做法是"保留 + 显式标注",判断权交回模型/用户。
31
+ - **注入路径本来就没这问题**:`--avoid` 记忆注入时独立成块「已经排除的方向(别再提)」,缺口只在 `recall` 输出。
32
+
33
+ 验证:`tests/test_p18_polarity.py` 6/6(极性识别 / avoid 标记算 neg / 肯定查询标禁令 / 否定查询标可行做法 / 方向一致不打扰 / CLI 出现 ⚠)。
34
+
3
35
  ## v5.0(2026-11-24)
4
36
 
5
37
  > 主题:**底层保险(写前快照 + 写后校验 + 自动回滚)** + 六爻位体检。
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  > 名字取自《黄帝内经》:**算力给思考,人格给灵魂,记忆给生命。**
4
4
 
5
- > 当前版本 **v5.0**(变更见 [CHANGELOG.md](CHANGELOG.md))
5
+ > 当前版本 **v5.2**(变更见 [CHANGELOG.md](CHANGELOG.md))
6
6
 
7
7
  > 🔁 **双仓库镜像**:GitHub(主)与 Gitee(镜像)保持同步——[gitee.com/htmcwy_0/lingshu-skill](https://gitee.com/htmcwy_0/lingshu-skill)。灵枢的更新检查会探测两边最新提交,**谁更新就自动从谁拉取**;任一边不可达(Gitee 匿名风控 / GitHub 限额)时走另一边兜底。
8
8
 
package/SKILL.md CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: lingshu
3
3
  title: 灵枢
4
- version: 5.0
4
+ version: 5.2
5
5
  description: 类脑持久记忆、人格与成长系统——跨会话记住事情、长出自己的人格、上下文将满时做梦式整理记忆。用户提到记忆/记住/上次/人格/设定/性格/知识库/笔记/日志/成长/自我进化/工作记忆,或新会话开始需要恢复关系与上下文时使用。纯本地零依赖。
6
6
  ---
7
7
 
@@ -811,6 +811,100 @@ export function apply(ctx, config) {
811
811
  } catch {} // turn-stopping 是串行事件,任何异常都不能拖住回合关闭
812
812
  })
813
813
 
814
+ // ── 盈不足标定(v5.2)──────────────────────────────────────────────
815
+ // 估算模型是 tokens = chars / ratio + overhead,有两个未知数。宿主偶尔会给出
816
+ // **真实 token 数**,那就是"盈不足"里的两次假设:拿 ≥2 组 (chars, tokens) 做
817
+ // 最小二乘,同时反推 ratio 与 overhead,比把 overhead 写死 18000 准得多。
818
+ // 只写 token-calib.jsonl / token-calib.json 两个新文件,绝不碰记忆数据。
819
+ const CALIB_SAMPLES = 500 // 最多留多少组样本
820
+ const CALIB_MIN_SPAN = 2000 // 两组样本字符差至少要这么大才有解
821
+ const _calibState = { lastAt: 0, lastChars: 0, cache: null }
822
+
823
+ function _calibPaths() {
824
+ try {
825
+ const home = readBrainHome()
826
+ if (!home) return null
827
+ return { samples: join(home, 'token-calib.jsonl'), fit: join(home, 'token-calib.json') }
828
+ } catch { return null }
829
+ }
830
+
831
+ function _fitFrom(samples) {
832
+ // 最小二乘拟合 y = a + b·x(等价于以字符数为自变量预测 token)
833
+ const n = samples.length
834
+ if (n < 2) return null
835
+ const xs = samples.map((s) => s.chars), ys = samples.map((s) => s.tokens)
836
+ const minX = Math.min(...xs), maxX = Math.max(...xs)
837
+ if (maxX - minX < CALIB_MIN_SPAN) return null // 跨度太小,解不稳定
838
+ const mx = xs.reduce((a, b) => a + b, 0) / n
839
+ const my = ys.reduce((a, b) => a + b, 0) / n
840
+ let sxx = 0, sxy = 0
841
+ for (let i = 0; i < n; i++) {
842
+ sxx += (xs[i] - mx) ** 2
843
+ sxy += (xs[i] - mx) * (ys[i] - my)
844
+ }
845
+ if (!(sxx > 0)) return null
846
+ const b = sxy / sxx // tokens per char
847
+ const a = my - b * mx // overhead
848
+ if (!(b > 0)) return null
849
+ const ratio = 1 / b
850
+ // 合理性闸:中文语境 1 字符大致 0.4~1 token;overhead 上万但不该离谱
851
+ if (!(ratio >= 0.5 && ratio <= 5)) return null
852
+ if (!(a >= 0 && a <= 200000)) return null
853
+ return { charsPerToken: Number(ratio.toFixed(3)),
854
+ systemOverheadTokens: Math.round(a), samples: n,
855
+ at: Math.floor(Date.now() / 1000) }
856
+ }
857
+
858
+ function _readCalibFit() {
859
+ if (_calibState.cache) return _calibState.cache
860
+ try {
861
+ const paths = _calibPaths()
862
+ if (!paths) return null
863
+ const raw = readFileSync(paths.fit, 'utf8')
864
+ const j = JSON.parse(raw)
865
+ if (!(j && j.charsPerToken > 0 && j.systemOverheadTokens >= 0)) return null
866
+ _calibState.cache = j
867
+ return j
868
+ } catch { return null }
869
+ }
870
+
871
+ function _recordCalib(chars, tokens) {
872
+ try {
873
+ if (!(chars > 0) || !(tokens > 0)) return
874
+ const now = Date.now()
875
+ // 限流:60 秒内且字符差不足 2000 就不记(热路径,别每轮都写盘)
876
+ if (now - _calibState.lastAt < 60000
877
+ && Math.abs(chars - _calibState.lastChars) < CALIB_MIN_SPAN) return
878
+ _calibState.lastAt = now
879
+ _calibState.lastChars = chars
880
+ const paths = _calibPaths()
881
+ if (!paths) return
882
+ appendFileSync(paths.samples,
883
+ JSON.stringify({ chars, tokens, at: Math.floor(now / 1000) }) + '\n')
884
+ // 读回来拟合(顺带裁到最近 CALIB_SAMPLES 条,防无限膨胀)
885
+ let lines = []
886
+ try {
887
+ lines = readFileSync(paths.samples, 'utf8').split('\n').filter((x) => x.trim())
888
+ } catch { return }
889
+ const tail = lines.slice(-CALIB_SAMPLES)
890
+ if (lines.length > CALIB_SAMPLES * 2) {
891
+ try { writeFileSync(paths.samples, tail.join('\n') + '\n') } catch {}
892
+ }
893
+ const samples = []
894
+ for (const line of tail) {
895
+ try {
896
+ const o = JSON.parse(line)
897
+ if (o && o.chars > 0 && o.tokens > 0) samples.push(o)
898
+ } catch {}
899
+ }
900
+ const fit = _fitFrom(samples)
901
+ if (fit) {
902
+ try { writeFileSync(paths.fit, JSON.stringify(fit, null, 2)) } catch {}
903
+ _calibState.cache = fit
904
+ }
905
+ } catch {}
906
+ }
907
+
814
908
  // 水位估算:宿主给了 usage 就用真值(prompt 侧 = 未缓存 + 缓存读 + 缓存写);
815
909
  // 否则按「消息正文字符数 + system/工具固定开销」折算。
816
910
  // v3.23 修:旧版只数 messages 的 text 字符,system prompt 与工具 schema 完全不计,
@@ -820,6 +914,16 @@ export function apply(ctx, config) {
820
914
  try {
821
915
  const msgs = Array.isArray(decision?.messages) ? decision.messages : []
822
916
  const num = (x) => (Number.isFinite(x) ? x : 0)
917
+ // 先把"真实对话字符数"算出来:既给下面的 chars 分支用,也给盈不足标定
918
+ // 提供自变量(宿主给真值 token 时才成对记录)。
919
+ let chars = 0
920
+ for (const m of msgs) {
921
+ // 估算只看"真实对话":灵枢自己注入的消息不算(v3.59:三个子插件各有名字)
922
+ if (LINGSHU_SOURCES.has(m?.source?.name)) continue
923
+ for (const c of (Array.isArray(m?.content) ? m.content : [])) {
924
+ if (c?.type === 'text' && typeof c.text === 'string') chars += c.text.length
925
+ }
926
+ }
823
927
  for (let i = msgs.length - 1; i >= 0; i--) {
824
928
  const u = msgs[i]?.metadata?.usage || msgs[i]?.usage || msgs[i]?.modelUsage
825
929
  || msgs[i]?.metadata?.modelUsage
@@ -829,17 +933,11 @@ export function apply(ctx, config) {
829
933
  const total = num(u.totalTokens)
830
934
  const used = total > 0 ? total : prompt
831
935
  if (used > 0) {
936
+ // 盈不足:拿到真值时顺手记一组 (字符数, 真实 token),交给 _recordCalib 拟合
937
+ _recordCalib(chars, used)
832
938
  return { pct: Math.min(100, Math.round(used / cfg.contextLimit * 100)), source: 'usage' }
833
939
  }
834
940
  }
835
- let chars = 0
836
- for (const m of msgs) {
837
- // 估算只看"真实对话":灵枢自己注入的消息不算(v3.59:三个子插件各有名字)
838
- if (LINGSHU_SOURCES.has(m?.source?.name)) continue
839
- for (const c of (Array.isArray(m?.content) ? m.content : [])) {
840
- if (c?.type === 'text' && typeof c.text === 'string') chars += c.text.length
841
- }
842
- }
843
941
  if (!chars) {
844
942
  // v3.57(保护 C):原来这里直接 return null,守卫就此静默跳过——「以为没到水位,
845
943
  // 其实已经快满」正是要防的情况。现在至少按 system/工具固定开销给一个下限
@@ -848,8 +946,13 @@ export function apply(ctx, config) {
848
946
  if (!floor) return null
849
947
  return { pct: Math.min(100, Math.round(floor / cfg.contextLimit * 100)), source: 'floor' }
850
948
  }
851
- const tokens = chars / cfg.charsPerToken + (cfg.systemOverheadTokens || 0)
852
- return { pct: Math.min(100, Math.round(tokens / cfg.contextLimit * 100)), source: 'chars' }
949
+ // 拟合值优先(盈不足标定过就用实测参数),没有则退回配置默认值。
950
+ const _fit = _readCalibFit()
951
+ const _ratio = (_fit && _fit.charsPerToken > 0) ? _fit.charsPerToken : cfg.charsPerToken
952
+ const _over = _fit ? _fit.systemOverheadTokens : (cfg.systemOverheadTokens || 0)
953
+ const tokens = chars / _ratio + _over
954
+ return { pct: Math.min(100, Math.round(tokens / cfg.contextLimit * 100)),
955
+ source: _fit ? 'chars+calib' : 'chars' }
853
956
  } catch { return null }
854
957
  }
855
958
 
@@ -116,6 +116,15 @@ recall "不要用 DiskGenius 恢复分区" → ①, ③, ②
116
116
  - 真正的毛病更具体:**肯定查询把「不要用」的禁止记忆排到了第一位,且结果里没有任何标记说明它是禁止项**——模型看到这个,很可能按"要用"去理解。
117
117
 
118
118
  这正是「错卦」算子要解决的事:把查询与其取反一起做,然后**按语义方向过滤/标注**,而不是只依赖词面重合。
119
+
120
+ **✅ 已实现(v5.1)**:`recall` 现在会算「查询极性」与「记忆极性」,
121
+ **方向相反时打标 `polarity_conflict`**,CLI 输出 `⚠ 这条是禁止/否定方向(avoid),与你的查询方向相反——别读反`。
122
+
123
+ 设计上刻意**不静默降权**:把禁令藏起来比标出来更危险——模型可能因此真的去做那件被禁止的事。
124
+ 所以做法是"保留 + 显式标注",把判断权交回给模型/用户。
125
+
126
+ 注:注入路径本来就已经按"已经排除的方向(别再提)"独立成块,不存在这个歧义;
127
+ 缺口只在 `recall` 的检索输出。
119
128
  | **综卦** | 词序反转 | **语序鲁棒性**:中文二元组本就无序,反转后结果应几乎不变;若变化大,说明打分对语序敏感(是个 bug) |
120
129
  | **互卦** | 取中间窗口为核心 | **核心提取**:长记忆的"核"在中段(首尾多是铺垫/尾巴),与现有 `gist` 互补 |
121
130
  | **之卦** | 6 个单 bit 扰动 | **稳定性**:翻转一个关键词,Top-K 不应剧烈变化;变化大 = 召回不稳 |
@@ -129,8 +138,11 @@ recall "不要用 DiskGenius 恢复分区" → ①, ③, ②
129
138
  灵枢的水位估算一直用固定常数 `charsPerToken = 2`(`cordis-plugin/lingshu-cron/plugin.js`),中文语境下这是粗估。而宿主其实偶尔会给**真实 token 数**。
130
139
 
131
140
  **盈不足(双假设法)**就是:拿两次观测 `(chars₁, realTokens₁)`、`(chars₂, realTokens₂)`,解一次线性方程反推真实系数,并据此修正后续估算。
132
- **落地**:把每次"宿主给了真值"的样本记进 `~/.brain-memory/token-calib.jsonl`,用最小二乘拟合 `charsPerToken`,水位估算读拟合值(样本不足时退回 2.0)。
133
- **风险**:低。纯增量,且天然 fail-open。
141
+ **落地(✅ 已实现 v5.2)**:`tokens = chars / ratio + overhead` 有**两个**未知数——所以不是只标 ratio,而是用 ≥2 组 `(chars, tokens)` 做最小二乘**同时反推 ratio 与 overhead**(把写死的 18000 也一起标定,收益比只标 ratio 大)。
142
+ - cron 插件在"宿主给出真实 token"时记一组样本到 `<记忆库>/token-calib.jsonl`(**限流**:60 秒内且字符差 <2000 不记,热路径不加重负担),随即拟合并写 `token-calib.json`;估算时优先用拟合值,`source` 变成 `chars+calib`。
143
+ - 合理性闸:ratio 必须落在 0.5~5、overhead 0~200000、样本 ≥2 且字符跨度 ≥2000,否则**退回配置默认**(宁可用旧的,不用错的)。
144
+ - `brain.py token-calib [--refit] [--json]`:查看样本、并用**同一公式独立重算**与插件写入值**对账**(两边不一致会明确报出来——这是给"JS 侧没法单元测试"补的保险)。
145
+ **风险**:低。只写两个新文件,不碰记忆数据;全程 try/catch;天然 fail-open。
134
146
 
135
147
  #### A4. 六十甲子 → 双周期复习调度
136
148
 
@@ -162,9 +174,10 @@ recall "不要用 DiskGenius 恢复分区" → ①, ③, ②
162
174
 
163
175
  | 顺序 | 项目 | 改动面 | 可验证性 | 建议版本 |
164
176
  |---|---|---|---|---|
165
- | 1 | **A2 错卦**:`recall` 区分否定("不要X" vs "用X") | `memory.py` 召回打分 + 一个测试 | 高(缺陷已实测确认,见 A2 的对照结果) | v5.1 |
177
+ | 1 | ~~**A2 错卦**:`recall` 区分否定~~ **✅ 已做 v5.1** | `memory.py` 加极性识别 + `parts["polarity_conflict"]` | 高(缺陷已实测确认) | v5.1 |
178
+ | 1b | ~~**A1 六爻位体检**~~ **✅ 已做 v5.0**(改用领域不变量,见第六节) | `scripts/shape_audit.py` | 高 | v5.0 |
166
179
  | 2 | **A1 六爻审计**:`memory shape-audit` 64 格热力表 | 新增只读命令 | 高(真库跑一遍就能看出问题) | v5.1 |
167
- | 3 | **A3 盈不足**:`charsPerToken` 自适应标定 | cron 插件 + 一个校准文件 | 中(需要宿主给真值样本) | v5.2 |
180
+ | 3 | ~~**A3 盈不足**~~ **✅ 已做 v5.2**(同时标定 ratio 与 overhead) | cron 插件 + `scripts/token_calib.py` | 中(需宿主给真值样本,会慢慢攒) | v5.2 |
168
181
  | 4 | **A2 其余三算子**:`recall --robust` 稳定性报告 | `memory.py` + CLI | 高(可量化重合率) | v5.2 |
169
182
  | 5 | **A4 双周期复习** | `memory.py` 复习调度 | 中 | 视情况 |
170
183
 
@@ -543,6 +543,22 @@ startup 注入的记忆块与 cron 的瞬态提醒**同名**,于是 cron 的 p
543
543
  - **实测修正**:字面「当位/得中/有应」在真数据上**无区分度**(100% / 75% / 74%),属伪精度;已改为三条领域不变量:**①AI派生+已确认+低置信 13 条(4%)②高置信却在淡忘/归档层 4 条(1%)③稳定事实过期 0 条**。
544
544
  - 结论写进 `docs/借鉴-易经与古典算法.md` 第六节:**易经给的是编码与变换,不是判据**。
545
545
 
546
+ 91. **【已做 v5.1】错卦落地:`recall` 标注否定极性冲突**(研究文档 A2)。
547
+ - **问题**(已实测):`recall "用 DiskGenius 恢复分区"` 与 `recall "不要用…"` **结果集 3/3 完全重合**,且**肯定查询把「不要用」的禁止记忆排到第一位、无任何标记**——模型极易读反。
548
+ - **做法**:`memory._polarity_of()` / `_memory_polarity()`(显式 `avoid` 标记优先,其次正文否定词:不要/别用/勿/禁止/避免/不能/不可/禁用/放弃/不推荐…);`recall` 里比对查询极性与记忆极性,**方向相反时打 `parts["polarity"]` + `parts["polarity_conflict"]`**;CLI `_print_mem` 输出 `⚠ 这条是禁止/否定方向(avoid),与你的查询方向相反——别读反`。
549
+ - **为什么不静默降权**:把禁令藏起来比标出来更危险——模型可能因此真的去做那件被禁止的事。保留 + 显式标注,判断权交回模型/用户。
550
+ - **注入路径本来就没这个歧义**:`--avoid` 记忆注入时独立成块「已经排除的方向(别再提)」,缺口只在 `recall` 的检索输出。
551
+ - 回归 6/6(极性识别 / avoid 标记算 neg / 肯定查询标禁令 / 否定查询标可行做法 / 方向一致不打扰 / CLI 出现 ⚠)。
552
+
553
+ 92. **【已修 v5.2】`shape-audit` 的假阳性:13 条"幻觉风险"全是做梦聚合条目**(我自己的审计规则写错)。
554
+ - **取证**:逐条打印后确认,13 条**全部**是 `最近关于「X」的一组事情(N 条)` 的做梦聚合——已知噪音(v3.93 起已排除在注入/审核之外)。
555
+ - **根因**:聚合条目**没有 `confidence` 字段**,我拿 `importance`(默认 0.45)当置信度代理,于是全被判成"低置信 AI 派生"。
556
+ - **修**:① `audit()` 跳过聚合条目并在报告里注明"已跳过 N 条已知噪音";② 置信位不再用 importance 当代理——有 `confidence` 才用它,否则按"来源是否亲历 / importance≥0.6"判。
557
+ - **修后真库**:286 条(跳过 24 条聚合),① 幻觉风险 **0 条**、② 高置信沉底 3 条、③ 过期 0 条。
558
+ - **顺带处置**:3 条沉底里 #1 是测试消息、#2 正文只有 `list`(退化垃圾)→ 留在淡忘区;#3 是「用户怀疑我删了备份、我核实后证明没删」这类**信任事实**(importance 0.7、user 亲历)→ 已 `memory dust revive` 拉回 cortex,实测 recall 第一条命中(回忆度 0.69)。
559
+
560
+ 93. **【已做 v5.2】盈不足标定水位估算**(研究文档 A3):`tokens = chars/ratio + overhead` 两个未知数,用 ≥2 组真实样本最小二乘同时反推 ratio 与 overhead(不再把 18000 写死)。cron 插件限流记录样本、拟合写 `token-calib.json`,估算 `source` 变 `chars+calib`;`brain.py token-calib [--refit]` 查看并与插件写入值对账。合理性闸:ratio 0.5~5、overhead 0~200000、跨度 ≥2000,不过就退回默认。**注**:JS 改动需重启插件才生效,所以真库当前样本数仍是 0(正常使用会慢慢攒)。
561
+
546
562
  ## 三、已知问题与风险
547
563
 
548
564
  | # | 现象 | 影响 | 处置 |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lingshu-skill",
3
- "version": "5.0.0",
3
+ "version": "5.2.0",
4
4
  "description": "Brain-inspired persistent memory, persona and growth system for AI coding agents. Local-only, zero-dependency Python. Requires Python 3.10+.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "PATCH_NOTES.md": "9296e524f743f358fd11115598398a754cfd69534526dde9c8ad85f14a418f89",
3
3
  "README.md": "3d634d743b085eebd2cbb5dd3a00edfa728ed23947e20cc29e7c3b29087ec043",
4
- "engine/CHANGELOG.md": "72d040ebbad0a2f3f355202721b9a90200b0a70fc6d7c27590089e93226dd967",
5
- "engine/README.md": "d06b18883cf8349951702c28555f74d1db62d9dcb74847543670ab08ba4ec25c",
4
+ "engine/CHANGELOG.md": "a5edcc670c4e723e925bc257ecece7355f940d1a13465f1dd0189f84394d7bcd",
5
+ "engine/README.md": "2df8358d3df2e7005f5628449e696d77cd58e080563448b0dc8cf8b805b86a5c",
6
6
  "engine/SKILL-lite.md": "04b87789232a0f7537c861c857888b4a0e947bcf92a461cbad5328af05361c58",
7
7
  "engine/SKILL-tiny.md": "74e1955cc5bf4ec0ca28d52030f799f039283de27a52345a33ce783d6ee0c608",
8
- "engine/SKILL.md": "6ebbcc175208091f93813f08353f63e557e8990824c1bb95ece8bdeda3963a0f",
8
+ "engine/SKILL.md": "711b359d0710eb413b0fe6e5b70e750b3c38767abf811822fb6ab618076e58bc",
9
9
  "engine/assets/panel.html": "cdb54b41c363e37d3e85daa971a7d4cb1fd971f1788808ae451e2fac5a21ee8b",
10
10
  "engine/docs/commands.md": "454b83814c74d8677c1a02754e4da24c73c1abebaa92a1cdcb0aa0b2e1472432",
11
11
  "engine/docs/mechanics.md": "e8a6602a434ed5b78cac64a98884f65a6888eb48daa7a1c0be1f6c3984041b34",
@@ -19,7 +19,7 @@
19
19
  "engine/scripts/check_pressure_sync.py": "46d53934f17c7b740d0ec9fdbef9d2653850f6e01e883eedd70ff9a1527e869a",
20
20
  "engine/scripts/check_tag.py": "6f0b8209dc2deebb1f9ec90d429e1fad60c040a2ec014a6406d9d3498faafd7f",
21
21
  "engine/scripts/checkpoint.py": "3a9292121042692dc872a865b6ee1c1e5f14c054791887e0791f19ccdb9638fb",
22
- "engine/scripts/cli.py": "f5b4095a9bac5b4ab9c47a5bbfb7fc32a821465604456a65bdd3b246c57caa5a",
22
+ "engine/scripts/cli.py": "adc4fa2c367951519e9b9ed0659ad6b78f826aaa40c9a49ed675d17f5fe38cbd",
23
23
  "engine/scripts/context_ab.py": "3d383f1fc16d328612825bbf731866fa427da0746490d027a0ddb719d210f1cb",
24
24
  "engine/scripts/core.py": "7046d4fb14bded3d5e9c8c716d223b07a9f5855f4d4ba6bf54054df8f30887dd",
25
25
  "engine/scripts/desktop_shortcut.py": "ac202335a9ce32e12729e04d82e62337b880a49c962945e9112482523ce9cc0b",
@@ -37,7 +37,7 @@
37
37
  "engine/scripts/mem_lesson.py": "e1520786315f3e41c829909c739e5af3eee89397da7db5026d106710b2b3c118",
38
38
  "engine/scripts/mem_score.py": "95dcecba5f4db7c0c16ebc415434e1cb58cc7dd8b8213360b4df36e2a90faf6e",
39
39
  "engine/scripts/mem_topic.py": "c22f75c128cdd3b26ff845f1a71608401bc0dc8955f9f0e1988d7f0cd663d0d5",
40
- "engine/scripts/memory.py": "b3e98536b7abd446ed2b5716e1735117d2db072845ff6fdbfde48577bae81acd",
40
+ "engine/scripts/memory.py": "d16efbd9f964f4cb2e10c3e2359da5aa6530f2cd99b1c8f492c01e928c610202",
41
41
  "engine/scripts/npm_prepack.py": "d62c491a6f9edfcab2dd465a995e72df879a61b4da26ae0fe76121c8adc77e02",
42
42
  "engine/scripts/panel_build.py": "6394c1d74d203093e43b2106d7acca6e0ca9db61ca1cd6cd3a1616053653414b",
43
43
  "engine/scripts/panel_cloud.py": "fff72888123d45bbf05ab329a06b2126f1c0b972c76283ecff32454bc4155c58",
@@ -54,8 +54,9 @@
54
54
  "engine/scripts/session_import.py": "31c68069800e6ca8c91aad7869e7e174adc0b1e027ac0a4f7361a2c3a5363b3f",
55
55
  "engine/scripts/session_rag.py": "a62e7cdf0e32c87c0031d0bc289b7864d6981c255af8055dcf02c70a153e7d61",
56
56
  "engine/scripts/session_summary.py": "7f86a47cfb75b5340f748176f3cd2ca2242bd568351f241df6b9bbd6da3e66c0",
57
- "engine/scripts/shape_audit.py": "bce96d9c467bf851648ad681caa75c071ce11593965b1ae2a1f269a12b7fb9d9",
57
+ "engine/scripts/shape_audit.py": "3c361b8138d95c1e11476092e4d4da2eba71d9ed5300857bb3ce9113a8bf3be7",
58
58
  "engine/scripts/summarizer.py": "b9a31094fd55199b111d269bcbb1630cb164e9465bf4f4ed7159dfd0b1d06726",
59
+ "engine/scripts/token_calib.py": "17d3cbbe5cca2bac3ff1d183f56b48460e71cebc8b8f43a299dd1720c5f3821a",
59
60
  "engine/scripts/trash.py": "48c8b8cb2bbbc7c4740fd2103f091fd26c0fb2e0148502150848ee9720ca71b6",
60
61
  "main.py": "ab5eb934e78abd11ebcc34c7226fa66c805b7b8739b00704c47557881c735c47",
61
62
  "metadata.yaml": "1992c16812e971277f6a87336398e2c31b3a2cdd447de32655ffb87da8b4eb4f"
@@ -1,5 +1,37 @@
1
1
  # 更新日志
2
2
 
3
+ ## v5.2(2026-11-24)
4
+
5
+ > 主题:**盈不足标定水位估算** + 修掉 `shape-audit` 的假阳性。
6
+
7
+ ### 盈不足(双假设法)标定(#93)
8
+
9
+ - 估算模型 `tokens = chars / ratio + overhead` 有**两个**未知数。宿主给出真实 token 时,cron 插件记一组 `(chars, tokens)`,用**最小二乘同时反推 ratio 与 overhead**(不再把 overhead 写死 18000——那才是误差大头)。
10
+ - 记录**限流**(60 秒内且字符差 <2000 不记),热路径不加重负担;拟合写 `<记忆库>/token-calib.json`,估算 `source` 变 `chars+calib`。
11
+ - 合理性闸:ratio 0.5~5、overhead 0~200000、样本 ≥2 且字符跨度 ≥2000,**不过就退回配置默认**(宁用旧的不用错的)。
12
+ - `brain.py token-calib [--refit] [--json]`:看样本,并用**同一公式独立重算**与插件写入值**对账**——两边不一致会明确报错(补"JS 侧没法单元测试"的保险)。
13
+
14
+ ### 修 `shape-audit` 假阳性(#92)
15
+
16
+ - **13 条"幻觉风险"全是假阳性**:逐条打印后确认,全部是 `最近关于「X」的一组事情(N 条)` 的**做梦聚合**(已知噪音)。
17
+ - 根因:聚合条目没有 `confidence` 字段,我拿 `importance`(默认 0.45)当代理 → 全被判"低置信 AI 派生"。
18
+ - 修:`audit()` 跳过聚合并注明跳过数;置信位不再用 importance 当代理。
19
+ - 修后真库:286 条(跳过 24 条聚合),幻觉风险 **0 条**。
20
+ - 顺带:3 条"高置信沉底"里,1 条测试消息 + 1 条正文只有 `list`(退化垃圾)留在淡忘区;1 条**信任事实**("用户怀疑我删了备份、我核实证明没删")已 `dust revive` 拉回 cortex,recall 实测第一条命中。
21
+
22
+ 验证:`tests/test_p19_token_calib.py` 7/7(拟合还原已知参数 / 需≥2样本 / 需跨度 / 拒荒谬值 / 样本读回与渲染 / **JS 与 Python 常量一致** / CLI 冒烟)。
23
+
24
+ ## v5.1(2026-11-24)
25
+
26
+ > 主题:**错卦落地**——`recall` 不再把"不要用 X"当成"要用 X"。
27
+
28
+ - **实测确认的问题**:`recall "用 DiskGenius 恢复分区"` 与 `recall "不要用…"` **结果集 3/3 完全重合**(仅排序不同),且**肯定查询把「不要用」的禁止记忆排到第一位、结果里没有任何标记**——模型看到极易读反。
29
+ - **做法**:新增极性识别 `_polarity_of()` / `_memory_polarity()`(显式 `avoid` 标记优先,其次正文否定词:不要/别用/勿/禁止/避免/不能/不可/禁用/放弃/不推荐…);`recall` 比对查询极性与记忆极性,**方向相反时打 `parts["polarity_conflict"]`**;CLI 输出 `⚠ 这条是禁止/否定方向(avoid),与你的查询方向相反——别读反`。
30
+ - **刻意不静默降权**:把禁令藏起来比标出来更危险(模型可能真去做那件被禁止的事)。做法是"保留 + 显式标注",判断权交回模型/用户。
31
+ - **注入路径本来就没这问题**:`--avoid` 记忆注入时独立成块「已经排除的方向(别再提)」,缺口只在 `recall` 输出。
32
+
33
+ 验证:`tests/test_p18_polarity.py` 6/6(极性识别 / avoid 标记算 neg / 肯定查询标禁令 / 否定查询标可行做法 / 方向一致不打扰 / CLI 出现 ⚠)。
34
+
3
35
  ## v5.0(2026-11-24)
4
36
 
5
37
  > 主题:**底层保险(写前快照 + 写后校验 + 自动回滚)** + 六爻位体检。
@@ -2,7 +2,7 @@
2
2
 
3
3
  > 名字取自《黄帝内经》:**算力给思考,人格给灵魂,记忆给生命。**
4
4
 
5
- > 当前版本 **v5.0**(变更见 [CHANGELOG.md](CHANGELOG.md))
5
+ > 当前版本 **v5.2**(变更见 [CHANGELOG.md](CHANGELOG.md))
6
6
 
7
7
  > 🔁 **双仓库镜像**:GitHub(主)与 Gitee(镜像)保持同步——[gitee.com/htmcwy_0/lingshu-skill](https://gitee.com/htmcwy_0/lingshu-skill)。灵枢的更新检查会探测两边最新提交,**谁更新就自动从谁拉取**;任一边不可达(Gitee 匿名风控 / GitHub 限额)时走另一边兜底。
8
8
 
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: lingshu
3
3
  title: 灵枢
4
- version: 5.0
4
+ version: 5.2
5
5
  description: 类脑持久记忆、人格与成长系统——跨会话记住事情、长出自己的人格、上下文将满时做梦式整理记忆。用户提到记忆/记住/上次/人格/设定/性格/知识库/笔记/日志/成长/自我进化/工作记忆,或新会话开始需要恢复关系与上下文时使用。纯本地零依赖。
6
6
  ---
7
7
 
@@ -1301,6 +1301,9 @@ def _print_mem(m: dict, score: float | None = None, parts: dict | None = None) -
1301
1301
  print(head)
1302
1302
  print(f" {m['id']}")
1303
1303
  print(f" {display_text(m)}")
1304
+ # 错卦(v5.1):方向相反的记忆要明说,否则"不要用 X"会被当成"要用 X"读
1305
+ if parts and parts.get("polarity_conflict"):
1306
+ print(" ⚠ 这条是禁止/否定方向(avoid),与你的查询方向相反——别读反")
1304
1307
  if m.get("tags") or m.get("entities"):
1305
1308
  print(f" 标签: {'、'.join(m.get('tags', []))} 实体: {'、'.join(m.get('entities', []))}")
1306
1309
  print()
@@ -1578,6 +1581,13 @@ def _main(argv=None) -> int:
1578
1581
  p_tr.add_argument("--json", action="store_true")
1579
1582
 
1580
1583
  # P11 #76 桌面快捷方式「灵枢面板」
1584
+ p_tc = sub.add_parser(
1585
+ "token-calib",
1586
+ help="水位估算标定(盈不足/双假设法):看样本与拟合值,并与插件写入值对账")
1587
+ p_tc.add_argument("--refit", action="store_true",
1588
+ help="用 Python 独立重算并写回 token-calib.json(以 Python 为准)")
1589
+ p_tc.add_argument("--json", action="store_true")
1590
+
1581
1591
  p_sc = sub.add_parser("shortcut", help="在桌面生成/删除「灵枢面板」快捷方式(静默启动面板)")
1582
1592
  p_sc.add_argument("--name", default="灵枢面板", help="快捷方式名字(默认 灵枢面板)")
1583
1593
  p_sc.add_argument("--port", type=int, default=0, help="固定端口(默认读 config.panel_port)")
@@ -2602,6 +2612,17 @@ def _main(argv=None) -> int:
2602
2612
  print("没有删除任何东西;要清空请你自己动手。")
2603
2613
  return 0 if res["ok"] else 1
2604
2614
 
2615
+ if args.cmd == "token-calib":
2616
+ import token_calib as _tcal
2617
+ rep = _tcal.refit(write=args.refit)
2618
+ if args.json:
2619
+ print(json.dumps(rep, ensure_ascii=False, indent=2))
2620
+ return 0 if rep.get("ok") else 1
2621
+ print(_tcal.render(rep))
2622
+ if args.refit and rep.get("fit"):
2623
+ print("\n已用 Python 结果重写 token-calib.json")
2624
+ return 0
2625
+
2605
2626
  if args.cmd == "shortcut":
2606
2627
  import desktop_shortcut as _ds
2607
2628
  if args.remove:
@@ -1938,6 +1938,36 @@ def dereference(memory_id: str) -> list:
1938
1938
  return out
1939
1939
 
1940
1940
 
1941
+ # ---------------------------------------------------------------- 错卦:否定极性
1942
+ # 「错卦」在易经里是六爻全变(按位取反)。借到检索上就是**否定极性**:
1943
+ # "用 X" 和 "不要用 X" 是两个方向,不该拿到同一批无标记的结果。
1944
+ #
1945
+ # 实测问题(2026-11-24,隔离库三条记忆):
1946
+ # recall "用 DiskGenius 恢复分区" → ①不要用…(排第一)②用…可行 ③先做镜像
1947
+ # recall "不要用 DiskGenius 恢复分区" → ①不要用… ③先做镜像 ②用…可行
1948
+ # 结果集 3/3 完全重合,且**肯定查询把「不要用」的禁止记忆排到第一位、无任何标记**。
1949
+ # 模型看到这个很容易读反,所以这里不静默降权(把禁令藏起来更危险),
1950
+ # 而是**把冲突标出来**,交给调用方/模型自己判断。
1951
+ _POLARITY_NEG = re.compile(
1952
+ r"不要|别用|别再|别碰|别动|不要再|勿|切勿|禁止|避免|不能|不可|禁用|放弃|"
1953
+ r"不推荐|不建议|不需要|无需|千万别")
1954
+
1955
+
1956
+ def _polarity_of(text: str) -> str:
1957
+ """文本的否定极性:'neg'(否定/禁止)或 'pos'(肯定)。空文本返回 ''。"""
1958
+ s = str(text or "").strip()
1959
+ if not s:
1960
+ return ""
1961
+ return "neg" if _POLARITY_NEG.search(s) else "pos"
1962
+
1963
+
1964
+ def _memory_polarity(rec: dict) -> str:
1965
+ """一条记忆的极性:显式 avoid 标记优先,否则看正文。"""
1966
+ if rec.get("avoid"):
1967
+ return "neg"
1968
+ return _polarity_of(rec.get("text") or "")
1969
+
1970
+
1941
1971
  def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
1942
1972
  strengthen: bool = True, include_dust: bool = False,
1943
1973
  include_archive: bool = False,
@@ -2302,6 +2332,19 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
2302
2332
  kept_texts.append(txt)
2303
2333
  result = kept
2304
2334
 
2335
+ # 错卦(v5.1):标注"查询方向"与"记忆极性"的冲突。
2336
+ # 只在**方向相反**时打标(查询肯定↔记忆禁止,或反之),一致时不打扰。
2337
+ try:
2338
+ _qp = _polarity_of(query)
2339
+ if _qp:
2340
+ for _m, _s, _p in result:
2341
+ _mp = _memory_polarity(_m)
2342
+ if _mp and _mp != _qp and isinstance(_p, dict):
2343
+ _p["polarity"] = _mp
2344
+ _p["polarity_conflict"] = True
2345
+ except Exception:
2346
+ pass
2347
+
2305
2348
  if strengthen and not READONLY:
2306
2349
  touched = [m for m, _, _ in result]
2307
2350
  for m in touched:
@@ -55,9 +55,18 @@ def signature(rec: dict) -> int:
55
55
  bits.append(1 if str(rec.get("review") or "") == "confirmed" else 0) # 二:审核
56
56
  bits.append(1 if str(rec.get("layer") or "") in HOT_LAYERS else 0) # 三:层
57
57
  bits.append(1 if str(rec.get("kind") or "") in STABLE_KINDS else 0) # 四:类型
58
+ # 五:置信。**不能用 importance 当代理**——做梦产物根本没有 confidence 字段,
59
+ # 它的 importance 是默认值(0.45),当成"低置信"会批量误判(实测 13 条全是假阳性)。
60
+ # 规则:有 confidence 就用它;没有就按"来源是否亲历"判断,只有明确 AI 派生
61
+ # 且 importance 也偏低才算低置信。
58
62
  conf = rec.get("confidence")
59
- conf = _num(conf, _num(rec.get("importance"), 0.5))
60
- bits.append(1 if conf >= 0.6 else 0) # 五:置信
63
+ if conf is None:
64
+ src_l = str(rec.get("source") or "")
65
+ imp = _num(rec.get("importance"), 0.5)
66
+ conf_hi = 1 if (src_l in ("user", "checkpoint") or imp >= 0.6) else 0
67
+ else:
68
+ conf_hi = 1 if _num(conf, 0.5) >= 0.6 else 0
69
+ bits.append(conf_hi) # 五:置信
61
70
  rb = rec.get("review_by")
62
71
  expired = bool(rb) and _num(rb, 0) > 0 and _num(rb, 0) < core.now_ts()
63
72
  bits.append(0 if expired else 1) # 上:时效
@@ -105,7 +114,14 @@ def audit(limit: int = 2000) -> dict:
105
114
  records = mem.load_all()
106
115
  except Exception as exc: # noqa: BLE001
107
116
  return {"error": f"读取记忆库失败:{exc}"}
108
- records = [r for r in records if isinstance(r, dict) and r.get("id")][:limit]
117
+ # 做梦聚合条目是已知噪音(派生视图,无独立信息),不计入体检——
118
+ # 否则它们会占满"幻觉风险"桶,把真问题淹掉(实测 13/13 全是这类)。
119
+ records = [r for r in records
120
+ if isinstance(r, dict) and r.get("id")
121
+ and not mem._is_dream_aggregate(r.get("text", ""))][:limit]
122
+ skipped_agg = sum(1 for r in (mem.load_all() or [])
123
+ if isinstance(r, dict) and r.get("id")
124
+ and mem._is_dream_aggregate(r.get("text", "")))
109
125
 
110
126
  cells = Counter()
111
127
  buckets = {"hallucination": [], "sunk": [], "stale": []}
@@ -137,8 +153,9 @@ def audit(limit: int = 2000) -> dict:
137
153
  "sunk": len(buckets["sunk"]),
138
154
  "stale": len(buckets["stale"]),
139
155
  "samples": {k: v[:8] for k, v in buckets.items()},
156
+ "skipped_aggregates": skipped_agg,
140
157
  "note": ("字面「当位/得中/有应」在本数据上无区分度(实测 100%/75%/74%),"
141
- "已改用三条领域不变量"),
158
+ "已改用三条领域不变量;做梦聚合条目已跳过(它们是已知噪音)"),
142
159
  }
143
160
 
144
161
 
@@ -147,8 +164,10 @@ def render(rep: dict, top: int = 12) -> str:
147
164
  if rep.get("error"):
148
165
  return f"[错误] {rep['error']}"
149
166
  total = rep["total"]
167
+ skip = rep.get("skipped_aggregates") or 0
168
+ extra = f";已跳过 {skip} 条做梦聚合条目(已知噪音)" if skip else ""
150
169
  lines = [f"六爻位体检:共 {total} 条记忆,落在 {rep['distinct_cells']}/64 格"
151
- f"(结构干净 {rep['clean']} 条)", ""]
170
+ f"(结构干净 {rep['clean']} 条{extra})", ""]
152
171
  lines.append("领域不变量违规(这些是真问题,不是玄学):")
153
172
  for key, label in (("hallucination", "① AI 派生+已确认+低置信(幻觉风险)"),
154
173
  ("sunk", "② 高置信却在淡忘/归档层(可能被误淡忘)"),
@@ -0,0 +1,144 @@
1
+ # -*- coding: utf-8 -*-
2
+ """水位估算标定(盈不足/双假设法)的查看与交叉验证。
3
+
4
+ 模型:`tokens = chars / charsPerToken + systemOverheadTokens`
5
+ 两个未知数。宿主给出真实 token 时,cron 插件会记一组 `(chars, tokens)` 样本,
6
+ 并用最小二乘同时反推 ratio 与 overhead(写在 `<记忆库>/token-calib.json`)。
7
+
8
+ 本模块做两件事:
9
+ 1. `show()` —— 把样本与插件写下的拟合结果摊开给人看;
10
+ 2. `refit()` —— **用同一套公式独立算一遍**,与插件的拟合值对账。
11
+ 两边不一致就说明有一边写错了(这是给"JS 侧算法没法单元测试"补的保险)。
12
+
13
+ 只读为主:`refit(write=True)` 才会写 `token-calib.json`。
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ from pathlib import Path
19
+
20
+ import core
21
+
22
+ SAMPLES = "token-calib.jsonl"
23
+ FIT = "token-calib.json"
24
+ MIN_SPAN = 2000 # 样本字符跨度下限(跨度太小解不稳定)
25
+ MAX_SAMPLES = 500
26
+
27
+
28
+ def _paths():
29
+ home = Path(core.HOME)
30
+ return home / SAMPLES, home / FIT
31
+
32
+
33
+ def load_samples(limit: int = MAX_SAMPLES) -> list:
34
+ sp, _ = _paths()
35
+ if not sp.is_file():
36
+ return []
37
+ out = []
38
+ try:
39
+ for line in sp.read_text(encoding="utf-8", errors="replace").splitlines():
40
+ line = line.strip()
41
+ if not line:
42
+ continue
43
+ try:
44
+ o = json.loads(line)
45
+ except Exception:
46
+ continue
47
+ if isinstance(o, dict) and o.get("chars", 0) > 0 and o.get("tokens", 0) > 0:
48
+ out.append({"chars": float(o["chars"]), "tokens": float(o["tokens"]),
49
+ "at": int(o.get("at") or 0)})
50
+ except OSError:
51
+ return []
52
+ return out[-limit:]
53
+
54
+
55
+ def fit(samples: list) -> dict | None:
56
+ """最小二乘 y = a + b·x(x=字符数,y=token)。与插件 _fitFrom 同公式。"""
57
+ n = len(samples)
58
+ if n < 2:
59
+ return None
60
+ xs = [s["chars"] for s in samples]
61
+ ys = [s["tokens"] for s in samples]
62
+ if max(xs) - min(xs) < MIN_SPAN:
63
+ return None
64
+ mx = sum(xs) / n
65
+ my = sum(ys) / n
66
+ sxx = sum((x - mx) ** 2 for x in xs)
67
+ sxy = sum((x - mx) * (y - my) for x, y in zip(xs, ys))
68
+ if sxx <= 0:
69
+ return None
70
+ b = sxy / sxx
71
+ a = my - b * mx
72
+ if b <= 0:
73
+ return None
74
+ ratio = 1 / b
75
+ if not (0.5 <= ratio <= 5):
76
+ return None
77
+ if not (0 <= a <= 200000):
78
+ return None
79
+ return {"charsPerToken": round(ratio, 3),
80
+ "systemOverheadTokens": int(round(a)), "samples": n}
81
+
82
+
83
+ def stored_fit() -> dict | None:
84
+ _, fp = _paths()
85
+ if not fp.is_file():
86
+ return None
87
+ try:
88
+ j = json.loads(fp.read_text(encoding="utf-8"))
89
+ return j if isinstance(j, dict) else None
90
+ except Exception:
91
+ return None
92
+
93
+
94
+ def refit(write: bool = False) -> dict:
95
+ """独立重算一遍,并与插件写下的值对账。"""
96
+ samples = load_samples()
97
+ mine = fit(samples)
98
+ theirs = stored_fit()
99
+ agree = None
100
+ if mine and theirs:
101
+ try:
102
+ agree = (abs(float(theirs.get("charsPerToken") or 0) - mine["charsPerToken"]) < 0.01
103
+ and abs(int(theirs.get("systemOverheadTokens") or 0)
104
+ - mine["systemOverheadTokens"]) <= 50)
105
+ except Exception:
106
+ agree = False
107
+ if write and mine:
108
+ _, fp = _paths()
109
+ try:
110
+ core.atomic_json(fp, {**mine, "source": "python-refit"})
111
+ except Exception as exc: # noqa: BLE001
112
+ return {"ok": False, "error": str(exc), "fit": mine, "stored": theirs}
113
+ return {"ok": True, "samples": len(samples), "fit": mine,
114
+ "stored": theirs, "agree": agree}
115
+
116
+
117
+ def render(rep: dict | None = None) -> str:
118
+ rep = rep or refit()
119
+ lines = []
120
+ n = rep.get("samples") or 0
121
+ lines.append(f"水位标定样本:{n} 组(模型 tokens = chars / ratio + overhead)")
122
+ if n < 2:
123
+ lines.append(" 样本不足(至少 2 组、且字符跨度 ≥2000 才有解)。")
124
+ lines.append(" 样本由 cron 插件在\"宿主给出真实 token\"时自动记录,正常使用会慢慢攒。")
125
+ fitd = rep.get("fit")
126
+ if fitd:
127
+ lines.append(f" 独立重算:charsPerToken={fitd['charsPerToken']} "
128
+ f"overhead={fitd['systemOverheadTokens']} n={fitd['samples']}")
129
+ elif n >= 2:
130
+ lines.append(" 有样本但跨度不够或拟合越界,暂不用(保守起见退回配置默认)。")
131
+ stored = rep.get("stored")
132
+ if stored:
133
+ lines.append(f" 插件已写入:charsPerToken={stored.get('charsPerToken')} "
134
+ f"overhead={stored.get('systemOverheadTokens')} "
135
+ f"n={stored.get('samples')}")
136
+ if rep.get("agree") is False:
137
+ lines.append(" ⚠ 两边结果不一致——说明有一侧算错,需要查(用 --refit 以 Python 为准重写)。")
138
+ elif rep.get("agree") is True:
139
+ lines.append(" ✓ 两边一致")
140
+ else:
141
+ lines.append(" 插件还没写过拟合值(会退回配置默认 charsPerToken/overhead)。")
142
+ lines.append("")
143
+ lines.append("默认配置:charsPerToken=2、systemOverheadTokens=18000(都可在 config.json 覆盖)")
144
+ return "\n".join(lines)
package/scripts/cli.py CHANGED
@@ -1301,6 +1301,9 @@ def _print_mem(m: dict, score: float | None = None, parts: dict | None = None) -
1301
1301
  print(head)
1302
1302
  print(f" {m['id']}")
1303
1303
  print(f" {display_text(m)}")
1304
+ # 错卦(v5.1):方向相反的记忆要明说,否则"不要用 X"会被当成"要用 X"读
1305
+ if parts and parts.get("polarity_conflict"):
1306
+ print(" ⚠ 这条是禁止/否定方向(avoid),与你的查询方向相反——别读反")
1304
1307
  if m.get("tags") or m.get("entities"):
1305
1308
  print(f" 标签: {'、'.join(m.get('tags', []))} 实体: {'、'.join(m.get('entities', []))}")
1306
1309
  print()
@@ -1578,6 +1581,13 @@ def _main(argv=None) -> int:
1578
1581
  p_tr.add_argument("--json", action="store_true")
1579
1582
 
1580
1583
  # P11 #76 桌面快捷方式「灵枢面板」
1584
+ p_tc = sub.add_parser(
1585
+ "token-calib",
1586
+ help="水位估算标定(盈不足/双假设法):看样本与拟合值,并与插件写入值对账")
1587
+ p_tc.add_argument("--refit", action="store_true",
1588
+ help="用 Python 独立重算并写回 token-calib.json(以 Python 为准)")
1589
+ p_tc.add_argument("--json", action="store_true")
1590
+
1581
1591
  p_sc = sub.add_parser("shortcut", help="在桌面生成/删除「灵枢面板」快捷方式(静默启动面板)")
1582
1592
  p_sc.add_argument("--name", default="灵枢面板", help="快捷方式名字(默认 灵枢面板)")
1583
1593
  p_sc.add_argument("--port", type=int, default=0, help="固定端口(默认读 config.panel_port)")
@@ -2602,6 +2612,17 @@ def _main(argv=None) -> int:
2602
2612
  print("没有删除任何东西;要清空请你自己动手。")
2603
2613
  return 0 if res["ok"] else 1
2604
2614
 
2615
+ if args.cmd == "token-calib":
2616
+ import token_calib as _tcal
2617
+ rep = _tcal.refit(write=args.refit)
2618
+ if args.json:
2619
+ print(json.dumps(rep, ensure_ascii=False, indent=2))
2620
+ return 0 if rep.get("ok") else 1
2621
+ print(_tcal.render(rep))
2622
+ if args.refit and rep.get("fit"):
2623
+ print("\n已用 Python 结果重写 token-calib.json")
2624
+ return 0
2625
+
2605
2626
  if args.cmd == "shortcut":
2606
2627
  import desktop_shortcut as _ds
2607
2628
  if args.remove:
package/scripts/memory.py CHANGED
@@ -1938,6 +1938,36 @@ def dereference(memory_id: str) -> list:
1938
1938
  return out
1939
1939
 
1940
1940
 
1941
+ # ---------------------------------------------------------------- 错卦:否定极性
1942
+ # 「错卦」在易经里是六爻全变(按位取反)。借到检索上就是**否定极性**:
1943
+ # "用 X" 和 "不要用 X" 是两个方向,不该拿到同一批无标记的结果。
1944
+ #
1945
+ # 实测问题(2026-11-24,隔离库三条记忆):
1946
+ # recall "用 DiskGenius 恢复分区" → ①不要用…(排第一)②用…可行 ③先做镜像
1947
+ # recall "不要用 DiskGenius 恢复分区" → ①不要用… ③先做镜像 ②用…可行
1948
+ # 结果集 3/3 完全重合,且**肯定查询把「不要用」的禁止记忆排到第一位、无任何标记**。
1949
+ # 模型看到这个很容易读反,所以这里不静默降权(把禁令藏起来更危险),
1950
+ # 而是**把冲突标出来**,交给调用方/模型自己判断。
1951
+ _POLARITY_NEG = re.compile(
1952
+ r"不要|别用|别再|别碰|别动|不要再|勿|切勿|禁止|避免|不能|不可|禁用|放弃|"
1953
+ r"不推荐|不建议|不需要|无需|千万别")
1954
+
1955
+
1956
+ def _polarity_of(text: str) -> str:
1957
+ """文本的否定极性:'neg'(否定/禁止)或 'pos'(肯定)。空文本返回 ''。"""
1958
+ s = str(text or "").strip()
1959
+ if not s:
1960
+ return ""
1961
+ return "neg" if _POLARITY_NEG.search(s) else "pos"
1962
+
1963
+
1964
+ def _memory_polarity(rec: dict) -> str:
1965
+ """一条记忆的极性:显式 avoid 标记优先,否则看正文。"""
1966
+ if rec.get("avoid"):
1967
+ return "neg"
1968
+ return _polarity_of(rec.get("text") or "")
1969
+
1970
+
1941
1971
  def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
1942
1972
  strengthen: bool = True, include_dust: bool = False,
1943
1973
  include_archive: bool = False,
@@ -2302,6 +2332,19 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
2302
2332
  kept_texts.append(txt)
2303
2333
  result = kept
2304
2334
 
2335
+ # 错卦(v5.1):标注"查询方向"与"记忆极性"的冲突。
2336
+ # 只在**方向相反**时打标(查询肯定↔记忆禁止,或反之),一致时不打扰。
2337
+ try:
2338
+ _qp = _polarity_of(query)
2339
+ if _qp:
2340
+ for _m, _s, _p in result:
2341
+ _mp = _memory_polarity(_m)
2342
+ if _mp and _mp != _qp and isinstance(_p, dict):
2343
+ _p["polarity"] = _mp
2344
+ _p["polarity_conflict"] = True
2345
+ except Exception:
2346
+ pass
2347
+
2305
2348
  if strengthen and not READONLY:
2306
2349
  touched = [m for m, _, _ in result]
2307
2350
  for m in touched:
@@ -55,9 +55,18 @@ def signature(rec: dict) -> int:
55
55
  bits.append(1 if str(rec.get("review") or "") == "confirmed" else 0) # 二:审核
56
56
  bits.append(1 if str(rec.get("layer") or "") in HOT_LAYERS else 0) # 三:层
57
57
  bits.append(1 if str(rec.get("kind") or "") in STABLE_KINDS else 0) # 四:类型
58
+ # 五:置信。**不能用 importance 当代理**——做梦产物根本没有 confidence 字段,
59
+ # 它的 importance 是默认值(0.45),当成"低置信"会批量误判(实测 13 条全是假阳性)。
60
+ # 规则:有 confidence 就用它;没有就按"来源是否亲历"判断,只有明确 AI 派生
61
+ # 且 importance 也偏低才算低置信。
58
62
  conf = rec.get("confidence")
59
- conf = _num(conf, _num(rec.get("importance"), 0.5))
60
- bits.append(1 if conf >= 0.6 else 0) # 五:置信
63
+ if conf is None:
64
+ src_l = str(rec.get("source") or "")
65
+ imp = _num(rec.get("importance"), 0.5)
66
+ conf_hi = 1 if (src_l in ("user", "checkpoint") or imp >= 0.6) else 0
67
+ else:
68
+ conf_hi = 1 if _num(conf, 0.5) >= 0.6 else 0
69
+ bits.append(conf_hi) # 五:置信
61
70
  rb = rec.get("review_by")
62
71
  expired = bool(rb) and _num(rb, 0) > 0 and _num(rb, 0) < core.now_ts()
63
72
  bits.append(0 if expired else 1) # 上:时效
@@ -105,7 +114,14 @@ def audit(limit: int = 2000) -> dict:
105
114
  records = mem.load_all()
106
115
  except Exception as exc: # noqa: BLE001
107
116
  return {"error": f"读取记忆库失败:{exc}"}
108
- records = [r for r in records if isinstance(r, dict) and r.get("id")][:limit]
117
+ # 做梦聚合条目是已知噪音(派生视图,无独立信息),不计入体检——
118
+ # 否则它们会占满"幻觉风险"桶,把真问题淹掉(实测 13/13 全是这类)。
119
+ records = [r for r in records
120
+ if isinstance(r, dict) and r.get("id")
121
+ and not mem._is_dream_aggregate(r.get("text", ""))][:limit]
122
+ skipped_agg = sum(1 for r in (mem.load_all() or [])
123
+ if isinstance(r, dict) and r.get("id")
124
+ and mem._is_dream_aggregate(r.get("text", "")))
109
125
 
110
126
  cells = Counter()
111
127
  buckets = {"hallucination": [], "sunk": [], "stale": []}
@@ -137,8 +153,9 @@ def audit(limit: int = 2000) -> dict:
137
153
  "sunk": len(buckets["sunk"]),
138
154
  "stale": len(buckets["stale"]),
139
155
  "samples": {k: v[:8] for k, v in buckets.items()},
156
+ "skipped_aggregates": skipped_agg,
140
157
  "note": ("字面「当位/得中/有应」在本数据上无区分度(实测 100%/75%/74%),"
141
- "已改用三条领域不变量"),
158
+ "已改用三条领域不变量;做梦聚合条目已跳过(它们是已知噪音)"),
142
159
  }
143
160
 
144
161
 
@@ -147,8 +164,10 @@ def render(rep: dict, top: int = 12) -> str:
147
164
  if rep.get("error"):
148
165
  return f"[错误] {rep['error']}"
149
166
  total = rep["total"]
167
+ skip = rep.get("skipped_aggregates") or 0
168
+ extra = f";已跳过 {skip} 条做梦聚合条目(已知噪音)" if skip else ""
150
169
  lines = [f"六爻位体检:共 {total} 条记忆,落在 {rep['distinct_cells']}/64 格"
151
- f"(结构干净 {rep['clean']} 条)", ""]
170
+ f"(结构干净 {rep['clean']} 条{extra})", ""]
152
171
  lines.append("领域不变量违规(这些是真问题,不是玄学):")
153
172
  for key, label in (("hallucination", "① AI 派生+已确认+低置信(幻觉风险)"),
154
173
  ("sunk", "② 高置信却在淡忘/归档层(可能被误淡忘)"),
@@ -0,0 +1,144 @@
1
+ # -*- coding: utf-8 -*-
2
+ """水位估算标定(盈不足/双假设法)的查看与交叉验证。
3
+
4
+ 模型:`tokens = chars / charsPerToken + systemOverheadTokens`
5
+ 两个未知数。宿主给出真实 token 时,cron 插件会记一组 `(chars, tokens)` 样本,
6
+ 并用最小二乘同时反推 ratio 与 overhead(写在 `<记忆库>/token-calib.json`)。
7
+
8
+ 本模块做两件事:
9
+ 1. `show()` —— 把样本与插件写下的拟合结果摊开给人看;
10
+ 2. `refit()` —— **用同一套公式独立算一遍**,与插件的拟合值对账。
11
+ 两边不一致就说明有一边写错了(这是给"JS 侧算法没法单元测试"补的保险)。
12
+
13
+ 只读为主:`refit(write=True)` 才会写 `token-calib.json`。
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ from pathlib import Path
19
+
20
+ import core
21
+
22
+ SAMPLES = "token-calib.jsonl"
23
+ FIT = "token-calib.json"
24
+ MIN_SPAN = 2000 # 样本字符跨度下限(跨度太小解不稳定)
25
+ MAX_SAMPLES = 500
26
+
27
+
28
+ def _paths():
29
+ home = Path(core.HOME)
30
+ return home / SAMPLES, home / FIT
31
+
32
+
33
+ def load_samples(limit: int = MAX_SAMPLES) -> list:
34
+ sp, _ = _paths()
35
+ if not sp.is_file():
36
+ return []
37
+ out = []
38
+ try:
39
+ for line in sp.read_text(encoding="utf-8", errors="replace").splitlines():
40
+ line = line.strip()
41
+ if not line:
42
+ continue
43
+ try:
44
+ o = json.loads(line)
45
+ except Exception:
46
+ continue
47
+ if isinstance(o, dict) and o.get("chars", 0) > 0 and o.get("tokens", 0) > 0:
48
+ out.append({"chars": float(o["chars"]), "tokens": float(o["tokens"]),
49
+ "at": int(o.get("at") or 0)})
50
+ except OSError:
51
+ return []
52
+ return out[-limit:]
53
+
54
+
55
+ def fit(samples: list) -> dict | None:
56
+ """最小二乘 y = a + b·x(x=字符数,y=token)。与插件 _fitFrom 同公式。"""
57
+ n = len(samples)
58
+ if n < 2:
59
+ return None
60
+ xs = [s["chars"] for s in samples]
61
+ ys = [s["tokens"] for s in samples]
62
+ if max(xs) - min(xs) < MIN_SPAN:
63
+ return None
64
+ mx = sum(xs) / n
65
+ my = sum(ys) / n
66
+ sxx = sum((x - mx) ** 2 for x in xs)
67
+ sxy = sum((x - mx) * (y - my) for x, y in zip(xs, ys))
68
+ if sxx <= 0:
69
+ return None
70
+ b = sxy / sxx
71
+ a = my - b * mx
72
+ if b <= 0:
73
+ return None
74
+ ratio = 1 / b
75
+ if not (0.5 <= ratio <= 5):
76
+ return None
77
+ if not (0 <= a <= 200000):
78
+ return None
79
+ return {"charsPerToken": round(ratio, 3),
80
+ "systemOverheadTokens": int(round(a)), "samples": n}
81
+
82
+
83
+ def stored_fit() -> dict | None:
84
+ _, fp = _paths()
85
+ if not fp.is_file():
86
+ return None
87
+ try:
88
+ j = json.loads(fp.read_text(encoding="utf-8"))
89
+ return j if isinstance(j, dict) else None
90
+ except Exception:
91
+ return None
92
+
93
+
94
+ def refit(write: bool = False) -> dict:
95
+ """独立重算一遍,并与插件写下的值对账。"""
96
+ samples = load_samples()
97
+ mine = fit(samples)
98
+ theirs = stored_fit()
99
+ agree = None
100
+ if mine and theirs:
101
+ try:
102
+ agree = (abs(float(theirs.get("charsPerToken") or 0) - mine["charsPerToken"]) < 0.01
103
+ and abs(int(theirs.get("systemOverheadTokens") or 0)
104
+ - mine["systemOverheadTokens"]) <= 50)
105
+ except Exception:
106
+ agree = False
107
+ if write and mine:
108
+ _, fp = _paths()
109
+ try:
110
+ core.atomic_json(fp, {**mine, "source": "python-refit"})
111
+ except Exception as exc: # noqa: BLE001
112
+ return {"ok": False, "error": str(exc), "fit": mine, "stored": theirs}
113
+ return {"ok": True, "samples": len(samples), "fit": mine,
114
+ "stored": theirs, "agree": agree}
115
+
116
+
117
+ def render(rep: dict | None = None) -> str:
118
+ rep = rep or refit()
119
+ lines = []
120
+ n = rep.get("samples") or 0
121
+ lines.append(f"水位标定样本:{n} 组(模型 tokens = chars / ratio + overhead)")
122
+ if n < 2:
123
+ lines.append(" 样本不足(至少 2 组、且字符跨度 ≥2000 才有解)。")
124
+ lines.append(" 样本由 cron 插件在\"宿主给出真实 token\"时自动记录,正常使用会慢慢攒。")
125
+ fitd = rep.get("fit")
126
+ if fitd:
127
+ lines.append(f" 独立重算:charsPerToken={fitd['charsPerToken']} "
128
+ f"overhead={fitd['systemOverheadTokens']} n={fitd['samples']}")
129
+ elif n >= 2:
130
+ lines.append(" 有样本但跨度不够或拟合越界,暂不用(保守起见退回配置默认)。")
131
+ stored = rep.get("stored")
132
+ if stored:
133
+ lines.append(f" 插件已写入:charsPerToken={stored.get('charsPerToken')} "
134
+ f"overhead={stored.get('systemOverheadTokens')} "
135
+ f"n={stored.get('samples')}")
136
+ if rep.get("agree") is False:
137
+ lines.append(" ⚠ 两边结果不一致——说明有一侧算错,需要查(用 --refit 以 Python 为准重写)。")
138
+ elif rep.get("agree") is True:
139
+ lines.append(" ✓ 两边一致")
140
+ else:
141
+ lines.append(" 插件还没写过拟合值(会退回配置默认 charsPerToken/overhead)。")
142
+ lines.append("")
143
+ lines.append("默认配置:charsPerToken=2、systemOverheadTokens=18000(都可在 config.json 覆盖)")
144
+ return "\n".join(lines)