dsh-zdiary-kit 3.17.0 → 3.18.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,121 @@
1
+ /**
2
+ * zk_memory_report:MEMORY 现行条目、计数与检索命中观测(只报告,不执行)。
3
+ *
4
+ * 报告只用两类现成数据:
5
+ * · MEMORY.md 的现行条目(退役条目不算)与来源链接;
6
+ * · recall-signal.ts 的 sidecar 命中记录(count / last / days / queryKinds)。
7
+ *
8
+ * 边界:
9
+ * · 只读:不写盘、不改 MEMORY 一个字、不写 sidecar;
10
+ * · 零 LLM:全部是机械聚合与日期算术;
11
+ * · 命中只表示「检索结果包含来源」,不代表条目被阅读过;
12
+ * · 直接路径用本地 fs 解析,0 个 zk 子进程;只有展示的链接里仍有未解析目标时,
13
+ * 才做一次有上限的 zk 扫描(`scanNotes`,最多 MAX_SCAN 条,触顶/解析失败即不完整);
14
+ * · 扫描不完整时,未能确认的目标是 `unknown`,不是「断链」。
15
+ */
16
+ import fs from 'node:fs';
17
+ import path from 'node:path';
18
+ import { countWords } from './memory.js';
19
+ import { daysSinceDate, entryDate, isRetiredEntry, splitMemoryEntries } from './memory-format.js';
20
+ import { hasRecallSignal, readRecallSignal, recallEntryOf, RECALL_PROTECT_DAYS } from './recall-signal.js';
21
+ import { retireEntrySummary, sourceTargetsOf } from './retire.js';
22
+ import { resolveWikiTarget, wikiIndex } from './wikilink.js';
23
+ import { hasNotebook, MAX_SCAN, scanNotes } from './zk.js';
24
+ /** hot 的界:最近这么多天内观测到命中。与 warm 的 RECALL_PROTECT_DAYS = 30 配对使用。 */
25
+ export const HOT_DAYS = 7;
26
+ /**
27
+ * band 判据(纯机械):
28
+ * · hot = HOT_DAYS(7) 天内观测到命中;warm = RECALL_PROTECT_DAYS(30) 天内;cold = 有记录但更久;
29
+ * · never = 无命中记录且 age > 30 天;
30
+ * · 无命中记录但 age ≤ 30 天 → null(太新,「没有记录」还不是「从未被用」)。
31
+ * 仅在观测开启时调用;关闭时 band 字段整体不出现。
32
+ */
33
+ export function bandOfEntry(row, now) {
34
+ if (row.lastRecall) {
35
+ const days = daysSinceDate(row.lastRecall, now);
36
+ // 有记录但日期坏得算不出天数:当「有记录但不在保护期内」(cold),不假装它没被用过
37
+ if (days === null)
38
+ return 'cold';
39
+ if (days <= HOT_DAYS)
40
+ return 'hot';
41
+ if (days <= RECALL_PROTECT_DAYS)
42
+ return 'warm';
43
+ return 'cold';
44
+ }
45
+ if (row.ageDays > RECALL_PROTECT_DAYS)
46
+ return 'never';
47
+ return null;
48
+ }
49
+ /** 空的索引:路径式目标照样能解析(纯 fs 检查),标题 / id 式会返回 unknown */
50
+ const EMPTY_INDEX = wikiIndex([]);
51
+ /**
52
+ * MEMORY 条目级报告。纯读:MEMORY.md + sidecar(可选)+ 至多一次有上限的 zk 扫描。
53
+ * entries 只列现行条目(退役条目不算)。
54
+ */
55
+ export async function memoryReport(cfg, opts = {}, signal) {
56
+ const now = opts.now ?? new Date();
57
+ const limit = Math.min(200, Math.max(1, Math.trunc(opts.limit ?? 50)));
58
+ const bandFilter = opts.band && opts.band !== 'all' ? opts.band : undefined;
59
+ const recallSignal = readRecallSignal(cfg);
60
+ const signalActive = hasRecallSignal(recallSignal);
61
+ let body = '';
62
+ try {
63
+ body = fs.readFileSync(path.join(cfg.notebook, 'MEMORY.md'), 'utf8');
64
+ }
65
+ catch { /* 缺文件 = 空报告 */ }
66
+ const rows = splitMemoryEntries(body).filter((entry) => !isRetiredEntry(entry));
67
+ const counts = { total: rows.length, hot: 0, warm: 0, cold: 0, never: 0 };
68
+ const annotated = rows.map((entry) => {
69
+ const date = entryDate(entry) ?? '';
70
+ // 观测关闭时连 lookup 都不碰:band / lastRecall 整体缺失,输出退化成纯日期表
71
+ const last = signalActive ? recallEntryOf(recallSignal, entry) : null;
72
+ const ageDays = date ? (daysSinceDate(date, now) ?? -1) : -1;
73
+ const band = signalActive ? bandOfEntry({ lastRecall: last?.last ?? '', ageDays }, now) : null;
74
+ if (band)
75
+ counts[band] += 1;
76
+ return { entry, date, last, ageDays, band };
77
+ });
78
+ const shown = annotated
79
+ .filter((row) => !signalActive || !bandFilter || row.band === bandFilter)
80
+ .slice(0, limit)
81
+ .map((row) => ({ ...row, targets: sourceTargetsOf(row.entry) }));
82
+ // 直接路径用空索引先解析一遍:路径式目标不依赖索引,也就不需要 zk。
83
+ // 只有仍未解析的目标才值得付出一次有上限的扫描。
84
+ const resolved = new Map();
85
+ const unresolved = [];
86
+ for (const { targets } of shown) {
87
+ for (const target of targets) {
88
+ if (resolved.has(target))
89
+ continue;
90
+ const hit = resolveWikiTarget(cfg, target, EMPTY_INDEX, 'unknown');
91
+ resolved.set(target, hit.status);
92
+ if (hit.status === 'unknown' && !hit.path)
93
+ unresolved.push(target);
94
+ }
95
+ }
96
+ if (unresolved.length && hasNotebook(cfg)) {
97
+ try {
98
+ const scanLimit = Math.min(MAX_SCAN, Math.max(1, Math.trunc(opts.scanLimit ?? MAX_SCAN)));
99
+ const scan = await scanNotes(cfg, { limit: scanLimit }, signal);
100
+ const index = wikiIndex(scan.notes);
101
+ for (const target of unresolved) {
102
+ resolved.set(target, resolveWikiTarget(cfg, target, index, scan.completeness).status);
103
+ }
104
+ }
105
+ catch (err) {
106
+ // zk 不可用:保留直接路径的核实结果,其余仍是未知(不是断链)。
107
+ if (signal?.aborted)
108
+ throw err;
109
+ }
110
+ }
111
+ const entries = shown.map(({ entry, date, last, ageDays, band, targets }) => ({
112
+ entry: retireEntrySummary(entry),
113
+ date,
114
+ ageDays,
115
+ words: countWords(entry),
116
+ ...(last ? { lastRecall: last.last, recallDays: last.days.length, recallKinds: last.queryKinds.length } : {}),
117
+ sources: targets.map((target) => ({ target, status: resolved.get(target) ?? 'unknown' })),
118
+ ...(band ? { band } : {}),
119
+ }));
120
+ return { signalActive, entries, counts };
121
+ }
@@ -116,6 +116,10 @@ export function writeMemory(cfg, input) {
116
116
  if (!entryDate(entry)) {
117
117
  return reject(base, 'missing-date', '首行要带 YYYY-MM-DD 真实日期;插件不自动补');
118
118
  }
119
+ // 真写不能建库;目录缺失不能因索引陈旧误报为来源失效。
120
+ if (!input.dryRun && !fs.existsSync(path.dirname(file))) {
121
+ return reject(base, 'no-notebook', '笔记本目录还不存在;先用别的工具或 zk-kit init 建好库再写');
122
+ }
119
123
  // 3. 来源:带 [[…]] 且解析到活笔记
120
124
  const links = [...entry.matchAll(WIKI_LINK)];
121
125
  if (!links.length) {
@@ -173,7 +177,7 @@ export function writeMemory(cfg, input) {
173
177
  if (fileStamp(file) !== stamp) {
174
178
  return reject(base, 'concurrent-change', '落盘前发现文件被改过(stamp 变了),本次放弃');
175
179
  }
176
- // 预演不建库,真写也不替调用方建库:目录不存在时给结构化拒绝,别让 atomicWrite 裸抛 ENOENT
180
+ // 目录也可能在核对来源后被移走。
177
181
  if (!fs.existsSync(path.dirname(file))) {
178
182
  return reject(base, 'no-notebook', '笔记本目录还不存在;先用别的工具或 zk-kit init 建好库再写');
179
183
  }
@@ -572,7 +572,7 @@ function computePayload(cfg) {
572
572
  }
573
573
  // 模型真正收到的总量与开销:口径与 memoryUsage 的载荷预览同源
574
574
  const totalWords = countWords(text);
575
- return {
575
+ const payload = {
576
576
  text,
577
577
  words: finalWords,
578
578
  budget,
@@ -605,6 +605,7 @@ function computePayload(cfg) {
605
605
  totalWords,
606
606
  overheadWords: Math.max(0, totalWords - personaContentWords - finalWords),
607
607
  };
608
+ return payload;
608
609
  }
609
610
  /**
610
611
  * 记忆用量。只是 `buildMemoryPayload` 的投影 —— 不重读、不重算,
@@ -625,6 +626,48 @@ export function memoryUsage(cfg) {
625
626
  files: payload.files,
626
627
  };
627
628
  }
629
+ /**
630
+ * 「同日按最后召回时间」决胜是否生效:召回信号开启(15.2)且确实有条目带召回时间。
631
+ * 只传 signal 时行为与 0.9 逐字节一致 —— 变化只发生在显式开信号的人身上。
632
+ */
633
+ export function recallTieOf(rows, signal) {
634
+ return signal !== undefined && hasRecallSignal(signal) &&
635
+ rows.some((row) => lastRecallOf(signal, row.entry) !== '');
636
+ }
637
+ /**
638
+ * 活条目丢弃顺序(与注入截断的 oldestIndex 同一套决胜键):
639
+ * 有日期按最旧;同日期按「越久没被召回越先丢」(信号开启且可比时),否则按位置靠后的先丢;
640
+ * 没日期退回尾部(也是位置靠后先丢)。不改输入数组,返回新数组。
641
+ */
642
+ export function evictionOrderOf(rows, signal) {
643
+ const recallTie = recallTieOf(rows, signal);
644
+ const active = recallTie ? signal : null;
645
+ const recallOf = (row) => active ? lastRecallOf(active, row.entry) : '';
646
+ return [...rows].sort((a, b) => {
647
+ if (a.date && b.date) {
648
+ if (a.date !== b.date)
649
+ return a.date < b.date ? -1 : 1;
650
+ // 越久没被召回的越先丢;两边都没信号时仍是原来的位置决胜
651
+ if (active) {
652
+ const la = recallOf(a), lb = recallOf(b);
653
+ if (la !== lb)
654
+ return la < lb ? -1 : 1;
655
+ }
656
+ return b.index - a.index;
657
+ }
658
+ if (a.date)
659
+ return -1;
660
+ if (b.date)
661
+ return 1;
662
+ return b.index - a.index;
663
+ });
664
+ }
665
+ /** 条目首行摘要(dropCandidates.title 用这份口径):压空白、截 max 字 */
666
+ export function memoryEntryTitle(entry, max = TOC_TITLE_MAX) {
667
+ const one = String(entry.split('\n', 1)[0] ?? '').replace(/\s+/g, ' ').trim();
668
+ const title = one.length > max ? one.slice(0, max) + '…' : one;
669
+ return title || '(无标题)';
670
+ }
628
671
  /**
629
672
  * 「改 MEMORY 之前」的容量快照:复用 `buildMemoryPayload` / `memoryUsage` 的投影,不新增计数口径;
630
673
  * 条目解析复用 `splitMemoryEntries` / `entryDate` / `isRetiredEntry`,与截断、`zk_lint` 同一份。
@@ -657,37 +700,15 @@ export function memoryCapacity(cfg, opts = {}) {
657
700
  const oldestDate = orderDebt.oldestDate;
658
701
  const sameDateCount = orderDebt.oldestTies;
659
702
  // 15.2:只有确实有条目带召回信号时才启用「最后召回时间」次级键,否则连文案都不变
660
- const recallTie = hasRecallSignal(signal) && entries.some((row) => lastRecallOf(signal, row.entry) !== '');
661
- const recallOf = (row) => recallTie ? lastRecallOf(signal, row.entry) : '';
662
- // 与 oldestIndex 同口径:有日期按最旧;同日期按位置靠后的先丢;没日期退回尾部(也是位置靠后先丢)
663
- const order = [...entries].sort((a, b) => {
664
- if (a.date && b.date) {
665
- if (a.date !== b.date)
666
- return a.date < b.date ? -1 : 1;
667
- // 越久没被召回的越先丢;两边都没信号时仍是原来的位置决胜
668
- if (recallTie) {
669
- const la = recallOf(a), lb = recallOf(b);
670
- if (la !== lb)
671
- return la < lb ? -1 : 1;
672
- }
673
- return b.index - a.index;
674
- }
675
- if (a.date)
676
- return -1;
677
- if (b.date)
678
- return 1;
679
- return b.index - a.index;
680
- });
681
- const dropCandidates = order.slice(0, 5).map(({ entry, date }) => {
682
- const one = String(entry.split('\n', 1)[0] ?? '').replace(/\s+/g, ' ').trim();
683
- const title = one.length > TOC_TITLE_MAX ? one.slice(0, TOC_TITLE_MAX) + '…' : one;
684
- return {
685
- title: title || '(无标题)',
686
- date: date ?? '',
687
- words: countWords(entry),
688
- reason: !date ? 'undated' : sameDateCount > 1 && date === oldestDate ? 'same-date' : 'oldest',
689
- };
690
- });
703
+ // (排序实现在上面的 evictionOrderOf,这里不再抄一遍比较器)
704
+ const recallTie = recallTieOf(entries, signal);
705
+ const order = evictionOrderOf(entries, signal);
706
+ const dropCandidates = order.slice(0, 5).map(({ entry, date }) => ({
707
+ title: memoryEntryTitle(entry),
708
+ date: date ?? '',
709
+ words: countWords(entry),
710
+ reason: !date ? 'undated' : sameDateCount > 1 && date === oldestDate ? 'same-date' : 'oldest',
711
+ }));
691
712
  const format = [];
692
713
  if (debt.undated > 0)
693
714
  format.push('undated');
@@ -98,6 +98,12 @@ function dailyGroup(cfg) {
98
98
  }
99
99
  /** layered 的四种笔记类型(顺序与目录 / group 一致) */
100
100
  export const NOTE_KINDS = ['source', 'concept', 'entity', 'pattern'];
101
+ /**
102
+ * type 过滤 / 工具枚举的取值:笔记类型 + daily。
103
+ * daily 不在 NOTE_KINDS 里 —— 日记模板没有 frontmatter `type`,查询时按 dailyDir 路径兜底
104
+ * (见 zk.ts 的 keep),但下拉 / 工具参数都得能筛到它。只读视图与 zk_query / zk_recall 共用这一份。
105
+ */
106
+ export const NOTE_TYPE_VALUES = ['daily', ...NOTE_KINDS];
101
107
  /** type → 目录名的复数(entity 不规则,不能直接加 s) */
102
108
  const PLURAL_DIR = {
103
109
  source: 'sources',
@@ -118,6 +118,11 @@ export function bumpRecall(cfg, hits, kind) {
118
118
  * 一次工具调用内复用同一份索引:`memoryCapacity` 的排序比较器会反复调 `lastRecallOf`,
119
119
  * 每次重建全量 lookup 会让 10k sidecar 退化到秒级。signal 只读不写(写只在 bumpRecall 的独立副本里),
120
120
  * 所以用 WeakMap 按对象缓存,readRecallSignal 每次返回新对象,不会跨调用拿到过期索引。
121
+ *
122
+ * 值存**完整 sidecar 条目**而不是 last 日期:zk_memory_report 的 recallDays / recallKinds
123
+ * 需要同一条记录,两种访问器共用一份 lookup,才不会出现「last 与 days 不是一个口径」。
124
+ * 与旧版同口径:没有 last 日期的记录不参与关联(旧的 `e.last > ''` 不成立),
125
+ * 同键多条时取 last 最新的那条(并列时先到先得)。
121
126
  */
122
127
  const lookupCache = new WeakMap();
123
128
  /** 同一次调用里排序比较器会把同一条目反复比较,结果按 (signal, entry) 缓存 */
@@ -130,21 +135,23 @@ function recallLookup(signal) {
130
135
  for (const [p, e] of Object.entries(signal.byPath)) {
131
136
  const stem = p.replace(/\.[^./]+$/, '');
132
137
  for (const key of [p, stem, e.title]) {
133
- if (key && e.last > (lookup.get(key) ?? ''))
134
- lookup.set(key, e.last);
138
+ if (key && e.last && e.last > (lookup.get(key)?.last ?? ''))
139
+ lookup.set(key, e);
135
140
  }
136
141
  }
137
142
  lookupCache.set(signal, lookup);
138
143
  return lookup;
139
144
  }
140
145
  /**
141
- * MEMORY 条目 → 最近召回日期。sidecar 的 path / stem / title 都建成键,
146
+ * MEMORY 条目 → 完整 sidecar 条目。sidecar 的 path / stem / title 都建成键,
142
147
  * 所以标题式 `[[标题]]` 与路径式 `[[notes/x]]` 都能关联上(纯 JS、不跑 zk)。
148
+ * `lastRecallOf` 与 `zk_memory_report` 的 recallDays / recallKinds 都走这一个入口 ——
149
+ * 「哪条最后何时被召回」只许有一个口径。没有关联记录返回 null。
143
150
  * signal 只读、entry 是字符串,结果确定 —— 一次调用内按 entry 缓存,避免排序比较器重复解析。
144
151
  */
145
- export function lastRecallOf(signal, entry) {
152
+ export function recallEntryOf(signal, entry) {
146
153
  if (!hasRecallSignal(signal))
147
- return '';
154
+ return null;
148
155
  let results = resultCache.get(signal);
149
156
  if (!results) {
150
157
  results = new Map();
@@ -154,13 +161,20 @@ export function lastRecallOf(signal, entry) {
154
161
  if (cached !== undefined)
155
162
  return cached;
156
163
  const lookup = recallLookup(signal);
157
- let best = '';
164
+ let best = null;
158
165
  for (const m of String(entry).matchAll(WIKI_LINK)) {
159
166
  const target = String(m[1] ?? '').trim();
160
167
  const hit = lookup.get(target) ?? lookup.get(target.replace(/\.[^./]+$/, ''));
161
- if (hit && hit > best)
168
+ if (hit && (best === null || hit.last > best.last))
162
169
  best = hit;
163
170
  }
164
171
  results.set(entry, best);
165
172
  return best;
166
173
  }
174
+ /**
175
+ * MEMORY 条目 → 最近召回日期。复用 recallEntryOf 的同一份 lookup(行为与旧版逐字节一致),
176
+ * 保证「哪条最后何时被召回」只有一个口径。
177
+ */
178
+ export function lastRecallOf(signal, entry) {
179
+ return recallEntryOf(signal, entry)?.last ?? '';
180
+ }
@@ -8,6 +8,44 @@ export const DEFAULT_RECALL_BUDGET = 500;
8
8
  export const MAX_RECALL_BUDGET = 5_000;
9
9
  export const DEFAULT_RECALL_LIMIT = 30;
10
10
  export const MAX_RECALL_LIMIT = 200;
11
+ /** line 档的固定截断点:detail 取前 40 词(countWords 口径)。固定规则渲染,不按剩余预算切半句 */
12
+ export const MAX_LINE_WORDS = 40;
13
+ /** 与 memory.ts 的 countWords 同一口径的 CJK 判定;不带 g flag,逐字 test 不会被 lastIndex 坑 */
14
+ const CJK_CHAR = /[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uac00-\ud7af]/;
15
+ /**
16
+ * 按 countWords 口径截前 max 词:CJK 2 字 1 词(逐字累加、ceil 进位),
17
+ * 连续非 CJK 非空白算 1 词。超限就在那半个 CJK 字 / 那个词之前截断 ——
18
+ * 截断点是固定的(MAX_LINE_WORDS),属于 line 档格式的一部分,不是按剩余预算切半句。
19
+ */
20
+ function truncateWords(text, max) {
21
+ if (max <= 0)
22
+ return '';
23
+ let cjk = 0;
24
+ let latin = 0;
25
+ let i = 0;
26
+ while (i < text.length) {
27
+ const ch = text[i];
28
+ if (/\s/.test(ch)) {
29
+ i += 1;
30
+ continue;
31
+ }
32
+ if (CJK_CHAR.test(ch)) {
33
+ if (Math.ceil((cjk + 1) / 2) + latin > max)
34
+ break;
35
+ cjk += 1;
36
+ i += 1;
37
+ continue;
38
+ }
39
+ let j = i;
40
+ while (j < text.length && !/\s/.test(text[j]) && !CJK_CHAR.test(text[j]))
41
+ j += 1;
42
+ if (Math.ceil(cjk / 2) + latin + 1 > max)
43
+ break;
44
+ latin += 1;
45
+ i = j;
46
+ }
47
+ return text.slice(0, i).trimEnd();
48
+ }
11
49
  /** 分组键:type 优先,其次首个标签,都没有归「未分类」。分组只决定装配的轮转顺序,组内保持检索顺序 */
12
50
  function groupOf(n) {
13
51
  if (n.type)
@@ -50,6 +88,14 @@ function entryText(n, index) {
50
88
  const detail = detailOf(n);
51
89
  return `## ${index + 1}. ${n.title || n.path}\n${meta}${detail ? '\n\n' + detail : ''}`;
52
90
  }
91
+ /** line 档(索引行):`· 标题 — detail 前 40 词 · 绝对路径`。detail 与 entryText 同一份 detailOf 口径 */
92
+ function lineText(n) {
93
+ const title = n.title || n.path;
94
+ const detail = truncateWords(detailOf(n), MAX_LINE_WORDS);
95
+ return detail
96
+ ? `· ${title} — ${detail} · ${n.absPath || n.path}`
97
+ : `· ${title} · ${n.absPath || n.path}`;
98
+ }
53
99
  /**
54
100
  * 一次检索 + 内存装配。候选数由 opts.limit 决定(缺省 30),不再为装配多起一个 zk 进程;
55
101
  * 每条附 absPath,需要全文时仍由宿主原生 read 取。
@@ -57,8 +103,11 @@ function entryText(n, index) {
57
103
  export async function assembleRecall(cfg, opts = {}, signal) {
58
104
  const budget = Math.min(MAX_RECALL_BUDGET, Math.max(1, Math.trunc(Number(opts.budget) || DEFAULT_RECALL_BUDGET)));
59
105
  const limit = Math.min(MAX_RECALL_LIMIT, Math.max(1, Math.trunc(Number(opts.limit) || DEFAULT_RECALL_LIMIT)));
106
+ // degrade 是装配档位,不是检索参数:别把它透传给 zk
107
+ const { fit: fitOpt, ...searchOpts } = opts;
108
+ const degrade = fitOpt === 'degrade';
60
109
  const result = await searchNotesDetailed(cfg, {
61
- ...opts,
110
+ ...searchOpts,
62
111
  limit,
63
112
  sort: opts.sort ?? (opts.query ? 'relevance' : 'created-desc'),
64
113
  }, signal);
@@ -80,6 +129,7 @@ export async function assembleRecall(cfg, opts = {}, signal) {
80
129
  }
81
130
  let used = text ? countWords(text) : 0;
82
131
  let index = 0;
132
+ let degraded = 0;
83
133
  for (const n of roundRobin(result.notes)) {
84
134
  const note = {
85
135
  title: n.title, path: n.path, absPath: n.absPath, summary: n.summary, included: false, reason: 'over-budget',
@@ -101,6 +151,22 @@ export async function assembleRecall(cfg, opts = {}, signal) {
101
151
  const candidate = text ? text + '\n\n' + entry : entry;
102
152
  const words = countWords(candidate);
103
153
  if (words > budget) {
154
+ // degrade:detail 放不下先降 line 档再试一次;line 也放不下才记 over-budget。
155
+ // line 档不占 `## N.` 编号(索引行没有编号),编号仍只数 detail 档
156
+ if (degrade) {
157
+ const lineCandidate = text ? text + '\n\n' + lineText(n) : lineText(n);
158
+ const lineWords = countWords(lineCandidate);
159
+ if (lineWords <= budget) {
160
+ text = lineCandidate;
161
+ used = lineWords;
162
+ note.included = true;
163
+ note.reason = 'included';
164
+ note.resolution = 'line';
165
+ degraded += 1;
166
+ items.push(note);
167
+ continue;
168
+ }
169
+ }
104
170
  note.reason = 'over-budget';
105
171
  items.push(note);
106
172
  continue;
@@ -109,6 +175,8 @@ export async function assembleRecall(cfg, opts = {}, signal) {
109
175
  used = words;
110
176
  note.included = true;
111
177
  note.reason = 'included';
178
+ if (degrade)
179
+ note.resolution = 'detail';
112
180
  index += 1;
113
181
  items.push(note);
114
182
  }
@@ -131,5 +199,7 @@ export async function assembleRecall(cfg, opts = {}, signal) {
131
199
  entryPointsInText,
132
200
  counterEntries: counters.entries,
133
201
  counterEntriesTruncated: counters.truncated,
202
+ // 新字段只在 degrade 模式出现:whole 模式保持旧返回形状,无损 JSON 与旧输出逐字节一致
203
+ ...(degrade ? { degraded } : {}),
134
204
  };
135
205
  }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * `zk_dream` 的 MEMORY 退役候选。
3
+ * 规则只做机械判断,不判断「这条还有没有用」(那是 agent 的语义活):
4
+ * · 有日期且超过 STALE_DAYS → stale;
5
+ * · 条目里的 `[[来源]]` 指向归档 / 不存在 → source-superseded / source-missing;
6
+ * · 显式写 `archive/` 的链接是有意引用旧结论(与 lint 同口径),不算来源断了;
7
+ * · 无日期、无链接的不算候选(它们已经由 lint 的 undated / unlinked 报告);
8
+ * · 召回信号开启且 30 天内被召回过的条目受保护(RECALL_PROTECT_DAYS)。
9
+ */
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { withoutFences } from './fence.js';
13
+ import { daysSinceDate, entryDate, isRetiredEntry, splitMemoryEntries } from './memory-format.js';
14
+ import { resolveWikiTarget, WIKI_LINK, wikiIndex } from './wikilink.js';
15
+ import { lastRecallOf, RECALL_PROTECT_DAYS } from './recall-signal.js';
16
+ /** 超过多少天没复核算「可考虑退役」(只做机械年龄判断) */
17
+ export const STALE_DAYS = 90;
18
+ /** 退役候选最多回几条:给材料,不是给清理清单 */
19
+ export const MAX_RETIRE = 10;
20
+ /**
21
+ * 条目里的 `[[来源]]` 目标(去围栏、去空目标、去重)。
22
+ * MEMORY 条目切分与链接解析只在这里一份口径 —— 退役候选、依据回对与 utility 报告共用,
23
+ * 免得同一份 MEMORY 在两处解出不同的来源集合。
24
+ */
25
+ export function sourceTargetsOf(entry) {
26
+ const out = [];
27
+ for (const match of withoutFences(entry).matchAll(WIKI_LINK)) {
28
+ const target = String(match[1] ?? '').trim();
29
+ if (target && !out.includes(target))
30
+ out.push(target);
31
+ }
32
+ return out;
33
+ }
34
+ /**
35
+ * 条目首行摘要(最多 100 字):去掉列表符号、压空白。
36
+ * retireCandidates / dream.evidence / zk_memory_report 的 `entries[].entry` 同这一份口径。
37
+ */
38
+ export function retireEntrySummary(entry) {
39
+ const summary = (entry.split('\n', 1)[0] ?? '')
40
+ .replace(/^\s*(?:[-*+]|\d+[.)])\s+/, '')
41
+ .replace(/\s+/g, ' ')
42
+ .trim();
43
+ return summary.length > 100 ? summary.slice(0, 100) + '…' : summary;
44
+ }
45
+ /**
46
+ * 退役候选:只做机械规则,不判断「这条还有没有用」。
47
+ * 扫描不完整时只根据已核实的来源或条目年龄给出候选:未解析的目标不是「来源断了」。
48
+ */
49
+ export function retireCandidatesOf(cfg, notes, now, signal, completeness = 'complete') {
50
+ let body = '';
51
+ try {
52
+ body = fs.readFileSync(path.join(cfg.notebook, 'MEMORY.md'), 'utf8');
53
+ }
54
+ catch {
55
+ return [];
56
+ }
57
+ const index = wikiIndex(notes);
58
+ const out = [];
59
+ const seen = new Set();
60
+ for (const entry of splitMemoryEntries(body)) {
61
+ if (isRetiredEntry(entry))
62
+ continue;
63
+ // 15.2:近期被召回过的条目不算退役候选 —— 门控要看得见「其实一直被用到」
64
+ const last = lastRecallOf(signal, entry);
65
+ if (last && (daysSinceDate(last, now) ?? Infinity) <= RECALL_PROTECT_DAYS)
66
+ continue;
67
+ const date = entryDate(entry) ?? '';
68
+ const age = date ? (daysSinceDate(date, now) ?? -1) : -1;
69
+ let reason = null;
70
+ for (const target of sourceTargetsOf(entry)) {
71
+ const hit = resolveWikiTarget(cfg, target, index, completeness);
72
+ // 显式写 archive/ 的链接是有意引用(supersede 就是这样重写入链的):与 lint 一个口径,不算来源断了;
73
+ // 索引没扫全时 unknown 也不能当「断了」—— 否则会给出误导性的退役候选
74
+ if (hit.status === 'live' || hit.status === 'unknown' || hit.explicit)
75
+ continue;
76
+ reason = hit.status === 'archived' ? 'source-superseded' : 'source-missing';
77
+ break;
78
+ }
79
+ if (!reason && age > STALE_DAYS)
80
+ reason = 'stale';
81
+ if (!reason)
82
+ continue;
83
+ const one = retireEntrySummary(entry);
84
+ if (!one || seen.has(one))
85
+ continue;
86
+ seen.add(one);
87
+ out.push({ entry: one, date, age, reason });
88
+ }
89
+ // 越旧越靠前;无日期(-1)的排在最后(不假装它们更旧)
90
+ out.sort((a, b) => b.age - a.age || a.entry.localeCompare(b.entry));
91
+ return out.slice(0, MAX_RETIRE);
92
+ }
@@ -5,8 +5,9 @@
5
5
  * 「这条候选是不是已经晋升进 MEMORY 了」—— 两处都要回答同一个问题(这个 `[[目标]]` 现在对应哪篇笔记),
6
6
  * 各写一份的话,解析顺序迟早分叉,于是同一份 MEMORY 在两个工具里给出不同答案。
7
7
  *
8
- * 顺序固定(与 lint 原来的口径一致):原路径 → 加 `.md` → `archive/` 下同名 → 活笔记标题 / 文件名。
8
+ * 顺序固定:原路径 → 加 `.md` → `archive/` 下同名 → 索引中的 ID → 活笔记标题 / 文件名。
9
9
  * 归档标题**不**反查:归档默认不进检索,再造一套索引就成了第二真相。
10
+ * 索引没扫全时不把「没找到」当「不存在」:返回 `unknown`,由调用方决定怎么措辞。
10
11
  */
11
12
  import fs from 'node:fs';
12
13
  import path from 'node:path';
@@ -44,51 +45,62 @@ function insideNotebook(cfg, abs) {
44
45
  const p = path.resolve(abs);
45
46
  return p === root || p.startsWith(root + path.sep);
46
47
  }
47
- function statusOf(abs) {
48
+ function isFile(abs) {
48
49
  try {
49
- return parseFrontmatter(fs.readFileSync(abs, 'utf8')).fields.status ?? '';
50
+ return fs.statSync(abs, { throwIfNoEntry: false })?.isFile() === true;
50
51
  }
51
52
  catch {
52
- return '';
53
+ return false;
54
+ }
55
+ }
56
+ function fileStatus(abs) {
57
+ try {
58
+ return parseFrontmatter(fs.readFileSync(abs, 'utf8')).fields.status === 'superseded' ? 'archived' : 'live';
59
+ }
60
+ catch {
61
+ return 'unknown';
53
62
  }
54
63
  }
55
64
  function relOf(cfg, abs) {
56
65
  return path.relative(cfg.notebook, abs).split(path.sep).join('/');
57
66
  }
58
- /** 把一个 `[[目标]]` 落到具体文件上:活笔记 / 已归档 / 不存在 */
59
- export function resolveWikiTarget(cfg, target, index) {
67
+ /** 把一个 `[[目标]]` 落到具体文件上:活笔记 / 已归档(含手工 status)/ 不存在 / 未能确认 */
68
+ export function resolveWikiTarget(cfg, target, index, completeness = 'complete') {
60
69
  const rel = String(target ?? '').replace(/\\/g, '/').replace(/^\.\//, '').trim();
61
70
  if (!rel)
62
71
  return { status: 'missing', path: '', explicit: false };
63
- // 稳定 ID 优先:`[[<id>]]` 直接落到那篇笔记的当前路径,改名之后也不断链。
64
- // 老库没有 id,byId 为空,下面的路径 / 标题解析顺序逐字不变。
65
- const byId = index.byId.get(rel);
66
- if (byId)
67
- return { status: 'live', path: byId, explicit: false };
68
72
  const candidates = /\.md$/i.test(rel) ? [rel] : [rel, `${rel}.md`];
73
+ const archive = cfg.archiveDir.replace(/\/+$/, '');
69
74
  for (const candidate of candidates) {
70
75
  const abs = path.resolve(cfg.notebook, candidate);
71
- if (!insideNotebook(cfg, abs) || !fs.existsSync(abs) || !fs.statSync(abs).isFile())
76
+ if (!insideNotebook(cfg, abs) || !isFile(abs))
72
77
  continue;
73
78
  const hit = relOf(cfg, abs);
74
79
  // 显式写 archive/ 路径 = 有意引用旧结论(supersede 就是这样重写入链的),不算漂移
75
- if (hit === cfg.archiveDir || hit.startsWith(`${cfg.archiveDir}/`)) {
80
+ if (hit === archive || hit.startsWith(`${archive}/`)) {
76
81
  return { status: 'archived', path: hit, explicit: true };
77
82
  }
78
- return { status: statusOf(abs) === 'superseded' ? 'archived' : 'live', path: hit, explicit: false };
83
+ return { status: fileStatus(abs), path: hit, explicit: false };
79
84
  }
80
85
  // 链接还停在废弃前的路径:文件已经搬进 archive/ —— 这正是要抓的漂移
81
- if (!rel.startsWith(`${cfg.archiveDir}/`)) {
86
+ if (!rel.startsWith(`${archive}/`)) {
82
87
  for (const candidate of candidates) {
83
- const abs = path.resolve(cfg.notebook, cfg.archiveDir, candidate);
84
- if (!insideNotebook(cfg, abs) || !fs.existsSync(abs) || !fs.statSync(abs).isFile())
88
+ const abs = path.resolve(cfg.notebook, archive, candidate);
89
+ if (!insideNotebook(cfg, abs) || !isFile(abs))
85
90
  continue;
86
91
  return { status: 'archived', path: relOf(cfg, abs), explicit: false };
87
92
  }
88
93
  }
89
- // 标题式链接只在活笔记里找
90
- const byTitle = index.byTitle.get(normalizeTitle(rel));
91
- if (byTitle)
92
- return { status: 'live', path: byTitle, explicit: false };
93
- return { status: 'missing', path: '', explicit: false };
94
+ // 稳定 ID 优先于标题;索引命中不是「活笔记」的证明,仍然核对文件状态。
95
+ // 这样路径 / 标题 / id 三种写法对 `status: superseded` 给同一个答案。
96
+ const indexed = index?.byId.get(rel) ?? index?.byTitle.get(normalizeTitle(rel));
97
+ if (indexed) {
98
+ const abs = path.resolve(cfg.notebook, indexed);
99
+ if (insideNotebook(cfg, abs)) {
100
+ const hit = relOf(cfg, abs);
101
+ const status = hit === archive || hit.startsWith(`${archive}/`) ? 'archived' : fileStatus(abs);
102
+ return { status, path: indexed, explicit: false };
103
+ }
104
+ }
105
+ return { status: completeness === 'complete' ? 'missing' : 'unknown', path: '', explicit: false };
94
106
  }
package/dist/lib/zk.js CHANGED
@@ -37,7 +37,9 @@ export class ZkError extends Error {
37
37
  }
38
38
  const SORT_TERMS = {
39
39
  'created-desc': 'created-',
40
- 'created-asc': 'created',
40
+ // zk 的 -/+ 后缀是「钉死方向」不是反转(NoteSorterFromString):created / modified 默认就是降序,
41
+ // 所以 `created` 与 `created-` 同序 —— 升序必须显式给 `created+`,否则 asc / desc 结果完全一样。
42
+ 'created-asc': 'created+',
41
43
  'modified-desc': 'modified-',
42
44
  'title-asc': 'title',
43
45
  };
@@ -33,6 +33,9 @@
33
33
  别的会话切了默认值不会把已开的会话换库,裸装配才退回进程工作区 + 全局默认
34
34
  - `zk_context` 工具:同一份 payload(含 `ratio` 用量),给「宿主没有 `systemPrompt`」和「人想核对被截断了什么」用;
35
35
  另返回 `notebooks`(名字 / 路径 / 结构 / 当前),没有提示注入时模型也能发现已配置的库
36
+ - `zk_memory_report` 工具:只读报告 MEMORY 现行条目的日期、词数、来源状态、计数与检索命中观测。
37
+ `never` 表示条目超过 30 天且未观测到命中;观测关闭或数据不可用时不分档。命中只表示检索结果包含来源,
38
+ 不代表条目被使用或阅读。直接路径无需 zk,其他来源至多做一次有上限的扫描;细节见 [工具文档](zk-tools.md)。
36
39
  - 设置页「记忆」:注入预算、人格上限;「目录与 group」:归档目录。
37
40
  快照里带 `memory.words/budget/truncatedWords/retiredWords/persona` 状态行;自检多一项「角色人格」
38
41