dsh-zdiary-kit 2.3.0 → 3.0.1

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,662 +0,0 @@
1
- /**
2
- * `.state/rules` 的规则 DSL(包 1:严格)。
3
- *
4
- * 规则是**数据**,不是代码:一行一条 `变量 = 表达式`,自上而下求值,只能引用前面已定义的变量。
5
- * 宿主只提供白名单函数,不做 eval —— 人在文件里写公式,插件不给模型写规则的入口(D7)。
6
- * 注意这只是「插件不给入口」:宿主自带的写文件工具仍能改,规则的可信度靠 git diff 审。
7
- *
8
- * 为什么严格:
9
- * · 拼错变量名必须报错,不能静默当字符串 —— 否则一条 `energi = ...` 会让整段场景消失,
10
- * 而人只会以为「状态没生效」;
11
- * · 任何解析 / 类型 / 求值错误 = **整份规则拒绝**,回退内置默认并告警;
12
- * 半套规则比没有规则更难排查。
13
- *
14
- * 两套语法别混:事件日志里参数值可以是裸词(`at place=书房`),规则里字符串**必须加引号**
15
- * (`if(energy < 20, "力竭", "正常")`)——裸的中文在表达式里会被当成未定义变量。
16
- *
17
- * 版本号:`version` 是**规则内容**版本(只用于审计),与日志首行的 `# zdiary-state v1` 无关。
18
- */
19
- export class RulesCompileError extends Error {
20
- errors;
21
- constructor(errors) {
22
- super(errors[0] ? formatRuleError(errors[0]) : '规则不合法');
23
- this.name = 'RulesCompileError';
24
- this.errors = errors;
25
- }
26
- }
27
- export function formatRuleError(error) {
28
- return `规则第 ${error.line} 行第 ${error.col} 列:${error.message}`;
29
- }
30
- const VAR_RE = /^[a-z][a-z0-9_]{0,15}$/;
31
- const EVENT_RE = /^[a-z][a-z0-9_]{0,31}$/;
32
- const KEY_RE = /^[a-z][a-z0-9_]{0,15}$/;
33
- const RESERVED = new Set(['version', 'sceneWindowDays', 'staleHours']);
34
- function lex(src, line) {
35
- const toks = [];
36
- let i = 0;
37
- while (i < src.length) {
38
- const ch = src[i];
39
- if (/\s/.test(ch)) {
40
- i++;
41
- continue;
42
- }
43
- const col = i + 1;
44
- if (ch === '"') {
45
- let j = i + 1;
46
- let buf = '';
47
- let closed = false;
48
- while (j < src.length) {
49
- const c = src[j];
50
- if (c === '\\') {
51
- const next = src[j + 1];
52
- if (next !== '"' && next !== '\\')
53
- throw new RulesCompileError([{ message: '字符串里的转义只认 \\" 和 \\\\', line, col: j + 1 }]);
54
- buf += next;
55
- j += 2;
56
- continue;
57
- }
58
- if (c === '"') {
59
- j++;
60
- closed = true;
61
- break;
62
- }
63
- buf += c;
64
- j++;
65
- }
66
- if (!closed)
67
- throw new RulesCompileError([{ message: '字符串没有闭合', line, col }]);
68
- toks.push({ t: 'str', v: buf, col });
69
- i = j;
70
- continue;
71
- }
72
- if (/[0-9]/.test(ch)) {
73
- let j = i;
74
- while (j < src.length && /[0-9]/.test(src[j]))
75
- j++;
76
- if (src[j] === '.') {
77
- j++;
78
- if (!/[0-9]/.test(src[j] ?? ''))
79
- throw new RulesCompileError([{ message: '小数点后面缺数字', line, col }]);
80
- while (j < src.length && /[0-9]/.test(src[j]))
81
- j++;
82
- }
83
- toks.push({ t: 'num', v: src.slice(i, j), col });
84
- i = j;
85
- continue;
86
- }
87
- if (/[A-Za-z_]/.test(ch)) {
88
- let j = i;
89
- while (j < src.length && /[A-Za-z0-9_]/.test(src[j]))
90
- j++;
91
- toks.push({ t: 'id', v: src.slice(i, j), col });
92
- i = j;
93
- continue;
94
- }
95
- const two = src.slice(i, i + 2);
96
- if (two === '==' || two === '!=' || two === '<=' || two === '>=') {
97
- toks.push({ t: 'op', v: two, col });
98
- i += 2;
99
- continue;
100
- }
101
- if ('+-*/'.includes(ch)) {
102
- toks.push({ t: 'op', v: ch, col });
103
- i++;
104
- continue;
105
- }
106
- if (ch === '<' || ch === '>') {
107
- toks.push({ t: 'op', v: ch, col });
108
- i++;
109
- continue;
110
- }
111
- if (ch === '(' || ch === ')' || ch === ',') {
112
- toks.push({ t: ch, v: ch, col });
113
- i++;
114
- continue;
115
- }
116
- throw new RulesCompileError([{ message: `不认识的字符:${ch}`, line, col }]);
117
- }
118
- return toks;
119
- }
120
- class Parser {
121
- index = 0;
122
- toks;
123
- line;
124
- constructor(toks, line) {
125
- this.toks = toks;
126
- this.line = line;
127
- }
128
- peek() { return this.toks[this.index]; }
129
- next() { return this.toks[this.index++]; }
130
- expect(type, value) {
131
- const tok = this.next();
132
- if (!tok || tok.t !== type || (value !== undefined && tok.v !== value)) {
133
- throw new RulesCompileError([{ message: `这里应该是 ${value ?? type}`, line: this.line, col: tok?.col ?? this.toks.length }]);
134
- }
135
- return tok;
136
- }
137
- parseAll() {
138
- const node = this.parseExpr();
139
- const rest = this.peek();
140
- if (rest)
141
- throw new RulesCompileError([{ message: `多余的字符:${rest.v}`, line: this.line, col: rest.col }]);
142
- return node;
143
- }
144
- parseExpr() {
145
- const left = this.parseAdd();
146
- const tok = this.peek();
147
- if (tok && tok.t === 'op' && ['<', '<=', '>', '>=', '==', '!='].includes(tok.v)) {
148
- this.next();
149
- const right = this.parseAdd();
150
- const after = this.peek();
151
- if (after && after.t === 'op' && ['<', '<=', '>', '>=', '==', '!='].includes(after.v)) {
152
- throw new RulesCompileError([{ message: '比较不能连写,拆成两个变量', line: this.line, col: after.col }]);
153
- }
154
- return { k: 'bin', op: tok.v, left, right, pos: { line: this.line, col: tok.col } };
155
- }
156
- return left;
157
- }
158
- parseAdd() {
159
- let node = this.parseMul();
160
- for (;;) {
161
- const tok = this.peek();
162
- if (!tok || tok.t !== 'op' || (tok.v !== '+' && tok.v !== '-'))
163
- return node;
164
- this.next();
165
- node = { k: 'bin', op: tok.v, left: node, right: this.parseMul(), pos: { line: this.line, col: tok.col } };
166
- }
167
- }
168
- parseMul() {
169
- let node = this.parseUnary();
170
- for (;;) {
171
- const tok = this.peek();
172
- if (!tok || tok.t !== 'op' || (tok.v !== '*' && tok.v !== '/'))
173
- return node;
174
- this.next();
175
- node = { k: 'bin', op: tok.v, left: node, right: this.parseUnary(), pos: { line: this.line, col: tok.col } };
176
- }
177
- }
178
- parseUnary() {
179
- const tok = this.peek();
180
- if (tok && tok.t === 'op' && tok.v === '-') {
181
- this.next();
182
- return { k: 'un', op: '-', expr: this.parseUnary(), pos: { line: this.line, col: tok.col } };
183
- }
184
- return this.parsePrimary();
185
- }
186
- parsePrimary() {
187
- const tok = this.next();
188
- if (!tok)
189
- throw new RulesCompileError([{ message: '表达式不完整', line: this.line, col: this.toks.length }]);
190
- if (tok.t === 'num')
191
- return { k: 'num', v: Number(tok.v) };
192
- if (tok.t === 'str')
193
- return { k: 'str', v: tok.v };
194
- if (tok.t === '(') {
195
- const inner = this.parseExpr();
196
- this.expect(')');
197
- return inner;
198
- }
199
- if (tok.t === 'id') {
200
- if (tok.v === 'null')
201
- return { k: 'null' };
202
- if (this.peek()?.t === '(') {
203
- this.next();
204
- const args = [];
205
- if (this.peek()?.t !== ')') {
206
- for (;;) {
207
- args.push(this.parseExpr());
208
- if (this.peek()?.t === ',') {
209
- this.next();
210
- continue;
211
- }
212
- break;
213
- }
214
- }
215
- this.expect(')');
216
- return { k: 'call', name: tok.v, args, pos: { line: this.line, col: tok.col } };
217
- }
218
- return { k: 'var', name: tok.v, pos: { line: this.line, col: tok.col } };
219
- }
220
- throw new RulesCompileError([{ message: `这里不该出现 ${tok.v}`, line: this.line, col: tok.col }]);
221
- }
222
- }
223
- /** 在顶层找赋值用的单个 `=`:引号里的不算,`==` `!=` `<=` `>=` 也不算 */
224
- function splitAssignment(text, line) {
225
- let inString = false;
226
- let escape = false;
227
- let at = -1;
228
- for (let i = 0; i < text.length; i++) {
229
- const ch = text[i];
230
- if (inString) {
231
- if (escape) {
232
- escape = false;
233
- continue;
234
- }
235
- if (ch === '\\') {
236
- escape = true;
237
- continue;
238
- }
239
- if (ch === '"')
240
- inString = false;
241
- continue;
242
- }
243
- if (ch === '"') {
244
- inString = true;
245
- continue;
246
- }
247
- if (ch !== '=')
248
- continue;
249
- const prev = text[i - 1] ?? '';
250
- const next = text[i + 1] ?? '';
251
- if (next === '=' || prev === '=' || '<>!'.includes(prev))
252
- continue;
253
- if (at >= 0)
254
- throw new RulesCompileError([{ message: '一行里只能有一个赋值 =', line, col: i + 1 }]);
255
- at = i;
256
- }
257
- if (at < 0)
258
- throw new RulesCompileError([{ message: '缺赋值 =(形如 energy = clamp(...))', line, col: 1 }]);
259
- return { left: text.slice(0, at).trim(), right: text.slice(at + 1).trim() };
260
- }
261
- const FUNCTION_ARITY = {
262
- clamp: [3, 3],
263
- min: [2, Number.POSITIVE_INFINITY],
264
- max: [2, Number.POSITIVE_INFINITY],
265
- abs: [1, 1],
266
- if: [3, 3],
267
- hoursSince: [1, 1],
268
- count: [1, 2],
269
- last: [2, 2],
270
- num: [1, 1],
271
- coalesce: [1, Number.POSITIVE_INFINITY],
272
- isNull: [1, 1],
273
- };
274
- /** 只读事件 / 参数的函数:第一个参数按裸词读,不当变量解析 */
275
- const EVENT_ARG_FUNCS = new Set(['hoursSince', 'count', 'last']);
276
- function checkEventName(node, line, what) {
277
- if (node.k !== 'var')
278
- throw new RulesCompileError([{ message: `${what}必须是裸事件名`, line, col: ('pos' in node ? node.pos.col : 1) }]);
279
- if (!EVENT_RE.test(node.name))
280
- throw new RulesCompileError([{ message: `事件名不合法:${node.name}`, line, col: node.pos.col }]);
281
- }
282
- function checkParamKey(node, line) {
283
- if (node.k !== 'var')
284
- throw new RulesCompileError([{ message: 'last 的第二个参数必须是裸参数名', line, col: ('pos' in node ? node.pos.col : 1) }]);
285
- if (!KEY_RE.test(node.name))
286
- throw new RulesCompileError([{ message: `参数名不合法:${node.name}`, line, col: node.pos.col }]);
287
- }
288
- function infer(node, env, line) {
289
- switch (node.k) {
290
- case 'num': return 'number';
291
- case 'str': return 'string';
292
- case 'null': return 'null';
293
- case 'un': {
294
- const t = infer(node.expr, env, line);
295
- if (t !== 'number')
296
- throw new RulesCompileError([{ message: `一元 - 只能用在数字上(这里是 ${t})`, line, col: node.pos.col }]);
297
- return 'number';
298
- }
299
- case 'bin': {
300
- const left = infer(node.left, env, line);
301
- const right = infer(node.right, env, line);
302
- const comparison = ['<', '<=', '>', '>=', '==', '!='].includes(node.op);
303
- for (const t of [left, right]) {
304
- if (t !== 'number') {
305
- throw new RulesCompileError([{
306
- message: `${node.op} 只比较数字(这里是 ${t})${t === 'string' ? ':字符串要加引号但不参与运算' : ''}`,
307
- line,
308
- col: node.pos.col,
309
- }]);
310
- }
311
- }
312
- return comparison ? 'boolean' : 'number';
313
- }
314
- case 'var': {
315
- if (node.name === 'sceneWindowDays' || node.name === 'staleHours')
316
- return 'number';
317
- const t = env.get(node.name);
318
- if (!t)
319
- throw new RulesCompileError([{ message: `未定义变量:${node.name}`, line, col: node.pos.col }]);
320
- return t;
321
- }
322
- case 'call': {
323
- const arity = FUNCTION_ARITY[node.name];
324
- if (!arity)
325
- throw new RulesCompileError([{ message: `不认识的函数:${node.name}`, line, col: node.pos.col }]);
326
- const [min, max] = arity;
327
- if (node.args.length < min || node.args.length > max) {
328
- throw new RulesCompileError([{
329
- message: `${node.name} 需要 ${min === max ? min : `${min}–${max}`} 个参数,给了 ${node.args.length}`,
330
- line,
331
- col: node.pos.col,
332
- }]);
333
- }
334
- if (EVENT_ARG_FUNCS.has(node.name)) {
335
- checkEventName(node.args[0], line, `${node.name} 的第一个参数`);
336
- if (node.name === 'last')
337
- checkParamKey(node.args[1], line);
338
- if (node.name === 'count' && node.args.length > 1) {
339
- const days = node.args[1];
340
- const t = infer(days, env, line);
341
- if (t !== 'number')
342
- throw new RulesCompileError([{ message: `count 的天数必须是数字(这里是 ${t})`, line, col: node.pos.col }]);
343
- if (days.k === 'num' && (!Number.isInteger(days.v) || days.v <= 0)) {
344
- throw new RulesCompileError([{ message: 'count 的天数必须是正整数', line, col: node.pos.col }]);
345
- }
346
- }
347
- return node.name === 'last' ? 'string' : 'number';
348
- }
349
- if (node.name === 'isNull') {
350
- infer(node.args[0], env, line);
351
- return 'boolean';
352
- }
353
- if (node.name === 'num') {
354
- const t = infer(node.args[0], env, line);
355
- if (t !== 'number' && t !== 'string' && t !== 'null') {
356
- throw new RulesCompileError([{ message: `num 只接受字符串 / 数字 / null(这里是 ${t})`, line, col: node.pos.col }]);
357
- }
358
- return 'number';
359
- }
360
- if (node.name === 'if') {
361
- const cond = infer(node.args[0], env, line);
362
- if (cond !== 'boolean')
363
- throw new RulesCompileError([{ message: `if 的第一个参数必须是比较 / isNull(这里是 ${cond})`, line, col: node.pos.col }]);
364
- return unify(infer(node.args[1], env, line), infer(node.args[2], env, line), line, node.pos);
365
- }
366
- if (node.name === 'coalesce') {
367
- let type = 'null';
368
- for (const arg of node.args)
369
- type = unify(type, infer(arg, env, line), line, node.pos);
370
- return type;
371
- }
372
- for (const arg of node.args) {
373
- const t = infer(arg, env, line);
374
- if (t !== 'number')
375
- throw new RulesCompileError([{ message: `${node.name} 只收数字(这里是 ${t})`, line, col: node.pos.col }]);
376
- }
377
- if (node.name === 'clamp') {
378
- const [x, lo, hi] = node.args;
379
- if (lo.k === 'num' && hi.k === 'num' && lo.v > hi.v) {
380
- throw new RulesCompileError([{ message: `clamp 的下限 ${lo.v} 大于上限 ${hi.v}`, line, col: node.pos.col }]);
381
- }
382
- void x;
383
- }
384
- return 'number';
385
- }
386
- }
387
- }
388
- function unify(a, b, line, pos) {
389
- if (a === 'null')
390
- return b;
391
- if (b === 'null')
392
- return a;
393
- if (a !== b)
394
- throw new RulesCompileError([{ message: `两边类型不一致:${a} 与 ${b}`, line, col: pos.col }]);
395
- return a;
396
- }
397
- /**
398
- * 收集规则里引用的事件 / 参数(`hoursSince` / `count` / `last` 的裸词参数)。
399
- * 只遍历 AST,不求值:自定义规则换了事件名,模型侧词汇表要跟着变。
400
- */
401
- function collectEvents(node, acc) {
402
- switch (node.k) {
403
- case 'bin':
404
- collectEvents(node.left, acc);
405
- collectEvents(node.right, acc);
406
- return;
407
- case 'un':
408
- collectEvents(node.expr, acc);
409
- return;
410
- case 'call': {
411
- if (EVENT_ARG_FUNCS.has(node.name)) {
412
- const first = node.args[0];
413
- if (first && first.k === 'var') {
414
- const params = acc.get(first.name) ?? new Set();
415
- if (node.name === 'last') {
416
- const second = node.args[1];
417
- if (second && second.k === 'var')
418
- params.add(second.name);
419
- }
420
- acc.set(first.name, params);
421
- }
422
- // count 的第二参数是表达式(天数),里面还可能嵌套函数;last 的参数是裸词,不遍历
423
- if (node.name !== 'hoursSince' && node.name !== 'last') {
424
- for (const arg of node.args.slice(1))
425
- collectEvents(arg, acc);
426
- }
427
- return;
428
- }
429
- for (const arg of node.args)
430
- collectEvents(arg, acc);
431
- return;
432
- }
433
- default:
434
- return;
435
- }
436
- }
437
- function evalNode(node, env, ctx, line) {
438
- switch (node.k) {
439
- case 'num': return node.v;
440
- case 'str': return node.v;
441
- case 'null': return null;
442
- case 'un': {
443
- const value = evalNode(node.expr, env, ctx, line);
444
- if (typeof value !== 'number')
445
- throw runtime(line, node.pos.col, '一元 - 只能用在数字上');
446
- return -value;
447
- }
448
- case 'bin': {
449
- const left = evalNode(node.left, env, ctx, line);
450
- const right = evalNode(node.right, env, ctx, line);
451
- if (typeof left !== 'number' || typeof right !== 'number') {
452
- throw runtime(line, node.pos.col, `${node.op} 只比较数字;null 先用 isNull / coalesce 处理`);
453
- }
454
- switch (node.op) {
455
- case '+': return left + right;
456
- case '-': return left - right;
457
- case '*': return left * right;
458
- case '/':
459
- if (right === 0)
460
- throw runtime(line, node.pos.col, '除以零');
461
- return left / right;
462
- case '<': return left < right ? 1 : 0;
463
- case '<=': return left <= right ? 1 : 0;
464
- case '>': return left > right ? 1 : 0;
465
- case '>=': return left >= right ? 1 : 0;
466
- case '==': return left === right ? 1 : 0;
467
- case '!=': return left !== right ? 1 : 0;
468
- default: throw runtime(line, node.pos.col, `不认识的运算符 ${node.op}`);
469
- }
470
- }
471
- case 'var': {
472
- if (node.name === 'sceneWindowDays')
473
- return ctx.sceneWindowDays;
474
- if (node.name === 'staleHours')
475
- return ctx.staleHours;
476
- if (!env.has(node.name))
477
- throw runtime(line, node.pos.col, `未定义变量:${node.name}`);
478
- return env.get(node.name);
479
- }
480
- case 'call': return evalCall(node, env, ctx, line);
481
- }
482
- }
483
- /** 布尔在内部用 1 / 0 表示(RuleValue 只有三种值,布尔不能落进变量) */
484
- const asBool = (value, line, col) => {
485
- if (typeof value !== 'number')
486
- throw runtime(line, col, '条件必须是布尔值');
487
- return value !== 0;
488
- };
489
- function evalCall(node, env, ctx, line) {
490
- if (node.name === 'if') {
491
- const cond = evalNode(node.args[0], env, ctx, line);
492
- return asBool(cond, line, node.pos.col)
493
- ? evalNode(node.args[1], env, ctx, line)
494
- : evalNode(node.args[2], env, ctx, line);
495
- }
496
- if (node.name === 'isNull')
497
- return evalNode(node.args[0], env, ctx, line) === null ? 1 : 0;
498
- if (node.name === 'coalesce') {
499
- for (const arg of node.args) {
500
- const value = evalNode(arg, env, ctx, line);
501
- if (value !== null)
502
- return value;
503
- }
504
- return null;
505
- }
506
- if (node.name === 'hoursSince') {
507
- const name = node.args[0].name;
508
- const last = ctx.lastSeen.get(name);
509
- if (!last)
510
- return null;
511
- return (ctx.now - last.atMs) / 3600_000;
512
- }
513
- if (node.name === 'count') {
514
- const name = node.args[0].name;
515
- const days = node.args.length > 1 ? evalNode(node.args[1], env, ctx, line) : ctx.sceneWindowDays;
516
- if (typeof days !== 'number' || !Number.isInteger(days) || days <= 0)
517
- throw runtime(line, node.pos.col, 'count 的天数必须是正整数');
518
- if (days > ctx.sceneWindowDays)
519
- throw runtime(line, node.pos.col, `count 的天数不能超过窗口 ${ctx.sceneWindowDays} 天`);
520
- const cutoff = ctx.now - days * 24 * 3600_000;
521
- return ctx.events.filter((e) => e.name === name && e.atMs >= cutoff).length;
522
- }
523
- if (node.name === 'last') {
524
- const name = node.args[0].name;
525
- const key = node.args[1].name;
526
- const last = ctx.lastSeen.get(name);
527
- return last && key in last.params ? last.params[key] : null;
528
- }
529
- if (node.name === 'num') {
530
- const value = evalNode(node.args[0], env, ctx, line);
531
- if (value === null)
532
- return null;
533
- if (typeof value === 'number')
534
- return value;
535
- const n = Number(value.trim());
536
- return Number.isFinite(n) ? n : null;
537
- }
538
- const values = node.args.map((arg) => evalNode(arg, env, ctx, line));
539
- const nums = values.map((value) => {
540
- if (typeof value !== 'number')
541
- throw runtime(line, node.pos.col, `${node.name} 只收数字`);
542
- return value;
543
- });
544
- if (node.name === 'clamp') {
545
- const [x, lo, hi] = nums;
546
- if (lo > hi)
547
- throw runtime(line, node.pos.col, 'clamp 的下限大于上限');
548
- return Math.min(hi, Math.max(lo, x));
549
- }
550
- if (node.name === 'min')
551
- return Math.min(...nums);
552
- if (node.name === 'max')
553
- return Math.max(...nums);
554
- if (node.name === 'abs')
555
- return Math.abs(nums[0]);
556
- throw runtime(line, node.pos.col, `不认识的函数 ${node.name}`);
557
- }
558
- function runtime(line, col, message) {
559
- const err = new Error(formatRuleError({ message, line, col }));
560
- err.name = 'RulesRuntimeError';
561
- return err;
562
- }
563
- /**
564
- * 编译规则文本。空文本 / 只有注释 = 没有规则(调用方走内置默认),返回 null。
565
- * 任何错误都抛 RulesCompileError(带行号列号),调用方整份回退。
566
- */
567
- export function compileRules(source) {
568
- const lines = String(source ?? '').split('\n');
569
- const assignments = [];
570
- let version = null;
571
- let sawAnything = false;
572
- for (const [index, raw] of lines.entries()) {
573
- const lineNo = index + 1;
574
- const text = raw.replace(/\r$/, '').trim();
575
- if (!text || text.startsWith('#'))
576
- continue;
577
- sawAnything = true;
578
- const { left, right } = splitAssignment(text, lineNo);
579
- if (version === null) {
580
- if (left !== 'version') {
581
- throw new RulesCompileError([{ message: '第一条非注释行必须是 version = <整数>', line: lineNo, col: 1 }]);
582
- }
583
- if (!/^\d+$/.test(right))
584
- throw new RulesCompileError([{ message: 'version 必须是正整数', line: lineNo, col: 1 }]);
585
- version = Number(right);
586
- continue;
587
- }
588
- if (!VAR_RE.test(left))
589
- throw new RulesCompileError([{ message: `变量名不合法:${left}`, line: lineNo, col: 1 }]);
590
- if (RESERVED.has(left))
591
- throw new RulesCompileError([{ message: `${left} 是保留名,不能当变量`, line: lineNo, col: 1 }]);
592
- if (assignments.some((a) => a.name === left))
593
- throw new RulesCompileError([{ message: `变量重复定义:${left}`, line: lineNo, col: 1 }]);
594
- if (!right)
595
- throw new RulesCompileError([{ message: `${left} 没有表达式`, line: lineNo, col: 1 }]);
596
- const node = new Parser(lex(right, lineNo), lineNo).parseAll();
597
- assignments.push({ name: left, expr: node, pos: { line: lineNo, col: 1 } });
598
- }
599
- if (!sawAnything)
600
- return null;
601
- if (version === null)
602
- throw new RulesCompileError([{ message: '缺 version = <整数>', line: 1, col: 1 }]);
603
- // 静态类型:自上而下,只能引用前面已定义的变量(没有前向引用,也就没有环)
604
- const env = new Map();
605
- for (const assignment of assignments) {
606
- const type = infer(assignment.expr, env, assignment.pos.line);
607
- if (type === 'boolean') {
608
- throw new RulesCompileError([{ message: `${assignment.name} 是布尔值,不能存进变量(用 1 / 0 或字符串)`, line: assignment.pos.line, col: 1 }]);
609
- }
610
- env.set(assignment.name, type);
611
- }
612
- const eventMap = new Map();
613
- for (const assignment of assignments)
614
- collectEvents(assignment.expr, eventMap);
615
- return {
616
- version,
617
- vars: assignments.map((a) => a.name),
618
- events: [...eventMap].map(([name, params]) => ({ name, params: [...params] })),
619
- evaluate(ctx) {
620
- const values = new Map();
621
- for (const assignment of assignments) {
622
- values.set(assignment.name, evalNode(assignment.expr, values, ctx, assignment.pos.line));
623
- }
624
- return Object.fromEntries(values);
625
- },
626
- };
627
- }
628
- /**
629
- * 内置默认规则(版本 4)。
630
- *
631
- * 曲线是**单调下降**的:醒得越久越累,不存在「熬夜回血」。恢复只能靠一条新的 `woke`,
632
- * 起点由 `woke hours=` 决定(睡 7 小时 = 70 分);没有 `woke` 记录时 `energy` 是 null
633
- * ——「没记录」不等于「刚睡醒」。
634
- *
635
- * 所有会「过期」的值(energy / satiety / location / goal / present)用同一个 `staleHours`:
636
- * 超过它就返回 null,交给渲染层说「未知(最后 X · N 天前)」,不拿旧值当现在。
637
- * 地板 0 而不是 20:`mood` 的「力竭」分支必须够得着(energy < 20)。
638
- *
639
- * `satiety` 是饱腹度不是饥饿值:100 = 刚吃完,30 = 很久没吃;没记录 = null,不给中性先验。
640
- */
641
- export const DEFAULT_RULES = `version = 4
642
- woke_h = hoursSince(woke)
643
- awake = coalesce(woke_h, 0)
644
- sleep_h = coalesce(num(last(woke, hours)), 7)
645
- energy = if(isNull(woke_h), null, if(woke_h > staleHours, null, clamp(70 + 4 * (sleep_h - 7) - 5 * awake, 0, 100)))
646
- mood = if(isNull(energy), null, if(energy < 20, "力竭", if(energy < 45, "疲惫", "正常")))
647
- ate_h = hoursSince(ate)
648
- satiety = if(isNull(ate_h), null, if(ate_h > staleHours, null, clamp(100 - 4 * ate_h, 30, 100)))
649
- at_h = coalesce(hoursSince(at), 0)
650
- location = if(isNull(hoursSince(at)), null, if(at_h > staleHours, null, last(at, place)))
651
- goal_h = coalesce(hoursSince(set_goal), 0)
652
- goal = if(isNull(hoursSince(set_goal)), null, if(goal_h > staleHours, null, last(set_goal, text)))
653
- `;
654
- /** 内置默认规则编译一次就够;失败说明代码写错了,调用方按 fallback 处理 */
655
- let defaultCompiled;
656
- export function compileDefaultRules() {
657
- if (defaultCompiled === undefined)
658
- defaultCompiled = compileRules(DEFAULT_RULES);
659
- if (!defaultCompiled)
660
- throw new Error('内置默认规则为空');
661
- return defaultCompiled;
662
- }