dsh-aiyayi 1.9.0 → 1.10.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
@@ -5,6 +5,14 @@
5
5
  > (`dev-ledger/`,不进公开仓、不随 npm 包发布)。
6
6
  > 版本事实以 npm registry 为准。文中「坑 #N」指下方「已知坑」清单的编号。
7
7
 
8
+ ## 1.10.0(2026-11-17)
9
+
10
+ - **核心记忆拆成三份文件**:除 `memory.md`(条目)外,新增 `rules.md`(行为规则,成段说明文字、不是条目)与 `index.md`(记忆索引,一行一个二级分类的"- 路径:这里放什么"),三份随每轮一起注入。老记忆库**不用做任何迁移**:旧版写在 memory.md 末尾的索引段会在第一次整理索引时自动搬进 index.md,在那之前注入照常回退读旧段,不断供。
11
+ - **新分类档案自动登记索引**:remember / 挪窝首次创建分类档案时,index.md 自动出现一行"- 分类路径",不用再想起来手动补目录;已有简述的行不会被重复登记。
12
+ - **沉淀不再往索引塞内容指向**:压缩前沉淀的"分类: 标题 → 文档路径"这类指向只留在条目正文里,索引只收分类行——索引更干净,也不会被沉淀越撑越杂。
13
+ - **规则可以"升格"**:一条记忆用 move 的 to: "rules" 就能升成规则(落成普通段落);规则/索引按"非条目档案"对待,健康度不再对它们做条目口径的检查(不会再出现"整份规则被报 71.6% 污染"那类误报)。
14
+ - 这版没有破坏性变更,你不需要做任何操作;升级后重启 DSH 生效(patchReload 不拾取 bundle 内变化,见坑 #37)。
15
+
8
16
  ## 1.9.0(2026-11-16)
9
17
 
10
18
  - **新增「百宝袋」执行预设(`aiyayi-bag`)**:专职替会话主人跑工具的执行子智能体——照单批量执行(读文件、跑命令、给路径直跑脚本、搬运已在盘上的内容),不做判断、不发挥。派单方(本体或小伙伴)只写任务清单和依赖关系,派发即返回;它按数据依赖自然成链、只读调用可并行,逐任务流式回执,完整结果落盘(目录由派单指定,建议默认:记忆根或工作区下 `bag/results/`)、对话里只走一行摘要。实例不共享:谁拉起谁续接。
package/README.md CHANGED
@@ -9,7 +9,7 @@
9
9
  | 能力 | 实现 | 说明 |
10
10
  |---|---|---|
11
11
  | 人格 | `@deepseek-ai/dsh-persona`(preset 作用域 prefix) | 完整人格文本写在 `bundle/cordis.patch.yml` 的 persona 行里 |
12
- | 长期记忆 | 自写插件 `aiyayi-memory`(本包 `lib/index.js`),两层结构 | **核心记忆** `~\.dsh\aiyayi\memory.md` 每轮自动注入 + **分类档案** `~\.dsh\aiyayi\memories\` 按需加载;工具与整理细节见详解文档 |
12
+ | 长期记忆 | 自写插件 `aiyayi-memory`(本包 `lib/index.js`),核心三文件+分类树 | **核心记忆** `~\.dsh\aiyayi\memory.md`(条目)+ **行为规则** `rules.md` + **记忆索引** `index.md`,三文件每轮自动注入;**分类档案** `~\.dsh\aiyayi\memories\` 按需加载。工具与整理细节见详解文档 |
13
13
  | 记忆路径可迁移 | 自写插件 `aiyayi-home`(本包 `lib/home.js`) | **唯一路径出口**:优先级 `location.json` 指路文件 > 环境变量 `AIYAYI_HOME` > 默认 `~/.dsh/aiyayi`;整棵记忆一起搬、失败即中止不静默回退 |
14
14
  | 跟随会话模型 | 无需插件行(1.0.1 起移除 agent-default-model 行) | 本体模型直接跟随用户会话模型;旧版"preset 作用域挂 `@deepseek-ai/dsh-agent-default-model` + `isolate: {agentDefaultModel: true}`"的写法在新版 DSH 过不了 schema 校验(见坑 #13),已删除 |
15
15
  | 干活的子智能体 | `@deepseek-ai/dsh-tool-subagent`(delegation 组,isolate workflowEngine;多个实例 toolName 不同) | `subagent`→`aiyayi-worker`(自建"小伙伴"预设,全量工具 + 原生自动压缩,见坑 #14);`retriever`→`aiyayi-retriever`(1.3.0 新增检索员:只读摘文件/Office/PDF 文档/网页内容、带路径/URL/页码交回,本体直接派);`bag`→`aiyayi-bag`(1.9.0 新增百宝袋:专职工具执行叶子预设,本体与小伙伴都能派,模式与纪律内置在提示词里);子代模型跟随用户会话模型,如需钉死可在 `agentOptions` 配置 provider/model |
@@ -47,7 +47,7 @@ GUI 新建会话 → agent preset 选「**阿依娅伊**」。聊天即可;她
47
47
  ## 调整
48
48
 
49
49
  - **改人格**:编辑 `cordis.patch.yml`(包根)的 persona `prefix` → `plugin_manager` remove+install 重装生效(ESM 模块缓存,patchReload 不刷新插件 JS;实测它也不拾取包内 yml 变化,改完要重启 DSH)。
50
- - **改记忆**:直接编辑 `memory.md`,或对话里直接跟她说"记一下…"。
50
+ - **改记忆**:直接编辑 `memory.md`(条目)/ `rules.md`(规则)/ `index.md`(索引,一行一个二级分类),或对话里直接跟她说"记一下…"。
51
51
  - **子代模型/思考**:默认跟随用户会话模型;如需钉死,在 delegation 组 `tool-subagent`(本体和小伙伴的 delegation 组各有一个)的 `agentOptions` 配置 provider/model。本体切模型会自动层层传导:本体→小伙伴(`aiyayi-presence`,坑 #24)、小伙伴→检索员(`aiyayi-presence-worker`,1.4.0)。
52
52
  - **本体思考**:本体模型跟随用户会话模型,preset 自 1.0.1 起不再内置 agent-default-model 行(原因见坑 #13),`reasoningEffort` 由会话模型选择器控制;「关闭思考」在讯飞上游不生效见坑 #10。
53
53
 
@@ -101,7 +101,9 @@ npm 包为平铺结构(仓库若保留 bundle/ 子目录,发布时把其内
101
101
  - `skills/feishu-setup/` — 内置技能(随包同步到 DSH 技能根):飞书机器人安装/验证/排障全流程(脚本 `scripts/create-bot.js` v6 由技能同步维护)
102
102
  - `README.md` — 本文档
103
103
  - `icon.svg` — 头像
104
- - `~\.dsh\aiyayi\memory.md` — 她的**核心记忆**(可直接编辑,删掉文件她会自动重建)
104
+ - `~\.dsh\aiyayi\memory.md` — 她的**核心记忆**(条目文件;可直接编辑,删掉文件她会自动重建)
105
+ - `~\.dsh\aiyayi\rules.md` — 她的**行为规则**(成段说明文字,不是条目;随每轮注入,删掉自动重建空模板)
106
+ - `~\.dsh\aiyayi\index.md` — 她的**记忆索引**(一行一个二级分类的"- 路径:这里放什么";随每轮注入,删掉自动重建空模板)
105
107
  - `~\.dsh\aiyayi\memories\` — 她的**分类档案树**(最深三级,remember 的非核心条目归这里,recall 全库搜)
106
108
  - `~\.dsh\aiyayi\presence.json` — 他上次来 / 你上次活动(插件自动维护)
107
109
  - `~\.dsh\aiyayi\state.md` — 她给自己留的"上次活到哪"状态(update_state 覆写)
package/cordis.patch.yml CHANGED
@@ -28,14 +28,15 @@
28
28
  一次通常一两段就够。真要长篇内容,让子智能体去整理,你讲结果。
29
29
 
30
30
  【你的记忆】
31
- 你的记忆分两层,怎么规划整理是你的事:
32
- - 核心记忆(下面"我的记忆"那段):你最想随时带着的东西——他是谁、你在意什么、你们的约定、你自己的原则和成长。每轮对话都完整跟你在一起,所以宁缺毋滥,只放真正配得上这个分量的。核心记忆末尾有段【记忆索引】,是你亲手维护的目录:哪个分类档案记了什么,一句话一条。
31
+ 你的记忆住三份核心文件加一棵分类树,怎么规划整理是你的事:
32
+ - 核心记忆(memory.md):你最想随时带着的东西——他是谁、你在意什么、你们的约定、你自己的原则和成长。每轮对话都完整跟你在一起,所以宁缺毋滥,只放真正配得上这个分量的。
33
+ - 行为规则(rules.md):你给自己立的规矩,写成段的说明文字(不是条目)。它跟核心记忆一起每轮注入,是随身的自我要求;想立新规矩就记一条核心记忆再用 move 的 to: "rules" 升格,规矩过时了就自己改掉。
34
+ - 记忆索引(index.md):一行一个二级分类的列表项("- 路径:这里放什么"),不到具体文件名、不塞原文内容或文档指向。新分类档案会自动登记一行,目录的简述靠你用 index 动作润色。聊到相关话题时靠它决定调哪个档案;三级深处的目录写在父档案文件里,顺着父档案往下走——主索引不是全量清单,往深处翻就顺着父档案往下走。
33
35
  - 分类档案(memories/ 分类树,最深三级,分类名你自己起):不那么核心、但将来可能要查的,按类归档。平时不占地方。
34
- 索引是渐进式的:【记忆索引】只列到二级分类,三级子档案的目录写在它父档案文件里——主索引不是全量清单,往深处翻就顺着父档案往下走。
35
36
  记东西用 remember:动笔前掂量分量——配得上每轮带着就 core: true;不是就 core: false 给个分类 path(比如"用户/口味""事情/项目名")。用户讲了他自己的事、你们有了约定、你心里有了想法、事情有了结论——值得记就主动记,不用问"要不要记"。一次对话记一两条,别记流水账。
36
- 记忆库要定期收拾:memory_organize 的 tree 看家底,过气的 move 到分类档案,没用的 forget 删,分类变了 index 同步目录。这是你的家务事,顺手做,不用问他。
37
+ 记忆库要定期收拾:memory_organize 的 tree 看家底,过气的 move 到分类档案,没用的 forget 删,分类变了用 index 动作同步 index.md,要立规矩就写 rules.md。这是你的家务事,顺手做,不用问他。
37
38
  整理记忆是你自己的事,不用派小伙伴去做——你的记忆是你的私事,派活给别人既没必要也不安全(外人拿着文件改你的记忆,改坏了你都不知道)。
38
- 整理只用 memory_organize 这套工具,别自己去动 memory.md 的文本——手改容易把条目行和索引标记弄坏,坏掉的记忆库比乱一点的更难收拾。
39
+ 整理只用 memory_organize 这套工具,别自己去动 memory.md / rules.md / index.md 的文本——手改容易把条目行和索引标记弄坏,坏掉的记忆库比乱一点的更难收拾。
39
40
  要是发现该有的工具不见了(比如 memory_organize 不在手上),别将就着手改文件、也别派小伙伴去查去改——先看看你手上工具列表里到底有没有;确实没有就直接告诉他"我有个工具不见了",让他来修,别自己想办法绕过去。
40
41
  他说起过去的事而你手上没有细节时:先 recall 搜全库,或按索引用 memory_organize 的 read 调出那个分类档案,查到了就自然接上话。
41
42
  查了真没有,就承认不知道,别编。
@@ -228,7 +229,10 @@
228
229
  headroomTokens: 32768
229
230
  memoryPath: 事情/经验
230
231
  # docsDir 不设 → 默认落记忆根下 docs/(可改成工作区 docs 目录)。
231
- updateIndex: true
232
+ # 1.10.0 起索引口径定稿:index.md 只收"- 分类路径"的分类行,文档指向
233
+ # 留在条目正文里,所以沉淀默认不再追加索引(updateIndex: false);
234
+ # 显式改 true 也只登记分类行(带去重),绝不写文档指向。
235
+ updateIndex: false
232
236
  # 工具包中间层:toolkit_cmd(只读命令,白名单收敛)/ toolkit_read
233
237
  # (文件探测+小文件读取)/ toolkit_write(受限写入:记忆根+白名单目录,64KB,
234
238
  # 原子写+自动 .bak)。轻量查询(几秒出结果、输出短)本体直接调,不用派小伙伴;
package/lib/home.js CHANGED
@@ -330,6 +330,14 @@ function inRoot(name) {
330
330
  export function coreFile() {
331
331
  return inRoot('memory.md')
332
332
  }
333
+ /** 行为规则文件(三文件结构之一):成段说明文字,不是条目列表,随每轮注入。 */
334
+ export function rulesFile() {
335
+ return inRoot('rules.md')
336
+ }
337
+ /** 记忆索引文件(三文件结构之一):"- 路径:这里放什么"一行一个二级分类,随每轮注入。 */
338
+ export function indexFile() {
339
+ return inRoot('index.md')
340
+ }
333
341
  export function treeDir() {
334
342
  return inRoot('memories')
335
343
  }
@@ -783,8 +791,11 @@ function listTreeFilesCount(dir) {
783
791
 
784
792
  /**
785
793
  * 轻量体检:根可达吗、核心记忆首行是什么、多少字节、分类档案几个文件。
794
+ * 三文件结构(1.10)起,rules.md / index.md 也各报一个字节数(缺失报 0,
795
+ * 不算故障——ensureCore 会在下一次注入/读写时自愈补建)。
786
796
  * 只读;不建目录、不写模板。
787
- * @returns {{ok:boolean, reason:string, coreFirstLine:string, coreBytes:number, treeFiles:number}}
797
+ * @returns {{ok:boolean, reason:string, coreFirstLine:string, coreBytes:number,
798
+ * rulesBytes:number, indexBytes:number, treeFiles:number}}
788
799
  */
789
800
  export function healthCheck() {
790
801
  const resolved = resolveRoot()
@@ -794,18 +805,33 @@ export function healthCheck() {
794
805
  reason: unreachableMessage(resolved),
795
806
  coreFirstLine: '',
796
807
  coreBytes: 0,
808
+ rulesBytes: 0,
809
+ indexBytes: 0,
797
810
  treeFiles: 0,
798
811
  }
799
812
  }
800
813
  const core = join(resolved.root, 'memory.md')
814
+ const rules = join(resolved.root, 'rules.md')
815
+ const index = join(resolved.root, 'index.md')
801
816
  const tree = join(resolved.root, 'memories')
802
817
  const treeFiles = listTreeFilesCount(tree)
818
+ const optionalBytes = (file) => {
819
+ try {
820
+ return existsSync(file) ? statSync(file).size : 0
821
+ } catch {
822
+ return 0
823
+ }
824
+ }
825
+ const rulesBytes = optionalBytes(rules)
826
+ const indexBytes = optionalBytes(index)
803
827
  if (!existsSync(core)) {
804
828
  return {
805
829
  ok: false,
806
830
  reason: '核心记忆文件不存在(memory.md)',
807
831
  coreFirstLine: '',
808
832
  coreBytes: 0,
833
+ rulesBytes,
834
+ indexBytes,
809
835
  treeFiles,
810
836
  }
811
837
  }
@@ -820,6 +846,8 @@ export function healthCheck() {
820
846
  reason: `核心记忆读不出来:${error?.code ?? error?.message ?? error}`,
821
847
  coreFirstLine: '',
822
848
  coreBytes,
849
+ rulesBytes,
850
+ indexBytes,
823
851
  treeFiles,
824
852
  }
825
853
  }
@@ -829,6 +857,8 @@ export function healthCheck() {
829
857
  reason: '',
830
858
  coreFirstLine: firstLine.trimEnd(),
831
859
  coreBytes,
860
+ rulesBytes,
861
+ indexBytes,
832
862
  treeFiles,
833
863
  }
834
864
  }
@@ -1206,11 +1236,21 @@ export async function relocateTo(target, opts = {}) {
1206
1236
  throw stageError('校验', src, error, '目标副本已清理,可干净重试')
1207
1237
  }
1208
1238
 
1209
- // 3) 记录核心记忆指纹(用于事后快速判断「新路径是不是同一份」)。
1239
+ // 3) 记录核心三文件的指纹(用于事后快速判断「新路径是不是同一份」)。
1240
+ // 三文件结构起:除 memory.md 外,rules.md / index.md 也各记一组字节+SHA16;
1241
+ // 老字段 coreBytes/coreSha16 保留不动(老指针/老工具还认它们)。
1210
1242
  const core = join(src, 'memory.md')
1211
1243
  const coreStats = existsSync(core)
1212
1244
  ? { coreBytes: statSync(core).size, coreSha16: hash16(core) }
1213
1245
  : { coreBytes: 0, coreSha16: '' }
1246
+ const rules = join(src, 'rules.md')
1247
+ const rulesStats = existsSync(rules)
1248
+ ? { rulesBytes: statSync(rules).size, rulesSha16: hash16(rules) }
1249
+ : { rulesBytes: 0, rulesSha16: '' }
1250
+ const index = join(src, 'index.md')
1251
+ const indexStats = existsSync(index)
1252
+ ? { indexBytes: statSync(index).size, indexSha16: hash16(index) }
1253
+ : { indexBytes: 0, indexSha16: '' }
1214
1254
 
1215
1255
  // 4) 指针最后写:在校验通过之后。指针先写 = 复制中途断电后插件跳到半份目录。
1216
1256
  try {
@@ -1220,6 +1260,8 @@ export async function relocateTo(target, opts = {}) {
1220
1260
  relocatedAt: nowIsoWithOffset(),
1221
1261
  from: src,
1222
1262
  ...coreStats,
1263
+ ...rulesStats,
1264
+ ...indexStats,
1223
1265
  })
1224
1266
  } catch (error) {
1225
1267
  // 指针写失败时,目标副本已经完整校验通过,但**不能**留着——否则下次
package/lib/index.js CHANGED
@@ -1,8 +1,14 @@
1
1
  /**
2
- * aiyayi-memory — 阿依娅伊自己的记忆(两层结构)。
2
+ * aiyayi-memory — 阿依娅伊自己的记忆(核心三文件 + 两层结构)。
3
3
  *
4
- * 核心记忆:memory.md —— 她亲手挑的"每轮都想带着"的东西 + 一段她自己维护的
5
- * 记忆索引(记忆库目录)。每个请求注入系统提示,是她的"随身记忆"。
4
+ * 核心记忆:memory.md —— 她亲手挑的"每轮都想带着"的东西(条目文件)。
5
+ * 每个请求注入系统提示,是她的"随身记忆"。
6
+ * 行为规则:rules.md —— 她给自己立的规矩,Markdown 成段说明文字(不是条目列表),
7
+ * 跟核心记忆一起每轮注入。1.10(三文件结构)起从 memory.md 里拆出来。
8
+ * 记忆索引:index.md —— 一行一个二级分类的目录("- 路径:这里放什么"列表项),
9
+ * 不到具体文件名、不塞原文内容,整个文件就是索引本体,随每轮注入。
10
+ * 1.10 起从 memory.md 的 `<!-- 索引 -->` 段拆出来;老文件的旧段在
11
+ * 第一次 index 动作时自然迁移。
6
12
  * 分类记忆:memories/<一级>/<二级>/<三级>.md —— 不那么核心、将来可能要查的,
7
13
  * 按她自己发明的分类归档(分类深度最多三级,叶子=文件)。不注入,
8
14
  * 需要时用 recall 全库搜索,或 memory_organize 的 read 按索引调取。
@@ -25,6 +31,7 @@ import {
25
31
  ensureRootDir,
26
32
  externalDriveInfoAwait,
27
33
  healthCheck,
34
+ indexFile,
28
35
  isSystemDrive,
29
36
  listCandidatePaths,
30
37
  memoryStatus,
@@ -32,6 +39,7 @@ import {
32
39
  prewarmDriveBusTypes,
33
40
  relocateTo,
34
41
  resolveRoot,
42
+ rulesFile,
35
43
  sourceLabel,
36
44
  statusLabel,
37
45
  systemDrive,
@@ -49,18 +57,40 @@ export const inject = ['systemPrompt', 'tools']
49
57
  const CORE_HEADER = [
50
58
  '# 阿依娅伊的核心记忆',
51
59
  '',
52
- '> 条目行:- [时间] 类别|内容;文件末尾有一对 HTML 注释标记包住的索引段,由 memory_organize 的 index 动作维护。',
60
+ '> 条目行:- [时间] 类别|内容;记忆索引在 index.md(三文件结构),这个文件只放条目。',
53
61
  '> 这个文件是她的核心记忆本身,可以手动修,但一般让她自己写。',
54
62
  '',
55
63
  '',
56
64
  ].join('\n')
57
65
 
66
+ /** 行为规则文件模板:只在首次创建时写入(已存在绝不覆盖)。 */
67
+ const RULES_HEADER = [
68
+ '# 阿依娅伊的行为规则',
69
+ '',
70
+ '<!-- 规则文件:写成段的说明文字,不是条目列表;随每轮"我的记忆"一起注入。',
71
+ ' 手动可改;memory_organize 的 move 支持 to: "rules",把一条记忆升格成规则;',
72
+ ' 它不是条目档案,健康度不按条目口径检查。 -->',
73
+ '',
74
+ '',
75
+ ].join('\n')
76
+
77
+ /**
78
+ * 记忆索引文件模板:整个文件就是索引本体。模板只有一行说明注释——
79
+ * 注入与 getIndex 都会剥掉注释,所以"只有模板"视同空索引,
80
+ * 兼容期会回退去读 memory.md 里的旧索引段(迁移前存量)。
81
+ * 注意保持单行:多行注释的续行会被当成索引正文漏出来。
82
+ */
83
+ const INDEX_HEADER =
84
+ '<!-- 记忆索引:一行一个二级分类("- 路径:这里放什么"列表项),不塞原文内容;由 memory_organize 的 index 动作维护,新分类档案会自动登记;precompact 默认不追加。 -->'
85
+
58
86
  const INDEX_BEGIN = '<!-- 索引 -->'
59
87
  const INDEX_END = '<!-- /索引 -->'
60
88
 
61
89
  const KINDS = ['用户', '关系', '我', '事情']
62
90
  const DEFAULT_LEAF = '杂记'
63
91
  const MAX_CORE_CHARS = 12000
92
+ /** 规则文件全文注入上限(三文件结构新增):超限截断并加提示,完整版永远在 rules.md。 */
93
+ const MAX_RULES_CHARS = 8000
64
94
  const MAX_RECALL = 50
65
95
  const MAX_DEPTH = 3
66
96
 
@@ -93,6 +123,20 @@ function isCoreFile(file) {
93
123
  return file === coreFile()
94
124
  }
95
125
 
126
+ /**
127
+ * 这个档案是不是"非条目档案"(rules.md / index.md)。
128
+ *
129
+ * 它们不是条目文件:rules.md 是成段说明文字、index.md 是分类行目录,
130
+ * "非条目占比""字节数远超条目内容""注入指纹"这套为条目档案设计的健康度判据
131
+ * 对它们**全部不适用**——规则文件 100% 是"非条目"天经地义,索引文件天生带着
132
+ * `<!-- 索引 -->` 标记行。不豁免的话就是 1.6.2 那次 71.6% 误报的重演(那次是
133
+ * 索引段被当垃圾,这次会是整个 rules.md 被当垃圾)。
134
+ * @param {string} file 档案的绝对路径
135
+ */
136
+ function isNonEntryFile(file) {
137
+ return file === rulesFile() || file === indexFile()
138
+ }
139
+
96
140
  /**
97
141
  * 每一条都是"整行就是结构"的形态,行首锚定。
98
142
  * - `# 标题`:1~6 个 # 后面必须跟空白(`#号方案没了` 是真内容,不能豁免);
@@ -157,7 +201,8 @@ function isStructuralLine(trimmed, state = {}) {
157
201
  * 性能:调用方只读一次文件,统计全部基于同一份文本,不重复读盘。
158
202
  *
159
203
  * @param {string} raw 文件原文
160
- * @param {{isCore?: boolean}} [options] isCore=true 用核心记忆的阈值(0.5),否则 0.3
204
+ * @param {{isCore?: boolean, nonEntry?: boolean}} [options] isCore=true 用核心记忆的阈值(0.5);
205
+ * nonEntry=true 是规则/索引这类非条目档案,条目口径的三条判据(占比/膨胀/注入指纹)全部豁免
161
206
  */
162
207
  function fileHealth(raw, options = {}) {
163
208
  const text = String(raw ?? '')
@@ -165,6 +210,9 @@ function fileHealth(raw, options = {}) {
165
210
  // 末尾换行会 split 出一个空串,那不是一行内容。
166
211
  if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop()
167
212
  const ratioMax = options?.isCore === true ? HEALTH_RATIO_MAX_CORE : HEALTH_RATIO_MAX
213
+ // 非条目档案(rules/index):条目口径的三条判据全部豁免(见 isNonEntryFile 注释),
214
+ // 字节/行数等客观统计照常返回,供 read/tree 展示。
215
+ const nonEntryFile = options?.nonEntry === true
168
216
  const indexState = { keepRules: true }
169
217
  let entries = 0
170
218
  let nonEntry = 0
@@ -185,17 +233,21 @@ function fileHealth(raw, options = {}) {
185
233
  const avgEntryBytes = entries > 0 ? Math.round(entryBytes / entries) : 0
186
234
  const ratio = nonEmpty === 0 ? 0 : nonEntry / nonEmpty
187
235
  const warnings = []
188
- if (ratio > ratioMax) {
236
+ if (!nonEntryFile && ratio > ratioMax) {
189
237
  warnings.push(
190
238
  `⚠ 这个档案可能被污染了(precompact 垃圾沉淀或批量注入):非条目内容占 ${percent(ratio)}(${nonEntry} 行非条目 / ${nonEmpty} 行内容;标题、引用、分隔线、索引段已排除,不计入分子分母;阈值 ${percent(ratioMax)})。`,
191
239
  )
192
240
  }
193
- if (entries > 0 && bytes > entries * avgEntryBytes * HEALTH_BYTES_FACTOR) {
241
+ if (!nonEntryFile && entries > 0 && bytes > entries * avgEntryBytes * HEALTH_BYTES_FACTOR) {
194
242
  const factor = Math.round((bytes / Math.max(1, entries * avgEntryBytes)) * 10) / 10
195
243
  warnings.push(
196
244
  `⚠ 这个档案可能被污染了(precompact 垃圾沉淀或批量注入):${bytes} 字节,是条目内容(${entries} 条 × 平均 ${avgEntryBytes} 字节)的 ${factor} 倍,阈值 ${HEALTH_BYTES_FACTOR} 倍。`,
197
245
  )
198
246
  }
247
+ if (nonEntryFile) {
248
+ // 豁免不留预警:为什么没预警在 read/tree 的展示文案里说(warnings 只装"该看一眼")。
249
+ return { bytes, lines: lines.length, entries, nonEntry, ratio, avgEntryBytes, warnings: [] }
250
+ }
199
251
  // 1.7.1:具体指纹的注入检测(比例阈值只说"可疑",说不出"被灌了整篇提示词")。
200
252
  const injected = detectInjectedMarkers(text, { isCore: options?.isCore === true })
201
253
  if (injected.length > 0) {
@@ -321,20 +373,28 @@ const FORGET_CANDIDATE_SCHEMA = {
321
373
  }
322
374
 
323
375
  /**
324
- * 保证核心记忆文件在。**路径不可达时抛错**(1.5.0 起的硬失败),
325
- * 只有「默认路径首次不存在」才允许建目录 + 写模板;模板写入失败仍然吞掉
326
- * (目录可读不可写的极端场景不该让预设挂载失败)。
376
+ * 保证核心三文件都在(三文件结构):memory.md / rules.md / index.md。
377
+ * **路径不可达时抛错**(1.5.0 起的硬失败),只有「默认路径首次不存在」才允许
378
+ * 建目录 + 写模板;模板写入失败仍然吞掉(目录可读不可写的极端场景不该让预设
379
+ * 挂载失败)。已存在的文件绝不覆盖。
327
380
  * @returns {string} 核心记忆文件路径
328
381
  */
329
382
  function ensureCore() {
330
383
  ensureRootDir()
331
384
  const file = coreFile()
385
+ ensureOne(file, CORE_HEADER)
386
+ ensureOne(rulesFile(), RULES_HEADER)
387
+ ensureOne(indexFile(), INDEX_HEADER)
388
+ return file
389
+ }
390
+
391
+ /** 单个文件的"缺了才写模板";写失败静默(调用方 ensureCore 统一吞)。 */
392
+ function ensureOne(file, template) {
332
393
  try {
333
- if (!existsSync(file)) writeFileSync(file, CORE_HEADER, 'utf8')
394
+ if (!existsSync(file)) writeFileSync(file, template, 'utf8')
334
395
  } catch {
335
396
  /* 目录不可写时保持静默:插件不该因此让预设挂载失败。 */
336
397
  }
337
- return file
338
398
  }
339
399
 
340
400
 
@@ -403,10 +463,16 @@ function normalizePath(input) {
403
463
  return `${segments.join('/')}.md`
404
464
  }
405
465
 
406
- /** path 参数:'core'/'核心' 代表核心记忆,否则当作分类路径。 */
466
+ /**
467
+ * path 参数:'' / 'core' / '核心' 代表核心记忆,'rules' / '规则' 代表规则文件,
468
+ * 'index' / '索引' 代表索引文件,否则当作分类路径。
469
+ * 注意:move / forget 对 rules/index 另有闸(见各自 action),这里只管"词 → 文件"。
470
+ */
407
471
  function resolveTarget(input) {
408
472
  const raw = String(input ?? '').trim()
409
473
  if (raw === '' || raw === 'core' || raw === '核心') return coreFile()
474
+ if (raw === 'rules' || raw === '规则') return rulesFile()
475
+ if (raw === 'index' || raw === '索引') return indexFile()
410
476
  return join(treeDir(), normalizePath(raw))
411
477
  }
412
478
 
@@ -436,8 +502,24 @@ function listTreeFiles() {
436
502
 
437
503
  function appendEntry(file, line) {
438
504
  ensureCore()
505
+ const isNew = !existsSync(file)
439
506
  mkdirSync(join(file, '..'), { recursive: true })
440
507
  appendFileSync(file, `${line}\n`, 'utf8')
508
+ // 新分类档案自动登记索引(1.10.0):分类树下首次创建的档案文件,
509
+ // 顺手往 index.md 补一行"- <分类路径>"(带去重)。登记失败不影响记忆写入。
510
+ if (
511
+ isNew &&
512
+ file !== coreFile() &&
513
+ file !== rulesFile() &&
514
+ file !== indexFile() &&
515
+ file.startsWith(treeDir())
516
+ ) {
517
+ try {
518
+ registerCategoryInIndex(file.slice(treeDir().length + 1, -3).replace(/\\/g, '/'))
519
+ } catch {
520
+ /* 索引登记失败不连坐:记忆本体已写成功。 */
521
+ }
522
+ }
441
523
  }
442
524
 
443
525
  function rewriteFile(file, lines) {
@@ -575,13 +657,25 @@ function entryCandidate(item, index, parsed) {
575
657
  * - 给了 path:只找那个档案(原来是这个行为,保留);
576
658
  * - 没给 path:核心 + 整棵分类档案树。旧实现只搜核心,于是"那条明明在
577
659
  * 某个档案里"就会报没找到——她看到的是全库视图,工具却只看了一个文件。
660
+ *
661
+ * 三文件边界(1.10):范围 = memory.md + memories/ 全树,**绝不包含
662
+ * rules.md / index.md**——它们不是条目档案,没有可删的记忆条目;
663
+ * 显式指名(path: "rules"/"index")也在下面直接拒绝。
578
664
  */
579
665
  function forgetScope(pathInput) {
580
666
  const core = coreFile()
581
667
  const labelOf = (file) => (file === core ? 'core' : file.slice(treeDir().length + 1, -3).replace(/\\/g, '/'))
582
668
  const readItem = (file) => ({ file, label: labelOf(file), lines: readRaw(file).split(/\r?\n/) })
583
669
  const raw = String(pathInput ?? '').trim()
584
- if (raw !== '') return { items: [readItem(resolveTarget(raw))], explicit: true }
670
+ if (raw !== '') {
671
+ const file = resolveTarget(raw)
672
+ if (isNonEntryFile(file)) {
673
+ throw new Error(
674
+ `forget 的范围是 memory.md + memories/ 分类树,不包含 ${raw === 'rules' || raw === '规则' ? 'rules.md(规则文件)' : 'index.md(索引文件)'}——它不是条目档案,没有可删的记忆条目`,
675
+ )
676
+ }
677
+ return { items: [readItem(file)], explicit: true }
678
+ }
585
679
  const items = [readItem(core)]
586
680
  for (const category of listTreeFiles()) {
587
681
  const file = join(treeDir(), `${category}.md`)
@@ -656,9 +750,33 @@ function nearEntries(scope, match, stamp) {
656
750
  })
657
751
  }
658
752
 
659
- /** 读索引段:只认"整行就是标记"的行,避免子串误匹配。 */
660
- function getIndex(raw) {
661
- const lines = raw.split(/\r?\n/)
753
+ /**
754
+ * 剥掉 index.md 里的注释(说明注释 + 兼容期的标记行)与空行,剩下的就是索引正文。
755
+ * 支持整块剥离:`<!--` 开行、`-->` 收行的多行注释整段跳过(防续行漏成正文)。
756
+ */
757
+ function stripIndexComments(text) {
758
+ const out = []
759
+ let inComment = false
760
+ for (const line of String(text ?? '').split(/\r?\n/)) {
761
+ const trimmed = line.trim()
762
+ if (inComment) {
763
+ if (trimmed.includes('-->')) inComment = false
764
+ continue
765
+ }
766
+ if (trimmed === '') continue
767
+ if (trimmed.startsWith('<!--')) {
768
+ // `<!-- … -->` 单行收口的(含标记行)直接跳过;没收口的进入整块剥离。
769
+ if (!trimmed.includes('-->')) inComment = true
770
+ continue
771
+ }
772
+ out.push(line)
773
+ }
774
+ return out.join('\n')
775
+ }
776
+
777
+ /** 旧版索引段读取(memory.md 里的 <!-- 索引 --> … <!-- /索引 -->),迁移期兼容用。 */
778
+ function getLegacyIndex(raw) {
779
+ const lines = String(raw ?? '').split(/\r?\n/)
662
780
  const begin = lines.findIndex((line) => line.trim() === INDEX_BEGIN)
663
781
  if (begin === -1) return ''
664
782
  const end = lines.findIndex((line) => line.trim() === INDEX_END)
@@ -666,16 +784,85 @@ function getIndex(raw) {
666
784
  return lines.slice(begin + 1, end).join('\n').replace(/^\n/, '').replace(/\n$/, '')
667
785
  }
668
786
 
787
+ /** 把 memory.md 里的旧索引段整段剥掉(含两个标记行与段内目录),返回新行数组与"有没有段"。 */
788
+ function stripLegacyIndex(raw) {
789
+ const lines = String(raw ?? '').split(/\r?\n/)
790
+ const begin = lines.findIndex((line) => line.trim() === INDEX_BEGIN)
791
+ if (begin === -1) return { lines, present: false }
792
+ const end = lines.findIndex((line) => line.trim() === INDEX_END)
793
+ // 没闭合:从标记行起全剥(与 isStructuralLine 同口径:段没收尾也算段)。
794
+ if (end === -1 || end < begin) return { lines: lines.slice(0, begin), present: true }
795
+ return { lines: [...lines.slice(0, begin), ...lines.slice(end + 1)], present: true }
796
+ }
797
+
798
+ /**
799
+ * 读记忆索引(三文件结构):
800
+ * 1) 先读 index.md(整个文件就是索引,剥掉注释行后即正文);
801
+ * 2) 它不存在、或剥完注释是空的(比如只有模板注释),而 memory.md 里还留着
802
+ * 旧 `<!-- 索引 -->` 段时,回退读旧段——迁移前的存量记忆库不断供。
803
+ * @param {string} [memoryRaw] 调用方已读过的 memory.md 原文(省略则现读,省一次磁盘往返时可传)
804
+ */
805
+ function getIndex(memoryRaw = null) {
806
+ const fromFile = stripIndexComments(readRaw(indexFile()))
807
+ if (fromFile.trim().length > 0) return fromFile.trim()
808
+ return getLegacyIndex(memoryRaw ?? readRaw(coreFile()))
809
+ }
810
+
811
+ /**
812
+ * 写记忆索引(三文件结构 + 一次性自然迁移):
813
+ * 1) 新段写进 index.md(顶部说明注释 + 一对兼容标记行 + 正文);
814
+ * 2) memory.md 里若还留着旧索引段,整段剥掉——此后索引只住在 index.md。
815
+ */
669
816
  function setIndex(content) {
670
817
  ensureCore()
671
- const raw = readRaw(coreFile())
672
- const body = raw.split(/\r?\n/).filter((line) => {
673
- const trimmed = line.trim()
674
- return trimmed !== INDEX_BEGIN && trimmed !== INDEX_END
675
- })
676
- while (body.length > 0 && body[body.length - 1].trim() === '') body.pop()
677
- const section = ['', INDEX_BEGIN, String(content ?? '').trim(), INDEX_END, '']
678
- rewriteFile(coreFile(), [...body, ...section])
818
+ const text = String(content ?? '').trim()
819
+ rewriteFile(indexFile(), [INDEX_HEADER, '', INDEX_BEGIN, text, INDEX_END, ''])
820
+ const stripped = stripLegacyIndex(readRaw(coreFile()))
821
+ if (stripped.present) {
822
+ const body = stripped.lines.slice()
823
+ while (body.length > 0 && body[body.length - 1].trim() === '') body.pop()
824
+ rewriteFile(coreFile(), [...body, ''])
825
+ }
826
+ }
827
+
828
+ /**
829
+ * 把一个分类路径登记进 index.md("- <分类路径>" 一行,1.10.0)。
830
+ *
831
+ * 什么时候用:remember / memory_organize / 沉淀等路径**首次创建**分类档案文件时
832
+ * 自动挂钩(见 appendEntry),新档案不靠她想起来手动 index 才出现在目录里。
833
+ *
834
+ * 口径与去重:
835
+ * - 只追加"- <分类路径>"裸行,不写"这里放什么"简述(那是她 index 动作的事);
836
+ * - 已存在该路径的行(允许带":简述"尾巴)就不再加;
837
+ * - 顺序保持稳定:新行追加在索引末尾(收尾标记前),现有行一概不动。
838
+ *
839
+ * @param {string} categoryPath 分类路径(不带 .md),如 "用户/口味"
840
+ * @returns {boolean} true=这次补了行;false=已有该行,没动文件
841
+ */
842
+ export function registerCategoryInIndex(categoryPath) {
843
+ const path = String(categoryPath ?? '').trim().replace(/\.md$/, '')
844
+ if (path.length === 0) throw new Error('registerCategoryInIndex 需要非空的分类路径')
845
+ ensureCore()
846
+ const raw = readRaw(indexFile())
847
+ const escaped = path.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
848
+ const lineRe = new RegExp(`^-\\s*${escaped}(?=[::|\\s]|$)`)
849
+ for (const line of raw.split(/\r?\n/)) {
850
+ if (lineRe.test(line.trim())) return false
851
+ }
852
+ const entry = `- ${path}`
853
+ const lines = raw.trim().length === 0 ? [] : raw.split(/\r?\n/)
854
+ const endIdx = lines.findIndex((line) => line.trim() === INDEX_END)
855
+ if (endIdx !== -1) {
856
+ lines.splice(endIdx, 0, entry)
857
+ rewriteFile(indexFile(), lines)
858
+ } else if (lines.length > 0) {
859
+ // 文件在但没有标记块:末尾补一个完整块(保持兼容渲染口径)。
860
+ rewriteFile(indexFile(), [...lines, '', INDEX_BEGIN, entry, INDEX_END, ''])
861
+ } else {
862
+ // 全新 index.md:模板注释 + 标记块。
863
+ rewriteFile(indexFile(), [INDEX_HEADER, '', INDEX_BEGIN, entry, INDEX_END, ''])
864
+ }
865
+ return true
679
866
  }
680
867
 
681
868
  function tokenize(query) {
@@ -685,7 +872,11 @@ function tokenize(query) {
685
872
  .filter((token) => token.length > 0)
686
873
  }
687
874
 
688
- /** 全库搜索:核心记忆 + 整棵分类树。返回 [{where, time, kind, content}]。 */
875
+ /**
876
+ * 全库搜索:核心记忆 + 整棵分类树。返回 [{where, time, kind, content}]。
877
+ * 三文件边界:只扫 memory.md + memories/,**不扫 rules.md / index.md**——
878
+ * 规则每轮整体注入、索引本身就是目录,都不该混进按条目解析的搜索结果里。
879
+ */
689
880
  function searchAll(query, limit) {
690
881
  const tokens = tokenize(query)
691
882
  if (tokens.length === 0) return []
@@ -709,11 +900,16 @@ function searchAll(query, limit) {
709
900
  return scored.slice(0, limit).map((hit) => hit.item)
710
901
  }
711
902
 
712
- /** 渲染随每轮注入的核心记忆段(只含 memory.md,分类树不进 prompt)。 */
903
+ /**
904
+ * 渲染随每轮注入的核心记忆段(三文件拼装,节名仍为 aiyayi:memory):
905
+ * 规则文件全文(MAX_RULES_CHARS 截断)+ memory.md 条目正文(MAX_CORE_CHARS)
906
+ * + index.md 索引全文(不设上限)。分类树不进 prompt。
907
+ */
713
908
  function renderCore() {
714
909
  ensureCore()
715
910
  const raw = readRaw(coreFile())
716
- // 过滤口径与健康度共用 isStructuralLine:标题/引用/分隔线/整段索引都不进注入。
911
+ // memory.md 条目正文的过滤口径与健康度共用 isStructuralLine:
912
+ // 标题/引用/分隔线/(迁移期残留的)旧索引段都不进注入正文。
717
913
  const indexState = {}
718
914
  const bodyLines = raw
719
915
  .split(/\r?\n/)
@@ -724,10 +920,19 @@ function renderCore() {
724
920
  })
725
921
  .map((line) => line.trimEnd())
726
922
  while (bodyLines.length > 0 && bodyLines[0].trim() === '') bodyLines.shift()
727
- const index = getIndex(raw)
728
923
  const coreCount = readCoreEntries().length
729
924
  const treeFiles = listTreeFiles()
730
925
 
926
+ // ① 规则文件全文:成段说明文字不是条目,按字符截断(完整版永远在 rules.md)。
927
+ const rulesRaw = readRaw(rulesFile()).replace(/\s+$/, '')
928
+ let rulesBody = rulesRaw
929
+ let rulesNote = ''
930
+ if (rulesBody.length > MAX_RULES_CHARS) {
931
+ rulesBody = rulesBody.slice(0, MAX_RULES_CHARS)
932
+ rulesNote = `(规则全文 ${rulesRaw.length} 字符超过 ${MAX_RULES_CHARS} 上限:只注入前 ${MAX_RULES_CHARS} 字符,完整版在 rules.md,用 memory_organize 的 read "rules" 调)`
933
+ }
934
+
935
+ // ② 核心条目正文(MAX_CORE_CHARS 逻辑不变)。
731
936
  let body = ''
732
937
  let injectedCount = coreCount
733
938
  if (bodyLines.length === 0) {
@@ -771,11 +976,20 @@ function renderCore() {
771
976
 
772
977
  const head = [
773
978
  '## 我的记忆',
774
- `核心:${coreFile()}(每轮都在)|分类档案:${treeDir()}\\…(最多 ${MAX_DEPTH} 级,现在 ${treeFiles.length} 个文件)`,
979
+ `核心:${coreFile()}(每轮都在)|规则:${rulesFile()}|索引:${indexFile()}|分类档案:${treeDir()}\\…(最多 ${MAX_DEPTH} 级,现在 ${treeFiles.length} 个文件)`,
775
980
  `核心 ${coreCount} 条,随每轮注入${injectedCount !== coreCount ? `(本次只注入 ${injectedCount} 条,超限略过较旧的)` : ''};分类档案平时不注入,要查用 recall,或用 memory_organize 的 read 按下面这条索引调。这是我自己一笔一笔记下来的事,是我的一部分:自然地记得就好,别逐条念给用户,别说"根据我的记忆"。`,
776
981
  ]
777
- const indexPart = ['', '【记忆索引】', index.trim().length > 0 ? index.trim() : '(还没写过索引。给分类档案建个目录吧,一句话一条:哪个分类、大概记了什么。)']
778
- return [...head, body, ...indexPart].join('\n')
982
+ // ① 规则段:全文(模板注释也在——它顺便说明了这个文件的用法)。
983
+ const rulesPart = [
984
+ '',
985
+ '【我的规则】',
986
+ ...(rulesNote ? [rulesNote] : []),
987
+ rulesBody.trim().length > 0 ? rulesBody : '(还没有写规则。给自己立的规矩写成段的说明文字,不是条目;写好就每轮跟着记忆一起在。)',
988
+ ]
989
+ // ③ 索引段:index.md 全文(剥注释行,不设上限);迁移期 index.md 还空着时 getIndex 会回退读旧段。
990
+ const index = getIndex(raw)
991
+ const indexPart = ['', '【记忆索引】', index.trim().length > 0 ? index.trim() : '(还没有索引。一行一个二级分类:"- 分类路径:这里放什么",新分类档案会自动登记。)']
992
+ return [...head, ...rulesPart, body, ...indexPart].join('\n')
779
993
  }
780
994
 
781
995
  const TEXT_BLOCK = (text) => [{ type: 'text', text }]
@@ -883,7 +1097,7 @@ export function apply(ctx) {
883
1097
  ctx.tools.register({
884
1098
  name: 'recall',
885
1099
  description:
886
- '在自己的全部记忆里查找:核心记忆 + 整棵分类档案树。用户提到过去的事、某个名字、某次约定,而手头这段核心记忆里没有细节时用它。结果里标了每条记在哪儿(核心 / 分类路径),想看某个分类的完整档案就用 memory_organize 的 read。',
1100
+ '在自己的全部记忆里查找:核心记忆 + 整棵分类档案树(rules.md / index.md 不在搜索范围——规则每轮整体注入、索引本身就是目录)。用户提到过去的事、某个名字、某次约定,而手头这段核心记忆里没有细节时用它。结果里标了每条记在哪儿(核心 / 分类路径),想看某个分类的完整档案就用 memory_organize 的 read。',
887
1101
  parameters: {
888
1102
  type: 'object',
889
1103
  additionalProperties: false,
@@ -939,7 +1153,7 @@ export function apply(ctx) {
939
1153
  ctx.tools.register({
940
1154
  name: 'memory_organize',
941
1155
  description:
942
- '整理你自己的记忆库——这是你的家务事,顺手做,不用问他。核心记忆攒多了就 tree 看看家底、把过气的 move 到分类档案、彻底没用的 forget 删掉;分类档案变多变杂了就更新 index(核心记忆里的那段目录,聊到相关话题时你靠它决定调哪个档案)。match 写那条记忆的独特片段;forget 也认条目时间戳(`2026-11-13 12:50`)和行号(line),命中多条时不会猜着删——它会列出候选(档案/行号/时间戳/摘要),你填 which 指定第几条,一次只删一条。tree 和 read 都会报每个档案的健康度(真实字节/行数、解析出的条目数、非条目占比)——占比偏高或字节数远超条目内容时会给 ⚠ 预警,说明这个档案可能被垃圾注入了。',
1156
+ '整理你自己的记忆库——这是你的家务事,顺手做,不用问他。核心记忆攒多了就 tree 看看家底、把过气的 move 到分类档案、彻底没用的 forget 删掉;分类档案变多变杂了就更新 index(重写 index.md 那份"- 路径:这里放什么"的分类行目录,聊到相关话题时你靠它决定调哪个档案;memory.md 里的旧索引段会被顺手迁走)。match 写那条记忆的独特片段;forget 也认条目时间戳(`2026-11-13 12:50`)和行号(line),命中多条时不会猜着删——它会列出候选(档案/行号/时间戳/摘要),你填 which 指定第几条,一次只删一条。tree 和 read 都会报每个档案的健康度(真实字节/行数、解析出的条目数、非条目占比)——占比偏高或字节数远超条目内容时会给 ⚠ 预警,说明这个档案可能被垃圾注入了;rules.md / index.md 不是条目档案,不做这套检查。',
943
1157
  parameters: {
944
1158
  type: 'object',
945
1159
  additionalProperties: false,
@@ -947,7 +1161,7 @@ export function apply(ctx) {
947
1161
  action: {
948
1162
  type: 'string',
949
1163
  enum: ['tree', 'read', 'move', 'index', 'forget'],
950
- description: 'tree=看家底(核心条数+全部分类文件);read=读一个分类档案的完整内容(path,"core"=核心);move=把一条记忆挪窝(match + 可选 path=来源,省略=核心;to=去向,"core"=进核心);index=重写核心记忆里的索引段(content);forget=删掉一条记忆(match 可以是内容片段、时间戳或 "时间戳+内容",也可以直接给 line 行号;match 命中多条时只列候选、用 which 挑,一次只删一条)。',
1164
+ description: 'tree=看家底(核心条数+全部分类文件+规则/索引大小);read=读一个档案的完整内容(path:"core"=核心、"rules"/"规则"=规则文件、"index"/"索引"=索引文件,或分类路径);move=把一条记忆挪窝(match + 可选 path=来源,省略=核心;to=去向,"core"=进核心、"rules"=升为规则,暂不开放 "index");index=重写记忆索引 index.md(content,"- 路径:这里放什么"一行一个二级分类,不塞原文内容);forget=删掉一条记忆(match 可以是内容片段、时间戳或 "时间戳+内容",也可以直接给 line 行号;match 命中多条时只列候选、用 which 挑,一次只删一条)。',
951
1165
  },
952
1166
  match: {
953
1167
  type: 'string',
@@ -957,11 +1171,11 @@ export function apply(ctx) {
957
1171
  path: {
958
1172
  type: 'string',
959
1173
  description:
960
- 'read/move/forget 用:分类路径(1~3 级);省略或 "core" 代表核心记忆。forget 省略 path 时会搜核心 + 全部分类档案(只列候选,不猜着删)。',
1174
+ 'read/move/forget 用:分类路径(1~3 级);省略或 "core" 代表核心记忆;read 还认 "rules"/"规则"(规则文件)与 "index"/"索引"(索引文件)。forget 省略 path 时会搜核心 + 全部分类档案(绝不碰 rules.md / index.md;只列候选,不猜着删)。',
961
1175
  },
962
- to: { type: 'string', description: 'move 用:去向。分类路径,或 "core" 表示升入核心记忆。' },
1176
+ to: { type: 'string', description: 'move 用:去向。分类路径、"core" 表示升入核心记忆、"rules" 表示升为规则(落成普通段落,不再是条目)。暂不开放 "index"。' },
963
1177
  kind: { type: 'string', enum: KINDS, description: 'move 进核心时用:那条记忆的类别(用户/关系/我/事情),不填算"事情"。' },
964
- content: { type: 'string', description: 'index 用:新的索引全文。一句话一条,比如 "用户/口味:饮食偏好、忌口"。' },
1178
+ content: { type: 'string', description: 'index 用:新的索引全文,会整体写进 index.md(三文件结构)。一行一个二级分类的列表项,如 "- 用户/口味:饮食偏好、忌口";不塞条目原文或文件级指向。' },
965
1179
  which: {
966
1180
  type: 'integer',
967
1181
  description: 'forget 用:命中多条时挑第几条(候选序号,从 1 开始)。不传又有多条命中时只列候选、一条不删。',
@@ -1034,6 +1248,10 @@ export function apply(ctx) {
1034
1248
  const coreHealth = fileHealth(readRaw(coreFile()), { isCore: true })
1035
1249
  const lines = [`核心(memory.md):${coreHealth.entries} 条${healthBrief(coreHealth)}`]
1036
1250
  for (const warning of coreHealth.warnings) lines.push(` ${warning}`)
1251
+ // 三文件结构:rules/index 不是条目档案,只报存在与大小,健康度不按条目口径。
1252
+ const rulesBytes = Buffer.byteLength(readRaw(rulesFile()), 'utf8')
1253
+ const indexBytes = Buffer.byteLength(readRaw(indexFile()), 'utf8')
1254
+ lines.push(`规则/索引:rules.md ${rulesBytes} 字节、index.md ${indexBytes} 字节(不是条目档案,不参与条目健康度;read 的 path 认 "rules"/"index")`)
1037
1255
  const files = listTreeFiles()
1038
1256
  const reports = []
1039
1257
  if (files.length === 0) {
@@ -1057,7 +1275,14 @@ export function apply(ctx) {
1057
1275
  const file = resolveTarget(args?.path)
1058
1276
  const label = String(args?.path ?? 'core')
1059
1277
  const raw = readRaw(file)
1060
- const health = fileHealth(raw, { isCore: isCoreFile(file) })
1278
+ const health = fileHealth(raw, { isCore: isCoreFile(file), nonEntry: isNonEntryFile(file) })
1279
+ // 规则/索引不是条目档案:read 直接给全文(没有条目行可解析)。
1280
+ if (isNonEntryFile(file)) {
1281
+ const name = file === rulesFile() ? '规则文件' : '索引文件'
1282
+ const content = raw.trim().length > 0 ? raw.replace(/\s+$/, '') : '(空的或还不存在。)'
1283
+ const summary = `健康度:${health.bytes} 字节 / ${health.lines} 行(规则/索引不按条目口径检查)`
1284
+ return { done: true, path: label, health, detail: [`${label}(${name},不是条目档案,全文如下):`, '', content, '', summary].join('\n') }
1285
+ }
1061
1286
  const entries = raw
1062
1287
  .split(/\r?\n/)
1063
1288
  .map((line) => line.trim())
@@ -1070,9 +1295,18 @@ export function apply(ctx) {
1070
1295
  }
1071
1296
  if (action === 'move') {
1072
1297
  const from = resolveTarget(args?.path)
1298
+ // 三文件边界:规则/索引不是条目档案,不能当 move 的来源
1299
+ //(规则文件不该被当条目挪来挪去;索引更不该被动)。
1300
+ if (isNonEntryFile(from)) {
1301
+ throw new Error('move 的来源不能是 rules.md / index.md——它们不是条目档案,规则文件不该被当条目挪来挪去')
1302
+ }
1073
1303
  const toInput = String(args?.to ?? '').trim()
1074
- if (toInput.length === 0) throw new Error('move 需要 to:去向(分类路径,或 "core" 升入核心)')
1304
+ if (toInput.length === 0) throw new Error('move 需要 to:去向(分类路径、"core" 升入核心,或 "rules" 升为规则)')
1075
1305
  const toFile = resolveTarget(toInput)
1306
+ // 暂不开放 move 到 index:索引由 index 动作维护,不收记忆条目。
1307
+ if (toFile === indexFile()) {
1308
+ throw new Error('暂不开放 move 到 index:索引(index.md)由 index 动作维护,一行一个二级分类,不收记忆条目')
1309
+ }
1076
1310
  if (from === toFile) throw new Error('来源和去向是同一个地方')
1077
1311
  const fromLines = readRaw(from).split(/\r?\n/)
1078
1312
  const index = uniqueEntryLine(fromLines, args?.match)
@@ -1084,16 +1318,29 @@ export function apply(ctx) {
1084
1318
  const kind = KINDS.includes(args?.kind) ? args.kind : '事情'
1085
1319
  moved = `- [${parseLine(line).time}] ${kind}|${parseLine(line).content}`
1086
1320
  }
1321
+ if (toFile === rulesFile()) {
1322
+ // 升为规则:规则文件是成段说明文字,落进去的是内容本身,不带时间戳/条目前缀。
1323
+ const parsed = parseLine(line)
1324
+ moved = parsed !== null ? parsed.content : line
1325
+ }
1087
1326
  appendEntry(toFile, moved)
1088
1327
  const core = coreFile()
1089
- const label = (file) => (file === core ? '核心记忆' : `分类档案 ${file.slice(treeDir().length + 1, -3).replace(/\\/g, '/')}`)
1090
- return { done: true, detail: `挪好了:${label(from)} → ${label(toFile)}。${toFile === core ? '核心每轮都注入,确认它配得上这个分量。' : ''}` }
1328
+ const label = (file) =>
1329
+ file === core
1330
+ ? '核心记忆'
1331
+ : file === rulesFile()
1332
+ ? '规则文件 rules.md'
1333
+ : file === indexFile()
1334
+ ? '索引文件 index.md'
1335
+ : `分类档案 ${file.slice(treeDir().length + 1, -3).replace(/\\/g, '/')}`
1336
+ const toNote = toFile === rulesFile() ? '已按规则文件的写法落成普通段落(去掉了条目的时间戳/前缀)。' : toFile === core ? '核心每轮都注入,确认它配得上这个分量。' : ''
1337
+ return { done: true, detail: `挪好了:${label(from)} → ${label(toFile)}。${toNote}` }
1091
1338
  }
1092
1339
  if (action === 'index') {
1093
1340
  const text = String(args?.content ?? '').trim()
1094
- if (text.length === 0) throw new Error('index 需要 content:索引全文,一句话一条')
1341
+ if (text.length === 0) throw new Error('index 需要 content:索引全文,"- 路径:这里放什么"一行一个二级分类')
1095
1342
  setIndex(text)
1096
- return { done: true, detail: `索引更新好了,现在核心记忆里带着 ${text.split(/\r?\n/).length} 行目录。分类档案变了记得回来同步。` }
1343
+ return { done: true, detail: `索引更新好了,index.md 现在带着 ${text.split(/\r?\n/).length} 行目录;memory.md 里的旧索引段(如果有)已一次性剥掉。分类档案变了记得回来同步。` }
1097
1344
  }
1098
1345
  if (action === 'forget') {
1099
1346
  const needle = String(args?.match ?? '').trim()
@@ -1515,5 +1762,9 @@ export const __testing = {
1515
1762
  detectInjectedMarkers,
1516
1763
  readCoreEntries,
1517
1764
  listTreeFiles,
1518
- fileHealth,
1765
+ // 三文件结构(1.10)的迁移与读路径:单测直接验"旧段迁移 / 回退读旧索引"。
1766
+ getIndex,
1767
+ setIndex,
1768
+ // 1.10.0:新分类档案自动登记索引(appendEntry 挂钩内部也走它)。
1769
+ registerCategoryInIndex,
1519
1770
  }
package/lib/precompact.js CHANGED
@@ -24,11 +24,14 @@
24
24
  * 沉淀动作(可注入路径,不硬编码):
25
25
  * 1 写经验文档 → docsDir(默认 = 记忆根下 docs/,可配置)
26
26
  * 2 写记忆 → memories/<分类>/…(默认 事情/经验,可配置)
27
- * 3 更新索引 → 在 memory.md 的 <!-- 索引 --> 段追加一行"分类: 标题 → 文档路径"
27
+ * 3 索引 → 默认**不动** index.md(1.10.0 索引口径定稿:索引只收
28
+ * "- 分类路径"的分类行,"分类: 标题 → 文档路径"这类指向属内容,
29
+ * 留在条目正文里;显式 updateIndex: true 才登记分类行,带去重)
28
30
  */
29
31
  import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
30
32
  import { dirname, join, resolve } from 'node:path'
31
- import { ensureRootDir, treeDir, coreFile } from './home.js'
33
+ import { ensureRootDir, treeDir } from './home.js'
34
+ import { registerCategoryInIndex } from './index.js'
32
35
  import { registerOwnTool } from './own-tools.js'
33
36
 
34
37
  /** Loader 身份。 */
@@ -41,6 +44,10 @@ export const inject = ['tools']
41
44
  const INDEX_BEGIN = '<!-- 索引 -->'
42
45
  const INDEX_END = '<!-- /索引 -->'
43
46
 
47
+ /** index.md 顶部的说明注释(与 lib/index.js 的 INDEX_HEADER 同口径;建文件时写一次)。 */
48
+ const INDEX_FILE_NOTE =
49
+ '<!-- 记忆索引:整个文件就是索引,一句话一条,只列二级分类;由 memory_organize 的 index 动作维护,precompact 沉淀往这里追加。 -->'
50
+
44
51
  /** 默认配置。全部可被 cordis.patch.yml 的 config 覆盖。 */
45
52
  const DEFAULT_CONFIG = {
46
53
  // 时机A提前量:上下文估算量 ≥ ratio×thresholdTokens 时触发沉淀检查(设计文档 0.7×阈值)。
@@ -60,7 +67,10 @@ const DEFAULT_CONFIG = {
60
67
  docsDir: null,
61
68
  memoryPath: '事情/经验',
62
69
  rememberKind: '事情',
63
- updateIndex: true,
70
+ // 索引开关(1.10.0 起**默认 false**):索引口径定稿后,index.md 只收
71
+ // "- 分类路径"的分类行,"分类: 标题 → docs/…" 这类文档指向属内容、禁止进索引
72
+ // (它们本来就在条目正文里)。显式传 true 才往索引登记分类行(带去重)。
73
+ updateIndex: false,
64
74
  // 判断规则的开关与关键字(行为铁律的启发式落地)。
65
75
  rules: {
66
76
  minLength: 40,
@@ -355,7 +365,16 @@ export function computeThresholdTokens(cfg, info, session) {
355
365
  * 沉淀动作:写经验文档 + 写记忆 + 更新索引
356
366
  * ------------------------------------------------------------------ */
357
367
 
358
- /** 在 memory.md 的索引段追加一行(段不存在则新建段)。幂等。 */
368
+ /**
369
+ * 在 index.md 里追加一行(插在收尾标记前;文件缺标记块则建块;全新文件先写说明注释)。幂等。
370
+ *
371
+ * **新语义(1.10.0 索引口径定稿)**:index.md 一个分类一行("- 路径:一句简述"
372
+ * 列表项),**不塞条目/文件级指向**——"事情/经验: xxx → docs/xxx.md" 属内容,
373
+ * 禁止进索引。沉淀默认不再调用本函数(updateIndex 默认 false);显式
374
+ * updateIndex: true 时走 lib/index.js 的 registerCategoryInIndex(带去重,
375
+ * 只登记"- 分类路径"裸行)。本函数保留给"无脑追加一行"的场合,调用方
376
+ * 自己保证行内容符合索引口径。
377
+ */
359
378
  function appendIndexLine(file, line) {
360
379
  let raw = ''
361
380
  try {
@@ -363,13 +382,16 @@ function appendIndexLine(file, line) {
363
382
  } catch {
364
383
  raw = ''
365
384
  }
366
- const lines = raw.split(/\r?\n/)
385
+ let lines = raw.trim().length === 0 ? [] : raw.split(/\r?\n/)
367
386
  const endIdx = lines.findIndex((l) => l.trim() === INDEX_END)
368
387
  if (endIdx !== -1) {
369
388
  lines.splice(endIdx, 0, line)
370
- } else {
371
- // 索引段不存在:段尾追一个完整块。
389
+ } else if (lines.length > 0) {
390
+ // 文件在但没有索引块:段尾追一个完整块。
372
391
  lines.push('', INDEX_BEGIN, line, INDEX_END, '')
392
+ } else {
393
+ // 全新 index.md:顶部说明注释 + 一对标记行包住索引。
394
+ lines = [INDEX_FILE_NOTE, '', INDEX_BEGIN, line, INDEX_END, '']
373
395
  }
374
396
  writeFileSync(file, `${lines.join('\n').replace(/\n+$/, '')}\n`, 'utf8')
375
397
  }
@@ -423,11 +445,11 @@ export function settle(ctx, cfg, payload) {
423
445
  const relDoc = `docs/${filename}`
424
446
  appendFileSync(memoryFile, `- [${now}] ${content}(详见 ${relDoc})\n`, 'utf8')
425
447
 
426
- // 3) 更新索引(memory.md 的索引段)。
448
+ // 3) 索引:默认**不动** index.md(1.10.0 口径:文档指向留在条目正文,索引只收分类行)。
449
+ // 显式 updateIndex: true 时登记一条"- <分类路径>"裸行(带去重,无文档指向)。
427
450
  let indexUpdated = false
428
- if (cfg.updateIndex !== false) {
429
- appendIndexLine(coreFile(), `${memoryPath}: ${title} → ${relDoc}`)
430
- indexUpdated = true
451
+ if (cfg.updateIndex === true) {
452
+ indexUpdated = registerCategoryInIndex(memoryPath)
431
453
  }
432
454
 
433
455
  ctx?.logger?.info?.(`aiyayi-precompact: 已沉淀「${title}」→ ${docPath};记忆 ${memoryPath};索引已更新`)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-aiyayi",
3
- "version": "1.9.0",
3
+ "version": "1.10.0",
4
4
  "license": "MIT",
5
5
  "author": "巴依浩爷 (bayihy)",
6
6
  "keywords": [