lingshu-skill 3.82.0 → 3.84.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # 更新日志
2
2
 
3
+ ## v3.84(2026-11-22)
4
+
5
+ > 主题:**npm 发版自动化**——把台账第四节发布流程串成一条命令,守住"版本必须升、检查必须全绿"门禁。
6
+
7
+ - **`scripts/release.py`**(新):
8
+ - `status` —— 本地 SKILL/package 版本 / npm 线上 latest / 是否可发;
9
+ - `bump <X.Y> [标题]` —— 拒绝非 X.Y 或版本不升;自动改四处版本(SKILL/package X.Y.0/README/CHANGELOG 首节)+ 按依赖序重生成 sync_engine→checksums→manifest + 跑六项检查/行为基线/全量测试,全绿才成功;
10
+ - `publish [--wait 分钟]` —— 全套验证 + npm whoami + 版本大于线上防 E409 + npm publish + 轮询 registry 到可见(绕本机缓存,覆盖 npm staged 窗口 ~17 分钟,默认等 20 分钟)。
11
+ - **不做** git 提交/tag/push(用户决定);新文件未 git add 时 manifest 门禁照旧拦(脚本不替你决定入库范围)。
12
+ - **`docs/发布自动化.md`**(新):三条命令用法 + 典型发版流程(先 bump 再一起提交,最后 publish)。
13
+
14
+ 验证:release.py 编译通过;status 正确显示本地 3.83 / 线上 3.83.0 / 不可发;bump 正确拒绝非升版与未 git add 文件;副本上测了 bump 升版改四处 + 各检查全跑到(副本的 2 处失败是测试环境差异:未 add 新文件 / 临时目录冲突,正式仓库 56/56)。
15
+
16
+ ## v3.83(2026-11-22)
17
+
18
+ > 主题:**P5 #21 借鉴清单其余三项落地**——L7 意图层 / 群规 / agentId 维度。仅 Letta core-memory 可编辑暂不做(幻觉固化风险,现有双门限已够)。
19
+
20
+ - **L7 意图层**(dual-mem):`kind=intent` + `intent_status`(active/done/cancelled)+ 过期时间。新增 `intent add/done/cancel/reopen` 命令;注入新增「正在进行的目标/计划」块,只列 active 未过期的。与 `work`(12h 丢的会话暂存)不同,intent 是跨会话长期记忆,完成/取消只改状态不删记忆。
21
+ - **群规**(SocialMemBench):`kind=norm` 表示群体规范(group 公共、user 空),对全群可见且群聊召回加权 +0.30(硬约束优先);个人例外是带 user 的 preference,只本人可见——实测 U2 看不到 U1 的例外,群规对全群可见。
22
+ - **agentId 维度**(阿里云 Memory):`make_record`/`remember` 可选 `agent_id` 字段,`recall --agent-id` 只召回"该 agent + 全局(无 agent_id)"的记忆,其它 agent 物理隔离;不指定则看全部(向后兼容)。实现中顺带修复两处 recall 冷集递归漏传 `project`/`agent_id` 的既有问题。
23
+
24
+ 验证:`tests/test_three_borrowings.py` 4/4(意图生命周期 / 群规全群可见 / 个人例外隔离 / agentId 隔离);五项检查 + 压力检查 exit=0;行为基线 OK;全量测试全过。
25
+
3
26
  ## v3.82(2026-11-22)
4
27
 
5
28
  > 主题:**npm token 脱敏补丁**——堵住"裸 token 被原文封存落盘"的泄露口。
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  > 名字取自《黄帝内经》:**算力给思考,人格给灵魂,记忆给生命。**
4
4
 
