dsh-zdiary-kit 3.14.2 → 3.16.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.
@@ -15,7 +15,7 @@ import { configFor, pinSession, sessionNotebook, sessionState } from '../../conf
15
15
  import { defaultNotebook, expandHome, processWorkspace, resolveInWorkspace } from '../../config/paths.js';
16
16
  import { S, validateArgs } from '../../lib/tool.js';
17
17
  import { ensureNotebook, newNoteDir } from '../../lib/notebook.js';
18
- import { searchNotes, searchNotesDetailed, createNote, appendToNote, ensureDailyNote, appendDaily, linkNotes, withTags, taglessCjkWarning, notebookStats, supersedeNote, renameNote, hasNotebook, isUnderDir, localDate as dateOnly, runAlias, hasCjk, walkFrom, scanNotes, ZkError, } from '../../lib/zk.js';
18
+ import { searchNotes, searchNotesDetailed, createNote, appendToNote, ensureDailyNote, appendDaily, linkNotes, taglessCjkWarning, notebookStats, supersedeNote, renameNote, hasNotebook, isUnderDir, localDate as dateOnly, runAlias, hasCjk, walkFrom, scanNotes, ZkError, } from '../../lib/zk.js';
19
19
  import { configuredAliases, readAliases } from '../../lib/alias.js';
20
20
  import { buildMemoryPayload, memoryCapacity, META_FILES } from '../../lib/memory.js';
21
21
  import { assembleRecall } from '../../lib/recall.js';
@@ -26,7 +26,7 @@ import { bumpRecall } from '../../lib/recall-signal.js';
26
26
  import { wikiIndex } from '../../lib/wikilink.js';
27
27
  import { writeMemory } from '../../lib/memory-write.js';
28
28
  import { META_NAMES } from '../../lib/meta.js';
29
- import { formatLintExtras, formatMemoryLinks, lintNotebook } from '../../lib/lint.js';
29
+ import { formatLintExtras, formatMemoryLinks, formatOneWay, lintNotebook } from '../../lib/lint.js';
30
30
  import { dreamNotebook, STALE_DAYS } from '../../lib/dream.js';
31
31
  const text = (value) => [{ type: 'text', text: value }];
32
32
  /** render 的 args 是 unknown:只取 query 判断要不要给中文 0 命中提示(R7) */
@@ -77,10 +77,21 @@ const LINT_ONE_WAY = objSchema({
77
77
  edges: { type: 'number' },
78
78
  bodyOnly: { type: 'number' },
79
79
  linksOnly: { type: 'boolean' },
80
+ provenance: objSchema({ targets: { type: 'number' }, edges: { type: 'number' } }, ['targets', 'edges']),
81
+ includeProvenance: { type: 'boolean' },
82
+ byType: {
83
+ type: 'array',
84
+ items: objSchema({
85
+ from: { type: 'string' },
86
+ to: { type: 'string' },
87
+ edges: { type: 'number' },
88
+ }, ['from', 'to', 'edges']),
89
+ },
80
90
  edgesTruncated: { type: 'boolean' },
91
+ itemsTruncated: { type: 'boolean' },
81
92
  completeness: { type: 'string', enum: ['complete', 'partial', 'unknown'] },
82
93
  items: { type: 'array', items: LINT_ONE_WAY_ITEM },
83
- }, ['total', 'edges', 'bodyOnly', 'linksOnly', 'edgesTruncated', 'completeness', 'items']);
94
+ }, ['total', 'edges', 'bodyOnly', 'linksOnly', 'provenance', 'includeProvenance', 'byType', 'edgesTruncated', 'itemsTruncated', 'completeness', 'items']);
84
95
  const LINT_STALE = objSchema({
85
96
  total: { type: 'number' },
86
97
  items: {
@@ -95,7 +106,7 @@ const LINT_DUPLICATE = objSchema({
95
106
  items: objSchema({ title: { type: 'string' }, paths: { type: 'array', items: { type: 'string' } } }, ['title', 'paths']),
96
107
  },
97
108
  }, ['total', 'items']);
98
- /** 疑似重复标题(P2-10):只差一两个字 */
109
+ /** 疑似重复标题:只差一两个字 */
99
110
  const LINT_SIMILAR = objSchema({
100
111
  total: { type: 'number' },
101
112
  truncated: { type: 'boolean' },
@@ -196,7 +207,33 @@ const LINT_EMPTY_SECTIONS = objSchema({
196
207
  }, ['path', 'title', 'empty']),
197
208
  },
198
209
  }, ['scanned', 'skipped', 'notes', 'total', 'truncated', 'items']);
199
- /** frontmatter 缺字段(P2-13) */
210
+ /** 正文重复标签:整段只有 #tag、frontmatter 已覆盖(只报告;zk-kit tidy --fix 收掉) */
211
+ const LINT_BODY_TAGS = objSchema({
212
+ scanned: { type: 'number' },
213
+ skipped: { type: 'number' },
214
+ notes: { type: 'number' },
215
+ paragraphs: { type: 'number' },
216
+ driftNotes: { type: 'number' },
217
+ truncated: { type: 'boolean' },
218
+ items: {
219
+ type: 'array',
220
+ items: objSchema({
221
+ path: { type: 'string' },
222
+ title: { type: 'string' },
223
+ paragraphs: { type: 'number' },
224
+ tags: { type: 'array', items: { type: 'string' } },
225
+ }, ['path', 'title', 'paragraphs', 'tags']),
226
+ },
227
+ drift: {
228
+ type: 'array',
229
+ items: objSchema({
230
+ path: { type: 'string' },
231
+ title: { type: 'string' },
232
+ tags: { type: 'array', items: { type: 'string' } },
233
+ }, ['path', 'title', 'tags']),
234
+ },
235
+ }, ['scanned', 'skipped', 'notes', 'paragraphs', 'driftNotes', 'truncated', 'items', 'drift']);
236
+ /** frontmatter 缺字段 */
200
237
  const LINT_INCOMPLETE = objSchema({
201
238
  total: { type: 'number' },
202
239
  truncated: { type: 'boolean' },
@@ -213,7 +250,7 @@ const LINT_INCOMPLETE = objSchema({
213
250
  }, ['path', 'missing']),
214
251
  },
215
252
  }, ['total', 'truncated', 'byField', 'items']);
