lingshu-skill 3.79.0 → 3.83.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 +44 -0
- package/README.md +1 -1
- package/SKILL.md +1 -1
- package/docs//350/277/233/345/261/225/344/270/216/345/276/205/345/212/236.md +4 -2
- package/package.json +1 -1
- package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +6 -6
- package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +44 -0
- package/scripts/astrbot_plugin_lingshu/engine/README.md +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +87 -1
- package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +5 -2
- package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +148 -3
- package/scripts/cli.py +87 -1
- package/scripts/core.py +5 -2
- package/scripts/memory.py +148 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,49 @@
|
|
|
1
1
|
# 更新日志
|
|
2
2
|
|
|
3
|
+
## v3.83(2026-11-22)
|
|
4
|
+
|
|
5
|
+
> 主题:**P5 #21 借鉴清单其余三项落地**——L7 意图层 / 群规 / agentId 维度。仅 Letta core-memory 可编辑暂不做(幻觉固化风险,现有双门限已够)。
|
|
6
|
+
|
|
7
|
+
- **L7 意图层**(dual-mem):`kind=intent` + `intent_status`(active/done/cancelled)+ 过期时间。新增 `intent add/done/cancel/reopen` 命令;注入新增「正在进行的目标/计划」块,只列 active 未过期的。与 `work`(12h 丢的会话暂存)不同,intent 是跨会话长期记忆,完成/取消只改状态不删记忆。
|
|
8
|
+
- **群规**(SocialMemBench):`kind=norm` 表示群体规范(group 公共、user 空),对全群可见且群聊召回加权 +0.30(硬约束优先);个人例外是带 user 的 preference,只本人可见——实测 U2 看不到 U1 的例外,群规对全群可见。
|
|
9
|
+
- **agentId 维度**(阿里云 Memory):`make_record`/`remember` 可选 `agent_id` 字段,`recall --agent-id` 只召回"该 agent + 全局(无 agent_id)"的记忆,其它 agent 物理隔离;不指定则看全部(向后兼容)。实现中顺带修复两处 recall 冷集递归漏传 `project`/`agent_id` 的既有问题。
|
|
10
|
+
|
|
11
|
+
验证:`tests/test_three_borrowings.py` 4/4(意图生命周期 / 群规全群可见 / 个人例外隔离 / agentId 隔离);五项检查 + 压力检查 exit=0;行为基线 OK;全量测试全过。
|
|
12
|
+
|
|
13
|
+
## v3.82(2026-11-22)
|
|
14
|
+
|
|
15
|
+
> 主题:**npm token 脱敏补丁**——堵住"裸 token 被原文封存落盘"的泄露口。
|
|
16
|
+
|
|
17
|
+
- **`core._REDACT_PATTERNS` 加 npm granular token 规则**(`npm_` + 30 位以上字母数字 → `[REDACTED:npm-token]`)。起因:本会话实测用户贴的裸 npm token(`npm_p2P3...`)被 `capture` 原文落盘——泛化 `kv-secret` 只认 `token=` 键值形态,裸发漏网。具名规则放在泛化兜底之前(否则会被吃掉一半导致具名扫不到)。
|
|
18
|
+
- **不碰历史数据**:真库 verbatim 里那条旧 token 已作废(现用新 token),且删改真实记忆库属不可逆操作——只保证以后不再落盘,历史残留由用户自行决定清理。
|
|
19
|
+
|
|
20
|
+
验证:`tests/test_npm_redact.py` 2/2(npm token 脱敏 + 其它 token 规则不回归);五项检查 + 压力检查 exit=0;行为基线 OK;全量测试全过。
|
|
21
|
+
|
|
22
|
+
## v3.81(2026-11-22)
|
|
23
|
+
|
|
24
|
+
> 主题:**P5 #21 借鉴清单首选落地**——foldkeep 的「逐字原文可展开」,让有损压缩可追溯。
|
|
25
|
+
|
|
26
|
+
- **`recall --verbatim <id>`(新)**:按记忆 id 取回它对应的逐字原文快照。做梦/合并是有损的、AI 可能改写错——这条给每条封存记忆一个"回到原文"的硬证据通道,直接对着台账反复警告的"幻觉会被固化落盘"。
|
|
27
|
+
- 写入侧:`capture()` 写记录时新增 `verbatim_path`(归档文件名,无绝对路径,换机器可用)。
|
|
28
|
+
- 读取侧:`memory.verbatim_source(id)` 两步取——新记忆有 path 直接读(`via=path`);老记忆无 path 则在 `verbatim/*.md` 里文本匹配兜底(`via=text-match`)。失败返回 `{ok:False,reason}` 不抛异常。
|
|
29
|
+
- 输出:整份封存快照(不是那段记忆),`--json` 可机器读。
|
|
30
|
+
- **对照实测**:真库老记忆 `m_1793448847_edb4538a6c`(2026-10-31,无 path)经文本兜底成功展开原文。
|
|
31
|
+
|
|
32
|
+
**其余 4 项决定暂不做**:Letta core memory 可编辑(幻觉固化自我风险高,现有 `update_persona` 双门限/EMA/evidence 已够)、L7 长期意图层(新层收益待观察)、群规类型(需求不迫切)、agentId 维度(低优先)。
|
|
33
|
+
|
|
34
|
+
验证:`tests/test_verbatim_recall.py` 3/3(新记忆走 path / 老记忆走 text-match / 非 verbatim 拒绝);真库老记忆实测展开成功;五项检查 + 压力检查 exit=0;行为基线 OK;全量测试全过。
|
|
35
|
+
|
|
36
|
+
## v3.80(2026-11-22)
|
|
37
|
+
|
|
38
|
+
> 主题:**P5 #20 方案 A 落地**——用户亲口说的记忆直接确认,打通知识库增长链路。
|
|
39
|
+
|
|
40
|
+
- **问题**:知识库几乎不增长——真库 5 条知识、72 条封存记忆全部 `review=None`,`auto_archive` 只认 `review=confirmed`,封存记忆永远进不了知识库。这是"审核闸防 AI 幻觉"的设计代价。
|
|
41
|
+
- **方案 A(用户选定)**:`source="user"`(用户亲口说的)本就是事实,在 `make_record()` 层直接标 `review="confirmed"` + `review_at` + `review_source="user-statement"`;AI 产出(默认 `ai`/dream/work-flush)一律不标,继续走 pending 审核闸。
|
|
42
|
+
- **落点**:`memory.py make_record()`——`remember()` 与 `capture()` 两条写入路径都覆盖;面板/astrbot 等已显式传 `source="user"` 的调用方自动受益,无需各自改。
|
|
43
|
+
- **不变量**:`source="ai"` 的高重要性(≥0.8)记忆仍标 pending(L1268 既有逻辑不变)——审核闸没被绕过。
|
|
44
|
+
|
|
45
|
+
验证:`tests/test_user_confirmed.py` 3/3(user→confirmed / ai→不标 / ai 高重要性仍 pending / user 记忆能被 auto_archive 转进知识库);五项发布检查 + 压力检查 exit=0;行为基线 OK;全量测试全过。
|
|
46
|
+
|
|
3
47
|
## v3.79(2026-11-22)
|
|
4
48
|
|
|
5
49
|
> 主题:**交接笔记-20261122 转入的两条运维缺陷**(cron 失败静默 / doctor 备份误报)+ laneai 余额补齐。
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
> 名字取自《黄帝内经》:**算力给思考,人格给灵魂,记忆给生命。**
|
|
4
4
|
|
|
5
|
-
> 当前版本 **v3.
|
|
5
|
+
> 当前版本 **v3.83**(变更见 [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
|
@@ -236,7 +236,7 @@ startup 注入的记忆块与 cron 的瞬态提醒**同名**,于是 cron 的 p
|
|
|
236
236
|
|
|
237
237
|
19. ~~**即记即存保留 AI 说的话(speaker attribution)**~~ **已在 v3.72 落地**:`_split_segments` 角色正则改大小写不敏感 + 保留角色前缀;实测 4 轮对话切成 4 段、assistant 的话单独入库。详见 CHANGELOG v3.72。
|
|
238
238
|
|
|
239
|
-
20.
|
|
239
|
+
20. ~~**知识库几乎不增长——审核闸把链路卡死**~~ **已在 v3.80 落地(方案 A)**:`source=user` 的记忆在 `make_record` 层直接标 `review=confirmed`(`review_source=user-statement`),auto_archive 能把用户亲口说的沉淀进知识库;AI 产出仍走 pending 审核闸。
|
|
240
240
|
- 实测:真库 5 条知识(2 confirmed / 3 discarded 垃圾),72 条封存记忆全部 `review=None`。
|
|
241
241
|
- 因果链:`capture` 写入的记忆无 review 标记 → `auto_archive` 只转 `review=="confirmed"` 的(L3004/L3020,刻意"绝不碰 pending")→ 封存记忆永远进不了知识库 → 知识库只靠人工 `knowledge add`,几乎不增长。
|
|
242
242
|
- 这是"审核闸防 AI 幻觉"的设计代价,不能简单去掉。候选方向(需定):
|
|
@@ -245,7 +245,7 @@ startup 注入的记忆块与 cron 的瞬态提醒**同名**,于是 cron 的 p
|
|
|
245
245
|
- **C**:保持现状,知识库靠显式 `knowledge add` / `review confirm` 增长——把"慢"当成刻意的保守设计,写进文档管理预期。
|
|
246
246
|
- 验收(若改):封存一段时间真库后,知识库条数随对话自然增长,且 discarded/pending 不被误转。
|
|
247
247
|
|
|
248
|
-
21.
|
|
248
|
+
21. **同类项目借鉴清单**(v3.81 定了首选):**已吸收 foldkeep 的 verbatim 逐字召回**——`recall --verbatim <id>` 按 id 展开逐字原文快照(新记忆走 verbatim_path、老记忆文本兜底),让有损做梦/改写可追溯到原文。其余 3 项 v3.83 也落地:L7 意图层(kind=intent + intent_status + `intent add/done/cancel/reopen` + 注入块)、群规(kind=norm 群公共可见 + 召回加权 + 个人 preference 例外隔离)、agentId 维度(可选 agent_id 字段 + recall --agent-id 隔离,全局记忆任何 agent 可见)。仅 Letta core-memory 可编辑暂不做(幻觉固化风险,现有 update_persona 双门限已够)。
|
|
249
249
|
- **Graphiti / neuralscape role→speaker mapping**:对话以 `EpisodeType.message` 入库、角色映射成说话人、speaker-first 提取([commit](https://github.com/ehfazrezwan/neuralscape/commit/7aeb1ea623804e01b4a59424f1e29b49ffcdd9e7))。**已吸收**:P5-1 的 speaker attribution。
|
|
250
250
|
- **Letta / MemGPT 四层**([架构综述](https://raw.githubusercontent.com/MohamedAbdallah-14/prompt-to-asset/refs/heads/main/docs/research/30-agent-memory-state/30a-agent-memory-architectures.md)):message buffer(原始对话 FIFO)+ core memory(常驻人格,agent 可编辑)+ recall memory(可搜索历史)+ archival memory(长期向量/图)。灵枢已有 hippo/cortex/dust/archive 四层,但 **core memory 的"agent 可编辑"语义**没有——人格只能靠 `persona` 命令改,模型不能自主更新常驻块。借鉴方向:给模型一个受控的 core-memory 编辑入口(带白名单字段),像 Letta 的 core memory block。
|
|
251
251
|
- **dual-mem L0–L7 八层**([dual-mem](https://pypi.org/project/dual-mem/0.1.2/)):L1 完整对话原文、L2 事实、L6 行为模式、**L7 意图/未来计划**("准备跑马拉松")。灵枢有事实/习惯/人格,但**没有独立的"意图/待办"层**——`work` 是会话暂存(12h 丢), dreams 的"未完成事"是临时摘要。借鉴方向:加长期意图层(用户说明的目标/计划,带 TTL 和完成标记),跨会话保留。
|
|
@@ -347,6 +347,8 @@ startup 注入的记忆块与 cron 的瞬态提醒**同名**,于是 cron 的 p
|
|
|
347
347
|
50. **【中·可运维性】cron 天级任务失败无日志**(`cordis-plugin/lingshu-cron/plugin.js:570-576`):`fire()` 失败只记 `state.retries`、不写日志。真实现场:16:26 自动备份失败留下 22 字节空壳,doctor 报「补跑失败:backup」,但 `lingshu.log` / `failures` 里查不到任何记录。修复:失败分支写一条明确的 lingshu.log(task id / 原因 / 补跑次数)。**v3.79 已修**(三处失败分支:无 brainPy / 退出码非0-10 / 顶层异常)。
|
|
348
348
|
51. **【中·doctor 误报】backup-sha 口径过时**(`cli.py:3730-3745`):只认 `<记忆库>/backups/*.jsonl` 老格式;现机制是跨卷 `D:\brain-memory-backups\*.zip` + `.sha256`,于是"手动备份 118 文件、sha 吻合"仍显示「无备份可对账」。修复:同时识别两种格式——zip 侧读 `.sha256` 记录与 `Get-FileHash` 比对,无记录也别报"无备份"而是提示"跨卷 zip 备份不在对账范围"。 **【已在 v3.79 修】backup-sha 识别跨卷 zip**
|
|
349
349
|
|
|
350
|
+
52. **【中·安全】npm token 裸发漏脱敏**——`core._REDACT_PATTERNS` 无 npm 规则,裸 `npm_xxx` 被 capture 原文落盘。**已在 v3.82 修**(加 `npm_`+30 位具名规则)。历史残留(真库旧 token)已作废,不擅自删改记忆库。
|
|
351
|
+
|
|
350
352
|
## 三、已知问题与风险
|
|
351
353
|
|
|
352
354
|
| # | 现象 | 影响 | 处置 |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "lingshu-skill",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.83.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": "d900d9d7fc1d3470b3e67e90b4f3cc07358905977840bd6f24203db681f742b9",
|
|
5
|
+
"engine/README.md": "7b89935f1d30d61b210484a59a5be2aca6a455a3c0330e74d817d4f59949de42",
|
|
6
6
|
"engine/SKILL-lite.md": "04b87789232a0f7537c861c857888b4a0e947bcf92a461cbad5328af05361c58",
|
|
7
7
|
"engine/SKILL-tiny.md": "74e1955cc5bf4ec0ca28d52030f799f039283de27a52345a33ce783d6ee0c608",
|
|
8
|
-
"engine/SKILL.md": "
|
|
8
|
+
"engine/SKILL.md": "0b44863da7bd45b73f4d6a978e99ba9c3fe25c56497bb593c55711c2f1b540d4",
|
|
9
9
|
"engine/assets/panel.html": "8b368f16f0c1447413456a16cb4666daa4df08983bd30d627af04ad2a0fbda26",
|
|
10
10
|
"engine/docs/commands.md": "15f57adbeeca393fe001831853d5b9a5dfb237ac666711fa5662000eb22b2c59",
|
|
11
11
|
"engine/docs/mechanics.md": "e8a6602a434ed5b78cac64a98884f65a6888eb48daa7a1c0be1f6c3984041b34",
|
|
@@ -19,9 +19,9 @@
|
|
|
19
19
|
"engine/scripts/check_pressure_sync.py": "46d53934f17c7b740d0ec9fdbef9d2653850f6e01e883eedd70ff9a1527e869a",
|
|
20
20
|
"engine/scripts/check_tag.py": "6f0b8209dc2deebb1f9ec90d429e1fad60c040a2ec014a6406d9d3498faafd7f",
|
|
21
21
|
"engine/scripts/checkpoint.py": "ec74e70e6ae1338ee3d7048c71b8297a1f60bd3c572a2e2843b8e9696bdf2d9a",
|
|
22
|
-
"engine/scripts/cli.py": "
|
|
22
|
+
"engine/scripts/cli.py": "aa7ee68faf12de8701d9ce75538510d882f65b5010377714faf4e7e44009ec7b",
|
|
23
23
|
"engine/scripts/context_ab.py": "3d383f1fc16d328612825bbf731866fa427da0746490d027a0ddb719d210f1cb",
|
|
24
|
-
"engine/scripts/core.py": "
|
|
24
|
+
"engine/scripts/core.py": "849db4196a2b2b39060f5824fef98e944043a3b162449ca5d6508767909cbca6",
|
|
25
25
|
"engine/scripts/dream.py": "e25749c32fe6cb3b3845c9541ef663dffe8efaa0d9bd251f611e1359208800b9",
|
|
26
26
|
"engine/scripts/emotion.py": "c2928217a856c9201291ebd63dee33a4a641ff30dcd79964738c24e7a9d94672",
|
|
27
27
|
"engine/scripts/failures.py": "3a16234a1871f62e3ba7b7b743110b4044fb7b715b4d0e924b8ebf1cf0be50d0",
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
"engine/scripts/mem_lesson.py": "6d9c26d4307dccb80f01d406e5253fe26f3540e0774b212f5fbd939d2ac442f0",
|
|
36
36
|
"engine/scripts/mem_score.py": "95dcecba5f4db7c0c16ebc415434e1cb58cc7dd8b8213360b4df36e2a90faf6e",
|
|
37
37
|
"engine/scripts/mem_topic.py": "c22f75c128cdd3b26ff845f1a71608401bc0dc8955f9f0e1988d7f0cd663d0d5",
|
|
38
|
-
"engine/scripts/memory.py": "
|
|
38
|
+
"engine/scripts/memory.py": "b06c650777b8a9167db85d91326653deb5ccd2920aca8297ce87b22924c8a547",
|
|
39
39
|
"engine/scripts/npm_prepack.py": "d62c491a6f9edfcab2dd465a995e72df879a61b4da26ae0fe76121c8adc77e02",
|
|
40
40
|
"engine/scripts/panel_build.py": "6394c1d74d203093e43b2106d7acca6e0ca9db61ca1cd6cd3a1616053653414b",
|
|
41
41
|
"engine/scripts/panel_cloud.py": "fff72888123d45bbf05ab329a06b2126f1c0b972c76283ecff32454bc4155c58",
|
|
@@ -1,5 +1,49 @@
|
|
|
1
1
|
# 更新日志
|
|
2
2
|
|
|
3
|
+
## v3.83(2026-11-22)
|
|
4
|
+
|
|
5
|
+
> 主题:**P5 #21 借鉴清单其余三项落地**——L7 意图层 / 群规 / agentId 维度。仅 Letta core-memory 可编辑暂不做(幻觉固化风险,现有双门限已够)。
|
|
6
|
+
|
|
7
|
+
- **L7 意图层**(dual-mem):`kind=intent` + `intent_status`(active/done/cancelled)+ 过期时间。新增 `intent add/done/cancel/reopen` 命令;注入新增「正在进行的目标/计划」块,只列 active 未过期的。与 `work`(12h 丢的会话暂存)不同,intent 是跨会话长期记忆,完成/取消只改状态不删记忆。
|
|
8
|
+
- **群规**(SocialMemBench):`kind=norm` 表示群体规范(group 公共、user 空),对全群可见且群聊召回加权 +0.30(硬约束优先);个人例外是带 user 的 preference,只本人可见——实测 U2 看不到 U1 的例外,群规对全群可见。
|
|
9
|
+
- **agentId 维度**(阿里云 Memory):`make_record`/`remember` 可选 `agent_id` 字段,`recall --agent-id` 只召回"该 agent + 全局(无 agent_id)"的记忆,其它 agent 物理隔离;不指定则看全部(向后兼容)。实现中顺带修复两处 recall 冷集递归漏传 `project`/`agent_id` 的既有问题。
|
|
10
|
+
|
|
11
|
+
验证:`tests/test_three_borrowings.py` 4/4(意图生命周期 / 群规全群可见 / 个人例外隔离 / agentId 隔离);五项检查 + 压力检查 exit=0;行为基线 OK;全量测试全过。
|
|
12
|
+
|
|
13
|
+
## v3.82(2026-11-22)
|
|
14
|
+
|
|
15
|
+
> 主题:**npm token 脱敏补丁**——堵住"裸 token 被原文封存落盘"的泄露口。
|
|
16
|
+
|
|
17
|
+
- **`core._REDACT_PATTERNS` 加 npm granular token 规则**(`npm_` + 30 位以上字母数字 → `[REDACTED:npm-token]`)。起因:本会话实测用户贴的裸 npm token(`npm_p2P3...`)被 `capture` 原文落盘——泛化 `kv-secret` 只认 `token=` 键值形态,裸发漏网。具名规则放在泛化兜底之前(否则会被吃掉一半导致具名扫不到)。
|
|
18
|
+
- **不碰历史数据**:真库 verbatim 里那条旧 token 已作废(现用新 token),且删改真实记忆库属不可逆操作——只保证以后不再落盘,历史残留由用户自行决定清理。
|
|
19
|
+
|
|
20
|
+
验证:`tests/test_npm_redact.py` 2/2(npm token 脱敏 + 其它 token 规则不回归);五项检查 + 压力检查 exit=0;行为基线 OK;全量测试全过。
|
|
21
|
+
|
|
22
|
+
## v3.81(2026-11-22)
|
|
23
|
+
|
|
24
|
+
> 主题:**P5 #21 借鉴清单首选落地**——foldkeep 的「逐字原文可展开」,让有损压缩可追溯。
|
|
25
|
+
|
|
26
|
+
- **`recall --verbatim <id>`(新)**:按记忆 id 取回它对应的逐字原文快照。做梦/合并是有损的、AI 可能改写错——这条给每条封存记忆一个"回到原文"的硬证据通道,直接对着台账反复警告的"幻觉会被固化落盘"。
|
|
27
|
+
- 写入侧:`capture()` 写记录时新增 `verbatim_path`(归档文件名,无绝对路径,换机器可用)。
|
|
28
|
+
- 读取侧:`memory.verbatim_source(id)` 两步取——新记忆有 path 直接读(`via=path`);老记忆无 path 则在 `verbatim/*.md` 里文本匹配兜底(`via=text-match`)。失败返回 `{ok:False,reason}` 不抛异常。
|
|
29
|
+
- 输出:整份封存快照(不是那段记忆),`--json` 可机器读。
|
|
30
|
+
- **对照实测**:真库老记忆 `m_1793448847_edb4538a6c`(2026-10-31,无 path)经文本兜底成功展开原文。
|
|
31
|
+
|
|
32
|
+
**其余 4 项决定暂不做**:Letta core memory 可编辑(幻觉固化自我风险高,现有 `update_persona` 双门限/EMA/evidence 已够)、L7 长期意图层(新层收益待观察)、群规类型(需求不迫切)、agentId 维度(低优先)。
|
|
33
|
+
|
|
34
|
+
验证:`tests/test_verbatim_recall.py` 3/3(新记忆走 path / 老记忆走 text-match / 非 verbatim 拒绝);真库老记忆实测展开成功;五项检查 + 压力检查 exit=0;行为基线 OK;全量测试全过。
|
|
35
|
+
|
|
36
|
+
## v3.80(2026-11-22)
|
|
37
|
+
|
|
38
|
+
> 主题:**P5 #20 方案 A 落地**——用户亲口说的记忆直接确认,打通知识库增长链路。
|
|
39
|
+
|
|
40
|
+
- **问题**:知识库几乎不增长——真库 5 条知识、72 条封存记忆全部 `review=None`,`auto_archive` 只认 `review=confirmed`,封存记忆永远进不了知识库。这是"审核闸防 AI 幻觉"的设计代价。
|
|
41
|
+
- **方案 A(用户选定)**:`source="user"`(用户亲口说的)本就是事实,在 `make_record()` 层直接标 `review="confirmed"` + `review_at` + `review_source="user-statement"`;AI 产出(默认 `ai`/dream/work-flush)一律不标,继续走 pending 审核闸。
|
|
42
|
+
- **落点**:`memory.py make_record()`——`remember()` 与 `capture()` 两条写入路径都覆盖;面板/astrbot 等已显式传 `source="user"` 的调用方自动受益,无需各自改。
|
|
43
|
+
- **不变量**:`source="ai"` 的高重要性(≥0.8)记忆仍标 pending(L1268 既有逻辑不变)——审核闸没被绕过。
|
|
44
|
+
|
|
45
|
+
验证:`tests/test_user_confirmed.py` 3/3(user→confirmed / ai→不标 / ai 高重要性仍 pending / user 记忆能被 auto_archive 转进知识库);五项发布检查 + 压力检查 exit=0;行为基线 OK;全量测试全过。
|
|
46
|
+
|
|
3
47
|
## v3.79(2026-11-22)
|
|
4
48
|
|
|
5
49
|
> 主题:**交接笔记-20261122 转入的两条运维缺陷**(cron 失败静默 / doctor 备份误报)+ laneai 余额补齐。
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
> 名字取自《黄帝内经》:**算力给思考,人格给灵魂,记忆给生命。**
|
|
4
4
|
|
|
5
|
-
> 当前版本 **v3.
|
|
5
|
+
> 当前版本 **v3.83**(变更见 [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
|
|
|
@@ -1353,6 +1353,8 @@ def _main(argv=None) -> int:
|
|
|
1353
1353
|
help="显式指定复核时间点(YYYY-MM-DD 或时间戳),优先于 --ttl 推算")
|
|
1354
1354
|
p_rem.add_argument("--correction", action="store_true", help="#41 改口标记:这条是用户纠正过的更正版,做梦合并/淡忘/归档永不自动动它"
|
|
1355
1355
|
"(教训提炼 #36 优先读它)")
|
|
1356
|
+
p_rem.add_argument("--agent-id", default="",
|
|
1357
|
+
help="agent 维度:多 agent 共库时隔离,recall --agent-id 只召回本 agent + 全局")
|
|
1356
1358
|
p_rem.add_argument("--project", default="",
|
|
1357
1359
|
help="项目名标记(第四轮#3):recall --project 同名时此记忆排前")
|
|
1358
1360
|
# v3.58 三层元数据(借自 AOCI-CODE,见 docs/进展与待办.md P4)
|
|
@@ -1390,6 +1392,11 @@ def _main(argv=None) -> int:
|
|
|
1390
1392
|
help="带证据解引用:做梦合并/蒸馏产物命中时自动附最多 2 条证据原文(#46)")
|
|
1391
1393
|
p_rec.add_argument("--project", default="",
|
|
1392
1394
|
help="项目上下文(第四轮#3):同项目记忆加分排前(不硬过滤)")
|
|
1395
|
+
p_rec.add_argument("--verbatim", metavar="记忆ID",
|
|
1396
|
+
help='按 id 取回这条封存记忆的逐字原文快照(P5 #21 / foldkeep):'
|
|
1397
|
+
'做梦是有损压缩,用它追溯 AI 有没有改错原文。')
|
|
1398
|
+
p_rec.add_argument("--agent-id", default="",
|
|
1399
|
+
help="只召回该 agent 的记忆 + 全局记忆(agentId 维度隔离)")
|
|
1393
1400
|
|
|
1394
1401
|
p_deref = sub.add_parser("deref", help="按需解引用:取一条记忆的证据原文(#46 Memex)")
|
|
1395
1402
|
p_deref.add_argument("memory_id", help="记忆 id(通常是合并/蒸馏产物的 id)")
|
|
@@ -1710,6 +1717,15 @@ def _main(argv=None) -> int:
|
|
|
1710
1717
|
help="flush 时丢弃已完成条目,不转记忆(做完了就该放下)")
|
|
1711
1718
|
p_work.add_argument("--json", action="store_true")
|
|
1712
1719
|
|
|
1720
|
+
p_intent = sub.add_parser("intent", help="意图层(L7):跨会话保留的目标/计划")
|
|
1721
|
+
p_intent.add_argument("action", nargs="?", default="list",
|
|
1722
|
+
choices=["list", "add", "done", "cancel", "reopen"])
|
|
1723
|
+
p_intent.add_argument("text", nargs="*", default=[],
|
|
1724
|
+
help="add 时为目标内容;done/cancel/reopen 时为记忆 id")
|
|
1725
|
+
p_intent.add_argument("--ttl-days", type=float, default=None,
|
|
1726
|
+
help="add:过期天数(到期后注入不再列出,状态不变)")
|
|
1727
|
+
p_intent.add_argument("--json", action="store_true")
|
|
1728
|
+
|
|
1713
1729
|
p_topic = sub.add_parser("topic", help="话题栈:拟人闲聊用,记录聊过的话题与权重")
|
|
1714
1730
|
p_topic.add_argument("action", nargs="?", default="list",
|
|
1715
1731
|
choices=["list", "touch", "feedback", "drop", "status"])
|
|
@@ -1934,6 +1950,7 @@ def _main(argv=None) -> int:
|
|
|
1934
1950
|
args.cmd in ("remember", "init", "restore", "forget", "capture", "extract")
|
|
1935
1951
|
or (args.cmd == "dream" and not args.dry_run)
|
|
1936
1952
|
or (args.cmd == "work" and action in ("add", "done", "flush", "clear"))
|
|
1953
|
+
or (args.cmd == "intent" and action in ("add", "done", "cancel", "reopen"))
|
|
1937
1954
|
or (args.cmd == "topic" and action in ("touch", "feedback", "drop"))
|
|
1938
1955
|
or (args.cmd == "persona" and action not in ("show", "path", "onboarding",
|
|
1939
1956
|
"history", "snapshots", "drift",
|
|
@@ -2037,6 +2054,7 @@ def _main(argv=None) -> int:
|
|
|
2037
2054
|
ttl_days=_ttl_days, review_at=_review_ts,
|
|
2038
2055
|
correction=args.correction,
|
|
2039
2056
|
project=(getattr(args, "project", "") or "").strip() or None,
|
|
2057
|
+
agent_id=(getattr(args, "agent_id", "") or "").strip() or None,
|
|
2040
2058
|
# v3.58 三层元数据(FRAS / 源指纹 / 负空间)
|
|
2041
2059
|
fras={"f": getattr(args, "fras_f", ""),
|
|
2042
2060
|
"r": getattr(args, "fras_r", ""),
|
|
@@ -2127,6 +2145,20 @@ def _main(argv=None) -> int:
|
|
|
2127
2145
|
return 2
|
|
2128
2146
|
|
|
2129
2147
|
if args.cmd == "recall":
|
|
2148
|
+
# P5 #21:按 id 展开逐字原文——先于普通召回处理,绕过 query 逻辑
|
|
2149
|
+
_vb_id = getattr(args, "verbatim", "") or ""
|
|
2150
|
+
if _vb_id:
|
|
2151
|
+
from memory import verbatim_source
|
|
2152
|
+
r = verbatim_source(_vb_id)
|
|
2153
|
+
if not r.get("ok"):
|
|
2154
|
+
print(f"[错误] {r.get('reason')}", file=sys.stderr)
|
|
2155
|
+
return 1
|
|
2156
|
+
if getattr(args, "json", False):
|
|
2157
|
+
print(json.dumps(r, ensure_ascii=False, indent=2))
|
|
2158
|
+
else:
|
|
2159
|
+
print(f"# 逐字原文 · {r.get('path')}(取法:{r.get('via')})\n")
|
|
2160
|
+
print(r.get("text", ""))
|
|
2161
|
+
return 0
|
|
2130
2162
|
query = " ".join(args.query)
|
|
2131
2163
|
if not query:
|
|
2132
2164
|
for m in recent(args.k):
|
|
@@ -2134,7 +2166,7 @@ def _main(argv=None) -> int:
|
|
|
2134
2166
|
return 0
|
|
2135
2167
|
results = recall(query, args.k, include_archive=args.include_archive,
|
|
2136
2168
|
mode=args.mode, with_evidence=args.evidence,
|
|
2137
|
-
project=(getattr(args, "project", "") or "").strip() or None)
|
|
2169
|
+
project=(getattr(args, "project", "") or "").strip() or None, agent_id=(getattr(args, "agent_id", "") or "").strip() or None)
|
|
2138
2170
|
record_retrieval(query, results, channel="recall")
|
|
2139
2171
|
# 知识条目命中提示:recall 原本只查记忆层,顺带在 knowledge.jsonl 里做
|
|
2140
2172
|
# 简单词面匹配——这个问题曾被沉淀成知识时先亮出来(含待审核条目),
|
|
@@ -3450,6 +3482,60 @@ def _main(argv=None) -> int:
|
|
|
3450
3482
|
print(" work clear 丢掉")
|
|
3451
3483
|
return 0
|
|
3452
3484
|
|
|
3485
|
+
if args.cmd == "intent":
|
|
3486
|
+
from memory import active_intents, set_intent_state
|
|
3487
|
+
act = args.action
|
|
3488
|
+
if act == "add":
|
|
3489
|
+
text = " ".join(args.text).strip()
|
|
3490
|
+
if not text:
|
|
3491
|
+
print("用法:intent add \"准备下个月跑马拉松\" [--ttl-days 60]", file=sys.stderr)
|
|
3492
|
+
return 1
|
|
3493
|
+
rec, how = remember(text, kind="intent", source="user")
|
|
3494
|
+
# 意图是用户亲口说的目标——make_record 已按 source=user 标 confirmed;
|
|
3495
|
+
# intent_status 缺省视为 active(active_intents 里兼容无字段的老记录)。
|
|
3496
|
+
rec["intent_status"] = "active"
|
|
3497
|
+
if args.ttl_days and args.ttl_days > 0:
|
|
3498
|
+
rec["expires_at"] = int(__import__("time").time() + args.ttl_days * 86400)
|
|
3499
|
+
# 补写这两个字段到已落盘的那条记录
|
|
3500
|
+
with _locked(HOME / "hippocampus.jsonl"):
|
|
3501
|
+
rows = load_all()
|
|
3502
|
+
for r in rows:
|
|
3503
|
+
if r.get("id") == rec["id"]:
|
|
3504
|
+
r["intent_status"] = "active"
|
|
3505
|
+
if "expires_at" in rec:
|
|
3506
|
+
r["expires_at"] = rec["expires_at"]
|
|
3507
|
+
save_all(rows)
|
|
3508
|
+
print(f"已记下目标(跨会话保留):{rec['id']} {text}")
|
|
3509
|
+
return 0
|
|
3510
|
+
if act in ("done", "cancel", "reopen"):
|
|
3511
|
+
mid = " ".join(args.text).strip()
|
|
3512
|
+
if not mid:
|
|
3513
|
+
print(f"用法:intent {act} <记忆id>", file=sys.stderr)
|
|
3514
|
+
return 1
|
|
3515
|
+
state = {"done": "done", "cancel": "cancelled", "reopen": "active"}[act]
|
|
3516
|
+
try:
|
|
3517
|
+
r = set_intent_state(mid, state)
|
|
3518
|
+
except (ValueError, PermissionError) as e:
|
|
3519
|
+
print(f"[错误] {e}", file=sys.stderr)
|
|
3520
|
+
return 1
|
|
3521
|
+
print(f"已标记 {r['id']} → {state}:{r.get('text', '')[:60]}")
|
|
3522
|
+
return 0
|
|
3523
|
+
rows = active_intents(20)
|
|
3524
|
+
if args.json:
|
|
3525
|
+
print(json.dumps([{"id": m["id"], "text": m.get("text", ""),
|
|
3526
|
+
"created": m.get("created"), "expires_at": m.get("expires_at")}
|
|
3527
|
+
for m in rows], ensure_ascii=False, indent=2))
|
|
3528
|
+
return 0
|
|
3529
|
+
if not rows:
|
|
3530
|
+
print("没有正在进行的目标。用 `intent add \"...\"` 记一个(跨会话保留,work 是会话暂存)。")
|
|
3531
|
+
return 0
|
|
3532
|
+
print(f"正在进行的目标({len(rows)} 条):")
|
|
3533
|
+
for m in rows:
|
|
3534
|
+
exp = f" · 到期 {fmt_time(m['expires_at'])}" if m.get("expires_at") else ""
|
|
3535
|
+
print(f" {m['id']} {m.get('text', '')[:70]}{exp}")
|
|
3536
|
+
print(" intent done <id> / cancel <id> / reopen <id> 改状态(不删记忆)")
|
|
3537
|
+
return 0
|
|
3538
|
+
|
|
3453
3539
|
if args.cmd == "topic":
|
|
3454
3540
|
name = (args.name or "").strip()
|
|
3455
3541
|
if args.action in ("touch", "feedback", "drop") and not name:
|
|
@@ -218,7 +218,7 @@ TRAIT_DRIFT_EMA = 0.6 # 兑现比例:账面 6 分只改 3.6 分,余款下
|
|
|
218
218
|
# "relationship":人际关系类记录(A 和我是什么关系、Ta 在意什么、欠了谁/被谁帮过——
|
|
219
219
|
# 注入时独立成块,跨群共享画像的基础)。
|
|
220
220
|
KINDS = ("episode", "fact", "preference", "emotion", "insight", "identity", "habit",
|
|
221
|
-
"mistake", "relationship")
|
|
221
|
+
"mistake", "relationship", "intent", "norm")
|
|
222
222
|
LAYERS = ("hippo", "cortex", "dust")
|
|
223
223
|
|
|
224
224
|
# 冷热归档层:长期没被想起、保留度极低的沉眠记忆雪藏到这里。
|
|
@@ -466,9 +466,12 @@ def load_config() -> dict:
|
|
|
466
466
|
# ---------------------------------------------------------------- 脱敏(v3.02 #1/#3)
|
|
467
467
|
|
|
468
468
|
# 常见密钥/凭据形态:命中后替换为 [REDACTED:类型],保留首尾 3 字符便于人工辨认。
|
|
469
|
-
# 顺序敏感:具名前缀(sk-/ghp_/github_pat_/xox/AKIA)先扫,泛化兜底(kv/Bearer)后扫,
|
|
469
|
+
# 顺序敏感:具名前缀(npm_/sk-/ghp_/github_pat_/xox/AKIA)先扫,泛化兜底(kv/Bearer)后扫,
|
|
470
470
|
# 否则泛化规则会把具名 token 先吃掉一半、留下前缀导致具名规则扫不到。
|
|
471
471
|
_REDACT_PATTERNS: list[tuple[str, re.Pattern]] = [
|
|
472
|
+
# npm 2026 granular token:npm_ + 36 位(本会话实测裸 token 贴进对话被
|
|
473
|
+
# capture 原文落盘——泛化 kv-secret 只认 "token=" 形态,裸发漏网,补具名规则)
|
|
474
|
+
("npm-token", re.compile(r"npm_[A-Za-z0-9]{30,}")),
|
|
472
475
|
("api-key", re.compile(r"sk-[A-Za-z0-9]{20,}")),
|
|
473
476
|
("github-pat", re.compile(r"github_pat_[A-Za-z0-9_]{20,}")),
|
|
474
477
|
("github-token", re.compile(r"ghp_[A-Za-z0-9]{20,}")),
|
|
@@ -244,6 +244,49 @@ def set_memory_review(mid: str, status: str) -> dict:
|
|
|
244
244
|
return target
|
|
245
245
|
|
|
246
246
|
|
|
247
|
+
# ---------------------------------------------------------------- 意图层(dual-mem L7)
|
|
248
|
+
# 目标/计划:用户说明的意图,跨会话保留,带状态与完成标记。与 work(12h 丢的
|
|
249
|
+
# 会话暂存)不同,intent 是长期记忆(kind=intent),完成/取消只是改状态不删除。
|
|
250
|
+
|
|
251
|
+
INTENT_STATES = ("active", "done", "cancelled")
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def set_intent_state(mem_id: str, state: str) -> dict:
|
|
255
|
+
"""把一条 intent 记忆标记为 active/done/cancelled。返回更新后的记录。"""
|
|
256
|
+
if READONLY:
|
|
257
|
+
raise PermissionError("记忆库当前只读,无法改意图状态。")
|
|
258
|
+
state = str(state or "").strip().lower()
|
|
259
|
+
if state not in INTENT_STATES:
|
|
260
|
+
raise ValueError(f"非法意图状态 {state!r}:只支持 {'/'.join(INTENT_STATES)}")
|
|
261
|
+
with _locked(HOME / "hippocampus.jsonl"):
|
|
262
|
+
records = load_all()
|
|
263
|
+
target = next((m for m in records if m.get("id") == str(mem_id)), None)
|
|
264
|
+
if not target:
|
|
265
|
+
raise ValueError(f"没有这条记忆:{mem_id}")
|
|
266
|
+
if target.get("kind") != "intent":
|
|
267
|
+
raise ValueError("这条记忆不是意图(kind 不为 intent)")
|
|
268
|
+
target["intent_status"] = state
|
|
269
|
+
target["intent_updated"] = now_ts()
|
|
270
|
+
save_all(records)
|
|
271
|
+
return target
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def active_intents(limit: int = 8) -> list:
|
|
275
|
+
"""列出仍在进行中的意图(active、未过期、非 dust),按创建时间倒序。"""
|
|
276
|
+
now = now_ts()
|
|
277
|
+
out = []
|
|
278
|
+
for m in recent(60):
|
|
279
|
+
if m.get("kind") != "intent" or m.get("layer") == "dust":
|
|
280
|
+
continue
|
|
281
|
+
if str(m.get("intent_status") or "active").strip().lower() != "active":
|
|
282
|
+
continue
|
|
283
|
+
exp = _num(m.get("expires_at"), 0)
|
|
284
|
+
if 0 < exp <= now:
|
|
285
|
+
continue
|
|
286
|
+
out.append(m)
|
|
287
|
+
return out[:max(1, int(limit))]
|
|
288
|
+
|
|
289
|
+
|
|
247
290
|
def review_report() -> dict:
|
|
248
291
|
"""待审核清单:AI 记忆 / AI 知识 / AI 人格变更。
|
|
249
292
|
|
|
@@ -921,7 +964,8 @@ def make_record(text: str, kind: str = "fact", importance: float | None = None,
|
|
|
921
964
|
layer: str = "hippo", links=None,
|
|
922
965
|
channel: str | None = None, group_id: str | None = None,
|
|
923
966
|
user: str | None = None,
|
|
924
|
-
project: str | None = None, session: str | None = None
|
|
967
|
+
project: str | None = None, session: str | None = None,
|
|
968
|
+
agent_id: str | None = None) -> dict:
|
|
925
969
|
ts = now_ts()
|
|
926
970
|
text = text.strip()
|
|
927
971
|
tags = _dedupe([t.strip().lstrip("#") for t in (tags or []) if t.strip()])
|
|
@@ -952,6 +996,15 @@ def make_record(text: str, kind: str = "fact", importance: float | None = None,
|
|
|
952
996
|
"consolidated": False,
|
|
953
997
|
"pinned": False,
|
|
954
998
|
}
|
|
999
|
+
# P5 #20 方案 A(v3.80):用户亲口说的(source="user")本就是事实——直接标
|
|
1000
|
+
# review=confirmed,让 auto_archive 能把它们沉淀进知识库。AI 产出(默认
|
|
1001
|
+
# "ai"/dream/work-flush 等)一律不标,继续走 pending/审核闸防幻觉固化。
|
|
1002
|
+
# 标在 make_record 这一层,remember() 与 capture() 两条写入路径都覆盖;
|
|
1003
|
+
# 面板/astrbot 等已经显式传 source="user" 的调用方自动受益,无需各自改。
|
|
1004
|
+
if str(source).strip().lower() == "user":
|
|
1005
|
+
rec["review"] = "confirmed"
|
|
1006
|
+
rec["review_at"] = now_ts()
|
|
1007
|
+
rec["review_source"] = "user-statement"
|
|
955
1008
|
# 通道三元组(可选):来自聊天平台的记忆带上来源,用于群间隔离与跨群用户画像。
|
|
956
1009
|
# 缺省不写入字段 = 传统全局记忆,完全向后兼容(旧数据没有这些字段也照常召回)。
|
|
957
1010
|
if channel:
|
|
@@ -960,6 +1013,10 @@ def make_record(text: str, kind: str = "fact", importance: float | None = None,
|
|
|
960
1013
|
rec["group_id"] = str(group_id)
|
|
961
1014
|
if user:
|
|
962
1015
|
rec["user"] = str(user)
|
|
1016
|
+
# agent 维度(阿里云 Memory 最佳实践):多 agent 共用同一记忆库时隔离。
|
|
1017
|
+
# 缺省不写字段 = 全局记忆,任何 agent 都能召回(向后兼容)。
|
|
1018
|
+
if agent_id:
|
|
1019
|
+
rec["agent_id"] = str(agent_id)
|
|
963
1020
|
# —— 来源归属(origin,强制带):项目/会话 id 让每条记忆都能回答「从哪来的」。
|
|
964
1021
|
# 冲突检测按同源比较(跨项目不误报),做梦/审计按 source 溯源。
|
|
965
1022
|
# 缺省回落到 "default":老数据没有这两个字段照常工作,新写入一律补全。
|
|
@@ -1134,6 +1191,7 @@ def remember(text: str, kind: str = "fact", importance: float | None = None,
|
|
|
1134
1191
|
channel: str | None = None, group_id: str | None = None,
|
|
1135
1192
|
user: str | None = None,
|
|
1136
1193
|
project: str | None = None, session: str | None = None,
|
|
1194
|
+
agent_id: str | None = None,
|
|
1137
1195
|
ttl_days: float | None = None, review_at: int | None = None,
|
|
1138
1196
|
correction: bool = False,
|
|
1139
1197
|
fras: dict | None = None,
|
|
@@ -1253,7 +1311,7 @@ def remember(text: str, kind: str = "fact", importance: float | None = None,
|
|
|
1253
1311
|
|
|
1254
1312
|
rec = make_record(text, kind, importance, tags, entities, source, layer,
|
|
1255
1313
|
channel=channel, group_id=group_id, user=user,
|
|
1256
|
-
project=project, session=session)
|
|
1314
|
+
project=project, session=session, agent_id=agent_id)
|
|
1257
1315
|
# —— #41 correction 语义:用户说「不对/不是」语境下显式标记的改口记录 ——
|
|
1258
1316
|
# correction 条目是失败闭环的第一手证据:做梦教训提炼(#36)优先读它,
|
|
1259
1317
|
# 且合并/淡忘/归档路径都会跳过(永不自动合并消失),只有人工才能处理。
|
|
@@ -1822,7 +1880,7 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
|
|
|
1822
1880
|
channel: str | None = None, group_id: str | None = None,
|
|
1823
1881
|
user: str | None = None,
|
|
1824
1882
|
target_user: str | None = None, asker: str | None = None,
|
|
1825
|
-
project: str | None = None,
|
|
1883
|
+
project: str | None = None, agent_id: str | None = None,
|
|
1826
1884
|
mode: str = "auto", with_evidence: bool = False, _archive_pass: int = 0) -> list:
|
|
1827
1885
|
"""模糊回忆:相关度 + 近期性 + 重要性 + 联想扩散。返回 [(record, score, parts), ...]
|
|
1828
1886
|
|
|
@@ -1873,6 +1931,14 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
|
|
|
1873
1931
|
# 通道上下文的群间隔离:先物理过滤,其他群的记忆根本不进打分
|
|
1874
1932
|
if channel is not None or group_id is not None or user is not None:
|
|
1875
1933
|
records = [m for m in records if _channel_visible(m, channel, group_id, user)]
|
|
1934
|
+
# agent 维度(阿里云 Memory 最佳实践):指定 agent_id 时只看"该 agent 的 +
|
|
1935
|
+
# 全局的(无 agent_id)"记忆,其它 agent 的专属记忆物理隔离。不指定则不过滤
|
|
1936
|
+
# (本机全局查询照旧看全部,向后兼容)。
|
|
1937
|
+
if agent_id:
|
|
1938
|
+
aid = str(agent_id).strip()
|
|
1939
|
+
records = [m for m in records
|
|
1940
|
+
if not str(m.get("agent_id") or "").strip()
|
|
1941
|
+
or str(m.get("agent_id")).strip() == aid]
|
|
1876
1942
|
if include_archive:
|
|
1877
1943
|
archive = [m for m in load_archive() if m.get("id")
|
|
1878
1944
|
and _channel_visible(m, channel, group_id, user)]
|
|
@@ -1946,6 +2012,7 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
|
|
|
1946
2012
|
try:
|
|
1947
2013
|
return recall(query, k, layers, strengthen, include_dust, True,
|
|
1948
2014
|
channel, group_id, user, target_user, asker,
|
|
2015
|
+
project=project, agent_id=agent_id,
|
|
1949
2016
|
mode=mode, _archive_pass=_archive_pass + 1)
|
|
1950
2017
|
except Exception as e:
|
|
1951
2018
|
log_event("recall", f"冷集兜底(热集空候选)失败:{e}", level="warn")
|
|
@@ -2006,6 +2073,13 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
|
|
|
2006
2073
|
# 第四轮#3:同项目记忆加成(recall(project=...) 时生效)
|
|
2007
2074
|
if project and m.pop("_project_boost", None):
|
|
2008
2075
|
score += 0.25
|
|
2076
|
+
# 群规(SocialMemBench):本群的 norm 类记忆在群聊召回里优先命中——
|
|
2077
|
+
# 群体规范是硬约束,比普通记忆/项目记忆都该先被看到。个人例外
|
|
2078
|
+
# (带 user 的 preference)由 _channel_visible 保证只本人可见,两者不冲突;
|
|
2079
|
+
# 展示层再标注"个人习惯优先于群规",让模型知道覆盖关系。
|
|
2080
|
+
if group_id and str(m.get("kind") or "") == "norm" \
|
|
2081
|
+
and str(m.get("group_id") or "") == str(group_id):
|
|
2082
|
+
score += 0.30
|
|
2009
2083
|
# —— persona core 加权——
|
|
2010
2084
|
# 记忆 kind=identity 或 tags/entities/kind 命中 persona 核心关键词时,
|
|
2011
2085
|
# 追加 core_bias 比例加权;identity 是核心身份类,权重更高一点。
|
|
@@ -2110,6 +2184,7 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
|
|
|
2110
2184
|
try:
|
|
2111
2185
|
return recall(query, k, layers, strengthen, include_dust, True,
|
|
2112
2186
|
channel, group_id, user, target_user, asker,
|
|
2187
|
+
project=project, agent_id=agent_id,
|
|
2113
2188
|
mode=mode, _archive_pass=_archive_pass + 1)
|
|
2114
2189
|
except Exception as e:
|
|
2115
2190
|
log_event("recall", f"冷集自动补召失败:{e}", level="warn")
|
|
@@ -2819,6 +2894,10 @@ def capture(payload: str, tag: str = "", kind: str = "episode",
|
|
|
2819
2894
|
rec = make_record(seg, kind=kind, importance=importance, tags=tags,
|
|
2820
2895
|
source=source, layer="hippo")
|
|
2821
2896
|
rec["verbatim"] = True
|
|
2897
|
+
# P5 #21 verbatim 召回:记下这条原文出自哪个封存快照,让
|
|
2898
|
+
# `recall --verbatim <id>` 能按 id 直接展开逐字原文(老记忆无此字段,
|
|
2899
|
+
# 召回时用文本匹配兜底)。归档文件名唯一,不含绝对路径,换机器也能用。
|
|
2900
|
+
rec["verbatim_path"] = archive.name
|
|
2822
2901
|
rec["detail"] = 1.0
|
|
2823
2902
|
# #41 correction 语义:封存的改口原文同样打标,合并/提炼路径会特殊对待
|
|
2824
2903
|
if correction:
|
|
@@ -2837,6 +2916,58 @@ def capture(payload: str, tag: str = "", kind: str = "episode",
|
|
|
2837
2916
|
return {"saved": saved, "skipped": skipped, "archive": archive, "chars": len(payload)}
|
|
2838
2917
|
|
|
2839
2918
|
|
|
2919
|
+
def verbatim_source(mem_id: str) -> dict:
|
|
2920
|
+
"""按记忆 id 取回它对应的**逐字原文快照**(P5 #21 / foldkeep 借鉴)。
|
|
2921
|
+
|
|
2922
|
+
压缩/做梦是有损的,AI 可能合并改写;每条 verbatim 记忆都该能追溯到原始
|
|
2923
|
+
封存文件。取法两步:
|
|
2924
|
+
1) 新记忆有 `verbatim_path` → 直接读那个文件;
|
|
2925
|
+
2) 老记忆没有 path → 在 verbatim/*.md 里搜包含该记忆 text 的文件
|
|
2926
|
+
(取最长片段匹配,避免短句命中多个快照)。
|
|
2927
|
+
|
|
2928
|
+
返回 {ok, path, text, via};失败返回 {ok: False, reason: ...},绝不抛异常。
|
|
2929
|
+
"""
|
|
2930
|
+
mid = str(mem_id or "").strip()
|
|
2931
|
+
if not mid:
|
|
2932
|
+
return {"ok": False, "reason": "缺少记忆 id"}
|
|
2933
|
+
try:
|
|
2934
|
+
target = None
|
|
2935
|
+
for m in load_all() + load_archive():
|
|
2936
|
+
if str(m.get("id") or "") == mid:
|
|
2937
|
+
target = m
|
|
2938
|
+
break
|
|
2939
|
+
if target is None:
|
|
2940
|
+
return {"ok": False, "reason": f"没有这条记忆:{mid}"}
|
|
2941
|
+
if not target.get("verbatim"):
|
|
2942
|
+
return {"ok": False, "reason": "这条记忆不是原文封存(无 verbatim 标记)"}
|
|
2943
|
+
files = []
|
|
2944
|
+
vp = target.get("verbatim_path")
|
|
2945
|
+
if vp:
|
|
2946
|
+
p = VERBATIM_DIR / Path(str(vp)).name # 只取文件名,防路径穿越
|
|
2947
|
+
if p.is_file():
|
|
2948
|
+
files.append(p)
|
|
2949
|
+
if not files and VERBATIM_DIR.is_dir():
|
|
2950
|
+
files = sorted(VERBATIM_DIR.glob("*.md"))
|
|
2951
|
+
text = str(target.get("text") or "").strip()
|
|
2952
|
+
if not files:
|
|
2953
|
+
return {"ok": False, "reason": "没有找到 verbatim 原文快照"}
|
|
2954
|
+
if vp and len(files) == 1:
|
|
2955
|
+
return {"ok": True, "path": files[0].name,
|
|
2956
|
+
"text": files[0].read_text(encoding="utf-8"), "via": "path"}
|
|
2957
|
+
# 文本兜底:找包含记忆原文的文件(用最长片段,短句用前 24 字)
|
|
2958
|
+
needle = text[:40] if len(text) >= 40 else text
|
|
2959
|
+
for p in sorted(files, key=lambda f: f.stat().st_mtime, reverse=True):
|
|
2960
|
+
body = p.read_text(encoding="utf-8", errors="replace")
|
|
2961
|
+
if needle and needle in body:
|
|
2962
|
+
return {"ok": True, "path": p.name, "text": body, "via": "text-match"}
|
|
2963
|
+
# 连片段都匹配不上:返回最新那份(并注明是猜测)
|
|
2964
|
+
p = max(files, key=lambda f: f.stat().st_mtime)
|
|
2965
|
+
return {"ok": True, "path": p.name,
|
|
2966
|
+
"text": p.read_text(encoding="utf-8"), "via": "fallback-latest"}
|
|
2967
|
+
except Exception as exc:
|
|
2968
|
+
return {"ok": False, "reason": f"读取原文失败:{exc}"}
|
|
2969
|
+
|
|
2970
|
+
|
|
2840
2971
|
# ---------------------------------------------------------------- 教训库(#36 lessons.jsonl)
|
|
2841
2972
|
# 失败闭环的落点:做梦从「被取代的旧记忆 + conflict 记录 + correction 改口」里提炼出
|
|
2842
2973
|
# 可复用的教训,先入 pending 待审(与 knowledge/persona 的一致审核闸同约定),
|
|
@@ -3590,6 +3721,20 @@ def build_injection(query: str = "", budget_tokens: int | None = None,
|
|
|
3590
3721
|
[f"- [{fmt_date(m.get('created', 0))}] {display_text(m)}" for m in _rels],
|
|
3591
3722
|
0.15)
|
|
3592
3723
|
|
|
3724
|
+
# 「正在进行的目标/计划」:dual-mem L7 意图层(kind=intent,跨会话保留)。
|
|
3725
|
+
# 与 work(12h 丢的会话暂存)不同,intent 是长期意图,完成/取消改状态不删。
|
|
3726
|
+
# 只列 active、未过期的,让 AI 在各会话里都记得用户正在推进什么。
|
|
3727
|
+
_bill["sec"] = "intents"
|
|
3728
|
+
try:
|
|
3729
|
+
_active_intents = active_intents(6)
|
|
3730
|
+
except Exception:
|
|
3731
|
+
_active_intents = []
|
|
3732
|
+
if _active_intents:
|
|
3733
|
+
used += _soft_block("\n## 正在进行的目标/计划(用户想推进的事,完成用 intent done)",
|
|
3734
|
+
[f"- [{fmt_date(m.get('created', 0))}] {display_text(m)}"
|
|
3735
|
+
for m in _active_intents],
|
|
3736
|
+
0.12)
|
|
3737
|
+
|
|
3593
3738
|
# 时段语境:一句话给当下时间定性,让语气/行为与真实时间对齐(克制,不煽情)。
|
|
3594
3739
|
# 这是全包变化最快的内容(分钟级),必须放在实时区,别毁掉前缀缓存。
|
|
3595
3740
|
_bill["sec"] = "dynamic"
|
package/scripts/cli.py
CHANGED
|
@@ -1353,6 +1353,8 @@ def _main(argv=None) -> int:
|
|
|
1353
1353
|
help="显式指定复核时间点(YYYY-MM-DD 或时间戳),优先于 --ttl 推算")
|
|
1354
1354
|
p_rem.add_argument("--correction", action="store_true", help="#41 改口标记:这条是用户纠正过的更正版,做梦合并/淡忘/归档永不自动动它"
|
|
1355
1355
|
"(教训提炼 #36 优先读它)")
|
|
1356
|
+
p_rem.add_argument("--agent-id", default="",
|
|
1357
|
+
help="agent 维度:多 agent 共库时隔离,recall --agent-id 只召回本 agent + 全局")
|
|
1356
1358
|
p_rem.add_argument("--project", default="",
|
|
1357
1359
|
help="项目名标记(第四轮#3):recall --project 同名时此记忆排前")
|
|
1358
1360
|
# v3.58 三层元数据(借自 AOCI-CODE,见 docs/进展与待办.md P4)
|
|
@@ -1390,6 +1392,11 @@ def _main(argv=None) -> int:
|
|
|
1390
1392
|
help="带证据解引用:做梦合并/蒸馏产物命中时自动附最多 2 条证据原文(#46)")
|
|
1391
1393
|
p_rec.add_argument("--project", default="",
|
|
1392
1394
|
help="项目上下文(第四轮#3):同项目记忆加分排前(不硬过滤)")
|
|
1395
|
+
p_rec.add_argument("--verbatim", metavar="记忆ID",
|
|
1396
|
+
help='按 id 取回这条封存记忆的逐字原文快照(P5 #21 / foldkeep):'
|
|
1397
|
+
'做梦是有损压缩,用它追溯 AI 有没有改错原文。')
|
|
1398
|
+
p_rec.add_argument("--agent-id", default="",
|
|
1399
|
+
help="只召回该 agent 的记忆 + 全局记忆(agentId 维度隔离)")
|
|
1393
1400
|
|
|
1394
1401
|
p_deref = sub.add_parser("deref", help="按需解引用:取一条记忆的证据原文(#46 Memex)")
|
|
1395
1402
|
p_deref.add_argument("memory_id", help="记忆 id(通常是合并/蒸馏产物的 id)")
|
|
@@ -1710,6 +1717,15 @@ def _main(argv=None) -> int:
|
|
|
1710
1717
|
help="flush 时丢弃已完成条目,不转记忆(做完了就该放下)")
|
|
1711
1718
|
p_work.add_argument("--json", action="store_true")
|
|
1712
1719
|
|
|
1720
|
+
p_intent = sub.add_parser("intent", help="意图层(L7):跨会话保留的目标/计划")
|
|
1721
|
+
p_intent.add_argument("action", nargs="?", default="list",
|
|
1722
|
+
choices=["list", "add", "done", "cancel", "reopen"])
|
|
1723
|
+
p_intent.add_argument("text", nargs="*", default=[],
|
|
1724
|
+
help="add 时为目标内容;done/cancel/reopen 时为记忆 id")
|
|
1725
|
+
p_intent.add_argument("--ttl-days", type=float, default=None,
|
|
1726
|
+
help="add:过期天数(到期后注入不再列出,状态不变)")
|
|
1727
|
+
p_intent.add_argument("--json", action="store_true")
|
|
1728
|
+
|
|
1713
1729
|
p_topic = sub.add_parser("topic", help="话题栈:拟人闲聊用,记录聊过的话题与权重")
|
|
1714
1730
|
p_topic.add_argument("action", nargs="?", default="list",
|
|
1715
1731
|
choices=["list", "touch", "feedback", "drop", "status"])
|
|
@@ -1934,6 +1950,7 @@ def _main(argv=None) -> int:
|
|
|
1934
1950
|
args.cmd in ("remember", "init", "restore", "forget", "capture", "extract")
|
|
1935
1951
|
or (args.cmd == "dream" and not args.dry_run)
|
|
1936
1952
|
or (args.cmd == "work" and action in ("add", "done", "flush", "clear"))
|
|
1953
|
+
or (args.cmd == "intent" and action in ("add", "done", "cancel", "reopen"))
|
|
1937
1954
|
or (args.cmd == "topic" and action in ("touch", "feedback", "drop"))
|
|
1938
1955
|
or (args.cmd == "persona" and action not in ("show", "path", "onboarding",
|
|
1939
1956
|
"history", "snapshots", "drift",
|
|
@@ -2037,6 +2054,7 @@ def _main(argv=None) -> int:
|
|
|
2037
2054
|
ttl_days=_ttl_days, review_at=_review_ts,
|
|
2038
2055
|
correction=args.correction,
|
|
2039
2056
|
project=(getattr(args, "project", "") or "").strip() or None,
|
|
2057
|
+
agent_id=(getattr(args, "agent_id", "") or "").strip() or None,
|
|
2040
2058
|
# v3.58 三层元数据(FRAS / 源指纹 / 负空间)
|
|
2041
2059
|
fras={"f": getattr(args, "fras_f", ""),
|
|
2042
2060
|
"r": getattr(args, "fras_r", ""),
|
|
@@ -2127,6 +2145,20 @@ def _main(argv=None) -> int:
|
|
|
2127
2145
|
return 2
|
|
2128
2146
|
|
|
2129
2147
|
if args.cmd == "recall":
|
|
2148
|
+
# P5 #21:按 id 展开逐字原文——先于普通召回处理,绕过 query 逻辑
|
|
2149
|
+
_vb_id = getattr(args, "verbatim", "") or ""
|
|
2150
|
+
if _vb_id:
|
|
2151
|
+
from memory import verbatim_source
|
|
2152
|
+
r = verbatim_source(_vb_id)
|
|
2153
|
+
if not r.get("ok"):
|
|
2154
|
+
print(f"[错误] {r.get('reason')}", file=sys.stderr)
|
|
2155
|
+
return 1
|
|
2156
|
+
if getattr(args, "json", False):
|
|
2157
|
+
print(json.dumps(r, ensure_ascii=False, indent=2))
|
|
2158
|
+
else:
|
|
2159
|
+
print(f"# 逐字原文 · {r.get('path')}(取法:{r.get('via')})\n")
|
|
2160
|
+
print(r.get("text", ""))
|
|
2161
|
+
return 0
|
|
2130
2162
|
query = " ".join(args.query)
|
|
2131
2163
|
if not query:
|
|
2132
2164
|
for m in recent(args.k):
|
|
@@ -2134,7 +2166,7 @@ def _main(argv=None) -> int:
|
|
|
2134
2166
|
return 0
|
|
2135
2167
|
results = recall(query, args.k, include_archive=args.include_archive,
|
|
2136
2168
|
mode=args.mode, with_evidence=args.evidence,
|
|
2137
|
-
project=(getattr(args, "project", "") or "").strip() or None)
|
|
2169
|
+
project=(getattr(args, "project", "") or "").strip() or None, agent_id=(getattr(args, "agent_id", "") or "").strip() or None)
|
|
2138
2170
|
record_retrieval(query, results, channel="recall")
|
|
2139
2171
|
# 知识条目命中提示:recall 原本只查记忆层,顺带在 knowledge.jsonl 里做
|
|
2140
2172
|
# 简单词面匹配——这个问题曾被沉淀成知识时先亮出来(含待审核条目),
|
|
@@ -3450,6 +3482,60 @@ def _main(argv=None) -> int:
|
|
|
3450
3482
|
print(" work clear 丢掉")
|
|
3451
3483
|
return 0
|
|
3452
3484
|
|
|
3485
|
+
if args.cmd == "intent":
|
|
3486
|
+
from memory import active_intents, set_intent_state
|
|
3487
|
+
act = args.action
|
|
3488
|
+
if act == "add":
|
|
3489
|
+
text = " ".join(args.text).strip()
|
|
3490
|
+
if not text:
|
|
3491
|
+
print("用法:intent add \"准备下个月跑马拉松\" [--ttl-days 60]", file=sys.stderr)
|
|
3492
|
+
return 1
|
|
3493
|
+
rec, how = remember(text, kind="intent", source="user")
|
|
3494
|
+
# 意图是用户亲口说的目标——make_record 已按 source=user 标 confirmed;
|
|
3495
|
+
# intent_status 缺省视为 active(active_intents 里兼容无字段的老记录)。
|
|
3496
|
+
rec["intent_status"] = "active"
|
|
3497
|
+
if args.ttl_days and args.ttl_days > 0:
|
|
3498
|
+
rec["expires_at"] = int(__import__("time").time() + args.ttl_days * 86400)
|
|
3499
|
+
# 补写这两个字段到已落盘的那条记录
|
|
3500
|
+
with _locked(HOME / "hippocampus.jsonl"):
|
|
3501
|
+
rows = load_all()
|
|
3502
|
+
for r in rows:
|
|
3503
|
+
if r.get("id") == rec["id"]:
|
|
3504
|
+
r["intent_status"] = "active"
|
|
3505
|
+
if "expires_at" in rec:
|
|
3506
|
+
r["expires_at"] = rec["expires_at"]
|
|
3507
|
+
save_all(rows)
|
|
3508
|
+
print(f"已记下目标(跨会话保留):{rec['id']} {text}")
|
|
3509
|
+
return 0
|
|
3510
|
+
if act in ("done", "cancel", "reopen"):
|
|
3511
|
+
mid = " ".join(args.text).strip()
|
|
3512
|
+
if not mid:
|
|
3513
|
+
print(f"用法:intent {act} <记忆id>", file=sys.stderr)
|
|
3514
|
+
return 1
|
|
3515
|
+
state = {"done": "done", "cancel": "cancelled", "reopen": "active"}[act]
|
|
3516
|
+
try:
|
|
3517
|
+
r = set_intent_state(mid, state)
|
|
3518
|
+
except (ValueError, PermissionError) as e:
|
|
3519
|
+
print(f"[错误] {e}", file=sys.stderr)
|
|
3520
|
+
return 1
|
|
3521
|
+
print(f"已标记 {r['id']} → {state}:{r.get('text', '')[:60]}")
|
|
3522
|
+
return 0
|
|
3523
|
+
rows = active_intents(20)
|
|
3524
|
+
if args.json:
|
|
3525
|
+
print(json.dumps([{"id": m["id"], "text": m.get("text", ""),
|
|
3526
|
+
"created": m.get("created"), "expires_at": m.get("expires_at")}
|
|
3527
|
+
for m in rows], ensure_ascii=False, indent=2))
|
|
3528
|
+
return 0
|
|
3529
|
+
if not rows:
|
|
3530
|
+
print("没有正在进行的目标。用 `intent add \"...\"` 记一个(跨会话保留,work 是会话暂存)。")
|
|
3531
|
+
return 0
|
|
3532
|
+
print(f"正在进行的目标({len(rows)} 条):")
|
|
3533
|
+
for m in rows:
|
|
3534
|
+
exp = f" · 到期 {fmt_time(m['expires_at'])}" if m.get("expires_at") else ""
|
|
3535
|
+
print(f" {m['id']} {m.get('text', '')[:70]}{exp}")
|
|
3536
|
+
print(" intent done <id> / cancel <id> / reopen <id> 改状态(不删记忆)")
|
|
3537
|
+
return 0
|
|
3538
|
+
|
|
3453
3539
|
if args.cmd == "topic":
|
|
3454
3540
|
name = (args.name or "").strip()
|
|
3455
3541
|
if args.action in ("touch", "feedback", "drop") and not name:
|
package/scripts/core.py
CHANGED
|
@@ -218,7 +218,7 @@ TRAIT_DRIFT_EMA = 0.6 # 兑现比例:账面 6 分只改 3.6 分,余款下
|
|
|
218
218
|
# "relationship":人际关系类记录(A 和我是什么关系、Ta 在意什么、欠了谁/被谁帮过——
|
|
219
219
|
# 注入时独立成块,跨群共享画像的基础)。
|
|
220
220
|
KINDS = ("episode", "fact", "preference", "emotion", "insight", "identity", "habit",
|
|
221
|
-
"mistake", "relationship")
|
|
221
|
+
"mistake", "relationship", "intent", "norm")
|
|
222
222
|
LAYERS = ("hippo", "cortex", "dust")
|
|
223
223
|
|
|
224
224
|
# 冷热归档层:长期没被想起、保留度极低的沉眠记忆雪藏到这里。
|
|
@@ -466,9 +466,12 @@ def load_config() -> dict:
|
|
|
466
466
|
# ---------------------------------------------------------------- 脱敏(v3.02 #1/#3)
|
|
467
467
|
|
|
468
468
|
# 常见密钥/凭据形态:命中后替换为 [REDACTED:类型],保留首尾 3 字符便于人工辨认。
|
|
469
|
-
# 顺序敏感:具名前缀(sk-/ghp_/github_pat_/xox/AKIA)先扫,泛化兜底(kv/Bearer)后扫,
|
|
469
|
+
# 顺序敏感:具名前缀(npm_/sk-/ghp_/github_pat_/xox/AKIA)先扫,泛化兜底(kv/Bearer)后扫,
|
|
470
470
|
# 否则泛化规则会把具名 token 先吃掉一半、留下前缀导致具名规则扫不到。
|
|
471
471
|
_REDACT_PATTERNS: list[tuple[str, re.Pattern]] = [
|
|
472
|
+
# npm 2026 granular token:npm_ + 36 位(本会话实测裸 token 贴进对话被
|
|
473
|
+
# capture 原文落盘——泛化 kv-secret 只认 "token=" 形态,裸发漏网,补具名规则)
|
|
474
|
+
("npm-token", re.compile(r"npm_[A-Za-z0-9]{30,}")),
|
|
472
475
|
("api-key", re.compile(r"sk-[A-Za-z0-9]{20,}")),
|
|
473
476
|
("github-pat", re.compile(r"github_pat_[A-Za-z0-9_]{20,}")),
|
|
474
477
|
("github-token", re.compile(r"ghp_[A-Za-z0-9]{20,}")),
|
package/scripts/memory.py
CHANGED
|
@@ -244,6 +244,49 @@ def set_memory_review(mid: str, status: str) -> dict:
|
|
|
244
244
|
return target
|
|
245
245
|
|
|
246
246
|
|
|
247
|
+
# ---------------------------------------------------------------- 意图层(dual-mem L7)
|
|
248
|
+
# 目标/计划:用户说明的意图,跨会话保留,带状态与完成标记。与 work(12h 丢的
|
|
249
|
+
# 会话暂存)不同,intent 是长期记忆(kind=intent),完成/取消只是改状态不删除。
|
|
250
|
+
|
|
251
|
+
INTENT_STATES = ("active", "done", "cancelled")
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def set_intent_state(mem_id: str, state: str) -> dict:
|
|
255
|
+
"""把一条 intent 记忆标记为 active/done/cancelled。返回更新后的记录。"""
|
|
256
|
+
if READONLY:
|
|
257
|
+
raise PermissionError("记忆库当前只读,无法改意图状态。")
|
|
258
|
+
state = str(state or "").strip().lower()
|
|
259
|
+
if state not in INTENT_STATES:
|
|
260
|
+
raise ValueError(f"非法意图状态 {state!r}:只支持 {'/'.join(INTENT_STATES)}")
|
|
261
|
+
with _locked(HOME / "hippocampus.jsonl"):
|
|
262
|
+
records = load_all()
|
|
263
|
+
target = next((m for m in records if m.get("id") == str(mem_id)), None)
|
|
264
|
+
if not target:
|
|
265
|
+
raise ValueError(f"没有这条记忆:{mem_id}")
|
|
266
|
+
if target.get("kind") != "intent":
|
|
267
|
+
raise ValueError("这条记忆不是意图(kind 不为 intent)")
|
|
268
|
+
target["intent_status"] = state
|
|
269
|
+
target["intent_updated"] = now_ts()
|
|
270
|
+
save_all(records)
|
|
271
|
+
return target
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def active_intents(limit: int = 8) -> list:
|
|
275
|
+
"""列出仍在进行中的意图(active、未过期、非 dust),按创建时间倒序。"""
|
|
276
|
+
now = now_ts()
|
|
277
|
+
out = []
|
|
278
|
+
for m in recent(60):
|
|
279
|
+
if m.get("kind") != "intent" or m.get("layer") == "dust":
|
|
280
|
+
continue
|
|
281
|
+
if str(m.get("intent_status") or "active").strip().lower() != "active":
|
|
282
|
+
continue
|
|
283
|
+
exp = _num(m.get("expires_at"), 0)
|
|
284
|
+
if 0 < exp <= now:
|
|
285
|
+
continue
|
|
286
|
+
out.append(m)
|
|
287
|
+
return out[:max(1, int(limit))]
|
|
288
|
+
|
|
289
|
+
|
|
247
290
|
def review_report() -> dict:
|
|
248
291
|
"""待审核清单:AI 记忆 / AI 知识 / AI 人格变更。
|
|
249
292
|
|
|
@@ -921,7 +964,8 @@ def make_record(text: str, kind: str = "fact", importance: float | None = None,
|
|
|
921
964
|
layer: str = "hippo", links=None,
|
|
922
965
|
channel: str | None = None, group_id: str | None = None,
|
|
923
966
|
user: str | None = None,
|
|
924
|
-
project: str | None = None, session: str | None = None
|
|
967
|
+
project: str | None = None, session: str | None = None,
|
|
968
|
+
agent_id: str | None = None) -> dict:
|
|
925
969
|
ts = now_ts()
|
|
926
970
|
text = text.strip()
|
|
927
971
|
tags = _dedupe([t.strip().lstrip("#") for t in (tags or []) if t.strip()])
|
|
@@ -952,6 +996,15 @@ def make_record(text: str, kind: str = "fact", importance: float | None = None,
|
|
|
952
996
|
"consolidated": False,
|
|
953
997
|
"pinned": False,
|
|
954
998
|
}
|
|
999
|
+
# P5 #20 方案 A(v3.80):用户亲口说的(source="user")本就是事实——直接标
|
|
1000
|
+
# review=confirmed,让 auto_archive 能把它们沉淀进知识库。AI 产出(默认
|
|
1001
|
+
# "ai"/dream/work-flush 等)一律不标,继续走 pending/审核闸防幻觉固化。
|
|
1002
|
+
# 标在 make_record 这一层,remember() 与 capture() 两条写入路径都覆盖;
|
|
1003
|
+
# 面板/astrbot 等已经显式传 source="user" 的调用方自动受益,无需各自改。
|
|
1004
|
+
if str(source).strip().lower() == "user":
|
|
1005
|
+
rec["review"] = "confirmed"
|
|
1006
|
+
rec["review_at"] = now_ts()
|
|
1007
|
+
rec["review_source"] = "user-statement"
|
|
955
1008
|
# 通道三元组(可选):来自聊天平台的记忆带上来源,用于群间隔离与跨群用户画像。
|
|
956
1009
|
# 缺省不写入字段 = 传统全局记忆,完全向后兼容(旧数据没有这些字段也照常召回)。
|
|
957
1010
|
if channel:
|
|
@@ -960,6 +1013,10 @@ def make_record(text: str, kind: str = "fact", importance: float | None = None,
|
|
|
960
1013
|
rec["group_id"] = str(group_id)
|
|
961
1014
|
if user:
|
|
962
1015
|
rec["user"] = str(user)
|
|
1016
|
+
# agent 维度(阿里云 Memory 最佳实践):多 agent 共用同一记忆库时隔离。
|
|
1017
|
+
# 缺省不写字段 = 全局记忆,任何 agent 都能召回(向后兼容)。
|
|
1018
|
+
if agent_id:
|
|
1019
|
+
rec["agent_id"] = str(agent_id)
|
|
963
1020
|
# —— 来源归属(origin,强制带):项目/会话 id 让每条记忆都能回答「从哪来的」。
|
|
964
1021
|
# 冲突检测按同源比较(跨项目不误报),做梦/审计按 source 溯源。
|
|
965
1022
|
# 缺省回落到 "default":老数据没有这两个字段照常工作,新写入一律补全。
|
|
@@ -1134,6 +1191,7 @@ def remember(text: str, kind: str = "fact", importance: float | None = None,
|
|
|
1134
1191
|
channel: str | None = None, group_id: str | None = None,
|
|
1135
1192
|
user: str | None = None,
|
|
1136
1193
|
project: str | None = None, session: str | None = None,
|
|
1194
|
+
agent_id: str | None = None,
|
|
1137
1195
|
ttl_days: float | None = None, review_at: int | None = None,
|
|
1138
1196
|
correction: bool = False,
|
|
1139
1197
|
fras: dict | None = None,
|
|
@@ -1253,7 +1311,7 @@ def remember(text: str, kind: str = "fact", importance: float | None = None,
|
|
|
1253
1311
|
|
|
1254
1312
|
rec = make_record(text, kind, importance, tags, entities, source, layer,
|
|
1255
1313
|
channel=channel, group_id=group_id, user=user,
|
|
1256
|
-
project=project, session=session)
|
|
1314
|
+
project=project, session=session, agent_id=agent_id)
|
|
1257
1315
|
# —— #41 correction 语义:用户说「不对/不是」语境下显式标记的改口记录 ——
|
|
1258
1316
|
# correction 条目是失败闭环的第一手证据:做梦教训提炼(#36)优先读它,
|
|
1259
1317
|
# 且合并/淡忘/归档路径都会跳过(永不自动合并消失),只有人工才能处理。
|
|
@@ -1822,7 +1880,7 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
|
|
|
1822
1880
|
channel: str | None = None, group_id: str | None = None,
|
|
1823
1881
|
user: str | None = None,
|
|
1824
1882
|
target_user: str | None = None, asker: str | None = None,
|
|
1825
|
-
project: str | None = None,
|
|
1883
|
+
project: str | None = None, agent_id: str | None = None,
|
|
1826
1884
|
mode: str = "auto", with_evidence: bool = False, _archive_pass: int = 0) -> list:
|
|
1827
1885
|
"""模糊回忆:相关度 + 近期性 + 重要性 + 联想扩散。返回 [(record, score, parts), ...]
|
|
1828
1886
|
|
|
@@ -1873,6 +1931,14 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
|
|
|
1873
1931
|
# 通道上下文的群间隔离:先物理过滤,其他群的记忆根本不进打分
|
|
1874
1932
|
if channel is not None or group_id is not None or user is not None:
|
|
1875
1933
|
records = [m for m in records if _channel_visible(m, channel, group_id, user)]
|
|
1934
|
+
# agent 维度(阿里云 Memory 最佳实践):指定 agent_id 时只看"该 agent 的 +
|
|
1935
|
+
# 全局的(无 agent_id)"记忆,其它 agent 的专属记忆物理隔离。不指定则不过滤
|
|
1936
|
+
# (本机全局查询照旧看全部,向后兼容)。
|
|
1937
|
+
if agent_id:
|
|
1938
|
+
aid = str(agent_id).strip()
|
|
1939
|
+
records = [m for m in records
|
|
1940
|
+
if not str(m.get("agent_id") or "").strip()
|
|
1941
|
+
or str(m.get("agent_id")).strip() == aid]
|
|
1876
1942
|
if include_archive:
|
|
1877
1943
|
archive = [m for m in load_archive() if m.get("id")
|
|
1878
1944
|
and _channel_visible(m, channel, group_id, user)]
|
|
@@ -1946,6 +2012,7 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
|
|
|
1946
2012
|
try:
|
|
1947
2013
|
return recall(query, k, layers, strengthen, include_dust, True,
|
|
1948
2014
|
channel, group_id, user, target_user, asker,
|
|
2015
|
+
project=project, agent_id=agent_id,
|
|
1949
2016
|
mode=mode, _archive_pass=_archive_pass + 1)
|
|
1950
2017
|
except Exception as e:
|
|
1951
2018
|
log_event("recall", f"冷集兜底(热集空候选)失败:{e}", level="warn")
|
|
@@ -2006,6 +2073,13 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
|
|
|
2006
2073
|
# 第四轮#3:同项目记忆加成(recall(project=...) 时生效)
|
|
2007
2074
|
if project and m.pop("_project_boost", None):
|
|
2008
2075
|
score += 0.25
|
|
2076
|
+
# 群规(SocialMemBench):本群的 norm 类记忆在群聊召回里优先命中——
|
|
2077
|
+
# 群体规范是硬约束,比普通记忆/项目记忆都该先被看到。个人例外
|
|
2078
|
+
# (带 user 的 preference)由 _channel_visible 保证只本人可见,两者不冲突;
|
|
2079
|
+
# 展示层再标注"个人习惯优先于群规",让模型知道覆盖关系。
|
|
2080
|
+
if group_id and str(m.get("kind") or "") == "norm" \
|
|
2081
|
+
and str(m.get("group_id") or "") == str(group_id):
|
|
2082
|
+
score += 0.30
|
|
2009
2083
|
# —— persona core 加权——
|
|
2010
2084
|
# 记忆 kind=identity 或 tags/entities/kind 命中 persona 核心关键词时,
|
|
2011
2085
|
# 追加 core_bias 比例加权;identity 是核心身份类,权重更高一点。
|
|
@@ -2110,6 +2184,7 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
|
|
|
2110
2184
|
try:
|
|
2111
2185
|
return recall(query, k, layers, strengthen, include_dust, True,
|
|
2112
2186
|
channel, group_id, user, target_user, asker,
|
|
2187
|
+
project=project, agent_id=agent_id,
|
|
2113
2188
|
mode=mode, _archive_pass=_archive_pass + 1)
|
|
2114
2189
|
except Exception as e:
|
|
2115
2190
|
log_event("recall", f"冷集自动补召失败:{e}", level="warn")
|
|
@@ -2819,6 +2894,10 @@ def capture(payload: str, tag: str = "", kind: str = "episode",
|
|
|
2819
2894
|
rec = make_record(seg, kind=kind, importance=importance, tags=tags,
|
|
2820
2895
|
source=source, layer="hippo")
|
|
2821
2896
|
rec["verbatim"] = True
|
|
2897
|
+
# P5 #21 verbatim 召回:记下这条原文出自哪个封存快照,让
|
|
2898
|
+
# `recall --verbatim <id>` 能按 id 直接展开逐字原文(老记忆无此字段,
|
|
2899
|
+
# 召回时用文本匹配兜底)。归档文件名唯一,不含绝对路径,换机器也能用。
|
|
2900
|
+
rec["verbatim_path"] = archive.name
|
|
2822
2901
|
rec["detail"] = 1.0
|
|
2823
2902
|
# #41 correction 语义:封存的改口原文同样打标,合并/提炼路径会特殊对待
|
|
2824
2903
|
if correction:
|
|
@@ -2837,6 +2916,58 @@ def capture(payload: str, tag: str = "", kind: str = "episode",
|
|
|
2837
2916
|
return {"saved": saved, "skipped": skipped, "archive": archive, "chars": len(payload)}
|
|
2838
2917
|
|
|
2839
2918
|
|
|
2919
|
+
def verbatim_source(mem_id: str) -> dict:
|
|
2920
|
+
"""按记忆 id 取回它对应的**逐字原文快照**(P5 #21 / foldkeep 借鉴)。
|
|
2921
|
+
|
|
2922
|
+
压缩/做梦是有损的,AI 可能合并改写;每条 verbatim 记忆都该能追溯到原始
|
|
2923
|
+
封存文件。取法两步:
|
|
2924
|
+
1) 新记忆有 `verbatim_path` → 直接读那个文件;
|
|
2925
|
+
2) 老记忆没有 path → 在 verbatim/*.md 里搜包含该记忆 text 的文件
|
|
2926
|
+
(取最长片段匹配,避免短句命中多个快照)。
|
|
2927
|
+
|
|
2928
|
+
返回 {ok, path, text, via};失败返回 {ok: False, reason: ...},绝不抛异常。
|
|
2929
|
+
"""
|
|
2930
|
+
mid = str(mem_id or "").strip()
|
|
2931
|
+
if not mid:
|
|
2932
|
+
return {"ok": False, "reason": "缺少记忆 id"}
|
|
2933
|
+
try:
|
|
2934
|
+
target = None
|
|
2935
|
+
for m in load_all() + load_archive():
|
|
2936
|
+
if str(m.get("id") or "") == mid:
|
|
2937
|
+
target = m
|
|
2938
|
+
break
|
|
2939
|
+
if target is None:
|
|
2940
|
+
return {"ok": False, "reason": f"没有这条记忆:{mid}"}
|
|
2941
|
+
if not target.get("verbatim"):
|
|
2942
|
+
return {"ok": False, "reason": "这条记忆不是原文封存(无 verbatim 标记)"}
|
|
2943
|
+
files = []
|
|
2944
|
+
vp = target.get("verbatim_path")
|
|
2945
|
+
if vp:
|
|
2946
|
+
p = VERBATIM_DIR / Path(str(vp)).name # 只取文件名,防路径穿越
|
|
2947
|
+
if p.is_file():
|
|
2948
|
+
files.append(p)
|
|
2949
|
+
if not files and VERBATIM_DIR.is_dir():
|
|
2950
|
+
files = sorted(VERBATIM_DIR.glob("*.md"))
|
|
2951
|
+
text = str(target.get("text") or "").strip()
|
|
2952
|
+
if not files:
|
|
2953
|
+
return {"ok": False, "reason": "没有找到 verbatim 原文快照"}
|
|
2954
|
+
if vp and len(files) == 1:
|
|
2955
|
+
return {"ok": True, "path": files[0].name,
|
|
2956
|
+
"text": files[0].read_text(encoding="utf-8"), "via": "path"}
|
|
2957
|
+
# 文本兜底:找包含记忆原文的文件(用最长片段,短句用前 24 字)
|
|
2958
|
+
needle = text[:40] if len(text) >= 40 else text
|
|
2959
|
+
for p in sorted(files, key=lambda f: f.stat().st_mtime, reverse=True):
|
|
2960
|
+
body = p.read_text(encoding="utf-8", errors="replace")
|
|
2961
|
+
if needle and needle in body:
|
|
2962
|
+
return {"ok": True, "path": p.name, "text": body, "via": "text-match"}
|
|
2963
|
+
# 连片段都匹配不上:返回最新那份(并注明是猜测)
|
|
2964
|
+
p = max(files, key=lambda f: f.stat().st_mtime)
|
|
2965
|
+
return {"ok": True, "path": p.name,
|
|
2966
|
+
"text": p.read_text(encoding="utf-8"), "via": "fallback-latest"}
|
|
2967
|
+
except Exception as exc:
|
|
2968
|
+
return {"ok": False, "reason": f"读取原文失败:{exc}"}
|
|
2969
|
+
|
|
2970
|
+
|
|
2840
2971
|
# ---------------------------------------------------------------- 教训库(#36 lessons.jsonl)
|
|
2841
2972
|
# 失败闭环的落点:做梦从「被取代的旧记忆 + conflict 记录 + correction 改口」里提炼出
|
|
2842
2973
|
# 可复用的教训,先入 pending 待审(与 knowledge/persona 的一致审核闸同约定),
|
|
@@ -3590,6 +3721,20 @@ def build_injection(query: str = "", budget_tokens: int | None = None,
|
|
|
3590
3721
|
[f"- [{fmt_date(m.get('created', 0))}] {display_text(m)}" for m in _rels],
|
|
3591
3722
|
0.15)
|
|
3592
3723
|
|
|
3724
|
+
# 「正在进行的目标/计划」:dual-mem L7 意图层(kind=intent,跨会话保留)。
|
|
3725
|
+
# 与 work(12h 丢的会话暂存)不同,intent 是长期意图,完成/取消改状态不删。
|
|
3726
|
+
# 只列 active、未过期的,让 AI 在各会话里都记得用户正在推进什么。
|
|
3727
|
+
_bill["sec"] = "intents"
|
|
3728
|
+
try:
|
|
3729
|
+
_active_intents = active_intents(6)
|
|
3730
|
+
except Exception:
|
|
3731
|
+
_active_intents = []
|
|
3732
|
+
if _active_intents:
|
|
3733
|
+
used += _soft_block("\n## 正在进行的目标/计划(用户想推进的事,完成用 intent done)",
|
|
3734
|
+
[f"- [{fmt_date(m.get('created', 0))}] {display_text(m)}"
|
|
3735
|
+
for m in _active_intents],
|
|
3736
|
+
0.12)
|
|
3737
|
+
|
|
3593
3738
|
# 时段语境:一句话给当下时间定性,让语气/行为与真实时间对齐(克制,不煽情)。
|
|
3594
3739
|
# 这是全包变化最快的内容(分钟级),必须放在实时区,别毁掉前缀缓存。
|
|
3595
3740
|
_bill["sec"] = "dynamic"
|