dsh-zdiary-kit 3.6.0 → 3.8.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.
@@ -25,7 +25,7 @@ import fs from 'node:fs';
25
25
  import path from 'node:path';
26
26
  import { DREAM_INTERVAL_DAYS, daysSinceDream, lastDreamDate } from './dream.js';
27
27
  import { fileStamp } from './file-stamp.js';
28
- import { entryDate, memoryFormatDebt, stripRetiredEntries } from './memory-format.js';
28
+ import { entryDate, isRetiredEntry, memoryFormatDebt, splitMemoryEntries, stripRetiredEntries } from './memory-format.js';
29
29
  import { templateVersionOf } from './agents-template.js';
30
30
  import { PERSONA_META_FILES, MEMORY_META_FILES } from './meta.js';
31
31
  /** vault 根目录下、按优先级排列的三份 meta 文件(定义在 lib/meta.ts,这里只挂个本地名) */
@@ -555,6 +555,7 @@ function computePayload(cfg) {
555
555
  ratio: budget > 0 ? Math.round((finalWords / budget) * 100) / 100 : 0,
556
556
  truncatedWords,
557
557
  retiredWords,
558
+ retiredEntries: omitted.count,
558
559
  tocWords: countWords(toc),
559
560
  formatDebt: debt,
560
561
  templateVersion,
@@ -593,6 +594,88 @@ export function memoryUsage(cfg) {
593
594
  budget: payload.budget,
594
595
  // 人格是独立层:整段(含它的告警)都不该占记忆预算,否则 dream 会误报「余量」
595
596
  headroom: payload.budget - (payload.totalWords - payload.persona.words),
597
+ undated: payload.formatDebt.undated,
598
+ unlinked: payload.formatDebt.unlinked,
599
+ retired: payload.retiredEntries,
596
600
  files: payload.files,
597
601
  };
598
602
  }
