dsh-zdiary-kit 1.0.5 → 2.1.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.
@@ -1,11 +1,12 @@
1
1
  /**
2
- * zk 工具(feature 的公共入口):14 个模型可调用的工具,全部经 lib/zk.ts。
2
+ * zk 工具(feature 的公共入口):15 个内置工具 + `[alias]` 别名工具,全部经 lib/zk.ts。
3
3
  *
4
4
  * 设计要点:
5
5
  * · 除 zk_context(只读 meta 文件,不依赖 zk)外,每个工具进来先 ensureNotebook —— 第一次调用就自动建好笔记本,用户不用先点设置页;
6
6
  * · 参数在 execute 里手动校验(DSH 对裸注册的工具不做输入校验);
7
7
  * · output.schema 只用 DSH 支持的子集(type/properties/required/items/enum + 注释);
8
- * · render 是纯函数:模型看到人话,程序拿到结构化值。
8
+ * · render 是纯函数:模型看到人话,程序拿到结构化值;
9
+ * · 别名工具在注册时按 `.zk/config.toml` 的 `[alias]` 追加,执行交给 `zk <别名>`(插件不拼 shell)。
9
10
  */
10
11
  import fs from 'node:fs';
11
12
  import path from 'node:path';
@@ -14,13 +15,17 @@ import { configFor, pinSession, sessionNotebook, sessionState } from '../../conf
14
15
  import { defaultNotebook, expandHome, processWorkspace, resolveInWorkspace } from '../../config/paths.js';
15
16
  import { S, validateArgs } from '../../lib/tool.js';
16
17
  import { ensureNotebook, newNoteDir } from '../../lib/notebook.js';
17
- import { searchNotes, searchNotesDetailed, createNote, readNote, findNote, appendToNote, ensureDailyNote, appendDaily, linkNotes, withTags, taglessCjkWarning, notebookStats, supersedeNote, renameNote, hasNotebook, isUnderDir, localDate as dateOnly, ZkError, } from '../../lib/zk.js';
18
+ import { searchNotes, searchNotesDetailed, createNote, readNote, findNote, appendToNote, ensureDailyNote, appendDaily, linkNotes, withTags, taglessCjkWarning, notebookStats, supersedeNote, renameNote, hasNotebook, isUnderDir, localDate as dateOnly, runAlias, ZkError, } from '../../lib/zk.js';
19
+ import { configuredAliases, readAliases } from '../../lib/alias.js';
18
20
  import { buildMemoryPayload, META_FILES } from '../../lib/memory.js';
19
- import { capPolicyIssues, parsePolicy, POLICY_APPROVALS, POLICY_ISSUE_KINDS, POLICY_LEVELS } from '../../lib/policy.js';
20
21
  import { META_NAMES } from '../../lib/meta.js';
22
+ import { buildScene, combinedWords } from '../../lib/scene.js';
23
+ import { appendEvent, checkAppendInput, pruneStateLog, readStateLog, StateError } from '../../lib/state-log.js';
21
24
  import { formatLintExtras, formatMemoryLinks, lintNotebook } from '../../lib/lint.js';
22
25
  import { dreamNotebook, STALE_DAYS } from '../../lib/dream.js';
23
26
  const text = (value) => [{ type: 'text', text: value }];
