dsh-zdiary-kit 3.7.0 → 3.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.
@@ -0,0 +1,159 @@
1
+ /**
2
+ * 死胡同探针:检索命中一篇活笔记时,顺手看归档里有没有**同一条结论**的废弃版本,带出废弃原因。
3
+ *
4
+ * 为什么需要(plan §14.3):`supersede` 的旧结论被 `excludedNames` 排除出检索,
5
+ * 只有 `zk_new` 写同名时才提示一次。于是 agent 在读 / 想的阶段看不到「这条路试过、为什么废」,
6
+ * 只能重新踩一遍 —— 而按 HackerNoon 那条分工,死胡同复现正是最该省掉的工。
7
+ * 这不是「不查全」的谦逊,是主动隐藏反例。
8
+ *
9
+ * 成本口径:**零子进程、零 zk 调用**。只读 `archive/` 下的文件(归档只放 supersede 搬进去的旧结论),
10
+ * 按标题相似度(`lib/similar.ts` 的同一份口径)与本次命中对照。扫描量有硬顶,触顶显式报。
11
+ *
12
+ * 边界:不判断「是不是同一个错误」(那是 agent 的活),只做机械标题比对;
13
+ * 不改默认结果集、不改 `completeness` 口径 —— 它是一条提示,不是第二份结果列表。
14
+ */
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+ import { parseFrontmatter } from './frontmatter.js';
18
+ import { similarKeyOf, similarScore } from './similar.js';
19
+ /** 一次最多回几条:这是提醒,不是结果列表 */
20
+ export const MAX_COUNTER_ENTRIES = 3;
21
+ /** 归档最多扫多少篇(触顶置 truncated,不静默少看) */
22
+ export const MAX_ARCHIVE_SCAN = 2_000;
23
+ /** 最多拿多少条本次命中当对照(结果列表可以很长,探针只取前 N 条:这是提示,不是全量比对) */
24
+ export const MAX_COUNTER_PROBES = 50;
25
+ /**
26
+ * 人话版(工具 render 与 `zk-kit search` 共用一份措辞,免得两处写法分叉)。
27
+ * `zeroHit` = 本次一条活笔记都没命中:要说清「没有」不等于「从来没有」。
28
+ */
29
+ export function describeCounterEntries(counters, opts = {}) {
30
+ const tail = counters.truncated ? '\n(归档超过扫描上限:只看了一部分,没看全 ≠ 没有)' : '';
31
+ if (!counters.entries.length)
32
+ return tail.trim() ? tail : '';
33
+ const head = opts.zeroHit
34
+ ? '⚠️ 没有活笔记命中,但归档里有同名旧结论(先看废弃原因,别重新提出来):'
35
+ : '⚠️ 归档里有同名旧结论(先看废弃原因,别重新提出来):';
36
+ const lines = counters.entries.map((e) => {
37
+ const why = e.reason ? `废弃原因:${e.reason}` : '没有记录废弃原因';
38
+ const by = e.supersededBy ? ` · 已被 ${e.supersededBy} 取代` : '';
39
+ return `· ${e.title}(${e.path},相似度 ${e.score})—— ${why}${by}\n 全文:${e.absPath}`;
40
+ });
41
+ return head + '\n' + lines.join('\n') + tail;
42
+ }
43
+ /** 递归列出归档里的 markdown(不用 readdirSync 的 recursive,老 Node 上没有) */
44
+ function listArchived(root, limit) {
45
+ const files = [];
46
+ const stack = [root];
47
+ while (stack.length) {
48
+ const dir = stack.pop();
49
+ let items = [];
50
+ try {
51
+ items = fs.readdirSync(dir, { withFileTypes: true });
52
+ }
53
+ catch {
54
+ continue;
55
+ }
56
+ for (const item of items) {
57
+ const abs = path.join(dir, item.name);
58
+ if (item.isDirectory()) {
59
+ stack.push(abs);
60
+ continue;
61
+ }
62
+ if (!item.isFile() || !/\.md$/i.test(item.name))
63
+ continue;
64
+ if (files.length >= limit)
65
+ return { files, truncated: true };
66
+ files.push(abs);
67
+ }
68
+ }
69
+ return { files, truncated: false };
70
+ }
71
+ function readArchived(cfg, abs) {
72
+ let fields = {};
73
+ try {
74
+ fields = parseFrontmatter(fs.readFileSync(abs, 'utf8')).fields;
75
+ }
76
+ catch {
77
+ return null;
78
+ }
79
+ const rel = path.relative(cfg.notebook, abs).split(path.sep).join('/');
80
+ const title = String(fields.title ?? '').trim() || path.basename(rel, path.extname(rel));
81
+ const key = similarKeyOf(title);
82
+ if (!key)
83
+ return null;
84
+ return {
85
+ title,
86
+ path: rel,
87
+ absPath: abs,
88
+ reason: String(fields['supersede-reason'] ?? '').trim(),
89
+ supersededBy: String(fields['superseded-by'] ?? '').trim(),
90
+ key,
91
+ };
92
+ }
93
+ /**
94
+ * 归档里与本次检索「同一条结论」的废弃版本。
95
+ *
96
+ * 对照对象:
97
+ * · 有命中 → 逐条比较命中笔记的标题(「这条结论以前被废过吗」);
98
+ * · 0 命中且给了 query → 把查询词当标题比(「库里没有」不等于「从来没出现过」)。
99
+ * 0 命中时不比较查询词以外的东西:查询词做标题比对噪声大,所以只在这一种情况下开。
100
+ */
101
+ export function archivedCounterparts(cfg, notes, opts = {}) {
102
+ const empty = { entries: [], scanned: 0, truncated: false };
103
+ const root = path.join(cfg.notebook, cfg.archiveDir);
104
+ if (!fs.existsSync(root))
105
+ return empty;
106
+ // 对照项:命中笔记的标题;0 命中时退回查询词
107
+ const probes = [];
108
+ if (notes.length === 0) {
109
+ const query = String(opts.query ?? '').trim();
110
+ const key = query ? similarKeyOf(query) : null;
111
+ if (key)
112
+ probes.push({ matched: '', key });
113
+ }
114
+ else {
115
+ for (const note of notes.slice(0, MAX_COUNTER_PROBES)) {
116
+ const key = similarKeyOf(note.title || '');
117
+ if (key)
118
+ probes.push({ matched: note.path, key });
119
+ }
120
+ }
121
+ if (!probes.length)
122
+ return empty;
123
+ const { files, truncated } = listArchived(root, MAX_ARCHIVE_SCAN);
124
+ const archived = [];
125
+ for (const abs of files) {
126
+ if (abs === root)
127
+ continue;
128
+ const note = readArchived(cfg, abs);
129
+ if (note)
130
+ archived.push(note);
131
+ }
132
+ const picked = [];
133
+ const seen = new Set();
134
+ for (const probe of probes) {
135
+ for (const note of archived) {
136
+ if (seen.has(note.path))
137
+ continue;
138
+ const score = similarScore(probe.key, note.key);
139
+ if (score === null)
140
+ continue;
141
+ seen.add(note.path);
142
+ picked.push({
143
+ matched: probe.matched,
144
+ title: note.title,
145
+ path: note.path,
146
+ absPath: note.absPath,
147
+ reason: note.reason,
148
+ supersededBy: note.supersededBy,
149
+ score,
150
+ });
151
+ }
152
+ }
153
+ picked.sort((a, b) => b.score - a.score);
154
+ return {
155
+ entries: picked.slice(0, MAX_COUNTER_ENTRIES),
156
+ scanned: files.length,
157
+ truncated,
158
+ };
159
+ }
package/dist/lib/dream.js CHANGED
@@ -20,7 +20,7 @@ import { parseFrontmatter } from './frontmatter.js';
20
20
  import { memoryUsage } from './memory.js';
