dsh-zdiary-kit 3.8.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/README.md +33 -12
- package/dist/cli.js +51 -4
- 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 +373 -19
- package/dist/lib/agents-template.js +15 -8
- package/dist/lib/archive-probe.js +159 -0
- package/dist/lib/dream.js +36 -7
- package/dist/lib/edge-context.js +94 -0
- package/dist/lib/entry-points.js +206 -0
- package/dist/lib/fence.js +45 -0
- package/dist/lib/lint.js +8 -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 +35 -4
- package/dist/lib/timeline.js +18 -10
- package/dist/lib/usage.js +60 -0
- package/dist/lib/zk.js +207 -28
- package/docs/features/memory.md +22 -3
- package/docs/features/zk-tools.md +86 -4
- package/package.json +1 -1
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
+
}
|
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
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
import { countWords } from './memory.js';
|
|
2
|
+
import { entryPointsOf } from './entry-points.js';
|
|
3
|
+
import { archivedCounterparts } from './archive-probe.js';
|
|
4
|
+
import { bumpUsage } from './usage.js';
|
|
5
|
+
import { bumpRecall } from './recall-signal.js';
|
|
2
6
|
import { searchNotesDetailed } from './zk.js';
|
|
3
7
|
export const DEFAULT_RECALL_BUDGET = 500;
|
|
4
8
|
export const MAX_RECALL_BUDGET = 5_000;
|
|
@@ -36,9 +40,9 @@ function roundRobin(notes) {
|
|
|
36
40
|
}
|
|
37
41
|
return out;
|
|
38
42
|
}
|
|
39
|
-
/** 与 feature.ts 的 detailOf 同口径:snippet
|
|
43
|
+
/** 与 feature.ts 的 detailOf 同口径:15.6 先用 summary,空串再退回 snippet / lead(lead 实测就是 H1) */
|
|
40
44
|
function detailOf(n) {
|
|
41
|
-
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 ?? ''));
|
|
42
46
|
}
|
|
43
47
|
function entryText(n, index) {
|
|
44
48
|
const badges = [n.type, ...n.tags.map((t) => '#' + t)].filter(Boolean);
|
|
@@ -60,12 +64,25 @@ export async function assembleRecall(cfg, opts = {}, signal) {
|
|
|
60
64
|
}, signal);
|
|
61
65
|
const items = [];
|
|
62
66
|
const seen = new Set();
|
|
67
|
+
// R9:入口卡排在装配正文之前。`via: 'query'` 的条目指向的笔记可以不在本次结果里 ——
|
|
68
|
+
// 这是卢曼的索引方向(关键词 → 卡号),`via: 'result'` 那些已经在这段正文里,不重复占预算。
|
|
69
|
+
const entryPoints = entryPointsOf(cfg, result.notes, { query: opts.query });
|
|
70
|
+
let entryPointsInText = false;
|
|
71
|
+
const entryLines = entryPoints.points.filter((p) => p.via === 'query')
|
|
72
|
+
.map((p) => `· ${p.entry} → ${p.resolved ? p.absPath : `[[${p.title}]](用 zk_walk 走进去)`}`);
|
|
63
73
|
let text = '';
|
|
64
|
-
|
|
74
|
+
if (entryLines.length) {
|
|
75
|
+
const block = `入口(MEMORY 命中):\n${entryLines.join('\n')}`;
|
|
76
|
+
if (countWords(block) <= budget) {
|
|
77
|
+
text = block;
|
|
78
|
+
entryPointsInText = true;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
let used = text ? countWords(text) : 0;
|
|
65
82
|
let index = 0;
|
|
66
83
|
for (const n of roundRobin(result.notes)) {
|
|
67
84
|
const note = {
|
|
68
|
-
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',
|
|
69
86
|
};
|
|
70
87
|
if (seen.has(n.path)) {
|
|
71
88
|
note.reason = 'duplicate';
|
|
@@ -95,10 +112,24 @@ export async function assembleRecall(cfg, opts = {}, signal) {
|
|
|
95
112
|
index += 1;
|
|
96
113
|
items.push(note);
|
|
97
114
|
}
|
|
115
|
+
const counters = opts.includeArchived
|
|
116
|
+
? { entries: [], scanned: 0, truncated: false }
|
|
117
|
+
: archivedCounterparts(cfg, result.notes, { query: opts.query });
|
|
118
|
+
bumpUsage(cfg, [
|
|
119
|
+
'recall',
|
|
120
|
+
...(entryPoints.points.length ? ['entryPoints'] : []),
|
|
121
|
+
...(counters.entries.length ? ['counterEntries'] : []),
|
|
122
|
+
]);
|
|
123
|
+
bumpRecall(cfg, result.notes.map((n) => ({ path: n.path, title: n.title })), 'recall');
|
|
98
124
|
return {
|
|
99
125
|
text, used, budget,
|
|
100
126
|
completeness: result.completeness,
|
|
101
127
|
hasMore: result.hasMore,
|
|
102
128
|
notes: items,
|
|
129
|
+
entryPoints: entryPoints.points,
|
|
130
|
+
entryPointsTruncated: entryPoints.truncated,
|
|
131
|
+
entryPointsInText,
|
|
132
|
+
counterEntries: counters.entries,
|
|
133
|
+
counterEntriesTruncated: counters.truncated,
|
|
103
134
|
};
|
|
104
135
|
}
|