5
- > 当前版本 **v3.82**(变更见 [CHANGELOG.md](CHANGELOG.md))
5
+ > 当前版本 **v3.84**(变更见 [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: 3.82
4
+ version: 3.84
5
5
  description: 类脑持久记忆、人格与成长系统——跨会话记住事情、长出自己的人格、上下文将满时做梦式整理记忆。用户提到记忆/记住/上次/人格/设定/性格/知识库/笔记/日志/成长/自我进化/工作记忆,或新会话开始需要恢复关系与上下文时使用。纯本地零依赖。
6
6
  ---
7
7
 
@@ -0,0 +1,54 @@
1
+ # 发版自动化(release.py)
2
+
3
+ 把台账第四节的发布流程串成命令,**守住"版本必须升、检查必须全绿"的门禁**,不再靠人肉记步骤。
4
+
5
+ ## 三条命令
6
+
7
+ ```powershell
8
+ $py = "D:\ServBay\packages\python\current\python.exe"
9
+ cd E:\丁厚同\文档\程序\灵枢-skill
10
+
11
+ # 看现状:本地版本 / 线上 latest / 是否可发
12
+ & $py scripts\release.py status
13
+
14
+ # 1)升版本(X.Y):自动改四处版本 + CHANGELOG 首节 + 重生成派生文件 + 全套验证
15
+ & $py scripts\release.py bump 3.84 "一句话主题"
16
+
17
+ # 2)发布:校验版本一致+检查全绿 → npm publish → 轮询 registry 到可见
18
+ & $py scripts\release.py publish
19
+ ```
20
+
21
+ ## 各命令细节
22
+
23
+ - **bump `<X.Y>` `[标题]`**:
24
+ - 拒绝非 X.Y 格式、拒绝新版本 ≤ 当前版本;
25
+ - 改 `SKILL.md` / `package.json`(X.Y.0) / `README.md` / `CHANGELOG.md` 首节;
26
+ - 按依赖序重生成 `sync_engine` → `make_checksums` → `make_manifest`;
27
+ - 跑六项检查 + 行为基线 + 全量测试,**全绿才成功**(任一红即退出码 1)。
28
+ - 不做 git 提交/tag/push。
29
+ - **publish `[--wait 分钟]`**:
30
+ - 先跑全套验证;`npm whoami` 确认登录;确认本地版本 > 线上 latest(防 E409 重发);
31
+ - `npm publish` 后轮询 registry(绕本机 npm 缓存)直到 `latest` == 本地版本——**npm staged 窗口最多 ~17 分钟**,脚本默认等 20 分钟。
32
+ - **status**:打印本地/线上版本与"是否可发"。
33
+
34
+ ## 两条铁律(脚本替你守)
35
+
36
+ 1. **新文件必须先 `git add`**:`manifest --check` 会拒绝未入库的发布范围内文件(如新脚本自己)。先 `git add` 新文件再 bump,脚本不替你决定哪些文件入库。
37
+ 2. **tag/push 不做**:按用户决定,脚本不含 git 提交/tag/push;发版后如需提交,仍按"一个版本一个提交"手工做(提交时排除 `tests/test_*.py` 本地测试文件)。
38
+
39
+ ## 典型发版流程(建议顺序)
40
+
41
+ ```powershell
42
+ # 1) 改完功能代码(先别提交版本文件)
43
+ # 2) 升版本 + 重生成 + 全套验证(bump 会改 SKILL/package/README/CHANGELOG/manifest)
44
+ & $py scripts\release.py bump 3.84 "主题"
45
+ # 3) 全绿后,把功能代码 + 版本文件一起提交(一个版本一个提交)
46
+ git add -A
47
+ git commit -m "feat: v3.84 主题"
48
+ # 4) 发布到 npm(等 staged 可见)
49
+ & $py scripts\release.py publish
50
+ # 5) 同步 DSH 副本 + 重启插件(脚本不做)
51
+ powershell -ExecutionPolicy Bypass -File scripts\update_dsh_copy.ps1 -Profile desktop
52
+ ```
53
+
54
+ > tag/push 按用户决定不做;提交时排除 `tests/test_*.py` 本地测试文件。
@@ -245,7 +245,7 @@ startup 注入的记忆块与 cron 的瞬态提醒**同名**,于是 cron 的 p
245
245
  - **C**:保持现状,知识库靠显式 `knowledge add` / `review confirm` 增长——把"慢"当成刻意的保守设计,写进文档管理预期。
246
246
  - 验收(若改):封存一段时间真库后,知识库条数随对话自然增长,且 discarded/pending 不被误转。
247
247
 
248
- 21. **同类项目借鉴清单**(v3.81 定了首选):**已吸收 foldkeep 的 verbatim 逐字召回**——`recall --verbatim <id>` 按 id 展开逐字原文快照(新记忆走 verbatim_path、老记忆文本兜底),让有损做梦/改写可追溯到原文。其余 4 项暂不做:Letta core-memory 可编辑(幻觉固化风险,现有 update_persona 双门限已够)、L7 意图层(新增层收益待观察)、群规(需求不迫切)、agentId 维度(低优先)。
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 和完成标记),跨会话保留。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lingshu-skill",
3
- "version": "3.82.0",
3
+ "version": "3.84.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": "28963c1cfc011680a99694afee561bd8f04b4668cdfaf52d1ebfd8e824402333",
5
- "engine/README.md": "a3a90df5a0c3bbb9ff4d4fc4df59e9ec6694d05bd649c3b49922eac66a2fd531",
4
+ "engine/CHANGELOG.md": "cef97664722696544f96be45334b7e1dfa30c924730019335e6d148f6fb4dcf5",
5
+ "engine/README.md": "6a9ddceb69a9c4ac05498ec7940ca39a8879d3c5f0f844f6e82aebf144cf2556",
6
6
  "engine/SKILL-lite.md": "04b87789232a0f7537c861c857888b4a0e947bcf92a461cbad5328af05361c58",
7
7
  "engine/SKILL-tiny.md": "74e1955cc5bf4ec0ca28d52030f799f039283de27a52345a33ce783d6ee0c608",
8
- "engine/SKILL.md": "0111f6cc710cd45d55f9fb379cf63d432cf93a2bcb0aae7ce8ea0fc6758a8363",
8
+ "engine/SKILL.md": "f9e9dc44f621d686cbefd6f791b57fdd32f08183cd9f86e43d2f8c3fc812af8c",
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": "81a7dd9cbca19b0c2ab030861a5039553d7e10423dc1dd06da0ad5f827eb4218",
22
+ "engine/scripts/cli.py": "aa7ee68faf12de8701d9ce75538510d882f65b5010377714faf4e7e44009ec7b",
23
23
  "engine/scripts/context_ab.py": "3d383f1fc16d328612825bbf731866fa427da0746490d027a0ddb719d210f1cb",
24
- "engine/scripts/core.py": "d75dd0a26118cceafdf1e89badf241e7f2bf3c7b809d3f7e7e92e30e82008a11",
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,13 +35,14 @@
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": "cb64ada8ad7221d485f320cfb53754cf0bbb6b8bf8246f1e701c34d0ea47a6d0",
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",
42
42
  "engine/scripts/panel_server.py": "51c735de0d78d8cc9d3aae5bee4ca1e66a551f200cab37f327bf9c2666abd297",
43
43
  "engine/scripts/panels.py": "87dfce47693340af7c9bc6010a593256331e32c2e8504a0ac0745cf2ef992fd6",
44
44
  "engine/scripts/persona.py": "fb748d2fb7b176d9dd0d7394de69ba4560da7f4205f62256477d3a69dcbdf0f5",
45
+ "engine/scripts/release.py": "f54ff5f5a0a12992c8173e7f5ea10cc61427a55c9d8cbe3f0d97cec7d1bc2f10",
45
46
  "engine/scripts/retriever.py": "85a35f8f660767cff1c068e722b51e3b5623c4dffe4822527eee96f9220240d3",
46
47
  "engine/scripts/safety.py": "7586d8d4a627eec67a4891b758665289a33e07a45fd27d526d45c70d1178cd53",
47
48
  "engine/scripts/session_import.py": "31c68069800e6ca8c91aad7869e7e174adc0b1e027ac0a4f7361a2c3a5363b3f",
@@ -1,5 +1,28 @@
1
1
  # 更新日志
2
2
 
3
+ ## v3.84(2026-11-22)
4
+
5
+ > 主题:**npm 发版自动化**——把台账第四节发布流程串成一条命令,守住"版本必须升、检查必须全绿"门禁。
6
+
7
+ - **`scripts/release.py`**(新):
8
+ - `status` —— 本地 SKILL/package 版本 / npm 线上 latest / 是否可发;
9
+ - `bump <X.Y> [标题]` —— 拒绝非 X.Y 或版本不升;自动改四处版本(SKILL/package X.Y.0/README/CHANGELOG 首节)+ 按依赖序重生成 sync_engine→checksums→manifest + 跑六项检查/行为基线/全量测试,全绿才成功;
10
+ - `publish [--wait 分钟]` —— 全套验证 + npm whoami + 版本大于线上防 E409 + npm publish + 轮询 registry 到可见(绕本机缓存,覆盖 npm staged 窗口 ~17 分钟,默认等 20 分钟)。
11
+ - **不做** git 提交/tag/push(用户决定);新文件未 git add 时 manifest 门禁照旧拦(脚本不替你决定入库范围)。
12
+ - **`docs/发布自动化.md`**(新):三条命令用法 + 典型发版流程(先 bump 再一起提交,最后 publish)。
13
+
14
+ 验证:release.py 编译通过;status 正确显示本地 3.83 / 线上 3.83.0 / 不可发;bump 正确拒绝非升版与未 git add 文件;副本上测了 bump 升版改四处 + 各检查全跑到(副本的 2 处失败是测试环境差异:未 add 新文件 / 临时目录冲突,正式仓库 56/56)。
15
+
16
+ ## v3.83(2026-11-22)
17
+
18
+ > 主题:**P5 #21 借鉴清单其余三项落地**——L7 意图层 / 群规 / agentId 维度。仅 Letta core-memory 可编辑暂不做(幻觉固化风险,现有双门限已够)。
19
+
20
+ - **L7 意图层**(dual-mem):`kind=intent` + `intent_status`(active/done/cancelled)+ 过期时间。新增 `intent add/done/cancel/reopen` 命令;注入新增「正在进行的目标/计划」块,只列 active 未过期的。与 `work`(12h 丢的会话暂存)不同,intent 是跨会话长期记忆,完成/取消只改状态不删记忆。
21
+ - **群规**(SocialMemBench):`kind=norm` 表示群体规范(group 公共、user 空),对全群可见且群聊召回加权 +0.30(硬约束优先);个人例外是带 user 的 preference,只本人可见——实测 U2 看不到 U1 的例外,群规对全群可见。
22
+ - **agentId 维度**(阿里云 Memory):`make_record`/`remember` 可选 `agent_id` 字段,`recall --agent-id` 只召回"该 agent + 全局(无 agent_id)"的记忆,其它 agent 物理隔离;不指定则看全部(向后兼容)。实现中顺带修复两处 recall 冷集递归漏传 `project`/`agent_id` 的既有问题。
23
+
24
+ 验证:`tests/test_three_borrowings.py` 4/4(意图生命周期 / 群规全群可见 / 个人例外隔离 / agentId 隔离);五项检查 + 压力检查 exit=0;行为基线 OK;全量测试全过。
25
+
3
26
  ## v3.82(2026-11-22)
4
27
 
5
28
  > 主题:**npm token 脱敏补丁**——堵住"裸 token 被原文封存落盘"的泄露口。
@@ -2,7 +2,7 @@
2
2
 
3
3
  > 名字取自《黄帝内经》:**算力给思考,人格给灵魂,记忆给生命。**
4
4
 
5
- > 当前版本 **v3.82**(变更见 [CHANGELOG.md](CHANGELOG.md))
5
+ > 当前版本 **v3.84**(变更见 [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: 3.82
4
+ version: 3.84
5
5
  description: 类脑持久记忆、人格与成长系统——跨会话记住事情、长出自己的人格、上下文将满时做梦式整理记忆。用户提到记忆/记住/上次/人格/设定/性格/知识库/笔记/日志/成长/自我进化/工作记忆,或新会话开始需要恢复关系与上下文时使用。纯本地零依赖。
6
6
  ---
7
7
 
@@ -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)
@@ -1393,6 +1395,8 @@ def _main(argv=None) -> int:
1393
1395
  p_rec.add_argument("--verbatim", metavar="记忆ID",
1394
1396
  help='按 id 取回这条封存记忆的逐字原文快照(P5 #21 / foldkeep):'
1395
1397
  '做梦是有损压缩,用它追溯 AI 有没有改错原文。')
1398
+ p_rec.add_argument("--agent-id", default="",
1399
+ help="只召回该 agent 的记忆 + 全局记忆(agentId 维度隔离)")
1396
1400
 
1397
1401
  p_deref = sub.add_parser("deref", help="按需解引用:取一条记忆的证据原文(#46 Memex)")
1398
1402
  p_deref.add_argument("memory_id", help="记忆 id(通常是合并/蒸馏产物的 id)")
@@ -1713,6 +1717,15 @@ def _main(argv=None) -> int:
1713
1717
  help="flush 时丢弃已完成条目,不转记忆(做完了就该放下)")
1714
1718
  p_work.add_argument("--json", action="store_true")
1715
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
+
1716
1729
  p_topic = sub.add_parser("topic", help="话题栈:拟人闲聊用,记录聊过的话题与权重")
1717
1730
  p_topic.add_argument("action", nargs="?", default="list",
1718
1731
  choices=["list", "touch", "feedback", "drop", "status"])
@@ -1937,6 +1950,7 @@ def _main(argv=None) -> int:
1937
1950
  args.cmd in ("remember", "init", "restore", "forget", "capture", "extract")
1938
1951
  or (args.cmd == "dream" and not args.dry_run)
1939
1952
  or (args.cmd == "work" and action in ("add", "done", "flush", "clear"))
1953
+ or (args.cmd == "intent" and action in ("add", "done", "cancel", "reopen"))
1940
1954
  or (args.cmd == "topic" and action in ("touch", "feedback", "drop"))
1941
1955
  or (args.cmd == "persona" and action not in ("show", "path", "onboarding",
1942
1956
  "history", "snapshots", "drift",
@@ -2040,6 +2054,7 @@ def _main(argv=None) -> int:
2040
2054
  ttl_days=_ttl_days, review_at=_review_ts,
2041
2055
  correction=args.correction,
2042
2056
  project=(getattr(args, "project", "") or "").strip() or None,
2057
+ agent_id=(getattr(args, "agent_id", "") or "").strip() or None,
2043
2058
  # v3.58 三层元数据(FRAS / 源指纹 / 负空间)
2044
2059
  fras={"f": getattr(args, "fras_f", ""),
2045
2060
  "r": getattr(args, "fras_r", ""),
@@ -2151,7 +2166,7 @@ def _main(argv=None) -> int:
2151
2166
  return 0
2152
2167
  results = recall(query, args.k, include_archive=args.include_archive,
2153
2168
  mode=args.mode, with_evidence=args.evidence,
2154
- 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)
2155
2170
  record_retrieval(query, results, channel="recall")
2156
2171
  # 知识条目命中提示:recall 原本只查记忆层,顺带在 knowledge.jsonl 里做
2157
2172
  # 简单词面匹配——这个问题曾被沉淀成知识时先亮出来(含待审核条目),
@@ -3467,6 +3482,60 @@ def _main(argv=None) -> int:
3467
3482
  print(" work clear 丢掉")
3468
3483
  return 0
3469
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
+
3470
3539
  if args.cmd == "topic":
3471
3540
  name = (args.name or "").strip()
3472
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
  # 冷热归档层:长期没被想起、保留度极低的沉眠记忆雪藏到这里。
@@ -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) -> dict:
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()])
@@ -969,6 +1013,10 @@ def make_record(text: str, kind: str = "fact", importance: float | None = None,
969
1013
  rec["group_id"] = str(group_id)
970
1014
  if user:
971
1015
  rec["user"] = str(user)
1016
+ # agent 维度(阿里云 Memory 最佳实践):多 agent 共用同一记忆库时隔离。
1017
+ # 缺省不写字段 = 全局记忆,任何 agent 都能召回(向后兼容)。
1018
+ if agent_id:
1019
+ rec["agent_id"] = str(agent_id)
972
1020
  # —— 来源归属(origin,强制带):项目/会话 id 让每条记忆都能回答「从哪来的」。
973
1021
  # 冲突检测按同源比较(跨项目不误报),做梦/审计按 source 溯源。
974
1022
  # 缺省回落到 "default":老数据没有这两个字段照常工作,新写入一律补全。
@@ -1143,6 +1191,7 @@ def remember(text: str, kind: str = "fact", importance: float | None = None,
1143
1191
  channel: str | None = None, group_id: str | None = None,
1144
1192
  user: str | None = None,
1145
1193
  project: str | None = None, session: str | None = None,
1194
+ agent_id: str | None = None,
1146
1195
  ttl_days: float | None = None, review_at: int | None = None,
1147
1196
  correction: bool = False,
1148
1197
  fras: dict | None = None,
@@ -1262,7 +1311,7 @@ def remember(text: str, kind: str = "fact", importance: float | None = None,
1262
1311
 
1263
1312
  rec = make_record(text, kind, importance, tags, entities, source, layer,
1264
1313
  channel=channel, group_id=group_id, user=user,
1265
- project=project, session=session)
1314
+ project=project, session=session, agent_id=agent_id)
1266
1315
  # —— #41 correction 语义:用户说「不对/不是」语境下显式标记的改口记录 ——
1267
1316
  # correction 条目是失败闭环的第一手证据:做梦教训提炼(#36)优先读它,
1268
1317
  # 且合并/淡忘/归档路径都会跳过(永不自动合并消失),只有人工才能处理。
@@ -1831,7 +1880,7 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
1831
1880
  channel: str | None = None, group_id: str | None = None,
1832
1881
  user: str | None = None,
1833
1882
  target_user: str | None = None, asker: str | None = None,
1834
- project: str | None = None,
1883
+ project: str | None = None, agent_id: str | None = None,
1835
1884
  mode: str = "auto", with_evidence: bool = False, _archive_pass: int = 0) -> list:
1836
1885
  """模糊回忆:相关度 + 近期性 + 重要性 + 联想扩散。返回 [(record, score, parts), ...]
1837
1886
 
@@ -1882,6 +1931,14 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
1882
1931
  # 通道上下文的群间隔离:先物理过滤,其他群的记忆根本不进打分
1883
1932
  if channel is not None or group_id is not None or user is not None:
1884
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]
1885
1942
  if include_archive:
1886
1943
  archive = [m for m in load_archive() if m.get("id")
1887
1944
  and _channel_visible(m, channel, group_id, user)]
@@ -1955,6 +2012,7 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
1955
2012
  try:
1956
2013
  return recall(query, k, layers, strengthen, include_dust, True,
1957
2014
  channel, group_id, user, target_user, asker,
2015
+ project=project, agent_id=agent_id,
1958
2016
  mode=mode, _archive_pass=_archive_pass + 1)
1959
2017
  except Exception as e:
1960
2018
  log_event("recall", f"冷集兜底(热集空候选)失败:{e}", level="warn")
@@ -2015,6 +2073,13 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
2015
2073
  # 第四轮#3:同项目记忆加成(recall(project=...) 时生效)
2016
2074
  if project and m.pop("_project_boost", None):
2017
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
2018
2083
  # —— persona core 加权——
2019
2084
  # 记忆 kind=identity 或 tags/entities/kind 命中 persona 核心关键词时,
2020
2085
  # 追加 core_bias 比例加权;identity 是核心身份类,权重更高一点。
@@ -2119,6 +2184,7 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
2119
2184
  try:
2120
2185
  return recall(query, k, layers, strengthen, include_dust, True,
2121
2186
  channel, group_id, user, target_user, asker,
2187
+ project=project, agent_id=agent_id,
2122
2188
  mode=mode, _archive_pass=_archive_pass + 1)
2123
2189
  except Exception as e:
2124
2190
  log_event("recall", f"冷集自动补召失败:{e}", level="warn")
@@ -3655,6 +3721,20 @@ def build_injection(query: str = "", budget_tokens: int | None = None,
3655
3721
  [f"- [{fmt_date(m.get('created', 0))}] {display_text(m)}" for m in _rels],
3656
3722
  0.15)
3657
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
+
3658
3738
  # 时段语境:一句话给当下时间定性,让语气/行为与真实时间对齐(克制,不煽情)。
3659
3739
  # 这是全包变化最快的内容(分钟级),必须放在实时区,别毁掉前缀缓存。
3660
3740
  _bill["sec"] = "dynamic"
@@ -0,0 +1,225 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """灵枢发版自动化(把台账第四节的发布流程串成一条命令)。
4
+
5
+ 子命令
6
+ ------
7
+ python scripts/release.py bump <X.Y> ["小节标题"]
8
+ 1) 校验新版本 > 当前版本;
9
+ 2) 改四处版本:SKILL.md / package.json(X.Y.0) / README.md / CHANGELOG 首节占位;
10
+ 3) 按依赖序重生成:sync_engine → make_checksums → make_manifest;
11
+ 4) 跑六项检查 + 行为基线 + 全量测试,全绿才成功。
12
+ 不做 git 提交/tag/push(用户明确不做 tag/push,提交仍按"一个版本一个提交"手工或另配)。
13
+ 注意:若有新代码文件(如本脚本自己)尚未 git add,manifest --check 会拒绝——
14
+ 这是既有门禁,先 git add 新文件再 bump,脚本不替你决定哪些文件入库。
15
+
16
+ python scripts/release.py publish
17
+ 1) 校验版本四处一致(check_version)+ 六项检查全绿;
18
+ 2) npm whoami 确认登录;
19
+ 3) 确认包版本比线上大(避免 E409 重复发);
20
+ 4) npm publish;
21
+ 5) 轮询 registry 直到 latest==本地版本(npm staged 窗口最多 ~17 分钟)。
22
+ 不构建 tgz、不打 tag、不推 git。
23
+
24
+ python scripts/release.py status
25
+ 打印当前版本 / 线上 latest / 是否可发。
26
+ """
27
+ from __future__ import annotations
28
+
29
+ import argparse
30
+ import json
31
+ import re
32
+ import shutil
33
+ import subprocess
34
+ import sys
35
+ import time
36
+ import urllib.request
37
+ from pathlib import Path
38
+
39
+ ROOT = Path(__file__).resolve().parent.parent
40
+ PY = sys.executable
41
+ REGISTRY = "https://registry.npmjs.org"
42
+ PKG_NAME = "lingshu-skill"
43
+
44
+ CHECKS = [
45
+ ("manifest", ["scripts/make_manifest.py", "--check"]),
46
+ ("sync", ["scripts/sync_engine.py", "--check"]),
47
+ ("panel", ["scripts/panel_build.py", "--check"]),
48
+ ("checksums", ["scripts/astrbot_plugin_lingshu/make_checksums.py", "--check"]),
49
+ ("version", ["scripts/check_version.py"]),
50
+ ("pressure", ["scripts/check_pressure_sync.py"]),
51
+ ]
52
+ GENERATE = [
53
+ ["scripts/sync_engine.py"],
54
+ ["scripts/astrbot_plugin_lingshu/make_checksums.py"],
55
+ ["scripts/make_manifest.py"],
56
+ ]
57
+
58
+
59
+ def _run(args: list, *, capture: bool = False) -> tuple[int, str]:
60
+ cmd = [PY] + args
61
+ r = subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True,
62
+ encoding="utf-8", errors="replace")
63
+ out = (r.stdout + r.stderr) if capture else ""
64
+ if not capture:
65
+ # 直接透传,用户能看见进度
66
+ print(r.stdout, end="")
67
+ if r.stderr:
68
+ print(r.stderr, end="", file=sys.stderr)
69
+ return r.returncode, out
70
+
71
+
72
+ def cur_version() -> str:
73
+ t = (ROOT / "SKILL.md").read_text(encoding="utf-8-sig")
74
+ m = re.search(r"^version:\s*([\d.]+)", t, re.M)
75
+ return m.group(1) if m else ""
76
+
77
+
78
+ def _ver_tuple(v: str) -> tuple:
79
+ return tuple(int(x) for x in re.findall(r"\d+", v))
80
+
81
+
82
+ def registry_latest(timeout: int = 15) -> str | None:
83
+ try:
84
+ with urllib.request.urlopen(f"{REGISTRY}/{PKG_NAME}", timeout=timeout) as r:
85
+ d = json.load(r)
86
+ return str(d.get("dist-tags", {}).get("latest", "")) or None
87
+ except Exception:
88
+ return None
89
+
90
+
91
+ def do_bump(new_ver: str, title: str) -> int:
92
+ new_ver = new_ver.strip().lstrip("v")
93
+ if not re.fullmatch(r"\d+\.\d+", new_ver):
94
+ print(f"[release] 版本格式应为 X.Y,收到 {new_ver!r}", file=sys.stderr)
95
+ return 1
96
+ old = cur_version()
97
+ if _ver_tuple(new_ver) <= _ver_tuple(old):
98
+ print(f"[release] 新版本 {new_ver} 必须大于当前 {old}", file=sys.stderr)
99
+ return 1
100
+
101
+ # 1) 改四处版本(bytes,保 BOM/换行原样)
102
+ edits = [
103
+ ("SKILL.md", f"version: {old}".encode(), f"version: {new_ver}".encode()),
104
+ ("package.json", f'"version": "{old}.0"'.encode(), f'"version": "{new_ver}.0"'.encode()),
105
+ ("README.md", f"**v{old}**".encode(), f"**v{new_ver}**".encode()),
106
+ ]
107
+ for rel, o, n in edits:
108
+ p = ROOT / rel
109
+ b = p.read_bytes()
110
+ if o not in b:
111
+ print(f"[release] {rel} 没找到版本标记 {o!r},拒绝继续", file=sys.stderr)
112
+ return 1
113
+ p.write_bytes(b.replace(o, n, 1))
114
+ # CHANGELOG 首节改写为新版本(占位,正文留空由维护者补)
115
+ cl = ROOT / "CHANGELOG.md"
116
+ t = cl.read_text(encoding="utf-8")
117
+ first = re.search(r"^## v[\d.]+([^)]*)", t, re.M)
118
+ if not first:
119
+ print("[release] CHANGELOG.md 找不到首节标题,拒绝继续", file=sys.stderr)
120
+ return 1
121
+ today = time.strftime("%Y-%m-%d")
122
+ t = t[:first.start()] + f"## v{new_ver}({today})" + t[first.end():]
123
+ cl.write_text(t, encoding="utf-8", newline="")
124
+
125
+ # 2) 重生成派生文件
126
+ print(f"[release] 版本 {old} → {new_ver};重生成派生文件...")
127
+ for gen in GENERATE:
128
+ code, _ = _run(gen)
129
+ if code != 0:
130
+ print(f"[release] 生成失败:{gen}", file=sys.stderr)
131
+ return 1
132
+
133
+ # 3) 验证
134
+ return do_verify()
135
+
136
+
137
+ def do_verify() -> int:
138
+ bad = []
139
+ for name, args in CHECKS:
140
+ code, _ = _run(args)
141
+ print(f" {name}: {'OK' if code == 0 else 'FAIL'}")
142
+ if code != 0:
143
+ bad.append(name)
144
+ print("[release] 行为基线...")
145
+ code, _ = _run(["scripts/behavior_baseline.py", "check"])
146
+ print(f" baseline: {'OK' if code == 0 else 'FAIL'}")
147
+ if code != 0:
148
+ bad.append("baseline")
149
+ print("[release] 全量测试...")
150
+ code, _ = _run(["scripts/run_tests.py"])
151
+ print(f" tests: {'OK' if code == 0 else 'FAIL'}")
152
+ if code != 0:
153
+ bad.append("tests")
154
+ if bad:
155
+ print(f"[release] 验证失败:{', '.join(bad)}", file=sys.stderr)
156
+ return 1
157
+ print("[release] 全部验证通过 ✔")
158
+ return 0
159
+
160
+
161
+ def do_publish(wait_minutes: int) -> int:
162
+ ver = cur_version()
163
+ if do_verify() != 0:
164
+ return 1
165
+ npm = shutil.which("npm") or shutil.which("npm.cmd")
166
+ if not npm:
167
+ print("[release] 找不到 npm 命令", file=sys.stderr)
168
+ return 1
169
+ who = subprocess.run([npm, "whoami"], cwd=ROOT, capture_output=True, text=True,
170
+ encoding="utf-8", errors="replace").stdout.strip()
171
+ if not who:
172
+ print("[release] npm 未登录(npm whoami 无输出)", file=sys.stderr)
173
+ return 1
174
+ online = registry_latest()
175
+ if online and _ver_tuple(online) >= _ver_tuple(ver):
176
+ print(f"[release] 线上 latest={online} >= 本地 {ver},无需重复发布", file=sys.stderr)
177
+ return 1
178
+ print(f"[release] npm 发布 {PKG_NAME}@{ver}(登录用户 {who};线上 {online or '无'})...")
179
+ r = subprocess.run([npm, "publish"], cwd=ROOT)
180
+ if r.returncode != 0:
181
+ print("[release] npm publish 失败", file=sys.stderr)
182
+ return 1
183
+ # staged 窗口轮询
184
+ deadline = time.time() + wait_minutes * 60
185
+ while time.time() < deadline:
186
+ latest = registry_latest()
187
+ if latest == ver:
188
+ print(f"[release] 已可见:{PKG_NAME}@{latest}(latest)✔")
189
+ return 0
190
+ print(f" staged 窗口:latest={latest},等待可见(目标 {ver})...")
191
+ time.sleep(20)
192
+ print(f"[release] 超时({wait_minutes} 分钟)仍不可见,请手动查 registry", file=sys.stderr)
193
+ return 1
194
+
195
+
196
+ def do_status() -> int:
197
+ ver = cur_version()
198
+ online = registry_latest()
199
+ pkg = json.loads((ROOT / "package.json").read_text(encoding="utf-8-sig"))["version"]
200
+ print(f" 本地 SKILL: {ver} package.json: {pkg}")
201
+ print(f" 线上 latest: {online or '查询失败'}")
202
+ if online:
203
+ print(" 可发布:" , "是" if _ver_tuple(ver) > _ver_tuple(online) else "否(线上已 >= 本地)")
204
+ return 0
205
+
206
+
207
+ def main() -> int:
208
+ ap = argparse.ArgumentParser(description="灵枢发版自动化")
209
+ sub = ap.add_subparsers(dest="action", required=True)
210
+ p_bump = sub.add_parser("bump", help="升版本+重生成+验证")
211
+ p_bump.add_argument("version", help="新版本 X.Y")
212
+ p_bump.add_argument("title", nargs="?", default="", help="CHANGELOG 小节标题(可选)")
213
+ p_pub = sub.add_parser("publish", help="校验后 npm publish 并等 staged 可见")
214
+ p_pub.add_argument("--wait", type=int, default=20, help="staged 可见轮询最长分钟数(默认20)")
215
+ sub.add_parser("status", help="查看本地/线上版本")
216
+ args = ap.parse_args()
217
+ if args.action == "bump":
218
+ return do_bump(args.version, args.title)
219
+ if args.action == "publish":
220
+ return do_publish(getattr(args, "wait", 20))
221
+ return do_status()
222
+
223
+
224
+ if __name__ == "__main__":
225
+ sys.exit(main())
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)
@@ -1393,6 +1395,8 @@ def _main(argv=None) -> int:
1393
1395
  p_rec.add_argument("--verbatim", metavar="记忆ID",
1394
1396
  help='按 id 取回这条封存记忆的逐字原文快照(P5 #21 / foldkeep):'
1395
1397
  '做梦是有损压缩,用它追溯 AI 有没有改错原文。')
1398
+ p_rec.add_argument("--agent-id", default="",
1399
+ help="只召回该 agent 的记忆 + 全局记忆(agentId 维度隔离)")
1396
1400
 
1397
1401
  p_deref = sub.add_parser("deref", help="按需解引用:取一条记忆的证据原文(#46 Memex)")
1398
1402
  p_deref.add_argument("memory_id", help="记忆 id(通常是合并/蒸馏产物的 id)")
@@ -1713,6 +1717,15 @@ def _main(argv=None) -> int:
1713
1717
  help="flush 时丢弃已完成条目,不转记忆(做完了就该放下)")
1714
1718
  p_work.add_argument("--json", action="store_true")
1715
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
+
1716
1729
  p_topic = sub.add_parser("topic", help="话题栈:拟人闲聊用,记录聊过的话题与权重")
1717
1730
  p_topic.add_argument("action", nargs="?", default="list",
1718
1731
  choices=["list", "touch", "feedback", "drop", "status"])
@@ -1937,6 +1950,7 @@ def _main(argv=None) -> int:
1937
1950
  args.cmd in ("remember", "init", "restore", "forget", "capture", "extract")
1938
1951
  or (args.cmd == "dream" and not args.dry_run)
1939
1952
  or (args.cmd == "work" and action in ("add", "done", "flush", "clear"))
1953
+ or (args.cmd == "intent" and action in ("add", "done", "cancel", "reopen"))
1940
1954
  or (args.cmd == "topic" and action in ("touch", "feedback", "drop"))
1941
1955
  or (args.cmd == "persona" and action not in ("show", "path", "onboarding",
1942
1956
  "history", "snapshots", "drift",
@@ -2040,6 +2054,7 @@ def _main(argv=None) -> int:
2040
2054
  ttl_days=_ttl_days, review_at=_review_ts,
2041
2055
  correction=args.correction,
2042
2056
  project=(getattr(args, "project", "") or "").strip() or None,
2057
+ agent_id=(getattr(args, "agent_id", "") or "").strip() or None,
2043
2058
  # v3.58 三层元数据(FRAS / 源指纹 / 负空间)
2044
2059
  fras={"f": getattr(args, "fras_f", ""),
2045
2060
  "r": getattr(args, "fras_r", ""),
@@ -2151,7 +2166,7 @@ def _main(argv=None) -> int:
2151
2166
  return 0
2152
2167
  results = recall(query, args.k, include_archive=args.include_archive,
2153
2168
  mode=args.mode, with_evidence=args.evidence,
2154
- 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)
2155
2170
  record_retrieval(query, results, channel="recall")
2156
2171
  # 知识条目命中提示:recall 原本只查记忆层,顺带在 knowledge.jsonl 里做
2157
2172
  # 简单词面匹配——这个问题曾被沉淀成知识时先亮出来(含待审核条目),
@@ -3467,6 +3482,60 @@ def _main(argv=None) -> int:
3467
3482
  print(" work clear 丢掉")
3468
3483
  return 0
3469
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
+
3470
3539
  if args.cmd == "topic":
3471
3540
  name = (args.name or "").strip()
3472
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
  # 冷热归档层:长期没被想起、保留度极低的沉眠记忆雪藏到这里。
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) -> dict:
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()])
@@ -969,6 +1013,10 @@ def make_record(text: str, kind: str = "fact", importance: float | None = None,
969
1013
  rec["group_id"] = str(group_id)
970
1014
  if user:
971
1015
  rec["user"] = str(user)
1016
+ # agent 维度(阿里云 Memory 最佳实践):多 agent 共用同一记忆库时隔离。
1017
+ # 缺省不写字段 = 全局记忆,任何 agent 都能召回(向后兼容)。
1018
+ if agent_id:
1019
+ rec["agent_id"] = str(agent_id)
972
1020
  # —— 来源归属(origin,强制带):项目/会话 id 让每条记忆都能回答「从哪来的」。
973
1021
  # 冲突检测按同源比较(跨项目不误报),做梦/审计按 source 溯源。
974
1022
  # 缺省回落到 "default":老数据没有这两个字段照常工作,新写入一律补全。
@@ -1143,6 +1191,7 @@ def remember(text: str, kind: str = "fact", importance: float | None = None,
1143
1191
  channel: str | None = None, group_id: str | None = None,
1144
1192
  user: str | None = None,
1145
1193
  project: str | None = None, session: str | None = None,
1194
+ agent_id: str | None = None,
1146
1195
  ttl_days: float | None = None, review_at: int | None = None,
1147
1196
  correction: bool = False,
1148
1197
  fras: dict | None = None,
@@ -1262,7 +1311,7 @@ def remember(text: str, kind: str = "fact", importance: float | None = None,
1262
1311
 
1263
1312
  rec = make_record(text, kind, importance, tags, entities, source, layer,
1264
1313
  channel=channel, group_id=group_id, user=user,
1265
- project=project, session=session)
1314
+ project=project, session=session, agent_id=agent_id)
1266
1315
  # —— #41 correction 语义:用户说「不对/不是」语境下显式标记的改口记录 ——
1267
1316
  # correction 条目是失败闭环的第一手证据:做梦教训提炼(#36)优先读它,
1268
1317
  # 且合并/淡忘/归档路径都会跳过(永不自动合并消失),只有人工才能处理。
@@ -1831,7 +1880,7 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
1831
1880
  channel: str | None = None, group_id: str | None = None,
1832
1881
  user: str | None = None,
1833
1882
  target_user: str | None = None, asker: str | None = None,
1834
- project: str | None = None,
1883
+ project: str | None = None, agent_id: str | None = None,
1835
1884
  mode: str = "auto", with_evidence: bool = False, _archive_pass: int = 0) -> list:
1836
1885
  """模糊回忆:相关度 + 近期性 + 重要性 + 联想扩散。返回 [(record, score, parts), ...]
