dsh-zdiary-kit 3.9.0 → 3.10.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/dist/lib/dream.js CHANGED
@@ -15,12 +15,14 @@ import fs from 'node:fs';
15
15
  import path from 'node:path';
16
16
  import { GRAPH_BUDGET_NOTES, graphEdges, localDate, scanNotes } from './zk.js';
17
17
  import { parseFrontmatter } from './frontmatter.js';
18
+ import { withoutFences } from './fence.js';
18
19
  // memory.ts 也 import 本模块(DREAM_INTERVAL_DAYS / daysSinceDream):这里是运行期才取用,
19
20
  // 循环引用在 ESM 下安全 —— 不要在模块顶层调用 memoryUsage。
20
21
  import { memoryUsage } from './memory.js';
21
22
  import { daysSinceDate, entryDate, isRetiredEntry, splitMemoryEntries, stripRetiredEntries } from './memory-format.js';
22
23
  import { isDayString } from './dates.js';
23
24
  import { normalizeTitle, noteKey, resolveWikiTarget, WIKI_LINK, wikiIndex } from './wikilink.js';
25
+ import { AUDIT_RATE, hasRecallSignal, lastRecallOf, readRecallSignal, RECALL_PROTECT_DAYS } from './recall-signal.js';
24
26
  /** 每栏最多回多少条(计划 §4 M3 的 50 条上限) */
25
27
  export const MAX_ITEMS = 50;
26
28
  /** topCited 只取前几名:给 agent 一个「本周被反复引用」的提示,不是排行榜 */