216
- /** 标签卫生(P2-14) */
253
+ /** 标签卫生 */
217
254
  const LINT_TAGS = objSchema({
218
255
  total: { type: 'number' },
219
256
  reported: { type: 'boolean' },
@@ -229,10 +266,32 @@ const LINT_TAGS = objSchema({
229
266
  }, ['total', 'items']),
230
267
  singletons: objSchema({
231
268
  total: { type: 'number' },
232
- items: { type: 'array', items: { type: 'string' } },
269
+ items: {
270
+ type: 'array',
271
+ items: objSchema({
272
+ tag: { type: 'string' },
273
+ suggest: {
274
+ type: 'array',
275
+ items: objSchema({
276
+ tag: { type: 'string' },
277
+ count: { type: 'number' },
278
+ kind: { type: 'string', enum: ['case', 'similar'] },
279
+ }, ['tag', 'count', 'kind']),
280
+ },
281
+ }, ['tag', 'suggest']),
282
+ },
233
283
  }, ['total', 'items']),
234
284
  }, ['total', 'reported', 'caseVariants', 'singletons']);
235
- /** 模板版本(P2-15) */
285
+ /** INDEX.md 规模行漂移(只核对,不生成) */
286
+ const LINT_INDEX = objSchema({
287
+ present: { type: 'boolean' },
288
+ claimedNotes: { type: 'number' },
289
+ claimedDate: { type: 'string' },
290
+ actualNotes: { type: 'number' },
291
+ ageDays: { type: 'number' },
292
+ drifted: { type: 'boolean' },
293
+ }, ['present', 'actualNotes', 'drifted']);
294
+ /** 模板版本 */
236
295
  const LINT_TEMPLATE = objSchema({
237
296
  present: { type: 'boolean' },
238
297
  version: { type: 'number' },
@@ -241,7 +300,16 @@ const LINT_TEMPLATE = objSchema({
241
300
  mismatch: { type: 'boolean' },
242
301
  mismatchDetail: { type: 'string' },
243
302
  currentText: { type: 'string' },
244
- }, ['present', 'version', 'current', 'stale']);
303
+ workflow: objSchema({
304
+ present: { type: 'boolean' },
305
+ version: { type: 'number' },
306
+ current: { type: 'number' },
307
+ stale: { type: 'boolean' },
308
+ legacyMark: { type: 'boolean' },
309
+ detail: { type: 'string' },
310
+ currentText: { type: 'string' },
311
+ }, ['present', 'version', 'current', 'stale']),
312
+ }, ['present', 'version', 'current', 'stale', 'workflow']);
245
313
  /** 人格体检:缺失 / 旧版 / 比插件新 / 标记与内容不符 / 未填占位符(只报告,不覆盖) */