27
+ /** 事件参数回显成一行 `key=value`;含空白 / 引号的值用 JSON 引号包一层 */
28
+ const paramsText = (params) => Object.entries(params).map(([key, value]) => `${key}=${/[\s"]/.test(value) ? JSON.stringify(value) : value}`).join(' ');
24
29
  const objSchema = (properties, required) => ({
25
30
  type: 'object',
26
31
  properties,
@@ -149,29 +154,13 @@ const LINT_TEMPLATE = objSchema({
149
154
  mismatchDetail: { type: 'string' },
150
155
  currentText: { type: 'string' },
151
156
  }, ['present', 'version', 'current', 'stale']);
152
- /** 自主权契约的一条结构问题:lint 与 zk_context 共用,enum 从 POLICY_ISSUE_KINDS 取,避免两处漂移 */
153
- const POLICY_ISSUE = objSchema({
154
- kind: { type: 'string', enum: [...POLICY_ISSUE_KINDS] },
155
- detail: { type: 'string' },
156
- }, ['kind', 'detail']);
157
- /** 自主权契约体检:表头 / 列数 / level / approval / reversible / 重复动作 / 审计落点(只报告) */
158
- const LINT_POLICY = objSchema({
159
- present: { type: 'boolean' },
160
- rows: { type: 'number' },
161
- total: { type: 'number' },
162
- items: {
163
- type: 'array',
164
- items: POLICY_ISSUE,
165
- },
166
- truncated: { type: 'boolean' },
167
- }, ['present', 'rows', 'total', 'items', 'truncated']);
168
157
  /** 契约体检:缺失 / 旧版 / 比插件新 / 标记与内容不符 / 未填占位符(只报告,不覆盖) */
169
158
  const LINT_CONTRACT = objSchema({
170
159
  total: { type: 'number' },
171
160
  items: {
172
161
  type: 'array',
173
162
  items: objSchema({
174
- file: { type: 'string', enum: ['PERSONA.md', 'POLICY.md'] },
163
+ file: { type: 'string', enum: ['PERSONA.md'] },
175
164
  kind: { type: 'string', enum: ['missing', 'old', 'newer', 'mismatch', 'placeholder'] },
176
165
  detail: { type: 'string' },
177
166
  }, ['file', 'kind', 'detail']),
@@ -203,7 +192,8 @@ const LINT_PARSE = objSchema({
203
192
  },
204
193
  }, ['total', 'items']);
205
194
  function fail(err) {
206
- if (err instanceof ZkError) {
195
+ // StateError 与 ZkError 同为「人话 + 下一步」:hint 必须一起交给模型,否则它只知道写错了、不知道怎么写
196
+ if (err instanceof ZkError || err instanceof StateError) {
207
197
  throw new Error(err.hint ? `${err.message}(${err.hint})` : err.message);
208
198
  }
209
199
  throw err instanceof Error ? err : new Error(String(err));
@@ -273,9 +263,75 @@ function def(spec, workspaceOf) {
273
263
  },
274
264
  };
275
265
  }
266
+ /** `[alias]` 自定义命令 → `zk_<名>` 工具:执行完全交给 zk,插件只负责把 argv 传进去 */
267
+ function aliasTool(alias, workspaceOf) {
268
+ const command = alias.command.length > 200 ? alias.command.slice(0, 200) + '…' : alias.command;
269
+ const detail = alias.description
270
+ ? `${alias.description.replace(/[。.!!]\s*$/, '')}${command ? `(命令:${command})` : ''}`
271
+ : (command ? `运行命令 ${command}` : '运行 config.toml 里定义的命令');
272
+ return def({
273
+ name: `zk_${alias.name}`,
274
+ description: `笔记本 .zk/config.toml 的 [alias] 里定义的自定义命令「${alias.name}」:${detail}。` +
275
+ '调用等于 `zk <别名> [args]`:args 按顺序追加到别名命令里的 $@;输出按原样返回,不做 JSON 解析。' +
276
+ '它是人写的 shell 命令,不受内置 zk_* 的路径 / meta 守卫约束(args 也可能改变它操作的库)。',
277
+ parameters: {
278
+ type: 'object',
279
+ properties: {
280
+ args: S.arr('额外参数,按顺序追加到 zk <别名> 之后(对应别名命令里的 $@)', S.str('参数值')),
281
+ },
282
+ additionalProperties: false,
283
+ },
284
+ output: {
285
+ schema: objSchema({
286
+ alias: { type: 'string' },
287
+ output: { type: 'string' },
288
+ stderr: { type: 'string' },
289
+ chars: { type: 'number' },
290
+ truncated: { type: 'boolean' },
291
+ }, ['alias', 'output', 'stderr', 'chars', 'truncated']),
292
+ },
293
+ async run(args, env) {
294
+ const cfg = configFor(env.workspace, env.sessionId);
295
+ // 工具列表只在下一次加载时重建,执行权不能跟着等到重载才收:开关关掉就立刻拒绝。
296
+ if (!cfg.aliasTools) {
297
+ throw new ZkError(`别名工具已停用:aliasTools=false(zk_${alias.name} 不再执行)`, '设置页「工具」组重新打开,或 zk-kit config set aliasTools=true;重载插件后工具列表也会同步');
298
+ }
299
+ await ensureNotebook(cfg, env.signal);
300
+ // 工具是全局注册的,会话可以随时 zk_use 切库:执行前按**当前笔记本**核对一次
301
+ if (!readAliases(cfg).some((item) => item.name === alias.name)) {
302
+ throw new ZkError(`当前笔记本没有别名「${alias.name}」:${cfg.notebook}`, `在 ${path.join(cfg.notebook, '.zk', 'config.toml')} 的 [alias] 里定义它,或用 zk_use 切到定义了它的笔记本`);
303
+ }
304
+ const argv = Array.isArray(args.args) ? args.args.map(String) : [];
305
+ const r = await runAlias(cfg, alias.name, argv, { cwd: env.workspace, signal: env.signal });
306
+ const limit = Math.min(200_000, Math.max(1000, Math.trunc(cfg.maxReadChars)));
307
+ const truncated = r.stdout.length > limit;
308
+ const stderr = r.stderr.trim();
309
+ return {
310
+ alias: alias.name,
311
+ output: truncated ? r.stdout.slice(0, limit) : r.stdout,
312
+ stderr: stderr.length > 2_000 ? stderr.slice(0, 2_000) + '…' : stderr,
313
+ chars: r.stdout.length,
314
+ truncated,
315
+ };
316
+ },
317
+ render(_args, value) {
318
+ const v = value;
319
+ if (!v.output.trim() && !v.stderr)
320
+ return text(`别名 ${v.alias}:没有输出`);
321
+ const parts = [];
322
+ if (v.output.trim())
323
+ parts.push(v.output.trimEnd());
324
+ if (v.truncated)
325
+ parts.push(`…(已截断:原输出 ${v.chars} 字,可在 config.toml 里改用更短的 --format)`);
326
+ if (v.stderr)
327
+ parts.push('⚠️ ' + v.stderr);
328
+ return text(parts.join('\n'));
329
+ },
330
+ }, workspaceOf);
331
+ }
276
332
  export function buildTools(workspaceOf = () => processWorkspace()) {
277
333
  const t = (spec) => def(spec, workspaceOf);
278
- return [
334
+ const builtins = [
279
335
  t({
280
336
  name: 'zk_search',
281
337
  description: '在 zk 知识库里搜索笔记(全文 / 标签 / 日期 / 断链 / 孤立笔记),返回标题、相对路径、标签、创建日与摘要。' +
@@ -889,9 +945,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
889
945
  t({
890
946
  name: 'zk_context',
891
947
  description: '读知识库根目录的长期约定与记忆(AGENTS.md / USER.md / MEMORY.md),按注入预算截断后返回;' +
892
- '角色契约与自主权契约(PERSONA.md / POLICY.md)单独成段、在记忆段之前、不参与截断。' +
893
- '另解析 POLICY.md 的四列动作表(只读;结构问题放 issues,不执行权限);' +
894
- 'issues 最多 50 条,total / truncated 给完整口径。' +
948
+ '角色契约(PERSONA.md)单独成段、在记忆段之前、不参与截断。' +
895
949
  '同时列出已配置的笔记本(名字 / 路径 / 结构 / 当前)。' +
896
950
  '宿主支持注入时这些内容每轮已自动进入系统提示;宿主不支持、或想核对「被截断了多少」时用它。',
897
951
  parameters: { type: 'object', properties: {}, additionalProperties: false },
@@ -925,27 +979,14 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
925
979
  }, ['present', 'contentWords', 'words', 'noticeWords', 'budget', 'overBudget', 'overWords', 'files']),
926
980
  scene: objSchema({
927
981
  present: { type: 'boolean' },
928
- expired: { type: 'boolean' },
982
+ presence: { type: 'string' },
983
+ events: { type: 'number' },
984
+ rulesVersion: { type: 'string' },
929
985
  words: { type: 'number' },
930
- }, ['present', 'expired', 'words']),
931
- policy: objSchema({
932
- present: { type: 'boolean' },
933
- actions: {
934
- type: 'array',
935
- items: objSchema({
936
- action: { type: 'string' },
937
- level: { type: 'string', enum: [...POLICY_LEVELS] },
938
- approval: { type: 'string', enum: [...POLICY_APPROVALS] },
939
- reversible: { type: 'boolean' },
940
- }, ['action', 'level', 'approval', 'reversible']),
941
- },
942
- total: { type: 'number' },
943
- issues: {
944
- type: 'array',
945
- items: POLICY_ISSUE,
946
- },
947
- truncated: { type: 'boolean' },
948
- }, ['present', 'actions', 'total', 'issues', 'truncated']),
986
+ emptyReason: { type: 'string' },
987
+ }, ['present', 'presence', 'events', 'rulesVersion', 'words', 'emptyReason']),
988
+ combinedWords: { type: 'number' },
989
+ combinedBudget: { type: 'number' },
949
990
  notebook: { type: 'string' },
950
991
  defaultNotebook: { type: 'string' },
951
992
  pinned: { type: 'string' },
@@ -968,25 +1009,27 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
968
1009
  retiredWords: { type: 'number' },
969
1010
  }, ['name', 'present', 'words', 'originalWords', 'retiredWords']),
970
1011
  },
971
- }, ['text', 'words', 'budget', 'ratio', 'truncatedWords', 'retiredWords', 'tocWords', 'totalWords', 'overheadWords', 'contract', 'scene', 'policy', 'notebook', 'defaultNotebook', 'pinned', 'notebooks', 'files']),
1012
+ }, ['text', 'words', 'budget', 'ratio', 'truncatedWords', 'retiredWords', 'tocWords', 'totalWords', 'overheadWords', 'contract', 'scene', 'combinedWords', 'combinedBudget', 'notebook', 'defaultNotebook', 'pinned', 'notebooks', 'files']),
972
1013
  },
