dsh-zdiary-kit 3.9.0 → 3.11.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 +10 -8
- package/dist/config/store.js +3 -0
- package/dist/features/readonly/feature.js +12 -10
- package/dist/features/readonly/html.js +10 -5
- package/dist/features/settings/client.js +1 -0
- package/dist/features/zk-tools/feature.js +178 -8
- package/dist/lib/agents-template.js +14 -8
- package/dist/lib/dream.js +36 -7
- package/dist/lib/edge-context.js +6 -7
- package/dist/lib/entry-points.js +3 -1
- package/dist/lib/fence.js +45 -0
- package/dist/lib/lint.js +66 -1
- package/dist/lib/memory-format.js +23 -4
- package/dist/lib/memory-write.js +187 -0
- package/dist/lib/memory.js +26 -19
- package/dist/lib/recall-signal.js +166 -0
- package/dist/lib/recall.js +5 -3
- package/dist/lib/sections.js +97 -0
- package/dist/lib/timeline.js +18 -10
- package/dist/lib/zk.js +80 -26
- package/docs/features/memory.md +2 -0
- package/docs/features/zk-tools.md +36 -4
- package/package.json +1 -1
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
|
-
|
|
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) =>
|
|
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.
|
|
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
|
}
|
package/dist/lib/edge-context.js
CHANGED
|
@@ -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
|
|
63
|
-
for (const line of content.split('\n')) {
|
|
65
|
+
for (let i = 0; i < lines.length; i++) {
|
|
64
66
|
// 代码块里的 `[[...]]` 是例子,不是链接
|
|
65
|
-
if (
|
|
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();
|
package/dist/lib/entry-points.js
CHANGED
|
@@ -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
|
-
|
|
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,8 @@ 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';
|
|
30
|
+
import { emptyTemplateSlots } from './sections.js';
|
|
29
31
|
import { parseFrontmatter } from './frontmatter.js';
|
|
30
32
|
import { daysSinceDate, entryDate, isRetiredEntry, memoryFormatDebt, splitMemoryEntries } from './memory-format.js';
|
|
31
33
|
import { AGENTS_TEMPLATE, AGENTS_TEMPLATE_FLAT, TEMPLATE_SENTINELS, TEMPLATE_VERSION, templateVersionOf } from './agents-template.js';
|
|
@@ -43,6 +45,8 @@ const MAX_ONE_WAY_TARGETS = 50;
|
|
|
43
45
|
const MAX_ONE_WAY_QUERIES = 60;
|
|
44
46
|
/** 时间轴只扫最近多少天(计划 §2 D4):一年日记会报几百条旧问题,把今天的问题挤出 50 条上限 */
|
|
45
47
|
export const TIMELINE_WINDOW_DAYS = 90;
|
|
48
|
+
/** 超过这个大小不读(同 TIMELINE_MAX_BYTES:巡检不该把一个大文件拉进内存) */
|
|
49
|
+
export const EMPTY_SECTION_MAX_BYTES = 1024 * 1024;
|
|
46
50
|
/** 超过这个大小的日记不读(doctor / lint 不该把 2 GiB 的日志拉进内存):跳过并计入 skipped */
|
|
47
51
|
export const TIMELINE_MAX_BYTES = 2 * 1024 * 1024;
|
|
48
52
|
/** 标题归一化与链接解析在 `lib/wikilink.ts`(dream 也用同一套);这里保留导出,免得调用方跟着搬 */
|
|
@@ -164,7 +168,13 @@ export function memoryLinkIssues(cfg, notes, opts = {}) {
|
|
|
164
168
|
continue;
|
|
165
169
|
}
|
|
166
170
|
files += 1;
|
|
167
|
-
|
|
171
|
+
const lines = body.split('\n');
|
|
172
|
+
const fenced = fenceMask(lines);
|
|
173
|
+
for (let i = 0; i < lines.length; i++) {
|
|
174
|
+
// 代码块里的 `[[…]]` 是示例,不是来源链接
|
|
175
|
+
if (fenced[i])
|
|
176
|
+
continue;
|
|
177
|
+
const line = lines[i] ?? '';
|
|
168
178
|
for (const match of line.matchAll(WIKI_LINK)) {
|
|
169
179
|
links += 1;
|
|
170
180
|
const target = String(match[1] ?? '').trim();
|
|
@@ -287,6 +297,19 @@ export function formatLintExtras(r) {
|
|
|
287
297
|
const timeline = formatTimeline(r.timeline);
|
|
288
298
|
if (timeline)
|
|
289
299
|
lines.push(timeline);
|
|
300
|
+
const emptySections = r.emptySections;
|
|
301
|
+
if (emptySections && emptySections.total > 0) {
|
|
302
|
+
// 文案只回显几篇:篇数按 notes 报全量,多出来的用省略号,不假装列全
|
|
303
|
+
const listed = emptySections.items.slice(0, 5);
|
|
304
|
+
const shown = listed
|
|
305
|
+
.map((i) => `${i.path}(${i.empty.map((e) => e.heading).join('、')})`)
|
|
306
|
+
.join('、');
|
|
307
|
+
lines.push(`⚠️ 空模板小节:${emptySections.total} 处 / ${emptySections.notes} 篇 — ${shown}` +
|
|
308
|
+
(emptySections.notes > listed.length ? ' …' : '') +
|
|
309
|
+
'|正文自己起了 ## 小节,模板的内容槽(Content / Key claims / Quotes)空着;删掉那行空标题,或把正文并进那一节' +
|
|
310
|
+
(emptySections.skipped > 0 ? `(另有 ${emptySections.skipped} 篇没读:文件过大或读不出来)` : '') +
|
|
311
|
+
'(只报告,不改写)');
|
|
312
|
+
}
|
|
290
313
|
if (r.missingId > 0) {
|
|
291
314
|
lines.push(`· 稳定 ID:${r.missingId} 篇没有 id — 新建的笔记已自动写入,老笔记只提示、不回填(§9.2)`);
|
|
292
315
|
}
|
|
@@ -584,6 +607,45 @@ export function templateStatus(cfg) {
|
|
|
584
607
|
return { ...base, mismatch: true, mismatchDetail, currentText };
|
|
585
608
|
return version < TEMPLATE_VERSION ? { ...base, currentText } : base;
|
|
586
609
|
}
|
|
610
|
+
/**
|
|
611
|
+
* 空模板小节:`## Content` / `## Key claims` / `## Quotes` 空着,而正文写在了别的 `##` 小节里。
|
|
612
|
+
*
|
|
613
|
+
* 判定在 `lib/sections.ts`(`zk_new` 建完收尾共用同一份),这里只负责读盘与计数。
|
|
614
|
+
* 日记不查:layered 的 `## Observations` / `## Loose ends` 空着是版式。
|
|
615
|
+
* 超过 `EMPTY_SECTION_MAX_BYTES` 或读不出来的文件不计入 `scanned` 而计入 `skipped` ——
|
|
616
|
+
* 不把「没读」当成「没有」。
|
|
617
|
+
*/
|
|
618
|
+
export function emptySectionStatus(cfg, notes, isDaily, max = MAX_ITEMS) {
|
|
619
|
+
let scanned = 0;
|
|
620
|
+
let skipped = 0;
|
|
621
|
+
let total = 0;
|
|
622
|
+
const items = [];
|
|
623
|
+
for (const note of notes) {
|
|
624
|
+
const abs = note.absPath ? path.resolve(note.absPath) : path.resolve(cfg.notebook, note.path);
|
|
625
|
+
// 日记不查:layered 模板的 Observations / Loose ends 空着是版式(每天新建都如此),不是噪声
|
|
626
|
+
if (isDaily(abs))
|
|
627
|
+
continue;
|
|
628
|
+
let body = '';
|
|
629
|
+
try {
|
|
630
|
+
if (fs.statSync(abs).size > EMPTY_SECTION_MAX_BYTES) {
|
|
631
|
+
skipped += 1;
|
|
632
|
+
continue;
|
|
633
|
+
}
|
|
634
|
+
body = fs.readFileSync(abs, 'utf8');
|
|
635
|
+
}
|
|
636
|
+
catch {
|
|
637
|
+
skipped += 1;
|
|
638
|
+
continue;
|
|
639
|
+
}
|
|
640
|
+
scanned += 1;
|
|
641
|
+
const empty = emptyTemplateSlots(body);
|
|
642
|
+
if (empty.length === 0)
|
|
643
|
+
continue;
|
|
644
|
+
total += empty.length;
|
|
645
|
+
items.push({ path: note.path, title: note.title, empty });
|
|
646
|
+
}
|
|
647
|
+
return { scanned, skipped, notes: items.length, total, truncated: items.length > max, items: items.slice(0, max) };
|
|
648
|
+
}
|
|
587
649
|
/**
|
|
588
650
|
* 最近 `TIMELINE_WINDOW_DAYS` 天的日记时间轴(计划 §2 D4)。
|
|
589
651
|
*
|
|
@@ -951,6 +1013,9 @@ export async function lintNotebook(cfg, opts = {}, signal) {
|
|
|
951
1013
|
template: templateStatus(cfg),
|
|
952
1014
|
persona: personaStatus(cfg),
|
|
953
1015
|
timeline: timelineStatus(cfg, now),
|
|
1016
|
+
// 模板空壳(`## Content` 空着、正文写在别的 `##` 下):读正文的桶,只对非日记笔记;
|
|
1017
|
+
// 上限 / 跳过的计数照实给出,别把「没读」当成「没有」
|
|
1018
|
+
emptySections: emptySectionStatus(cfg, notes, isDaily),
|
|
954
1019
|
// 150 篇(不含日记)是检索开始变糊的拐点:提示一下,不生成静态索引(会过期,还要决定谁更新)
|
|
955
1020
|
indexHint: nonDaily.length >= 150 && !fs.existsSync(path.join(cfg.notebook, 'INDEX.md')),
|
|
956
1021
|
// 放在最后算:前面的读命令已经把 pending 的 dirty 补掉了,剩下的是「补不上 / 外部编辑」
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
+
}
|