dsh-zdiary-kit 3.2.0 → 3.4.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 +15 -5
- package/dist/cli.js +3 -0
- package/dist/config/store.js +8 -0
- package/dist/features/readonly/feature.js +29 -31
- package/dist/features/settings/client.js +1 -0
- package/dist/features/zk-tools/feature.js +33 -4
- package/dist/lib/agents-template.js +10 -0
- package/dist/lib/dream.js +8 -2
- package/dist/lib/exec.js +13 -2
- package/dist/lib/lint.js +143 -66
- package/dist/lib/memory-format.js +23 -0
- package/dist/lib/memory.js +111 -37
- package/dist/lib/notebook.js +4 -2
- package/dist/lib/similar.js +103 -0
- package/dist/lib/zk.js +244 -18
- package/docs/features/memory.md +25 -2
- package/docs/features/readonly.md +8 -4
- package/docs/features/settings.md +4 -2
- package/docs/features/zk-tools.md +35 -6
- package/package.json +3 -1
package/dist/lib/lint.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* 巡检(M3):只报告,不改任何笔记(计划 §3 D5)。
|
|
3
3
|
*
|
|
4
|
-
* 一次 `zk list` 拿全量,再用 zk
|
|
5
|
-
*
|
|
4
|
+
* 一次 `zk list` 拿全量,再用 zk 原生的几个过滤器(孤儿 / 断链 / 无标签 / 缺回链)各跑一次进程;
|
|
5
|
+
* 「陈旧」「重名」在 JS 里算,单向链接小库用一次 `zk graph` 的边、大库按篇反查(见 `oneWayByQueries`)。
|
|
6
|
+
* 200 条笔记上 5 次进程就够 —— 大库那条路也按「问题数」而不是「篇数」计费。
|
|
6
7
|
*
|
|
7
8
|
* 「陈旧」为什么自己算:zk 的 `stale` 不是内置过滤器,`zk list stale` 只在你自己的
|
|
8
9
|
* `[filter]` 里定义过才存在(Z3 只说了位置参数语法,没说它是内置的)。所以阈值由插件定。
|
|
@@ -12,7 +13,7 @@
|
|
|
12
13
|
*
|
|
13
14
|
* 「单向链接」为什么自己算:zk 的 `--missing-backlink` 是「至少有一条单向链接」(S 链 X、X 不回链),
|
|
14
15
|
* 而日记天然是一串出边 —— 日记提过的每篇笔记都会常年挂在桶里。那不是「笔记没接上」,是正常的引用方向。
|
|
15
|
-
*
|
|
16
|
+
* 所以在边上自己算,只报**非日记来源**的单向链接。
|
|
16
17
|
*
|
|
17
18
|
* 解析失败单列一桶:frontmatter 写坏(典型是 `tags: [#你好世界]`,`#` 不是 tag 前缀)时
|
|
18
19
|
* zk 只在 stderr 吭一声就跳过那篇,它于是从索引里消失 —— 搜不到,也不进上面任何一个桶。
|
|
@@ -23,16 +24,23 @@
|
|
|
23
24
|
*/
|
|
24
25
|
import fs from 'node:fs';
|
|
25
26
|
import path from 'node:path';
|
|
26
|
-
import { allNotes, graphEdges, localDate, MAX_SCAN, notesWithFlag, parseErrorWarnings } from './zk.js';
|
|
27
|
+
import { allNotes, backlinksOf, GRAPH_BUDGET_NOTES, graphEdges, localDate, MAX_SCAN, notesWithFlag, outlinksOf, parseErrorWarnings, } from './zk.js';
|
|
27
28
|
import { normalizeTitle, resolveWikiTarget, WIKI_LINK, wikiIndex } from './wikilink.js';
|
|
28
29
|
import { parseFrontmatter } from './frontmatter.js';
|
|
29
|
-
import { daysSinceDate, entryDate, isRetiredEntry, splitMemoryEntries } from './memory-format.js';
|
|
30
|
-
import { AGENTS_TEMPLATE, AGENTS_TEMPLATE_FLAT, TEMPLATE_SENTINELS, TEMPLATE_VERSION } from './agents-template.js';
|
|
30
|
+
import { daysSinceDate, entryDate, isRetiredEntry, memoryFormatDebt, splitMemoryEntries } from './memory-format.js';
|
|
31
|
+
import { AGENTS_TEMPLATE, AGENTS_TEMPLATE_FLAT, TEMPLATE_SENTINELS, TEMPLATE_VERSION, templateVersionOf } from './agents-template.js';
|
|
31
32
|
import { PERSONA_TEMPLATE_SENTINELS, PERSONA_TEMPLATE_VERSION } from './persona-template.js';
|
|
32
33
|
import { timelineCounts, timelineIssues } from './timeline.js';
|
|
33
34
|
import { isDayString } from './dates.js';
|
|
35
|
+
import { similarKeyOf, similarScore } from './similar.js';
|
|
34
36
|
/** 每类最多回多少条(计划 §4 M3);总数另给 */
|
|
35
37
|
export const MAX_ITEMS = 50;
|
|
38
|
+
/**
|
|
39
|
+
* 大库按篇反查的上限(plan §9.3):目标数 50、子进程 60,取先到者(每个目标要 2 个进程,
|
|
40
|
+
* 实际约 30 个目标;10k 库上每个约 0.45 s)。超了就报 `edgesTruncated`,不静默少报。
|
|
41
|
+
*/
|
|
42
|
+
const MAX_ONE_WAY_TARGETS = 50;
|
|
43
|
+
const MAX_ONE_WAY_QUERIES = 60;
|
|
36
44
|
/** 时间轴只扫最近多少天(计划 §2 D4):一年日记会报几百条旧问题,把今天的问题挤出 50 条上限 */
|
|
37
45
|
export const TIMELINE_WINDOW_DAYS = 90;
|
|
38
46
|
/** 超过这个大小的日记不读(doctor / lint 不该把 2 GiB 的日志拉进内存):跳过并计入 skipped */
|
|
@@ -56,33 +64,8 @@ export function duplicateTitles(notes, max = MAX_ITEMS) {
|
|
|
56
64
|
dup.sort((a, b) => b.paths.length - a.paths.length || a.title.localeCompare(b.title));
|
|
57
65
|
return { total: dup.length, items: dup.slice(0, max) };
|
|
58
66
|
}
|
|
59
|
-
/** 相似标题的判定:字符二元组 Jaccard 下限;短串被长串包含时另算(短串至少 6 字) */
|
|
60
|
-
const SIMILAR_RATIO = 0.6;
|
|
61
|
-
const SIMILAR_SHORT = 6;
|
|
62
67
|
/** 同目录最多两两比较多少篇:超过就截断并置 truncated,别让 1 万篇变成 O(n²) */
|
|
63
68
|
const SIMILAR_GROUP_MAX = 300;
|
|
64
|
-
/** 比较用的标题:NFKC → 小写 → 去标点 / 空白。中文不改字,只抹掉排版差异 */
|
|
65
|
-
function similarKey(title) {
|
|
66
|
-
return String(title ?? '').normalize('NFKC').toLowerCase().replace(/[\s\p{P}\p{S}]/gu, '');
|
|
67
|
-
}
|
|
68
|
-
function bigrams(key) {
|
|
69
|
-
const chars = [...key];
|
|
70
|
-
const out = new Set();
|
|
71
|
-
for (let i = 0; i < chars.length - 1; i++)
|
|
72
|
-
out.add(chars[i] + chars[i + 1]);
|
|
73
|
-
if (out.size === 0 && chars.length > 0)
|
|
74
|
-
out.add(chars[0]);
|
|
75
|
-
return out;
|
|
76
|
-
}
|
|
77
|
-
function jaccard(a, b) {
|
|
78
|
-
if (a.size === 0 || b.size === 0)
|
|
79
|
-
return 0;
|
|
80
|
-
let shared = 0;
|
|
81
|
-
for (const gram of a)
|
|
82
|
-
if (b.has(gram))
|
|
83
|
-
shared += 1;
|
|
84
|
-
return shared / (a.size + b.size - shared);
|
|
85
|
-
}
|
|
86
69
|
/**
|
|
87
70
|
* 疑似重复标题(P2-10):精确查重只能挡住手滑 —— 中文改两个字就绕过去了。
|
|
88
71
|
*
|
|
@@ -98,15 +81,13 @@ export function similarTitles(notes, scanTruncated, max = MAX_ITEMS) {
|
|
|
98
81
|
const groups = new Map();
|
|
99
82
|
for (const note of notes) {
|
|
100
83
|
const title = note.title || path.basename(note.path, path.extname(note.path));
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
// 纯数字:日期 / 编号类标题,相似度只反映「数字挨着」,不反映重复结论
|
|
105
|
-
if (/^\d+$/.test(key))
|
|
84
|
+
// 空标题、纯数字(日期 / 编号)都在这里被挡掉,口径与 zk_new 的写路径提示同一份
|
|
85
|
+
const target = similarKeyOf(title);
|
|
86
|
+
if (!target)
|
|
106
87
|
continue;
|
|
107
88
|
const dir = path.posix.dirname(note.path);
|
|
108
89
|
const list = groups.get(dir) ?? [];
|
|
109
|
-
list.push({ title, path: note.path,
|
|
90
|
+
list.push({ title, path: note.path, exact: normalizeTitle(title), ...target });
|
|
110
91
|
groups.set(dir, list);
|
|
111
92
|
}
|
|
112
93
|
let truncated = scanTruncated;
|
|
@@ -124,24 +105,14 @@ export function similarTitles(notes, scanTruncated, max = MAX_ITEMS) {
|
|
|
124
105
|
// 归一化后完全一样:那是 duplicateTitles 的活(这里报会让同一件事出现两遍)
|
|
125
106
|
if (a.exact === b.exact)
|
|
126
107
|
continue;
|
|
127
|
-
//
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
let score = jaccard(a.grams, b.grams);
|
|
131
|
-
let hit = score >= SIMILAR_RATIO;
|
|
132
|
-
if (!hit) {
|
|
133
|
-
const [short, long, shortSize] = a.size <= b.size ? [a.key, b.key, a.size] : [b.key, a.key, b.size];
|
|
134
|
-
if (shortSize >= SIMILAR_SHORT && long.includes(short)) {
|
|
135
|
-
hit = true;
|
|
136
|
-
score = SIMILAR_RATIO;
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
if (!hit)
|
|
108
|
+
// 相似判定只有 similar.ts 一份:短标题(< 4 码点)也由它挡掉
|
|
109
|
+
const score = similarScore(a, b);
|
|
110
|
+
if (score === null)
|
|
140
111
|
continue;
|
|
141
112
|
found.push({
|
|
142
113
|
titles: [a.title, b.title],
|
|
143
114
|
paths: [a.path, b.path],
|
|
144
|
-
score
|
|
115
|
+
score,
|
|
145
116
|
});
|
|
146
117
|
}
|
|
147
118
|
}
|
|
@@ -211,10 +182,13 @@ export function memoryLinkIssues(cfg, notes, opts = {}) {
|
|
|
211
182
|
}
|
|
212
183
|
// 只对 MEMORY.md 数「没附来源 / 没日期 / 退役 / 陈旧」:USER.md 是偏好清单,大多数条目本来就没有来源
|
|
213
184
|
if (name === 'MEMORY.md') {
|
|
185
|
+
// 日期 / 来源缺口取唯一口径 memoryFormatDebt(退役条目不算、`[[ ]]` 不算来源),
|
|
186
|
+
// 注入提示与记忆页用的也是它 —— 同一个「N 条没来源」不许在三处给出三个数。
|
|
187
|
+
const debt = memoryFormatDebt(body);
|
|
188
|
+
undated = debt.undated;
|
|
189
|
+
unlinked = debt.unlinked;
|
|
214
190
|
for (const entry of splitMemoryEntries(body)) {
|
|
215
191
|
const first = entry.split('\n', 1)[0] ?? '';
|
|
216
|
-
if (!entry.includes('[['))
|
|
217
|
-
unlinked += 1;
|
|
218
192
|
// 退役行:磁盘保留、注入从 0.9 起省略(D3),只核对它指向的新结论是否还活着
|
|
219
193
|
if (isRetiredEntry(entry)) {
|
|
220
194
|
retired += 1;
|
|
@@ -226,10 +200,8 @@ export function memoryLinkIssues(cfg, notes, opts = {}) {
|
|
|
226
200
|
}
|
|
227
201
|
// 日期要真校验:`2026-99-99` 既不算「有日期」,也不该在陈旧里报一次
|
|
228
202
|
const date = entryDate(entry);
|
|
229
|
-
if (!date)
|
|
230
|
-
undated += 1;
|
|
203
|
+
if (!date)
|
|
231
204
|
continue;
|
|
232
|
-
}
|
|
233
205
|
const age = daysSinceDate(date, now);
|
|
234
206
|
if (age !== null && age > staleDays) {
|
|
235
207
|
staleTotal += 1;
|
|
@@ -501,7 +473,6 @@ export function tagHygiene(notes, max = 20) {
|
|
|
501
473
|
singletons: { total: singletons.length, items: singletons.slice(0, 10) },
|
|
502
474
|
};
|
|
503
475
|
}
|
|
504
|
-
const TEMPLATE_MARK_RE = /<!--\s*zdiary-template:\s*v(\d+)\s*-->/;
|
|
505
476
|
const PERSONA_MARK_RE = /<!--\s*zdiary-persona:\s*v(\d+)\s*-->/;
|
|
506
477
|
const PLACEHOLDER_RE = /\{\{\s*[^}]+\s*\}\}/g;
|
|
507
478
|
/**
|
|
@@ -594,8 +565,7 @@ export function templateStatus(cfg) {
|
|
|
594
565
|
catch {
|
|
595
566
|
return { present: false, version: 0, current: TEMPLATE_VERSION, stale: false };
|
|
596
567
|
}
|
|
597
|
-
const
|
|
598
|
-
const version = hit ? Number(hit[1]) : 0;
|
|
568
|
+
const version = templateVersionOf(body);
|
|
599
569
|
const mismatchDetail = version === TEMPLATE_VERSION
|
|
600
570
|
? sentinelIssue(body, TEMPLATE_SENTINELS[TEMPLATE_VERSION])
|
|
601
571
|
: null;
|
|
@@ -707,10 +677,6 @@ export async function lintNotebook(cfg, opts = {}, signal) {
|
|
|
707
677
|
const orphanAbs = await notesWithFlag(cfg, '--orphan', signal);
|
|
708
678
|
const brokenAbs = await notesWithFlag(cfg, '--broken-links', signal);
|
|
709
679
|
const taglessAbs = await notesWithFlag(cfg, '--tagless', signal);
|
|
710
|
-
const graph = await graphEdges(cfg, signal);
|
|
711
|
-
const edges = graph.edges;
|
|
712
|
-
// 图里的路径是笔记本相对:先拼回绝对路径再判断是不是日记(isDaily 收的是绝对路径)
|
|
713
|
-
const oneWay = oneWayLinks(edges, notes, (p) => isDaily(path.resolve(cfg.notebook, p)));
|
|
714
680
|
// 别用 `path.resolve(n.absPath || n.path)`:absPath 缺失时相对路径会按进程 cwd 解析,键就错了。
|
|
715
681
|
const byAbs = new Map(notes.map((n) => [n.absPath ? path.resolve(n.absPath) : path.resolve(cfg.notebook, n.path), n]));
|
|
716
682
|
const byPath = new Map(notes.map((n) => [n.path, n]));
|
|
@@ -758,11 +724,122 @@ export async function lintNotebook(cfg, opts = {}, signal) {
|
|
|
758
724
|
return 'body';
|
|
759
725
|
return starts.some((s) => s >= section.start && s < section.end) ? 'links' : 'body';
|
|
760
726
|
};
|
|
727
|
+
// ── 单向链接:小库一次全图;大库按篇反查(plan §0.5.1 结论 3)─────────────
|
|
728
|
+
// 全图在 10k / 1 链要 26–31 s / 17 MB,2–5 链会直接超过 60 s 超时;
|
|
729
|
+
// 单篇反链已经走 `backlinksOf`,巡检在超过预算时也走同一条路。
|
|
730
|
+
const sourceTextCache = new Map();
|
|
731
|
+
const sourceText = (rel) => {
|
|
732
|
+
const cached = sourceTextCache.get(rel);
|
|
733
|
+
if (cached !== undefined)
|
|
734
|
+
return cached;
|
|
735
|
+
let text = '';
|
|
736
|
+
try {
|
|
737
|
+
text = fs.readFileSync(path.resolve(cfg.notebook, rel), 'utf8');
|
|
738
|
+
}
|
|
739
|
+
catch {
|
|
740
|
+
text = '';
|
|
741
|
+
}
|
|
742
|
+
sourceTextCache.set(rel, text);
|
|
743
|
+
return text;
|
|
744
|
+
};
|
|
745
|
+
/** 按篇反查没有 snippetStart:自己扫源文件,判断链接写在 Links 小节还是正文 */
|
|
746
|
+
const linkWhereOf = (sourceRel, targetRel) => {
|
|
747
|
+
const text = sourceText(sourceRel);
|
|
748
|
+
if (!text)
|
|
749
|
+
return 'body';
|
|
750
|
+
const keys = new Set([targetRel, targetRel.replace(/\.md$/i, ''), path.basename(targetRel, path.extname(targetRel)), byPath.get(targetRel)?.title ?? '']
|
|
751
|
+
.map((k) => normalizeTitle(k))
|
|
752
|
+
.filter(Boolean));
|
|
753
|
+
const head = /^##[ \t]+(?:Links|链接)[ \t]*\r?$/m.exec(text);
|
|
754
|
+
let start = -1;
|
|
755
|
+
let end = -1;
|
|
756
|
+
if (head) {
|
|
757
|
+
start = head.index + head[0].length;
|
|
758
|
+
const next = /^#{1,2}[ \t]+\S/m.exec(text.slice(start));
|
|
759
|
+
end = next ? start + next.index : text.length;
|
|
760
|
+
}
|
|
761
|
+
for (const m of text.matchAll(WIKI_LINK)) {
|
|
762
|
+
if (!keys.has(normalizeTitle(String(m[1] ?? ''))))
|
|
763
|
+
continue;
|
|
764
|
+
const at = m.index ?? 0;
|
|
765
|
+
if (start >= 0 && at >= start && at < end)
|
|
766
|
+
return 'links';
|
|
767
|
+
}
|
|
768
|
+
return 'body';
|
|
769
|
+
};
|
|
770
|
+
/**
|
|
771
|
+
* 大库的单向链接:zk 先给「缺回链的目标」(一次 `--missing-backlink`),
|
|
772
|
+
* 再对每个目标 `--link-to` 取来源、对每个来源 `--linked-by` 判回链(缓存)。
|
|
773
|
+
* 成本随问题数增长,而不是随库大小增长;触到上限就报 partial,不静默少报。
|
|
774
|
+
*/
|
|
775
|
+
const oneWayByQueries = async () => {
|
|
776
|
+
let left = MAX_ONE_WAY_QUERIES;
|
|
777
|
+
const spend = () => (left > 0 ? ((left -= 1), true) : false);
|
|
778
|
+
const missingAbs = await notesWithFlag(cfg, '--missing-backlink', signal);
|
|
779
|
+
const targets = missingAbs
|
|
780
|
+
.map((abs) => path.relative(cfg.notebook, abs).split(path.sep).join('/'))
|
|
781
|
+
.filter((rel) => byPath.has(rel) && !isDaily(path.resolve(cfg.notebook, rel)))
|
|
782
|
+
.sort((a, b) => a.localeCompare(b));
|
|
783
|
+
const capped = targets.slice(0, MAX_ONE_WAY_TARGETS);
|
|
784
|
+
let truncated = targets.length > capped.length;
|
|
785
|
+
const rows = [];
|
|
786
|
+
for (const target of capped) {
|
|
787
|
+
if (!spend()) {
|
|
788
|
+
truncated = true;
|
|
789
|
+
break;
|
|
790
|
+
}
|
|
791
|
+
const back = await backlinksOf(cfg, target, { limit: MAX_SCAN }, signal);
|
|
792
|
+
if (back.truncated)
|
|
793
|
+
truncated = true;
|
|
794
|
+
if (!back.notes.length)
|
|
795
|
+
continue;
|
|
796
|
+
if (!spend()) {
|
|
797
|
+
truncated = true;
|
|
798
|
+
break;
|
|
799
|
+
}
|
|
800
|
+
// 回链方向是 T → S:取目标自己的出链,看它有没有连回来源
|
|
801
|
+
const linked = await outlinksOf(cfg, target, { limit: MAX_SCAN }, signal);
|
|
802
|
+
if (linked.truncated)
|
|
803
|
+
truncated = true;
|
|
804
|
+
const outs = new Set(linked.notes.map((n) => n.path));
|
|
805
|
+
const from = [];
|
|
806
|
+
for (const note of back.notes) {
|
|
807
|
+
if (note.path === target || isDaily(path.resolve(cfg.notebook, note.path)))
|
|
808
|
+
continue;
|
|
809
|
+
if (outs.has(note.path))
|
|
810
|
+
continue;
|
|
811
|
+
from.push({ path: note.path, where: linkWhereOf(note.path, target) });
|
|
812
|
+
}
|
|
813
|
+
if (from.length)
|
|
814
|
+
rows.push({ target, from: from.sort((a, b) => a.path.localeCompare(b.path)) });
|
|
815
|
+
}
|
|
816
|
+
return { rows, truncated };
|
|
817
|
+
};
|
|
818
|
+
// 预算来自配置(设置页可调);opts.graphBudget 只给测试覆盖
|
|
819
|
+
const graphBudget = Math.max(0, Math.trunc(opts.graphBudget ?? cfg.graphBudgetNotes ?? GRAPH_BUDGET_NOTES));
|
|
820
|
+
const oneWayRows = [];
|
|
821
|
+
let oneWayTruncated = false;
|
|
822
|
+
if (notes.length <= graphBudget) {
|
|
823
|
+
const graph = await graphEdges(cfg, signal);
|
|
824
|
+
oneWayTruncated = graph.truncated;
|
|
825
|
+
// 图里的路径是笔记本相对:先拼回绝对路径再判断是不是日记(isDaily 收的是绝对路径)
|
|
826
|
+
for (const row of oneWayLinks(graph.edges, notes, (p) => isDaily(path.resolve(cfg.notebook, p)))) {
|
|
827
|
+
oneWayRows.push({
|
|
828
|
+
target: row.target,
|
|
829
|
+
from: row.from.map((s) => ({ path: s.path, where: whereOf(s.path, s.snippetStarts) })),
|
|
830
|
+
});
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
else {
|
|
834
|
+
const scanned = await oneWayByQueries();
|
|
835
|
+
oneWayRows.push(...scanned.rows);
|
|
836
|
+
oneWayTruncated = scanned.truncated;
|
|
837
|
+
}
|
|
761
838
|
const linksOnly = opts.linksOnly === true;
|
|
762
839
|
const oneWayItems = [];
|
|
763
840
|
let oneWayEdges = 0;
|
|
764
841
|
let bodyOnly = 0;
|
|
765
|
-
for (const row of
|
|
842
|
+
for (const row of oneWayRows) {
|
|
766
843
|
// 目标也不报日记:普通笔记链到日记("今天做了 X")同样是正常引用方向,
|
|
767
844
|
// 要求日记回链每篇被提到的笔记,跟要求笔记回链日记是同一个问题。
|
|
768
845
|
if (isDaily(path.resolve(cfg.notebook, row.target)))
|
|
@@ -775,7 +852,7 @@ export async function lintNotebook(cfg, opts = {}, signal) {
|
|
|
775
852
|
const body = [];
|
|
776
853
|
for (const source of row.from) {
|
|
777
854
|
all.push(source.path);
|
|
778
|
-
if (
|
|
855
|
+
if (source.where === 'links')
|
|
779
856
|
links.push(source.path);
|
|
780
857
|
else
|
|
781
858
|
body.push(source.path);
|
|
@@ -809,7 +886,7 @@ export async function lintNotebook(cfg, opts = {}, signal) {
|
|
|
809
886
|
edges: oneWayEdges,
|
|
810
887
|
bodyOnly,
|
|
811
888
|
linksOnly,
|
|
812
|
-
edgesTruncated:
|
|
889
|
+
edgesTruncated: oneWayTruncated,
|
|
813
890
|
items: oneWayItems.slice(0, MAX_ITEMS),
|
|
814
891
|
};
|
|
815
892
|
const parseErrors = parseErrorWarnings(cfg, warnings);
|
|
@@ -60,6 +60,29 @@ export function entryDate(entry) {
|
|
|
60
60
|
return null;
|
|
61
61
|
return validDate(m[1], m[2], m[3]) ? `${m[1]}-${m[2]}-${m[3]}` : null;
|
|
62
62
|
}
|
|
63
|
+
/**
|
|
64
|
+
* 条目里的双链来源;只看写没写,链接是否真存在是 lint 的事。
|
|
65
|
+
* 目标是「非空白」:`[[ ]]` 不算来源(lint 的 `WIKI_LINK` 也把空目标当没链接),
|
|
66
|
+
* `[[目标|别名]]` / `[[目标#小节]]` 算。
|
|
67
|
+
*/
|
|
68
|
+
const LINK = /\[\[[^\]\n]*\S[^\]\n]*\]\]/;
|
|
69
|
+
/**
|
|
70
|
+
* 数一遍格式债:只机械计数,不猜日期、不补来源 —— 两者仍由人和 agent 写。
|
|
71
|
+
* 注入与记忆页只负责把缺口摆出来,否则「按日期淘汰」对没日期的老库永远空转。
|
|
72
|
+
* 退役条目不算:它们按约定退役,不该因为格式被继续提醒。
|
|
73
|
+
*/
|
|
74
|
+
export function memoryFormatDebt(body) {
|
|
75
|
+
const entries = splitMemoryEntries(body).filter((entry) => !isRetiredEntry(entry));
|
|
76
|
+
let undated = 0;
|
|
77
|
+
let unlinked = 0;
|
|
78
|
+
for (const entry of entries) {
|
|
79
|
+
if (!entryDate(entry))
|
|
80
|
+
undated += 1;
|
|
81
|
+
if (!LINK.test(entry))
|
|
82
|
+
unlinked += 1;
|
|
83
|
+
}
|
|
84
|
+
return { total: entries.length, undated, unlinked };
|
|
85
|
+
}
|
|
63
86
|
/**
|
|
64
87
|
* 去掉退役条目(整条,不留半行),返回正文与删掉的条数。
|
|
65
88
|
* 磁盘上的文件不动 —— 省略只发生在注入路径上;记忆页 / git 仍看得到它们。
|
package/dist/lib/memory.js
CHANGED
|
@@ -25,7 +25,8 @@ 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,
|
|
28
|
+
import { entryDate, memoryFormatDebt, stripRetiredEntries } from './memory-format.js';
|
|
29
|
+
import { templateVersionOf } from './agents-template.js';
|
|
29
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;
|
|
@@ -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 });
|
|
@@ -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(';')})` : '';
|
|
@@ -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,
|
package/dist/lib/notebook.js
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
*/
|
|
12
12
|
import fs from 'node:fs';
|
|
13
13
|
import path from 'node:path';
|
|
14
|
-
import { assertNotArchiveCreate, ZkError, zk } from './zk.js';
|
|
14
|
+
import { assertNotArchiveCreate, indexPolicy, ZkError, zk } from './zk.js';
|
|
15
15
|
import { AGENTS_TEMPLATE, AGENTS_TEMPLATE_FLAT, WORKFLOW_TEMPLATE } from './agents-template.js';
|
|
16
16
|
import { PERSONA_TEMPLATE } from './persona-template.js';
|
|
17
17
|
import { effectivePaths, isPluginOwned, normGroupPath, parseGroupBlocks, sameGroupPath, samePaths } from './notebook-config.js';
|
|
@@ -367,7 +367,9 @@ export async function ensureNotebook(cfg, signal, opts = {}) {
|
|
|
367
367
|
const configFile = path.join(cfg.notebook, '.zk', 'config.toml');
|
|
368
368
|
let initialized = false;
|
|
369
369
|
if (!fs.existsSync(configFile)) {
|
|
370
|
-
|
|
370
|
+
// init 会把目录里已有的笔记一起索引进空库 —— 10k / 1 链实测 202 s,
|
|
371
|
+
// 原来的 120 s 会把进程杀在写事务里,留下半库。这里直接给建库预算(M5.0a)。
|
|
372
|
+
await zk(cfg, ['init', cfg.notebook], { signal, timeoutMs: indexPolicy.buildTimeoutMs });
|
|
371
373
|
initialized = true;
|
|
372
374
|
}
|
|
373
375
|
const templatesWritten = layered
|