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/memory.js
CHANGED
|
@@ -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
|
-
|
|
83
|
-
for (
|
|
84
|
-
|
|
85
|
-
|
|
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
|
-
|
|
126
|
+
const fenced = fenceMask(lines);
|
|
128
127
|
// 1a) `##` 小节
|
|
129
128
|
const head = [];
|
|
130
129
|
const sections = [];
|
|
131
|
-
for (
|
|
132
|
-
|
|
133
|
-
|
|
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
|
-
|
|
156
|
-
|
|
157
|
-
if (
|
|
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 {
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 15.2 召回信号 sidecar:**可关的本地聚合计数**,不是查询日志。
|
|
3
|
+
*
|
|
4
|
+
* `zk_search` / `zk_query` / `zk_recall` 命中时按 path 记一笔「哪篇、哪天、被哪类检索命中」,
|
|
5
|
+
* 给 MEMORY 的晋升(topCited)、退役保护(retireCandidates)、同日淘汰、周审审计流
|
|
6
|
+
* 提供「其实被用过」的证据;否则没被召回过的笔记永远拿不到这类信号。
|
|
7
|
+
*
|
|
8
|
+
* 硬边界(§7.4 / §9.4 / §15.12):
|
|
9
|
+
* · 不记查询词、不记正文、不上报;`title` 只是命中笔记的标题,用来关联 MEMORY 的标题式 `[[来源]]`;
|
|
10
|
+
* · 默认关(`cfg.recallSignal`),关掉时不读不写,输出与改动前逐字节一致;
|
|
11
|
+
* · 原子写(tmp + rename)+ 失败静默,计数不能把工具调用弄失败;
|
|
12
|
+
* · 插件不跑定时器,只在工具调用内触发。
|
|
13
|
+
*/
|
|
14
|
+
import fs from 'node:fs';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import { WIKI_LINK } from './wikilink.js';
|
|
17
|
+
export const RECALL_SIGNAL_FILE = path.join('.zk', 'dsh-recall.json');
|
|
18
|
+
/** 每篇最多保留多少个不同召回日期,防止 sidecar 无限膨胀 */
|
|
19
|
+
export const MAX_RECALL_DAYS = 30;
|
|
20
|
+
/** 周审审计流的固定抽样比例(与分数无关、确定性) */
|
|
21
|
+
export const AUDIT_RATE = 0.1;
|
|
22
|
+
/** 最近这么多天内被召回过的 MEMORY 条目,不算退役候选 */
|
|
23
|
+
export const RECALL_PROTECT_DAYS = 30;
|
|
24
|
+
const empty = () => ({ version: 1, since: '', byPath: {} });
|
|
25
|
+
/** 「这份信号非空」按 signal 对象缓存:10k 篇时 for...in / Object.keys 每次都要 O(n) 枚举,
|
|
26
|
+
* 而排序比较器一条路径就会调上百次。readRecallSignal 构建时算一次,之后全是 O(1)。 */
|
|
27
|
+
const activeCache = new WeakMap();
|
|
28
|
+
/** 开关关闭 / 没有笔记本 / 文件坏了:一律空信号,调用方行为与改动前完全一致 */
|
|
29
|
+
export function readRecallSignal(cfg) {
|
|
30
|
+
if (cfg.recallSignal !== true || !cfg.notebook)
|
|
31
|
+
return empty();
|
|
32
|
+
try {
|
|
33
|
+
const raw = JSON.parse(fs.readFileSync(path.join(cfg.notebook, RECALL_SIGNAL_FILE), 'utf8'));
|
|
34
|
+
const out = empty();
|
|
35
|
+
if (typeof raw?.since === 'string')
|
|
36
|
+
out.since = raw.since;
|
|
37
|
+
let count = 0;
|
|
38
|
+
if (raw && typeof raw.byPath === 'object' && raw.byPath) {
|
|
39
|
+
for (const [p, value] of Object.entries(raw.byPath)) {
|
|
40
|
+
const e = value;
|
|
41
|
+
if (!e || typeof e !== 'object')
|
|
42
|
+
continue;
|
|
43
|
+
count += 1;
|
|
44
|
+
out.byPath[p] = {
|
|
45
|
+
count: Number.isFinite(Number(e.count)) ? Math.max(0, Math.trunc(Number(e.count))) : 0,
|
|
46
|
+
last: typeof e.last === 'string' ? e.last : '',
|
|
47
|
+
days: Array.isArray(e.days)
|
|
48
|
+
? e.days.filter((d) => typeof d === 'string').slice(-MAX_RECALL_DAYS)
|
|
49
|
+
: [],
|
|
50
|
+
queryKinds: Array.isArray(e.queryKinds)
|
|
51
|
+
? e.queryKinds.filter((k) => k === 'search' || k === 'query' || k === 'recall')
|
|
52
|
+
: [],
|
|
53
|
+
title: typeof e.title === 'string' ? e.title : '',
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
activeCache.set(out, count > 0);
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return empty();
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/** 有实际召回记录才算「信号生效」;开关打开但空文件仍按老口径走。
|
|
65
|
+
* readRecallSignal 已按对象算好;未经它构造的手工对象(测试 / 外部)才 fallback 一次短路判断。 */
|
|
66
|
+
export function hasRecallSignal(signal) {
|
|
67
|
+
const known = activeCache.get(signal);
|
|
68
|
+
if (known !== undefined)
|
|
69
|
+
return known;
|
|
70
|
+
let active = false;
|
|
71
|
+
for (const key in signal.byPath) {
|
|
72
|
+
if (key) {
|
|
73
|
+
active = true;
|
|
74
|
+
break;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
activeCache.set(signal, active);
|
|
78
|
+
return active;
|
|
79
|
+
}
|
|
80
|
+
/** 命中时记一笔:同一批里的同 path 只记一次;失败静默(计数器,不是账本) */
|
|
81
|
+
export function bumpRecall(cfg, hits, kind) {
|
|
82
|
+
if (cfg.recallSignal !== true || !hits.length || !cfg.notebook)
|
|
83
|
+
return;
|
|
84
|
+
const file = path.join(cfg.notebook, RECALL_SIGNAL_FILE);
|
|
85
|
+
const signal = readRecallSignal(cfg);
|
|
86
|
+
const now = new Date();
|
|
87
|
+
const today = now.toISOString().slice(0, 10);
|
|
88
|
+
if (!signal.since)
|
|
89
|
+
signal.since = now.toISOString();
|
|
90
|
+
const seen = new Set();
|
|
91
|
+
for (const hit of hits) {
|
|
92
|
+
if (!hit.path || seen.has(hit.path))
|
|
93
|
+
continue;
|
|
94
|
+
seen.add(hit.path);
|
|
95
|
+
const prev = signal.byPath[hit.path] ?? { count: 0, last: '', days: [], queryKinds: [], title: hit.title ?? '' };
|
|
96
|
+
signal.byPath[hit.path] = {
|
|
97
|
+
count: prev.count + 1,
|
|
98
|
+
last: today,
|
|
99
|
+
days: prev.days.includes(today) ? prev.days : [...prev.days, today].slice(-MAX_RECALL_DAYS),
|
|
100
|
+
queryKinds: prev.queryKinds.includes(kind) ? prev.queryKinds : [...prev.queryKinds, kind],
|
|
101
|
+
title: hit.title || prev.title,
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
105
|
+
try {
|
|
106
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
107
|
+
fs.writeFileSync(tmp, JSON.stringify(signal), 'utf8');
|
|
108
|
+
fs.renameSync(tmp, file);
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
try {
|
|
112
|
+
fs.rmSync(tmp, { force: true });
|
|
113
|
+
}
|
|
114
|
+
catch { /* 连清理都失败就只能算了 */ }
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* 一次工具调用内复用同一份索引:`memoryCapacity` 的排序比较器会反复调 `lastRecallOf`,
|
|
119
|
+
* 每次重建全量 lookup 会让 10k sidecar 退化到秒级。signal 只读不写(写只在 bumpRecall 的独立副本里),
|
|
120
|
+
* 所以用 WeakMap 按对象缓存,readRecallSignal 每次返回新对象,不会跨调用拿到过期索引。
|
|
121
|
+
*/
|
|
122
|
+
const lookupCache = new WeakMap();
|
|
123
|
+
/** 同一次调用里排序比较器会把同一条目反复比较,结果按 (signal, entry) 缓存 */
|
|
124
|
+
const resultCache = new WeakMap();
|
|
125
|
+
function recallLookup(signal) {
|
|
126
|
+
const cached = lookupCache.get(signal);
|
|
127
|
+
if (cached)
|
|
128
|
+
return cached;
|
|
129
|
+
const lookup = new Map();
|
|
130
|
+
for (const [p, e] of Object.entries(signal.byPath)) {
|
|
131
|
+
const stem = p.replace(/\.[^./]+$/, '');
|
|
132
|
+
for (const key of [p, stem, e.title]) {
|
|
133
|
+
if (key && e.last > (lookup.get(key) ?? ''))
|
|
134
|
+
lookup.set(key, e.last);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
lookupCache.set(signal, lookup);
|
|
138
|
+
return lookup;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* MEMORY 条目 → 最近召回日期。sidecar 的 path / stem / title 都建成键,
|
|
142
|
+
* 所以标题式 `[[标题]]` 与路径式 `[[notes/x]]` 都能关联上(纯 JS、不跑 zk)。
|
|
143
|
+
* signal 只读、entry 是字符串,结果确定 —— 一次调用内按 entry 缓存,避免排序比较器重复解析。
|
|
144
|
+
*/
|
|
145
|
+
export function lastRecallOf(signal, entry) {
|
|
146
|
+
if (!hasRecallSignal(signal))
|
|
147
|
+
return '';
|
|
148
|
+
let results = resultCache.get(signal);
|
|
149
|
+
if (!results) {
|
|
150
|
+
results = new Map();
|
|
151
|
+
resultCache.set(signal, results);
|
|
152
|
+
}
|
|
153
|
+
const cached = results.get(entry);
|
|
154
|
+
if (cached !== undefined)
|
|
155
|
+
return cached;
|
|
156
|
+
const lookup = recallLookup(signal);
|
|
157
|
+
let best = '';
|
|
158
|
+
for (const m of String(entry).matchAll(WIKI_LINK)) {
|
|
159
|
+
const target = String(m[1] ?? '').trim();
|
|
160
|
+
const hit = lookup.get(target) ?? lookup.get(target.replace(/\.[^./]+$/, ''));
|
|
161
|
+
if (hit && hit > best)
|
|
162
|
+
best = hit;
|
|
163
|
+
}
|
|
164
|
+
results.set(entry, best);
|
|
165
|
+
return best;
|
|
166
|
+
}
|
package/dist/lib/recall.js
CHANGED
|
@@ -2,6 +2,7 @@ import { countWords } from './memory.js';
|
|
|
2
2
|
import { entryPointsOf } from './entry-points.js';
|
|
3
3
|
import { archivedCounterparts } from './archive-probe.js';
|
|
4
4
|
import { bumpUsage } from './usage.js';
|
|
5
|
+
import { bumpRecall } from './recall-signal.js';
|
|
5
6
|
import { searchNotesDetailed } from './zk.js';
|
|
6
7
|
export const DEFAULT_RECALL_BUDGET = 500;
|
|
7
8
|
export const MAX_RECALL_BUDGET = 5_000;
|
|
@@ -39,9 +40,9 @@ function roundRobin(notes) {
|
|
|
39
40
|
}
|
|
40
41
|
return out;
|
|
41
42
|
}
|
|
42
|
-
/** 与 feature.ts 的 detailOf 同口径:snippet
|
|
43
|
+
/** 与 feature.ts 的 detailOf 同口径:15.6 先用 summary,空串再退回 snippet / lead(lead 实测就是 H1) */
|
|
43
44
|
function detailOf(n) {
|
|
44
|
-
return n.snippet && n.snippet !== n.lead ? n.snippet : (n.lead ?? '');
|
|
45
|
+
return n.summary || (n.snippet && n.snippet !== n.lead ? n.snippet : (n.lead ?? ''));
|
|
45
46
|
}
|
|
46
47
|
function entryText(n, index) {
|
|
47
48
|
const badges = [n.type, ...n.tags.map((t) => '#' + t)].filter(Boolean);
|
|
@@ -81,7 +82,7 @@ export async function assembleRecall(cfg, opts = {}, signal) {
|
|
|
81
82
|
let index = 0;
|
|
82
83
|
for (const n of roundRobin(result.notes)) {
|
|
83
84
|
const note = {
|
|
84
|
-
title: n.title, path: n.path, absPath: n.absPath, included: false, reason: 'over-budget',
|
|
85
|
+
title: n.title, path: n.path, absPath: n.absPath, summary: n.summary, included: false, reason: 'over-budget',
|
|
85
86
|
};
|
|
86
87
|
if (seen.has(n.path)) {
|
|
87
88
|
note.reason = 'duplicate';
|
|
@@ -119,6 +120,7 @@ export async function assembleRecall(cfg, opts = {}, signal) {
|
|
|
119
120
|
...(entryPoints.points.length ? ['entryPoints'] : []),
|
|
120
121
|
...(counters.entries.length ? ['counterEntries'] : []),
|
|
121
122
|
]);
|
|
123
|
+
bumpRecall(cfg, result.notes.map((n) => ({ path: n.path, title: n.title })), 'recall');
|
|
122
124
|
return {
|
|
123
125
|
text, used, budget,
|
|
124
126
|
completeness: result.completeness,
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 「空模板小节」的唯一判定:模板里装正文 / 论断 / 摘录的二级小节空着,
|
|
3
|
+
* 而同一篇里另有自己起的、有内容的二级小节 —— 内容在,只是被写到了别处,模板槽只剩一个标题。
|
|
4
|
+
*
|
|
5
|
+
* 根因是模板的 `{{content}}` 位置:`ENTRY_TEMPLATE` 是 `## Summary` → `## Content` → `{{content}}`,
|
|
6
|
+
* `SOURCE_TEMPLATE` 是 `## Summary` → `## Key claims` → `## Quotes` → `{{content}}`。
|
|
7
|
+
* 正文第一行就是 `## 一句话` / `## 问题:…` 时,前面那些槽必然空着 —— 这不是内容缺失,
|
|
8
|
+
* 是排版噪声(`zk_new` 的返回值与 `zk_lint` 都只提示,不改正文)。
|
|
9
|
+
*
|
|
10
|
+
* 为什么只认这三个槽:
|
|
11
|
+
* · `## Summary` 本来就选填(`zk_new` 给了 summary 才填),空着不是问题;
|
|
12
|
+
* · `## Links` 大多数笔记没有出链,空着是常态;
|
|
13
|
+
* · 其余标题(`## 一句话` / `## 问题:…`)是正文自己的结构,空不空由作者决定。
|
|
14
|
+
*
|
|
15
|
+
* 只看「槽空着」不够:`## Content` 空 + 整篇没有正文(新建的空笔记)不算错位。
|
|
16
|
+
* 所以再加一条:必须存在另一个有内容的二级小节,才说明内容在、只是没放进槽里。
|
|
17
|
+
*
|
|
18
|
+
* 判空口径与 zk 的标题一致:ATX、收尾井号是装饰;frontmatter 与围栏代码里的 `##`
|
|
19
|
+
* 既不算标题也不算正文(否则代码块里的示例会被当内容,或者被当小节)。
|
|
20
|
+
*/
|
|
21
|
+
import { fenceMask } from './fence.js';
|
|
22
|
+
/** 模板里装正文 / 论断 / 摘录的二级小节(英文模板标题,小写比较) */
|
|
23
|
+
export const TEMPLATE_CONTENT_SLOTS = ['content', 'key claims', 'quotes'];
|
|
24
|
+
/** 空着也不代表错位的二级小节:Summary 选填,Links 常年为空 */
|
|
25
|
+
const NEUTRAL_SECTIONS = ['summary', '摘要', 'links', '链接'];
|
|
26
|
+
function normalizeHeading(title) {
|
|
27
|
+
return title.trim().replace(/\s+/g, ' ').toLowerCase();
|
|
28
|
+
}
|
|
29
|
+
/** frontmatter 与围栏代码换成空行,行号保持不变 */
|
|
30
|
+
function maskLines(input) {
|
|
31
|
+
const masked = input.slice();
|
|
32
|
+
if ((masked[0] ?? '').trim() === '---') {
|
|
33
|
+
for (let i = 1; i < masked.length; i++) {
|
|
34
|
+
const text = (masked[i] ?? '').trim();
|
|
35
|
+
if (text === '---' || text === '...') {
|
|
36
|
+
for (let j = 0; j <= i; j++)
|
|
37
|
+
masked[j] = '';
|
|
38
|
+
break;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const fenced = fenceMask(masked);
|
|
43
|
+
for (let i = 0; i < masked.length; i++)
|
|
44
|
+
if (fenced[i])
|
|
45
|
+
masked[i] = '';
|
|
46
|
+
return masked;
|
|
47
|
+
}
|
|
48
|
+
function headingsOf(masked) {
|
|
49
|
+
const heads = [];
|
|
50
|
+
for (let i = 0; i < masked.length; i++) {
|
|
51
|
+
const m = /^(#{1,6})[ \t]+(.*?)[ \t]*$/.exec(masked[i] ?? '');
|
|
52
|
+
if (!m)
|
|
53
|
+
continue;
|
|
54
|
+
const title = (m[2] ?? '').replace(/[ \t]+#+$/, '').trim();
|
|
55
|
+
if (!title)
|
|
56
|
+
continue;
|
|
57
|
+
heads.push({ line: i + 1, level: (m[1] ?? '').length, title });
|
|
58
|
+
}
|
|
59
|
+
return heads;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* 找出空着的内容槽;没有(或没有「正文写到了别处」这个前提)就给空数组。
|
|
63
|
+
* 纯函数、只读文本:`zk_new` 建完收尾与 `zk_lint` 巡检共用同一份判定。
|
|
64
|
+
*/
|
|
65
|
+
export function emptyTemplateSlots(content) {
|
|
66
|
+
const lines = String(content ?? '').split('\n');
|
|
67
|
+
const masked = maskLines(lines);
|
|
68
|
+
const heads = headingsOf(masked);
|
|
69
|
+
const slots = new Set(TEMPLATE_CONTENT_SLOTS);
|
|
70
|
+
const neutral = new Set(NEUTRAL_SECTIONS);
|
|
71
|
+
/** 这一节到下一个同级 / 更高级标题之间(1 起、含上界) */
|
|
72
|
+
const sectionEnd = (k) => {
|
|
73
|
+
for (let i = k + 1; i < heads.length; i++) {
|
|
74
|
+
if (heads[i].level <= heads[k].level)
|
|
75
|
+
return heads[i].line - 1;
|
|
76
|
+
}
|
|
77
|
+
return lines.length;
|
|
78
|
+
};
|
|
79
|
+
const isEmptySection = (k) => {
|
|
80
|
+
const end = sectionEnd(k);
|
|
81
|
+
for (let ln = heads[k].line + 1; ln <= end; ln++) {
|
|
82
|
+
// 判空用原文、不用 masked:只含一个代码块的小节也算「有内容」(标题才必须从 masked 取)
|
|
83
|
+
if ((lines[ln - 1] ?? '').trim() !== '')
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
return true;
|
|
87
|
+
};
|
|
88
|
+
const adHoc = heads.some((h, k) => h.level === 2
|
|
89
|
+
&& !slots.has(normalizeHeading(h.title))
|
|
90
|
+
&& !neutral.has(normalizeHeading(h.title))
|
|
91
|
+
&& !isEmptySection(k));
|
|
92
|
+
if (!adHoc)
|
|
93
|
+
return [];
|
|
94
|
+
return heads
|
|
95
|
+
.filter((h, k) => h.level === 2 && slots.has(normalizeHeading(h.title)) && isEmptySection(k))
|
|
96
|
+
.map((h) => ({ heading: h.title, line: h.line }));
|
|
97
|
+
}
|
package/dist/lib/timeline.js
CHANGED
|
@@ -1,3 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 日记时间轴校验(v3.1 M0):只报告,不改文件(计划 §2 D1 / D2 / D5)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么单独一层:日记的 `## HH:MM` / `### HH:MM` 是人的工作面,空块、倒序、层级混用
|
|
5
|
+
* 都不会让 zk 报错,也不会影响检索 —— 只会让时间轴慢慢读不出顺序。自动重排会改正文顺序,
|
|
6
|
+
* diff 不可审,所以这里只产出问题清单,修不修由人或 agent 决定。
|
|
7
|
+
*
|
|
8
|
+
* 两种结构分开判:
|
|
9
|
+
* · layered(有 `## Events`,大小写不敏感):时间条目必须是 `### HH:MM`,且落在 Events 与下一个 `##` 之间;
|
|
10
|
+
* · flat(没有 `## Events`):时间条目必须是 `## HH:MM`,按文件顺序追加。
|
|
11
|
+
* 统一要求 `## Events` 会让所有 flat 日记一次性全红,所以用第一个 `## Events` 决定结构。
|
|
12
|
+
* 大小写不敏感是为了跟 `appendDaily` 对齐:`sectionRange` 用 `/^##\s+Events\s*$/i` 找小节,
|
|
13
|
+
* 这里若区分大小写,`## EVENTS` 会被判成 flat、然后 `### HH:MM` 全报位置错。
|
|
14
|
+
*/
|
|
15
|
+
import { fenceMask } from './fence.js';
|
|
1
16
|
/** 合法时间标题:00:00–23:59,可跟全角 / 半角括号标题 */
|
|
2
17
|
const TIME_TITLE = /^(?:[01]\d|2[0-3]):[0-5]\d(?:\s*[((].*[))])?$/;
|
|
3
18
|
/** 看起来像时间(用于抓 11:5x / 9:5 / 24:00 / 12:60 / 12:45 标题):格式错也要报 */
|
|
@@ -6,7 +21,6 @@ const TIME_LIKE = /^\d{1,2}:\d{1,2}/;
|
|
|
6
21
|
const HEADING = /^(#{1,6})[ \t]+(.*?)[ \t]*$/;
|
|
7
22
|
/** ATX 收尾井号是装饰(`### 12:00 ##` 的标题仍是 `12:00`),与 zk 的 atxHeading 同口径 */
|
|
8
23
|
const CLOSING_HASHES = /[ \t]+#+$/;
|
|
9
|
-
const FENCE = /^\s{0,3}(?:```|~~~)/;
|
|
10
24
|
/**
|
|
11
25
|
* 按行遮掉 frontmatter 与围栏代码:内容换成空行,行号保持不变。
|
|
12
26
|
* 不这样做,围栏里的示例 `## 12:00` 会被当成真的时间条目。
|
|
@@ -24,16 +38,10 @@ function maskLines(body) {
|
|
|
24
38
|
}
|
|
25
39
|
}
|
|
26
40
|
}
|
|
27
|
-
|
|
28
|
-
for (let i = 0; i < masked.length; i++)
|
|
29
|
-
if (
|
|
41
|
+
const fenced = fenceMask(masked);
|
|
42
|
+
for (let i = 0; i < masked.length; i++)
|
|
43
|
+
if (fenced[i])
|
|
30
44
|
masked[i] = '';
|
|
31
|
-
inFence = !inFence;
|
|
32
|
-
continue;
|
|
33
|
-
}
|
|
34
|
-
if (inFence)
|
|
35
|
-
masked[i] = '';
|
|
36
|
-
}
|
|
37
45
|
return masked;
|
|
38
46
|
}
|
|
39
47
|
function parseHeadings(lines) {
|
package/dist/lib/zk.js
CHANGED
|
@@ -18,6 +18,8 @@ import { parseFrontmatter, setFrontmatter } from './frontmatter.js';
|
|
|
18
18
|
import { isMetaPath, META_NAMES } from './meta.js';
|
|
19
19
|
import { similarCandidates } from './similar.js';
|
|
20
20
|
import { linkContextOf } from './edge-context.js';
|
|
21
|
+
import { fenceMask } from './fence.js';
|
|
22
|
+
import { emptyTemplateSlots } from './sections.js';
|
|
21
23
|
import { normalizeTitle, noteKey } from './wikilink.js';
|
|
22
24
|
export class ZkError extends Error {
|
|
23
25
|
hint;
|
|
@@ -759,6 +761,7 @@ function toRecord(raw, cfg, terms = []) {
|
|
|
759
761
|
modified: String(raw.modified ?? ''),
|
|
760
762
|
lead: String(raw.lead ?? '').replace(/\s+/g, ' ').trim().slice(0, 200),
|
|
761
763
|
snippet: buildSnippet(raw, terms),
|
|
764
|
+
summary: '',
|
|
762
765
|
words: Number(raw.wordCount ?? 0),
|
|
763
766
|
metadata,
|
|
764
767
|
id: meta('id'),
|
|
@@ -929,6 +932,7 @@ function parseLeanList(stdout, cfg, withSnippet = false) {
|
|
|
929
932
|
modified: leanIso(modified ?? ''),
|
|
930
933
|
lead,
|
|
931
934
|
snippet,
|
|
935
|
+
summary: '',
|
|
932
936
|
words: Number(words ?? 0),
|
|
933
937
|
metadata,
|
|
934
938
|
id: String(id ?? ''),
|
|
@@ -1053,7 +1057,8 @@ export async function searchNotesDetailed(cfg, opts = {}, signal) {
|
|
|
1053
1057
|
: extra.malformed || extra.strategyFailed ? 'unknown' : 'complete';
|
|
1054
1058
|
// R2:只有 complete 时 notes.length 才是精确总数;partial / unknown 不给 total。
|
|
1055
1059
|
const total = completeness === 'complete' ? { total: notes.length } : {};
|
|
1056
|
-
|
|
1060
|
+
// 15.6:只对可见命中读盘补 summary(O(limit) 本地 IO,零子进程);scanNotes 全库路径不经过这里
|
|
1061
|
+
return { notes: attachSummaries(cfg, notes.slice(0, limit)), hasMore: more, completeness, scanned: examined, ...total, matchStrategy: 'fts' };
|
|
1057
1062
|
};
|
|
1058
1063
|
/**
|
|
1059
1064
|
* mixed 的判据必须看「截断后的可见结果」:FTS 已占满 limit 时,正则补的那条
|
|
@@ -1576,6 +1581,7 @@ function noteFromDisk(cfg, abs) {
|
|
|
1576
1581
|
modified: stat.mtime.toISOString(),
|
|
1577
1582
|
lead: '',
|
|
1578
1583
|
snippet: '',
|
|
1584
|
+
summary: summarizeContent(content),
|
|
1579
1585
|
words: content.split(/\s+/).filter(Boolean).length,
|
|
1580
1586
|
metadata: { ...fields },
|
|
1581
1587
|
id: fields.id ?? '',
|
|
@@ -1802,7 +1808,23 @@ export async function createNote(cfg, input, signal, scan = (c, s) => allNotes(c
|
|
|
1802
1808
|
}
|
|
1803
1809
|
}
|
|
1804
1810
|
catch { /* 收尾失败:文件已落盘,不回滚、不误导 */ }
|
|
1805
|
-
|
|
1811
|
+
// 模板内容槽空着(正文自己起了 `##`):这是 `{{content}}` 落在 `## Content` 下面的必然形状。
|
|
1812
|
+
// 只报告、不改正文 —— 与 fillSummary 的「只填不删」同一原则;判定在 lib/sections.ts,lint 共用。
|
|
1813
|
+
let emptyTemplateSections = [];
|
|
1814
|
+
try {
|
|
1815
|
+
emptyTemplateSections = emptyTemplateSlots(fs.readFileSync(finalAbs, 'utf8')).map((slot) => slot.heading);
|
|
1816
|
+
}
|
|
1817
|
+
catch { /* 收尾失败:文件已落盘,不回滚 */ }
|
|
1818
|
+
return {
|
|
1819
|
+
path: relPathOf(cfg, finalAbs),
|
|
1820
|
+
absPath: finalAbs,
|
|
1821
|
+
title,
|
|
1822
|
+
archived,
|
|
1823
|
+
similar,
|
|
1824
|
+
summaryApplied,
|
|
1825
|
+
summaryWarning,
|
|
1826
|
+
emptyTemplateSections,
|
|
1827
|
+
};
|
|
1806
1828
|
}
|
|
1807
1829
|
/** 笔记本相对路径是否在归档目录下(supersede 会把文件搬进去,路径保持不变) */
|
|
1808
1830
|
function inArchive(cfg, rel) {
|
|
@@ -1856,24 +1878,55 @@ function atxHeading(line) {
|
|
|
1856
1878
|
const title = m[2].replace(/[ \t]+#+$/, '').trim();
|
|
1857
1879
|
return title ? { level: m[1].length, title } : null;
|
|
1858
1880
|
}
|
|
1859
|
-
/**
|
|
1860
|
-
function
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1881
|
+
/** `## Summary` / `## 摘要` 都算摘要节:写入(fillSummary)与读回(summarizeContent)共用同一口径 */
|
|
1882
|
+
function isSummaryTitle(title) {
|
|
1883
|
+
return /^(summary|摘要)$/i.test(title.trim());
|
|
1884
|
+
}
|
|
1885
|
+
/**
|
|
1886
|
+
* 15.6:从正文取一句话摘要,只读不改。
|
|
1887
|
+
* frontmatter 的 `summary` 标量优先;否则读 `## Summary` 一节,取到下一个同级 / 更高级标题之前,
|
|
1888
|
+
* 首段压空白、截到 240 字。没有这一节 / 读不到就返回空串(老笔记不假装有摘要)。
|
|
1889
|
+
*/
|
|
1890
|
+
export function summarizeContent(content) {
|
|
1891
|
+
const fromMeta = String(parseFrontmatter(content).fields.summary ?? '').replace(/\s+/g, ' ').trim();
|
|
1892
|
+
if (fromMeta)
|
|
1893
|
+
return fromMeta.slice(0, 240);
|
|
1894
|
+
const lines = String(content ?? '').split('\n');
|
|
1895
|
+
const fenced = fenceMask(lines);
|
|
1896
|
+
const heads = lines.map((line, i) => (fenced[i] ? null : atxHeading(line)));
|
|
1897
|
+
const target = heads.findIndex((h) => h !== null && isSummaryTitle(h.title));
|
|
1898
|
+
if (target < 0)
|
|
1899
|
+
return '';
|
|
1900
|
+
const head = heads[target];
|
|
1901
|
+
let end = lines.length;
|
|
1902
|
+
for (let i = target + 1; i < lines.length; i += 1) {
|
|
1903
|
+
const next = heads[i];
|
|
1904
|
+
if (next && next.level <= head.level) {
|
|
1905
|
+
end = i;
|
|
1906
|
+
break;
|
|
1874
1907
|
}
|
|
1875
1908
|
}
|
|
1876
|
-
return
|
|
1909
|
+
return lines.slice(target + 1, end).join('\n').replace(/\s+/g, ' ').trim().slice(0, 240);
|
|
1910
|
+
}
|
|
1911
|
+
/**
|
|
1912
|
+
* 15.6:给一批**已可见**的命中补 `summary`。逐条 `readFileSync` 是本地文件 IO、不是子进程,
|
|
1913
|
+
* 不改 LEAN 模板、不落索引、不给全库扫描用 —— 只挂在检索结果的出口(O(limit))。
|
|
1914
|
+
* 已有非空 summary 的行直接跳过,避免只读视图对同一批结果重复读盘。
|
|
1915
|
+
*/
|
|
1916
|
+
export function attachSummaries(cfg, notes) {
|
|
1917
|
+
return notes.map((n) => {
|
|
1918
|
+
if (n.summary)
|
|
1919
|
+
return n;
|
|
1920
|
+
const abs = n.absPath || (n.path ? path.resolve(cfg.notebook, n.path) : '');
|
|
1921
|
+
if (!abs)
|
|
1922
|
+
return n;
|
|
1923
|
+
try {
|
|
1924
|
+
return { ...n, summary: summarizeContent(fs.readFileSync(abs, 'utf8')) };
|
|
1925
|
+
}
|
|
1926
|
+
catch {
|
|
1927
|
+
return n;
|
|
1928
|
+
}
|
|
1929
|
+
});
|
|
1877
1930
|
}
|
|
1878
1931
|
/**
|
|
1879
1932
|
* 把一句话摘要填进 `## Summary`。
|
|
@@ -1892,10 +1945,9 @@ export function fillSummary(content, summary) {
|
|
|
1892
1945
|
if (!body)
|
|
1893
1946
|
return { text: content, applied: false };
|
|
1894
1947
|
const lines = String(content ?? '').split('\n');
|
|
1895
|
-
const fenced =
|
|
1948
|
+
const fenced = fenceMask(lines);
|
|
1896
1949
|
const heads = lines.map((line, i) => (fenced[i] ? null : atxHeading(line)));
|
|
1897
|
-
const
|
|
1898
|
-
const target = heads.findIndex((h) => h !== null && isSummary(h.title));
|
|
1950
|
+
const target = heads.findIndex((h) => h !== null && isSummaryTitle(h.title));
|
|
1899
1951
|
if (target >= 0) {
|
|
1900
1952
|
const head = heads[target];
|
|
1901
1953
|
let end = lines.length;
|
|
@@ -1909,7 +1961,7 @@ export function fillSummary(content, summary) {
|
|
|
1909
1961
|
if (lines.slice(target + 1, end).some((line) => line.trim() !== ''))
|
|
1910
1962
|
return { text: content, applied: false };
|
|
1911
1963
|
// 正文自己又写了一份 Summary(模板那一节只是空壳):那一节已经有主,不覆盖、也不在旁边再长一节
|
|
1912
|
-
const writtenByContent = heads.some((h, k) => k >= end && h !== null && h.level === head.level &&
|
|
1964
|
+
const writtenByContent = heads.some((h, k) => k >= end && h !== null && h.level === head.level && isSummaryTitle(h.title));
|
|
1913
1965
|
if (writtenByContent)
|
|
1914
1966
|
return { text: content, applied: false };
|
|
1915
1967
|
const out = [...lines.slice(0, target + 1), '', body, '', ...lines.slice(end)];
|
|
@@ -2317,10 +2369,12 @@ function relativeLinkPath(outDir, targetAbs, keepExt) {
|
|
|
2317
2369
|
rel = path.basename(targetAbs);
|
|
2318
2370
|
return keepExt ? rel : rel.replace(NOTE_EXT, '');
|
|
2319
2371
|
}
|
|
2320
|
-
/** 按计划重写一段 Markdown
|
|
2372
|
+
/** 按计划重写一段 Markdown 里的链接;返回新文本与被改条数。围栏里的示例链接不动 */
|
|
2321
2373
|
function relinkText(cfg, text, plan) {
|
|
2322
2374
|
let changed = 0;
|
|
2323
|
-
const
|
|
2375
|
+
const lines = String(text).split('\n');
|
|
2376
|
+
const masked = fenceMask(lines);
|
|
2377
|
+
const wikiOf = (line) => line.replace(WIKI_LINK, (whole, inner) => {
|
|
2324
2378
|
const bar = inner.indexOf('|');
|
|
2325
2379
|
const head = bar >= 0 ? inner.slice(0, bar) : inner;
|
|
2326
2380
|
const tail = bar >= 0 ? inner.slice(bar) : '';
|
|
@@ -2343,7 +2397,7 @@ function relinkText(cfg, text, plan) {
|
|
|
2343
2397
|
changed++;
|
|
2344
2398
|
return rebuilt;
|
|
2345
2399
|
});
|
|
2346
|
-
const
|
|
2400
|
+
const mdOf = (line) => line.replace(MD_LINK, (whole, prefix, dest, tail) => {
|
|
2347
2401
|
const angled = dest.startsWith('<') && dest.endsWith('>');
|
|
2348
2402
|
const raw = angled ? dest.slice(1, -1) : dest;
|
|
2349
2403
|
if (!raw || raw.startsWith('#'))
|
|
@@ -2368,7 +2422,7 @@ function relinkText(cfg, text, plan) {
|
|
|
2368
2422
|
changed++;
|
|
2369
2423
|
return rebuilt;
|
|
2370
2424
|
});
|
|
2371
|
-
return { text:
|
|
2425
|
+
return { text: lines.map((line, i) => (masked[i] ? line : mdOf(wikiOf(line)))).join('\n'), changed };
|
|
2372
2426
|
}
|
|
2373
2427
|
/** 新路径归一化:可只给文件名、可给目录(末尾 /),扩展名不变;跑出笔记本由 absPathOf 兜 */
|
|
2374
2428
|
function renameTargetRel(cfg, oldAbs, to) {
|
package/docs/features/memory.md
CHANGED
|
@@ -35,6 +35,8 @@
|
|
|
35
35
|
**Does not own.** MEMORY.md 写什么(agent 按 AGENTS.md 直接改文件,git diff 可审);
|
|
36
36
|
哪些记忆该晋升(语义判断是 agent 的活,插件只做机械截断);`MEMORY.md` 的写入路径 ——
|
|
37
37
|
它由人和 agent 直接编辑,`zk_append` / `zk_link` / `zk_supersede` 都会拒绝(追加会把记忆变成流水账,也丢掉「谁改的」这条审计线;后者还会把文件搬进 archive/)。
|
|
38
|
+
唯一的例外是 `zk_memory_write`(§15.1):它按机械门只往末尾追加一条调用方给的结论,并往 `DREAMS.md` 追加改前摘要与 diff;
|
|
39
|
+
不替换 / 合并 / 改写已有条目,也不自动判断该写什么,语义判断仍在调用方。
|
|
38
40
|
|
|
39
41
|
**人格层(0.10 M1)。** `PERSONA.md` 与 `MEMORY.md` 同级:根目录 meta,人类所有,
|
|
40
42
|
`zk_append` / `zk_new` / `zk_link` / `zk_supersede` 一律拒绝写入或搬移。
|