246
314
  const LINT_PERSONA = objSchema({
247
315
  total: { type: 'number' },
@@ -828,7 +896,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
828
896
  absPath: { type: 'string' },
829
897
  relation: { type: 'string', enum: ['in', 'out'] },
830
898
  lead: { type: 'string' },
831
- /** 这条边所在的 `##` / `###` 小节;找不到时键不出现(plan §14.1) */
899
+ /** 这条边所在的 `##` / `###` 小节;找不到时键不出现 */
832
900
  section: { type: 'string' },
833
901
  /** 这条边的那一行(压空白、截 160 码点):没有它,同一篇种子的出链长得一模一样 */
834
902
  linkLine: { type: 'string' },
@@ -900,7 +968,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
900
968
  name: S.str('文件名(不含扩展名,也不要带目录);不给就由 zk 按标题生成。中文标题建议给一个短名,否则是长拼音'),
901
969
  body: S.str('正文 Markdown(可空)。会插在模板的 {{content}} 位置(layered 下在 ## Content 之下、## Links 之前):不要自己再写 ## Content / ## Summary 这类模板小节,会多出重复标题'),
902
970
  summary: S.str('一句话摘要(填进模板的 ## Summary;正文里已经写了这一节就不动)'),
903
- tags: S.arr('标签(不写 #)。与设置里的默认标签合并;正文里已经写过的标签不会再追加一行', S.str('标签名')),
971
+ tags: S.arr('标签(不写 #)。与设置里的默认标签合并;模板有 frontmatter tags 格就写那一格(layered),没有才追加正文 hashtag 行;与库里已有标签近义时在 tagHints 里提示', S.str('标签名')),
904
972
  dir: S.str('放到哪个子目录(相对笔记本)。flat 默认 notesDir;layered 必须落在某个 group(notes/sources 等,子目录也行),不给就按 type 落位;两者都没有、或不在 group 里都会报错'),
905
973
  type: S.enum('笔记类型(写进 frontmatter;layered 结构下决定模板的分节,不给 dir 时也决定目录)', ['source', 'concept', 'entity', 'pattern']),
906
974
  authority: S.enum('可信度(写进 frontmatter,给未来的自己判断该不该引用)', ['official', 'expert', 'informal']),
@@ -922,6 +990,15 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
922
990
  summaryWarning: { type: 'string' },
923
991
  emptyTemplateSections: { type: 'array', items: { type: 'string' } },
924
992
  tagWarning: { type: 'string' },
993
+ tagHints: {
994
+ type: 'array',
995
+ items: objSchema({
996
+ input: { type: 'string' },
997
+ tag: { type: 'string' },
998
+ count: { type: 'number' },
999
+ kind: { type: 'string', enum: ['case', 'similar'] },
1000
+ }, ['input', 'tag', 'count', 'kind']),
1001
+ },
925
1002
  archived: {
926
1003
  type: 'array',
927
1004
  items: objSchema({
@@ -944,20 +1021,24 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
944
1021
  async run(args, env) {
945
1022
  const cfg = configFor(env.workspace, env.sessionId);
946
1023
  await ensureNotebook(cfg, env.signal);
947
- const tags = [...new Set([...(cfg.defaultTags ?? []), ...(Array.isArray(args.tags) ? args.tags.map(String) : [])])];
1024
+ // 标签只留名字:前导 # 去掉、去空、去重(写进 frontmatter 的那份必须是同一个形状)
1025
+ const tags = [...new Set([...(cfg.defaultTags ?? []), ...(Array.isArray(args.tags) ? args.tags.map(String) : [])]
1026
+ .map((t) => t.trim().replace(/^#+/, ''))
1027
+ .filter(Boolean))];
948
1028
  const type = args.type ? String(args.type) : undefined;
949
1029
  const title = String(args.title);
950
1030
  const body = args.body ? String(args.body) : '';
951
- const content = withTags(body, tags);
1031
+ // 标签交给 createNote 落位:模板有 frontmatter `tags` 格就写那一格,没有才追加正文 hashtag 行
952
1032
  const created = await createNote(cfg, {
953
1033
  title,
954
1034
  name: args.name ? String(args.name) : undefined,
955
1035
  summary: args.summary ? String(args.summary) : undefined,
956
- content,
1036
+ content: body,
957
1037
  dir: newNoteDir(cfg, { dir: args.dir ? String(args.dir) : undefined, type }),
958
1038
  group: args.group ? String(args.group) : undefined,
959
1039
  type,
960
1040
  authority: args.authority ? String(args.authority) : undefined,
1041
+ tags,
961
1042
  }, env.signal);
962
1043
  const links = [];
963
1044
  const warnings = [];
@@ -971,8 +1052,8 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
971
1052
  warnings.push(`${target}:${err instanceof Error ? err.message : String(err)}`);
972
1053
  }
973
1054
  }
974
- // 中文没标签:写路径是唯一便宜的修复点(P2-9)。只提示,不阻断。
975
- const tagWarning = taglessCjkWarning(title, content, tags);
1055
+ // 中文没标签:写路径是唯一便宜的修复点。只提示,不阻断。
1056
+ const tagWarning = taglessCjkWarning(title, body, tags);
976
1057
  // 归档同名只是提醒:zk_new 的查重本来就不含 archive,允许复用标题 —— 但要把废弃原因一起交出来
977
1058
  // (createNote 建之前那次全库扫描已经算好了,这里不再单独跑一次 zk)
978
1059
  const archived = created.archived;
@@ -984,6 +1065,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
984
1065
  ...(created.similar.length ? { similar: created.similar } : {}),
985
1066
  ...(created.summaryWarning ? { summaryWarning: created.summaryWarning } : {}),
986
1067
  ...(created.emptyTemplateSections.length ? { emptyTemplateSections: created.emptyTemplateSections } : {}),
1068
+ ...(created.tagHints.length ? { tagHints: created.tagHints } : {}),
987
1069
  ...(tagWarning ? { tagWarning } : {}),
988
1070
  };
989
1071
  },
@@ -1000,8 +1082,10 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1000
1082
  lines.push('⚠️ 模板小节空着:' + v.emptyTemplateSections.join('、') +
1001
1083
  ' —— 正文以 ## 开头,内容落在了它后面;把正文并进那一节,或删掉那行空标题(zk_lint 的「空模板小节」会复查)');
1002
1084
  }
1003
- if (v.tagWarning)
1004
- lines.push('⚠️ ' + v.tagWarning);
1085
+ if (v.tagHints?.length) {
1086
+ lines.push('⚠️ 标签近义:' + v.tagHints.map((h) => `${h.kind === 'case' ? '大小写变体' : '近义'}:#${h.input} ≈ #${h.tag}(${h.count} 篇)`).join('、') +
1087
+ ' —— 确认是不是同一个标签;要统一就改这一篇的 tags');
1088
+ }
1005
1089
  if (v.similar?.length) {
1006
1090
  lines.push('⚠️ 疑似已有:' + v.similar.map((s) => `${s.title}(${s.path},${s.score.toFixed(2)})`).join('、') +
1007
1091
  ' —— 先 read 确认是不是同一条;要合并就 zk_supersede,不要直接再写一遍');
@@ -1167,7 +1251,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1167
1251
  path: String(args.path),
1168
1252
  by: args.by ? String(args.by) : undefined,
1169
1253
  reason: args.reason ? String(args.reason) : undefined,
1170
- // 缺省是预演:一句「更新一下 wiki」不该让全库漂移(计划 D7)
1254
+ // 缺省是预演:一句「更新一下 wiki」不该让全库漂移
1171
1255
  dryRun: args.dry_run !== false,
1172
1256
  }, env.signal);
1173
1257
  return {
@@ -1315,7 +1399,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1315
1399
  tocWords: { type: 'number' },
1316
1400
  totalWords: { type: 'number' },
1317
1401
  overheadWords: { type: 'number' },
1318
- // G1 / G4:写 MEMORY 前的容量(纯增量字段,旧客户端只是多看到几列)
1402
+ // 写 MEMORY 前的容量(纯增量字段,旧客户端只是多看到几列)
1319
1403
  retiredEntries: { type: 'number' },
1320
1404
  headroom: { type: 'number' },
1321
1405
  extraWords: { type: 'number' },
@@ -1418,7 +1502,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1418
1502
  ? `笔记本「${current.name}」(${current.structure})→ ${current.path}` +
1419
1503
  (others.length ? `\n另有:${others.map((n) => `${n.name}(${n.structure})`).join('、')} —— zk_use 切换本会话` : '')
1420
1504
  : `笔记本「${v.notebook}」`;
1421
- // G1 / G4:写 MEMORY 前的余量、是否触发截断、同日决胜与「下一条会丢谁」
1505
+ // 写 MEMORY 前的余量、是否触发截断、同日决胜与「下一条会丢谁」
1422
1506
  const capacity = `\n\n容量:余 ${v.headroom} 词(记忆内容 ${v.words}/${v.budget},总载荷 ${v.totalWords})` +
1423
1507
  (v.extraWords > 0 ? ` · 拟新增 ${v.extraWords} 词${v.wouldTruncate ? '(会触发截断)' : ''}` : '') +
1424
1508
  (v.sameDateCount > 1 ? ` · ${v.sameDateCount} 条同日,按位置决胜` : '') +
@@ -1564,6 +1648,8 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1564
1648
  properties: {
1565
1649
  stale_days: S.num('多少天没修改算陈旧(1-3650,默认 90)'),
1566
1650
  links_only: S.bool('只报 Links 小节的单向链接;正文引用只计数(默认 false)'),
1651
+ include_provenance: S.bool('单向链接里连出处链(concept↔source)一起列;默认只计数(那类边按惯例有向)'),
1652
+ one_way_max: S.num('单向链接清单上限(1-500,默认 50);total 始终是全量'),
1567
1653
  },
1568
1654
  additionalProperties: false,
1569
1655
  },
@@ -1591,9 +1677,11 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1591
1677
  persona: LINT_PERSONA,
1592
1678
  timeline: LINT_TIMELINE,
1593
1679
  emptySections: LINT_EMPTY_SECTIONS,
1680
+ bodyTags: LINT_BODY_TAGS,
1594
1681
  indexHint: { type: 'boolean' },
1682
+ index: LINT_INDEX,
1595
1683
  indexLag: { type: 'string' },
1596
- }, ['notebook', 'notes', 'missingId', 'truncated', 'completeness', 'scanLimit', 'staleDays', 'parseErrors', 'orphans', 'brokenLinks', 'stale', 'tagless', 'oneWayLinks', 'duplicateTitles', 'similarTitles', 'memoryLinks', 'incomplete', 'tags', 'template', 'persona', 'timeline', 'emptySections', 'indexHint', 'indexLag']),
1684
+ }, ['notebook', 'notes', 'missingId', 'truncated', 'completeness', 'scanLimit', 'staleDays', 'parseErrors', 'orphans', 'brokenLinks', 'stale', 'tagless', 'oneWayLinks', 'duplicateTitles', 'similarTitles', 'memoryLinks', 'incomplete', 'tags', 'template', 'persona', 'timeline', 'emptySections', 'bodyTags', 'indexHint', 'index', 'indexLag']),
1597
1685
  },