603
+ /**
604
+ * 「改 MEMORY 之前」的容量快照:复用 `buildMemoryPayload` / `memoryUsage` 的投影,不新增计数口径;
605
+ * 条目解析复用 `splitMemoryEntries` / `entryDate` / `isRetiredEntry`,与截断、`zk_lint` 同一份。
606
+ * 纯读:不跑 zk、不写文件。同日 tie 只做可见化(G4),不改变 `oldestIndex` 的淘汰行为。
607
+ */
608
+ export function memoryCapacity(cfg, opts = {}) {
609
+ const payload = buildMemoryPayload(cfg);
610
+ const usage = memoryUsage(cfg);
611
+ const extraWords = typeof opts.extraWords === 'number' && Number.isFinite(opts.extraWords)
612
+ ? Math.max(0, Math.trunc(opts.extraWords))
613
+ : countWords(String(opts.proposedEntry ?? ''));
614
+ const wouldTruncate = extraWords > usage.headroom;
615
+ let body = '';
616
+ try {
617
+ body = fs.readFileSync(path.join(cfg.notebook, 'MEMORY.md'), 'utf8');
618
+ }
619
+ catch { /* 缺文件 = 空 */ }
620
+ const debt = memoryFormatDebt(body);
621
+ const retired = stripRetiredEntries(body).count;
622
+ // 退役条目注入时已省略,不会因预算被丢 —— 预告里不列它们
623
+ const entries = splitMemoryEntries(body)
624
+ .map((entry, index) => ({ entry, index, date: entryDate(entry) }))
625
+ .filter((row) => !isRetiredEntry(row.entry));
626
+ const withDate = entries.filter((row) => row.date !== null);
627
+ const oldestDate = withDate.reduce((min, row) => (row.date < min ? row.date : min), '9999-99-99');
628
+ const sameDateCount = withDate.filter((row) => row.date === oldestDate).length;
629
+ // 与 oldestIndex 同口径:有日期按最旧;同日期按位置靠后的先丢;没日期退回尾部(也是位置靠后先丢)
630
+ const order = [...entries].sort((a, b) => {
631
+ if (a.date && b.date) {
632
+ if (a.date !== b.date)
633
+ return a.date < b.date ? -1 : 1;
634
+ return b.index - a.index;
635
+ }
636
+ if (a.date)
637
+ return -1;
638
+ if (b.date)
639
+ return 1;
640
+ return b.index - a.index;
641
+ });
642
+ const dropCandidates = order.slice(0, 5).map(({ entry, date }) => {
643
+ const one = String(entry.split('\n', 1)[0] ?? '').replace(/\s+/g, ' ').trim();
644
+ const title = one.length > TOC_TITLE_MAX ? one.slice(0, TOC_TITLE_MAX) + '…' : one;
645
+ return {
646
+ title: title || '(无标题)',
647
+ date: date ?? '',
648
+ words: countWords(entry),
649
+ reason: !date ? 'undated' : sameDateCount > 1 && date === oldestDate ? 'same-date' : 'oldest',
650
+ };
651
+ });
652
+ const format = [];
653
+ if (debt.undated > 0)
654
+ format.push('undated');
655
+ if (debt.unlinked > 0)
656
+ format.push('unlinked');
657
+ if (retired > 0)
658
+ format.push('retired');
659
+ const parts = [extraWords > 0
660
+ ? (wouldTruncate
661
+ ? `再加 ${extraWords} 词会触发截断(余 ${usage.headroom} 词),先退役 / 精简 dropCandidates 里的条目`
662
+ : `还能放 ${usage.headroom - extraWords} 词`)
663
+ : (usage.headroom < 0 ? `已超预算 ${-usage.headroom} 词` : `余 ${usage.headroom} 词`)];
664
+ // G4:同日不是「按日期挑的」,明说是位置决胜,不假装有使用频率
665
+ if (sameDateCount > 1)
666
+ parts.push(`${sameDateCount} 条同日,按位置决胜`);
667
+ if (format.length)
668
+ parts.push(`格式债:${format.join(' / ')}`);
669
+ return {
670
+ words: payload.words,
671
+ totalWords: payload.totalWords,
672
+ budget: payload.budget,
673
+ headroom: usage.headroom,
674
+ extraWords,
675
+ wouldTruncate,
676
+ dropCandidates,
677
+ format,
678
+ sameDateCount,
679
+ suggestion: parts.join(';'),
680
+ };
681
+ }
@@ -0,0 +1,104 @@
1
+ import { countWords } from './memory.js';
2
+ import { searchNotesDetailed } from './zk.js';
3
+ export const DEFAULT_RECALL_BUDGET = 500;
4
+ export const MAX_RECALL_BUDGET = 5_000;
5
+ export const DEFAULT_RECALL_LIMIT = 30;
6
+ export const MAX_RECALL_LIMIT = 200;
7
+ /** 分组键:type 优先,其次首个标签,都没有归「未分类」。分组只决定装配的轮转顺序,组内保持检索顺序 */
8
+ function groupOf(n) {
9
+ if (n.type)
10
+ return n.type;
11
+ if (n.tags.length)
12
+ return '#' + n.tags[0];
13
+ return '未分类';
14
+ }
15
+ /** 各轮转一次地取:预算不会被排在最前的那一类全吃掉 */
16
+ function roundRobin(notes) {
17
+ const groups = new Map();
18
+ for (const n of notes) {
19
+ const key = groupOf(n);
20
+ if (!groups.has(key))
21
+ groups.set(key, []);
22
+ groups.get(key).push(n);
23
+ }
24
+ const queues = [...groups.values()];
25
+ const out = [];
26
+ for (let round = 0; out.length < notes.length; round += 1) {
27
+ let added = false;
28
+ for (const q of queues) {
29
+ if (q[round]) {
30
+ out.push(q[round]);
31
+ added = true;
32
+ }
33
+ }
34
+ if (!added)
35
+ break;
36
+ }
37
+ return out;
38
+ }
39
+ /** 与 feature.ts 的 detailOf 同口径:snippet 比 lead 多带命中上下文时优先用它 */
40
+ function detailOf(n) {
41
+ return n.snippet && n.snippet !== n.lead ? n.snippet : (n.lead ?? '');
42
+ }
43
+ function entryText(n, index) {
44
+ const badges = [n.type, ...n.tags.map((t) => '#' + t)].filter(Boolean);
45
+ const meta = [n.absPath || n.path, `全文 ${n.words} 词`, ...badges].filter(Boolean).join(' · ');
46
+ const detail = detailOf(n);
47
+ return `## ${index + 1}. ${n.title || n.path}\n${meta}${detail ? '\n\n' + detail : ''}`;
48
+ }
49
+ /**
50
+ * 一次检索 + 内存装配。候选数由 opts.limit 决定(缺省 30),不再为装配多起一个 zk 进程;
51
+ * 每条附 absPath,需要全文时仍由宿主原生 read 取。
52
+ */
53
+ export async function assembleRecall(cfg, opts = {}, signal) {
54
+ const budget = Math.min(MAX_RECALL_BUDGET, Math.max(1, Math.trunc(Number(opts.budget) || DEFAULT_RECALL_BUDGET)));
55
+ const limit = Math.min(MAX_RECALL_LIMIT, Math.max(1, Math.trunc(Number(opts.limit) || DEFAULT_RECALL_LIMIT)));
56
+ const result = await searchNotesDetailed(cfg, {
57
+ ...opts,
58
+ limit,
59
+ sort: opts.sort ?? (opts.query ? 'relevance' : 'created-desc'),
60
+ }, signal);
61
+ const items = [];
62
+ const seen = new Set();
63
+ let text = '';
64
+ let used = 0;
65
+ let index = 0;
66
+ for (const n of roundRobin(result.notes)) {
67
+ const note = {
68
+ title: n.title, path: n.path, absPath: n.absPath, included: false, reason: 'over-budget',
69
+ };
70
+ if (seen.has(n.path)) {
71
+ note.reason = 'duplicate';
72
+ items.push(note);
73
+ continue;
74
+ }
75
+ seen.add(n.path);
76
+ const detail = detailOf(n);
77
+ if (!n.title && !detail) {
78
+ note.reason = 'empty';
79
+ items.push(note);
80
+ continue;
81
+ }
82
+ const entry = entryText(n, index);
83
+ // 整条试算:分隔符也计入预算,且 countWords 的 CJK 边界让逐条累加不准,直接算整段最稳
84
+ const candidate = text ? text + '\n\n' + entry : entry;
85
+ const words = countWords(candidate);
86
+ if (words > budget) {
87
+ note.reason = 'over-budget';
88
+ items.push(note);
89
+ continue;
90
+ }
91
+ text = candidate;
92
+ used = words;
93
+ note.included = true;
94
+ note.reason = 'included';
95
+ index += 1;
96
+ items.push(note);
97
+ }
98
+ return {
99
+ text, used, budget,
100
+ completeness: result.completeness,
101
+ hasMore: result.hasMore,
102
+ notes: items,
103
+ };
104
+ }
@@ -17,15 +17,27 @@ export const WIKI_LINK = /\[\[([^\]|#]+)(?:#[^\]|]*)?(?:\|[^\]]*)?\]\]/g;
17
17
  export function normalizeTitle(title) {
18
18
  return String(title ?? '').replace(/\s+/g, ' ').trim().toLowerCase();
19
19
  }
20
+ /**
21
+ * 「同一篇」的身份键(§9.2):有稳定 id 就只看 id,老笔记 / 日记退回 path。
22
+ * 改名 / 移动 / 重建索引不会改 frontmatter 里的 id,所以这个键不随检索地址漂移。
23
+ */
24
+ export function noteKey(note) {
25
+ const id = String(note.id ?? '').trim();
26
+ return id ? `id:${id}` : `path:${note.path}`;
27
+ }
20
28
  export function wikiIndex(notes) {
21
29
  const byTitle = new Map();
30
+ const byId = new Map();
22
31
  for (const note of notes) {
23
32
  for (const key of [normalizeTitle(note.title), normalizeTitle(path.basename(note.path, path.extname(note.path)))]) {
24
33
  if (key && !byTitle.has(key))
25
34
  byTitle.set(key, note.path);
26
35
  }
36
+ const id = String(note.id ?? '').trim();
37
+ if (id && !byId.has(id))
38
+ byId.set(id, note.path);
27
39
  }
28
- return { byTitle };
40
+ return { byTitle, byId };
29
41
  }
30
42
  function insideNotebook(cfg, abs) {
31
43
  const root = path.resolve(cfg.notebook);
@@ -48,6 +60,11 @@ export function resolveWikiTarget(cfg, target, index) {
48
60
  const rel = String(target ?? '').replace(/\\/g, '/').replace(/^\.\//, '').trim();
49
61
  if (!rel)
50
62
  return { status: 'missing', path: '', explicit: false };
63
+ // 稳定 ID 优先(§9.2):`[[<id>]]` 直接落到那篇笔记的当前路径,改名之后也不断链。
64
+ // 老库没有 id,byId 为空,下面的路径 / 标题解析顺序逐字不变。
65
+ const byId = index.byId.get(rel);
66
+ if (byId)
67
+ return { status: 'live', path: byId, explicit: false };
51
68
  const candidates = /\.md$/i.test(rel) ? [rel] : [rel, `${rel}.md`];
52
69
  for (const candidate of candidates) {
53
70
  const abs = path.resolve(cfg.notebook, candidate);
package/dist/lib/zk.js CHANGED
@@ -9,6 +9,7 @@
9
9
  */
10
10
  import fs from 'node:fs';
11
11
  import path from 'node:path';
12
+ import { randomBytes } from 'node:crypto';
12
13
  import { BIN_DIR } from '../config/paths.js';
13
14
  import { ExecError, findOnPath, run } from './exec.js';
14
15
  import { readJson, writeJson } from './json-file.js';
@@ -701,7 +702,38 @@ export function parseErrorWarnings(cfg, warnings) {
701
702
  }
702
703
  return out.sort((a, b) => a.path.localeCompare(b.path));
703
704
  }
704
- function toRecord(raw, cfg) {
705
+ /** 压空白、去 zk 的 <zk:match> 高亮、截到 240 字 */
706
+ function clipSnippet(value) {
707
+ const first = Array.isArray(value) ? value[0] : value;
708
+ if (typeof first !== 'string')
709
+ return '';
710
+ return first.replace(/<\/?zk:match>/g, '').replace(/\s+/g, ' ').trim().slice(0, 240);
711
+ }
712
+ /**
713
+ * R2:命中片段。
714
+ *
715
+ * zk 0.15.7 的 snippets[0] 实测**就是首段**(长笔记里与 lead 完全相同),
716
+ * 深处命中时它并不定位命中句。所以先看片段里有没有查询词,没有就从
717
+ * rawContent 里取「最早命中 ± 窗口」;两者都没有才退回 snippets[0]。
718
+ * 精简字段格式(LEAN)没有 rawContent,调用方只传 snippets[0]。
719
+ */
720
+ function buildSnippet(raw, terms) {
721
+ const first = clipSnippet(raw.snippets);
722
+ if (terms.length === 0 || terms.some((t) => t && first.includes(t)))
723
+ return first;
724
+ const content = String(raw.rawContent ?? raw.body ?? '');
725
+ let at = -1;
726
+ for (const t of terms) {
727
+ const i = content.indexOf(t);
728
+ if (i >= 0 && (at < 0 || i < at))
729
+ at = i;
730
+ }
731
+ if (at < 0)
732
+ return first;
733
+ return content.slice(Math.max(0, at - 80), Math.max(0, at - 80) + 240)
734
+ .replace(/<\/?zk:match>/g, '').replace(/\s+/g, ' ').trim();
735
+ }
736
+ function toRecord(raw, cfg, terms = []) {
705
737
  const rawTags = Array.isArray(raw.tags) ? raw.tags : [];
706
738
  const absPath = String(raw.absPath ?? '');
707
739
  // ⚠️ zk 在 cwd 之外用 --notebook-dir 时,path 会变成相对 cwd 的 `../../…`;
@@ -725,8 +757,10 @@ function toRecord(raw, cfg) {
725
757
  created: String(raw.created ?? ''),
726
758
  modified: String(raw.modified ?? ''),
727
759
  lead: String(raw.lead ?? '').replace(/\s+/g, ' ').trim().slice(0, 200),
760
+ snippet: buildSnippet(raw, terms),
728
761
  words: Number(raw.wordCount ?? 0),
729
762
  metadata,
763
+ id: meta('id'),
730
764
  status: meta('status'),
731
765
  type: meta('type'),
732
766
  authority: meta('authority'),
@@ -780,6 +814,31 @@ const HASHTAG = new RegExp(HASHTAG_SRC, 'u');
780
814
  export function hasCjk(text) {
781
815
  return CJK_TEXT.test(String(text ?? ''));
782
816
  }
817
+ const REGEX_META = /[.*+?^${}()|[\]\\]/g;
818
+ const escapeRegex = (s) => s.replace(REGEX_META, '\\$&');
819
+ /**
820
+ * R3:把 CJK 多词查询切成词。按空白 / 标点切、去重、保留 ≥2 字、最多 4 个;
821
+ * 少于 2 个词、纯 ASCII 或超过 4 个词都返回 [],交给现有「整串正则」两遍策略。
822
+ */
823
+ export function splitCjkQuery(query) {
824
+ const q = String(query ?? '').trim();
825
+ if (!hasCjk(q))
826
+ return [];
827
+ const words = [...new Set(q.split(/[\s\p{P}\p{S}]+/u).filter((w) => [...w].length >= 2))];
828
+ return words.length >= 2 && words.length <= 4 ? words : [];
829
+ }
830
+ /** 多词正则:转义后做 alternation,仍然一次进程召回(不做逐词 N 次进程) */
831
+ export function cjkAlternation(words) {
832
+ return `(?:${words.map(escapeRegex).join('|')})`;
833
+ }
834
+ /** 命中覆盖了几个查询词(字面子串) */
835
+ function coverageOf(text, words) {
836
+ let n = 0;
837
+ for (const w of words)
838
+ if (text.includes(w))
839
+ n += 1;
840
+ return n;
841
+ }
783
842
  /**
784
843
  * 全量遍历用的字段格式(plan §0.5.1):10k 实测 JSON 17.2 MB,
785
844
  * 这些字段只要约 2 MB,且省掉 body / rawContent / snippets。
@@ -790,7 +849,7 @@ export function hasCjk(text) {
790
849
  const LEAN_FIELD = '\u001f';
791
850
  const LEAN_RECORD = '\u001e';
792
851
  const LEAN_TAG = '\u001c';
793
- const LEAN_TEMPLATE = [
852
+ const LEAN_FIELDS = [
794
853
  '{{absPath}}',
795
854
  '{{title}}',
796
855
  '{{wordCount}}',
@@ -802,34 +861,44 @@ const LEAN_TEMPLATE = [
802
861
  '{{metadata.authority}}',
803
862
  '{{metadata.date}}',
804
863
  '{{metadata.supersede-reason}}',
805
- '{{lead}}',
806
- ].join(LEAN_FIELD);
864
+ '{{metadata.id}}',
865
+ ];
866
+ const LEAN_TEMPLATE = [...LEAN_FIELDS, '{{lead}}'].join(LEAN_FIELD);
867
+ /**
868
+ * 带 query 的结构化检索额外取 snippets[0](R2)。只在有 query 时用:
869
+ * 无 query 的 `zk_query` 会扫全库,加这一列等于给 10k 全量遍历多背一段正文。
870
+ * lead 仍放最后,解析时把剩余段拼回去。
871
+ */
872
+ const SEARCH_LEAN_TEMPLATE = [...LEAN_FIELDS, '{{snippets}}', '{{lead}}'].join(LEAN_FIELD);
807
873
  /** zk 模板给的是 `2026-01-02 03:04:05 +0000 UTC`,转成 Date 能吃的 ISO(zk 存的是 UTC) */
808
874
  function leanIso(value) {
809
875
  const m = /^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})/.exec(String(value).trim());
810
876
  return m ? `${m[1]}T${m[2]}Z` : String(value).trim();
811
877
  }
812
878
  /**
813
- * 解析 LEAN_TEMPLATE 的输出。字段顺序与模板一一对应;不足 11 段说明 zk 行为变了,
814
- * 记 malformed(调用方报 unknown,而不是把空数组当「没有笔记」)。
879
+ * 解析 LEAN_TEMPLATE / SEARCH_LEAN_TEMPLATE 的输出。字段顺序与模板一一对应;
880
+ * 不足定长字段数说明 zk 行为变了,记 malformed(调用方报 unknown,而不是把空数组当「没有笔记」)。
815
881
  */
816
- function parseLeanList(stdout, cfg) {
882
+ function parseLeanList(stdout, cfg, withSnippet = false) {
817
883
  const text = String(stdout ?? '');
818
884
  if (!text.trim())
819
885
  return { notes: [], malformed: false };
820
886
  const notes = [];
821
887
  let malformed = false;
888
+ // 12 个定长字段(含 id)+(可选)snippet + lead;lead 放最后,多余的段拼回去
889
+ const leadAt = withSnippet ? 13 : 12;
822
890
  for (const chunk of text.split(LEAN_RECORD)) {
823
891
  const record = chunk.replace(/^[\r\n]+|[\r\n]+$/g, '');
824
892
  if (!record.trim())
825
893
  continue;
826
894
  const parts = record.split(LEAN_FIELD);
827
- if (parts.length < 11) {
895
+ if (parts.length < leadAt) {
828
896
  malformed = true;
829
897
  continue;
830
898
  }
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);
899
+ const [absPath, title, words, created, modified, tags, status, type, authority, date, reason, id] = parts;
900
+ const snippet = withSnippet ? clipSnippet(parts[12]) : '';
901
+ const lead = parts.slice(leadAt).join(LEAN_FIELD).replace(/\s+/g, ' ').trim().slice(0, 200);
833
902
  const abs = absPath ?? '';
834
903
  if (!abs) {
835
904
  malformed = true;
@@ -847,6 +916,8 @@ function parseLeanList(stdout, cfg) {
847
916
  metadata.date = date;
848
917
  if (reason)
849
918
  metadata['supersede-reason'] = reason;
919
+ if (id)
920
+ metadata.id = id;
850
921
  notes.push({
851
922
  title: String(title ?? ''),
852
923
  path: rel,
@@ -856,8 +927,10 @@ function parseLeanList(stdout, cfg) {
856
927
  created: leanIso(created ?? ''),
857
928
  modified: leanIso(modified ?? ''),
858
929
  lead,
930
+ snippet,
859
931
  words: Number(words ?? 0),
860
932
  metadata,
933
+ id: String(id ?? ''),
861
934
  status: String(status ?? ''),
862
935
  type: String(type ?? ''),
863
936
  authority: String(authority ?? ''),
@@ -882,14 +955,21 @@ export async function searchNotesDetailed(cfg, opts = {}, signal) {
882
955
  // 改用只取必要字段的一次全量扫描(10k ≈ 2 MB / 2.6 s,JSON 是 17.2 MB),
883
956
  // 取到 MAX_SCAN + 1 条,超过 MAX_SCAN 才能确定「触顶」而不是刚好 10 000 条。
884
957
  const scanLimit = MAX_SCAN;
958
+ // R3:CJK 多词切词。整串查询仍走现有两遍策略;多词时正则这一路换成转义后的
959
+ // alternation(一次进程召回),再按 rawContent 的覆盖度排序(R3 第 2 条)。
960
+ const cjkWords = splitCjkQuery(opts.query ?? '');
961
+ const queryTerms = cjkWords.length > 0
962
+ ? cjkWords
963
+ : (String(opts.query ?? '').trim() ? [String(opts.query ?? '').trim()] : []);
964
+ const regexQuery = cjkWords.length > 0 ? cjkAlternation(cjkWords) : opts.query;
885
965
  const build = (strategy, format, fetchLimit) => {
886
966
  const args = ['list', '--quiet', '--no-pager', '--format', format, '--limit', String(fetchLimit)];
887
- if (format === LEAN_TEMPLATE)
967
+ if (format === LEAN_TEMPLATE || format === SEARCH_LEAN_TEMPLATE)
888
968
  args.push('-d', LEAN_RECORD);
889
969
  for (const name of excludedNames(cfg, { includeArchived: opts.includeArchived }))
890
970
  args.push('-x', name);
891
971
  if (opts.query)
892
- args.push('-m', opts.query);
972
+ args.push('-m', strategy === 're' ? String(regexQuery) : opts.query);
893
973
  if (strategy)
894
974
  args.push('-M', strategy);
895
975
  for (const t of opts.tags ?? [])
@@ -902,8 +982,13 @@ export async function searchNotesDetailed(cfg, opts = {}, signal) {
902
982
  args.push('--orphan');
903
983
  if (opts.brokenLinks)
904
984
  args.push('--broken-links');
905
- if (opts.sort && SORT_TERMS[opts.sort])
906
- args.push('--sort', SORT_TERMS[opts.sort]);
985
+ // R1:有 query 且未显式给 sort(或显式 relevance)时不要传 --sort,
986
+ // 否则 zk 的 created- 会覆盖 FTS 的相关性顺序;无 query 的 relevance 回退 created-desc。
987
+ const sortTerm = opts.sort === 'relevance'
988
+ ? (opts.query ? undefined : SORT_TERMS['created-desc'])
989
+ : (opts.sort ? SORT_TERMS[opts.sort] : undefined);
990
+ if (sortTerm)
991
+ args.push('--sort', sortTerm);
907
992
  for (const p of opts.paths ?? [])
908
993
  args.push(p);
909
994
  return args;
@@ -916,26 +1001,58 @@ export async function searchNotesDetailed(cfg, opts = {}, signal) {
916
1001
  (types.length === 0 || types.includes(n.type) || (types.includes('daily') && isUnderDir(n.path, cfg.dailyDir)));
917
1002
  /** 无 JS 过滤:limit + 1 就够判断 hasMore,继续走 JSON(小、字段全) */
918
1003
  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 };
1004
+ const raws = parseList(await zk(cfg, build(strategy, 'json', limit + 1), { signal }));
1005
+ const notes = raws.map((raw) => toRecord(raw, cfg, queryTerms));
1006
+ const coverage = new Map();
1007
+ if (cjkWords.length > 0) {
1008
+ for (let i = 0; i < raws.length; i += 1) {
1009
+ coverage.set(notes[i].path, coverageOf(`${String(raws[i].title ?? '')} ${String(raws[i].rawContent ?? '')}`, cjkWords));
1010
+ }
1011
+ }
1012
+ return { notes, examined: notes.length, coverage };
922
1013
  };
923
1014
  /** 有 JS 过滤:扫到 MAX_SCAN + 1,过滤后再按 limit 截断;字段格式见 LEAN_TEMPLATE */
924
1015
  const filteredStrategy = async (strategy) => {
925
- const parsed = parseLeanList(await zk(cfg, build(strategy, LEAN_TEMPLATE, scanLimit + 1), { signal }), cfg);
1016
+ // 有 query 才多取 snippets[0](R2):无 query 时这一列会给全库扫描多背一段正文。
1017
+ const format = opts.query ? SEARCH_LEAN_TEMPLATE : LEAN_TEMPLATE;
1018
+ const parsed = parseLeanList(await zk(cfg, build(strategy, format, scanLimit + 1), { signal }), cfg, !!opts.query);
1019
+ const notes = parsed.notes.filter(keep);
1020
+ const coverage = new Map();
1021
+ if (cjkWords.length > 0) {
1022
+ // LEAN 没有 rawContent:只能用标题 / lead / snippet 算覆盖度(best effort)。
1023
+ for (const n of notes)
1024
+ coverage.set(n.path, coverageOf(`${n.title} ${n.lead} ${n.snippet}`, cjkWords));
1025
+ }
926
1026
  return {
927
- notes: parsed.notes.filter(keep),
1027
+ notes,
928
1028
  examined: parsed.notes.length,
929
1029
  capped: parsed.notes.length > scanLimit,
930
1030
  malformed: parsed.malformed,
1031
+ coverage,
931
1032
  };
932
1033
  };
1034
+ /** 合并两路的覆盖度,按 coverage 降序 → 原顺序(FTS 在前)→ created-desc 排序 */
1035
+ const rank = (notes, ...maps) => {
1036
+ if (cjkWords.length === 0)
1037
+ return notes;
1038
+ const coverage = new Map();
1039
+ for (const m of maps) {
1040
+ for (const [p, c] of m ?? [])
1041
+ coverage.set(p, Math.max(coverage.get(p) ?? 0, c));
1042
+ }
1043
+ const order = new Map(notes.map((n, i) => [n.path, i]));
1044
+ return [...notes].sort((a, b) => (coverage.get(b.path) ?? 0) - (coverage.get(a.path) ?? 0)
1045
+ || (order.get(a.path) ?? 0) - (order.get(b.path) ?? 0)
1046
+ || String(b.created).localeCompare(String(a.created)));
1047
+ };
933
1048
  const finish = (notes, examined, extra = {}) => {
934
1049
  const more = notes.length > limit || extra.capped === true;
935
1050
  const completeness = more
936
1051
  ? 'partial'
937
1052
  : extra.malformed || extra.strategyFailed ? 'unknown' : 'complete';
938
- return { notes: notes.slice(0, limit), hasMore: more, completeness, scanned: examined, matchStrategy: 'fts' };
1053
+ // R2:只有 complete 时 notes.length 才是精确总数;partial / unknown 不给 total。
1054
+ const total = completeness === 'complete' ? { total: notes.length } : {};
1055
+ return { notes: notes.slice(0, limit), hasMore: more, completeness, scanned: examined, ...total, matchStrategy: 'fts' };
939
1056
  };
940
1057
  /**
941
1058
  * mixed 的判据必须看「截断后的可见结果」:FTS 已占满 limit 时,正则补的那条
@@ -977,15 +1094,16 @@ export async function searchNotesDetailed(cfg, opts = {}, signal) {
977
1094
  seen.add(n.path);
978
1095
  merged.push(n);
979
1096
  }
1097
+ const ranked = rank(merged, hits.coverage, regex?.coverage);
980
1098
  return {
981
- ...finish(merged, hits.examined + (regex?.examined ?? 0), { strategyFailed }),
982
- matchStrategy: strategyOf(hits.notes, merged),
1099
+ ...finish(ranked, hits.examined + (regex?.examined ?? 0), { strategyFailed }),
1100
+ matchStrategy: strategyOf(hits.notes, ranked),
983
1101
  };
984
1102
  }
985
1103
  catch (err) {
986
1104
  if (opts.query && err instanceof ZkError) {
987
1105
  const retry = await plainStrategy('re');
988
- return { ...finish(retry.notes, retry.examined), matchStrategy: 'regex' };
1106
+ return { ...finish(rank(retry.notes, retry.coverage), retry.examined), matchStrategy: 'regex' };
989
1107
  }
990
1108
  throw err;
991
1109
  }
@@ -1018,19 +1136,20 @@ export async function searchNotesDetailed(cfg, opts = {}, signal) {
1018
1136
  seen.add(n.path);
1019
1137
  merged.push(n);
1020
1138
  }
1139
+ const ranked = rank(merged, hits.coverage, regex?.coverage);
1021
1140
  return {
1022
- ...finish(merged, hits.examined + (regex?.examined ?? 0), {
1141
+ ...finish(ranked, hits.examined + (regex?.examined ?? 0), {
1023
1142
  capped: hits.capped || regex?.capped === true,
1024
1143
  malformed: hits.malformed || regex?.malformed === true,
1025
1144
  strategyFailed,
1026
1145
  }),
1027
- matchStrategy: strategyOf(hits.notes, merged),
1146
+ matchStrategy: strategyOf(hits.notes, ranked),
1028
1147
  };
1029
1148
  }
1030
1149
  catch (err) {
1031
1150
  if (opts.query && err instanceof ZkError) {
1032
1151
  const retry = await filteredStrategy('re');
1033
- return { ...finish(retry.notes, retry.examined, retry), matchStrategy: 'regex' };
1152
+ return { ...finish(rank(retry.notes, retry.coverage), retry.examined, retry), matchStrategy: 'regex' };
1034
1153
  }
1035
1154
  throw err;
1036
1155
  }
@@ -1314,8 +1433,10 @@ function noteFromDisk(cfg, abs) {
1314
1433
  created: stat.birthtime.toISOString(),
1315
1434
  modified: stat.mtime.toISOString(),
1316
1435
  lead: '',
1436
+ snippet: '',
1317
1437
  words: content.split(/\s+/).filter(Boolean).length,
1318
1438
  metadata: { ...fields },
1439
+ id: fields.id ?? '',
1319
1440
  status: fields.status ?? '',
1320
1441
  type: fields.type ?? '',
1321
1442
  authority: fields.authority ?? '',
@@ -1381,6 +1502,13 @@ function normalizeNoteName(raw) {
1381
1502
  }
1382
1503
  return name;
1383
1504
  }
1505
+ /**
1506
+ * 稳定 ID(§9.2):10 位十六进制短随机串(40 bit,10⁴ 篇库的碰撞概率可忽略)。
1507
+ * 纯小写 hex,不会与路径 / `.md` 后缀 / 中文标题撞形,`[[id]]` 才认得出来。
1508
+ */
1509
+ export function newNoteId() {
1510
+ return randomBytes(5).toString('hex');
1511
+ }
1384
1512
  /**
1385
1513
  * 用 zk new 建一篇(正文走 stdin → 模板里的 {{content}})。
1386
1514
  *
@@ -1521,6 +1649,17 @@ export async function createNote(cfg, input, signal, scan = (c, s) => allNotes(c
1521
1649
  summaryWarning = `summary 没写进去:${err instanceof Error ? err.message : String(err)}(文件已建好,可以直接编辑那一节)`;
1522
1650
  }
1523
1651
  }
1652
+ // 稳定 ID(§9.2):只给 zk_new 新建的笔记写 id,老笔记 / 日记不回填。
1653
+ // 建完才写:zk new -i 索引的是模板产物,改了文件就得标脏,让下一次读补索引(R6)。
1654
+ // 收尾失败一律吞掉(同 markIndexDirty):笔记已经建好,不能让一次 id 写入看起来像整次创建失败。
1655
+ try {
1656
+ const text = fs.readFileSync(finalAbs, 'utf8');
1657
+ if (!parseFrontmatter(text).fields.id) {
1658
+ fs.writeFileSync(finalAbs, setFrontmatter(text, { id: newNoteId() }), 'utf8');
1659
+ markIndexDirty(cfg);
1660
+ }
1661
+ }
1662
+ catch { /* 收尾失败:文件已落盘,不回滚、不误导 */ }
1524
1663
  return { path: relPathOf(cfg, finalAbs), absPath: finalAbs, title, archived, similar, summaryApplied, summaryWarning };
1525
1664
  }
1526
1665
  /** 笔记本相对路径是否在归档目录下(supersede 会把文件搬进去,路径保持不变) */