973
1014
  async run(_args, env) {
974
1015
  // 不 ensureNotebook:读记忆不该依赖 zk,笔记本不存在时就是空载荷
975
1016
  const cfg = configFor(env.workspace, env.sessionId);
976
1017
  const state = sessionState(env.workspace, env.sessionId);
977
- const policy = parsePolicy(cfg);
978
- const policyIssues = capPolicyIssues(policy?.issues ?? []);
1018
+ const payload = buildMemoryPayload(cfg);
1019
+ const scene = buildScene(cfg);
979
1020
  return {
980
- ...buildMemoryPayload(cfg),
981
- policy: policy
982
- ? {
983
- present: true,
984
- actions: policy.rows,
985
- total: policyIssues.total,
986
- issues: policyIssues.items,
987
- truncated: policyIssues.truncated,
988
- }
989
- : { present: false, actions: [], total: 0, issues: [], truncated: false },
1021
+ ...payload,
1022
+ // 场景单独投影、单独预算(D7):不进 memory text,也不占记忆预算
1023
+ scene: {
1024
+ present: scene.present,
1025
+ presence: scene.presence,
1026
+ events: scene.events,
1027
+ rulesVersion: scene.rulesVersion,
1028
+ words: scene.words,
1029
+ emptyReason: scene.emptyReason,
1030
+ },
1031
+ combinedWords: combinedWords(payload.totalWords, scene),
1032
+ combinedBudget: cfg.totalPromptBudgetWords,
990
1033
  notebook: state.active,
991
1034
  defaultNotebook: state.defaultName,
992
1035
  pinned: state.diverged ? state.pinned : '',
@@ -1006,19 +1049,178 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1006
1049
  ? `笔记本「${current.name}」(${current.structure})→ ${current.path}` +
1007
1050
  (others.length ? `\n另有:${others.map((n) => `${n.name}(${n.structure})`).join('、')} —— zk_use 切换本会话` : '')
1008
1051
  : `笔记本「${v.notebook}」`;
1009
- if (!v.text)
1010
- return text(drift + head + `\n\n知识库根目录没有 ${META_FILES.join(' / ')}(或都是空的),也没有 PERSONA.md / POLICY.md 契约。`);
1052
+ if (!v.text && !v.scene.present) {
1053
+ const why = v.scene.emptyReason === 'budget'
1054
+ ? '场景有事件,但一行都放不下(调大 sceneBudgetWords)'
1055
+ : v.scene.emptyReason === 'rules'
1056
+ ? '场景规则没算出可展示的值'
1057
+ : v.scene.emptyReason === 'error'
1058
+ ? '场景读取失败(看 doctor / 设置页)'
1059
+ : '没有状态事件';
1060
+ return text(drift + head + `\n\n知识库根目录没有 ${META_FILES.join(' / ')}(或都是空的),也没有 PERSONA.md 契约。\n${why}。`);
1061
+ }
1011
1062
  const contract = v.contract?.present
1012
1063
  ? `\n\n契约:正文(含标题)${v.contract.contentWords}/${v.contract.budget} 词` +
1013
1064
  `(${v.contract.files.filter((f) => f.present).map((f) => `${f.name} ${f.words} 词`).join(' · ')})` +
1014
1065
  (v.contract.overBudget ? `,超 ${v.contract.overWords} 词(契约不截断)` : '')
1015
- : '\n\n契约:未启用(根目录没有 PERSONA.md / POLICY.md)';
1016
- const policy = v.policy?.present
1017
- ? `\n自主权契约:${v.policy.actions.length} 行动作` +
1018
- (v.policy.total > 0 ? ` · ${v.policy.total} 条结构问题(zk_lint 看明细)` : '') +
1019
- (v.policy.truncated ? `,issues 只列前 ${v.policy.issues.length} 条` : '')
1020
- : '';
1021
- return text(drift + head + contract + policy + '\n\n' + v.text);
1066
+ : '\n\n契约:未启用(根目录没有 PERSONA.md)';
1067
+ const presence = v.scene.presence === 'present' ? '在场' : v.scene.presence === 'absent' ? '不在' : '未知';
1068
+ const scene = v.scene.present
1069
+ ? `\n\n场景:${v.scene.words} 词(规则 ${v.scene.rulesVersion} · 窗口内 ${v.scene.events} 条事件 · 用户${presence})`
1070
+ : v.scene.emptyReason === 'budget'
1071
+ ? '\n\n场景:有事件,但一句都放不下(调大 sceneBudgetWords)'
1072
+ : v.scene.emptyReason === 'rules'
1073
+ ? '\n\n场景:规则没算出可展示的值(energy / mood / satiety / 地点 / 目标 都是 null)'
1074
+ : v.scene.emptyReason === 'error'
1075
+ ? '\n\n场景:读取失败(看 doctor / 设置页)'
1076
+ : '\n\n场景:未启用(.state/events.log 不存在或没有事件)';
1077
+ const over = v.combinedBudget > 0 && v.combinedWords > v.combinedBudget
1078
+ ? `,超 ${v.combinedWords - v.combinedBudget} 词(合并预算 ${v.combinedBudget})`
1079
+ : `(合并预算 ${v.combinedBudget})`;
1080
+ const totals = `\n\n用量:记忆载荷 ${v.totalWords} 词(预算 ${v.budget})+ 场景 ${v.scene.words} 词(预算单独算)= 合计 ${v.combinedWords} 词` + over;
1081
+ return text(drift + head + contract + scene + totals + (v.text ? '\n\n' + v.text : ''));
1082
+ },
1083
+ }),
1084
+ t({
1085
+ name: 'zk_state',
1086
+ description: '运行时状态:一行一条事件,场景是日志的投影(不存快照、不跑定时器)。' +
1087
+ 'append:记一件已经发生的事 —— 事件名 + 可选 key=value 参数,例:woke hours=7.5 / ate amount=1 / at place=书房 / set_goal text="写完 D7" / user_left / user_returned。' +
1088
+ '事件是你自己的叙述,插件只校验格式与时间,不校验真假;别把 token 余额之类宿主观测写进来。' +
1089
+ 'show:读当前投影(energy / mood / satiety / 地点 / 目标 / 在场)+ 窗口内最近 20 条事件,不回全量日志。' +
1090
+ 'prune:压实日志(保留窗口内全部 + 每个事件名在窗口外的最后一条),返回 dropped / kept;不自动 commit。' +
1091
+ '它不是日常操作:只有人明确要求、或 doctor 提示日志偏大时才用;它会删掉旧事件,默认别碰。' +
1092
+ '默认不翻历史:只有用户明确问「之前 / 过去」时才查;平时不要主动读 .state。',
1093
+ parameters: {
1094
+ type: 'object',
1095
+ properties: {
1096
+ action: S.enum('append 追加事件 / show 读投影 / prune 压实', ['append', 'show', 'prune']),
1097
+ event: S.str('append 用:事件名(小写字母开头,只含 [a-z0-9_],最长 32)'),
1098
+ params: S.arr('append 用:参数列表,形如 key=value(最多 8 个;字符串含空格要加引号)', S.str('key=value')),
1099
+ at: S.str('append 用:回填时间(ISO,必须带时区,如 2026-11-04T07:10:00+08:00);缺省 = 现在'),
1100
+ days: S.num('prune 用:窗口外的截止天数(必须 ≥ 投影窗口)'),
1101
+ force: S.bool('prune 用:截止天数小于投影窗口时强行压实'),
1102
+ },
1103
+ required: ['action'],
1104
+ additionalProperties: false,
1105
+ },
1106
+ output: {
1107
+ schema: objSchema({
1108
+ action: { type: 'string' },
1109
+ present: { type: 'boolean' },
1110
+ presence: { type: 'string' },
1111
+ rulesVersion: { type: 'string' },
1112
+ words: { type: 'number' },
1113
+ text: { type: 'string' },
1114
+ emptyReason: { type: 'string' },
1115
+ total: { type: 'number' },
1116
+ windowEvents: { type: 'number' },
1117
+ badLines: { type: 'number' },
1118
+ events: {
1119
+ type: 'array',
1120
+ items: objSchema({
1121
+ at: { type: 'string' },
1122
+ event: { type: 'string' },
1123
+ params: { type: 'string' },
1124
+ }, ['at', 'event', 'params']),
1125
+ },
1126
+ dropped: { type: 'number' },
1127
+ kept: { type: 'number' },
1128
+ windowDays: { type: 'number' },
1129
+ at: { type: 'string' },
1130
+ name: { type: 'string' },
1131
+ line: { type: 'string' },
1132
+ }, ['action', 'present', 'presence', 'rulesVersion', 'words', 'text', 'emptyReason', 'total', 'windowEvents', 'badLines', 'events', 'dropped', 'kept', 'windowDays', 'at', 'name', 'line']),
1133
+ },
1134
+ async run(args, env) {
1135
+ const cfg = configFor(env.workspace, env.sessionId);
1136
+ const action = String(args.action);
1137
+ const empty = {
1138
+ action, present: false, presence: 'unknown', rulesVersion: '', words: 0, text: '', emptyReason: 'no-log',
1139
+ total: 0, windowEvents: 0, badLines: 0, events: [],
1140
+ dropped: 0, kept: 0, windowDays: cfg.sceneWindowDays, at: '', name: '', line: '',
1141
+ };
1142
+ if (action === 'append') {
1143
+ const name = String(args.event ?? '').trim();
1144
+ if (!name)
1145
+ throw new StateError('append 需要 event(事件名)');
1146
+ const params = {};
1147
+ for (const item of Array.isArray(args.params) ? args.params : []) {
1148
+ const raw = String(item ?? '');
1149
+ const eq = raw.indexOf('=');
1150
+ if (eq <= 0)
1151
+ throw new StateError(`参数写法不对:${raw}`, '形如 place=书房;值里有空格就写 place="书房 阳台"');
1152
+ const key = raw.slice(0, eq).trim();
1153
+ let value = raw.slice(eq + 1).trim();
1154
+ if (value.startsWith('"') && value.endsWith('"') && value.length >= 2)
1155
+ value = value.slice(1, -1);
1156
+ if (key in params)
1157
+ throw new StateError(`参数重复:${key}`);
1158
+ params[key] = value;
1159
+ }
1160
+ const input = { name, params, at: args.at ? String(args.at) : undefined };
1161
+ // 先校验再建库:写错的事件不该在磁盘上留下一个刚初始化好的笔记本
1162
+ checkAppendInput(input);
1163
+ // 与其它写工具一致:第一个事件顺手把笔记本建好(否则只多一个没有 .zk 的 .state/)
1164
+ await ensureNotebook(cfg, env.signal);
1165
+ const written = appendEvent(cfg, input);
1166
+ return {
1167
+ ...empty,
1168
+ at: written.at,
1169
+ name: written.name,
1170
+ line: written.line,
1171
+ events: [{ at: written.at, event: written.name, params: paramsText(written.params) }],
1172
+ };
1173
+ }
1174
+ if (action === 'show') {
1175
+ const log = readStateLog(cfg, { windowDays: cfg.sceneWindowDays });
1176
+ const scene = buildScene(cfg);
1177
+ return {
1178
+ ...empty,
1179
+ present: scene.present,
1180
+ presence: scene.presence,
1181
+ rulesVersion: scene.rulesVersion,
1182
+ words: scene.words,
1183
+ text: scene.text,
1184
+ emptyReason: log.readError ? 'error' : scene.emptyReason,
1185
+ total: log.total,
1186
+ windowEvents: log.events.length,
1187
+ badLines: log.badLines.length,
1188
+ events: log.events.slice(-20).reverse().map((e) => ({ at: e.at, event: e.name, params: paramsText(e.params) })),
1189
+ };
1190
+ }
1191
+ if (action === 'prune') {
1192
+ const days = Number(args.days ?? cfg.sceneWindowDays);
1193
+ const r = pruneStateLog(cfg, { days, force: args.force === true, windowDays: cfg.sceneWindowDays });
1194
+ return { ...empty, dropped: r.dropped, kept: r.kept, windowDays: r.windowDays };
1195
+ }
1196
+ throw new StateError(`不认识的 action:${action}`, '只能是 append / show / prune');
1197
+ },
1198
+ render(_args, value) {
1199
+ const v = value;
1200
+ if (v.action === 'append')
1201
+ return text(`已记录:${v.line}\n(.state/events.log;场景下一轮装配时重算)`);
1202
+ if (v.action === 'prune') {
1203
+ return text(`已压实 .state/events.log:删除 ${v.dropped} 条,保留 ${v.kept} 条(窗口 ${v.windowDays} 天)。\n没有自动 commit —— 删除证据在 git diff 里,由人决定何时提交。`);
1204
+ }
1205
+ const presence = v.presence === 'present' ? '在场' : v.presence === 'absent' ? '不在' : '未知';
1206
+ const emptyText = v.emptyReason === 'budget'
1207
+ ? '(有事件,但场景预算一句都放不下:调大 sceneBudgetWords)'
1208
+ : v.emptyReason === 'rules'
1209
+ ? '(规则没算出可展示的值:energy / mood / satiety / 地点 / 目标 都是 null)'
1210
+ : v.emptyReason === 'error'
1211
+ ? '(场景读取失败:看 doctor / 设置页)'
1212
+ : '(没有可投影的场景:日志为空或窗口内没有事件)';
1213
+ const lines = [
1214
+ v.text || emptyText,
1215
+ `规则 ${v.rulesVersion || 'default'} · 窗口内 ${v.windowEvents} 条 · 历史共 ${v.total} 条` +
1216
+ (v.badLines > 0 ? ` · 坏行 ${v.badLines}` : '') + ` · 用户${presence}`,
1217
+ ];
1218
+ if (v.events.length) {
1219
+ lines.push('最近事件(新 → 旧,最多 20 条):');
1220
+ for (const e of v.events)
1221
+ lines.push(` ${e.at} ${e.event}${e.params ? ' ' + e.params : ''}`);
1222
+ }
1223
+ return text(lines.join('\n'));
1022
1224
  },
1023
1225
  }),