21
21
  import { daysSinceDate, entryDate, isRetiredEntry, splitMemoryEntries, stripRetiredEntries } from './memory-format.js';
22
22
  import { isDayString } from './dates.js';
23
- import { normalizeTitle, resolveWikiTarget, WIKI_LINK, wikiIndex } from './wikilink.js';
23
+ import { normalizeTitle, noteKey, resolveWikiTarget, WIKI_LINK, wikiIndex } from './wikilink.js';
24
24
  /** 每栏最多回多少条(计划 §4 M3 的 50 条上限) */
25
25
  export const MAX_ITEMS = 50;
26
26
  /** topCited 只取前几名:给 agent 一个「本周被反复引用」的提示,不是排行榜 */
@@ -211,20 +211,24 @@ function promotionsOf(cfg, notes) {
211
211
  if (!body.trim())
212
212
  return out;
213
213
  const index = wikiIndex(notes);
214
+ const byPath = new Map(notes.map((n) => [n.path, n]));
214
215
  for (const match of body.matchAll(WIKI_LINK)) {
215
216
  const hit = resolveWikiTarget(cfg, String(match[1] ?? '').trim(), index);
216
- if (hit.status === 'live' && hit.path)
217
- out.set(hit.path, 'link');
217
+ // 解析结果是路径,按身份键记账(§9.2):有 id 的笔记改名后仍是同一篇,不会重复晋升。
218
+ const note = byPath.get(hit.path);
219
+ if (hit.status === 'live' && note)
220
+ out.set(noteKey(note), 'link');
218
221
  }
219
222
  const lines = stripRetiredEntries(body).body.split('\n').map((line) => normalizeTitle(line)).filter(Boolean);
220
223
  for (const note of notes) {
221
- if (out.has(note.path))
224
+ const key = noteKey(note);
225
+ if (out.has(key))
222
226
  continue;
223
- const key = normalizeTitle(note.title);
224
- if ([...key].length < MIN_TITLE_MATCH)
227
+ const title = normalizeTitle(note.title);
228
+ if ([...title].length < MIN_TITLE_MATCH)
225
229
  continue;
226
- if (lines.some((line) => line.includes(key)))
227
- out.set(note.path, 'title');
230
+ if (lines.some((line) => line.includes(title)))
231
+ out.set(key, 'title');
228
232
  }
229
233
  return out;
230
234
  }
