lingshu-skill 5.1.0 → 5.3.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 +31 -0
- package/README.md +1 -1
- package/SKILL.md +3 -1
- package/cordis-plugin/lingshu-cron/plugin.js +113 -10
- package/docs//345/200/237/351/211/264-/346/230/223/347/273/217/344/270/216/345/217/244/345/205/270/347/256/227/346/263/225.md +6 -3
- package/docs//350/277/233/345/261/225/344/270/216/345/276/205/345/212/236.md +16 -0
- package/package.json +1 -1
- package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +6 -5
- package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +31 -0
- package/scripts/astrbot_plugin_lingshu/engine/README.md +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +3 -1
- package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +18 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/shape_audit.py +24 -5
- package/scripts/astrbot_plugin_lingshu/engine/scripts/token_calib.py +144 -0
- package/scripts/cli.py +18 -0
- package/scripts/shape_audit.py +24 -5
- package/scripts/token_calib.py +144 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,36 @@
|
|
|
1
1
|
# 更新日志
|
|
2
2
|
|
|
3
|
+
## v5.3(2026-11-24)
|
|
4
|
+
|
|
5
|
+
> 主题:**行为准则归位**——教训写技能,版本记录写台账(用户指出我写错了地方)。
|
|
6
|
+
|
|
7
|
+
- **问题**:我把「方法论教训」写进了 `docs/进展与待办.md`(项目开发台账),而那个文件只在开发时翻,**下次会话根本不会读到**,等于把教训埋了。
|
|
8
|
+
- **修**:两条准则搬进 `SKILL.md` 末尾「注意」段(每会话注入、真正影响行为):
|
|
9
|
+
1. **别用"那天没做"证明"从没做过"**——更早的会话实例做过什么你看不到,只能查证据(备份清单/日志/审计/mtime 分布)。真实事故:一条"我当天未删备份"的错误记忆,实际是更早实例用 `keep=5` 触发修剪删的;它一度是 `recall "备份 核实"` 的第一条命中。
|
|
10
|
+
2. **分类别弄错**——行为准则/教训写 **SKILL.md**;项目版本与修复记录写 `docs/进展与待办.md`。
|
|
11
|
+
- 台账 #94 只保留项目事实(纠正了哪条记忆、怎么纠正、验证结果),教学部分改为指向 SKILL.md。
|
|
12
|
+
|
|
13
|
+
## v5.2(2026-11-24)
|
|
14
|
+
|
|
15
|
+
> 主题:**盈不足标定水位估算** + 修掉 `shape-audit` 的假阳性。
|
|
16
|
+
|
|
17
|
+
### 盈不足(双假设法)标定(#93)
|
|
18
|
+
|
|
19
|
+
- 估算模型 `tokens = chars / ratio + overhead` 有**两个**未知数。宿主给出真实 token 时,cron 插件记一组 `(chars, tokens)`,用**最小二乘同时反推 ratio 与 overhead**(不再把 overhead 写死 18000——那才是误差大头)。
|
|
20
|
+
- 记录**限流**(60 秒内且字符差 <2000 不记),热路径不加重负担;拟合写 `<记忆库>/token-calib.json`,估算 `source` 变 `chars+calib`。
|
|
21
|
+
- 合理性闸:ratio 0.5~5、overhead 0~200000、样本 ≥2 且字符跨度 ≥2000,**不过就退回配置默认**(宁用旧的不用错的)。
|
|
22
|
+
- `brain.py token-calib [--refit] [--json]`:看样本,并用**同一公式独立重算**与插件写入值**对账**——两边不一致会明确报错(补"JS 侧没法单元测试"的保险)。
|
|
23
|
+
|
|
24
|
+
### 修 `shape-audit` 假阳性(#92)
|
|
25
|
+
|
|
26
|
+
- **13 条"幻觉风险"全是假阳性**:逐条打印后确认,全部是 `最近关于「X」的一组事情(N 条)` 的**做梦聚合**(已知噪音)。
|
|
27
|
+
- 根因:聚合条目没有 `confidence` 字段,我拿 `importance`(默认 0.45)当代理 → 全被判"低置信 AI 派生"。
|
|
28
|
+
- 修:`audit()` 跳过聚合并注明跳过数;置信位不再用 importance 当代理。
|
|
29
|
+
- 修后真库:286 条(跳过 24 条聚合),幻觉风险 **0 条**。
|
|
30
|
+
- 顺带:3 条"高置信沉底"里,1 条测试消息 + 1 条正文只有 `list`(退化垃圾)留在淡忘区;1 条**信任事实**("用户怀疑我删了备份、我核实证明没删")已 `dust revive` 拉回 cortex,recall 实测第一条命中。
|
|
31
|
+
|
|
32
|
+
验证:`tests/test_p19_token_calib.py` 7/7(拟合还原已知参数 / 需≥2样本 / 需跨度 / 拒荒谬值 / 样本读回与渲染 / **JS 与 Python 常量一致** / CLI 冒烟)。
|
|
33
|
+
|
|
3
34
|
## v5.1(2026-11-24)
|
|
4
35
|
|
|
5
36
|
> 主题:**错卦落地**——`recall` 不再把"不要用 X"当成"要用 X"。
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
> 名字取自《黄帝内经》:**算力给思考,人格给灵魂,记忆给生命。**
|
|
4
4
|
|
|
5
|
-
> 当前版本 **v5.
|
|
5
|
+
> 当前版本 **v5.3**(变更见 [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.
|
|
4
|
+
version: 5.3
|
|
5
5
|
description: 类脑持久记忆、人格与成长系统——跨会话记住事情、长出自己的人格、上下文将满时做梦式整理记忆。用户提到记忆/记住/上次/人格/设定/性格/知识库/笔记/日志/成长/自我进化/工作记忆,或新会话开始需要恢复关系与上下文时使用。纯本地零依赖。
|
|
6
6
|
---
|
|
7
7
|
|
|
@@ -378,4 +378,6 @@ python scripts/bench.py [--n 1000|--quick] # 性能基准:隔离临
|
|
|
378
378
|
- 理智先过闸:深度思考是该花的算力,不是无脑钻牛角尖。
|
|
379
379
|
- 遇到问题先 `learn ask`(知识库 → 笔记 → 记忆),别一上来就联网。
|
|
380
380
|
- 情绪上头时大事交给用户:感受如实说,取舍让用户定。
|
|
381
|
+
- **别用"那天没做"证明"从没做过"**:更早的会话实例做过什么,你看不到——只能查证据(备份清单 / 日志 / 审计台账 / mtime 分布),不能凭"当天 mtime 未变"就断言"我没做过"。这类错误结论一旦写成记忆,会被当成真相反复召回(真实事故:一条"我当天未删备份"的错误记忆,实际是更早实例用 `keep=5` 触发修剪删的)。已犯过的错就如实写进记忆("更正:确实删过,原因是…"),别修饰。
|
|
382
|
+
- **分类别弄错**:行为准则/教训写进 **SKILL.md**(每会话注入、真正影响行为);项目版本与修复记录写进 `docs/进展与待办.md`(开发时翻)。教训写进台账等于埋起来。
|
|
381
383
|
- 引擎是纯标准库,Python 3.10+ 即可,无需安装任何依赖。
|
|
@@ -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
|
-
|
|
852
|
-
|
|
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
|
|
|
@@ -138,8 +138,11 @@ recall "不要用 DiskGenius 恢复分区" → ①, ③, ②
|
|
|
138
138
|
灵枢的水位估算一直用固定常数 `charsPerToken = 2`(`cordis-plugin/lingshu-cron/plugin.js`),中文语境下这是粗估。而宿主其实偶尔会给**真实 token 数**。
|
|
139
139
|
|
|
140
140
|
**盈不足(双假设法)**就是:拿两次观测 `(chars₁, realTokens₁)`、`(chars₂, realTokens₂)`,解一次线性方程反推真实系数,并据此修正后续估算。
|
|
141
|
-
|
|
142
|
-
|
|
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。
|
|
143
146
|
|
|
144
147
|
#### A4. 六十甲子 → 双周期复习调度
|
|
145
148
|
|
|
@@ -174,7 +177,7 @@ recall "不要用 DiskGenius 恢复分区" → ①, ③, ②
|
|
|
174
177
|
| 1 | ~~**A2 错卦**:`recall` 区分否定~~ **✅ 已做 v5.1** | `memory.py` 加极性识别 + `parts["polarity_conflict"]` | 高(缺陷已实测确认) | v5.1 |
|
|
175
178
|
| 1b | ~~**A1 六爻位体检**~~ **✅ 已做 v5.0**(改用领域不变量,见第六节) | `scripts/shape_audit.py` | 高 | v5.0 |
|
|
176
179
|
| 2 | **A1 六爻审计**:`memory shape-audit` 64 格热力表 | 新增只读命令 | 高(真库跑一遍就能看出问题) | v5.1 |
|
|
177
|
-
| 3 |
|
|
180
|
+
| 3 | ~~**A3 盈不足**~~ **✅ 已做 v5.2**(同时标定 ratio 与 overhead) | cron 插件 + `scripts/token_calib.py` | 中(需宿主给真值样本,会慢慢攒) | v5.2 |
|
|
178
181
|
| 4 | **A2 其余三算子**:`recall --robust` 稳定性报告 | `memory.py` + CLI | 高(可量化重合率) | v5.2 |
|
|
179
182
|
| 5 | **A4 双周期复习** | `memory.py` 复习调度 | 中 | 视情况 |
|
|
180
183
|
|
|
@@ -550,6 +550,22 @@ startup 注入的记忆块与 cron 的瞬态提醒**同名**,于是 cron 的 p
|
|
|
550
550
|
- **注入路径本来就没这个歧义**:`--avoid` 记忆注入时独立成块「已经排除的方向(别再提)」,缺口只在 `recall` 的检索输出。
|
|
551
551
|
- 回归 6/6(极性识别 / avoid 标记算 neg / 肯定查询标禁令 / 否定查询标可行做法 / 方向一致不打扰 / CLI 出现 ⚠)。
|
|
552
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
|
+
|
|
562
|
+
94. **【已纠正】一条错误记忆:「备份是我删的吗」**(用户指出:删除是**更早的会话实例**干的,不是当前实例)。
|
|
563
|
+
- **旧记录** `m_1795114775_0486c385d4` 写的是"核实:三份 zip 完好、mtime 停留 10-28/10-31 未变,**我当天未对该目录做删除**"——结论**是错的**:备份确实被删过,是更早实例在测面板备份时用 `keep=5` 触发修剪删掉的(当时没隔离备份目录;根因是修剪 glob 把 `.sha256` 也算进 keep,v3.99 已修,且现在修剪改成移入 `.pruned/` 不再删除)。
|
|
564
|
+
- **错在哪**:拿"那一天 mtime 未变"推断"从没删过"——过去实例做过什么我看不到,只能查证据。而这条错误结论当时被当成真相存了下来,还一度是 `recall "备份 核实"` 的**第一条命中**。
|
|
565
|
+
- **纠正方式**(不手改旧文本,保留历史):按系统既有机制写一条**用户亲历**的新记录 `m_1795515035_c4d407c553`(`correction=True`、importance 0.85),再把旧记录标 `superseded_by` 指向它、新记录反向 `links` 旧记录。回忆默认跳过被取代者,仍可沿链回溯旧说法。
|
|
566
|
+
- **验证**:旧记录仍在库里(历史不丢)、`superseded_by` 已设;`recall "备份 核实 删除"` 第一条变成纠正后的真相(0.67);完整性 311 条哈希链完好;`shape-audit` 幻觉风险 0 条。
|
|
567
|
+
- **行为准则已移到 SKILL.md**("注意"段:别用"那天没做"证明"从没做过";行为准则写技能、版本记录写台账)。教训本身已用 `lesson` 三写沉淀:记忆 + 知识 `k_23e3403967` + 笔记 `n_faa8432d5d`。
|
|
568
|
+
|
|
553
569
|
## 三、已知问题与风险
|
|
554
570
|
|
|
555
571
|
| # | 现象 | 影响 | 处置 |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "lingshu-skill",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.3.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": "
|
|
5
|
-
"engine/README.md": "
|
|
4
|
+
"engine/CHANGELOG.md": "620e572eca199e48258cf93225c4f464b994457fc66cd7a854fbacd2c3777956",
|
|
5
|
+
"engine/README.md": "19810eb32c701b2493e1e44c296d4180053cbe3b3da166fdca26ff0f6c0d76c5",
|
|
6
6
|
"engine/SKILL-lite.md": "04b87789232a0f7537c861c857888b4a0e947bcf92a461cbad5328af05361c58",
|
|
7
7
|
"engine/SKILL-tiny.md": "74e1955cc5bf4ec0ca28d52030f799f039283de27a52345a33ce783d6ee0c608",
|
|
8
|
-
"engine/SKILL.md": "
|
|
8
|
+
"engine/SKILL.md": "a24b9170637d7ea886edb9c61ebb12adc829fe68cb8fbbf01ecc4d1b2f627d99",
|
|
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": "
|
|
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",
|
|
@@ -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": "
|
|
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,36 @@
|
|
|
1
1
|
# 更新日志
|
|
2
2
|
|
|
3
|
+
## v5.3(2026-11-24)
|
|
4
|
+
|
|
5
|
+
> 主题:**行为准则归位**——教训写技能,版本记录写台账(用户指出我写错了地方)。
|
|
6
|
+
|
|
7
|
+
- **问题**:我把「方法论教训」写进了 `docs/进展与待办.md`(项目开发台账),而那个文件只在开发时翻,**下次会话根本不会读到**,等于把教训埋了。
|
|
8
|
+
- **修**:两条准则搬进 `SKILL.md` 末尾「注意」段(每会话注入、真正影响行为):
|
|
9
|
+
1. **别用"那天没做"证明"从没做过"**——更早的会话实例做过什么你看不到,只能查证据(备份清单/日志/审计/mtime 分布)。真实事故:一条"我当天未删备份"的错误记忆,实际是更早实例用 `keep=5` 触发修剪删的;它一度是 `recall "备份 核实"` 的第一条命中。
|
|
10
|
+
2. **分类别弄错**——行为准则/教训写 **SKILL.md**;项目版本与修复记录写 `docs/进展与待办.md`。
|
|
11
|
+
- 台账 #94 只保留项目事实(纠正了哪条记忆、怎么纠正、验证结果),教学部分改为指向 SKILL.md。
|
|
12
|
+
|
|
13
|
+
## v5.2(2026-11-24)
|
|
14
|
+
|
|
15
|
+
> 主题:**盈不足标定水位估算** + 修掉 `shape-audit` 的假阳性。
|
|
16
|
+
|
|
17
|
+
### 盈不足(双假设法)标定(#93)
|
|
18
|
+
|
|
19
|
+
- 估算模型 `tokens = chars / ratio + overhead` 有**两个**未知数。宿主给出真实 token 时,cron 插件记一组 `(chars, tokens)`,用**最小二乘同时反推 ratio 与 overhead**(不再把 overhead 写死 18000——那才是误差大头)。
|
|
20
|
+
- 记录**限流**(60 秒内且字符差 <2000 不记),热路径不加重负担;拟合写 `<记忆库>/token-calib.json`,估算 `source` 变 `chars+calib`。
|
|
21
|
+
- 合理性闸:ratio 0.5~5、overhead 0~200000、样本 ≥2 且字符跨度 ≥2000,**不过就退回配置默认**(宁用旧的不用错的)。
|
|
22
|
+
- `brain.py token-calib [--refit] [--json]`:看样本,并用**同一公式独立重算**与插件写入值**对账**——两边不一致会明确报错(补"JS 侧没法单元测试"的保险)。
|
|
23
|
+
|
|
24
|
+
### 修 `shape-audit` 假阳性(#92)
|
|
25
|
+
|
|
26
|
+
- **13 条"幻觉风险"全是假阳性**:逐条打印后确认,全部是 `最近关于「X」的一组事情(N 条)` 的**做梦聚合**(已知噪音)。
|
|
27
|
+
- 根因:聚合条目没有 `confidence` 字段,我拿 `importance`(默认 0.45)当代理 → 全被判"低置信 AI 派生"。
|
|
28
|
+
- 修:`audit()` 跳过聚合并注明跳过数;置信位不再用 importance 当代理。
|
|
29
|
+
- 修后真库:286 条(跳过 24 条聚合),幻觉风险 **0 条**。
|
|
30
|
+
- 顺带:3 条"高置信沉底"里,1 条测试消息 + 1 条正文只有 `list`(退化垃圾)留在淡忘区;1 条**信任事实**("用户怀疑我删了备份、我核实证明没删")已 `dust revive` 拉回 cortex,recall 实测第一条命中。
|
|
31
|
+
|
|
32
|
+
验证:`tests/test_p19_token_calib.py` 7/7(拟合还原已知参数 / 需≥2样本 / 需跨度 / 拒荒谬值 / 样本读回与渲染 / **JS 与 Python 常量一致** / CLI 冒烟)。
|
|
33
|
+
|
|
3
34
|
## v5.1(2026-11-24)
|
|
4
35
|
|
|
5
36
|
> 主题:**错卦落地**——`recall` 不再把"不要用 X"当成"要用 X"。
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
> 名字取自《黄帝内经》:**算力给思考,人格给灵魂,记忆给生命。**
|
|
4
4
|
|
|
5
|
-
> 当前版本 **v5.
|
|
5
|
+
> 当前版本 **v5.3**(变更见 [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.
|
|
4
|
+
version: 5.3
|
|
5
5
|
description: 类脑持久记忆、人格与成长系统——跨会话记住事情、长出自己的人格、上下文将满时做梦式整理记忆。用户提到记忆/记住/上次/人格/设定/性格/知识库/笔记/日志/成长/自我进化/工作记忆,或新会话开始需要恢复关系与上下文时使用。纯本地零依赖。
|
|
6
6
|
---
|
|
7
7
|
|
|
@@ -378,4 +378,6 @@ python scripts/bench.py [--n 1000|--quick] # 性能基准:隔离临
|
|
|
378
378
|
- 理智先过闸:深度思考是该花的算力,不是无脑钻牛角尖。
|
|
379
379
|
- 遇到问题先 `learn ask`(知识库 → 笔记 → 记忆),别一上来就联网。
|
|
380
380
|
- 情绪上头时大事交给用户:感受如实说,取舍让用户定。
|
|
381
|
+
- **别用"那天没做"证明"从没做过"**:更早的会话实例做过什么,你看不到——只能查证据(备份清单 / 日志 / 审计台账 / mtime 分布),不能凭"当天 mtime 未变"就断言"我没做过"。这类错误结论一旦写成记忆,会被当成真相反复召回(真实事故:一条"我当天未删备份"的错误记忆,实际是更早实例用 `keep=5` 触发修剪删的)。已犯过的错就如实写进记忆("更正:确实删过,原因是…"),别修饰。
|
|
382
|
+
- **分类别弄错**:行为准则/教训写进 **SKILL.md**(每会话注入、真正影响行为);项目版本与修复记录写进 `docs/进展与待办.md`(开发时翻)。教训写进台账等于埋起来。
|
|
381
383
|
- 引擎是纯标准库,Python 3.10+ 即可,无需安装任何依赖。
|
|
@@ -1581,6 +1581,13 @@ def _main(argv=None) -> int:
|
|
|
1581
1581
|
p_tr.add_argument("--json", action="store_true")
|
|
1582
1582
|
|
|
1583
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
|
+
|
|
1584
1591
|
p_sc = sub.add_parser("shortcut", help="在桌面生成/删除「灵枢面板」快捷方式(静默启动面板)")
|
|
1585
1592
|
p_sc.add_argument("--name", default="灵枢面板", help="快捷方式名字(默认 灵枢面板)")
|
|
1586
1593
|
p_sc.add_argument("--port", type=int, default=0, help="固定端口(默认读 config.panel_port)")
|
|
@@ -2605,6 +2612,17 @@ def _main(argv=None) -> int:
|
|
|
2605
2612
|
print("没有删除任何东西;要清空请你自己动手。")
|
|
2606
2613
|
return 0 if res["ok"] else 1
|
|
2607
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
|
+
|
|
2608
2626
|
if args.cmd == "shortcut":
|
|
2609
2627
|
import desktop_shortcut as _ds
|
|
2610
2628
|
if args.remove:
|
|
@@ -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
|
-
|
|
60
|
-
|
|
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
|
-
|
|
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
|
@@ -1581,6 +1581,13 @@ def _main(argv=None) -> int:
|
|
|
1581
1581
|
p_tr.add_argument("--json", action="store_true")
|
|
1582
1582
|
|
|
1583
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
|
+
|
|
1584
1591
|
p_sc = sub.add_parser("shortcut", help="在桌面生成/删除「灵枢面板」快捷方式(静默启动面板)")
|
|
1585
1592
|
p_sc.add_argument("--name", default="灵枢面板", help="快捷方式名字(默认 灵枢面板)")
|
|
1586
1593
|
p_sc.add_argument("--port", type=int, default=0, help="固定端口(默认读 config.panel_port)")
|
|
@@ -2605,6 +2612,17 @@ def _main(argv=None) -> int:
|
|
|
2605
2612
|
print("没有删除任何东西;要清空请你自己动手。")
|
|
2606
2613
|
return 0 if res["ok"] else 1
|
|
2607
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
|
+
|
|
2608
2626
|
if args.cmd == "shortcut":
|
|
2609
2627
|
import desktop_shortcut as _ds
|
|
2610
2628
|
if args.remove:
|
package/scripts/shape_audit.py
CHANGED
|
@@ -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
|
-
|
|
60
|
-
|
|
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
|
-
|
|
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)
|