1024
1226
  t({
@@ -1030,8 +1232,6 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1030
1232
  '没写日期(undated)、已退役(retired)、退役后新结论失效(retiredBroken)与超过 90 天没复核(stale)的条目。' +
1031
1233
  'incomplete 是 frontmatter 缺 type / status / authority 的笔记:缺失被索引落成空串,机械门会静默失效。' +
1032
1234
  'tags 查标签卫生(大小写变体 / 单例,标签总数 ≥ 30 才报);template 说根目录 AGENTS.md 是不是当前版本。' +
1033
- 'policy 查 POLICY.md 的自主权契约表(表头 / 列数 / level / approval / reversible / 重复动作 / 审计落点);' +
1034
- 'issues 最多 50 条(total 是完整数,truncated 标记截断);缺文件归 contract,不在这里重复报。' +
1035
1235
  'similarTitles 是「改一两个字」的疑似重复(同目录、二元组相似度 ≥ 0.6):与全等重名分开,只报告。' +
1036
1236
  'indexHint=true 表示笔记(不含日记)已到 150 篇而根目录还没有 INDEX.md(只是提示,不生成静态索引)。' +
1037
1237
  '孤儿与无标签不含日记(按天写的日记天然如此,报出来只会淹没真问题)。' +
@@ -1069,9 +1269,8 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1069
1269
  tags: LINT_TAGS,
1070
1270
  template: LINT_TEMPLATE,
1071
1271
  contract: LINT_CONTRACT,
1072
- policy: LINT_POLICY,
1073
1272
  indexHint: { type: 'boolean' },
1074
- }, ['notebook', 'notes', 'truncated', 'staleDays', 'parseErrors', 'orphans', 'brokenLinks', 'stale', 'tagless', 'oneWayLinks', 'duplicateTitles', 'similarTitles', 'memoryLinks', 'incomplete', 'tags', 'template', 'contract', 'policy', 'indexHint']),
1273
+ }, ['notebook', 'notes', 'truncated', 'staleDays', 'parseErrors', 'orphans', 'brokenLinks', 'stale', 'tagless', 'oneWayLinks', 'duplicateTitles', 'similarTitles', 'memoryLinks', 'incomplete', 'tags', 'template', 'contract', 'indexHint']),
1075
1274
  },