@@ -360,7 +364,7 @@ export async function dreamNotebook(cfg, opts = {}, signal) {
360
364
  if (isUnder(note.path, cfg.dailyDir))
361
365
  continue;
362
366
  // 已经进 MEMORY 的先说:否则每周原样重复,仪式几次之后就没人看了
363
- const by = promoted.get(note.path);
367
+ const by = promoted.get(noteKey(note));
364
368
  if (by) {
365
369
  alreadyPromoted.push(candidateOf(note, by));
366
370
  continue;
@@ -380,7 +384,7 @@ export async function dreamNotebook(cfg, opts = {}, signal) {
380
384
  const at = dayMs(noteDate(cfg, n));
381
385
  if (Number.isFinite(at) && at >= sinceMs)
382
386
  return false;
383
- if (promoted.has(n.path))
387
+ if (promoted.has(noteKey(n)))
384
388
  return false;
385
389
  return rejectionReason(n) === null;
386
390
  })
@@ -425,6 +429,8 @@ export async function dreamNotebook(cfg, opts = {}, signal) {
425
429
  scanLimit: scan.limit,
426
430
  graphSkipped: !graphReady,
427
431
  graphBudget,
432
+ // 只读计数:老笔记 / 日记没有 id 属预期,日记按日期命名、路径天然稳定,不计入
433
+ missingId: notes.filter((n) => !n.id && !isUnder(n.path, cfg.dailyDir)).length,
428
434
  counts: {
429
435
  window: windowNotes.length,
430
436
  daily: windowNotes.filter((n) => isUnder(n.path, cfg.dailyDir)).length,
@@ -0,0 +1,95 @@
1
+ /**
2
+ * 一条双链「为什么存在」:链接所在的那一行 + 它所属的 `##` / `###` 小节。
3
+ *
4
+ * 为什么需要(plan §14.1):`zk_walk` 原来只回邻居的标题 + `lead`,而 `lead` 是邻居首段 ——
5
+ * 同一篇种子的所有出链拿到的是**逐字相同**的第一句,八条边长得一模一样。
6
+ * 卢曼的 Sammelverweise 之所以是枢纽,不是因为一张卡写了 25 个编号,而是因为它写了
7
+ * 「关于 X 见这几处」。没有这一行,1 跳退化成「8 个标题」,和全库无引导随机只差一个过滤条件。
8
+ *
9
+ * 成本:`linkedNotes` 走的是 `zk list --format json`,`rawContent` **已经在传输字节里**
10
+ * (plan §11.2 R8 第 2 条已经记过这笔账),这里只是把被丢掉的那一段用起来 ——
11
+ * 纯内存 / 一次本地读,**不新增 zk 进程**。
12
+ *
13
+ * 口径:只认 wiki 双链与 Markdown 行内链接;找不到就不给这一栏(不猜、不拿「提到了标题」冒充链接)。
14
+ */
15
+ import path from 'node:path';
16
+ import { normalizeTitle } from './wikilink.js';
17
+ /** 一行的回显上限(码点):超了截断并留省略号,不把整段正文塞进工具输出 */
18
+ const MAX_LINE = 160;
19
+ const WIKI = /\[\[([^[\]\n]+)\]\]/g;
20
+ /** Markdown 行内链接 / 图片:[文字](目标 "标题"),目标可带尖括号 */
21
+ const MD = /!?\[[^\]\n]*\]\((<[^>\n]+>|[^)\s]+)[^)\n]*\)/g;
22
+ const HEADING = /^(#{2,3})\s+(.+?)\s*#*\s*$/;
23
+ /** `[[x|别名#节]]` 取 `x`;`<a%20b.md>` 去尖括号 */
24
+ function destOf(rawLink) {
25
+ return String(rawLink ?? '').split('|')[0].split('#')[0].trim().replace(/^<|>$/g, '');
26
+ }
27
+ /** 链接目标是否指向这篇笔记:稳定 id / 标题 / 相对路径 / 文件名 stem 四种写法 */
28
+ function pointsAt(dest, target, sourcePath) {
29
+ const raw = destOf(dest).replace(/\\/g, '/').replace(/^\.\//, '');
30
+ if (!raw)
31
+ return false;
32
+ if (target.id && raw === target.id)
33
+ return true;
34
+ // Markdown 链接可能是相对当前文件的位置:按源文件所在目录解析,避免 ../ 形态漏认
35
+ const joined = raw.startsWith('/') ? raw.replace(/^\/+/, '') : path.posix.normalize(path.posix.join(path.posix.dirname(sourcePath), raw));
36
+ const noExt = joined.replace(/\.(md|markdown)$/i, '');
37
+ const wantPath = normalizeTitle(target.path.replace(/\.(md|markdown)$/i, ''));
38
+ const wantTitle = normalizeTitle(target.title);
39
+ const wantStem = normalizeTitle(path.posix.basename(target.path, path.posix.extname(target.path)));
40
+ const got = normalizeTitle(noExt);
41
+ if (got === wantPath || got === wantTitle)
42
+ return true;
43
+ return normalizeTitle(path.posix.basename(noExt)) === wantStem;
44
+ }
45
+ /** 压空白 + 截断;截断用可见的省略号,不静默少字 */
46
+ function clip(line) {
47
+ const flat = line.replace(/\s+/g, ' ').trim();
48
+ const chars = [...flat];
49
+ return chars.length > MAX_LINE ? chars.slice(0, MAX_LINE).join('') + '…' : flat;
50
+ }
51
+ /**
52
+ * 在 `markdown` 里找到「指向 target」的那一行。`sourcePath` 是 `markdown` 所属笔记的相对路径
53
+ * (用来解析 Markdown 链接的相对目标)。
54
+ *
55
+ * 找不到返回 null —— 链接可能写成纯文本、也可能被重写过,这两种情况都不该编一行出来。
56
+ */
57
+ export function linkContextOf(markdown, target, sourcePath) {
58
+ const content = String(markdown ?? '');
59
+ if (!content.trim())
60
+ return null;
61
+ let section = '';
62
+ let fence = false;
63
+ for (const line of content.split('\n')) {
64
+ // 代码块里的 `[[...]]` 是例子,不是链接
65
+ if (/^\s*(```|~~~)/.test(line)) {
66
+ fence = !fence;
67
+ continue;
68
+ }
69
+ if (fence)
70
+ continue;
71
+ const heading = line.match(HEADING);
72
+ if (heading) {
73
+ section = heading[2].trim();
74
+ continue;
75
+ }
76
+ let hit = false;
77
+ for (const m of line.matchAll(WIKI)) {
78
+ if (pointsAt(m[1] ?? '', target, sourcePath)) {
79
+ hit = true;
80
+ break;
81
+ }
82
+ }
83
+ if (!hit) {
84
+ for (const m of line.matchAll(MD)) {
85
+ if (pointsAt(m[1] ?? '', target, sourcePath)) {
86
+ hit = true;
87
+ break;
88
+ }
89
+ }
90
+ }
91
+ if (hit)
92
+ return { section, line: clip(line) };
93
+ }
94
+ return null;
95
+ }
@@ -0,0 +1,204 @@
1
+ /**
2
+ * R9:让 `MEMORY.md` 当检索入口(plan §11.2 / §14.2)。
3
+ *
4
+ * 口径:MEMORY 里每条活条目已经是「概念 → 入口」的卡片,条目里的 `[[来源]]` 就是入口。
5
+ *
6
+ * 两个方向,缺一不可:
7
+ * · `via: 'result'` —— 条目指向的那篇**本次命中了**:把「已晋升的结论」贴回结果(3.9.0 的语义);
8
+ * · `via: 'query'` —— **条目本身命中检索词**:来源不必在结果集里。这才是卢曼的索引方向
9
+ * (关键词 → 卡号 → 那张卡可以不含这个词)。原来的实现用 `byPath` 卡死,只做成了注解。
10
+ *
11
+ * 三条边界(与 §11.2 / §11.4 一致):
12
+ * · 只做字符串解析,不做语义判断(哪条更相关是 agent 的活);
13
+ * · 零子进程:`via: 'result'` 只用传进来的结果笔记建索引;`via: 'query'` 只在条目命中查询时
14
+ * 多读一次那篇来源文件的 frontmatter(≤ MAX_ENTRY_POINTS 次本地读),**不扫全库、不调 zk**;
15
+ * · 解析失败 / 没有 MEMORY.md 一律降级为「不带这一栏」,不让检索整体失败,也不谎称 complete。
16
+ *
17
+ * 解析复用 lint / dream / memory 的同一份口径:`splitMemoryEntries` / `isRetiredEntry` / `WIKI_LINK` /
18
+ * `resolveWikiTarget` —— 退役行不计(D3),显式写 `archive/` 的链接是「有意引用旧结论」,不算活入口。
19
+ */
20
+ import fs from 'node:fs';
21
+ import path from 'node:path';
22
+ import { parseFrontmatter } from './frontmatter.js';
23
+ import { isMetaPath } from './meta.js';
24
+ import { isRetiredEntry, splitMemoryEntries } from './memory-format.js';
25
+ import { normalizeTitle, resolveWikiTarget, WIKI_LINK, wikiIndex } from './wikilink.js';
26
+ /** 一次最多回显几条入口:结论清单是给人看的,不是第二份结果列表 */
27
+ export const MAX_ENTRY_POINTS = 5;
28
+ /** 中日韩文字:整串很难在条目里原样出现,补二元组让「同一术语」能对上 */
29
+ const CJK_RUN = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]+/gu;
30
+ /**
31
+ * 检索词 → 比对项。ASCII 按空格分词(≥2 码点),CJK 长串补二元组。
32
+ * 只用于「这条结论跟你的查询是不是同一个话题」的机械判断,不参与排序、不影响结果集。
33
+ */
34
+ export function queryTerms(query) {
35
+ const q = normalizeTitle(String(query ?? ''));
36
+ if (!q)
37
+ return [];
38
+ const terms = new Set();
39
+ for (const word of q.split(/\s+/))
40
+ if ([...word].length >= 2)
41
+ terms.add(word);
42
+ for (const run of q.match(CJK_RUN) ?? []) {
43
+ const chars = [...run];
44
+ if (chars.length < 3)
45
+ continue;
46
+ for (let i = 0; i + 1 < chars.length; i += 1)
47
+ terms.add(chars[i] + chars[i + 1]);
48
+ }
49
+ return [...terms];
50
+ }
51
+ function matchesQuery(text, terms) {
52
+ if (!terms.length)
53
+ return false;
54
+ const hay = normalizeTitle(text);
55
+ return terms.some((term) => hay.includes(term));
56
+ }
57
+ /** raw / inbox / 根目录 meta 都不是可导航的笔记:入口指过去也没用 */
58
+ function isNonNotePath(cfg, rel) {
59
+ if (isMetaPath(rel))
60
+ return true;
61
+ return ['raw', 'inbox'].some((dir) => rel === dir || rel.startsWith(dir + '/'));
62
+ }
63
+ /** 结果集之外的目标:只读这一篇的 frontmatter(0 子进程),读不到就不算入口 */
64
+ function liveNoteAt(cfg, rel) {
65
+ const root = path.resolve(cfg.notebook);
66
+ const abs = path.resolve(cfg.notebook, rel);
67
+ if (!abs.startsWith(root + path.sep))
68
+ return null;
69
+ try {
70
+ const fields = parseFrontmatter(fs.readFileSync(abs, 'utf8')).fields;
71
+ const title = String(fields.title ?? '').trim() || path.basename(rel, path.extname(rel));
72
+ return { title, absPath: abs };
73
+ }
74
+ catch {
75
+ return null;
76
+ }
77
+ }
78
+ /**
79
+ * 读 MEMORY.md:只留带 `[[链接]]` 的活条目(纯文字条目没有可解析的入口)。
80
+ * 文件不在 / 读不了 → 空数组(老库与 0.9 之前的库照常检索)。
81
+ */
82
+ export function liveMemoryEntries(cfg) {
83
+ let body = '';
84
+ try {
85
+ body = fs.readFileSync(path.join(cfg.notebook, 'MEMORY.md'), 'utf8');
86
+ }
87
+ catch {
88
+ return [];
89
+ }
90
+ if (!body.trim())
91
+ return [];
92
+ const out = [];
93
+ for (const entry of splitMemoryEntries(body)) {
94
+ if (isRetiredEntry(entry))
95
+ continue;
96
+ const targets = [...entry.matchAll(WIKI_LINK)]
97
+ .map((match) => String(match[1] ?? '').trim())
98
+ .filter(Boolean);
99
+ if (targets.length === 0)
100
+ continue;
101
+ out.push({ entry: (entry.split('\n', 1)[0] ?? '').replace(/\s+/g, ' ').trim(), targets });
102
+ }
103
+ return out;
104
+ }
105
+ /**
106
+ * 人话版(工具 render 与 `zk-kit search` / `zk-kit recall` 共用一份措辞,免得三处写法分叉)。
107
+ * 没有入口就一个字都不加(老库输出与改动前一致)。
108
+ *
109
+ * `skipQuery`:`via: 'query'` 的入口已经写进召回正文时(`entryPointsInText`),只补另一种,别重复占版面。
110
+ */
111
+ export function entryPointLines(points, opts = {}) {
112
+ if (!points?.length)
113
+ return '';
114
+ // 两种来源分开写:`query` 是「你的查询在 MEMORY 里有对应结论」,来源可能不在本批结果里;
115
+ // `result` 只是本批结果的注解。混在一起写,agent 会以为两件事一样。
116
+ const query = opts.skipQuery ? [] : points.filter((p) => p.via === 'query');
117
+ const result = points.filter((p) => p.via !== 'query');
118
+ if (!query.length && !result.length)
119
+ return '';
120
+ const where = (p) => p.resolved
121
+ ? p.path
122
+ : `[[${p.title}]](不在本批结果里:用 zk_walk 走进去)`;
123
+ const block = (title, list) => title +
124
+ list.map((p) => `· ${p.entry} → ${where(p)}`).join('\n') + '\n';
125
+ return '\n\n' +
126
+ (query.length ? block('MEMORY 里与查询相关的入口(来源不必在本批结果里):\n', query) : '') +
127
+ (result.length ? block('已晋升结论的入口(MEMORY.md 指向本批结果):\n', result) : '') +
128
+ (opts.truncated ? '(只回前 5 条:还有更多入口没列)' : '');
129
+ }
130
+ /**
131
+ * 本次检索的入口。两条来源(先查询命中,再结果命中),按 MEMORY 文件顺序,最多 MAX_ENTRY_POINTS 条:
132
+ * 1. 条目本身命中 `query` → 目标不必在结果集里(路径式 `[[来源路径]]` 直接读盘;标题式仍要结果集里有);
133
+ * 2. 条目指向本次命中的笔记 → 结果集的注解。
134
+ * 一条条目只取第一个能落地的目标;退役行 / 归档目标不计。
135
+ */
136
+ export function entryPointsOf(cfg, notes, opts = {}) {
137
+ const entries = liveMemoryEntries(cfg);
138
+ if (entries.length === 0)
139
+ return { points: [], truncated: false };
140
+ const index = wikiIndex(notes);
141
+ const byPath = new Map(notes.map((note) => [note.path, note]));
142
+ const terms = queryTerms(opts.query);
143
+ const out = [];
144
+ const seen = new Set();
145
+ let matched = 0;
146
+ const add = (point) => {
147
+ matched += 1;
148
+ if (out.length >= MAX_ENTRY_POINTS)
149
+ return;
150
+ out.push(point);
151
+ seen.add(point.entry);
152
+ };
153
+ // 1)查询命中的条目:来源可以在结果集之外 —— 这才是「入口」,不是注解
154
+ if (terms.length) {
155
+ for (const entry of entries) {
156
+ if (seen.has(entry.entry))
157
+ continue;
158
+ if (!matchesQuery(entry.entry, terms))
159
+ continue;
160
+ for (const target of entry.targets) {
161
+ const hit = resolveWikiTarget(cfg, target, index);
162
+ if (hit.status === 'archived')
163
+ continue; // 废弃结论归死胡同探针,不当活入口
164
+ if (hit.status === 'live') {
165
+ if (isNonNotePath(cfg, hit.path))
166
+ continue;
167
+ const known = byPath.get(hit.path);
168
+ if (known) {
169
+ add({ entry: entry.entry, title: known.title || hit.path, path: hit.path, absPath: known.absPath, via: 'query', resolved: true });
170
+ break;
171
+ }
172
+ const disk = liveNoteAt(cfg, hit.path);
173
+ if (disk) {
174
+ add({ entry: entry.entry, title: disk.title, path: hit.path, absPath: disk.absPath, via: 'query', resolved: true });
175
+ break;
176
+ }
177
+ continue;
178
+ }
179
+ // 标题 / id 写法且不在本批结果里:只给入口名,不为了补一次路径再起一个 zk 进程。
180
+ // 落地交给 `zk_walk <标题>` —— 卢曼的索引给的本来也是卡号,不是卡片。
181
+ if (isNonNotePath(cfg, target))
182
+ continue;
183
+ add({ entry: entry.entry, title: target, path: '', absPath: '', via: 'query', resolved: false });
184
+ break;
185
+ }
186
+ }
187
+ }
188
+ // 2)指向本次命中的条目:结果集的注解(3.9.0 的语义,保持不变)
189
+ for (const entry of entries) {
190
+ if (seen.has(entry.entry))
191
+ continue;
192
+ for (const target of entry.targets) {
193
+ const hit = resolveWikiTarget(cfg, target, index);
194
+ if (hit.status !== 'live')
195
+ continue;
196
+ const note = byPath.get(hit.path);
197
+ if (!note)
198
+ continue;
199
+ add({ entry: entry.entry, title: note.title || note.path, path: note.path, absPath: note.absPath, via: 'result', resolved: true });
200
+ break;
201
+ }
202
+ }
203
+ return { points: out, truncated: matched > out.length };
204
+ }
package/dist/lib/lint.js CHANGED
@@ -287,6 +287,9 @@ export function formatLintExtras(r) {
287
287
  const timeline = formatTimeline(r.timeline);
288
288
  if (timeline)
289
289
  lines.push(timeline);
290
+ if (r.missingId > 0) {
291
+ lines.push(`· 稳定 ID:${r.missingId} 篇没有 id — 新建的笔记已自动写入,老笔记只提示、不回填(§9.2)`);
292
+ }
290
293
  // 缺文件 = 人格未启用(默认状态):不报错、不占行。
291
294
  // 有旧版 / 占位符 / 标记不符时才提醒 —— 否则每个老库每次 lint 都多一条永久 ⚠️,反而训练人忽略告警。
292
295
  const persona = r.persona.items;
@@ -925,6 +928,8 @@ export async function lintNotebook(cfg, opts = {}, signal) {
925
928
  return {
926
929
  notebook: cfg.notebook,
927
930
  notes: notes.length,
931
+ // 只读计数:日记按日期命名、路径天然稳定,不计入;老笔记缺 id 属预期,不回填
932
+ missingId: nonDaily.filter((n) => !n.id).length,
928
933
  truncated: scanTruncated,
929
934
  completeness,
930
935
  scanLimit: scan.limit,
@@ -1,4 +1,7 @@
1
1
  import { countWords } from './memory.js';
2
+ import { entryPointsOf } from './entry-points.js';
3
+ import { archivedCounterparts } from './archive-probe.js';
4
+ import { bumpUsage } from './usage.js';
2
5
  import { searchNotesDetailed } from './zk.js';
3
6
  export const DEFAULT_RECALL_BUDGET = 500;
4
7
  export const MAX_RECALL_BUDGET = 5_000;
@@ -60,8 +63,21 @@ export async function assembleRecall(cfg, opts = {}, signal) {
60
63
  }, signal);
61
64
  const items = [];
62
65
  const seen = new Set();
66
+ // R9:入口卡排在装配正文之前。`via: 'query'` 的条目指向的笔记可以不在本次结果里 ——
67
+ // 这是卢曼的索引方向(关键词 → 卡号),`via: 'result'` 那些已经在这段正文里,不重复占预算。
68
+ const entryPoints = entryPointsOf(cfg, result.notes, { query: opts.query });
69
+ let entryPointsInText = false;
70
+ const entryLines = entryPoints.points.filter((p) => p.via === 'query')
71
+ .map((p) => `· ${p.entry} → ${p.resolved ? p.absPath : `[[${p.title}]](用 zk_walk 走进去)`}`);
63
72
  let text = '';
64
- let used = 0;
73
+ if (entryLines.length) {
74
+ const block = `入口(MEMORY 命中):\n${entryLines.join('\n')}`;
75
+ if (countWords(block) <= budget) {
76
+ text = block;
77
+ entryPointsInText = true;
78
+ }
79
+ }
80
+ let used = text ? countWords(text) : 0;
65
81
  let index = 0;
66
82
  for (const n of roundRobin(result.notes)) {
67
83
  const note = {
@@ -95,10 +111,23 @@ export async function assembleRecall(cfg, opts = {}, signal) {
95
111
  index += 1;
96
112
  items.push(note);
97
113
  }
114
+ const counters = opts.includeArchived
115
+ ? { entries: [], scanned: 0, truncated: false }
116
+ : archivedCounterparts(cfg, result.notes, { query: opts.query });
117
+ bumpUsage(cfg, [
118
+ 'recall',
119
+ ...(entryPoints.points.length ? ['entryPoints'] : []),
120
+ ...(counters.entries.length ? ['counterEntries'] : []),
121
+ ]);
98
122
  return {
99
123
  text, used, budget,
100
124
  completeness: result.completeness,
101
125
  hasMore: result.hasMore,
102
126
  notes: items,
127
+ entryPoints: entryPoints.points,
128
+ entryPointsTruncated: entryPoints.truncated,
129
+ entryPointsInText,
130
+ counterEntries: counters.entries,
131
+ counterEntriesTruncated: counters.truncated,
103
132
  };
104
133
  }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * 本地聚合计数(**不是** usage 日志):只数「哪个工具被调了几次」,不记查询词、不记路径、不上报。
3
+ *
4
+ * 为什么需要(plan §14.4):到 3.9.0 为止,入口 / 一跳的验收全是机械口径
5
+ * (子进程数、传输字节、schema、与 `graph` 对账),没有一条问「这条路有没有被真的用上」。
6
+ * 于是「补入口 + 遍历」只能靠论证说它对。这里给出唯一可观测的代理:
7
+ * `zk_stats` 里的 `usage`,发布后过一段时间看 `walk` / `entryPoints` / `counterEntries` 有没有涨。
8
+ *
9
+ * 口径:
10
+ * · 只加不减,`since` 是第一次计数的时间;没有文件就是全 0。
11
+ * · 写入失败一律吞掉 —— 计数不能把工具调用弄失败,也不能让工具输出看起来成功/失败。
12
+ * · 原子写(tmp + rename),并发调用最多丢一两次计数(计数器,不是账本)。
13
+ */
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+ /** 落在 `.zk/` 里:与 `dsh-index-state.json` 同级,不进 zk 索引 */
17
+ export const USAGE_FILE = path.join('.zk', 'dsh-usage.json');
18
+ export function readUsage(cfg) {
19
+ const file = path.join(cfg.notebook, USAGE_FILE);
20
+ try {
21
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
22
+ const counts = {};
23
+ if (raw && typeof raw.counts === 'object' && raw.counts) {
24
+ for (const [key, value] of Object.entries(raw.counts)) {
25
+ const n = Number(value);
26
+ if (Number.isFinite(n) && n >= 0)
27
+ counts[key] = Math.trunc(n);
28
+ }
29
+ }
30
+ return { since: typeof raw?.since === 'string' ? raw.since : '', counts };
31
+ }
32
+ catch {
33
+ return { since: '', counts: {} };
34
+ }
35
+ }
36
+ /**
37
+ * 给若干键各 +1。`keys` 为空直接返回(不白读文件)。
38
+ * 失败静默:笔记本只读 / 磁盘满 / 有人同时在写 —— 都不该影响这次工具调用。
39
+ */
40
+ export function bumpUsage(cfg, keys) {
41
+ if (!keys.length || !cfg.notebook)
42
+ return;
43
+ const file = path.join(cfg.notebook, USAGE_FILE);
44
+ const usage = readUsage(cfg);
45
+ const since = usage.since || new Date().toISOString();
46
+ for (const key of keys)
47
+ usage.counts[key] = (usage.counts[key] ?? 0) + 1;
48
+ const tmp = `${file}.${process.pid}.tmp`;
49
+ try {
50
+ fs.mkdirSync(path.dirname(file), { recursive: true });
51
+ fs.writeFileSync(tmp, JSON.stringify({ version: 1, since, counts: usage.counts }), 'utf8');
52
+ fs.renameSync(tmp, file);
53
+ }
54
+ catch {
55
+ try {
56
+ fs.rmSync(tmp, { force: true });
57
+ }
58
+ catch { /* 连清理都失败就只能算了 */ }
59
+ }
60
+ }