dsh-zdiary-kit 3.4.0 → 3.6.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 +22 -3
- package/dist/cli.js +23 -9
- package/dist/features/readonly/feature.js +26 -12
- package/dist/features/settings/feature.js +3 -2
- package/dist/features/zk-tools/feature.js +73 -23
- package/dist/lib/dream.js +6 -3
- package/dist/lib/lint.js +30 -10
- package/dist/lib/zk.js +594 -50
- package/docs/features/readonly.md +1 -1
- package/docs/features/zk-tools.md +22 -4
- package/package.json +1 -1
package/dist/lib/zk.js
CHANGED
|
@@ -11,6 +11,8 @@ import fs from 'node:fs';
|
|
|
11
11
|
import path from 'node:path';
|
|
12
12
|
import { BIN_DIR } from '../config/paths.js';
|
|
13
13
|
import { ExecError, findOnPath, run } from './exec.js';
|
|
14
|
+
import { readJson, writeJson } from './json-file.js';
|
|
15
|
+
import { withFileLockSync } from './lock.js';
|
|
14
16
|
import { parseFrontmatter, setFrontmatter } from './frontmatter.js';
|
|
15
17
|
import { isMetaPath, META_NAMES } from './meta.js';
|
|
16
18
|
import { similarCandidates } from './similar.js';
|
|
@@ -120,7 +122,7 @@ function baseArgs(cfg) {
|
|
|
120
122
|
/** stderr 里的一行 warning(`zk: warning: ...`),exit 0 时也会出现 */
|
|
121
123
|
const WARNING_LINE = /^zk: warning: /;
|
|
122
124
|
/**
|
|
123
|
-
* 索引策略。测试会改 `waitMs` / `autoBuildMaxNotes` 把等待压到毫秒级;
|
|
125
|
+
* 索引策略。测试会改 `waitMs` / `lockWaitMs` / `autoBuildMaxNotes` 把等待压到毫秒级;
|
|
124
126
|
* 生产路径一律用默认值(不要从配置里读 —— 这几个数是按 §0.5.1 的实测定的)。
|
|
125
127
|
*/
|
|
126
128
|
export const indexPolicy = {
|
|
@@ -128,6 +130,11 @@ export const indexPolicy = {
|
|
|
128
130
|
buildTimeoutMs: 30 * 60_000,
|
|
129
131
|
/** 冷建时最多阻塞工具调用多久;等不到就让调用先失败,后台继续建 */
|
|
130
132
|
waitMs: 15_000,
|
|
133
|
+
/**
|
|
134
|
+
* 别的进程持锁时,读路径最多等多久(显式重建传 `waitMs`)。
|
|
135
|
+
* 不能用 15 s:10k 库建库要几分钟,这期间的每次读都会白卡一轮。
|
|
136
|
+
*/
|
|
137
|
+
lockWaitMs: 2_000,
|
|
131
138
|
/** 这个规模以内让命令自己建:200 篇约 1 s,塞进长超时也不会卡住调用 */
|
|
132
139
|
autoBuildMaxNotes: 200,
|
|
133
140
|
/** 建索引连续失败时,这段时间内直接报错、不重启进程(避免 fork 风暴) */
|
|
@@ -148,6 +155,96 @@ export function indexStateOf(cfg) {
|
|
|
148
155
|
return 'interrupted';
|
|
149
156
|
return 'ready';
|
|
150
157
|
}
|
|
158
|
+
function indexStatePaths(cfg) {
|
|
159
|
+
const base = path.join(cfg.notebook, '.zk');
|
|
160
|
+
return { file: path.join(base, 'dsh-index-state.json'), lock: path.join(base, 'dsh-index-state.lock') };
|
|
161
|
+
}
|
|
162
|
+
function readIndexState(cfg) {
|
|
163
|
+
const raw = readJson(indexStatePaths(cfg).file, {});
|
|
164
|
+
const num = (v) => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? Math.floor(v) : 0);
|
|
165
|
+
return { generation: num(raw?.generation), indexedGeneration: num(raw?.indexedGeneration) };
|
|
166
|
+
}
|
|
167
|
+
/** 读-改-写走同一把跨进程锁,否则与 markIndexed 并发时会丢掉一次写(dirty 被误清) */
|
|
168
|
+
function withIndexState(cfg, fn) {
|
|
169
|
+
const { file, lock } = indexStatePaths(cfg);
|
|
170
|
+
return withFileLockSync(lock, () => {
|
|
171
|
+
const [next, value] = fn(readIndexState(cfg));
|
|
172
|
+
writeJson(file, next);
|
|
173
|
+
return value;
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
/** 写盘之后标脏:绝不能因为标脏失败,让已经落盘的写入看起来失败了 */
|
|
177
|
+
export function markIndexDirty(cfg) {
|
|
178
|
+
try {
|
|
179
|
+
withIndexState(cfg, (s) => [{ ...s, generation: s.generation + 1 }, undefined]);
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
const { file } = indexStatePaths(cfg);
|
|
183
|
+
const s = readIndexState(cfg);
|
|
184
|
+
try {
|
|
185
|
+
writeJson(file, { ...s, generation: s.generation + 1 });
|
|
186
|
+
}
|
|
187
|
+
catch { /* 连状态文件都写不了就认了 */ }
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
/** 建库成功:只清掉「这次建库开始前」的那些写入 */
|
|
191
|
+
function markIndexed(cfg, generation) {
|
|
192
|
+
try {
|
|
193
|
+
withIndexState(cfg, (s) => [
|
|
194
|
+
{ ...s, indexedGeneration: Math.max(s.indexedGeneration, generation) },
|
|
195
|
+
undefined,
|
|
196
|
+
]);
|
|
197
|
+
}
|
|
198
|
+
catch { /* 清不掉就留着 dirty,下一次读者再补一次,不影响正确性 */ }
|
|
199
|
+
}
|
|
200
|
+
/** 给测试 / doctor 看当前差值;不暴露写接口 */
|
|
201
|
+
export function indexDirtyState(cfg) {
|
|
202
|
+
return readIndexState(cfg);
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* 「索引可能落后」的粗判(doctor / zk_lint 只提示,不自动重建)。
|
|
206
|
+
*
|
|
207
|
+
* 两条线索:
|
|
208
|
+
* 1. 我们自己写盘留下的 dirty(generation > indexedGeneration)—— 准确;
|
|
209
|
+
* 2. 外部在插件之外动文件:只看顶层条目的 mtime(10⁴ 篇不付 10⁴ 次 stat)。
|
|
210
|
+
* 目录 mtime 只在**新增 / 删除 / 改名**时变;改已有文件的正文不会变 ——
|
|
211
|
+
* 所以正文的外部修改**一定漏报**,不是「可能漏报」。注释与文案都不要把这点说小。
|
|
212
|
+
*/
|
|
213
|
+
export function indexLagHint(cfg) {
|
|
214
|
+
if (!hasNotebook(cfg))
|
|
215
|
+
return null;
|
|
216
|
+
const { db } = indexPaths(cfg);
|
|
217
|
+
let dbMtime;
|
|
218
|
+
try {
|
|
219
|
+
dbMtime = fs.statSync(db).mtimeMs;
|
|
220
|
+
}
|
|
221
|
+
catch {
|
|
222
|
+
return '索引数据库不存在,下次检索会重建';
|
|
223
|
+
}
|
|
224
|
+
const s = readIndexState(cfg);
|
|
225
|
+
if (s.generation > s.indexedGeneration) {
|
|
226
|
+
return `还有 ${s.generation - s.indexedGeneration} 次写入没进索引(下次检索会自动补)`;
|
|
227
|
+
}
|
|
228
|
+
const metas = META_NAMES;
|
|
229
|
+
let newest = 0;
|
|
230
|
+
try {
|
|
231
|
+
for (const entry of fs.readdirSync(cfg.notebook, { withFileTypes: true })) {
|
|
232
|
+
if (entry.name === '.zk' || metas.includes(entry.name))
|
|
233
|
+
continue;
|
|
234
|
+
try {
|
|
235
|
+
newest = Math.max(newest, fs.statSync(path.join(cfg.notebook, entry.name)).mtimeMs);
|
|
236
|
+
}
|
|
237
|
+
catch { /* 读不到就跳过 */ }
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
catch {
|
|
241
|
+
return null;
|
|
242
|
+
}
|
|
243
|
+
// 留 1 s 余量:同一秒里建完索引又写文件,不算「落后」
|
|
244
|
+
return newest > dbMtime + 1000
|
|
245
|
+
? '笔记本顶层有新增 / 删除 / 改名,或索引落后于库(外部直接改正文不会被发现);到设置页点「重建索引」'
|
|
246
|
+
: null;
|
|
247
|
+
}
|
|
151
248
|
/** 估算篇数:只为了报「首次要扫 N 篇」,不追求精确,封顶 2 万(大库不必数完) */
|
|
152
249
|
function approxNoteCount(cfg, cap = 20_000) {
|
|
153
250
|
let count = 0;
|
|
@@ -196,24 +293,235 @@ function indexFailureText(err) {
|
|
|
196
293
|
return String(err).slice(0, 300);
|
|
197
294
|
}
|
|
198
295
|
const INDEX_HINT = '到设置页点「重建索引」,或在这个笔记本里跑 zk index 看完整输出';
|
|
199
|
-
/**
|
|
200
|
-
|
|
296
|
+
/** 锁文件刚建好、token 还没写完的宽限期:这段窗口里读不出 JSON 不能当 stale */
|
|
297
|
+
const LOCK_WRITE_GRACE_MS = 5_000;
|
|
298
|
+
function buildLockPath(cfg) {
|
|
299
|
+
return path.join(cfg.notebook, '.zk', 'dsh-index.lock');
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* 跨进程 single-flight(R6):O_EXCL 建锁,持锁者跑完整条 `zk index`。
|
|
303
|
+
* 进程内已有 builds Map;这一把锁管的是「插件进程 A 与 CLI 进程 B 同时看到 dirty」。
|
|
304
|
+
* 残留锁按「pid 还活着吗 / 是否超过建库预算」判 stale,不让崩过的进程永久堵住索引。
|
|
305
|
+
*/
|
|
306
|
+
function tryAcquireIndexLock(cfg) {
|
|
307
|
+
const file = buildLockPath(cfg);
|
|
308
|
+
const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
|
|
309
|
+
try {
|
|
310
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
311
|
+
}
|
|
312
|
+
catch (err) {
|
|
313
|
+
return { kind: 'failed', reason: errnoText(err) };
|
|
314
|
+
}
|
|
315
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
316
|
+
let fd;
|
|
317
|
+
try {
|
|
318
|
+
fd = fs.openSync(file, 'wx');
|
|
319
|
+
}
|
|
320
|
+
catch (err) {
|
|
321
|
+
const code = err.code;
|
|
322
|
+
// 只有 EEXIST 才是「别人持锁」;EACCES / EROFS / ENOSPC 是建不出来
|
|
323
|
+
if (code !== 'EEXIST')
|
|
324
|
+
return { kind: 'failed', reason: errnoText(err) };
|
|
325
|
+
if (!indexLockStale(file))
|
|
326
|
+
return { kind: 'held' };
|
|
327
|
+
try {
|
|
328
|
+
fs.rmSync(file, { force: true });
|
|
329
|
+
}
|
|
330
|
+
catch { /* 别人也在清:下一轮再说 */ }
|
|
331
|
+
continue;
|
|
332
|
+
}
|
|
333
|
+
try {
|
|
334
|
+
fs.writeFileSync(fd, JSON.stringify({ token, pid: process.pid, at: Date.now() }));
|
|
335
|
+
}
|
|
336
|
+
catch (err) {
|
|
337
|
+
// 半成品锁文件必须自己收掉:留着会让别人白等一个宽限期
|
|
338
|
+
try {
|
|
339
|
+
fs.rmSync(file, { force: true });
|
|
340
|
+
}
|
|
341
|
+
catch { /* 删不掉就靠宽限期 */ }
|
|
342
|
+
return { kind: 'failed', reason: errnoText(err) };
|
|
343
|
+
}
|
|
344
|
+
finally {
|
|
345
|
+
try {
|
|
346
|
+
fs.closeSync(fd);
|
|
347
|
+
}
|
|
348
|
+
catch { /* 已经关了 */ }
|
|
349
|
+
}
|
|
350
|
+
return { kind: 'acquired', lock: { token } };
|
|
351
|
+
}
|
|
352
|
+
return { kind: 'held' };
|
|
353
|
+
}
|
|
354
|
+
function errnoText(err) {
|
|
355
|
+
const code = err?.code;
|
|
356
|
+
return code || (err instanceof Error ? err.message : String(err));
|
|
357
|
+
}
|
|
358
|
+
function indexLockStale(file) {
|
|
359
|
+
let st;
|
|
360
|
+
try {
|
|
361
|
+
st = fs.statSync(file);
|
|
362
|
+
}
|
|
363
|
+
catch {
|
|
364
|
+
return true;
|
|
365
|
+
} // 锁没了:让下一轮重试
|
|
366
|
+
const age = Date.now() - st.mtimeMs;
|
|
367
|
+
if (age > indexPolicy.buildTimeoutMs)
|
|
368
|
+
return true;
|
|
369
|
+
let data;
|
|
370
|
+
try {
|
|
371
|
+
data = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
372
|
+
}
|
|
373
|
+
catch {
|
|
374
|
+
// 刚 openSync 还没写入 token(或写到一半):给几秒宽限。
|
|
375
|
+
// 这里若一律当 stale,会把别人刚建好的锁删掉,两个进程同时跑 zk index —— 正是这把锁要防的。
|
|
376
|
+
return age > LOCK_WRITE_GRACE_MS;
|
|
377
|
+
}
|
|
378
|
+
if (typeof data.pid === 'number') {
|
|
379
|
+
try {
|
|
380
|
+
process.kill(data.pid, 0);
|
|
381
|
+
}
|
|
382
|
+
catch {
|
|
383
|
+
return true;
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
return false;
|
|
387
|
+
}
|
|
388
|
+
function releaseIndexLock(cfg, lock) {
|
|
389
|
+
const file = buildLockPath(cfg);
|
|
390
|
+
try {
|
|
391
|
+
const data = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
392
|
+
if (data.token === lock.token)
|
|
393
|
+
fs.rmSync(file, { force: true });
|
|
394
|
+
}
|
|
395
|
+
catch { /* 已经被别人清掉了 */ }
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* 启动一次索引:进程内 single-flight 靠 builds Map,跨进程靠调用方先抢到的锁。
|
|
399
|
+
* 不传 lock 的只有两种:M5.0a 的冷建路径(db 本来就不完整,与 flush 互斥)、
|
|
400
|
+
* 以及锁建不出来时的降级(退回 R6 之前的行为,不让显式重建失败)。
|
|
401
|
+
* 成功时按「建库前拍下的 generation」清 dirty:建库期间的写入会留下差值,不会被误清。
|
|
402
|
+
*/
|
|
403
|
+
function startIndexBuild(cfg, loc, signal, lock) {
|
|
201
404
|
const key = cfg.notebook;
|
|
202
405
|
const startedAt = Date.now();
|
|
406
|
+
const generation = readIndexState(cfg).generation;
|
|
203
407
|
const promise = run(loc.bin, [...baseArgs(cfg), 'index', '--quiet'], {
|
|
204
408
|
signal,
|
|
205
409
|
timeoutMs: indexPolicy.buildTimeoutMs,
|
|
206
|
-
}).then(() => {
|
|
410
|
+
}).then(() => {
|
|
411
|
+
buildFailures.delete(key);
|
|
412
|
+
markIndexed(cfg, generation);
|
|
413
|
+
}, (err) => {
|
|
207
414
|
const message = indexFailureText(err);
|
|
208
415
|
buildFailures.set(key, { at: Date.now(), message });
|
|
209
416
|
throw new ZkError(`建索引失败:${message}`, INDEX_HINT, 'index-failed');
|
|
210
|
-
}).finally(() => {
|
|
417
|
+
}).finally(() => {
|
|
418
|
+
if (lock)
|
|
419
|
+
releaseIndexLock(cfg, lock);
|
|
420
|
+
builds.delete(key);
|
|
421
|
+
});
|
|
211
422
|
const build = { promise, startedAt };
|
|
212
423
|
builds.set(key, build);
|
|
213
424
|
// 后台任务常常没有 await 的人:别让 rejection 变成 unhandledRejection
|
|
214
425
|
promise.catch(() => { });
|
|
215
426
|
return build;
|
|
216
427
|
}
|
|
428
|
+
const STALE_INDEX_WARNING = '索引刷新还没完成,这次读的是「完整但可能过期」的索引(新写入稍后可见);不要手动再跑 zk index';
|
|
429
|
+
/** 同一条告警按「笔记本 + generation」去重:10k 库上每次读都刷一行只会把日志淹掉 */
|
|
430
|
+
const staleWarned = new Map();
|
|
431
|
+
function warnStaleOnce(cfg, warning) {
|
|
432
|
+
const generation = readIndexState(cfg).generation;
|
|
433
|
+
if (staleWarned.get(cfg.notebook) === generation)
|
|
434
|
+
return;
|
|
435
|
+
staleWarned.set(cfg.notebook, generation);
|
|
436
|
+
console.warn(`[zdiary] ${warning}`);
|
|
437
|
+
}
|
|
438
|
+
function indexIsDirty(cfg) {
|
|
439
|
+
const s = readIndexState(cfg);
|
|
440
|
+
return s.generation > s.indexedGeneration;
|
|
441
|
+
}
|
|
442
|
+
/** 等一次建库落地;不抛错、不吞掉后台任务(超时只是让调用方 stale 回退) */
|
|
443
|
+
async function waitForBuild(build, signal) {
|
|
444
|
+
let settled = null;
|
|
445
|
+
void build.promise.then(() => { settled = 'ok'; }, () => { settled = 'error'; });
|
|
446
|
+
const deadline = Date.now() + indexPolicy.waitMs;
|
|
447
|
+
while (settled === null && Date.now() < deadline) {
|
|
448
|
+
try {
|
|
449
|
+
await sleep(150, signal);
|
|
450
|
+
}
|
|
451
|
+
catch {
|
|
452
|
+
return 'timeout';
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
return settled ?? 'timeout';
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* 别的进程持锁时:等它放开,不并发起第二个 zk index。
|
|
459
|
+
* 读路径只等 `indexPolicy.lockWaitMs`(2 s):10k 库建库要几分钟,等满 15 s 只会让每次读都卡住。
|
|
460
|
+
*/
|
|
461
|
+
async function waitForIndexLockRelease(cfg, signal, budgetMs = indexPolicy.lockWaitMs) {
|
|
462
|
+
const file = buildLockPath(cfg);
|
|
463
|
+
const deadline = Date.now() + budgetMs;
|
|
464
|
+
while (Date.now() < deadline) {
|
|
465
|
+
if (!fs.existsSync(file))
|
|
466
|
+
return true;
|
|
467
|
+
try {
|
|
468
|
+
await sleep(150, signal);
|
|
469
|
+
}
|
|
470
|
+
catch {
|
|
471
|
+
return false;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
return false;
|
|
475
|
+
}
|
|
476
|
+
/**
|
|
477
|
+
* 读之前补一次增量索引(R6 的「写后可读」)。返回一条告警,或 null。
|
|
478
|
+
*
|
|
479
|
+
* 优先级(§9.3 第 4 步 / §10.3 第 2 条):db 不完整(missing / interrupted)时**一律不在这里建**,
|
|
480
|
+
* 交给紧随其后的 `ensureIndexReady` —— 它决定「小库自己补完 / 大库后台建并报 index-building」。
|
|
481
|
+
* 所以 stale 回退只可能落在「完整但过期的 db」上,绝不会退回读半库,
|
|
482
|
+
* 也就不会把 M5.0a 修掉的「读 → 杀 → 半库 → 再读」循环放回来。
|
|
483
|
+
*
|
|
484
|
+
* 挂在 zk() 这个唯一读入口上,searchNotesDetailed / lint / dream 以及 findNote / stats / 反查
|
|
485
|
+
* 都自动覆盖;不脏时只是一次 stat + 一次读状态文件。
|
|
486
|
+
*/
|
|
487
|
+
export async function flushIndexIfDirty(cfg, signal) {
|
|
488
|
+
if (!hasNotebook(cfg))
|
|
489
|
+
return null;
|
|
490
|
+
if (indexStateOf(cfg) !== 'ready')
|
|
491
|
+
return null;
|
|
492
|
+
if (!indexIsDirty(cfg))
|
|
493
|
+
return null;
|
|
494
|
+
const key = cfg.notebook;
|
|
495
|
+
let build = builds.get(key);
|
|
496
|
+
if (!build) {
|
|
497
|
+
// 先解析二进制、再抢锁:反过来的话 requireZk 抛错会把锁文件留到 30 分钟后才被判 stale
|
|
498
|
+
const loc = await requireZk(cfg);
|
|
499
|
+
for (let attempt = 0; attempt < 2 && !build; attempt += 1) {
|
|
500
|
+
const acquired = tryAcquireIndexLock(cfg);
|
|
501
|
+
if (acquired.kind === 'failed') {
|
|
502
|
+
return `索引锁建不出来(${acquired.reason}):这次读的是完整但可能过期的索引;检查 .zk 目录的权限与磁盘,再到设置页点「重建索引」`;
|
|
503
|
+
}
|
|
504
|
+
if (acquired.kind === 'held') {
|
|
505
|
+
// 另一个进程正在建:只等一小会儿;等不到就带着完整但过期的 db 继续(dirty 保留)
|
|
506
|
+
const released = await waitForIndexLockRelease(cfg, signal);
|
|
507
|
+
if (!indexIsDirty(cfg))
|
|
508
|
+
return null;
|
|
509
|
+
if (!released)
|
|
510
|
+
break;
|
|
511
|
+
continue;
|
|
512
|
+
}
|
|
513
|
+
build = startIndexBuild(cfg, loc, signal, acquired.lock);
|
|
514
|
+
}
|
|
515
|
+
if (!build)
|
|
516
|
+
return STALE_INDEX_WARNING;
|
|
517
|
+
}
|
|
518
|
+
const settled = await waitForBuild(build, signal);
|
|
519
|
+
if (settled === 'error')
|
|
520
|
+
return '刷新索引失败:这次读的是完整但可能过期的索引(dirty 已保留,下次会重试)';
|
|
521
|
+
if (settled === 'timeout')
|
|
522
|
+
return STALE_INDEX_WARNING;
|
|
523
|
+
return null;
|
|
524
|
+
}
|
|
217
525
|
/** 有 journal 但 db 还在长 → 是别的 zk 进程在写,不要去抢 */
|
|
218
526
|
async function indexBeingWritten(cfg) {
|
|
219
527
|
const { db } = indexPaths(cfg);
|
|
@@ -291,6 +599,13 @@ async function ensureIndexReady(cfg, loc, signal) {
|
|
|
291
599
|
export async function zk(cfg, args, opts = {}) {
|
|
292
600
|
const loc = await requireZk(cfg);
|
|
293
601
|
const explicitBuild = args[0] === 'init' || args[0] === 'index';
|
|
602
|
+
// 先补「写后可读」,再让 ensureIndexReady 判 db 是否完整:flush 只在完整 db 上跑,
|
|
603
|
+
// 万一它超时留下 journal,紧随其后的守卫会拦下这次读(见 flushIndexIfDirty 的优先级说明)。
|
|
604
|
+
if (!explicitBuild) {
|
|
605
|
+
const warning = await flushIndexIfDirty(cfg, opts.signal);
|
|
606
|
+
if (warning)
|
|
607
|
+
warnStaleOnce(cfg, warning);
|
|
608
|
+
}
|
|
294
609
|
const timeoutMs = explicitBuild
|
|
295
610
|
? (opts.timeoutMs ?? 60_000)
|
|
296
611
|
: (opts.timeoutMs ?? await ensureIndexReady(cfg, loc, opts.signal));
|
|
@@ -465,6 +780,91 @@ const HASHTAG = new RegExp(HASHTAG_SRC, 'u');
|
|
|
465
780
|
export function hasCjk(text) {
|
|
466
781
|
return CJK_TEXT.test(String(text ?? ''));
|
|
467
782
|
}
|
|
783
|
+
/**
|
|
784
|
+
* 全量遍历用的字段格式(plan §0.5.1):10k 实测 JSON 17.2 MB,
|
|
785
|
+
* 这些字段只要约 2 MB,且省掉 body / rawContent / snippets。
|
|
786
|
+
*
|
|
787
|
+
* 分隔符用控制字符:标题 / 标签 / lead 里几乎不会出现;lead 放最后,
|
|
788
|
+
* 解析时把剩余段重新拼回去,避免正文里的分隔符把记录切断。
|
|
789
|
+
*/
|
|
790
|
+
const LEAN_FIELD = '\u001f';
|
|
791
|
+
const LEAN_RECORD = '\u001e';
|
|
792
|
+
const LEAN_TAG = '\u001c';
|
|
793
|
+
const LEAN_TEMPLATE = [
|
|
794
|
+
'{{absPath}}',
|
|
795
|
+
'{{title}}',
|
|
796
|
+
'{{wordCount}}',
|
|
797
|
+
'{{created}}',
|
|
798
|
+
'{{modified}}',
|
|
799
|
+
`{{join tags "${LEAN_TAG}"}}`,
|
|
800
|
+
'{{metadata.status}}',
|
|
801
|
+
'{{metadata.type}}',
|
|
802
|
+
'{{metadata.authority}}',
|
|
803
|
+
'{{metadata.date}}',
|
|
804
|
+
'{{metadata.supersede-reason}}',
|
|
805
|
+
'{{lead}}',
|
|
806
|
+
].join(LEAN_FIELD);
|
|
807
|
+
/** zk 模板给的是 `2026-01-02 03:04:05 +0000 UTC`,转成 Date 能吃的 ISO(zk 存的是 UTC) */
|
|
808
|
+
function leanIso(value) {
|
|
809
|
+
const m = /^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})/.exec(String(value).trim());
|
|
810
|
+
return m ? `${m[1]}T${m[2]}Z` : String(value).trim();
|
|
811
|
+
}
|
|
812
|
+
/**
|
|
813
|
+
* 解析 LEAN_TEMPLATE 的输出。字段顺序与模板一一对应;不足 11 段说明 zk 行为变了,
|
|
814
|
+
* 记 malformed(调用方报 unknown,而不是把空数组当「没有笔记」)。
|
|
815
|
+
*/
|
|
816
|
+
function parseLeanList(stdout, cfg) {
|
|
817
|
+
const text = String(stdout ?? '');
|
|
818
|
+
if (!text.trim())
|
|
819
|
+
return { notes: [], malformed: false };
|
|
820
|
+
const notes = [];
|
|
821
|
+
let malformed = false;
|
|
822
|
+
for (const chunk of text.split(LEAN_RECORD)) {
|
|
823
|
+
const record = chunk.replace(/^[\r\n]+|[\r\n]+$/g, '');
|
|
824
|
+
if (!record.trim())
|
|
825
|
+
continue;
|
|
826
|
+
const parts = record.split(LEAN_FIELD);
|
|
827
|
+
if (parts.length < 11) {
|
|
828
|
+
malformed = true;
|
|
829
|
+
continue;
|
|
830
|
+
}
|
|
831
|
+
const [absPath, title, words, created, modified, tags, status, type, authority, date, reason] = parts;
|
|
832
|
+
const lead = parts.slice(11).join(LEAN_FIELD).replace(/\s+/g, ' ').trim().slice(0, 200);
|
|
833
|
+
const abs = absPath ?? '';
|
|
834
|
+
if (!abs) {
|
|
835
|
+
malformed = true;
|
|
836
|
+
continue;
|
|
837
|
+
}
|
|
838
|
+
const rel = path.relative(cfg.notebook, abs).split(path.sep).join('/');
|
|
839
|
+
const metadata = {};
|
|
840
|
+
if (status)
|
|
841
|
+
metadata.status = status;
|
|
842
|
+
if (type)
|
|
843
|
+
metadata.type = type;
|
|
844
|
+
if (authority)
|
|
845
|
+
metadata.authority = authority;
|
|
846
|
+
if (date)
|
|
847
|
+
metadata.date = date;
|
|
848
|
+
if (reason)
|
|
849
|
+
metadata['supersede-reason'] = reason;
|
|
850
|
+
notes.push({
|
|
851
|
+
title: String(title ?? ''),
|
|
852
|
+
path: rel,
|
|
853
|
+
absPath: abs,
|
|
854
|
+
link: `[[${rel.replace(/\.[^./]+$/, '')}]]`,
|
|
855
|
+
tags: String(tags ?? '').split(LEAN_TAG).map((t) => t.trim()).filter(Boolean),
|
|
856
|
+
created: leanIso(created ?? ''),
|
|
857
|
+
modified: leanIso(modified ?? ''),
|
|
858
|
+
lead,
|
|
859
|
+
words: Number(words ?? 0),
|
|
860
|
+
metadata,
|
|
861
|
+
status: String(status ?? ''),
|
|
862
|
+
type: String(type ?? ''),
|
|
863
|
+
authority: String(authority ?? ''),
|
|
864
|
+
});
|
|
865
|
+
}
|
|
866
|
+
return { notes, malformed };
|
|
867
|
+
}
|
|
468
868
|
/**
|
|
469
869
|
* 检索 + 用了哪种匹配策略。
|
|
470
870
|
*
|
|
@@ -477,10 +877,15 @@ export async function searchNotesDetailed(cfg, opts = {}, signal) {
|
|
|
477
877
|
const statuses = (opts.status ?? []).filter(Boolean);
|
|
478
878
|
const types = (opts.type ?? []).filter(Boolean);
|
|
479
879
|
const jsFilter = statuses.length > 0 || types.length > 0;
|
|
480
|
-
//
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
880
|
+
// 有 JS 过滤时不能只取前 200 条:10k 库里前 200 条可能只有 3 条 active,
|
|
881
|
+
// 而全库有 50 条 —— 那是静默漏结果,不是截断。zk 没有 offset,无法真分页;
|
|
882
|
+
// 改用只取必要字段的一次全量扫描(10k ≈ 2 MB / 2.6 s,JSON 是 17.2 MB),
|
|
883
|
+
// 取到 MAX_SCAN + 1 条,超过 MAX_SCAN 才能确定「触顶」而不是刚好 10 000 条。
|
|
884
|
+
const scanLimit = MAX_SCAN;
|
|
885
|
+
const build = (strategy, format, fetchLimit) => {
|
|
886
|
+
const args = ['list', '--quiet', '--no-pager', '--format', format, '--limit', String(fetchLimit)];
|
|
887
|
+
if (format === LEAN_TEMPLATE)
|
|
888
|
+
args.push('-d', LEAN_RECORD);
|
|
484
889
|
for (const name of excludedNames(cfg, { includeArchived: opts.includeArchived }))
|
|
485
890
|
args.push('-x', name);
|
|
486
891
|
if (opts.query)
|
|
@@ -509,40 +914,124 @@ export async function searchNotesDetailed(cfg, opts = {}, signal) {
|
|
|
509
914
|
// 否则工具枚举里给得出这个值、查询却永远命中 0 条。
|
|
510
915
|
const keep = (n) => (statuses.length === 0 || statuses.includes(n.status || 'active')) &&
|
|
511
916
|
(types.length === 0 || types.includes(n.type) || (types.includes('daily') && isUnderDir(n.path, cfg.dailyDir)));
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
917
|
+
/** 无 JS 过滤:limit + 1 就够判断 hasMore,继续走 JSON(小、字段全) */
|
|
918
|
+
const plainStrategy = async (strategy) => {
|
|
919
|
+
const notes = parseList(await zk(cfg, build(strategy, 'json', limit + 1), { signal }))
|
|
920
|
+
.map((raw) => toRecord(raw, cfg));
|
|
921
|
+
return { notes, examined: notes.length };
|
|
922
|
+
};
|
|
923
|
+
/** 有 JS 过滤:扫到 MAX_SCAN + 1,过滤后再按 limit 截断;字段格式见 LEAN_TEMPLATE */
|
|
924
|
+
const filteredStrategy = async (strategy) => {
|
|
925
|
+
const parsed = parseLeanList(await zk(cfg, build(strategy, LEAN_TEMPLATE, scanLimit + 1), { signal }), cfg);
|
|
926
|
+
return {
|
|
927
|
+
notes: parsed.notes.filter(keep),
|
|
928
|
+
examined: parsed.notes.length,
|
|
929
|
+
capped: parsed.notes.length > scanLimit,
|
|
930
|
+
malformed: parsed.malformed,
|
|
931
|
+
};
|
|
515
932
|
};
|
|
933
|
+
const finish = (notes, examined, extra = {}) => {
|
|
934
|
+
const more = notes.length > limit || extra.capped === true;
|
|
935
|
+
const completeness = more
|
|
936
|
+
? 'partial'
|
|
937
|
+
: extra.malformed || extra.strategyFailed ? 'unknown' : 'complete';
|
|
938
|
+
return { notes: notes.slice(0, limit), hasMore: more, completeness, scanned: examined, matchStrategy: 'fts' };
|
|
939
|
+
};
|
|
940
|
+
/**
|
|
941
|
+
* mixed 的判据必须看「截断后的可见结果」:FTS 已占满 limit 时,正则补的那条
|
|
942
|
+
* 即使存在也会被 slice 掉,不能还报 mixed(否则界面谎称补上了全文索引漏掉的)。
|
|
943
|
+
*/
|
|
944
|
+
const strategyOf = (base, merged) => {
|
|
945
|
+
const top = new Set(base.slice(0, limit).map((n) => n.path));
|
|
946
|
+
const visibleExtra = merged.slice(0, limit).some((n) => !top.has(n.path));
|
|
947
|
+
return visibleExtra ? (base.length ? 'mixed' : 'regex') : base.length ? 'fts' : 'regex';
|
|
948
|
+
};
|
|
949
|
+
if (!jsFilter) {
|
|
950
|
+
try {
|
|
951
|
+
const hits = await plainStrategy();
|
|
952
|
+
// 没有查询词 / 纯 ASCII:维持单进程
|
|
953
|
+
if (!opts.query || !hasCjk(opts.query)) {
|
|
954
|
+
if (hits.examined === 0 && opts.query) {
|
|
955
|
+
const retry = await plainStrategy('re');
|
|
956
|
+
return { ...finish(retry.notes, retry.examined), matchStrategy: 'regex' };
|
|
957
|
+
}
|
|
958
|
+
return finish(hits.notes, hits.examined);
|
|
959
|
+
}
|
|
960
|
+
// 含中文:FTS 与正则各跑一次,合并去重(FTS 的排序在前,正则补漏在后)。
|
|
961
|
+
// 正则这一路单独兜住:FTS 已经有结果时,子串匹配出错不该把整次检索拖成失败。
|
|
962
|
+
let regex = null;
|
|
963
|
+
let strategyFailed = false;
|
|
964
|
+
try {
|
|
965
|
+
regex = await plainStrategy('re');
|
|
966
|
+
}
|
|
967
|
+
catch (err) {
|
|
968
|
+
if (!(err instanceof ZkError))
|
|
969
|
+
throw err;
|
|
970
|
+
strategyFailed = true;
|
|
971
|
+
}
|
|
972
|
+
const seen = new Set(hits.notes.map((n) => n.path));
|
|
973
|
+
const merged = [...hits.notes];
|
|
974
|
+
for (const n of regex?.notes ?? []) {
|
|
975
|
+
if (seen.has(n.path))
|
|
976
|
+
continue;
|
|
977
|
+
seen.add(n.path);
|
|
978
|
+
merged.push(n);
|
|
979
|
+
}
|
|
980
|
+
return {
|
|
981
|
+
...finish(merged, hits.examined + (regex?.examined ?? 0), { strategyFailed }),
|
|
982
|
+
matchStrategy: strategyOf(hits.notes, merged),
|
|
983
|
+
};
|
|
984
|
+
}
|
|
985
|
+
catch (err) {
|
|
986
|
+
if (opts.query && err instanceof ZkError) {
|
|
987
|
+
const retry = await plainStrategy('re');
|
|
988
|
+
return { ...finish(retry.notes, retry.examined), matchStrategy: 'regex' };
|
|
989
|
+
}
|
|
990
|
+
throw err;
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
// ── 有 status / type 过滤:取足再过滤 ─────────────────────────────
|
|
516
994
|
try {
|
|
517
|
-
const hits = await
|
|
518
|
-
// 没有查询词 / 纯 ASCII:维持单进程
|
|
995
|
+
const hits = await filteredStrategy();
|
|
519
996
|
if (!opts.query || !hasCjk(opts.query)) {
|
|
520
|
-
if (hits.
|
|
521
|
-
|
|
522
|
-
|
|
997
|
+
if (hits.examined === 0 && opts.query) {
|
|
998
|
+
const retry = await filteredStrategy('re');
|
|
999
|
+
return { ...finish(retry.notes, retry.examined, retry), matchStrategy: 'regex' };
|
|
1000
|
+
}
|
|
1001
|
+
return finish(hits.notes, hits.examined, hits);
|
|
523
1002
|
}
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
// 退回 hits、按 fts 报告,与「正则没补到东西」是同一个可观测结果。
|
|
527
|
-
let regex = [];
|
|
1003
|
+
let regex = null;
|
|
1004
|
+
let strategyFailed = false;
|
|
528
1005
|
try {
|
|
529
|
-
regex = await
|
|
1006
|
+
regex = await filteredStrategy('re');
|
|
530
1007
|
}
|
|
531
1008
|
catch (err) {
|
|
532
1009
|
if (!(err instanceof ZkError))
|
|
533
1010
|
throw err;
|
|
1011
|
+
strategyFailed = true;
|
|
1012
|
+
}
|
|
1013
|
+
const seen = new Set(hits.notes.map((n) => n.path));
|
|
1014
|
+
const merged = [...hits.notes];
|
|
1015
|
+
for (const n of regex?.notes ?? []) {
|
|
1016
|
+
if (seen.has(n.path))
|
|
1017
|
+
continue;
|
|
1018
|
+
seen.add(n.path);
|
|
1019
|
+
merged.push(n);
|
|
534
1020
|
}
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
1021
|
+
return {
|
|
1022
|
+
...finish(merged, hits.examined + (regex?.examined ?? 0), {
|
|
1023
|
+
capped: hits.capped || regex?.capped === true,
|
|
1024
|
+
malformed: hits.malformed || regex?.malformed === true,
|
|
1025
|
+
strategyFailed,
|
|
1026
|
+
}),
|
|
1027
|
+
matchStrategy: strategyOf(hits.notes, merged),
|
|
1028
|
+
};
|
|
542
1029
|
}
|
|
543
1030
|
catch (err) {
|
|
544
|
-
if (opts.query && err instanceof ZkError)
|
|
545
|
-
|
|
1031
|
+
if (opts.query && err instanceof ZkError) {
|
|
1032
|
+
const retry = await filteredStrategy('re');
|
|
1033
|
+
return { ...finish(retry.notes, retry.examined, retry), matchStrategy: 'regex' };
|
|
1034
|
+
}
|
|
546
1035
|
throw err;
|
|
547
1036
|
}
|
|
548
1037
|
}
|
|
@@ -552,25 +1041,49 @@ export async function searchNotes(cfg, opts = {}, signal) {
|
|
|
552
1041
|
}
|
|
553
1042
|
/** 巡检 / 做梦一次最多扫多少篇:到顶就告警,不静默截断(静默失败最难查) */
|
|
554
1043
|
export const MAX_SCAN = 10_000;
|
|
555
|
-
/**
|
|
556
|
-
|
|
1044
|
+
/**
|
|
1045
|
+
* 一次取回全部笔记(巡检 / 做梦 / 首页用),并明确「有没有扫全」。
|
|
1046
|
+
*
|
|
1047
|
+
* 取 `limit + 1` 条:刚好等于 limit 时不能判断是不是触顶,多取一条才分得出
|
|
1048
|
+
* 「库里正好 10 000 篇」和「还有第 10 001 篇」。字段用 LEAN_TEMPLATE:
|
|
1049
|
+
* 10k 实测 JSON 17.2 MB / 2.3 s,精简格式约 2 MB / 2.6 s,少 8 倍字节。
|
|
1050
|
+
* `warnings` 见 `zk()`。
|
|
1051
|
+
*/
|
|
1052
|
+
export async function scanNotes(cfg, opts = {}, signal) {
|
|
557
1053
|
const limit = Math.min(MAX_SCAN, Math.max(1, Math.trunc(opts.limit ?? MAX_SCAN)));
|
|
558
|
-
const args = ['list', '--quiet', '--no-pager', '--format', '
|
|
1054
|
+
const args = ['list', '--quiet', '--no-pager', '--format', LEAN_TEMPLATE, '-d', LEAN_RECORD, '--limit', String(limit + 1)];
|
|
559
1055
|
for (const name of excludedNames(cfg, { includeArchived: opts.includeArchived }))
|
|
560
1056
|
args.push('-x', name);
|
|
561
|
-
|
|
1057
|
+
const parsed = parseLeanList(await zk(cfg, args, { signal, warnings: opts.warnings }), cfg);
|
|
1058
|
+
const capped = parsed.notes.length > limit;
|
|
1059
|
+
const notes = capped ? parsed.notes.slice(0, limit) : parsed.notes;
|
|
1060
|
+
// 与 searchNotesDetailed 的 finish 同口径:partial(触顶)优先于 unknown(解析失败),
|
|
1061
|
+
// 两种情况同时成立时先说「还有更多」,再说「解析可能不全」。
|
|
1062
|
+
const completeness = capped ? 'partial' : parsed.malformed ? 'unknown' : 'complete';
|
|
1063
|
+
return { notes, completeness, scanned: notes.length, limit };
|
|
1064
|
+
}
|
|
1065
|
+
/** 旧入口:只要笔记。需要三态(lint / dream / 首页)用 `scanNotes`。 */
|
|
1066
|
+
export async function allNotes(cfg, opts = {}, signal) {
|
|
1067
|
+
return (await scanNotes(cfg, opts, signal)).notes;
|
|
562
1068
|
}
|
|
563
1069
|
/**
|
|
564
1070
|
* 用 zk 的过滤器挑笔记,只取**绝对路径**。
|
|
565
1071
|
* 别用 `{{path}}`:它相对 cwd,换个工作目录就变成 `../../tmp/...`(Z4 同款坑)。
|
|
566
|
-
*
|
|
1072
|
+
* 一类过滤器一次进程,不要按笔记逐条跑;取 MAX_SCAN + 1 条才能区分「正好 10 000」与「还有更多」。
|
|
567
1073
|
*/
|
|
568
|
-
export async function
|
|
569
|
-
const args = ['list', '--quiet', '--no-pager', '--format', '{{absPath}}', '--limit',
|
|
1074
|
+
export async function scanNotesWithFlag(cfg, flag, signal) {
|
|
1075
|
+
const args = ['list', '--quiet', '--no-pager', '--format', '{{absPath}}', '--limit', String(MAX_SCAN + 1), flag];
|
|
570
1076
|
for (const name of excludedNames(cfg))
|
|
571
1077
|
args.push('-x', name);
|
|
572
1078
|
const out = await zk(cfg, args, { signal });
|
|
573
|
-
|
|
1079
|
+
const all = out.split('\n').map((line) => line.trim()).filter(Boolean);
|
|
1080
|
+
const capped = all.length > MAX_SCAN;
|
|
1081
|
+
const paths = capped ? all.slice(0, MAX_SCAN) : all;
|
|
1082
|
+
return { paths, completeness: capped ? 'partial' : 'complete', scanned: paths.length };
|
|
1083
|
+
}
|
|
1084
|
+
/** 旧入口:只要路径(调用方不需要三态时用) */
|
|
1085
|
+
export async function notesWithFlag(cfg, flag, signal) {
|
|
1086
|
+
return (await scanNotesWithFlag(cfg, flag, signal)).paths;
|
|
574
1087
|
}
|
|
575
1088
|
/**
|
|
576
1089
|
* `zk graph` 的 `--limit` 上限。注意它限的是**笔记载入数**(`zk graph --help`:`Limit the number of notes found`),
|
|
@@ -596,13 +1109,13 @@ export async function graphEdges(cfg, signal, opts = {}) {
|
|
|
596
1109
|
const start = text.indexOf('{');
|
|
597
1110
|
const end = text.lastIndexOf('}');
|
|
598
1111
|
if (start < 0 || end <= start)
|
|
599
|
-
return { edges: [], truncated: false };
|
|
1112
|
+
return { edges: [], truncated: false, completeness: 'unknown' };
|
|
600
1113
|
let graph;
|
|
601
1114
|
try {
|
|
602
1115
|
graph = JSON.parse(text.slice(start, end + 1));
|
|
603
1116
|
}
|
|
604
1117
|
catch {
|
|
605
|
-
return { edges: [], truncated: false };
|
|
1118
|
+
return { edges: [], truncated: false, completeness: 'unknown' };
|
|
606
1119
|
}
|
|
607
1120
|
const out = [];
|
|
608
1121
|
const nodes = new Set();
|
|
@@ -618,7 +1131,10 @@ export async function graphEdges(cfg, signal, opts = {}) {
|
|
|
618
1131
|
}
|
|
619
1132
|
// notes 是实际载入的笔记数;两个条件取或,宁可多报一次也别静默漏掉告警
|
|
620
1133
|
const loaded = Array.isArray(graph.notes) ? graph.notes.length : 0;
|
|
621
|
-
|
|
1134
|
+
const truncated = loaded >= limit || nodes.size >= limit;
|
|
1135
|
+
// 没有 notes 数组(老 zk)时,nodes 没到上限也不能断言完整
|
|
1136
|
+
const completeness = truncated ? 'partial' : Array.isArray(graph.notes) ? 'complete' : 'unknown';
|
|
1137
|
+
return { edges: out, truncated, completeness };
|
|
622
1138
|
}
|
|
623
1139
|
/**
|
|
624
1140
|
* 全图预算的默认值(篇数):真正生效的是配置 `graphBudgetNotes`(默认取它)。
|
|
@@ -641,15 +1157,16 @@ async function linkedNotes(cfg, flag, rel, opts = {}, signal) {
|
|
|
641
1157
|
const root = path.resolve(cfg.notebook);
|
|
642
1158
|
const abs = path.resolve(cfg.notebook, rel);
|
|
643
1159
|
if (abs !== root && !abs.startsWith(root + path.sep))
|
|
644
|
-
return { notes: [], truncated: false };
|
|
1160
|
+
return { notes: [], truncated: false, completeness: 'complete' };
|
|
645
1161
|
if (!fs.existsSync(abs))
|
|
646
|
-
return { notes: [], truncated: false };
|
|
1162
|
+
return { notes: [], truncated: false, completeness: 'complete' };
|
|
647
1163
|
const limit = Math.min(MAX_SCAN, Math.max(1, Math.trunc(opts.limit ?? MAX_LINK_NOTES)));
|
|
648
1164
|
const args = ['list', '--quiet', '--no-pager', '--format', 'json', '--limit', String(limit + 1), flag, abs];
|
|
649
1165
|
for (const name of excludedNames(cfg, { includeArchived: opts.includeArchived }))
|
|
650
1166
|
args.push('-x', name);
|
|
651
1167
|
const notes = parseList(await zk(cfg, args, { signal })).map((raw) => toRecord(raw, cfg));
|
|
652
|
-
|
|
1168
|
+
const truncated = notes.length > limit;
|
|
1169
|
+
return { notes: notes.slice(0, limit), truncated, completeness: truncated ? 'partial' : 'complete' };
|
|
653
1170
|
}
|
|
654
1171
|
/** 谁链到这篇(入链 / 反链)。路径是笔记本相对的;目标不存在时返回空,不返回全库 */
|
|
655
1172
|
export async function backlinksOf(cfg, rel, opts = {}, signal) {
|
|
@@ -991,8 +1508,10 @@ export async function createNote(cfg, input, signal, scan = (c, s) => allNotes(c
|
|
|
991
1508
|
const text = fs.readFileSync(finalAbs, 'utf8');
|
|
992
1509
|
const filled = fillSummary(text, input.summary);
|
|
993
1510
|
summaryApplied = filled.applied;
|
|
994
|
-
if (filled.text !== text)
|
|
1511
|
+
if (filled.text !== text) {
|
|
995
1512
|
fs.writeFileSync(finalAbs, filled.text, 'utf8');
|
|
1513
|
+
markIndexDirty(cfg); // zk new 索引的是回填前的文件;摘要要等下一次 index 才搜得到
|
|
1514
|
+
}
|
|
996
1515
|
if (!filled.applied) {
|
|
997
1516
|
summaryWarning = 'summary 没写进去:正文里已经有一节 Summary(没覆盖它),要改就直接编辑那一节';
|
|
998
1517
|
}
|
|
@@ -1167,6 +1686,7 @@ export function appendToNote(cfg, p, text, opts = {}) {
|
|
|
1167
1686
|
fs.appendFileSync(abs, `${sep}${heading}${body}\n`, 'utf8');
|
|
1168
1687
|
}
|
|
1169
1688
|
const bytes = fs.statSync(abs).size;
|
|
1689
|
+
markIndexDirty(cfg);
|
|
1170
1690
|
return { path: relPathOf(cfg, abs), appendedChars: body.length, bytes };
|
|
1171
1691
|
}
|
|
1172
1692
|
/**
|
|
@@ -1235,6 +1755,7 @@ export async function linkNotes(cfg, fromPath, target, signal) {
|
|
|
1235
1755
|
// 小节标题统一用 `## Links`;旧笔记里已有的 `## 链接` 照用,不追加第二个小节
|
|
1236
1756
|
const heading = /^##\s+(?:Links|链接)\s*$/m.test(source) ? '' : '## Links\n\n';
|
|
1237
1757
|
fs.appendFileSync(fromAbs, `${sep}${heading}- ${link}\n`, 'utf8');
|
|
1758
|
+
markIndexDirty(cfg);
|
|
1238
1759
|
return { from: relPathOf(cfg, fromAbs), to: relPathOf(cfg, targetAbs), link, added: true };
|
|
1239
1760
|
}
|
|
1240
1761
|
export async function notebookStats(cfg, signal) {
|
|
@@ -1251,7 +1772,8 @@ export async function notebookStats(cfg, signal) {
|
|
|
1251
1772
|
// 并发的进程会互相看到对方写到一半的结果,同一次统计里「归档」和「活跃」就对不上。
|
|
1252
1773
|
const brokenLinks = await count(['--broken-links']);
|
|
1253
1774
|
const orphans = await count(['--orphan']);
|
|
1254
|
-
const
|
|
1775
|
+
const scan = await scanNotes(cfg, { includeArchived: true }, signal);
|
|
1776
|
+
const all = scan.notes;
|
|
1255
1777
|
const live = all.filter((n) => !inArchive(cfg, n.path));
|
|
1256
1778
|
// 标签数只从可见笔记汇总:zk tag list 没有 -x,直接用它会把 raw/inbox/archive/meta 的标签也算进来。
|
|
1257
1779
|
return {
|
|
@@ -1263,6 +1785,8 @@ export async function notebookStats(cfg, signal) {
|
|
|
1263
1785
|
// 含已归档的,以及手工标了但没搬进 archive 的(正常流程会搬,这里兜手滑)
|
|
1264
1786
|
superseded: all.filter((n) => n.status === 'superseded').length,
|
|
1265
1787
|
...distributionOf(live),
|
|
1788
|
+
completeness: scan.completeness,
|
|
1789
|
+
scanLimit: scan.limit,
|
|
1266
1790
|
};
|
|
1267
1791
|
}
|
|
1268
1792
|
/**
|
|
@@ -1289,16 +1813,34 @@ function distributionOf(live) {
|
|
|
1289
1813
|
}
|
|
1290
1814
|
/**
|
|
1291
1815
|
* 显式重建(设置页「重建索引」/ `zk-kit index`):走建库预算(30 min),不再 120 s 杀掉。
|
|
1292
|
-
*
|
|
1816
|
+
* 进程内已有后台建库时直接等它;跨进程先抢 `dsh-index.lock`,抢不到就不起第二个 zk 进程
|
|
1817
|
+
* (并发两个只会撞 SQLite 写锁)。`lockWaitMs` 只给显式重建用:写路径(refreshIndexQuietly)
|
|
1818
|
+
* 不应该把自己卡在别人的建库上。
|
|
1819
|
+
* 锁建不出来(权限 / 磁盘)时退回旧行为直接建:显式重建不能因为拿不到锁而失败。
|
|
1293
1820
|
*/
|
|
1294
|
-
export async function indexNotebook(cfg, signal) {
|
|
1821
|
+
export async function indexNotebook(cfg, signal, opts = {}) {
|
|
1295
1822
|
const running = builds.get(cfg.notebook);
|
|
1296
1823
|
if (running) {
|
|
1297
1824
|
await running.promise;
|
|
1298
1825
|
return;
|
|
1299
1826
|
}
|
|
1300
1827
|
const loc = await requireZk(cfg);
|
|
1301
|
-
|
|
1828
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
1829
|
+
const acquired = tryAcquireIndexLock(cfg);
|
|
1830
|
+
if (acquired.kind === 'failed') {
|
|
1831
|
+
await startIndexBuild(cfg, loc, signal).promise;
|
|
1832
|
+
return;
|
|
1833
|
+
}
|
|
1834
|
+
if (acquired.kind === 'acquired') {
|
|
1835
|
+
await startIndexBuild(cfg, loc, signal, acquired.lock).promise;
|
|
1836
|
+
return;
|
|
1837
|
+
}
|
|
1838
|
+
// 别的进程在建:等它放开,不并发起第二个 zk index
|
|
1839
|
+
const released = await waitForIndexLockRelease(cfg, signal, opts.lockWaitMs ?? indexPolicy.lockWaitMs);
|
|
1840
|
+
if (released)
|
|
1841
|
+
return;
|
|
1842
|
+
}
|
|
1843
|
+
throw new ZkError('另一个进程正在建索引,这次不另起一个 zk index', `已等了 ${Math.round((opts.lockWaitMs ?? indexPolicy.lockWaitMs) / 1000)} 秒;过一会儿再试,或等它建完(索引状态可在设置页看)`, 'index-building');
|
|
1302
1844
|
}
|
|
1303
1845
|
/**
|
|
1304
1846
|
* 我们自己动过文件(改名 / 搬归档)之后补一次增量索引。
|
|
@@ -1308,6 +1850,8 @@ export async function indexNotebook(cfg, signal) {
|
|
|
1308
1850
|
* 刷新失败不该把「已经落盘的改名」变成一句报错,所以这里吞掉异常。
|
|
1309
1851
|
*/
|
|
1310
1852
|
async function refreshIndexQuietly(cfg, signal) {
|
|
1853
|
+
// 先标脏再补:补失败(zk 不在 / 撞锁)时标记还在,下一次读者会重试,而不是永久留一份旧索引
|
|
1854
|
+
markIndexDirty(cfg);
|
|
1311
1855
|
try {
|
|
1312
1856
|
await indexNotebook(cfg, signal);
|
|
1313
1857
|
}
|