dsh-zdiary-kit 0.7.6 → 0.9.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 +96 -16
- package/dist/app/plugin.js +54 -20
- package/dist/cli.js +170 -25
- package/dist/config/store.js +37 -0
- package/dist/features/readonly/feature.js +563 -0
- package/dist/features/readonly/html.js +255 -0
- package/dist/features/settings/client.js +32 -9
- package/dist/features/settings/feature.js +71 -17
- package/dist/features/zk-tools/feature.js +228 -42
- package/dist/lib/agents-template.js +49 -11
- package/dist/lib/dream.js +213 -16
- package/dist/lib/http.js +26 -0
- package/dist/lib/lint.js +329 -90
- package/dist/lib/memory-format.js +100 -0
- package/dist/lib/memory.js +201 -24
- package/dist/lib/notebook-config.js +188 -0
- package/dist/lib/notebook.js +357 -21
- package/dist/lib/wikilink.js +77 -0
- package/dist/lib/zk.js +108 -17
- package/docs/features/memory.md +76 -9
- package/docs/features/provisioning.md +47 -9
- package/docs/features/readonly.md +73 -0
- package/docs/features/settings.md +20 -6
- package/docs/features/zk-tools.md +64 -6
- package/package.json +1 -1
package/dist/lib/lint.js
CHANGED
|
@@ -24,13 +24,14 @@
|
|
|
24
24
|
import fs from 'node:fs';
|
|
25
25
|
import path from 'node:path';
|
|
26
26
|
import { allNotes, graphEdges, localDate, MAX_SCAN, notesWithFlag, parseErrorWarnings } from './zk.js';
|
|
27
|
+
import { normalizeTitle, resolveWikiTarget, WIKI_LINK, wikiIndex } from './wikilink.js';
|
|
27
28
|
import { parseFrontmatter } from './frontmatter.js';
|
|
29
|
+
import { daysSinceDate, entryDate, isRetiredEntry, splitMemoryEntries } from './memory-format.js';
|
|
30
|
+
import { AGENTS_TEMPLATE, AGENTS_TEMPLATE_FLAT, TEMPLATE_VERSION } from './agents-template.js';
|
|
28
31
|
/** 每类最多回多少条(计划 §4 M3);总数另给 */
|
|
29
32
|
export const MAX_ITEMS = 50;
|
|
30
|
-
/**
|
|
31
|
-
export
|
|
32
|
-
return String(title ?? '').replace(/\s+/g, ' ').trim().toLowerCase();
|
|
33
|
-
}
|
|
33
|
+
/** 标题归一化与链接解析在 `lib/wikilink.ts`(dream 也用同一套);这里保留导出,免得调用方跟着搬 */
|
|
34
|
+
export { normalizeTitle };
|
|
34
35
|
/** 同一标题出现在多篇里(slug 命名下不同目录可以同名,检索时容易挑错) */
|
|
35
36
|
export function duplicateTitles(notes, max = MAX_ITEMS) {
|
|
36
37
|
const groups = new Map();
|
|
@@ -48,54 +49,106 @@ export function duplicateTitles(notes, max = MAX_ITEMS) {
|
|
|
48
49
|
dup.sort((a, b) => b.paths.length - a.paths.length || a.title.localeCompare(b.title));
|
|
49
50
|
return { total: dup.length, items: dup.slice(0, max) };
|
|
50
51
|
}
|
|
51
|
-
/**
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
52
|
+
/** 相似标题的判定:字符二元组 Jaccard 下限;短串被长串包含时另算(短串至少 6 字) */
|
|
53
|
+
const SIMILAR_RATIO = 0.6;
|
|
54
|
+
const SIMILAR_SHORT = 6;
|
|
55
|
+
/** 同目录最多两两比较多少篇:超过就截断并置 truncated,别让 1 万篇变成 O(n²) */
|
|
56
|
+
const SIMILAR_GROUP_MAX = 300;
|
|
57
|
+
/** 比较用的标题:NFKC → 小写 → 去标点 / 空白。中文不改字,只抹掉排版差异 */
|
|
58
|
+
function similarKey(title) {
|
|
59
|
+
return String(title ?? '').normalize('NFKC').toLowerCase().replace(/[\s\p{P}\p{S}]/gu, '');
|
|
60
|
+
}
|
|
61
|
+
function bigrams(key) {
|
|
62
|
+
const chars = [...key];
|
|
63
|
+
const out = new Set();
|
|
64
|
+
for (let i = 0; i < chars.length - 1; i++)
|
|
65
|
+
out.add(chars[i] + chars[i + 1]);
|
|
66
|
+
if (out.size === 0 && chars.length > 0)
|
|
67
|
+
out.add(chars[0]);
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
function jaccard(a, b) {
|
|
71
|
+
if (a.size === 0 || b.size === 0)
|
|
72
|
+
return 0;
|
|
73
|
+
let shared = 0;
|
|
74
|
+
for (const gram of a)
|
|
75
|
+
if (b.has(gram))
|
|
76
|
+
shared += 1;
|
|
77
|
+
return shared / (a.size + b.size - shared);
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* 疑似重复标题(P2-10):精确查重只能挡住手滑 —— 中文改两个字就绕过去了。
|
|
81
|
+
*
|
|
82
|
+
* 纯机械:NFKC + 去标点后按字符二元组算 Jaccard ≥ 0.6,或短串(≥ 6 字)被长串包含。
|
|
83
|
+
* 只在**同目录**内比较(不同目录的同名本来允许);全等标题留给 duplicateTitles,这里不重复报。
|
|
84
|
+
* 只报告:`zk_new` 不用它拦人,误报会挡住正常写作。
|
|
85
|
+
*
|
|
86
|
+
* 日记不进来(由调用方按 `isDaily` 过滤):标题就是日期,`2026-10-01` 与 `2026-10-02`
|
|
87
|
+
* 的二元组 Jaccard 是 0.86 —— 一年日记会吐出上千组「疑似重复」,真问题全被淹掉。
|
|
88
|
+
* 纯数字标题(日期 / 编号)同样跳过:那是「按天 / 按号」的记录,不是同一个结论写了两遍。
|
|
89
|
+
*/
|
|
90
|
+
export function similarTitles(notes, scanTruncated, max = MAX_ITEMS) {
|
|
91
|
+
const groups = new Map();
|
|
92
|
+
for (const note of notes) {
|
|
93
|
+
const title = note.title || path.basename(note.path, path.extname(note.path));
|
|
94
|
+
const key = similarKey(title);
|
|
95
|
+
if (!key)
|
|
96
|
+
continue;
|
|
97
|
+
// 纯数字:日期 / 编号类标题,相似度只反映「数字挨着」,不反映重复结论
|
|
98
|
+
if (/^\d+$/.test(key))
|
|
99
|
+
continue;
|
|
100
|
+
const dir = path.posix.dirname(note.path);
|
|
101
|
+
const list = groups.get(dir) ?? [];
|
|
102
|
+
list.push({ title, path: note.path, key, exact: normalizeTitle(title), grams: bigrams(key), size: [...key].length });
|
|
103
|
+
groups.set(dir, list);
|
|
104
|
+
}
|
|
105
|
+
let truncated = scanTruncated;
|
|
106
|
+
const found = [];
|
|
107
|
+
for (const group of groups.values()) {
|
|
108
|
+
let list = group;
|
|
109
|
+
if (list.length > SIMILAR_GROUP_MAX) {
|
|
110
|
+
truncated = true;
|
|
111
|
+
list = list.slice(0, SIMILAR_GROUP_MAX);
|
|
71
112
|
}
|
|
72
|
-
|
|
73
|
-
|
|
113
|
+
for (let i = 0; i < list.length; i++) {
|
|
114
|
+
for (let j = i + 1; j < list.length; j++) {
|
|
115
|
+
const a = list[i];
|
|
116
|
+
const b = list[j];
|
|
117
|
+
// 归一化后完全一样:那是 duplicateTitles 的活(这里报会让同一件事出现两遍)
|
|
118
|
+
if (a.exact === b.exact)
|
|
119
|
+
continue;
|
|
120
|
+
// 短标题的二元组太少(RAG / RAG 2 会算出 0.67),噪声大于信号
|
|
121
|
+
if (a.size < 4 || b.size < 4)
|
|
122
|
+
continue;
|
|
123
|
+
let score = jaccard(a.grams, b.grams);
|
|
124
|
+
let hit = score >= SIMILAR_RATIO;
|
|
125
|
+
if (!hit) {
|
|
126
|
+
const [short, long, shortSize] = a.size <= b.size ? [a.key, b.key, a.size] : [b.key, a.key, b.size];
|
|
127
|
+
if (shortSize >= SIMILAR_SHORT && long.includes(short)) {
|
|
128
|
+
hit = true;
|
|
129
|
+
score = SIMILAR_RATIO;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
if (!hit)
|
|
133
|
+
continue;
|
|
134
|
+
found.push({
|
|
135
|
+
titles: [a.title, b.title],
|
|
136
|
+
paths: [a.path, b.path],
|
|
137
|
+
score: Math.round(score * 100) / 100,
|
|
138
|
+
});
|
|
139
|
+
}
|
|
74
140
|
}
|
|
75
141
|
}
|
|
76
|
-
|
|
77
|
-
return
|
|
142
|
+
found.sort((a, b) => b.score - a.score || a.paths[0].localeCompare(b.paths[0]));
|
|
143
|
+
return { total: found.length, truncated, items: found.slice(0, max) };
|
|
78
144
|
}
|
|
145
|
+
/** 注入的三份 meta 里只有 MEMORY / USER 会写来源链接;AGENTS 是规则,不查 */
|
|
146
|
+
const MEMORY_LINK_FILES = ['MEMORY.md', 'USER.md'];
|
|
147
|
+
/** 按列表条目切分(含缩进续行):只有条目才谈得上「没附来源」 */
|
|
79
148
|
function collapse(text, max = 100) {
|
|
80
149
|
const one = text.replace(/\s+/g, ' ').trim();
|
|
81
150
|
return one.length > max ? one.slice(0, max) + '…' : one;
|
|
82
151
|
}
|
|
83
|
-
function insideNotebook(cfg, abs) {
|
|
84
|
-
const root = path.resolve(cfg.notebook);
|
|
85
|
-
const p = path.resolve(abs);
|
|
86
|
-
return p === root || p.startsWith(root + path.sep);
|
|
87
|
-
}
|
|
88
|
-
function statusOf(abs) {
|
|
89
|
-
try {
|
|
90
|
-
return parseFrontmatter(fs.readFileSync(abs, 'utf8')).fields.status ?? '';
|
|
91
|
-
}
|
|
92
|
-
catch {
|
|
93
|
-
return '';
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
function relOf(cfg, abs) {
|
|
97
|
-
return path.relative(cfg.notebook, abs).split(path.sep).join('/');
|
|
98
|
-
}
|
|
99
152
|
/**
|
|
100
153
|
* 记忆层体检:MEMORY.md / USER.md 里的 `[[来源]]` 是否还指向活笔记。
|
|
101
154
|
*
|
|
@@ -106,49 +159,21 @@ function relOf(cfg, abs) {
|
|
|
106
159
|
* 纯机械解析:路径优先(原路径 → 加 .md → archive/ 下同名),退而按标题/文件名匹配**活笔记**;
|
|
107
160
|
* 归档标题不反查 —— 归档默认不进检索,这里再造一套索引就成了第二真相。「语义重复」也不查。
|
|
108
161
|
*/
|
|
109
|
-
export function memoryLinkIssues(cfg, notes,
|
|
110
|
-
const
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
}
|
|
162
|
+
export function memoryLinkIssues(cfg, notes, opts = {}) {
|
|
163
|
+
const max = opts.max ?? MAX_ITEMS;
|
|
164
|
+
const staleDays = Math.min(3650, Math.max(1, Math.trunc(opts.staleDays ?? 90)));
|
|
165
|
+
const now = opts.now ?? new Date();
|
|
166
|
+
const index = wikiIndex(notes);
|
|
115
167
|
const items = [];
|
|
168
|
+
const staleItems = [];
|
|
116
169
|
const seen = new Set();
|
|
117
170
|
let files = 0;
|
|
118
171
|
let links = 0;
|
|
119
172
|
let unlinked = 0;
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
return null;
|
|
125
|
-
const candidates = /\.md$/i.test(rel) ? [rel] : [rel, `${rel}.md`];
|
|
126
|
-
for (const candidate of candidates) {
|
|
127
|
-
const abs = path.resolve(cfg.notebook, candidate);
|
|
128
|
-
if (!insideNotebook(cfg, abs) || !fs.existsSync(abs) || !fs.statSync(abs).isFile())
|
|
129
|
-
continue;
|
|
130
|
-
const hit = relOf(cfg, abs);
|
|
131
|
-
// 显式写 archive/ 路径 = 有意引用旧结论(supersede 就是这样重写入链的),不算漂移
|
|
132
|
-
if (hit === cfg.archiveDir || hit.startsWith(`${cfg.archiveDir}/`))
|
|
133
|
-
return null;
|
|
134
|
-
return statusOf(abs) === 'superseded'
|
|
135
|
-
? { reason: 'superseded', path: hit }
|
|
136
|
-
: null;
|
|
137
|
-
}
|
|
138
|
-
// 链接还停在废弃前的路径:文件已经搬进 archive/ —— 这正是要抓的漂移
|
|
139
|
-
if (!rel.startsWith(`${cfg.archiveDir}/`)) {
|
|
140
|
-
for (const candidate of candidates) {
|
|
141
|
-
const abs = path.resolve(cfg.notebook, cfg.archiveDir, candidate);
|
|
142
|
-
if (!insideNotebook(cfg, abs) || !fs.existsSync(abs) || !fs.statSync(abs).isFile())
|
|
143
|
-
continue;
|
|
144
|
-
return { reason: 'superseded', path: relOf(cfg, abs) };
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
// 标题式链接只在活笔记里找(zk 的 wiki 链接两种写法都认)
|
|
148
|
-
if (titles.has(normalizeTitle(rel)))
|
|
149
|
-
return null;
|
|
150
|
-
return { reason: 'missing', path: '' };
|
|
151
|
-
};
|
|
173
|
+
let undated = 0;
|
|
174
|
+
let retired = 0;
|
|
175
|
+
let retiredBroken = 0;
|
|
176
|
+
let staleTotal = 0;
|
|
152
177
|
for (const name of MEMORY_LINK_FILES) {
|
|
153
178
|
let body = '';
|
|
154
179
|
try {
|
|
@@ -162,9 +187,14 @@ export function memoryLinkIssues(cfg, notes, max = MAX_ITEMS) {
|
|
|
162
187
|
for (const match of line.matchAll(WIKI_LINK)) {
|
|
163
188
|
links += 1;
|
|
164
189
|
const target = String(match[1] ?? '').trim();
|
|
165
|
-
|
|
166
|
-
if (!
|
|
190
|
+
// `[[ ]]` 这种空目标不是链接,也不该算「失效」:解析器对它返回 missing
|
|
191
|
+
if (!target)
|
|
192
|
+
continue;
|
|
193
|
+
const resolved = resolveWikiTarget(cfg, target, index);
|
|
194
|
+
// 显式写 archive/ 路径的链接是有意引用旧结论(supersede 重写入链就是这个形状),不算漂移
|
|
195
|
+
if (resolved.status === 'live' || resolved.explicit)
|
|
167
196
|
continue;
|
|
197
|
+
const issue = { reason: resolved.status === 'archived' ? 'superseded' : 'missing', path: resolved.path };
|
|
168
198
|
const key = `${name}\u0000${target}`;
|
|
169
199
|
if (seen.has(key))
|
|
170
200
|
continue;
|
|
@@ -172,12 +202,47 @@ export function memoryLinkIssues(cfg, notes, max = MAX_ITEMS) {
|
|
|
172
202
|
items.push({ source: name, entry: collapse(line), link: target, reason: issue.reason, path: issue.path });
|
|
173
203
|
}
|
|
174
204
|
}
|
|
175
|
-
// 只对 MEMORY.md
|
|
205
|
+
// 只对 MEMORY.md 数「没附来源 / 没日期 / 退役 / 陈旧」:USER.md 是偏好清单,大多数条目本来就没有来源
|
|
176
206
|
if (name === 'MEMORY.md') {
|
|
177
|
-
|
|
207
|
+
for (const entry of splitMemoryEntries(body)) {
|
|
208
|
+
const first = entry.split('\n', 1)[0] ?? '';
|
|
209
|
+
if (!entry.includes('[['))
|
|
210
|
+
unlinked += 1;
|
|
211
|
+
// 退役行:磁盘保留、注入从 0.9 起省略(D3),只核对它指向的新结论是否还活着
|
|
212
|
+
if (isRetiredEntry(entry)) {
|
|
213
|
+
retired += 1;
|
|
214
|
+
const next = /→\s*\[\[([^\]|#]+)/.exec(entry);
|
|
215
|
+
const resolved = next ? resolveWikiTarget(cfg, String(next[1] ?? '').trim(), index) : null;
|
|
216
|
+
if (!resolved || resolved.status !== 'live')
|
|
217
|
+
retiredBroken += 1;
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
// 日期要真校验:`2026-99-99` 既不算「有日期」,也不该在陈旧里报一次
|
|
221
|
+
const date = entryDate(entry);
|
|
222
|
+
if (!date) {
|
|
223
|
+
undated += 1;
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
const age = daysSinceDate(date, now);
|
|
227
|
+
if (age !== null && age > staleDays) {
|
|
228
|
+
staleTotal += 1;
|
|
229
|
+
if (staleItems.length < max)
|
|
230
|
+
staleItems.push({ entry: collapse(first), date, age });
|
|
231
|
+
}
|
|
232
|
+
}
|
|
178
233
|
}
|
|
179
234
|
}
|
|
180
|
-
return {
|
|
235
|
+
return {
|
|
236
|
+
files,
|
|
237
|
+
links,
|
|
238
|
+
total: items.length,
|
|
239
|
+
unlinked,
|
|
240
|
+
undated,
|
|
241
|
+
retired,
|
|
242
|
+
retiredBroken,
|
|
243
|
+
stale: { total: staleTotal, staleDays, items: staleItems },
|
|
244
|
+
items: items.slice(0, max),
|
|
245
|
+
};
|
|
181
246
|
}
|
|
182
247
|
/**
|
|
183
248
|
* 一行「记忆链接」摘要:`zk-kit lint` 与 `zk_lint` 共用,免得两处各写一遍文案、
|
|
@@ -199,7 +264,71 @@ export function formatMemoryLinks(bucket) {
|
|
|
199
264
|
}
|
|
200
265
|
if (bucket.unlinked > 0)
|
|
201
266
|
parts.push(`${bucket.unlinked} 个条目没附来源链接`);
|
|
202
|
-
|
|
267
|
+
if (bucket.undated > 0)
|
|
268
|
+
parts.push(`${bucket.undated} 个条目没写日期(YYYY-MM-DD)`);
|
|
269
|
+
if (bucket.retired > 0) {
|
|
270
|
+
parts.push(bucket.retiredBroken > 0
|
|
271
|
+
? `${bucket.retired} 条已退役,其中 ${bucket.retiredBroken} 条的新结论不是活笔记`
|
|
272
|
+
: `${bucket.retired} 条已退役`);
|
|
273
|
+
}
|
|
274
|
+
if (bucket.stale.total > 0)
|
|
275
|
+
parts.push(`${bucket.stale.total} 条超过 ${bucket.stale.staleDays} 天未复核`);
|
|
276
|
+
return `${bucket.total === 0 && bucket.retiredBroken === 0 ? '✓' : '✗'} 记忆链接:${parts.join('|')}`;
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* 三个后加的桶(缺字段 / 标签卫生 / 模板版本)的文案,同样只写一份:
|
|
280
|
+
* `zk-kit lint` 与 `zk_lint` 各写一遍就会改到一半。返回空数组 = 这一库三项都没问题,不占行。
|
|
281
|
+
*/
|
|
282
|
+
export function formatLintExtras(r) {
|
|
283
|
+
const lines = [];
|
|
284
|
+
if (r.incomplete.total > 0) {
|
|
285
|
+
lines.push(`✗ frontmatter 缺字段:${r.incomplete.total} 篇 — ` +
|
|
286
|
+
r.incomplete.items.slice(0, 5).map((i) => `${i.path}(缺 ${i.missing.join('/')})`).join('、') +
|
|
287
|
+
(r.incomplete.total > 5 ? ' …' : '') +
|
|
288
|
+
'|缺失被索引落成空串,status / authority 的机械门对它们静默失效');
|
|
289
|
+
}
|
|
290
|
+
if (r.tags.reported) {
|
|
291
|
+
const cv = r.tags.caseVariants;
|
|
292
|
+
const sg = r.tags.singletons;
|
|
293
|
+
lines.push(cv.total === 0
|
|
294
|
+
? `✓ 标签卫生:${r.tags.total} 个标签,没有大小写变体;单例 ${sg.total} 个` +
|
|
295
|
+
(sg.items.length ? `(${sg.items.slice(0, 5).join('、')})` : '')
|
|
296
|
+
: `✗ 标签卫生:${cv.total} 组大小写变体 — ` +
|
|
297
|
+
cv.items.slice(0, 3).map((g) => `${g.variants.join(' / ')}(${g.total})`).join(';') +
|
|
298
|
+
`;单例 ${sg.total} 个`);
|
|
299
|
+
}
|
|
300
|
+
if (r.template.stale) {
|
|
301
|
+
const t = r.template;
|
|
302
|
+
if (t.version > t.current) {
|
|
303
|
+
// 插件比库旧(用户降级过插件 / 手写了更高标记):给旧模板等于让 agent 把规则改回去
|
|
304
|
+
lines.push(`⚠️ AGENTS.md 的模板版本比插件新(v${t.version} > 当前 v${t.current})—— ` +
|
|
305
|
+
'插件是旧的那个,别改文件去配它;升级插件后再看。这里不给旧模板,免得把规则改回去。');
|
|
306
|
+
}
|
|
307
|
+
else {
|
|
308
|
+
lines.push(`⚠️ AGENTS.md 是${t.version === 0 ? '旧版 / 无版本标记' : `旧版模板 v${t.version}`}` +
|
|
309
|
+
`(当前 v${t.current})—— 只报告,不覆盖。` +
|
|
310
|
+
(t.currentText
|
|
311
|
+
? `新版模板全文如下:按需合并,别整篇覆盖你改过的规则;合并后把首行标记更新为 v${t.current}。`
|
|
312
|
+
: ''));
|
|
313
|
+
if (t.currentText) {
|
|
314
|
+
lines.push('--- 新版模板开始 ---');
|
|
315
|
+
lines.push(t.currentText.trimEnd());
|
|
316
|
+
lines.push('--- 新版模板结束 ---');
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
if (r.similarTitles.total > 0) {
|
|
321
|
+
const sample = r.similarTitles.items.slice(0, 3)
|
|
322
|
+
.map((g) => `「${g.titles[0]}」/「${g.titles[1]}」(${g.score.toFixed(2)})`)
|
|
323
|
+
.join(';');
|
|
324
|
+
lines.push(`⚠️ 疑似重复标题:${r.similarTitles.total} 组 — ${sample}` +
|
|
325
|
+
(r.similarTitles.total > 3 ? ' …' : '') +
|
|
326
|
+
'|只报告,合并由人裁决');
|
|
327
|
+
}
|
|
328
|
+
if (r.indexHint) {
|
|
329
|
+
lines.push('· 笔记已到 150 篇(不含日记):根目录还没有 INDEX.md —— 需要总索引时再建(zk_stats 有实时目录 / 标签分布)');
|
|
330
|
+
}
|
|
331
|
+
return lines;
|
|
203
332
|
}
|
|
204
333
|
export function oneWayLinks(edges, notes, skipSource) {
|
|
205
334
|
const linked = new Set(edges.map((e) => e.sourcePath + '\u0000' + e.targetPath));
|
|
@@ -227,6 +356,103 @@ export function oneWayLinks(edges, notes, skipSource) {
|
|
|
227
356
|
.sort((a, b) => a.path.localeCompare(b.path)),
|
|
228
357
|
}));
|
|
229
358
|
}
|
|
359
|
+
/** 模板承诺的四个字段里,这三个是机械规则的前提(title 由文件名兜底,不查) */
|
|
360
|
+
const REQUIRED_FIELDS = ['type', 'status', 'authority'];
|
|
361
|
+
/**
|
|
362
|
+
* frontmatter 缺字段(P2-13):`toRecord` 把缺失的 status / type / authority 一律落成空串,
|
|
363
|
+
* 于是「没写 authority」=「authority 正常」—— dream 的 informal 门对它们静默失效。
|
|
364
|
+
* 索引里区分不出「没写」与「空值」,只能逐篇读 frontmatter;代价是 O(n) 次读盘,
|
|
365
|
+
* 护栏是只读 live 且非日记,扫描触到上限时置 truncated。
|
|
366
|
+
*
|
|
367
|
+
* 只在 layered 下检查:flat 的笔记本来就不写这三个字段(没有 group / 模板),
|
|
368
|
+
* 对它报这一桶等于把整个库标红,那就不是「可发现的状态」而是噪音。
|
|
369
|
+
*/
|
|
370
|
+
export function incompleteFrontmatter(cfg, notes, skip, scanTruncated, max = 20) {
|
|
371
|
+
const byField = { type: 0, status: 0, authority: 0 };
|
|
372
|
+
const items = [];
|
|
373
|
+
let total = 0;
|
|
374
|
+
for (const note of notes) {
|
|
375
|
+
if (skip(note.path))
|
|
376
|
+
continue;
|
|
377
|
+
let fields;
|
|
378
|
+
try {
|
|
379
|
+
fields = parseFrontmatter(fs.readFileSync(path.resolve(cfg.notebook, note.path), 'utf8')).fields;
|
|
380
|
+
}
|
|
381
|
+
catch {
|
|
382
|
+
continue;
|
|
383
|
+
}
|
|
384
|
+
const missing = REQUIRED_FIELDS.filter((key) => !String(fields[key] ?? '').trim());
|
|
385
|
+
if (!missing.length)
|
|
386
|
+
continue;
|
|
387
|
+
total += 1;
|
|
388
|
+
for (const key of missing)
|
|
389
|
+
byField[key] += 1;
|
|
390
|
+
if (items.length < max)
|
|
391
|
+
items.push({ path: note.path, missing });
|
|
392
|
+
}
|
|
393
|
+
return { total, truncated: scanTruncated, byField, items };
|
|
394
|
+
}
|
|
395
|
+
/** 小库不查标签卫生:20 个标签里出现几个单例是正常的,报出来只是噪音 */
|
|
396
|
+
const TAG_MIN = 30;
|
|
397
|
+
/**
|
|
398
|
+
* 标签卫生(P2-14):标签是中文召回的补丁,补丁自己的卫生没人看。
|
|
399
|
+
* 大小写变体纯机械可判(`#Agent` / `#agent`),单例标签是「写了一次就再没出现」的那批。
|
|
400
|
+
* 只报告,不合并 —— 在别的库里它们可能就是两个概念,裁决留给人。
|
|
401
|
+
*/
|
|
402
|
+
export function tagHygiene(notes, max = 20) {
|
|
403
|
+
const counts = new Map();
|
|
404
|
+
for (const note of notes)
|
|
405
|
+
for (const tag of note.tags)
|
|
406
|
+
counts.set(tag, (counts.get(tag) ?? 0) + 1);
|
|
407
|
+
const tags = [...counts.keys()];
|
|
408
|
+
if (tags.length < TAG_MIN) {
|
|
409
|
+
return { total: tags.length, reported: false, caseVariants: { total: 0, items: [] }, singletons: { total: 0, items: [] } };
|
|
410
|
+
}
|
|
411
|
+
const groups = new Map();
|
|
412
|
+
for (const tag of tags) {
|
|
413
|
+
const key = tag.toLowerCase();
|
|
414
|
+
const list = groups.get(key) ?? [];
|
|
415
|
+
list.push(tag);
|
|
416
|
+
groups.set(key, list);
|
|
417
|
+
}
|
|
418
|
+
const variants = [...groups.values()]
|
|
419
|
+
.filter((group) => group.length > 1)
|
|
420
|
+
.map((group) => {
|
|
421
|
+
group.sort((a, b) => (counts.get(b) ?? 0) - (counts.get(a) ?? 0) || a.localeCompare(b));
|
|
422
|
+
return { variants: group, total: group.reduce((sum, tag) => sum + (counts.get(tag) ?? 0), 0) };
|
|
423
|
+
})
|
|
424
|
+
.sort((a, b) => b.total - a.total || a.variants[0].localeCompare(b.variants[0]));
|
|
425
|
+
const singletons = tags.filter((tag) => counts.get(tag) === 1).sort((a, b) => a.localeCompare(b));
|
|
426
|
+
return {
|
|
427
|
+
total: tags.length,
|
|
428
|
+
reported: true,
|
|
429
|
+
caseVariants: { total: variants.length, items: variants.slice(0, max) },
|
|
430
|
+
singletons: { total: singletons.length, items: singletons.slice(0, 10) },
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
const TEMPLATE_MARK_RE = /<!--\s*zdiary-template:\s*v(\d+)\s*-->/;
|
|
434
|
+
/**
|
|
435
|
+
* 模板版本(P2-15):模板是行为契约,不是静态文档 —— 它每轮注入,写错一句就是每轮都在执行错规则。
|
|
436
|
+
* 但模板允许用户改,不能自动覆盖;版本标记把「过期」变成可发现状态,只报告。
|
|
437
|
+
*/
|
|
438
|
+
export function templateStatus(cfg) {
|
|
439
|
+
let body = '';
|
|
440
|
+
try {
|
|
441
|
+
body = fs.readFileSync(path.join(cfg.notebook, 'AGENTS.md'), 'utf8');
|
|
442
|
+
}
|
|
443
|
+
catch {
|
|
444
|
+
return { present: false, version: 0, current: TEMPLATE_VERSION, stale: false };
|
|
445
|
+
}
|
|
446
|
+
const hit = TEMPLATE_MARK_RE.exec(body);
|
|
447
|
+
const version = hit ? Number(hit[1]) : 0;
|
|
448
|
+
const stale = version !== TEMPLATE_VERSION;
|
|
449
|
+
const base = { present: true, version, current: TEMPLATE_VERSION, stale };
|
|
450
|
+
// 不 stale 时不要留下 currentText: undefined —— 宿主按无损 JSON 校验,undefined 会让整次调用 invalid;
|
|
451
|
+
// 版本比插件新时也不给:那是插件该升级,不是用户该回退
|
|
452
|
+
return stale && version < TEMPLATE_VERSION
|
|
453
|
+
? { ...base, currentText: cfg.structure === 'flat' ? AGENTS_TEMPLATE_FLAT : AGENTS_TEMPLATE }
|
|
454
|
+
: base;
|
|
455
|
+
}
|
|
230
456
|
export async function lintNotebook(cfg, opts = {}, signal) {
|
|
231
457
|
const staleDays = Math.min(3650, Math.max(1, Math.trunc(opts.staleDays ?? 90)));
|
|
232
458
|
const now = opts.now ?? new Date();
|
|
@@ -347,6 +573,7 @@ export async function lintNotebook(cfg, opts = {}, signal) {
|
|
|
347
573
|
items: oneWayItems.slice(0, MAX_ITEMS),
|
|
348
574
|
};
|
|
349
575
|
const parseErrors = parseErrorWarnings(cfg, warnings);
|
|
576
|
+
const scanTruncated = notes.length >= MAX_SCAN;
|
|
350
577
|
const staleNotes = notes
|
|
351
578
|
.map((n) => ({ note: n, at: Date.parse(n.modified) }))
|
|
352
579
|
.filter((x) => Number.isFinite(x.at) && x.at < cutoff)
|
|
@@ -359,10 +586,13 @@ export async function lintNotebook(cfg, opts = {}, signal) {
|
|
|
359
586
|
modified: localDate(x.note.modified),
|
|
360
587
|
})),
|
|
361
588
|
};
|
|
589
|
+
// 日记不参与下面两项:标题就是日期(相似度必然高),篇数又按天自动增长
|
|
590
|
+
// (一年日记足以把任何库顶到 150 篇,可库里其实只有几十篇知识)。
|
|
591
|
+
const nonDaily = notes.filter((n) => !isDaily(path.resolve(cfg.notebook, n.path)));
|
|
362
592
|
return {
|
|
363
593
|
notebook: cfg.notebook,
|
|
364
594
|
notes: notes.length,
|
|
365
|
-
truncated:
|
|
595
|
+
truncated: scanTruncated,
|
|
366
596
|
staleDays,
|
|
367
597
|
parseErrors: { total: parseErrors.length, items: parseErrors.slice(0, MAX_ITEMS) },
|
|
368
598
|
orphans: bucket(orphanAbs.filter((abs) => !isDaily(abs))),
|
|
@@ -371,6 +601,15 @@ export async function lintNotebook(cfg, opts = {}, signal) {
|
|
|
371
601
|
tagless: bucket(taglessAbs.filter((abs) => !isDaily(abs))),
|
|
372
602
|
oneWayLinks: oneWayBucket,
|
|
373
603
|
duplicateTitles: duplicateTitles(notes),
|
|
374
|
-
|
|
604
|
+
// 日记按天写,标题就是日期:同类比较只会产出一堆误报(见 similarTitles 的注释)
|
|
605
|
+
similarTitles: similarTitles(nonDaily, scanTruncated),
|
|
606
|
+
memoryLinks: memoryLinkIssues(cfg, notes, { staleDays, now }),
|
|
607
|
+
incomplete: cfg.structure === 'layered'
|
|
608
|
+
? incompleteFrontmatter(cfg, notes, (rel) => isDaily(path.resolve(cfg.notebook, rel)), scanTruncated)
|
|
609
|
+
: { total: 0, truncated: false, byField: { type: 0, status: 0, authority: 0 }, items: [] },
|
|
610
|
+
tags: tagHygiene(notes),
|
|
611
|
+
template: templateStatus(cfg),
|
|
612
|
+
// 150 篇(不含日记)是检索开始变糊的拐点:提示一下,不生成静态索引(会过期,还要决定谁更新)
|
|
613
|
+
indexHint: nonDaily.length >= 150 && !fs.existsSync(path.join(cfg.notebook, 'INDEX.md')),
|
|
375
614
|
};
|
|
376
615
|
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 记忆条目的格式口径(唯一一份):memory / dream / lint 都从这里取,
|
|
3
|
+
* 免得「什么算退役」「哪一天算日期」三处各写一遍、下次改措辞只改到一半。
|
|
4
|
+
*
|
|
5
|
+
* 只做机械解析,不做语义判断:
|
|
6
|
+
* · 条目 = 顶层列表项 + 它的缩进续行(与 MEMORY.md 的书写约定一致);
|
|
7
|
+
* · 退役 = 首行 `- [superseded …]`(大小写不敏感);
|
|
8
|
+
* · 日期 = 首行里的 `YYYY-MM-DD`,且必须是真实存在的日期(`2026-99-99` 不算)。
|
|
9
|
+
*/
|
|
10
|
+
/** 顶层列表项;缩进的子项算续行,不另起一条 */
|
|
11
|
+
const LIST_ITEM = /^(?:[-*+]|\d+[.)])\s+/;
|
|
12
|
+
/** 退役条目:`- [superseded 2026-01-01] 旧结论 → [[新结论]]`。必须带 `i`,与 lint 同口径 */
|
|
13
|
+
const RETIRED = /^\s*(?:[-*+]|\d+[.)])\s+\[superseded\b/i;
|
|
14
|
+
/** 只认能机械解析的日期:`YYYY-MM-DD` 且真校验(不是正则通过就算) */
|
|
15
|
+
const DATE = /\b(\d{4})-(\d{2})-(\d{2})\b/;
|
|
16
|
+
function validDate(y, m, d) {
|
|
17
|
+
const year = Number(y);
|
|
18
|
+
const month = Number(m);
|
|
19
|
+
const day = Number(d);
|
|
20
|
+
const at = new Date(year, month - 1, day);
|
|
21
|
+
return at.getFullYear() === year && at.getMonth() === month - 1 && at.getDate() === day;
|
|
22
|
+
}
|
|
23
|
+
function firstLine(entry) {
|
|
24
|
+
return entry.split('\n', 1)[0] ?? '';
|
|
25
|
+
}
|
|
26
|
+
/** 列表条目(含缩进续行)。没有列表项的散文不算条目 —— 那是截断按段落处理的事 */
|
|
27
|
+
export function splitMemoryEntries(body) {
|
|
28
|
+
const out = [];
|
|
29
|
+
let current = null;
|
|
30
|
+
const flush = () => {
|
|
31
|
+
if (current)
|
|
32
|
+
out.push(current.join('\n'));
|
|
33
|
+
current = null;
|
|
34
|
+
};
|
|
35
|
+
for (const line of String(body ?? '').split('\n')) {
|
|
36
|
+
if (LIST_ITEM.test(line)) {
|
|
37
|
+
flush();
|
|
38
|
+
current = [line];
|
|
39
|
+
}
|
|
40
|
+
else if (current && /^\s+\S/.test(line)) {
|
|
41
|
+
current.push(line);
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
flush();
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
flush();
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
/** true = 条目首行是 `[superseded …]`(大小写不敏感,必须带 i) */
|
|
51
|
+
export function isRetiredEntry(entry) {
|
|
52
|
+
return RETIRED.test(firstLine(entry));
|
|
53
|
+
}
|
|
54
|
+
/** 条目首行里的日期;没有或不合法返回 null(`2026-99-99` 不猜成 12 月) */
|
|
55
|
+
export function entryDate(entry) {
|
|
56
|
+
const m = DATE.exec(firstLine(entry));
|
|
57
|
+
if (!m)
|
|
58
|
+
return null;
|
|
59
|
+
return validDate(m[1], m[2], m[3]) ? `${m[1]}-${m[2]}-${m[3]}` : null;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* 去掉退役条目(整条,不留半行),返回正文与删掉的条数。
|
|
63
|
+
* 磁盘上的文件不动 —— 省略只发生在注入路径上;记忆页 / git 仍看得到它们。
|
|
64
|
+
*/
|
|
65
|
+
export function stripRetiredEntries(body) {
|
|
66
|
+
const out = [];
|
|
67
|
+
let count = 0;
|
|
68
|
+
let skipping = false;
|
|
69
|
+
for (const line of String(body ?? '').split('\n')) {
|
|
70
|
+
if (LIST_ITEM.test(line)) {
|
|
71
|
+
skipping = RETIRED.test(line);
|
|
72
|
+
if (skipping) {
|
|
73
|
+
count += 1;
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
out.push(line);
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
if (skipping) {
|
|
80
|
+
// 续行与紧随的空行跟着整条一起走:删条不留空洞
|
|
81
|
+
if (!line.trim() || /^\s+\S/.test(line))
|
|
82
|
+
continue;
|
|
83
|
+
skipping = false;
|
|
84
|
+
}
|
|
85
|
+
out.push(line);
|
|
86
|
+
}
|
|
87
|
+
return { body: out.join('\n').replace(/\n{3,}/g, '\n\n').trim(), count };
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* 距某天几个本地日历天(不是毫秒差 / 86400000 再取整 —— 夏时制会算出 6.958 天)。
|
|
91
|
+
* 日期不合法返回 null;未来日期返回负数(调用方自己决定怎么报)。
|
|
92
|
+
*/
|
|
93
|
+
export function daysSinceDate(date, now = new Date()) {
|
|
94
|
+
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(date ?? '').trim());
|
|
95
|
+
if (!m || !validDate(m[1], m[2], m[3]))
|
|
96
|
+
return null;
|
|
97
|
+
const at = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
|
|
98
|
+
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
|
99
|
+
return Math.round((today.getTime() - at.getTime()) / 86_400_000);
|
|
100
|
+
}
|