1076
1275
  async run(args, env) {
1077
1276
  const cfg = configFor(env.workspace, env.sessionId);
@@ -1443,6 +1642,23 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1443
1642
  },
1444
1643
  }),
1445
1644
  ];
1645
+ // 别名工具跟着笔记本里的 [alias] 走:没有定义别名时这里就是空数组,内置工具数量不变。
1646
+ // 默认不注册(aliasTools=false):别名是 `$SHELL -c` 的任意命令,注册成工具等于把它交到模型手里,
1647
+ // 得由人显式打开;关着时连 config.toml 都不读。
1648
+ // 配置读不了 / 宿主工作区取不到都不能拖垮内置工具:别名只是附加能力。
1649
+ let aliases = [];
1650
+ try {
1651
+ const workspace = workspaceOf(undefined);
1652
+ const cfg = config(workspace);
1653
+ const taken = new Set(builtins.map((tool) => tool.name));
1654
+ if (cfg.aliasTools) {
1655
+ aliases = configuredAliases(cfg, workspace)
1656
+ .filter((alias) => !taken.has(`zk_${alias.name}`)) // 别名 search → zk_search 会和内置工具撞名
1657
+ .map((alias) => aliasTool(alias, workspaceOf));
1658
+ }
1659
+ }
1660
+ catch { /* 内置工具照常注册 */ }
1661
+ return [...builtins, ...aliases];
1446
1662
  }
