dsh-zdiary-kit 3.1.0 → 3.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -17
- package/dist/cli.js +26 -26
- package/dist/config/store.js +2 -2
- package/dist/features/readonly/feature.js +30 -13
- package/dist/features/settings/client.js +5 -5
- package/dist/features/settings/feature.js +19 -19
- package/dist/features/zk-tools/feature.js +40 -19
- package/dist/lib/agents-template.js +11 -1
- package/dist/lib/lint.js +36 -73
- package/dist/lib/memory-format.js +23 -0
- package/dist/lib/memory.js +147 -73
- package/dist/lib/meta.js +4 -4
- package/dist/lib/notebook.js +10 -10
- package/dist/lib/persona-template.js +14 -14
- package/dist/lib/similar.js +103 -0
- package/dist/lib/zk.js +10 -6
- package/docs/features/memory.md +48 -25
- package/docs/features/provisioning.md +9 -9
- package/docs/features/readonly.md +10 -6
- package/docs/features/settings.md +11 -11
- package/docs/features/zk-tools.md +18 -10
- package/package.json +1 -1
package/dist/lib/memory.js
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
* 记忆注入(M1):读 vault 根目录的 AGENTS.md / USER.md / MEMORY.md,
|
|
3
3
|
* 按 `memoryBudgetWords` 截断,渲染成一段可注入系统提示的文本。
|
|
4
4
|
* 另读 DREAMS.md 的「上次做梦」一行(不进正文、不计预算),给周节奏一句机械提醒。
|
|
5
|
-
*
|
|
6
|
-
*
|
|
5
|
+
* 人格层(PERSONA.md)单独一段注入、永远在记忆段之前、不参与截断,
|
|
6
|
+
* 超上限只告警;缺文件 = 未启用,0.9 的老库逐字节不变。
|
|
7
7
|
*
|
|
8
8
|
* 硬约定:
|
|
9
9
|
* · 预算按**总载荷**算,不是只卡 MEMORY.md;
|
|
@@ -25,8 +25,9 @@ import fs from 'node:fs';
|
|
|
25
25
|
import path from 'node:path';
|
|
26
26
|
import { DREAM_INTERVAL_DAYS, daysSinceDream, lastDreamDate } from './dream.js';
|
|
27
27
|
import { fileStamp } from './file-stamp.js';
|
|
28
|
-
import { entryDate,
|
|
29
|
-
import {
|
|
28
|
+
import { entryDate, memoryFormatDebt, stripRetiredEntries } from './memory-format.js';
|
|
29
|
+
import { templateVersionOf } from './agents-template.js';
|
|
30
|
+
import { PERSONA_META_FILES, MEMORY_META_FILES } from './meta.js';
|
|
30
31
|
/** vault 根目录下、按优先级排列的三份 meta 文件(定义在 lib/meta.ts,这里只挂个本地名) */
|
|
31
32
|
export const META_FILES = MEMORY_META_FILES;
|
|
32
33
|
const CJK = /[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uac00-\ud7af]/g;
|
|
@@ -73,6 +74,46 @@ function finishSplit(head, sections, mode) {
|
|
|
73
74
|
mode,
|
|
74
75
|
};
|
|
75
76
|
}
|
|
77
|
+
/** 顶层列表项切分:缩进续行归上一条,围栏里的 `- ` 不算(与 1b / 单节降级共用) */
|
|
78
|
+
function splitItems(lines) {
|
|
79
|
+
const head = [];
|
|
80
|
+
const items = [];
|
|
81
|
+
let current = null;
|
|
82
|
+
let fenced = false;
|
|
83
|
+
for (const line of lines) {
|
|
84
|
+
if (FENCED.test(line))
|
|
85
|
+
fenced = !fenced;
|
|
86
|
+
if (!fenced && LIST_ITEM.test(line)) {
|
|
87
|
+
if (current)
|
|
88
|
+
items.push(current);
|
|
89
|
+
current = [line];
|
|
90
|
+
}
|
|
91
|
+
else if (current) {
|
|
92
|
+
current.push(line);
|
|
93
|
+
}
|
|
94
|
+
else {
|
|
95
|
+
head.push(line);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
if (current)
|
|
99
|
+
items.push(current);
|
|
100
|
+
return { head, items };
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* 单节再切一层(P0-2):小节标题并进 head(永不丢),正文按顶层列表项切;
|
|
104
|
+
* 不足两条就保持原样 —— 只有一条时没有可丢的粒度,交给「预算不足」照旧点名。
|
|
105
|
+
* 初次切分与「丢到只剩一节」都走这一个函数,保证两条路径同形。
|
|
106
|
+
*/
|
|
107
|
+
function degradeSingleSection(split) {
|
|
108
|
+
if (split.mode !== 'sections' || split.sections.length !== 1)
|
|
109
|
+
return null;
|
|
110
|
+
const [title, ...rest] = split.sections[0].split('\n');
|
|
111
|
+
const inner = splitItems(rest);
|
|
112
|
+
if (inner.items.length < 2)
|
|
113
|
+
return null;
|
|
114
|
+
const head = [split.head, title, inner.head.join('\n').trim()].filter(Boolean).join('\n\n');
|
|
115
|
+
return finishSplit([head], inner.items, 'items');
|
|
116
|
+
}
|
|
76
117
|
/**
|
|
77
118
|
* 三级降级切分(P0-1):`##` 小节 → 顶层列表项 → 空行段落。
|
|
78
119
|
* 只按 `##` 切时,「`# 记忆` + 要点列表」这种形状切不出任何小节,丢弃循环一次都不进,
|
|
@@ -97,33 +138,17 @@ function splitSections(body) {
|
|
|
97
138
|
else
|
|
98
139
|
head.push(line);
|
|
99
140
|
}
|
|
100
|
-
if (sections.length > 0)
|
|
101
|
-
|
|
141
|
+
if (sections.length > 0) {
|
|
142
|
+
const split = finishSplit(head, sections, 'sections');
|
|
143
|
+
// 只有一节时再降一层(P0-2):`## 结论` + 一串 `- 结论` 是最常见的形状,
|
|
144
|
+
// 不降级的话丢弃循环一次都不进,整篇绕过预算。
|
|
145
|
+
return split.sections.length === 1 ? degradeSingleSection(split) ?? split : split;
|
|
146
|
+
}
|
|
102
147
|
// 1b) 顶层列表项:`# 标题` + 若干 `- 结论` 是 MEMORY.md 最常见的形状。
|
|
103
148
|
// 至少两条才走这一级:只有一条时它更像散文里的一个符号,交给段落切分更不容易整篇卡死。
|
|
104
|
-
const
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
fenced = false;
|
|
108
|
-
for (const line of lines) {
|
|
109
|
-
if (FENCED.test(line))
|
|
110
|
-
fenced = !fenced;
|
|
111
|
-
if (!fenced && LIST_ITEM.test(line)) {
|
|
112
|
-
if (current)
|
|
113
|
-
items.push(current);
|
|
114
|
-
current = [line];
|
|
115
|
-
}
|
|
116
|
-
else if (current) {
|
|
117
|
-
current.push(line);
|
|
118
|
-
}
|
|
119
|
-
else {
|
|
120
|
-
itemHead.push(line);
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
if (current)
|
|
124
|
-
items.push(current);
|
|
125
|
-
if (items.length >= 2)
|
|
126
|
-
return finishSplit(itemHead, items, 'items');
|
|
149
|
+
const flat = splitItems(lines);
|
|
150
|
+
if (flat.items.length >= 2)
|
|
151
|
+
return finishSplit(flat.head, flat.items, 'items');
|
|
127
152
|
// 1c) 空行段落:整篇散文也能按段丢。首段作为 head(通常是标题 / 开场),永远保留。
|
|
128
153
|
const paragraphs = [];
|
|
129
154
|
let para = null;
|
|
@@ -150,7 +175,9 @@ function splitSections(body) {
|
|
|
150
175
|
function joinSections(split) {
|
|
151
176
|
return [split.head, ...split.sections].filter(Boolean).join('\n\n');
|
|
152
177
|
}
|
|
153
|
-
/** 只留首段(preamble +
|
|
178
|
+
/** 只留首段(preamble + 第一个切出来的段)。
|
|
179
|
+
* 单节形状下 splitSections 已经降级成条目,「首段」就是标题 + 第一条 ——
|
|
180
|
+
* 否则这个兜底对单节文件仍等于整篇,等于没裁。 */
|
|
154
181
|
function firstSection(body) {
|
|
155
182
|
const split = splitSections(body);
|
|
156
183
|
return joinSections({ head: split.head, sections: split.sections.slice(0, 1), mode: split.mode });
|
|
@@ -236,9 +263,9 @@ function readMeta(cfg) {
|
|
|
236
263
|
}
|
|
237
264
|
return out;
|
|
238
265
|
}
|
|
239
|
-
/**
|
|
240
|
-
function
|
|
241
|
-
return
|
|
266
|
+
/** 读人格层(PERSONA.md);缺文件 = 空 = 未启用,不报错 */
|
|
267
|
+
function readPersonas(cfg) {
|
|
268
|
+
return PERSONA_META_FILES.map((name) => {
|
|
242
269
|
let body = '';
|
|
243
270
|
try {
|
|
244
271
|
body = fs.readFileSync(path.join(cfg.notebook, name), 'utf8').trim();
|
|
@@ -290,14 +317,14 @@ function dreamNote(cfg) {
|
|
|
290
317
|
const PAYLOAD_CACHE_MAX = 8;
|
|
291
318
|
const payloadCache = new Map();
|
|
292
319
|
/** DREAMS.md 不进正文,但「上次做梦 N 天前」也算载荷的一部分 —— 它变了同样要重算 */
|
|
293
|
-
const STAMPED_FILES = [...
|
|
320
|
+
const STAMPED_FILES = [...PERSONA_META_FILES, ...META_FILES, 'DREAMS.md'];
|
|
294
321
|
function payloadKeyOf(cfg) {
|
|
295
322
|
const stamps = STAMPED_FILES.map((name) => `${name}=${fileStamp(path.join(cfg.notebook, name))}`).join('|');
|
|
296
323
|
// 做梦提醒按本地日历天变化(「3 天前」→「4 天前」):文件没动也得跟着日期失效
|
|
297
324
|
const now = new Date();
|
|
298
325
|
const day = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}`;
|
|
299
326
|
// 影响这个载荷的预算都要进键:改配置不重新写入任何文件,漏一个就会拿到旧预算的载荷。
|
|
300
|
-
return `${cfg.notebook}|${cfg.memoryBudgetWords}|${cfg.
|
|
327
|
+
return `${cfg.notebook}|${cfg.memoryBudgetWords}|${cfg.personaBudgetWords}|${day}|${stamps}`;
|
|
301
328
|
}
|
|
302
329
|
/**
|
|
303
330
|
* 生成注入载荷。纯读文件,不调 zk、不建目录:笔记本不存在时返回空载荷。
|
|
@@ -339,8 +366,23 @@ function computePayload(cfg) {
|
|
|
339
366
|
// 截断会改写这份计数;contentWords 保留原值,给 truncatedWords 与 files 用
|
|
340
367
|
const words = new Map(contentWords);
|
|
341
368
|
const total = () => [...words.values()].reduce((a, b) => a + b, 0);
|
|
342
|
-
// 截断前的 MEMORY
|
|
369
|
+
// 截断前的 MEMORY 正文(退役条目已剔除):格式债要在丢之前数
|
|
343
370
|
const memorySource = original.get('MEMORY.md') ?? '';
|
|
371
|
+
// 格式债(P1):日期 / 来源缺口的条数。只报告、不补 —— 但得摆到注入里,
|
|
372
|
+
// 否则「按日期淘汰」对没日期的老库永远空转,而 lint 一周才跑一次。
|
|
373
|
+
const debt = memoryFormatDebt(memorySource);
|
|
374
|
+
// 模板版本与记忆页共用这一份(只读首行 marker,不跑 lint):0 = 没有标记或没有 AGENTS.md
|
|
375
|
+
const agentsBody = original.get('AGENTS.md') ?? '';
|
|
376
|
+
const templateVersion = agentsBody.trim() ? templateVersionOf(agentsBody) : 0;
|
|
377
|
+
/** 格式债的一句;没有缺口返回空串。skipUndated 用于避开「只能按位置丢」已经报过的同一个数 */
|
|
378
|
+
const debtNote = (skipUndated) => {
|
|
379
|
+
const parts = [];
|
|
380
|
+
if (!skipUndated && debt.undated > 0)
|
|
381
|
+
parts.push(`${debt.undated} 条没日期`);
|
|
382
|
+
if (debt.unlinked > 0)
|
|
383
|
+
parts.push(`${debt.unlinked} 条没来源`);
|
|
384
|
+
return parts.length > 0 ? `MEMORY ${parts.join(' · ')}` : '';
|
|
385
|
+
};
|
|
344
386
|
// ── 机械截断:MEMORY 最旧条目 → USER 尾段 → 各留首段 ──────────────
|
|
345
387
|
// 丢掉的段落留一份目录(段落标题),让 agent 能按当前任务用 read 取回。
|
|
346
388
|
// 目录自己也要占预算,所以每丢一段都把它算进去;目录有上限,循环一定收敛。
|
|
@@ -350,10 +392,23 @@ function computePayload(cfg) {
|
|
|
350
392
|
for (const name of ['MEMORY.md', 'USER.md']) {
|
|
351
393
|
if (total() + countWords(tocText(dropped, tocCap)) <= budget)
|
|
352
394
|
break;
|
|
353
|
-
|
|
395
|
+
// 丢弃前的原文:目录要用「在原文件里排第几」排序,而丢弃顺序会随最旧日期乱跳;
|
|
396
|
+
// 更要命的是「多节 → 降成条目」会把两套坐标系(小节序号 / 条目序号)混进同一个 order,
|
|
397
|
+
// 目录顺序于是乱掉。直接用它在原文里的字符偏移,小节和条目共用一套坐标。
|
|
398
|
+
const pristine = original.get(name) ?? '';
|
|
399
|
+
let split = splitSections(pristine);
|
|
354
400
|
const mine = [];
|
|
355
401
|
const over = () => total() + countWords(tocText([...dropped, ...mine], tocCap)) > budget;
|
|
356
|
-
|
|
402
|
+
// 每轮重判形态:多节先丢整节;只剩一节且还能降级时冻结标题、按条目继续丢。
|
|
403
|
+
// 否则「多节丢到只剩一节」也会停在那里,剩下那一节自己超预算时同样丢不动。
|
|
404
|
+
while (over()) {
|
|
405
|
+
if (split.sections.length <= 1) {
|
|
406
|
+
const deeper = degradeSingleSection(split);
|
|
407
|
+
if (!deeper)
|
|
408
|
+
break;
|
|
409
|
+
split = deeper;
|
|
410
|
+
continue;
|
|
411
|
+
}
|
|
357
412
|
// MEMORY 按「最旧日期」丢;解析不出日期(或这是 USER)就退回尾部,行为与 0.8.3 一致
|
|
358
413
|
let index = split.sections.length - 1;
|
|
359
414
|
if (name === 'MEMORY.md') {
|
|
@@ -364,7 +419,9 @@ function computePayload(cfg) {
|
|
|
364
419
|
index = oldest;
|
|
365
420
|
}
|
|
366
421
|
const section = split.sections.splice(index, 1)[0];
|
|
367
|
-
|
|
422
|
+
// 相同文本(两条一模一样的条目)会拿到同一个偏移:并列时保持丢弃顺序,足够好
|
|
423
|
+
const at = pristine.indexOf(section);
|
|
424
|
+
mine.push({ name, title: sectionTitle(section, split.mode), order: at < 0 ? Number.MAX_SAFE_INTEGER : at });
|
|
368
425
|
const body = joinSections(split);
|
|
369
426
|
original.set(name, body);
|
|
370
427
|
words.set(name, countWords(body));
|
|
@@ -398,15 +455,20 @@ function computePayload(cfg) {
|
|
|
398
455
|
let memoryInner = '';
|
|
399
456
|
if (bodies.length > 0) {
|
|
400
457
|
const notes = [];
|
|
401
|
-
|
|
402
|
-
|
|
458
|
+
// 截断时也带上格式债(P1):先量词数,放不下就整条不加 —— 提示自己也要吃饭。
|
|
459
|
+
// 已经要说「只能按位置丢」时跳过没日期那半句,避免同一个数报两遍。
|
|
460
|
+
if (truncatedWords > 0) {
|
|
461
|
+
const suffix = debtNote(fellBack && debt.undated > 0);
|
|
462
|
+
const append = suffix && finalWords + countWords(` · ${suffix}`) <= budget ? ` · ${suffix}` : '';
|
|
463
|
+
notes.push(`已截断 ${truncatedWords} 词${append}`);
|
|
464
|
+
}
|
|
403
465
|
if (omittedNote)
|
|
404
466
|
notes.push(omittedNote);
|
|
405
467
|
// 一条日期都没有只能按位置丢:说出来,别让人以为是按日期挑的(D2.5)
|
|
468
|
+
// 数字取内存里那份格式债,不在这里另数一遍(退役条目算不算会两边不一致)
|
|
406
469
|
if (fellBack && truncatedWords > 0) {
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
notes.push(`MEMORY 有 ${undated} 条没日期,只能按位置丢`);
|
|
470
|
+
if (debt.undated > 0)
|
|
471
|
+
notes.push(`MEMORY 有 ${debt.undated} 条没日期,只能按位置丢`);
|
|
410
472
|
}
|
|
411
473
|
// 目录放不下时至少留一句指路;否则被丢掉的段落对模型完全不可见
|
|
412
474
|
if (!toc && dropped.length > 0) {
|
|
@@ -442,7 +504,17 @@ function computePayload(cfg) {
|
|
|
442
504
|
const cost = countWords(`记忆已用 ${finalWords}/${budget} 词(100%)`);
|
|
443
505
|
if (finalWords + cost <= budget) {
|
|
444
506
|
finalWords += cost;
|
|
445
|
-
|
|
507
|
+
// 格式债跟在用量后面(P1):整条量过再说,放不下就一句都不加,
|
|
508
|
+
// 不能出现「MEMORY 9 条没日期」却丢了「3 条没来源」这种半句。
|
|
509
|
+
const suffix = debtNote(false);
|
|
510
|
+
const debtCost = suffix ? countWords(` · ${suffix}`) : 0;
|
|
511
|
+
if (suffix && finalWords + debtCost <= budget) {
|
|
512
|
+
finalWords += debtCost;
|
|
513
|
+
notes.push(`记忆已用 ${finalWords}/${budget} 词(${Math.round((finalWords / budget) * 100)}%) · ${suffix}`);
|
|
514
|
+
}
|
|
515
|
+
else {
|
|
516
|
+
notes.push(`记忆已用 ${finalWords}/${budget} 词(${Math.round((finalWords / budget) * 100)}%)`);
|
|
517
|
+
}
|
|
446
518
|
}
|
|
447
519
|
}
|
|
448
520
|
const notice = notes.length > 0 ? `\n\n(注入预算 ${budget} 词:${notes.join(';')})` : '';
|
|
@@ -454,25 +526,25 @@ function computePayload(cfg) {
|
|
|
454
526
|
(dream ? `\n\n(${dream})` : '') +
|
|
455
527
|
notice;
|
|
456
528
|
}
|
|
457
|
-
// ──
|
|
529
|
+
// ── 人格段(角色):永远注入、在记忆段之前、不参与截断 ────
|
|
458
530
|
// 超预算只告警不静默丢。
|
|
459
|
-
//
|
|
460
|
-
const
|
|
461
|
-
const
|
|
462
|
-
const
|
|
463
|
-
const
|
|
531
|
+
// 没有人格文件 = 未启用:不多一个词。
|
|
532
|
+
const personaBudget = cfg.personaBudgetWords;
|
|
533
|
+
const personas = readPersonas(cfg);
|
|
534
|
+
const personaBodies = personas.filter((f) => f.body.length > 0);
|
|
535
|
+
const personaBodyText = personaBodies.map((f) => `## ${f.name}\n\n${escapeFrame(f.body)}`).join('\n\n');
|
|
464
536
|
// 预算只算正文(含文件标题),不能把告警行算进去 —— 否则「已用 / 超出」会随告警自己的长度变
|
|
465
|
-
const
|
|
466
|
-
const
|
|
467
|
-
const
|
|
468
|
-
if (
|
|
469
|
-
|
|
537
|
+
const personaContentWords = countWords(personaBodyText);
|
|
538
|
+
const personaOver = personaBodies.length > 0 && personaContentWords > personaBudget;
|
|
539
|
+
const personaNotes = [];
|
|
540
|
+
if (personaOver) {
|
|
541
|
+
personaNotes.push(`人格上限 ${personaBudget} 词:已用 ${personaContentWords},超出 ${personaContentWords - personaBudget} 词(人格不截断)`);
|
|
470
542
|
}
|
|
471
|
-
const
|
|
472
|
-
const
|
|
543
|
+
const personaText = personaBodyText + (personaNotes.length > 0 ? `\n\n(${personaNotes.join(';')})` : '');
|
|
544
|
+
const personaWords = countWords(personaText);
|
|
473
545
|
let text = '';
|
|
474
|
-
if (memoryInner ||
|
|
475
|
-
text = frameText((
|
|
546
|
+
if (memoryInner || personaText) {
|
|
547
|
+
text = frameText((personaText ? personaText + '\n\n' : '') + memoryInner);
|
|
476
548
|
}
|
|
477
549
|
// 模型真正收到的总量与开销:口径与 memoryUsage / D9 的载荷预览同源
|
|
478
550
|
const totalWords = countWords(text);
|
|
@@ -484,6 +556,8 @@ function computePayload(cfg) {
|
|
|
484
556
|
truncatedWords,
|
|
485
557
|
retiredWords,
|
|
486
558
|
tocWords: countWords(toc),
|
|
559
|
+
formatDebt: debt,
|
|
560
|
+
templateVersion,
|
|
487
561
|
files: files.map((f) => ({
|
|
488
562
|
name: f.name,
|
|
489
563
|
present: f.body.length > 0,
|
|
@@ -492,18 +566,18 @@ function computePayload(cfg) {
|
|
|
492
566
|
originalWords: diskWords.get(f.name) ?? 0,
|
|
493
567
|
retiredWords: f.name === 'MEMORY.md' ? retiredWords : 0,
|
|
494
568
|
})),
|
|
495
|
-
|
|
496
|
-
present:
|
|
497
|
-
contentWords:
|
|
498
|
-
words:
|
|
499
|
-
noticeWords: Math.max(0,
|
|
500
|
-
budget:
|
|
501
|
-
overBudget:
|
|
502
|
-
overWords: Math.max(0,
|
|
503
|
-
files:
|
|
569
|
+
persona: {
|
|
570
|
+
present: personaBodies.length > 0,
|
|
571
|
+
contentWords: personaContentWords,
|
|
572
|
+
words: personaWords,
|
|
573
|
+
noticeWords: Math.max(0, personaWords - personaContentWords),
|
|
574
|
+
budget: personaBudget,
|
|
575
|
+
overBudget: personaOver,
|
|
576
|
+
overWords: Math.max(0, personaContentWords - personaBudget),
|
|
577
|
+
files: personas.map((f) => ({ name: f.name, present: f.body.length > 0, words: countWords(f.body) })),
|
|
504
578
|
},
|
|
505
579
|
totalWords,
|
|
506
|
-
overheadWords: Math.max(0, totalWords -
|
|
580
|
+
overheadWords: Math.max(0, totalWords - personaContentWords - finalWords),
|
|
507
581
|
};
|
|
508
582
|
}
|
|
509
583
|
/**
|
|
@@ -514,11 +588,11 @@ export function memoryUsage(cfg) {
|
|
|
514
588
|
const payload = buildMemoryPayload(cfg);
|
|
515
589
|
return {
|
|
516
590
|
words: payload.words,
|
|
517
|
-
|
|
591
|
+
personaWords: payload.persona.words,
|
|
518
592
|
totalWords: payload.totalWords,
|
|
519
593
|
budget: payload.budget,
|
|
520
|
-
//
|
|
521
|
-
headroom: payload.budget - (payload.totalWords - payload.
|
|
594
|
+
// 人格是独立层:整段(含它的告警)都不该占记忆预算,否则 dream 会误报「余量」
|
|
595
|
+
headroom: payload.budget - (payload.totalWords - payload.persona.words),
|
|
522
596
|
files: payload.files,
|
|
523
597
|
};
|
|
524
598
|
}
|
package/dist/lib/meta.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* 笔记本根目录的 meta 文件:唯一定义处(计划 §7「工具层只放一个常量」)。
|
|
3
3
|
*
|
|
4
|
-
* 三份被注入记忆段(MEMORY_META_FILES
|
|
4
|
+
* 三份被注入记忆段(MEMORY_META_FILES,按注入顺序),角色人格(PERSONA_META_FILES)单独注入、
|
|
5
5
|
* 永远在记忆段之前;七份一律不进检索与统计(META_NAMES)。
|
|
6
6
|
* 为什么要拆:注入清单与排除清单共用一份真相,才不会出现「新加一份 meta 忘了排除」。
|
|
7
7
|
*
|
|
8
|
-
*
|
|
8
|
+
* 人格文件(PERSONA.md)与 MEMORY 同级:根目录 meta,人类所有;
|
|
9
9
|
* 工具不能写、不能搬(zk 层的 isMetaPath 守卫自动覆盖)。缺文件 = 未启用,不报错。
|
|
10
10
|
* 迁移说明:根目录曾有同名普通笔记的库,需要改名或移入子目录。
|
|
11
11
|
*/
|
|
12
12
|
/** 会被注入系统提示的三份,顺序即注入顺序 */
|
|
13
13
|
export const MEMORY_META_FILES = ['AGENTS.md', 'USER.md', 'MEMORY.md'];
|
|
14
|
-
/**
|
|
15
|
-
export const
|
|
14
|
+
/** 人格层(角色人格),人类所有,缺文件 = 未启用 */
|
|
15
|
+
export const PERSONA_META_FILES = ['PERSONA.md'];
|
|
16
16
|
/** 全部 meta 文件(不进检索 / 统计 / 追加写入) */
|
|
17
17
|
export const META_NAMES = ['AGENTS.md', 'MEMORY.md', 'USER.md', 'DREAMS.md', 'INDEX.md', 'WORKFLOW.md', 'PERSONA.md'];
|
|
18
18
|
/** 相对路径是不是根目录的 meta 文件(只认根目录;子目录里的同名文件是普通笔记) */
|
package/dist/lib/notebook.js
CHANGED
|
@@ -344,13 +344,13 @@ export function writeAgentsTemplate(cfg) {
|
|
|
344
344
|
return true;
|
|
345
345
|
}
|
|
346
346
|
/**
|
|
347
|
-
*
|
|
348
|
-
* 只走显式 opt-in(zk-kit init --with-
|
|
347
|
+
* 写根目录角色人格模板(PERSONA.md;缺了才写,已存在绝不覆盖 —— 人格允许人改)。
|
|
348
|
+
* 只走显式 opt-in(zk-kit init --with-persona / 设置页按钮):默认升级不多一个文件。
|
|
349
349
|
*
|
|
350
|
-
* 先 mkdir
|
|
351
|
-
*
|
|
350
|
+
* 先 mkdir 再写:设置页的按钮在笔记本还没初始化时也可点(「先定人格、再建库」是合法顺序)。
|
|
351
|
+
* 这里只建目录与人格文件,不碰 .zk / 模板 / 笔记;之后 ensureNotebook 幂等接管同一目录。
|
|
352
352
|
*/
|
|
353
|
-
export function
|
|
353
|
+
export function writePersonaTemplate(cfg) {
|
|
354
354
|
const persona = path.join(cfg.notebook, 'PERSONA.md');
|
|
355
355
|
const personaWritten = !fs.existsSync(persona);
|
|
356
356
|
if (personaWritten)
|
|
@@ -377,13 +377,13 @@ export async function ensureNotebook(cfg, signal, opts = {}) {
|
|
|
377
377
|
'entry.md': ENTRY_TEMPLATE,
|
|
378
378
|
})
|
|
379
379
|
: ensureTemplates(cfg, { 'daily.md': DAILY_TEMPLATE });
|
|
380
|
-
// AGENTS.md
|
|
380
|
+
// AGENTS.md 是工作约定(检索词归宿 / 中文打 tags / MEMORY 截断方向)。
|
|
381
381
|
// layered 自动写;flat 只有显式 withAgents 才写 —— 0.1.0 的 vault 升级过来必须一个文件都不多(M0)。
|
|
382
382
|
// 不写的话,默认安装既没有约定、也没有周节奏提醒(P1-6),所以要有一个 opt-in 入口。
|
|
383
383
|
const agentsWritten = layered || opts.withAgents === true ? writeAgentsTemplate(cfg) : false;
|
|
384
|
-
//
|
|
385
|
-
const
|
|
386
|
-
?
|
|
384
|
+
// 人格层(角色)只走显式 opt-in:两种结构都不自动多一个文件(D10)。
|
|
385
|
+
const personaWritten = opts.withPersona === true
|
|
386
|
+
? writePersonaTemplate(cfg)
|
|
387
387
|
: { personaWritten: false };
|
|
388
388
|
// WORKFLOW.md 是「动已有笔记」时才读的细则:不注入(省预算),但不进检索(是 meta)
|
|
389
389
|
const workflowFile = path.join(cfg.notebook, 'WORKFLOW.md');
|
|
@@ -442,7 +442,7 @@ export async function ensureNotebook(cfg, signal, opts = {}) {
|
|
|
442
442
|
groupWarnings,
|
|
443
443
|
agentsWritten,
|
|
444
444
|
workflowWritten,
|
|
445
|
-
personaWritten:
|
|
445
|
+
personaWritten: personaWritten.personaWritten,
|
|
446
446
|
};
|
|
447
447
|
}
|
|
448
448
|
const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
@@ -1,32 +1,32 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* 根目录 PERSONA.md 模板:opt-in 写入(`zk-kit init --with-
|
|
3
|
-
*
|
|
2
|
+
* 根目录 PERSONA.md 模板:opt-in 写入(`zk-kit init --with-persona`、
|
|
3
|
+
* 设置页「写入角色人格模板」、ensureNotebook(..., { withPersona: true })),已存在绝不覆盖。
|
|
4
4
|
*
|
|
5
5
|
* 与 AGENTS.md 模板同一条规矩:首行版本标记独立(`zdiary-persona`,
|
|
6
|
-
* 不复用 zdiary-template —— AGENTS
|
|
7
|
-
* 版本标记后**紧跟** frontmatter:解析 PERSONA 前先 `
|
|
6
|
+
* 不复用 zdiary-template —— AGENTS 改版不该让人格文件误报旧版)。
|
|
7
|
+
* 版本标记后**紧跟** frontmatter:解析 PERSONA 前先 `stripPersonaMarker()`,
|
|
8
8
|
* 再复用 `lib/frontmatter` —— 不要让「机器可读字段」依赖一个只在本模块才认的自定义语法。
|
|
9
9
|
* 缺文件 = 未启用,不报错;doctor / zk_lint 只给只读提示。
|
|
10
10
|
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
11
|
+
* 长度是设计约束:默认上限 240 词(personaBudgetWords,中文 2 字 = 1 词),
|
|
12
|
+
* 人格不参与截断,超了只告警 —— 所以模板只留骨架,占位符 `{{...}}` 由人填,
|
|
13
13
|
* lint 据此报告「未填」。
|
|
14
14
|
*/
|
|
15
15
|
/** PERSONA.md 模板版本:改模板就 +1(独立于 TEMPLATE_VERSION) */
|
|
16
|
-
export const PERSONA_TEMPLATE_VERSION =
|
|
16
|
+
export const PERSONA_TEMPLATE_VERSION = 4;
|
|
17
17
|
/**
|
|
18
18
|
* 只列当前版本的哨兵,用来发现「只改了首行数字」:
|
|
19
|
-
* - PERSONA v3 删掉了「##
|
|
20
|
-
*
|
|
19
|
+
* - PERSONA v3 删掉了「## 口头禅」;v4 统一标题为「# 角色人格」。
|
|
20
|
+
* 升版本时同步补;命中也只报告,不覆盖(人格允许人改)。
|
|
21
21
|
*/
|
|
22
|
-
export const
|
|
23
|
-
'PERSONA.md': {
|
|
22
|
+
export const PERSONA_TEMPLATE_SENTINELS = {
|
|
23
|
+
'PERSONA.md': { 4: { required: ['# 角色人格'], forbidden: ['## 口头禅'] } },
|
|
24
24
|
};
|
|
25
25
|
/**
|
|
26
|
-
*
|
|
26
|
+
* 去掉首行人格版本标记,剩下的可以直接交给 `parseFrontmatter()`。
|
|
27
27
|
* PERSONA 解析必须走这里,别自己再写一套「跳过第几行」的规则。
|
|
28
28
|
*/
|
|
29
|
-
export function
|
|
29
|
+
export function stripPersonaMarker(body) {
|
|
30
30
|
return String(body ?? '').replace(/^\uFEFF?\s*<!--\s*zdiary-persona:\s*v\d+\s*-->\s*\r?\n?/, '');
|
|
31
31
|
}
|
|
32
32
|
export const PERSONA_TEMPLATE = `<!-- zdiary-persona: v${PERSONA_TEMPLATE_VERSION} -->
|
|
@@ -36,7 +36,7 @@ role: {{role}}
|
|
|
36
36
|
updated: {{updated}}
|
|
37
37
|
---
|
|
38
38
|
|
|
39
|
-
#
|
|
39
|
+
# 角色人格
|
|
40
40
|
|
|
41
41
|
> zdiary 生成;人类所有。永远注入、不参与截断。git diff 可审。
|
|
42
42
|
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 标题相似度(唯一一份):周审 lint 与 zk_new 的写路径提示共用。
|
|
3
|
+
*
|
|
4
|
+
* 为什么单独一个文件:lint.ts 已经 import zk.ts,zk.ts 反向 import lint.ts 会成环;
|
|
5
|
+
* 相似判定抽到无依赖的小模块,两边都往下 import。
|
|
6
|
+
*
|
|
7
|
+
* 纯机械:NFKC → 小写 → 去标点 / 空白,按字符二元组算 Jaccard ≥ 0.6;
|
|
8
|
+
* 短串(≥ 6 字)被长串包含也算命中。不做语义判断、不调模型、不建索引。
|
|
9
|
+
*/
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { normalizeTitle } from './wikilink.js';
|
|
12
|
+
/** 字符二元组 Jaccard 下限 */
|
|
13
|
+
const SIMILAR_RATIO = 0.6;
|
|
14
|
+
/** 短串被长串包含时,短串至少要这么长(码点数) */
|
|
15
|
+
const SIMILAR_SHORT = 6;
|
|
16
|
+
/** 标题短于这个码点数不参与比较:二元组太少(RAG / RAG 2 会算出 0.67),噪声大于信号 */
|
|
17
|
+
const SIMILAR_MIN = 4;
|
|
18
|
+
/** 比较用的标题:NFKC → 小写 → 去标点 / 空白。中文不改字,只抹掉排版差异 */
|
|
19
|
+
function similarKey(title) {
|
|
20
|
+
return String(title ?? '').normalize('NFKC').toLowerCase().replace(/[\s\p{P}\p{S}]/gu, '');
|
|
21
|
+
}
|
|
22
|
+
/** 字符二元组;单字标题退化成单字本身(否则集合为空,永远算不出相似) */
|
|
23
|
+
function bigrams(key) {
|
|
24
|
+
const chars = [...key];
|
|
25
|
+
const out = new Set();
|
|
26
|
+
for (let i = 0; i < chars.length - 1; i++)
|
|
27
|
+
out.add(chars[i] + chars[i + 1]);
|
|
28
|
+
if (out.size === 0 && chars.length > 0)
|
|
29
|
+
out.add(chars[0]);
|
|
30
|
+
return out;
|
|
31
|
+
}
|
|
32
|
+
/** Jaccard 相似度(0–1) */
|
|
33
|
+
function jaccard(a, b) {
|
|
34
|
+
if (a.size === 0 || b.size === 0)
|
|
35
|
+
return 0;
|
|
36
|
+
let shared = 0;
|
|
37
|
+
for (const gram of a)
|
|
38
|
+
if (b.has(gram))
|
|
39
|
+
shared += 1;
|
|
40
|
+
return shared / (a.size + b.size - shared);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* 可比较的标题;空标题与纯数字(日期 / 编号)返回 null。
|
|
44
|
+
* 纯数字标题的相似度只反映「数字挨着」,不反映重复结论 —— 一年日记会吐出上千组误报。
|
|
45
|
+
*/
|
|
46
|
+
export function similarKeyOf(title) {
|
|
47
|
+
const key = similarKey(title);
|
|
48
|
+
if (!key || /^\d+$/.test(key))
|
|
49
|
+
return null;
|
|
50
|
+
// size 按码点算([...key].length),不混用 .length:后者数 UTF-16 单元,
|
|
51
|
+
// 标题带 emoji / 扩展区汉字时会比码点多一倍,「谁是短串」会判错。
|
|
52
|
+
return { key, grams: bigrams(key), size: [...key].length };
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* 两个标题的相似度(两位小数);不相似返回 null。
|
|
56
|
+
* 「短串被长串包含」命中时按下限 0.6 记 —— 否则 0.5 的分数会让「已经报了」看起来自相矛盾。
|
|
57
|
+
*/
|
|
58
|
+
export function similarScore(a, b) {
|
|
59
|
+
if (a.size < SIMILAR_MIN || b.size < SIMILAR_MIN)
|
|
60
|
+
return null;
|
|
61
|
+
const score = jaccard(a.grams, b.grams);
|
|
62
|
+
if (score >= SIMILAR_RATIO)
|
|
63
|
+
return Math.round(score * 100) / 100;
|
|
64
|
+
const [short, long, shortSize] = a.size <= b.size ? [a.key, b.key, a.size] : [b.key, a.key, b.size];
|
|
65
|
+
if (shortSize >= SIMILAR_SHORT && long.includes(short))
|
|
66
|
+
return SIMILAR_RATIO;
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* 写路径查重(P2):同一目录里与 title 相似的已有标题,最多 max 条,分数降序。
|
|
71
|
+
*
|
|
72
|
+
* 只提示、不阻断:误报会挡住正常写作,是否合并仍是人的判断。
|
|
73
|
+
* 归一化后全等的交给 duplicateTitles / createNote 的硬查重,这里不重复报。
|
|
74
|
+
* 归档由调用方先滤掉 —— 这里不认识 Config,也不该自己判断哪些路径算归档。
|
|
75
|
+
*/
|
|
76
|
+
export function similarCandidates(notes, title, dir, max = 3) {
|
|
77
|
+
const target = similarKeyOf(title);
|
|
78
|
+
if (!target)
|
|
79
|
+
return [];
|
|
80
|
+
const exact = normalizeTitle(title);
|
|
81
|
+
const dirKey = dir.replace(/\/+$/, '');
|
|
82
|
+
const out = [];
|
|
83
|
+
for (const note of notes) {
|
|
84
|
+
if (!note.path || path.posix.dirname(note.path) !== dirKey)
|
|
85
|
+
continue;
|
|
86
|
+
// 无标题的笔记用文件名 —— 与 `similarTitles` 的 `title || basename` 同口径,
|
|
87
|
+
// 否则写路径与周审的候选集不一样(分数一致也没用)。
|
|
88
|
+
const otherTitle = note.title || path.basename(note.path, path.extname(note.path));
|
|
89
|
+
if (!otherTitle)
|
|
90
|
+
continue;
|
|
91
|
+
if (normalizeTitle(otherTitle) === exact)
|
|
92
|
+
continue;
|
|
93
|
+
const other = similarKeyOf(otherTitle);
|
|
94
|
+
if (!other)
|
|
95
|
+
continue;
|
|
96
|
+
const score = similarScore(target, other);
|
|
97
|
+
if (score === null)
|
|
98
|
+
continue;
|
|
99
|
+
out.push({ title: otherTitle, path: note.path, score });
|
|
100
|
+
}
|
|
101
|
+
out.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path));
|
|
102
|
+
return out.slice(0, max);
|
|
103
|
+
}
|
package/dist/lib/zk.js
CHANGED
|
@@ -13,6 +13,8 @@ import { BIN_DIR } from '../config/paths.js';
|
|
|
13
13
|
import { ExecError, findOnPath, run } from './exec.js';
|
|
14
14
|
import { parseFrontmatter, setFrontmatter } from './frontmatter.js';
|
|
15
15
|
import { isMetaPath, META_NAMES } from './meta.js';
|
|
16
|
+
import { similarCandidates } from './similar.js';
|
|
17
|
+
import { normalizeTitle } from './wikilink.js';
|
|
16
18
|
export class ZkError extends Error {
|
|
17
19
|
hint;
|
|
18
20
|
/**
|
|
@@ -42,10 +44,6 @@ export function localDate(iso) {
|
|
|
42
44
|
const dd = String(d.getDate()).padStart(2, '0');
|
|
43
45
|
return `${d.getFullYear()}-${mm}-${dd}`;
|
|
44
46
|
}
|
|
45
|
-
/** 标题查重用的归一化:压空白 + 小写(与 lint 的重名口径一致) */
|
|
46
|
-
function normalizeTitle(title) {
|
|
47
|
-
return String(title ?? '').replace(/\s+/g, ' ').trim().toLowerCase();
|
|
48
|
-
}
|
|
49
47
|
/** 废弃原因最多这么长:frontmatter 是给人看的审计线,不是自由文本容器 */
|
|
50
48
|
const MAX_SUPERSEDE_REASON = 200;
|
|
51
49
|
/** 一句话、单行;换行会弄坏 frontmatter,超长机械截断(不判断内容) */
|
|
@@ -671,8 +669,9 @@ export async function createNote(cfg, input, signal, scan = (c, s) => allNotes(c
|
|
|
671
669
|
// 以前是各跑一次 `zk list`:同一个库扫两遍,还多起一个进程。
|
|
672
670
|
const dupCheck = cfg.structure !== 'layered';
|
|
673
671
|
let archived = [];
|
|
672
|
+
let similar = [];
|
|
673
|
+
let snapshot = null;
|
|
674
674
|
if (hasNotebook(cfg)) {
|
|
675
|
-
let snapshot = null;
|
|
676
675
|
try {
|
|
677
676
|
snapshot = await scan(cfg, signal);
|
|
678
677
|
}
|
|
@@ -740,6 +739,11 @@ export async function createNote(cfg, input, signal, scan = (c, s) => allNotes(c
|
|
|
740
739
|
throw new ZkError(`zk 说建好了但文件不存在:${abs}`);
|
|
741
740
|
// 扩展名被用户改成 .markdown 等时,预判可能漏掉;这里再兜一次(只删本次新建的文件)
|
|
742
741
|
const createdRel = relPathOf(cfg, abs);
|
|
742
|
+
// 相似标题(P2):按**实际落下的目录**比同目录标题(layered 不给 dir 时由 type / group 决定)。
|
|
743
|
+
// 只提示、不阻断 —— 精确同名在上面已经报错;口径与 zk_lint 的 similarTitles 同一份实现。
|
|
744
|
+
if (snapshot) {
|
|
745
|
+
similar = similarCandidates(snapshot.filter((n) => !inArchive(cfg, n.path)), title, path.posix.dirname(createdRel));
|
|
746
|
+
}
|
|
743
747
|
if (isMetaPath(createdRel)) {
|
|
744
748
|
if (!before.has(path.basename(abs))) {
|
|
745
749
|
try {
|
|
@@ -786,7 +790,7 @@ export async function createNote(cfg, input, signal, scan = (c, s) => allNotes(c
|
|
|
786
790
|
summaryWarning = `summary 没写进去:${err instanceof Error ? err.message : String(err)}(文件已建好,可以直接编辑那一节)`;
|
|
787
791
|
}
|
|
788
792
|
}
|
|
789
|
-
return { path: relPathOf(cfg, finalAbs), absPath: finalAbs, title, archived, summaryApplied, summaryWarning };
|
|
793
|
+
return { path: relPathOf(cfg, finalAbs), absPath: finalAbs, title, archived, similar, summaryApplied, summaryWarning };
|
|
790
794
|
}
|
|
791
795
|
/** 笔记本相对路径是否在归档目录下(supersede 会把文件搬进去,路径保持不变) */
|
|
792
796
|
function inArchive(cfg, rel) {
|