1837
1886
 
@@ -1882,6 +1931,14 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
1882
1931
  # 通道上下文的群间隔离:先物理过滤,其他群的记忆根本不进打分
1883
1932
  if channel is not None or group_id is not None or user is not None:
1884
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]
1885
1942
  if include_archive:
1886
1943
  archive = [m for m in load_archive() if m.get("id")
1887
1944
  and _channel_visible(m, channel, group_id, user)]
@@ -1955,6 +2012,7 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
1955
2012
  try:
1956
2013
  return recall(query, k, layers, strengthen, include_dust, True,
1957
2014
  channel, group_id, user, target_user, asker,
2015
+ project=project, agent_id=agent_id,
1958
2016
  mode=mode, _archive_pass=_archive_pass + 1)
1959
2017
  except Exception as e:
1960
2018
  log_event("recall", f"冷集兜底(热集空候选)失败:{e}", level="warn")
@@ -2015,6 +2073,13 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
2015
2073
  # 第四轮#3:同项目记忆加成(recall(project=...) 时生效)
2016
2074
  if project and m.pop("_project_boost", None):
2017
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
2018
2083
  # —— persona core 加权——
2019
2084
  # 记忆 kind=identity 或 tags/entities/kind 命中 persona 核心关键词时,
2020
2085
  # 追加 core_bias 比例加权;identity 是核心身份类,权重更高一点。