@@ -212,14 +214,16 @@ function promotionsOf(cfg, notes) {
212
214
  return out;
213
215
  const index = wikiIndex(notes);
214
216
  const byPath = new Map(notes.map((n) => [n.path, n]));
215
- for (const match of body.matchAll(WIKI_LINK)) {
217
+ // 代码块里的 `[[…]]` 是示例,不算「已经晋升过」
218
+ const clean = withoutFences(body);
219
+ for (const match of clean.matchAll(WIKI_LINK)) {
216
220
  const hit = resolveWikiTarget(cfg, String(match[1] ?? '').trim(), index);
217
221
  // 解析结果是路径,按身份键记账(§9.2):有 id 的笔记改名后仍是同一篇,不会重复晋升。
218
222
  const note = byPath.get(hit.path);
219
223
  if (hit.status === 'live' && note)
220
224
  out.set(noteKey(note), 'link');
221
225
  }
222
- const lines = stripRetiredEntries(body).body.split('\n').map((line) => normalizeTitle(line)).filter(Boolean);
226
+ const lines = withoutFences(stripRetiredEntries(body).body).split('\n').map((line) => normalizeTitle(line)).filter(Boolean);
223
227
  for (const note of notes) {
224
228
  const key = noteKey(note);
225
229
  if (out.has(key))
@@ -239,7 +243,7 @@ function promotionsOf(cfg, notes) {
239
243
  * · 显式写 `archive/` 的链接是有意引用旧结论(与 lint 同口径),不算来源断了;
240
244
  * · 无日期、无链接的不算候选(它们已经由 lint 的 undated / unlinked 报告)。
241
245
  */
242
- function retireCandidatesOf(cfg, notes, now) {
246
+ function retireCandidatesOf(cfg, notes, now, signal) {
243
247
  let body = '';
244
248
  try {
245
249
  body = fs.readFileSync(path.join(cfg.notebook, 'MEMORY.md'), 'utf8');
@@ -253,10 +257,14 @@ function retireCandidatesOf(cfg, notes, now) {
253
257
  for (const entry of splitMemoryEntries(body)) {
254
258
  if (isRetiredEntry(entry))
255
259
  continue;
260
+ // 15.2:近期被召回过的条目不算退役候选 —— 门控要看得见「其实一直被用到」
261
+ const last = lastRecallOf(signal, entry);
262
+ if (last && (daysSinceDate(last, now) ?? Infinity) <= RECALL_PROTECT_DAYS)
263
+ continue;
256
264
  const date = entryDate(entry) ?? '';
257
265
  const age = date ? (daysSinceDate(date, now) ?? -1) : -1;
258
266
  let reason = null;
259
- for (const match of entry.matchAll(WIKI_LINK)) {
267
+ for (const match of withoutFences(entry).matchAll(WIKI_LINK)) {
260
268
  const target = String(match[1] ?? '').trim();
261
269
  if (!target)
262
270
  continue;
@@ -287,6 +295,9 @@ function retireCandidatesOf(cfg, notes, now) {
287
295
  }
288
296
  export async function dreamNotebook(cfg, opts = {}, signal) {
289
297
  const now = opts.now ?? new Date();
298
+ // 15.2:默认关 / sidecar 为空时 signalActive=false,下面所有信号相关分支都不生效,输出逐字节不变
299
+ const recallSignal = readRecallSignal(cfg);
300
+ const signalActive = hasRecallSignal(recallSignal);
290
301
  const windowDays = windowDaysOf(cfg, now, opts.days);
291
302
  const sinceMs = now.getTime() - windowDays * 86_400_000;
292
303
  // 顺序跑:两个 zk 进程同时补索引会撞 SQLite 写锁(lint 里同样处理)
@@ -412,14 +423,31 @@ export async function dreamNotebook(cfg, opts = {}, signal) {
412
423
  // 排序说明(P2-12):先看「被日记提过几天」—— 跨天复现比同一天多次更强;同一天多篇日记
413
424
  // 再按 dailyMentions 排,入链数只是最后的次序。没有日记的库两项都是 0,
414
425
  // 排序自动退回原来的 cited 降序(行为兼容)。
426
+ // 15.2:信号生效时先按「召回跨天数 → 查询多样性」;全 0 时下面的次序与原排序完全一致。
415
427
  const topCited = notes
416
- .map((n) => ({ title: n.title, path: n.path, cited: citedOf(n), ...usageOf(n.path) }))
428
+ .map((n) => {
429
+ const r = recallSignal.byPath[n.path];
430
+ return {
431
+ title: n.title, path: n.path, cited: citedOf(n), ...usageOf(n.path),
432
+ ...(r ? { recallDays: r.days.length, recallKinds: r.queryKinds.length } : {}),
433
+ };
434
+ })
417
435
  .filter((x) => x.cited > 0)
418
- .sort((a, b) => b.daysMentioned - a.daysMentioned ||
436
+ .sort((a, b) => (signalActive ? (b.recallDays ?? 0) - (a.recallDays ?? 0) || (b.recallKinds ?? 0) - (a.recallKinds ?? 0) : 0) ||
437
+ b.daysMentioned - a.daysMentioned ||
419
438
  b.dailyMentions - a.dailyMentions ||
420
439
  b.cited - a.cited ||
421
440
  a.title.localeCompare(b.title))
422
441
  .slice(0, TOP_CITED);
442
+ // 15.2 审计流:固定比例、与分数无关、确定性(不看 cited / 日期,只按 path 字母序等距取样)。
443
+ // 仅信号生效时出现,且从窗口外积压里抽 —— 没被召回过的笔记否则永远拿不到「其实有用」的证据。
444
+ const auditSamples = [];
445
+ if (signalActive) {
446
+ const pool = [...backlogNotes].sort((a, b) => a.path.localeCompare(b.path));
447
+ const step = Math.max(1, Math.round(1 / AUDIT_RATE));
448
+ for (let i = 0; i < pool.length; i += step)
449
+ auditSamples.push(candidateOf(pool[i], ''));
450
+ }
423
451
  return {
424
452
  notebook: cfg.notebook,
425
453
  windowDays,
@@ -447,6 +475,7 @@ export async function dreamNotebook(cfg, opts = {}, signal) {
447
475
  topCited,
448
476
  dailyLooseEnds,
449
477
  memory: memoryUsage(cfg),
450
- retireCandidates: retireCandidatesOf(cfg, notes, now),
478
+ retireCandidates: retireCandidatesOf(cfg, notes, now, recallSignal),
479
+ ...(signalActive ? { auditSamples } : {}),
451
480
  };
452
481
  }
@@ -13,6 +13,7 @@
13
13
  * 口径:只认 wiki 双链与 Markdown 行内链接;找不到就不给这一栏(不猜、不拿「提到了标题」冒充链接)。
14
14
  */
15
15
  import path from 'node:path';
16
+ import { fenceMask } from './fence.js';
16
17
  import { normalizeTitle } from './wikilink.js';
17
18
  /** 一行的回显上限(码点):超了截断并留省略号,不把整段正文塞进工具输出 */
18
19
  const MAX_LINE = 160;
@@ -58,16 +59,14 @@ export function linkContextOf(markdown, target, sourcePath) {
58
59
  const content = String(markdown ?? '');
59
60
  if (!content.trim())
60
61
  return null;
62
+ const lines = content.split('\n');
63
+ const fenced = fenceMask(lines);
61
64
  let section = '';
62
- let fence = false;
63
- for (const line of content.split('\n')) {
65
+ for (let i = 0; i < lines.length; i++) {
64
66
  // 代码块里的 `[[...]]` 是例子,不是链接
65
- if (/^\s*(```|~~~)/.test(line)) {
66
- fence = !fence;
67
- continue;
68
- }
69
- if (fence)
67
+ if (fenced[i])
70
68
  continue;
69
+ const line = lines[i] ?? '';
71
70
  const heading = line.match(HEADING);
72
71
  if (heading) {
73
72
  section = heading[2].trim();
@@ -20,6 +20,7 @@
20
20
  import fs from 'node:fs';
21
21
  import path from 'node:path';
22
22
  import { parseFrontmatter } from './frontmatter.js';
23
+ import { withoutFences } from './fence.js';
23
24
  import { isMetaPath } from './meta.js';
24
25
  import { isRetiredEntry, splitMemoryEntries } from './memory-format.js';
25
26
  import { normalizeTitle, resolveWikiTarget, WIKI_LINK, wikiIndex } from './wikilink.js';
@@ -93,7 +94,8 @@ export function liveMemoryEntries(cfg) {
93
94
  for (const entry of splitMemoryEntries(body)) {
94
95
  if (isRetiredEntry(entry))
95
96
  continue;
96
- const targets = [...entry.matchAll(WIKI_LINK)]
97
+ // 代码块里的 `[[…]]` 是示例,不是检索入口
98
+ const targets = [...withoutFences(entry).matchAll(WIKI_LINK)]
97
99
  .map((match) => String(match[1] ?? '').trim())
98
100
  .filter(Boolean);
99
101
  if (targets.length === 0)
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Markdown 围栏代码块的唯一口径:渲染、时间轴、记忆切分、双链上下文、链接重写都从这里取。
3
+ *
4
+ * 之前每个模块各写一份 `^\s*``` `,认不认 `~~~`、几个反引号、闭合要不要同字符全不一样,
5
+ * 于是同一份笔记在只读视图里被解析成链接、在记忆里被当成可丢弃条目。口径(CommonMark + zk.ts 原有实现):
6
+ * · 行首 0–3 个空格 + ≥3 个同字符的 ` 或 ~ 才是围栏标记行,多余的前导空白不算;
7
+ * · 闭合行必须与开启行同字符、长度 ≥ 开启行,且不带 info(语言标记);
8
+ * · 围栏标记行与块内每一行都算「围栏内」—— 所有调用方都按这个口径跳过。
9
+ */
10
+ /** 一行是不是围栏标记行;不是返回 null */
11
+ export function fenceMarker(line) {
12
+ const m = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(String(line ?? ''));
13
+ if (!m)
14
+ return null;
15
+ const run = m[1] ?? '';
16
+ return { char: run[0] === '~' ? '~' : '`', len: run.length, info: (m[2] ?? '').trim() };
17
+ }
18
+ /**
19
+ * 每行是否属于围栏代码块(含开启 / 闭合标记行本身)。
20
+ * 闭合行必须同字符、长度 ≥ 开启行且无 info:块内出现的 ```js 只是代码,不是闭合。
21
+ */
22
+ export function fenceMask(lines) {
23
+ const mask = [];
24
+ let open = null;
25
+ for (const line of lines) {
26
+ const m = fenceMarker(line);
27
+ if (open) {
28
+ mask.push(true);
29
+ if (m && m.char === open.char && m.len >= open.len && !m.info)
30
+ open = null;
31
+ }
32
+ else {
33
+ mask.push(Boolean(m));
34
+ if (m)
35
+ open = m;
36
+ }
37
+ }
38
+ return mask;
39
+ }
40
+ /** 去掉围栏里的行,其余原样拼回(用于只扫「真正文」的正则匹配) */
41
+ export function withoutFences(text) {
42
+ const lines = String(text ?? '').split('\n');
43
+ const mask = fenceMask(lines);
44
+ return lines.filter((_, i) => !mask[i]).join('\n');
45
+ }
package/dist/lib/lint.js CHANGED
@@ -26,6 +26,7 @@ import fs from 'node:fs';
26
26
  import path from 'node:path';
27
27
  import { backlinksOf, GRAPH_BUDGET_NOTES, graphEdges, indexLagHint, localDate, MAX_SCAN, scanNotes, scanNotesWithFlag, outlinksOf, parseErrorWarnings, } from './zk.js';
28
28
  import { normalizeTitle, resolveWikiTarget, WIKI_LINK, wikiIndex } from './wikilink.js';
29
+ import { fenceMask } from './fence.js';
29
30
  import { parseFrontmatter } from './frontmatter.js';
30
31
  import { daysSinceDate, entryDate, isRetiredEntry, memoryFormatDebt, splitMemoryEntries } from './memory-format.js';
31
32
  import { AGENTS_TEMPLATE, AGENTS_TEMPLATE_FLAT, TEMPLATE_SENTINELS, TEMPLATE_VERSION, templateVersionOf } from './agents-template.js';
@@ -164,7 +165,13 @@ export function memoryLinkIssues(cfg, notes, opts = {}) {
164
165
  continue;
165
166
  }
166
167
  files += 1;
167
- for (const line of body.split('\n')) {
168
+ const lines = body.split('\n');
169
+ const fenced = fenceMask(lines);
170
+ for (let i = 0; i < lines.length; i++) {
171
+ // 代码块里的 `[[…]]` 是示例,不是来源链接
172
+ if (fenced[i])
173
+ continue;
174
+ const line = lines[i] ?? '';
168
175
  for (const match of line.matchAll(WIKI_LINK)) {
169
176
  links += 1;
170
177
  const target = String(match[1] ?? '').trim();
@@ -5,8 +5,10 @@
5
5
  * 只做机械解析,不做语义判断:
6
6
  * · 条目 = 顶层列表项 + 它的缩进续行(与 MEMORY.md 的书写约定一致);
7
7
  * · 退役 = 首行 `- [superseded …]`(大小写不敏感);
8
- * · 日期 = 首行里的 `YYYY-MM-DD`,且必须是真实存在的日期(`2026-99-99` 不算)。
8
+ * · 日期 = 首行里的 `YYYY-MM-DD`,且必须是真实存在的日期(`2026-99-99` 不算);
9
+ * · 围栏代码块整块算它所属条目的续行:块里的 `- ` / `[[…]]` 是示例,不是条目或来源。
9
10
  */
11
+ import { fenceMask, withoutFences } from './fence.js';
10
12
  /** 顶层列表项;缩进的子项算续行,不另起一条 */
11
13
  const LIST_ITEM = /^(?:[-*+]|\d+[.)])\s+/;
12
14
  /** 退役条目:`- [superseded 2026-01-01] 旧结论 → [[新结论]]`。必须带 `i`,与 lint 同口径 */
@@ -34,7 +36,16 @@ export function splitMemoryEntries(body) {
34
36
  out.push(current.join('\n'));
35
37
  current = null;
36
38
  };
37
- for (const line of String(body ?? '').split('\n')) {
39
+ const lines = String(body ?? '').split('\n');
40
+ const fenced = fenceMask(lines);
41
+ for (let i = 0; i < lines.length; i++) {
42
+ const line = lines[i] ?? '';
43
+ // 围栏整块跟着当前条目走:既不另起条目,也不把它后面的行误判成新条目
44
+ if (fenced[i]) {
45
+ if (current)
46
+ current.push(line);
47
+ continue;
48
+ }
38
49
  if (LIST_ITEM.test(line)) {
39
50
  flush();
40
51
  current = [line];
@@ -78,7 +89,7 @@ export function memoryFormatDebt(body) {
78
89
  for (const entry of entries) {
79
90
  if (!entryDate(entry))
80
91
  undated += 1;
81
- if (!LINK.test(entry))
92
+ if (!LINK.test(withoutFences(entry)))
82
93
  unlinked += 1;
83
94
  }
84
95
  return { total: entries.length, undated, unlinked };
@@ -91,7 +102,15 @@ export function stripRetiredEntries(body) {
91
102
  const out = [];
92
103
  let count = 0;
93
104
  let skipping = false;
94
- for (const line of String(body ?? '').split('\n')) {
105
+ const lines = String(body ?? '').split('\n');
106
+ const fenced = fenceMask(lines);
107
+ for (let i = 0; i < lines.length; i++) {
108
+ const line = lines[i] ?? '';
109
+ // 围栏里的 `- [superseded …]` 是示例,不参与退役判断
110
+ if (fenced[i]) {
111
+ out.push(line);
112
+ continue;
113
+ }
95
114
  if (LIST_ITEM.test(line)) {
96
115
  skipping = RETIRED.test(line);
97
116
  if (skipping) {
@@ -0,0 +1,187 @@
1
+ /**
2
+ * 记忆写路径:把一条结论追加进 MEMORY.md / USER.md。
3
+ *
4
+ * 边界(§15.1 / §16.1):插件只做机械门,语义判断全归调用方 ——
5
+ * · 不改 entry 一个字、不自动补日期、不自动合并 / 去重、不提议退役哪条;
6
+ * · 不做 replace / 合并:只往文件末尾追加,现有条目一律不动;
7
+ * · 超预算返回结构化错误 + dropCandidates,绝不静默截断;
8
+ * · 写前用 fileStamp 挡并发(与设置页 409 同语义)。
9
+ *
10
+ * `retire` 追加的是 `- [superseded …]` 标记(调用方给全文);退役条目在注入里被 strip,
11
+ * 所以不占预算、不做容量门。要让某条现行结论退役,调用方仍需用原生 edit 改写那一行 ——
12
+ * 这一步是语义判断,不在本工具里。
13
+ */
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+ import { fileStamp } from './file-stamp.js';
17
+ import { countWords, memoryCapacity } from './memory.js';
18
+ import { entryDate, isRetiredEntry, splitMemoryEntries } from './memory-format.js';
19
+ import { resolveWikiTarget, WIKI_LINK } from './wikilink.js';
20
+ const TARGET_FILE = { MEMORY: 'MEMORY.md', USER: 'USER.md' };
21
+ const LIST_ITEM = /^(?:[-*+]|\d+[.)])\s+/;
22
+ const PRE_IMAGE_LINES = 40;
23
+ const PRE_IMAGE_CHARS = 4000;
24
+ function reject(base, rejection, detail) {
25
+ return { ...base, accepted: false, rejection, detail };
26
+ }
27
+ /** 往文件末尾追加一条顶层列表项;不碰已有内容 */
28
+ function appendEntry(body, entry) {
29
+ const head = String(body ?? '').replace(/\s+$/, '');
30
+ return (head ? head + '\n\n' : '') + entry + '\n';
31
+ }
32
+ /** tmp + rename:写一半被杀不会留下半截 MEMORY.md */
33
+ function atomicWrite(file, text) {
34
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
35
+ fs.writeFileSync(tmp, text, 'utf8');
36
+ try {
37
+ fs.renameSync(tmp, file);
38
+ }
39
+ catch (err) {
40
+ try {
41
+ fs.unlinkSync(tmp);
42
+ }
43
+ catch { /* 已经不在了 */ }
44
+ throw err;
45
+ }
46
+ }
47
+ /** 周审复核材料:pre-image 摘要 + 一行 diff,只追加、不回改结论 */
48
+ function appendDreams(cfg, r, preImage) {
49
+ const at = new Date().toISOString();
50
+ // 审计流不能被 [[来源]] 里的换行注入任意行
51
+ const safeTarget = r.sourceTarget.replace(/[\r\n]+/g, ' ').trim();
52
+ const capped = preImage.length > PRE_IMAGE_CHARS ? preImage.slice(0, PRE_IMAGE_CHARS) + '\n…(pre-image 已截断)' : preImage;
53
+ const quoted = capped.split('\n').slice(0, PRE_IMAGE_LINES).map((line) => `> ${line}`).join('\n');
54
+ const block = [
55
+ '',
56
+ `## 记忆写入 ${at}(zk_memory_write)`,
57
+ '',
58
+ `- target: ${r.target} · action: ${r.action} · source: [[${safeTarget}]] → ${r.source || '(未解析)'}`,
59
+ `- pre-image stamp: ${r.stamp} · 词数 ${r.beforeWords} → ${r.afterWords}`,
60
+ `- diff: ${r.diff}`,
61
+ '',
62
+ '改前(pre-image 摘要):',
63
+ '',
64
+ quoted || '> (空文件)',
65
+ '',
66
+ ].join('\n');
67
+ fs.appendFileSync(path.join(cfg.notebook, 'DREAMS.md'), block, 'utf8');
68
+ }
69
+ export function writeMemory(cfg, input) {
70
+ const file = path.join(cfg.notebook, TARGET_FILE[input.target] ?? TARGET_FILE.MEMORY);
71
+ const entry = String(input.entry ?? '').trim();
72
+ let body = '';
73
+ try {
74
+ body = fs.readFileSync(file, 'utf8');
75
+ }
76
+ catch { /* 缺文件 = 空 */ }
77
+ const stamp = fileStamp(file);
78
+ const beforeWords = countWords(body);
79
+ const base = {
80
+ accepted: true,
81
+ rejection: '',
82
+ detail: '',
83
+ target: TARGET_FILE[input.target] ?? TARGET_FILE.MEMORY,
84
+ action: input.action === 'add' || input.action === 'retire' ? input.action : 'add',
85
+ dryRun: input.dryRun,
86
+ performed: false,
87
+ source: '',
88
+ sourceTarget: '',
89
+ stamp,
90
+ words: 0,
91
+ budget: 0,
92
+ headroom: 0,
93
+ extraWords: 0,
94
+ wouldTruncate: false,
95
+ needToFree: 0,
96
+ dropCandidates: [],
97
+ beforeWords,
98
+ afterWords: beforeWords,
99
+ diff: '',
100
+ indexComplete: input.indexComplete,
101
+ };
102
+ // 0. 枚举:宿主没拦住时也不能把脏值交给 path.join / 容量门,一律给结构化拒绝而不是抛
103
+ if (input.target !== 'MEMORY' && input.target !== 'USER') {
104
+ return reject(base, 'invalid-target', 'target 只能是 MEMORY 或 USER');
105
+ }
106
+ if (input.action !== 'add' && input.action !== 'retire') {
107
+ return reject(base, 'invalid-action', 'action 只能是 add 或 retire');
108
+ }
109
+ // 1. 形状:只能是单独一条顶层列表项,不带额外段落
110
+ const pieces = splitMemoryEntries(entry);
111
+ const firstLine = entry.split('\n', 1)[0] ?? '';
112
+ if (!entry || pieces.length !== 1 || !LIST_ITEM.test(firstLine) || pieces[0] !== entry) {
113
+ return reject(base, 'invalid-entry', 'entry 必须是一条顶层列表项(`- …`),不带额外段落;插件不改字');
114
+ }
115
+ // 2. 日期:首行带合法的 YYYY-MM-DD(与 memoryFormatDebt 同口径)
116
+ if (!entryDate(entry)) {
117
+ return reject(base, 'missing-date', '首行要带 YYYY-MM-DD 真实日期;插件不自动补');
118
+ }
119
+ // 3. 来源:带 [[…]] 且解析到活笔记
120
+ const links = [...entry.matchAll(WIKI_LINK)];
121
+ if (!links.length) {
122
+ return reject(base, 'missing-source', '要带 [[来源]];插件不自动补');
123
+ }
124
+ const sourceTarget = String(links[0][1] ?? '').trim();
125
+ const emptyIndex = { byTitle: new Map(), byId: new Map() };
126
+ const pathOnly = resolveWikiTarget(cfg, sourceTarget, emptyIndex);
127
+ // 索引没扫全 / 没起来时,标题式来源不能核实(可能只是前 10k 里碰巧有)—— 只放路径式过
128
+ if (!input.indexComplete && pathOnly.status !== 'live') {
129
+ base.sourceTarget = sourceTarget;
130
+ return reject(base, 'index-incomplete', '活笔记索引没扫全,标题式 [[来源]] 无法核实;改用笔记本根相对路径,或等索引可用后重试');
131
+ }
132
+ const resolved = resolveWikiTarget(cfg, sourceTarget, input.index);
133
+ base.sourceTarget = sourceTarget;
134
+ if (resolved.status !== 'live') {
135
+ const why = resolved.status === 'archived'
136
+ ? '指向归档 / superseded 笔记'
137
+ : '没找到(标题式来源在索引不可用时也解析不到)';
138
+ return reject(base, 'source-not-live', `[[${sourceTarget}]] ${why},没有晋升资格`);
139
+ }
140
+ base.source = resolved.path;
141
+ // 4. action 与条目形态要对得上(机械判断,不猜语义)
142
+ if (input.action === 'retire' && !isRetiredEntry(entry)) {
143
+ return reject(base, 'invalid-retire', 'action: retire 的 entry 必须是 `- [superseded …]` 形式');
144
+ }
145
+ if (input.action === 'add' && isRetiredEntry(entry)) {
146
+ return reject(base, 'invalid-add', '退役标记要用 action: retire;add 只收现行结论');
147
+ }
148
+ // 5. 容量门:只管 add(退役条目在注入里被 strip,不占预算)
149
+ const cap = memoryCapacity(cfg, { proposedEntry: input.action === 'add' ? entry : undefined });
150
+ base.words = cap.words;
151
+ base.budget = cap.budget;
152
+ base.headroom = cap.headroom;
153
+ base.extraWords = cap.extraWords;
154
+ base.wouldTruncate = cap.wouldTruncate;
155
+ base.needToFree = Math.max(0, cap.extraWords - cap.headroom);
156
+ base.dropCandidates = cap.dropCandidates;
157
+ if (input.action === 'add' && cap.wouldTruncate) {
158
+ return reject(base, 'over-budget', `再加 ${cap.extraWords} 词会触发截断(余 ${cap.headroom} 词),需先腾出 ${base.needToFree} 词;` +
159
+ 'dropCandidates 里是会让位给它的条目,插件不静默截断、也不替你退役');
160
+ }
161
+ // 6. 并发:预演时给的 stamp 必须与当前一致
162
+ if (input.expectStamp && input.expectStamp !== stamp) {
163
+ return reject(base, 'stale-stamp', '文件在预演之后被改过(stamp 不符),本次放弃;重新预演再写');
164
+ }
165
+ const diff = `+ ${firstLine.trim()}`;
166
+ base.diff = diff;
167
+ // 7. 预演到此为止:不改盘(索引 db 的刷新不算改记忆文件)
168
+ if (input.dryRun) {
169
+ base.detail = '预演通过:机械门都过了,没有动任何文件;确认后带 dry_run: false(可带 expect_stamp)执行';
170
+ return base;
171
+ }
172
+ // 8. 真写:落盘前再核一次指纹,期间有人改过就放弃
173
+ if (fileStamp(file) !== stamp) {
174
+ return reject(base, 'concurrent-change', '落盘前发现文件被改过(stamp 变了),本次放弃');
175
+ }
176
+ // 预演不建库,真写也不替调用方建库:目录不存在时给结构化拒绝,别让 atomicWrite 裸抛 ENOENT
177
+ if (!fs.existsSync(path.dirname(file))) {
178
+ return reject(base, 'no-notebook', '笔记本目录还不存在;先用别的工具或 zk-kit init 建好库再写');
179
+ }
180
+ const next = appendEntry(body, entry);
181
+ atomicWrite(file, next);
182
+ base.afterWords = countWords(next);
183
+ base.performed = true;
184
+ base.detail = `已追加到 ${base.target};pre-image 与 diff 已写进 DREAMS.md`;
185
+ appendDreams(cfg, base, body);
186
+ return base;
187
+ }
@@ -24,9 +24,11 @@
24
24
  import fs from 'node:fs';
25
25
  import path from 'node:path';
26
26
  import { DREAM_INTERVAL_DAYS, daysSinceDream, lastDreamDate } from './dream.js';
27
+ import { fenceMask } from './fence.js';
27
28
  import { fileStamp } from './file-stamp.js';
28
29
  import { entryDate, isRetiredEntry, memoryFormatDebt, splitMemoryEntries, stripRetiredEntries } from './memory-format.js';
29
30
  import { templateVersionOf } from './agents-template.js';
31
+ import { hasRecallSignal, lastRecallOf, readRecallSignal } from './recall-signal.js';
30
32
  import { PERSONA_META_FILES, MEMORY_META_FILES } from './meta.js';
31
33
  /** vault 根目录下、按优先级排列的三份 meta 文件(定义在 lib/meta.ts,这里只挂个本地名) */
32
34
  export const META_FILES = MEMORY_META_FILES;
@@ -61,8 +63,6 @@ const TOC_MAX = 5;
61
63
  const TOC_TITLE_MAX = 40;
62
64
  /** 到预算的这个比例就回显用量:等到截断才说,已经是最坏的时刻 */
63
65
  const MEMORY_NEAR_RATIO = 0.8;
64
- /** 围栏代码块:里面的 `- ` 与空行都不是条目 / 段落边界 */
65
- const FENCED = /^\s*(?:```|~~~)/;
66
66
  /** 二级小节(原有切分口径) */
67
67
  const SECTION = /^##\s+/;
68
68
  /** 顶层列表项;缩进的子项算续行,不另起一条 */
@@ -79,11 +79,10 @@ function splitItems(lines) {
79
79
  const head = [];
80
80
  const items = [];
81
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)) {
82
+ const fenced = fenceMask(lines);
83
+ for (let i = 0; i < lines.length; i++) {
84
+ const line = lines[i] ?? '';
85
+ if (!fenced[i] && LIST_ITEM.test(line)) {
87
86
  if (current)
88
87
  items.push(current);
89
88
  current = [line];
@@ -124,14 +123,13 @@ function degradeSingleSection(split) {
124
123
  */
125
124
  function splitSections(body) {
126
125
  const lines = String(body ?? '').split('\n');
127
- let fenced = false;
126
+ const fenced = fenceMask(lines);
128
127
  // 1a) `##` 小节
129
128
  const head = [];
130
129
  const sections = [];
131
- for (const line of lines) {
132
- if (FENCED.test(line))
133
- fenced = !fenced;
134
- if (!fenced && SECTION.test(line))
130
+ for (let i = 0; i < lines.length; i++) {
131
+ const line = lines[i] ?? '';
132
+ if (!fenced[i] && SECTION.test(line))
135
133
  sections.push([line]);
136
134
  else if (sections.length > 0)
137
135
  sections[sections.length - 1].push(line);
@@ -152,11 +150,9 @@ function splitSections(body) {
152
150
  // 1c) 空行段落:整篇散文也能按段丢。首段作为 head(通常是标题 / 开场),永远保留。
153
151
  const paragraphs = [];
154
152
  let para = null;
155
- fenced = false;
156
- for (const line of lines) {
157
- if (FENCED.test(line))
158
- fenced = !fenced;
159
- if (!fenced && !line.trim()) {
153
+ for (let i = 0; i < lines.length; i++) {
154
+ const line = lines[i] ?? '';
155
+ if (!fenced[i] && !line.trim()) {
160
156
  if (para)
161
157
  paragraphs.push(para);
162
158
  para = null;
@@ -606,6 +602,8 @@ export function memoryUsage(cfg) {
606
602
  * 纯读:不跑 zk、不写文件。同日 tie 只做可见化(G4),不改变 `oldestIndex` 的淘汰行为。
607
603
  */
608
604
  export function memoryCapacity(cfg, opts = {}) {
605
+ // 15.2:默认关 / 没有召回记录时不改变任何口径(suggestion 文本也保持「按位置决胜」)
606
+ const signal = readRecallSignal(cfg);
609
607
  const payload = buildMemoryPayload(cfg);
610
608
  const usage = memoryUsage(cfg);
611
609
  const extraWords = typeof opts.extraWords === 'number' && Number.isFinite(opts.extraWords)
@@ -626,11 +624,20 @@ export function memoryCapacity(cfg, opts = {}) {
626
624
  const withDate = entries.filter((row) => row.date !== null);
627
625
  const oldestDate = withDate.reduce((min, row) => (row.date < min ? row.date : min), '9999-99-99');
628
626
  const sameDateCount = withDate.filter((row) => row.date === oldestDate).length;
627
+ // 15.2:只有确实有条目带召回信号时才启用「最后召回时间」次级键,否则连文案都不变
628
+ const recallTie = hasRecallSignal(signal) && entries.some((row) => lastRecallOf(signal, row.entry) !== '');
629
+ const recallOf = (row) => recallTie ? lastRecallOf(signal, row.entry) : '';
629
630
  // 与 oldestIndex 同口径:有日期按最旧;同日期按位置靠后的先丢;没日期退回尾部(也是位置靠后先丢)
630
631
  const order = [...entries].sort((a, b) => {
631
632
  if (a.date && b.date) {
632
633
  if (a.date !== b.date)
633
634
  return a.date < b.date ? -1 : 1;
635
+ // 越久没被召回的越先丢;两边都没信号时仍是原来的位置决胜
636
+ if (recallTie) {
637
+ const la = recallOf(a), lb = recallOf(b);
638
+ if (la !== lb)
639
+ return la < lb ? -1 : 1;
640
+ }
634
641
  return b.index - a.index;
635
642
  }
636
643
  if (a.date)
@@ -661,9 +668,9 @@ export function memoryCapacity(cfg, opts = {}) {
661
668
  ? `再加 ${extraWords} 词会触发截断(余 ${usage.headroom} 词),先退役 / 精简 dropCandidates 里的条目`
662
669
  : `还能放 ${usage.headroom - extraWords} 词`)
663
670
  : (usage.headroom < 0 ? `已超预算 ${-usage.headroom} 词` : `余 ${usage.headroom} 词`)];
664
- // G4:同日不是「按日期挑的」,明说是位置决胜,不假装有使用频率
671
+ // G4:同日不是「按日期挑的」;15.2 有召回信号时明说改用了最后召回时间,不假装有使用频率
665
672
  if (sameDateCount > 1)
666
- parts.push(`${sameDateCount} 条同日,按位置决胜`);
673
+ parts.push(`${sameDateCount} 条同日,${recallTie ? '按最后召回时间决胜(无信号回退位置)' : '按位置决胜'}`);
667
674
  if (format.length)
668
675
  parts.push(`格式债:${format.join(' / ')}`);
669
676
  return {