1447
1663
  /** 注册全部工具,返回撤销函数(workspaceOf 由 app 注入:会话 cwd 优先) */
1448
1664
  export function registerZkTools(tools, workspaceOf) {
@@ -17,8 +17,8 @@
17
17
  * 首行 `<!-- zdiary-template: vN -->` 是版本标记:lint 据此报告「老库的 AGENTS.md 是旧版」,
18
18
  * 只报告不覆盖(模板允许用户改)。
19
19
  */
20
- /** 模板版本:改模板就 +1;lint 用它判断老库是否还在用旧契约(v2:去掉 inbox/;v3:截断改按日期;v4:去掉「宿主不会自动加载」一句;v5:MEMORY 条目补「先 zk_read 核对来源」) */
21
- export const TEMPLATE_VERSION = 5;
20
+ /** 模板版本:改模板就 +1;lint 用它判断老库是否还在用旧契约(v2:去掉 inbox/;v3:截断改按日期;v4:去掉「宿主不会自动加载」一句;v5:MEMORY 条目补「先 zk_read 核对来源」;v6:补状态层一句) */
21
+ export const TEMPLATE_VERSION = 6;
22
22
  /** 首行版本标记(实测 4 词);不许带日期 —— 带日期的写法实测 6 词,白花 2 词 */
23
23
  export const TEMPLATE_MARK = `<!-- zdiary-template: v${TEMPLATE_VERSION} -->`;
24
24
  /**
@@ -32,6 +32,7 @@ export const TEMPLATE_MARK = `<!-- zdiary-template: v${TEMPLATE_VERSION} -->`;
32
32
  export const TEMPLATE_SENTINELS = {
33
33
  4: { forbidden: ['DSH 不会自动加载', '从底部往前丢'] },
34
34
  5: { required: ['先 zk_read 核对来源'], forbidden: ['DSH 不会自动加载', '从底部往前丢'] },
35
+ 6: { required: ['先 zk_read 核对来源', 'zk_state'], forbidden: ['DSH 不会自动加载', '从底部往前丢'] },
35
36
  };
36
37
  export const AGENTS_TEMPLATE = `${TEMPLATE_MARK}
37
38
 
@@ -59,6 +60,10 @@ notes/{concepts,entities,patterns}/ 原子笔记 · archive/ 废弃(不删)
59
60
  每周:DREAMS.md 写「上次做梦:YYYY-MM-DD」;到期 zk_lint → zk_dream → 人裁决改 MEMORY。
60
61
  MEMORY.md 每条:结论(YYYY-MM-DD)[[来源路径]],先 zk_read 核对来源;退役写 - [superseded YYYY-MM-DD] 旧结论 → [[新结论]],行不删。
61
62
  新条目写顶部;超预算按日期丢最旧的一条。
63
+
64
+ ## 状态
65
+
66
+ 用 zk_state 记事件,不翻历史。
62
67
  `;
63
68
  /**
64
69
  * flat 结构用的模板:不出现 raw / inbox / archive / WORKFLOW.md 这些 flat 没有的路径。
@@ -78,6 +83,10 @@ export const AGENTS_TEMPLATE_FLAT = `${TEMPLATE_MARK}
78
83
 
79
84
  DREAMS.md 写「上次做梦:YYYY-MM-DD」;到期 zk_lint → zk_dream → 人裁决改 MEMORY。
80
85
  MEMORY.md 每条:结论(YYYY-MM-DD)[[来源路径]],先 zk_read 核对来源;退役写 - [superseded] 旧结论 → [[新结论]]。
86
+
87
+ ## 状态
88
+
89
+ 用 zk_state 记事件,不翻历史。
81
90
  `;
82
91
  /**
83
92
  * 根目录 WORKFLOW.md:只在「要动已有笔记」时才需要读,所以不注入、不计预算。