@@ -2119,6 +2184,7 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
2119
2184
  try:
2120
2185
  return recall(query, k, layers, strengthen, include_dust, True,
2121
2186
  channel, group_id, user, target_user, asker,
2187
+ project=project, agent_id=agent_id,
2122
2188
  mode=mode, _archive_pass=_archive_pass + 1)
2123
2189
  except Exception as e:
2124
2190
  log_event("recall", f"冷集自动补召失败:{e}", level="warn")
@@ -3655,6 +3721,20 @@ def build_injection(query: str = "", budget_tokens: int | None = None,
3655
3721
  [f"- [{fmt_date(m.get('created', 0))}] {display_text(m)}" for m in _rels],
3656
3722
  0.15)
3657
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
+
3658
3738
  # 时段语境:一句话给当下时间定性,让语气/行为与真实时间对齐(克制,不煽情)。
3659
3739
  # 这是全包变化最快的内容(分钟级),必须放在实时区,别毁掉前缀缓存。
3660
3740
  _bill["sec"] = "dynamic"
@@ -0,0 +1,225 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """灵枢发版自动化(把台账第四节的发布流程串成一条命令)。
4
+
5
+ 子命令
6
+ ------
7
+ python scripts/release.py bump <X.Y> ["小节标题"]
8
+ 1) 校验新版本 > 当前版本;
9
+ 2) 改四处版本:SKILL.md / package.json(X.Y.0) / README.md / CHANGELOG 首节占位;
10
+ 3) 按依赖序重生成:sync_engine → make_checksums → make_manifest;
11
+ 4) 跑六项检查 + 行为基线 + 全量测试,全绿才成功。
12
+ 不做 git 提交/tag/push(用户明确不做 tag/push,提交仍按"一个版本一个提交"手工或另配)。
13
+ 注意:若有新代码文件(如本脚本自己)尚未 git add,manifest --check 会拒绝——
14
+ 这是既有门禁,先 git add 新文件再 bump,脚本不替你决定哪些文件入库。
15
+
16
+ python scripts/release.py publish
17
+ 1) 校验版本四处一致(check_version)+ 六项检查全绿;
18
+ 2) npm whoami 确认登录;
19
+ 3) 确认包版本比线上大(避免 E409 重复发);
20
+ 4) npm publish;
21
+ 5) 轮询 registry 直到 latest==本地版本(npm staged 窗口最多 ~17 分钟)。
22
+ 不构建 tgz、不打 tag、不推 git。
23
+
24
+ python scripts/release.py status
25
+ 打印当前版本 / 线上 latest / 是否可发。
26
+ """
27
+ from __future__ import annotations
28
+
29
+ import argparse
30
+ import json
31
+ import re
32
+ import shutil
33
+ import subprocess
34
+ import sys
35
+ import time
36
+ import urllib.request
37
+ from pathlib import Path
38
+
39
+ ROOT = Path(__file__).resolve().parent.parent
40
+ PY = sys.executable
41
+ REGISTRY = "https://registry.npmjs.org"
42
+ PKG_NAME = "lingshu-skill"
43
+
44
+ CHECKS = [
45
+ ("manifest", ["scripts/make_manifest.py", "--check"]),
46
+ ("sync", ["scripts/sync_engine.py", "--check"]),
47
+ ("panel", ["scripts/panel_build.py", "--check"]),
48
+ ("checksums", ["scripts/astrbot_plugin_lingshu/make_checksums.py", "--check"]),
49
+ ("version", ["scripts/check_version.py"]),
50
+ ("pressure", ["scripts/check_pressure_sync.py"]),
51
+ ]
52
+ GENERATE = [
53
+ ["scripts/sync_engine.py"],
54
+ ["scripts/astrbot_plugin_lingshu/make_checksums.py"],
55
+ ["scripts/make_manifest.py"],
56
+ ]
57
+
58
+
59
+ def _run(args: list, *, capture: bool = False) -> tuple[int, str]:
60
+ cmd = [PY] + args
61
+ r = subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True,
62
+ encoding="utf-8", errors="replace")
63
+ out = (r.stdout + r.stderr) if capture else ""
64
+ if not capture:
65
+ # 直接透传,用户能看见进度
66
+ print(r.stdout, end="")
67
+ if r.stderr:
68
+ print(r.stderr, end="", file=sys.stderr)
69
+ return r.returncode, out
70
+
71
+
72
+ def cur_version() -> str:
73
+ t = (ROOT / "SKILL.md").read_text(encoding="utf-8-sig")
74
+ m = re.search(r"^version:\s*([\d.]+)", t, re.M)
75
+ return m.group(1) if m else ""
76
+
77
+
78
+ def _ver_tuple(v: str) -> tuple:
79
+ return tuple(int(x) for x in re.findall(r"\d+", v))
80
+
81
+
82
+ def registry_latest(timeout: int = 15) -> str | None:
83
+ try:
84
+ with urllib.request.urlopen(f"{REGISTRY}/{PKG_NAME}", timeout=timeout) as r:
85
+ d = json.load(r)
86
+ return str(d.get("dist-tags", {}).get("latest", "")) or None
87
+ except Exception:
88
+ return None
89
+
90
+
91
+ def do_bump(new_ver: str, title: str) -> int:
92
+ new_ver = new_ver.strip().lstrip("v")
93
+ if not re.fullmatch(r"\d+\.\d+", new_ver):
94
+ print(f"[release] 版本格式应为 X.Y,收到 {new_ver!r}", file=sys.stderr)
95
+ return 1
96
+ old = cur_version()
97
+ if _ver_tuple(new_ver) <= _ver_tuple(old):
98
+ print(f"[release] 新版本 {new_ver} 必须大于当前 {old}", file=sys.stderr)
99
+ return 1
100
+
101
+ # 1) 改四处版本(bytes,保 BOM/换行原样)
102
+ edits = [
103
+ ("SKILL.md", f"version: {old}".encode(), f"version: {new_ver}".encode()),
104
+ ("package.json", f'"version": "{old}.0"'.encode(), f'"version": "{new_ver}.0"'.encode()),
105
+ ("README.md", f"**v{old}**".encode(), f"**v{new_ver}**".encode()),
106
+ ]
107
+ for rel, o, n in edits:
108
+ p = ROOT / rel
109
+ b = p.read_bytes()
110
+ if o not in b:
111
+ print(f"[release] {rel} 没找到版本标记 {o!r},拒绝继续", file=sys.stderr)
112
+ return 1
113
+ p.write_bytes(b.replace(o, n, 1))
114
+ # CHANGELOG 首节改写为新版本(占位,正文留空由维护者补)
115
+ cl = ROOT / "CHANGELOG.md"
116
+ t = cl.read_text(encoding="utf-8")
117
+ first = re.search(r"^## v[\d.]+([^)]*)", t, re.M)
118
+ if not first:
119
+ print("[release] CHANGELOG.md 找不到首节标题,拒绝继续", file=sys.stderr)
120
+ return 1
121
+ today = time.strftime("%Y-%m-%d")
122
+ t = t[:first.start()] + f"## v{new_ver}({today})" + t[first.end():]
123
+ cl.write_text(t, encoding="utf-8", newline="")
124
+
125
+ # 2) 重生成派生文件
126
+ print(f"[release] 版本 {old} → {new_ver};重生成派生文件...")
127
+ for gen in GENERATE:
128
+ code, _ = _run(gen)
129
+ if code != 0:
130
+ print(f"[release] 生成失败:{gen}", file=sys.stderr)
131
+ return 1
132
+
133
+ # 3) 验证
134
+ return do_verify()
135
+
136
+
137
+ def do_verify() -> int:
138
+ bad = []
139
+ for name, args in CHECKS:
140
+ code, _ = _run(args)
141
+ print(f" {name}: {'OK' if code == 0 else 'FAIL'}")
142
+ if code != 0:
143
+ bad.append(name)
144
+ print("[release] 行为基线...")
145
+ code, _ = _run(["scripts/behavior_baseline.py", "check"])
146
+ print(f" baseline: {'OK' if code == 0 else 'FAIL'}")
147
+ if code != 0:
148
+ bad.append("baseline")
149
+ print("[release] 全量测试...")
150
+ code, _ = _run(["scripts/run_tests.py"])
151
+ print(f" tests: {'OK' if code == 0 else 'FAIL'}")
152
+ if code != 0:
153
+ bad.append("tests")
154
+ if bad:
155
+ print(f"[release] 验证失败:{', '.join(bad)}", file=sys.stderr)
156
+ return 1
157
+ print("[release] 全部验证通过 ✔")
158
+ return 0
159
+
160
+
161
+ def do_publish(wait_minutes: int) -> int:
162
+ ver = cur_version()
163
+ if do_verify() != 0:
164
+ return 1
165
+ npm = shutil.which("npm") or shutil.which("npm.cmd")
166
+ if not npm:
167
+ print("[release] 找不到 npm 命令", file=sys.stderr)
168
+ return 1
169
+ who = subprocess.run([npm, "whoami"], cwd=ROOT, capture_output=True, text=True,
170
+ encoding="utf-8", errors="replace").stdout.strip()
171
+ if not who:
172
+ print("[release] npm 未登录(npm whoami 无输出)", file=sys.stderr)
173
+ return 1
174
+ online = registry_latest()
175
+ if online and _ver_tuple(online) >= _ver_tuple(ver):
176
+ print(f"[release] 线上 latest={online} >= 本地 {ver},无需重复发布", file=sys.stderr)
177
+ return 1
178
+ print(f"[release] npm 发布 {PKG_NAME}@{ver}(登录用户 {who};线上 {online or '无'})...")
179
+ r = subprocess.run([npm, "publish"], cwd=ROOT)
180
+ if r.returncode != 0:
181
+ print("[release] npm publish 失败", file=sys.stderr)
182
+ return 1
183
+ # staged 窗口轮询
184
+ deadline = time.time() + wait_minutes * 60
185
+ while time.time() < deadline:
186
+ latest = registry_latest()
187
+ if latest == ver:
188
+ print(f"[release] 已可见:{PKG_NAME}@{latest}(latest)✔")
189
+ return 0
190
+ print(f" staged 窗口:latest={latest},等待可见(目标 {ver})...")
191
+ time.sleep(20)
192
+ print(f"[release] 超时({wait_minutes} 分钟)仍不可见,请手动查 registry", file=sys.stderr)
193
+ return 1
194
+
195
+
196
+ def do_status() -> int:
197
+ ver = cur_version()
198
+ online = registry_latest()
199
+ pkg = json.loads((ROOT / "package.json").read_text(encoding="utf-8-sig"))["version"]
200
+ print(f" 本地 SKILL: {ver} package.json: {pkg}")
201
+ print(f" 线上 latest: {online or '查询失败'}")
202
+ if online:
203
+ print(" 可发布:" , "是" if _ver_tuple(ver) > _ver_tuple(online) else "否(线上已 >= 本地)")
204
+ return 0
205
+
206
+
207
+ def main() -> int:
208
+ ap = argparse.ArgumentParser(description="灵枢发版自动化")
209
+ sub = ap.add_subparsers(dest="action", required=True)
210
+ p_bump = sub.add_parser("bump", help="升版本+重生成+验证")
211
+ p_bump.add_argument("version", help="新版本 X.Y")
212
+ p_bump.add_argument("title", nargs="?", default="", help="CHANGELOG 小节标题(可选)")
213
+ p_pub = sub.add_parser("publish", help="校验后 npm publish 并等 staged 可见")
214
+ p_pub.add_argument("--wait", type=int, default=20, help="staged 可见轮询最长分钟数(默认20)")
215
+ sub.add_parser("status", help="查看本地/线上版本")
216
+ args = ap.parse_args()
217
+ if args.action == "bump":
218
+ return do_bump(args.version, args.title)
219
+ if args.action == "publish":
220
+ return do_publish(getattr(args, "wait", 20))
221
+ return do_status()
222
+
223
+
224
+ if __name__ == "__main__":
225
+ sys.exit(main())