dsh-zdiary-kit 2.0.0 → 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.
- package/README.md +28 -8
- package/dist/app/plugin.js +38 -4
- package/dist/cli.js +156 -1
- package/dist/config/store.js +4 -0
- package/dist/features/readonly/feature.js +36 -5
- package/dist/features/settings/client.js +29 -3
- package/dist/features/settings/feature.js +41 -0
- package/dist/features/zk-tools/feature.js +196 -9
- package/dist/lib/agents-template.js +11 -2
- package/dist/lib/lint.js +5 -3
- package/dist/lib/memory.js +7 -17
- package/dist/lib/scene.js +244 -0
- package/dist/lib/state-log.js +395 -0
- package/dist/lib/state-rules.js +618 -0
- package/dist/lib/zk.js +7 -1
- package/docs/features/memory.md +20 -5
- package/docs/features/provisioning.md +6 -2
- package/docs/features/readonly.md +5 -2
- package/docs/features/settings.md +6 -3
- package/docs/features/zk-tools.md +23 -6
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* zk 工具(feature 的公共入口):
|
|
2
|
+
* zk 工具(feature 的公共入口):15 个内置工具 + `[alias]` 别名工具,全部经 lib/zk.ts。
|
|
3
3
|
*
|
|
4
4
|
* 设计要点:
|
|
5
5
|
* · 除 zk_context(只读 meta 文件,不依赖 zk)外,每个工具进来先 ensureNotebook —— 第一次调用就自动建好笔记本,用户不用先点设置页;
|
|
@@ -19,9 +19,13 @@ import { searchNotes, searchNotesDetailed, createNote, readNote, findNote, appen
|
|
|
19
19
|
import { configuredAliases, readAliases } from '../../lib/alias.js';
|
|
20
20
|
import { buildMemoryPayload, META_FILES } from '../../lib/memory.js';
|
|
21
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';
|
|
22
24
|
import { formatLintExtras, formatMemoryLinks, lintNotebook } from '../../lib/lint.js';
|
|
23
25
|
import { dreamNotebook, STALE_DAYS } from '../../lib/dream.js';
|
|
24
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(' ');
|
|
25
29
|
const objSchema = (properties, required) => ({
|
|
26
30
|
type: 'object',
|
|
27
31
|
properties,
|
|
@@ -188,7 +192,8 @@ const LINT_PARSE = objSchema({
|
|
|
188
192
|
},
|
|
189
193
|
}, ['total', 'items']);
|
|
190
194
|
function fail(err) {
|
|
191
|
-
|
|
195
|
+
// StateError 与 ZkError 同为「人话 + 下一步」:hint 必须一起交给模型,否则它只知道写错了、不知道怎么写
|
|
196
|
+
if (err instanceof ZkError || err instanceof StateError) {
|
|
192
197
|
throw new Error(err.hint ? `${err.message}(${err.hint})` : err.message);
|
|
193
198
|
}
|
|
194
199
|
throw err instanceof Error ? err : new Error(String(err));
|
|
@@ -974,9 +979,14 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
|
|
|
974
979
|
}, ['present', 'contentWords', 'words', 'noticeWords', 'budget', 'overBudget', 'overWords', 'files']),
|
|
975
980
|
scene: objSchema({
|
|
976
981
|
present: { type: 'boolean' },
|
|
977
|
-
|
|
982
|
+
presence: { type: 'string' },
|
|
983
|
+
events: { type: 'number' },
|
|
984
|
+
rulesVersion: { type: 'string' },
|
|
978
985
|
words: { type: 'number' },
|
|
979
|
-
|
|
986
|
+
emptyReason: { type: 'string' },
|
|
987
|
+
}, ['present', 'presence', 'events', 'rulesVersion', 'words', 'emptyReason']),
|
|
988
|
+
combinedWords: { type: 'number' },
|
|
989
|
+
combinedBudget: { type: 'number' },
|
|
980
990
|
notebook: { type: 'string' },
|
|
981
991
|
defaultNotebook: { type: 'string' },
|
|
982
992
|
pinned: { type: 'string' },
|
|
@@ -999,14 +1009,27 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
|
|
|
999
1009
|
retiredWords: { type: 'number' },
|
|
1000
1010
|
}, ['name', 'present', 'words', 'originalWords', 'retiredWords']),
|
|
1001
1011
|
},
|
|
1002
|
-
}, ['text', 'words', 'budget', 'ratio', 'truncatedWords', 'retiredWords', 'tocWords', 'totalWords', 'overheadWords', 'contract', 'scene', 'notebook', 'defaultNotebook', 'pinned', 'notebooks', 'files']),
|
|
1012
|
+
}, ['text', 'words', 'budget', 'ratio', 'truncatedWords', 'retiredWords', 'tocWords', 'totalWords', 'overheadWords', 'contract', 'scene', 'combinedWords', 'combinedBudget', 'notebook', 'defaultNotebook', 'pinned', 'notebooks', 'files']),
|
|
1003
1013
|
},
|
|
1004
1014
|
async run(_args, env) {
|
|
1005
1015
|
// 不 ensureNotebook:读记忆不该依赖 zk,笔记本不存在时就是空载荷
|
|
1006
1016
|
const cfg = configFor(env.workspace, env.sessionId);
|
|
1007
1017
|
const state = sessionState(env.workspace, env.sessionId);
|
|
1018
|
+
const payload = buildMemoryPayload(cfg);
|
|
1019
|
+
const scene = buildScene(cfg);
|
|
1008
1020
|
return {
|
|
1009
|
-
...
|
|
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,
|
|
1010
1033
|
notebook: state.active,
|
|
1011
1034
|
defaultNotebook: state.defaultName,
|
|
1012
1035
|
pinned: state.diverged ? state.pinned : '',
|
|
@@ -1026,14 +1049,178 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
|
|
|
1026
1049
|
? `笔记本「${current.name}」(${current.structure})→ ${current.path}` +
|
|
1027
1050
|
(others.length ? `\n另有:${others.map((n) => `${n.name}(${n.structure})`).join('、')} —— zk_use 切换本会话` : '')
|
|
1028
1051
|
: `笔记本「${v.notebook}」`;
|
|
1029
|
-
if (!v.text)
|
|
1030
|
-
|
|
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
|
+
}
|
|
1031
1062
|
const contract = v.contract?.present
|
|
1032
1063
|
? `\n\n契约:正文(含标题)${v.contract.contentWords}/${v.contract.budget} 词` +
|
|
1033
1064
|
`(${v.contract.files.filter((f) => f.present).map((f) => `${f.name} ${f.words} 词`).join(' · ')})` +
|
|
1034
1065
|
(v.contract.overBudget ? `,超 ${v.contract.overWords} 词(契约不截断)` : '')
|
|
1035
1066
|
: '\n\n契约:未启用(根目录没有 PERSONA.md)';
|
|
1036
|
-
|
|
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'));
|
|
1037
1224
|
},
|
|
1038
1225
|
}),
|
|
1039
1226
|
t({
|
|
@@ -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 =
|
|
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:只在「要动已有笔记」时才需要读,所以不注入、不计预算。
|
package/dist/lib/lint.js
CHANGED
|
@@ -487,13 +487,15 @@ function sentinelIssue(body, rule) {
|
|
|
487
487
|
if (!rule)
|
|
488
488
|
return null;
|
|
489
489
|
const quote = (texts) => texts.map((text) => `「${showSentinel(text)}」`).join('、');
|
|
490
|
+
// 两件事一起报:只报「缺了什么」会让「还留着旧句」被藏起来,人改完一处又撞一次
|
|
491
|
+
const parts = [];
|
|
490
492
|
const missing = (rule.required ?? []).filter((text) => !body.includes(text));
|
|
491
493
|
if (missing.length > 0)
|
|
492
|
-
|
|
494
|
+
parts.push(`缺少当前版本才有的内容:${quote(missing)}`);
|
|
493
495
|
const leftover = (rule.forbidden ?? []).filter((text) => body.includes(text));
|
|
494
496
|
if (leftover.length > 0)
|
|
495
|
-
|
|
496
|
-
return null;
|
|
497
|
+
parts.push(`仍含旧版已移除的内容:${quote(leftover)}`);
|
|
498
|
+
return parts.length > 0 ? parts.join(';') : null;
|
|
497
499
|
}
|
|
498
500
|
/**
|
|
499
501
|
* 契约体检(M1):缺文件 = 未启用(不算错,但要让 zk_lint 可见);
|
package/dist/lib/memory.js
CHANGED
|
@@ -251,7 +251,7 @@ function escapeFrame(text) {
|
|
|
251
251
|
// 文件内容不许提前闭合我们自己的 <system-reminder> 框
|
|
252
252
|
return text.replaceAll('</system-reminder>', '<\\/system-reminder>');
|
|
253
253
|
}
|
|
254
|
-
/**
|
|
254
|
+
/** 载荷框:定义成常量,最终拼装与各处词数统计才能共用同一份文字(否则数出来的词对不上) */
|
|
255
255
|
const FRAME_HEAD = '<system-reminder>\n' +
|
|
256
256
|
'以下内容由 zdiary 从知识库根目录读出,是长期约定与记忆;工作约定放在 AGENTS.md,不要写进 MEMORY.md。\n\n';
|
|
257
257
|
const FRAME_TAIL = '\n</system-reminder>';
|
|
@@ -296,8 +296,9 @@ function payloadKeyOf(cfg) {
|
|
|
296
296
|
// 做梦提醒按本地日历天变化(「3 天前」→「4 天前」):文件没动也得跟着日期失效
|
|
297
297
|
const now = new Date();
|
|
298
298
|
const day = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}`;
|
|
299
|
-
//
|
|
300
|
-
|
|
299
|
+
// 影响这个载荷的预算都要进键:改配置不重新写入任何文件,漏一个就会拿到旧预算的载荷。
|
|
300
|
+
// totalPromptBudgetWords 不进:它是 memory + scene 的合并总账,改它不改变 payload。
|
|
301
|
+
return `${cfg.notebook}|${cfg.memoryBudgetWords}|${cfg.contractBudgetWords}|${day}|${stamps}`;
|
|
301
302
|
}
|
|
302
303
|
/**
|
|
303
304
|
* 生成注入载荷。纯读文件,不调 zk、不建目录:笔记本不存在时返回空载荷。
|
|
@@ -455,7 +456,8 @@ function computePayload(cfg) {
|
|
|
455
456
|
notice;
|
|
456
457
|
}
|
|
457
458
|
// ── 契约段(角色):永远注入、在记忆段之前、不参与截断 ────
|
|
458
|
-
//
|
|
459
|
+
// 超预算只告警不静默丢。合并预算(记忆载荷 + 场景)不在这里量:
|
|
460
|
+
// memory 看不到场景,硬算会得到一个少了一截的「总 prompt」—— 那是错的。
|
|
459
461
|
// 没有契约文件 = 未启用:不多一个词,0.9 的老库逐字节一致。
|
|
460
462
|
const contractBudget = cfg.contractBudgetWords;
|
|
461
463
|
const contracts = readContracts(cfg);
|
|
@@ -468,16 +470,6 @@ function computePayload(cfg) {
|
|
|
468
470
|
if (contractOver) {
|
|
469
471
|
contractNotes.push(`契约预算 ${contractBudget} 词:已用 ${contractContentWords},超出 ${contractContentWords - contractBudget} 词(契约不截断)`);
|
|
470
472
|
}
|
|
471
|
-
if (contractBodies.length > 0) {
|
|
472
|
-
// 总 prompt 用「还没加契约告警」的完整载荷来量:框 / 做梦提醒 / 记忆 notice 都要算,
|
|
473
|
-
// 但本条告警自己不能算进自己报的数里(否则又是一个自指的口径)。
|
|
474
|
-
const provisional = frameText((contractBodyText ? contractBodyText + '\n\n' : '') + memoryInner);
|
|
475
|
-
const promptTotal = countWords(provisional);
|
|
476
|
-
if (promptTotal > cfg.totalPromptBudgetWords) {
|
|
477
|
-
const overhead = Math.max(0, promptTotal - contractContentWords - finalWords);
|
|
478
|
-
contractNotes.push(`总 prompt 预算 ${cfg.totalPromptBudgetWords} 词:契约 ${contractContentWords} + 记忆 ${finalWords} + 框与提示 ${overhead} = ${promptTotal},超出 ${promptTotal - cfg.totalPromptBudgetWords}`);
|
|
479
|
-
}
|
|
480
|
-
}
|
|
481
473
|
const contractText = contractBodyText + (contractNotes.length > 0 ? `\n\n(${contractNotes.join(';')})` : '');
|
|
482
474
|
const contractWords = countWords(contractText);
|
|
483
475
|
let text = '';
|
|
@@ -486,7 +478,6 @@ function computePayload(cfg) {
|
|
|
486
478
|
}
|
|
487
479
|
// 模型真正收到的总量与开销:口径与 memoryUsage / D9 的载荷预览同源
|
|
488
480
|
const totalWords = countWords(text);
|
|
489
|
-
const sceneWords = 0; // M1 只落形状:M3 起由 STATE 填
|
|
490
481
|
return {
|
|
491
482
|
text,
|
|
492
483
|
words: finalWords,
|
|
@@ -513,9 +504,8 @@ function computePayload(cfg) {
|
|
|
513
504
|
overWords: Math.max(0, contractContentWords - contractBudget),
|
|
514
505
|
files: contracts.map((f) => ({ name: f.name, present: f.body.length > 0, words: countWords(f.body) })),
|
|
515
506
|
},
|
|
516
|
-
scene: { present: false, expired: false, words: sceneWords },
|
|
517
507
|
totalWords,
|
|
518
|
-
overheadWords: Math.max(0, totalWords - contractContentWords - finalWords
|
|
508
|
+
overheadWords: Math.max(0, totalWords - contractContentWords - finalWords),
|
|
519
509
|
};
|
|
520
510
|
}
|
|
521
511
|
/**
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 场景投影:把事件日志 + 规则算成一行「此刻」文本,按 `sceneBudgetWords` 裁。
|
|
3
|
+
*
|
|
4
|
+
* 设计要点(D7):
|
|
5
|
+
* · 场景**不进** memory payload:独立投影、独立缓存、独立预算;合并总量只在
|
|
6
|
+
* `zk_context` / `doctor` / 记忆页 / 设置页算(combinedWords),超了只对人告警;
|
|
7
|
+
* · 规则算得出但展示层只认固定几个变量(energy / mood / satiety / location / goal),
|
|
8
|
+
* 其余变量不注入 —— 别把规则文件当 prompt 模板;
|
|
9
|
+
* · **没有 logs = 不注入**;只有窗口外事件时仍注入长尾(`hoursSince` 走 tombstone);
|
|
10
|
+
* · 规则编译 / 求值失败 → 整份回退内置默认并记 `rulesError`;连默认都失败才返回空串。
|
|
11
|
+
* 状态层坏掉不能把整个系统提示拖下水,也不能让场景无声消失。
|
|
12
|
+
*/
|
|
13
|
+
import fs from 'node:fs';
|
|
14
|
+
import { fileStamp } from './file-stamp.js';
|
|
15
|
+
import { countWords } from './memory.js';
|
|
16
|
+
import { eventsPathOf, humanAge, readStateLog, rulesPathOf } from './state-log.js';
|
|
17
|
+
import { DEFAULT_RULES, RulesCompileError, compileDefaultRules, compileRules } from './state-rules.js';
|
|
18
|
+
/** 读 `.state/rules`;缺文件 = 内置默认,解析失败 = 回退默认。两者都不抛。 */
|
|
19
|
+
export function loadRules(cfg) {
|
|
20
|
+
const file = rulesPathOf(cfg);
|
|
21
|
+
let source = '';
|
|
22
|
+
try {
|
|
23
|
+
source = fs.readFileSync(file, 'utf8');
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
const defaults = compileDefaultRules();
|
|
27
|
+
return { rules: defaults, source: 'default', label: 'default' };
|
|
28
|
+
}
|
|
29
|
+
try {
|
|
30
|
+
const compiled = compileRules(source);
|
|
31
|
+
if (!compiled) {
|
|
32
|
+
const defaults = compileDefaultRules();
|
|
33
|
+
return { rules: defaults, source: 'default', label: 'default' };
|
|
34
|
+
}
|
|
35
|
+
return { rules: compiled, source: 'file', label: `v${compiled.version}` };
|
|
36
|
+
}
|
|
37
|
+
catch (err) {
|
|
38
|
+
const message = err instanceof RulesCompileError
|
|
39
|
+
? err.errors.map((e) => `第 ${e.line} 行第 ${e.col} 列:${e.message}`).join(';')
|
|
40
|
+
: err instanceof Error ? err.message : String(err);
|
|
41
|
+
return { rules: compileDefaultRules(), source: 'fallback', label: 'default(fallback)', error: message };
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const SCENE_PREFIX = '当下:';
|
|
45
|
+
const SEP = ' · ';
|
|
46
|
+
/** 时间点 → 人话(脚注用;只接受毫秒) */
|
|
47
|
+
function ago(now, atMs) {
|
|
48
|
+
return humanAge((now - atMs) / 3600_000);
|
|
49
|
+
}
|
|
50
|
+
function presenceOf(log, now, staleHours) {
|
|
51
|
+
const left = log.lastSeen.get('user_left');
|
|
52
|
+
const returned = log.lastSeen.get('user_returned');
|
|
53
|
+
// ① 两个事件都没有 → 未知:不能因为「没记录」就默认在场,否则只记 ate 的日志永远显示在场
|
|
54
|
+
if (!left && !returned)
|
|
55
|
+
return { presence: 'unknown', note: '' };
|
|
56
|
+
const latest = left && returned ? (left.atMs >= returned.atMs ? left : returned) : (left ?? returned);
|
|
57
|
+
const latestWasLeft = !returned || (!!left && left.atMs >= returned.atMs);
|
|
58
|
+
// ② 最新一条太旧 → 未知(而不是把 40 天前的「离开」当成仍不在)
|
|
59
|
+
if (now - latest.atMs > staleHours * 3600_000) {
|
|
60
|
+
return { presence: 'unknown', note: `用户状态未知(最后${latestWasLeft ? '离开' : '回来'} · ${ago(now, latest.atMs)})` };
|
|
61
|
+
}
|
|
62
|
+
// ③ 有 left 无 returned(或 left 更晚)→ 不在
|
|
63
|
+
if (left && (!returned || left.atMs > returned.atMs)) {
|
|
64
|
+
return { presence: 'absent', note: `用户不在(离开 · ${ago(now, left.atMs)})` };
|
|
65
|
+
}
|
|
66
|
+
// ④ 否则在场
|
|
67
|
+
return { presence: 'present', note: returned ? `用户在场(回来 · ${ago(now, returned.atMs)})` : '' };
|
|
68
|
+
}
|
|
69
|
+
/** 规则给 null 时补「最后 X · N 天前」:值来自 last-seen,但**由投影层**给,渲染层不回读日志 */
|
|
70
|
+
function lastNote(log, now, event, key, label) {
|
|
71
|
+
const last = log.lastSeen.get(event);
|
|
72
|
+
if (!last || !(key in last.params))
|
|
73
|
+
return `${label}未知`;
|
|
74
|
+
const value = String(last.params[key] ?? '').trim();
|
|
75
|
+
if (!value)
|
|
76
|
+
return `${label}未知`;
|
|
77
|
+
return `${label}未知(最后 ${value} · ${ago(now, last.atMs)})`;
|
|
78
|
+
}
|
|
79
|
+
const numText = (value) => (typeof value === 'number' ? String(Math.round(value)) : null);
|
|
80
|
+
const strText = (value) => (typeof value === 'string' && value.trim() ? value.trim() : null);
|
|
81
|
+
/** 纯投影:不读配置、不读文件,只吃 logs + rules + now */
|
|
82
|
+
export function projectScene(log, rules, now, opts) {
|
|
83
|
+
const empty = {
|
|
84
|
+
present: false, presence: 'unknown', events: log.events.length, words: 0, text: '',
|
|
85
|
+
values: {}, dropped: [], emptyReason: 'no-log',
|
|
86
|
+
};
|
|
87
|
+
// lastSeen 为空 = 这一刻之前没有任何事件(重放到第一条事件之前也走这里),不是「规则没算出值」
|
|
88
|
+
if (!log.exists || log.total === 0 || log.lastSeen.size === 0)
|
|
89
|
+
return empty;
|
|
90
|
+
const ctx = {
|
|
91
|
+
now,
|
|
92
|
+
lastSeen: log.lastSeen,
|
|
93
|
+
events: log.events,
|
|
94
|
+
sceneWindowDays: opts.sceneWindowDays,
|
|
95
|
+
staleHours: opts.staleHours,
|
|
96
|
+
};
|
|
97
|
+
const values = rules.evaluate(ctx);
|
|
98
|
+
const presence = presenceOf(log, now, opts.staleHours);
|
|
99
|
+
// 展示顺序 = 裁剪优先级(后面的先被丢):energy / mood 先留,地点 / 目标后留
|
|
100
|
+
const parts = [];
|
|
101
|
+
const energy = numText(values.energy ?? null);
|
|
102
|
+
if (energy)
|
|
103
|
+
parts.push(`energy ${energy}`);
|
|
104
|
+
const mood = strText(values.mood ?? null);
|
|
105
|
+
if (mood)
|
|
106
|
+
parts.push(`mood ${mood}`);
|
|
107
|
+
const satiety = numText(values.satiety ?? null);
|
|
108
|
+
if (satiety)
|
|
109
|
+
parts.push(`satiety ${satiety}`);
|
|
110
|
+
if (presence.note && presence.presence !== 'present')
|
|
111
|
+
parts.push(presence.note);
|
|
112
|
+
const woke = log.lastSeen.get('woke');
|
|
113
|
+
if (woke && (now - woke.atMs) / 3600_000 > opts.staleHours)
|
|
114
|
+
parts.push(`最近醒来 ${ago(now, woke.atMs)}`);
|
|
115
|
+
const location = strText(values.location ?? null);
|
|
116
|
+
if (location)
|
|
117
|
+
parts.push(`地点 ${location}`);
|
|
118
|
+
else if (log.lastSeen.has('at'))
|
|
119
|
+
parts.push(lastNote(log, now, 'at', 'place', '地点'));
|
|
120
|
+
const goal = strText(values.goal ?? null);
|
|
121
|
+
if (goal)
|
|
122
|
+
parts.push(`目标 ${goal}`);
|
|
123
|
+
else if (log.lastSeen.has('set_goal'))
|
|
124
|
+
parts.push(lastNote(log, now, 'set_goal', 'text', '目标'));
|
|
125
|
+
if (presence.presence === 'present' && presence.note)
|
|
126
|
+
parts.push(presence.note);
|
|
127
|
+
// 预算:从尾部丢,直到放得下;一个都放不下就返回空串(不注入半行)
|
|
128
|
+
const dropped = [];
|
|
129
|
+
let keep = parts.slice();
|
|
130
|
+
const textOf = (list) => list.length ? SCENE_PREFIX + list.join(SEP) : '';
|
|
131
|
+
while (keep.length > 0 && countWords(textOf(keep)) > opts.budgetWords)
|
|
132
|
+
dropped.unshift(keep.pop());
|
|
133
|
+
const text = textOf(keep);
|
|
134
|
+
return {
|
|
135
|
+
present: text.length > 0,
|
|
136
|
+
presence: presence.presence,
|
|
137
|
+
events: log.events.length,
|
|
138
|
+
words: countWords(text),
|
|
139
|
+
text,
|
|
140
|
+
values,
|
|
141
|
+
dropped,
|
|
142
|
+
emptyReason: text.length > 0 ? '' : parts.length > 0 ? 'budget' : 'rules',
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
/** 缓存:日志 / 规则文件变了才重算;没有变化时连续 step 只付一次读盘 */
|
|
146
|
+
const SCENE_CACHE_MAX = 8;
|
|
147
|
+
const cache = new Map();
|
|
148
|
+
function cacheKey(cfg, now) {
|
|
149
|
+
const minute = Math.floor(now / 60_000);
|
|
150
|
+
return [
|
|
151
|
+
cfg.notebook,
|
|
152
|
+
fileStamp(eventsPathOf(cfg)),
|
|
153
|
+
fileStamp(rulesPathOf(cfg)),
|
|
154
|
+
cfg.sceneBudgetWords,
|
|
155
|
+
cfg.sceneWindowDays,
|
|
156
|
+
cfg.staleHours,
|
|
157
|
+
minute,
|
|
158
|
+
].join('|');
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* 读盘 + 投影 + 缓存。异常一律返回空场景(不抛):状态层是可选的,
|
|
162
|
+
* 坏掉时整个系统提示必须照常装配。
|
|
163
|
+
*
|
|
164
|
+
* 求值期错误(除零 / count 越界 / null 进算术)按 D7 整份回退内置默认,
|
|
165
|
+
* 而不是让场景整段消失 —— 「规则算错了」和「没有日志」不是一回事。
|
|
166
|
+
*/
|
|
167
|
+
export function buildScene(cfg, opts = {}) {
|
|
168
|
+
const now = opts.now ?? Date.now();
|
|
169
|
+
const key = cacheKey(cfg, now);
|
|
170
|
+
const hit = cache.get(key);
|
|
171
|
+
if (hit)
|
|
172
|
+
return hit;
|
|
173
|
+
const empty = {
|
|
174
|
+
present: false, presence: 'unknown', events: 0, rulesVersion: 'default', words: 0, text: '',
|
|
175
|
+
values: {}, dropped: [], emptyReason: 'no-log',
|
|
176
|
+
};
|
|
177
|
+
let result = empty;
|
|
178
|
+
try {
|
|
179
|
+
const log = readStateLog(cfg, { windowDays: cfg.sceneWindowDays, now });
|
|
180
|
+
if (log.readError) {
|
|
181
|
+
// 文件在、但读不出来:这不是「未启用」,空场景必须带上原因
|
|
182
|
+
result = { ...empty, rulesError: log.readError, emptyReason: 'error' };
|
|
183
|
+
}
|
|
184
|
+
else if (!log.exists || log.total === 0) {
|
|
185
|
+
result = empty;
|
|
186
|
+
}
|
|
187
|
+
else {
|
|
188
|
+
const optsFor = { staleHours: cfg.staleHours, sceneWindowDays: cfg.sceneWindowDays, budgetWords: cfg.sceneBudgetWords };
|
|
189
|
+
const loaded = loadRules(cfg);
|
|
190
|
+
try {
|
|
191
|
+
const projected = projectScene(log, loaded.rules, now, optsFor);
|
|
192
|
+
result = { ...projected, rulesVersion: loaded.label, ...(loaded.error ? { rulesError: loaded.error } : {}) };
|
|
193
|
+
}
|
|
194
|
+
catch (err) {
|
|
195
|
+
// 求值失败:整份规则拒绝,换内置默认重算(编译失败已在 loadRules 里回退过)
|
|
196
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
197
|
+
const projected = projectScene(log, compileDefaultRules(), now, optsFor);
|
|
198
|
+
result = { ...projected, rulesVersion: 'default(fallback)', rulesError: message };
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
catch (err) {
|
|
203
|
+
result = {
|
|
204
|
+
...empty,
|
|
205
|
+
rulesVersion: 'default(fallback)',
|
|
206
|
+
rulesError: err instanceof Error ? err.message : String(err),
|
|
207
|
+
emptyReason: 'error',
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
if (cache.size >= SCENE_CACHE_MAX) {
|
|
211
|
+
const oldest = cache.keys().next().value;
|
|
212
|
+
if (oldest !== undefined)
|
|
213
|
+
cache.delete(oldest);
|
|
214
|
+
}
|
|
215
|
+
cache.set(key, result);
|
|
216
|
+
return result;
|
|
217
|
+
}
|
|
218
|
+
/** 合并总账:记忆载荷(含框与提示)+ 场景行。别把它叫「总 prompt」——宿主自己的系统提示不在里面。 */
|
|
219
|
+
export function combinedWords(memoryTotalWords, scene) {
|
|
220
|
+
return memoryTotalWords + scene.words;
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* 合并预算的超限提示;没超返回空串。
|
|
224
|
+
*
|
|
225
|
+
* 只给人看(zk_context 的回复文本 / doctor / 记忆页 / 设置页),**不写进系统提示**:
|
|
226
|
+
* 那句话每轮都要花词,而模型并不需要这个数字 —— 预算诊断是人的工作面(D4)。
|
|
227
|
+
*/
|
|
228
|
+
export function combinedBudgetNote(memoryTotalWords, scene, budget) {
|
|
229
|
+
const total = combinedWords(memoryTotalWords, scene);
|
|
230
|
+
if (!(budget > 0) || total <= budget)
|
|
231
|
+
return '';
|
|
232
|
+
return `合并预算 ${budget} 词:记忆载荷 ${memoryTotalWords} + 场景 ${scene.words} = ${total},超出 ${total - budget}`;
|
|
233
|
+
}
|
|
234
|
+
/** 只读规则文本的原始内容(人用 CLI / 记忆页展示;模型侧不给入口) */
|
|
235
|
+
export function readRulesText(cfg) {
|
|
236
|
+
try {
|
|
237
|
+
return fs.readFileSync(rulesPathOf(cfg), 'utf8');
|
|
238
|
+
}
|
|
239
|
+
catch {
|
|
240
|
+
return '';
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
/** 内置默认规则的原文(缺失时展示「将用这套」) */
|
|
244
|
+
export const DEFAULT_RULES_TEXT = DEFAULT_RULES;
|