1598
1686
  async run(args, env) {
1599
1687
  const cfg = configFor(env.workspace, env.sessionId);
@@ -1601,6 +1689,8 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1601
1689
  return lintNotebook(cfg, {
1602
1690
  staleDays: args.stale_days === undefined ? undefined : Number(args.stale_days),
1603
1691
  linksOnly: args.links_only === true,
1692
+ includeProvenance: args.include_provenance === true,
1693
+ oneWayMax: args.one_way_max === undefined ? undefined : Number(args.one_way_max),
1604
1694
  }, env.signal);
1605
1695
  },
1606
1696
  render(_args, value) {
@@ -1621,18 +1711,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1621
1711
  lines.push(line('孤儿', v.orphans));
1622
1712
  lines.push(line('无标签', v.tagless));
1623
1713
  const oneWay = v.oneWayLinks;
1624
- const oneWayLabel = oneWay.linksOnly ? '单向链接(Links)' : '单向链接';
1625
- const bodyNote = oneWay.bodyOnly > 0
1626
- ? (oneWay.linksOnly ? '(另有正文引用 ' + oneWay.bodyOnly + ' 条未计)' : '(正文引用 ' + oneWay.bodyOnly + ' 条)')
1627
- : '';
1628
- if (oneWay.total === 0)
1629
- lines.push('✓ ' + oneWayLabel + ':0' + bodyNote);
1630
- else {
1631
- const items = oneWay.items.slice(0, 5).map((i) => i.path + ' ← ' + i.from.join('、'));
1632
- lines.push('✗ ' + oneWayLabel + ':' + oneWay.total + ' 篇 / ' + oneWay.edges + ' 条单向边' +
1633
- bodyNote +
1634
- ' — ' + items.join(';') + (oneWay.total > items.length ? ' …' : ''));
1635
- }
1714
+ lines.push(formatOneWay(oneWay));
1636
1715
  lines.push(v.stale.total === 0
1637
1716
  ? '✓ 陈旧:0'
1638
1717
  : '✗ 陈旧:' + v.stale.total + ' 篇 — ' +
@@ -1697,7 +1776,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1697
1776
  totalWords: { type: 'number' },
1698
1777
  budget: { type: 'number' },
1699
1778
  headroom: { type: 'number' },
1700
- /** G1:与 zk_lint.memoryLinks 同一口径的格式债 / 退役计数 */
1779
+ /** 与 zk_lint.memoryLinks 同一口径的格式债 / 退役计数 */
1701
1780
  undated: { type: 'number' },
1702
1781
  unlinked: { type: 'number' },
1703
1782
  retired: { type: 'number' },
@@ -1806,7 +1885,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1806
1885
  ' = ' + memoryTotal + ' 词(余 ' + v.memory.headroom + ')' +
1807
1886
  (v.memory.personaWords > 0 ? ' · 人格 ' + v.memory.personaWords + ' 词(单独注入,不计入记忆预算)' : ''));
1808
1887
  if (v.missingId > 0)
1809
- lines.push('· 稳定 ID:' + v.missingId + ' 篇没有 id — 新笔记自动写入,老笔记只提示、不回填(§9.2)');
1888
+ lines.push('· 稳定 ID:' + v.missingId + ' 篇没有 id — 新笔记自动写入,老笔记只提示、不回填');
1810
1889
  if (v.retireCandidates.length) {
1811
1890
  lines.push('可考虑退役:');
1812
1891
  for (const c of v.retireCandidates.slice(0, 10)) {
@@ -1926,7 +2005,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1926
2005
  },
1927
2006
  completeness: { type: 'string', enum: ['complete', 'partial', 'unknown'] },
1928
2007
  scanLimit: { type: 'number' },
1929
- /** 本地聚合计数(plan §14.4):只看「入口 / 一跳」这条路有没有被用上,不记查询词 */
2008
+ /** 本地聚合计数:只看「入口 / 一跳」这条路有没有被用上,不记查询词 */
1930
2009
  usage: objSchema({
1931
2010
  since: { type: 'string' },
1932
2011
  search: { type: 'number' },
@@ -31,6 +31,31 @@ export function templateVersionOf(body) {
31
31
  const hit = TEMPLATE_MARK_RE.exec(String(body ?? ''));
32
32
  return hit ? Number(hit[1]) : 0;
33
33
  }
34
+ /**
35
+ * WORKFLOW.md 的模板版本:**独立**于 `TEMPLATE_VERSION`。
36
+ *
37
+ * 为什么独立:两份文件各改各的(AGENTS 注入、WORKFLOW 按需读),共用一个号时
38
+ * 「AGENTS 升到 v12、WORKFLOW 内容一字未变」也会让 WORKFLOW 被标成旧版 —— 反过来,
39
+ * 只升 AGENTS 的人不会想到还要动 WORKFLOW,旧号就永远留着。v12 及更早的 WORKFLOW.md
40
+ * 首行用的是 `zdiary-template`,`workflowVersionOf` 对它返回 0(lint 报「旧标记」,不是「v0 模板」)。
41
+ */
42
+ export const WORKFLOW_VERSION = 1;
43
+ export const WORKFLOW_MARK = `<!-- zdiary-workflow: v${WORKFLOW_VERSION} -->`;
44
+ const WORKFLOW_MARK_RE = /<!--\s*zdiary-workflow:\s*v(\d+)\s*-->/;
45
+ /** WORKFLOW.md 的版本;没有新标记返回 0(含 v12 及更早的共用标记) */
46
+ export function workflowVersionOf(body) {
47
+ const hit = WORKFLOW_MARK_RE.exec(String(body ?? ''));
48
+ return hit ? Number(hit[1]) : 0;
49
+ }
50
+ /** 旧版 WORKFLOW.md 首行:与 AGENTS 共用的标记(v12 及更早) */
51
+ export const WORKFLOW_LEGACY_MARK_RE = /<!--\s*zdiary-template:\s*v(\d+)\s*-->/;
52
+ /**
53
+ * WORKFLOW.md 当前版本的正文哨兵:标记已经是新版号、正文却还是旧版时抓出来。
54
+ * 只挑「新版才有 / 旧版已删」的确定文本,不做语义判断。
55
+ */
56
+ export const WORKFLOW_SENTINELS = {
57
+ 1: { required: ['zk_memory_write', 'zk_rename'] },
58
+ };
34
59
  /**
35
60
  * 当前版本的正文哨兵:只查「标记已经是当前版本」的文件,用来发现
36
61
  * 「只把首行数字改成 vN、正文还是旧版」。
@@ -98,7 +123,7 @@ MEMORY.md 每条:结论(YYYY-MM-DD)[[来源路径]],先 read 核对来
98
123
  * 根目录 WORKFLOW.md:只在「要动已有笔记」时才需要读,所以不注入、不计预算。
99
124
  * 放进注入的话,AGENTS.md 一膨胀就会挤掉 MEMORY —— 这些规则低频但重要,适合按需读。
100
125
  */
101
- export const WORKFLOW_TEMPLATE = `${TEMPLATE_MARK}
126
+ export const WORKFLOW_TEMPLATE = `${WORKFLOW_MARK}
102
127
 
103
128
  # 改笔记的工作流(按需读)
104
129
 
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * 死胡同探针:检索命中一篇活笔记时,顺手看归档里有没有**同一条结论**的废弃版本,带出废弃原因。
3
3
  *
4
- * 为什么需要(plan §14.3):`supersede` 的旧结论被 `excludedNames` 排除出检索,
4
+ * 为什么需要:`supersede` 的旧结论被 `excludedNames` 排除出检索,
5
5
  * 只有 `zk_new` 写同名时才提示一次。于是 agent 在读 / 想的阶段看不到「这条路试过、为什么废」,
6
6
  * 只能重新踩一遍 —— 而按 HackerNoon 那条分工,死胡同复现正是最该省掉的工。
7
7
  * 这不是「不查全」的谦逊,是主动隐藏反例。
@@ -0,0 +1,139 @@
1
+ /**
2
+ * 正文里的「纯标签段」:整段只有 `#a #b`,一个字的正文都没有。
3
+ *
4
+ * 这是 frontmatter `tags` 的第二份真相 —— 模板带 `tags: []` 之后,`zk-new` 已经只写
5
+ * frontmatter(见 `frontmatter.ts` 的 `placeTags`),但旧版本 / 手工写入的笔记还留着正文那行。
6
+ * 两份同时存在时 zk 取并集:只改 frontmatter 不会让旧标签失效,删掉的标签还能被 `--tag` 命中,
7
+ * 人读正文却对不上。所以 lint 要报、`zk-kit tidy` 要能收掉。
8
+ *
9
+ * 口径只写这一份:lint(只报告)与 tidy(默认预演、--fix 落盘)必须同一个判据,
10
+ * 否则「体检说 3 篇」与「命令清 5 篇」会各说各话。
11
+ */
12
+ import { fenceMask } from './fence.js';
13
+ import { formatFlowList, parseFlowList, parseFrontmatter, setFrontmatter } from './frontmatter.js';
14
+ /**
15
+ * 整行只有 hashtag:`#a`、`#a #b`、`#中文-标签`。
16
+ * 必须整行匹配 —— 正文句子里的 `#tag` 不是标签段,不能当可删目标。
17
+ * 字符集与 zk 的 hashtag 解析一致(`\p{L}\p{N}_-`),别让「体检认得、zk 不认」。
18
+ */
19
+ const TAG_LINE = /^[ \t]*#[\p{L}\p{N}_-]+(?:[ \t]+#[\p{L}\p{N}_-]+)*[ \t]*\r?$/u;
20
+ const TAG_TOKEN = /#([\p{L}\p{N}_-]+)/gu;
21
+ /**
22
+ * 找正文里的纯标签段。
23
+ *
24
+ * 跳过三类位置:frontmatter、围栏代码块、以及正文第一行(无空格的 `#标题` 在 zk 眼里是
25
+ * hashtag,但结构上它是 H1 —— 删掉等于删标题,宁可不碰)。
26
+ * 连续多行标签算一段;空行分开的两行标签算两段(两段都删,空行一并收掉)。
27
+ */
28
+ export function findTagParagraphs(content) {
29
+ const text = String(content ?? '');
30
+ const lines = text.split('\n');
31
+ const body = parseFrontmatter(text).body;
32
+ const bodyStart = lines.length - body.split('\n').length;
33
+ const bodyLines = lines.slice(bodyStart);
34
+ const mask = fenceMask(bodyLines);
35
+ const out = [];
36
+ let firstContent = true;
37
+ let current = null;
38
+ const flush = () => {
39
+ if (current)
40
+ out.push(current);
41
+ current = null;
42
+ };
43
+ for (let i = 0; i < bodyLines.length; i++) {
44
+ const line = bodyLines[i];
45
+ if (line.trim() === '') {
46
+ flush();
47
+ continue;
48
+ }
49
+ if (mask[i] || !TAG_LINE.test(line)) {
50
+ flush();
51
+ firstContent = false;
52
+ continue;
53
+ }
54
+ // 正文的第一处内容不碰:`#标题`(无空格)与标签行同形,结构上却是标题
55
+ if (firstContent) {
56
+ firstContent = false;
57
+ continue;
58
+ }
59
+ const tags = [...line.matchAll(TAG_TOKEN)].map((m) => m[1]);
60
+ if (!tags.length) {
61
+ flush();
62
+ continue;
63
+ }
64
+ const start = bodyStart + i;
65
+ if (current && current.end === start - 1) {
66
+ current.end = start;
67
+ current.tags.push(...tags);
68
+ }
69
+ else {
70
+ flush();
71
+ current = { start, end: start, tags };
72
+ }
73
+ }
74
+ flush();
75
+ return out;
76
+ }
77
+ /**
78
+ * 这篇笔记的正文标签能不能收:只有 frontmatter 有可解析的 `tags` 格才判定。
79
+ *
80
+ * `null` 有三种情况,含义都是「别动」:没有 `tags` 格(flat / 自定义模板,正文标签是
81
+ * zk 唯一的索引来源)、`tags` 值不是 flow 列表(块式列表猜错一次就是写坏 frontmatter)、
82
+ * 正文没有纯标签段。
83
+ */
84
+ export function tagCleanup(content) {
85
+ const fields = parseFrontmatter(content).fields;
86
+ if (!('tags' in fields))
87
+ return null;
88
+ const frontmatterTags = parseFlowList(fields.tags ?? '');
89
+ if (frontmatterTags === null)
90
+ return null;
91
+ const paragraphs = findTagParagraphs(content);
92
+ if (!paragraphs.length)
93
+ return null;
94
+ const tags = [...new Set(paragraphs.flatMap((p) => p.tags))];
95
+ const known = new Set(frontmatterTags);
96
+ const drift = tags.filter((tag) => !known.has(tag));
97
+ return { paragraphs, tags, frontmatterTags, drift, removable: drift.length === 0 };
98
+ }
99
+ /** 把标签并进 frontmatter 的 `tags` 格(保留已有顺序,新标签追加在后);形状不认识时原样返回 */
100
+ export function mergeTagsIntoFrontmatter(content, tags) {
101
+ const fields = parseFrontmatter(content).fields;
102
+ const existing = parseFlowList(fields.tags ?? '');
103
+ if (existing === null)
104
+ return content;
105
+ const merged = [...existing];
106
+ for (const tag of tags)
107
+ if (!merged.includes(tag))
108
+ merged.push(tag);
109
+ return setFrontmatter(content, { tags: formatFlowList(merged) });
110
+ }
111
+ /**
112
+ * 删掉指定的标签段,并收掉段后紧跟的空行(否则正文与 `## Links` 之间会留双空行)。
113
+ * 只动这些行:其余行原样拼回,frontmatter 与围栏代码块不会被重排。
114
+ */
115
+ export function stripTagParagraphs(content, paragraphs) {
116
+ if (!paragraphs.length)
117
+ return content;
118
+ const lines = String(content ?? '').split('\n');
119
+ const gone = new Uint8Array(lines.length);
120
+ for (const p of paragraphs) {
121
+ for (let i = p.start; i <= p.end; i++)
122
+ if (i >= 0 && i < lines.length)
123
+ gone[i] = 1;
124
+ }
125
+ const keep = [];
126
+ let justRemoved = false;
127
+ for (let i = 0; i < lines.length; i++) {
128
+ if (gone[i]) {
129
+ justRemoved = true;
130
+ continue;
131
+ }
132
+ // 段后空行:删段时一并收掉,保留原来那一个分隔空行(段前那个)
133
+ if (justRemoved && lines[i].trim() === '')
134
+ continue;
135
+ justRemoved = false;
136
+ keep.push(lines[i]);
137
+ }
138
+ return keep.join('\n');
139
+ }
package/dist/lib/dream.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * 做梦(M3):只给材料,不写任何文件(计划 §3 D5 / D7)。
2
+ * 做梦:只给材料,不写任何文件。
3
3
  *
4
4
  * 晋升 MEMORY.md、写 DREAMS.md 都是 agent 的语义活;这里只做三件机械事:
5
5
  * · 最近 N 天新增的笔记(按机械规则挡掉不可晋升的,附原因;日记不算候选,它的未完成项单独一栏);
@@ -7,7 +7,7 @@
7
7
  * · 被引用最多的笔记(一次 `zk graph` 数入链)。
8
8
  * 「rejected」是机械规则,不是相关性判断:authority=informal 与无标签两条,别再加。
9
9
  *
10
- * 晋升是一道**门**,门得知道门里已经有什么(P0-2):读 MEMORY.md 判「这条已经晋升过」,
10
+ * 晋升是一道**门**,门得知道门里已经有什么:读 MEMORY.md 判「这条已经晋升过」,
11
11
  * 已经进去的移出候选、单列一栏 —— 否则同一批笔记每周原样重复,仪式几次之后就没人再看了。
12
12
  * 窗口默认也不再固定 7 天,而是跟着 DREAMS.md 的「上次做梦」走:漏做一周不会把笔记永久甩出窗口。
13
13
  */
@@ -25,7 +25,7 @@ import { isMetaPath } from './meta.js';
25
25
  import { MAX_EVIDENCE_ENTRIES, MAX_EVIDENCE_SOURCES, MAX_EVIDENCE_TARGETS, noteEvidenceOf, } from './evidence.js';
26
26
  import { normalizeTitle, noteKey, resolveWikiTarget, WIKI_LINK, wikiIndex } from './wikilink.js';
27
27
  import { AUDIT_RATE, hasRecallSignal, lastRecallOf, readRecallSignal, RECALL_PROTECT_DAYS } from './recall-signal.js';
28
- /** 每栏最多回多少条(计划 §4 M3 的 50 条上限) */
28
+ /** 每栏最多回多少条 */
29
29
  export const MAX_ITEMS = 50;
30
30
  /** topCited 只取前几名:给 agent 一个「本周被反复引用」的提示,不是排行榜 */
31
31
  export const TOP_CITED = 10;
@@ -96,7 +96,7 @@ export function looseEndsOf(content) {
96
96
  * 机械拒绝规则(只两条,别加语义判断):
97
97
  * · authority=informal —— 口头/未验证来源,进长期记忆会污染结论;
98
98
  * · 无标签 —— 标签是唯一能确定性筛选的维度;没标签的笔记晋升后只能靠全文检索找回来
99
- * (P2-7 起中文检索不再漏,但「按主题找」还是得靠标签)。
99
+ * (中文检索不再漏,但「按主题找」还是得靠标签)。
100
100
  */
101
101
  export function rejectionReason(note) {
102
102
  if (note.authority === 'informal')
@@ -110,7 +110,7 @@ function isUnder(rel, dir) {
110
110
  return rel === d || rel.startsWith(d + '/');
111
111
  }
112
112
  /**
113
- * 笔记的日历日期(计划 §2 D7 / Q6)。
113
+ * 笔记的日历日期。
114
114
  *
115
115
  * 日记补写时 `zk_daily --date` 只改文件名,zk 的 `created` 仍是今天 —— 按 created 筛窗口
116
116
  * 会把 10 月的日记算成本周新增。所以:日记看文件名,其他笔记看 frontmatter `date`,
@@ -198,7 +198,7 @@ function windowDaysOf(cfg, now, explicit) {
198
198
  * 而它们正是每周重复出现的候选来源。标题包含只做字符串比较、且要求标题 ≥ 6 字 ——
199
199
  * 短标题(「RAG」「额度」)在任意句子里都可能撞上,宁可重复报,不猜。
200
200
  *
201
- * 退役条目要分开处理(D3.3,顺序不能反):
201
+ * 退役条目要分开处理(顺序不能反):
202
202
  * · 链接匹配用**原文** —— 退役行里的 `→ [[新结论]]` 是合法的「已晋升」指针;
203
203
  * · 标题匹配用**去掉退役行之后**的正文 —— 退役行里的旧结论不该再算已晋升,
204
204
  * 否则归档后复用同一标题的笔记会永远进不了候选。
@@ -220,7 +220,7 @@ function promotionsOf(cfg, notes) {
220
220
  const clean = withoutFences(body);
221
221
  for (const match of clean.matchAll(WIKI_LINK)) {
222
222
  const hit = resolveWikiTarget(cfg, String(match[1] ?? '').trim(), index);
223
- // 解析结果是路径,按身份键记账(§9.2):有 id 的笔记改名后仍是同一篇,不会重复晋升。
223
+ // 解析结果是路径,按身份键记账:有 id 的笔记改名后仍是同一篇,不会重复晋升。
224
224
  const note = byPath.get(hit.path);
225
225
  if (hit.status === 'live' && note)
226
226
  out.set(noteKey(note), 'link');
@@ -253,7 +253,7 @@ function sourceTargetsOf(entry) {
253
253
  return out;
254
254
  }
255
255
  /**
256
- * 退役候选(D4.3):只做机械规则,不判断「这条还有没有用」。
256
+ * 退役候选:只做机械规则,不判断「这条还有没有用」。
257
257
  * · 有日期且超过 STALE_DAYS → stale;
258
258
  * · 条目里的 `[[来源]]` 指向归档 / 不存在 → source-superseded / source-missing;
259
259
  * · 显式写 `archive/` 的链接是有意引用旧结论(与 lint 同口径),不算来源断了;
@@ -309,7 +309,7 @@ function retireCandidatesOf(cfg, notes, now, signal) {
309
309
  /**
310
310
  * 依据回对(只读):把每条现行 MEMORY 结论的 `[[来源]]` 链与出处原话 / 外部地址并排摆出来。
311
311
  *
312
- * 两跳封顶,不做全图游走(§5):第一跳是条目里的 `[[来源]]`,第二跳只走这些笔记
312
+ * 两跳封顶,不做全图游走:第一跳是条目里的 `[[来源]]`,第二跳只走这些笔记
313
313
  * 「出处 / 引文」小节里的 `[[链接]]`。全部本地读盘、零 zk 子进程;`raw/` 里的原始材料
314
314
  * 虽然不进索引,路径式链接照样能读(那正是「拿原话回来对」要的东西)。
315
315
  * 解析不到 / meta 文件 / 越界一律跳过,不猜、不补、不写。
@@ -387,7 +387,7 @@ export async function dreamNotebook(cfg, opts = {}, signal) {
387
387
  // 顺序跑:两个 zk 进程同时补索引会撞 SQLite 写锁(lint 里同样处理)
388
388
  const scan = await scanNotes(cfg, {}, signal);
389
389
  const notes = scan.notes;
390
- // 全图在 10k 上 26–31 s / 17 MB(plan §0.5.1):超过预算就不建,并显式告诉调用方。
390
+ // 全图在 10k 上 26–31 s / 17 MB:超过预算就不建,并显式告诉调用方。
391
391
  // 预算来自配置(设置页可调);opts.graphBudget 只给测试覆盖。
392
392
  const graphBudget = Math.max(0, Math.trunc(opts.graphBudget ?? cfg.graphBudgetNotes ?? GRAPH_BUDGET_NOTES));
393
393
  const graphReady = notes.length <= graphBudget;
@@ -403,7 +403,7 @@ export async function dreamNotebook(cfg, opts = {}, signal) {
403
403
  inbound.set(edge.targetPath, sources);
404
404
  }
405
405
  const citedOf = (n) => inbound.get(n.path)?.length ?? 0;
406
- // 使用信号(P2-12):日记是本插件里唯一「按时间记录真实工作」的层,正好当召回日志用。
406
+ // 使用信号:日记是本插件里唯一「按时间记录真实工作」的层,正好当召回日志用。
407
407
  // 零新增状态:来源路径与日期都在已载入的 notes / edges 里。
408
408
  const byPath = new Map(notes.map((n) => [n.path, n]));
409
409
  const usageCache = new Map();
@@ -504,7 +504,7 @@ export async function dreamNotebook(cfg, opts = {}, signal) {
504
504
  dailyLooseEnds.push({ path: note.path, date: noteDate(cfg, note), items });
505
505
  }
506
506
  }
507
- // 排序说明(P2-12):先看「被日记提过几天」—— 跨天复现比同一天多次更强;同一天多篇日记
507
+ // 排序说明:先看「被日记提过几天」—— 跨天复现比同一天多次更强;同一天多篇日记
508
508
  // 再按 dailyMentions 排,入链数只是最后的次序。没有日记的库两项都是 0,
509
509
  // 排序自动退回原来的 cited 降序(行为兼容)。
510
510
  // 15.2:信号生效时先按「召回跨天数 → 查询多样性」;全 0 时下面的次序与原排序完全一致。