dsh-zdiary-kit 3.4.0 → 3.7.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.
@@ -17,8 +17,8 @@
17
17
  * 首行 `<!-- zdiary-template: vN -->` 是版本标记:lint 据此报告「老库的 AGENTS.md 是旧版」,
18
18
  * 只报告不覆盖(模板允许用户改)。
19
19
  */
20
- /** 模板版本:改模板就 +1;lint 用它判断老库是否还在用旧模板(v8:读取交给原生 read) */
21
- export const TEMPLATE_VERSION = 8;
20
+ /** 模板版本:改模板就 +1;lint 用它判断老库是否还在用旧模板(v9:改 MEMORY 前看 zk_context 余量) */
21
+ export const TEMPLATE_VERSION = 9;
22
22
  /** 首行版本标记(实测 4 词);不许带日期 —— 带日期的写法实测 6 词,白花 2 词 */
23
23
  export const TEMPLATE_MARK = `<!-- zdiary-template: v${TEMPLATE_VERSION} -->`;
24
24
  /** 版本标记的正则(本文件内用;外部只通过 `templateVersionOf` 取数,免得又一个口径) */
@@ -37,6 +37,7 @@ export function templateVersionOf(body) {
37
37
  */
38
38
  export const TEMPLATE_SENTINELS = {
39
39
  8: { required: ['先 read 核对来源'], forbidden: ['DSH 不会自动加载', '从底部往前丢'] },
40
+ 9: { required: ['先 read 核对来源', '改 MEMORY 前看 zk_context'], forbidden: ['DSH 不会自动加载', '从底部往前丢'] },
40
41
  };
41
42
  export const AGENTS_TEMPLATE = `${TEMPLATE_MARK}
42
43
 
@@ -64,6 +65,7 @@ notes/{concepts,entities,patterns}/ 原子笔记 · archive/ 废弃(不删)
64
65
  每周:DREAMS.md 写「上次做梦:YYYY-MM-DD」;到期 zk_lint → zk_dream → 人裁决改 MEMORY。
65
66
  MEMORY.md 每条:结论(YYYY-MM-DD)[[来源路径]],先 read 核对来源;退役写 - [superseded YYYY-MM-DD] 旧结论 → [[新结论]],行不删。
66
67
  新条目写顶部;超预算按日期丢最旧的一条。
68
+ 改 MEMORY 前看 zk_context 余量(WORKFLOW.md 有做法)。
67
69
  `;
68
70
  /**
69
71
  * flat 结构用的模板:不出现 raw / inbox / archive / WORKFLOW.md 这些 flat 没有的路径。
@@ -83,6 +85,7 @@ export const AGENTS_TEMPLATE_FLAT = `${TEMPLATE_MARK}
83
85
 
84
86
  DREAMS.md 写「上次做梦:YYYY-MM-DD」;到期 zk_lint → zk_dream → 人裁决改 MEMORY。
85
87
  MEMORY.md 每条:结论(YYYY-MM-DD)[[来源路径]],先 read 核对来源;退役写 - [superseded] 旧结论 → [[新结论]]。
88
+ 改 MEMORY 前看 zk_context 余量。
86
89
  `;
87
90
  /**
88
91
  * 根目录 WORKFLOW.md:只在「要动已有笔记」时才需要读,所以不注入、不计预算。
@@ -103,6 +106,11 @@ export const WORKFLOW_TEMPLATE = `${TEMPLATE_MARK}
103
106
 
104
107
  判断不了就按 3 处理:flag 的成本远低于悄悄改写。
105
108
 
109
+ ## 改 MEMORY.md 之前
110
+
111
+ 先看 zk_context 的 headroom 与 dropCandidates:余量不够就先退役 / 精简旧条目,别让新结论把最旧的挤掉。
112
+ 给 proposed_entry 能预估会不会触发截断;同日条目按位置决胜(sameDateCount),插件不猜谁更常用。
113
+
106
114
  ## 动笔前必须出清单
107
115
 
108
116
  1. 用 zk_search / zk_query 找出可能受影响的笔记;
package/dist/lib/dream.js CHANGED
@@ -13,7 +13,7 @@
13
13
  */
14
14
  import fs from 'node:fs';
15
15
  import path from 'node:path';
16
- import { allNotes, GRAPH_BUDGET_NOTES, graphEdges, localDate, MAX_SCAN } from './zk.js';
16
+ import { GRAPH_BUDGET_NOTES, graphEdges, localDate, scanNotes } from './zk.js';
17
17
  import { parseFrontmatter } from './frontmatter.js';
18
18
  // memory.ts 也 import 本模块(DREAM_INTERVAL_DAYS / daysSinceDream):这里是运行期才取用,
19
19
  // 循环引用在 ESM 下安全 —— 不要在模块顶层调用 memoryUsage。
@@ -286,7 +286,8 @@ export async function dreamNotebook(cfg, opts = {}, signal) {
286
286
  const windowDays = windowDaysOf(cfg, now, opts.days);
287
287
  const sinceMs = now.getTime() - windowDays * 86_400_000;
288
288
  // 顺序跑:两个 zk 进程同时补索引会撞 SQLite 写锁(lint 里同样处理)
289
- const notes = await allNotes(cfg, {}, signal);
289
+ const scan = await scanNotes(cfg, {}, signal);
290
+ const notes = scan.notes;
290
291
  // 全图在 10k 上 26–31 s / 17 MB(plan §0.5.1):超过预算就不建,并显式告诉调用方。
291
292
  // 预算来自配置(设置页可调);opts.graphBudget 只给测试覆盖。
292
293
  const graphBudget = Math.max(0, Math.trunc(opts.graphBudget ?? cfg.graphBudgetNotes ?? GRAPH_BUDGET_NOTES));
@@ -419,7 +420,9 @@ export async function dreamNotebook(cfg, opts = {}, signal) {
419
420
  notebook: cfg.notebook,
420
421
  windowDays,
421
422
  since: localDate(new Date(sinceMs).toISOString()),
422
- truncated: notes.length >= MAX_SCAN,
423
+ truncated: scan.completeness !== 'complete',
424
+ completeness: scan.completeness,
425
+ scanLimit: scan.limit,
423
426
  graphSkipped: !graphReady,
424
427
  graphBudget,
425
428
  counts: {
package/dist/lib/lint.js CHANGED
@@ -24,7 +24,7 @@
24
24
  */
25
25
  import fs from 'node:fs';
26
26
  import path from 'node:path';
27
- import { allNotes, backlinksOf, GRAPH_BUDGET_NOTES, graphEdges, localDate, MAX_SCAN, notesWithFlag, outlinksOf, parseErrorWarnings, } from './zk.js';
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
29
  import { parseFrontmatter } from './frontmatter.js';
30
30
  import { daysSinceDate, entryDate, isRetiredEntry, memoryFormatDebt, splitMemoryEntries } from './memory-format.js';
@@ -91,11 +91,13 @@ export function similarTitles(notes, scanTruncated, max = MAX_ITEMS) {
91
91
  groups.set(dir, list);
92
92
  }
93
93
  let truncated = scanTruncated;
94
+ let droppedGroups = 0;
94
95
  const found = [];
95
96
  for (const group of groups.values()) {
96
97
  let list = group;
97
98
  if (list.length > SIMILAR_GROUP_MAX) {
98
99
  truncated = true;
100
+ droppedGroups += 1;
99
101
  list = list.slice(0, SIMILAR_GROUP_MAX);
100
102
  }
101
103
  for (let i = 0; i < list.length; i++) {
@@ -118,7 +120,8 @@ export function similarTitles(notes, scanTruncated, max = MAX_ITEMS) {
118
120
  }
119
121
  }
120
122
  found.sort((a, b) => b.score - a.score || a.paths[0].localeCompare(b.paths[0]));
121
- return { total: found.length, truncated, items: found.slice(0, max) };
123
+ const completeness = truncated ? 'partial' : 'complete';
124
+ return { total: found.length, truncated, completeness, droppedGroups, items: found.slice(0, max) };
122
125
  }
123
126
  /** 注入的三份 meta 里只有 MEMORY / USER 会写来源链接;AGENTS 是规则,不查 */
124
127
  const MEMORY_LINK_FILES = ['MEMORY.md', 'USER.md'];
@@ -673,10 +676,17 @@ export async function lintNotebook(cfg, opts = {}, signal) {
673
676
  const warnings = [];
674
677
  const dailyAbs = path.resolve(cfg.notebook, cfg.dailyDir);
675
678
  const isDaily = (abs) => path.resolve(abs) === dailyAbs || path.resolve(abs).startsWith(dailyAbs + path.sep);
676
- const notes = await allNotes(cfg, { warnings }, signal);
677
- const orphanAbs = await notesWithFlag(cfg, '--orphan', signal);
678
- const brokenAbs = await notesWithFlag(cfg, '--broken-links', signal);
679
- const taglessAbs = await notesWithFlag(cfg, '--tagless', signal);
679
+ const scan = await scanNotes(cfg, { warnings }, signal);
680
+ const notes = scan.notes;
681
+ const orphanScan = await scanNotesWithFlag(cfg, '--orphan', signal);
682
+ const brokenScan = await scanNotesWithFlag(cfg, '--broken-links', signal);
683
+ const taglessScan = await scanNotesWithFlag(cfg, '--tagless', signal);
684
+ const orphanAbs = orphanScan.paths;
685
+ const brokenAbs = brokenScan.paths;
686
+ const taglessAbs = taglessScan.paths;
687
+ // 任一过滤器触顶都意味着对应桶少了;三态取最坏值(partial > unknown > complete)
688
+ const worst = (values) => values.includes('partial') ? 'partial' : values.includes('unknown') ? 'unknown' : 'complete';
689
+ const completeness = worst([scan.completeness, orphanScan.completeness, brokenScan.completeness, taglessScan.completeness]);
680
690
  // 别用 `path.resolve(n.absPath || n.path)`:absPath 缺失时相对路径会按进程 cwd 解析,键就错了。
681
691
  const byAbs = new Map(notes.map((n) => [n.absPath ? path.resolve(n.absPath) : path.resolve(cfg.notebook, n.path), n]));
682
692
  const byPath = new Map(notes.map((n) => [n.path, n]));
@@ -775,13 +785,15 @@ export async function lintNotebook(cfg, opts = {}, signal) {
775
785
  const oneWayByQueries = async () => {
776
786
  let left = MAX_ONE_WAY_QUERIES;
777
787
  const spend = () => (left > 0 ? ((left -= 1), true) : false);
778
- const missingAbs = await notesWithFlag(cfg, '--missing-backlink', signal);
779
- const targets = missingAbs
788
+ const missing = await scanNotesWithFlag(cfg, '--missing-backlink', signal);
789
+ let truncated = missing.completeness !== 'complete';
790
+ const targets = missing.paths
780
791
  .map((abs) => path.relative(cfg.notebook, abs).split(path.sep).join('/'))
781
792
  .filter((rel) => byPath.has(rel) && !isDaily(path.resolve(cfg.notebook, rel)))
782
793
  .sort((a, b) => a.localeCompare(b));
783
794
  const capped = targets.slice(0, MAX_ONE_WAY_TARGETS);
784
- let truncated = targets.length > capped.length;
795
+ if (targets.length > capped.length)
796
+ truncated = true;
785
797
  const rows = [];
786
798
  for (const target of capped) {
787
799
  if (!spend()) {
@@ -819,9 +831,11 @@ export async function lintNotebook(cfg, opts = {}, signal) {
819
831
  const graphBudget = Math.max(0, Math.trunc(opts.graphBudget ?? cfg.graphBudgetNotes ?? GRAPH_BUDGET_NOTES));
820
832
  const oneWayRows = [];
821
833
  let oneWayTruncated = false;
834
+ let oneWayCompleteness = 'complete';
822
835
  if (notes.length <= graphBudget) {
823
836
  const graph = await graphEdges(cfg, signal);
824
837
  oneWayTruncated = graph.truncated;
838
+ oneWayCompleteness = graph.completeness;
825
839
  // 图里的路径是笔记本相对:先拼回绝对路径再判断是不是日记(isDaily 收的是绝对路径)
826
840
  for (const row of oneWayLinks(graph.edges, notes, (p) => isDaily(path.resolve(cfg.notebook, p)))) {
827
841
  oneWayRows.push({
@@ -834,6 +848,7 @@ export async function lintNotebook(cfg, opts = {}, signal) {
834
848
  const scanned = await oneWayByQueries();
835
849
  oneWayRows.push(...scanned.rows);
836
850
  oneWayTruncated = scanned.truncated;
851
+ oneWayCompleteness = scanned.truncated ? 'partial' : 'complete';
837
852
  }
838
853
  const linksOnly = opts.linksOnly === true;
839
854
  const oneWayItems = [];
@@ -887,10 +902,11 @@ export async function lintNotebook(cfg, opts = {}, signal) {
887
902
  bodyOnly,
888
903
  linksOnly,
889
904
  edgesTruncated: oneWayTruncated,
905
+ completeness: oneWayCompleteness,
890
906
  items: oneWayItems.slice(0, MAX_ITEMS),
891
907
  };
892
908
  const parseErrors = parseErrorWarnings(cfg, warnings);
893
- const scanTruncated = notes.length >= MAX_SCAN;
909
+ const scanTruncated = completeness !== 'complete';
894
910
  const staleNotes = notes
895
911
  .map((n) => ({ note: n, at: Date.parse(n.modified) }))
896
912
  .filter((x) => Number.isFinite(x.at) && x.at < cutoff)
@@ -910,6 +926,8 @@ export async function lintNotebook(cfg, opts = {}, signal) {
910
926
  notebook: cfg.notebook,
911
927
  notes: notes.length,
912
928
  truncated: scanTruncated,
929
+ completeness,
930
+ scanLimit: scan.limit,
913
931
  staleDays,
914
932
  parseErrors: { total: parseErrors.length, items: parseErrors.slice(0, MAX_ITEMS) },
915
933
  orphans: bucket(orphanAbs.filter((abs) => !isDaily(abs))),
@@ -930,5 +948,7 @@ export async function lintNotebook(cfg, opts = {}, signal) {
930
948
  timeline: timelineStatus(cfg, now),
931
949
  // 150 篇(不含日记)是检索开始变糊的拐点:提示一下,不生成静态索引(会过期,还要决定谁更新)
932
950
  indexHint: nonDaily.length >= 150 && !fs.existsSync(path.join(cfg.notebook, 'INDEX.md')),
951
+ // 放在最后算:前面的读命令已经把 pending 的 dirty 补掉了,剩下的是「补不上 / 外部编辑」
952
+ indexLag: indexLagHint(cfg) ?? '',
933
953
  };
934
954
  }
@@ -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
+ }