work-rhythm 0.1.7 → 0.2.3

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.
Files changed (43) hide show
  1. package/.agents/notes/AGENTS.md +8 -1
  2. package/.agents/notes/decisions/2026-12-01-interjections-batch-into-one-answer-and-interrupt-reruns.md +33 -0
  3. package/.agents/notes/decisions/2026-12-01-long-runs-are-bounded-by-silence-not-wall-clock.md +35 -0
  4. package/.agents/notes/decisions/2026-12-01-router-and-worker-pass-content-in-handoff-docs.md +41 -0
  5. package/.agents/notes/pitfalls/2026-12-01-launchd-install-bakes-invoking-node.md +28 -0
  6. package/.agents/notes/pitfalls/2026-12-01-replace-string-dollar-quote-expands.md +16 -0
  7. package/.agents/skills/work-rhythm/SKILL.md +14 -12
  8. package/README.md +7 -4
  9. package/collectors/local.env.example +10 -1
  10. package/docs/agents.md +28 -11
  11. package/docs/channels.md +9 -6
  12. package/docs/router-worker.md +241 -0
  13. package/docs/scheduled-tasks.md +4 -4
  14. package/package.json +1 -1
  15. package/scripts/cli.js +4 -3
  16. package/scripts/cmd/agent.js +78 -40
  17. package/scripts/cmd/check.js +4 -0
  18. package/scripts/cmd/listen.js +20 -4
  19. package/scripts/cmd/rhythm.js +9 -2
  20. package/scripts/cmd/trigger.js +143 -0
  21. package/scripts/lib/agent.js +377 -30
  22. package/scripts/lib/bot.js +140 -35
  23. package/scripts/lib/engine.js +523 -0
  24. package/scripts/lib/handoff.js +165 -0
  25. package/scripts/lib/launchd.js +49 -3
  26. package/scripts/lib/markdown.js +328 -38
  27. package/scripts/lib/rhythm.js +377 -33
  28. package/scripts/lib/router.js +161 -0
  29. package/scripts/lib/run.js +43 -0
  30. package/scripts/lib/view.js +583 -0
  31. package/scripts/lib/worker.js +97 -0
  32. package/scripts/test/agent.test.js +17 -9
  33. package/scripts/test/check.test.js +7 -2
  34. package/scripts/test/harness.js +13 -1
  35. package/scripts/test/listen.test.js +3 -3
  36. package/scripts/test/rhythm.test.js +42 -8
  37. package/scripts/test/router-helper.js +80 -0
  38. package/scripts/test/router.test.js +509 -0
  39. package/scripts/test/stubs.js +82 -12
  40. package/scripts/test/timeout.test.js +99 -0
  41. package/templates/00-config/profile.example.yaml +7 -0
  42. package/templates/AGENTS.md +3 -1
  43. package/templates/README.md +4 -1
@@ -0,0 +1,97 @@
1
+ // 执行者:一次性的 agent 会话,领一份任务书(.agents/handoff/<短号>.md),做完写回执(<短号>.result.md)就退。
2
+ // 给它的提示词只有一句话——内容都在任务书里,提示词里只带路径。权限和超时由触发来源定(engine.js 查好了传进来),路由说了不算。
3
+ // 这里还有一个执行者池:同时最多跑 limit 个,多的排队;stop 能拿掉排队里的、杀掉在跑的。
4
+ 'use strict';
5
+ const path = require('node:path');
6
+ const { createAgent } = require('./agent');
7
+ const handoff = require('./handoff');
8
+
9
+ const WORKER_STATE_DIR = ['01-inbox', '_rhythm', 'workers'];
10
+
11
+ // 给执行者的那一句
12
+ function workerPrompt(id) {
13
+ return `读 ${handoff.relTask(id)}(任务书),照它做完,把回执写到 ${handoff.relResult(id)};没有写权限就把回执作为你最后一段话输出。不要向我提问,不要等待确认,不要自己发消息。`;
14
+ }
15
+
16
+ // 跑一个执行者。spec 是 { agent, model, effort };resume 给了就接着那个会话跑(续做),接不上时自动改开新会话(上下文在任务书里)。
17
+ // 返回 { ok, failed, stopped, reply, sessionId, seconds, config, partial };onSession 在拿到会话 id 时调(监控页上一开始就能看到),onKill 把停它的办法交出去。
18
+ // idleS 是静默闸:执行者可能长时间不出声(跑构建、跑测试),给得比值守宽
19
+ async function runWorker({ root, env, log = () => {}, id, mode, timeoutS, idleS = 0, spec, resume = '', onSession = () => {}, onKill = () => {} }) {
20
+ const agent = createAgent({ root, agent: spec.agent, mode, timeoutS, idleS, log, env, model: spec.model, effort: spec.effort });
21
+ const started = Date.now();
22
+ const handle = agent.start(workerPrompt(id), { session: resume, onSession, stateDir: path.join(root, ...WORKER_STATE_DIR) });
23
+ onKill(handle.kill);
24
+ const r = await handle.done;
25
+ return {
26
+ ok: !r.failed,
27
+ failed: r.failed || '',
28
+ stopped: Boolean(r.stopped),
29
+ reply: r.reply || '',
30
+ sessionId: r.sessionId || resume || '',
31
+ seconds: Math.round((Date.now() - started) / 1000),
32
+ config: Boolean(r.config),
33
+ partial: r.partial || '',
34
+ };
35
+ }
36
+
37
+ // 执行者池。submit(id, starter) 返回 starter 结果的 Promise;starter 收到一个 ctrl,用 ctrl.setKill(函数) 把停它的办法交出来
38
+ function createPool({ limit = 2 } = {}) {
39
+ const running = new Map(); // id → { id, startedAt, meta, ctrl }
40
+ const queue = []; // { id, meta, starter, resolve }
41
+
42
+ const launch = (job) => {
43
+ const entry = { id: job.id, startedAt: Date.now(), meta: job.meta || {}, ctrl: { kill: null, stopReason: '', setKill: null } };
44
+ entry.ctrl.setKill = (fn) => {
45
+ entry.ctrl.kill = fn;
46
+ if (entry.ctrl.stopReason) fn(entry.ctrl.stopReason); // 还没交出办法就叫停了:一交出来就停
47
+ };
48
+ running.set(job.id, entry);
49
+ Promise.resolve()
50
+ .then(() => job.starter(entry.ctrl))
51
+ .then(
52
+ (r) => finish(job, r),
53
+ (error) => finish(job, { ok: false, failed: `执行者出错:${error && error.message ? error.message : String(error)}` }),
54
+ );
55
+ };
56
+ const finish = (job, r) => {
57
+ running.delete(job.id);
58
+ job.resolve(r);
59
+ startNext();
60
+ };
61
+ const startNext = () => {
62
+ while (running.size < limit && queue.length) launch(queue.shift());
63
+ };
64
+
65
+ function submit(id, starter, meta = {}) {
66
+ return new Promise((resolve) => {
67
+ queue.push({ id, starter, meta, resolve });
68
+ startNext();
69
+ });
70
+ }
71
+
72
+ // 停掉一个:在排队里的拿掉(它的 Promise 以 { stopped } 结算),在跑的杀掉。返回 'queued' / 'running' / ''
73
+ function stop(id, reason = '已停止') {
74
+ const at = queue.findIndex((j) => j.id === id);
75
+ if (at >= 0) {
76
+ const [job] = queue.splice(at, 1);
77
+ job.resolve({ ok: false, stopped: true, failed: reason, reply: '', sessionId: '', seconds: 0 });
78
+ return 'queued';
79
+ }
80
+ const entry = running.get(id);
81
+ if (!entry) return '';
82
+ if (entry.ctrl.kill) entry.ctrl.kill(reason);
83
+ else entry.ctrl.stopReason = reason;
84
+ return 'running';
85
+ }
86
+
87
+ return {
88
+ limit,
89
+ submit,
90
+ stop,
91
+ running: () => [...running.values()],
92
+ queued: () => queue.map((j) => j.id),
93
+ idle: () => !running.size && !queue.length,
94
+ };
95
+ }
96
+
97
+ module.exports = { createPool, runWorker, workerPrompt, WORKER_STATE_DIR };
@@ -25,8 +25,8 @@ function setup(t) {
25
25
  const s = { box, stubs, env: { ...stubs, STUB_KEYCHAIN: 'ok', STUB_ROBOT_URL: 'http://127.0.0.1:1/send?yzjtoken=stubtoken0123456789abcd' } };
26
26
  s.run = (args, env = {}) => box.run(args, { env: { ...s.env, ...env } });
27
27
  s.bindEnv = () => ({ ...s.env, ZCODE_CLI: stubs.ZCODE_CLI, DSH_HOME: stubs.DSH_HOME, DSH_NODE: stubs.DSH_NODE, DSH_CLI: stubs.DSH_CLI });
28
- // 什么都没装的环境:PATH 上没有假的,ZCode 和 DSH 也指到不存在的地方
29
- s.nothing = () => ({ ...s.bindEnv(), PATH: path.join(box.root, 'nothing'), ZCODE_CLI: '/nonexistent', DSH_CLI: '', DSH_NODE: '', DSH_DESKTOP_DIR: path.join(box.root, 'nothing') });
28
+ // 什么都没装的环境:PATH 上没有假的,ZCode、DSH、Kimi 也指到不存在的地方
29
+ s.nothing = () => ({ ...s.bindEnv(), PATH: path.join(box.root, 'nothing'), ZCODE_CLI: '/nonexistent', KIMI_CLI: '/nonexistent', DSH_CLI: '', DSH_NODE: '', DSH_DESKTOP_DIR: path.join(box.root, 'nothing') });
30
30
  return s;
31
31
  }
32
32
 
@@ -92,7 +92,10 @@ test('agent --json:给 agent 读的结构', (t) => {
92
92
  assert.equal(doc.invokingFound, true);
93
93
  assert.equal(doc.bound, '');
94
94
  assert.equal(doc.suggest, 'qoder');
95
- assert.deepEqual(doc.agents.map((a) => [a.name, a.found]), [['zcode', true], ['dsh', true], ['qoder', true], ['claude', true]]);
95
+ assert.deepEqual(doc.agents.map((a) => [a.name, a.found]), [['zcode', true], ['dsh', true], ['qoder', true], ['claude', true], ['kimi', true]]);
96
+ // 两个角色:没单独配时都落到绑定的那个
97
+ assert.deepEqual(doc.roles, { router: { agent: '', model: '', effort: '', session: '' }, worker: { agent: '', model: '', effort: '' } });
98
+ assert.deepEqual(doc.agents.map((a) => a.readOnly), [true, true, true, true, false], 'kimi 无界面没有只读档');
96
99
  assert.match(s.run(['agent', '--json'], s.bindEnv()).stdout, /"invoking": ""/);
97
100
  });
98
101
 
@@ -103,7 +106,7 @@ test('agent bind:不给名字就绑正在调的这个;没标记就绑装了
103
106
  assert.equal(exists(`${s.box.work}/collectors/local.env`), false);
104
107
  const r = s.run(['agent', 'bind'], { ...env, DSH_SESSION_ID: 'sess-1' });
105
108
  assert.equal(r.code, 0, r.out);
106
- assert.match(r.stdout, /已绑定 dsh(DSH(DeepSeek Harness)的 headless 模式),写进了 collectors\/local\.env 的 YZJ_BOT_AGENT。\n 模型用它自己的默认,思考强度用它自己的默认\n 会话:绑着 sess-1,机器人的话从这个会话接着走(刚绑上)\n 模型和思考强度还没配:work-rhythm agent models dsh 看能用哪些[\s\S]*\n下一步:work-rhythm agent test/);
109
+ assert.match(r.stdout, /已绑定 dsh(DSH(DeepSeek Harness)的 headless 模式),两个角色共用,写进了 collectors\/local\.env 的 YZJ_BOT_AGENT。\n 模型用它自己的默认,思考强度用它自己的默认\n 会话:绑着 sess-1,机器人的话从这个会话接着走(刚绑上)\n 模型和思考强度还没配:work-rhythm agent models dsh 看能用哪些[\s\S]*\n下一步:work-rhythm agent test/);
107
110
  // 正在调的这个 agent 的当前会话(DSH_SESSION_ID)顺手绑上了
108
111
  assert.match(read(`${s.box.work}/collectors/local.env`), /^YZJ_BOT_SESSION="sess-1"$/m);
109
112
  // local.env 原来没有:从样例复制一份,再把样例里注释掉的那行换成真的
@@ -208,17 +211,22 @@ test('agent doctor:绑定的 agent 有没有问题;用法不对退出码为
208
211
  assert.equal(s.run(['agent', 'nope'], env).code, 2);
209
212
  const help = s.run(['agent', '--help'], env);
210
213
  assert.equal(help.code, 0);
211
- assert.match(help.stdout, /work-rhythm agent \[子命令\] —— 定时任务和机器人值守用哪个 agent/);
214
+ assert.match(help.stdout, /work-rhythm agent \[子命令\] —— 路由、执行者、值守用哪个 agent/);
212
215
  });
213
216
 
214
217
  test('installedAgents:本机真有什么就报什么,不编造', () => {
215
218
  const list = installedAgents(process.env);
216
- assert.deepEqual(list.map((a) => a.name), ['zcode', 'dsh', 'qoder', 'claude']);
219
+ assert.deepEqual(list.map((a) => a.name), ['zcode', 'dsh', 'qoder', 'claude', 'kimi']);
217
220
  for (const a of list) assert.equal(typeof a.found, 'boolean');
218
221
  });
219
222
 
220
223
  // ---------------------------------------------------------------- 模型和思考强度
221
- const patchOf = (box) => read(`${box.work}/01-inbox/_bot/dsh-headless.patch.yml`);
224
+ // 覆盖文件按模型和强度分文件名:在 _bot 下按前缀找,取最新的一份
225
+ const patchOf = (box) => {
226
+ const dir = `${box.work}/01-inbox/_bot`;
227
+ const newest = fs.readdirSync(dir).filter((n) => /^dsh-headless.*\.patch\.yml$/.test(n)).sort((a, b) => fs.statSync(`${dir}/${b}`).mtimeMs - fs.statSync(`${dir}/${a}`).mtimeMs)[0];
228
+ return read(`${dir}/${newest}`);
229
+ };
222
230
 
223
231
  test('agent bind --model --effort:写进 local.env;dsh 把它写进自动生成的覆盖文件,agent 真的按它跑', (t) => {
224
232
  const s = setup(t);
@@ -388,7 +396,7 @@ test('agent session / sessions:看、换、清;dsh 按工作区列出会话
388
396
  assert.match(list.stdout, /^dsh 在这个工作区的会话,新的在前:\n session-new .*\n session-mid .*\n session-old .*\n绑哪个:work-rhythm agent session <id>/);
389
397
  // 换一个,再列就标出来
390
398
  const bind = s.run(['agent', 'session', 'session-mid'], env);
391
- assert.match(bind.stdout, /会话已绑为 session-mid,写进了 collectors\/local\.env。机器人下一句从这个会话接着走。/);
399
+ assert.match(bind.stdout, /会话已绑为 session-mid,写进了 collectors\/local\.env。路由下一句从这个会话接着走。/);
392
400
  assert.match(read(`${s.box.work}/collectors/local.env`), /^YZJ_BOT_SESSION="session-mid"$/m);
393
401
  const listed = s.run(['agent', 'sessions'], env).stdout;
394
402
  assert.match(listed, / session-mid .* 绑着的\n/);
@@ -398,7 +406,7 @@ test('agent session / sessions:看、换、清;dsh 按工作区列出会话
398
406
  write(`${s.box.work}/01-inbox/_bot/session-id`, 'session-new\n');
399
407
  assert.match(s.run(['agent', 'sessions'], env).stdout, / session-new .* 值守自己的\n/);
400
408
  // 清掉
401
- assert.match(s.run(['agent', 'session', '--clear'], env).stdout, /会话已清掉,机器人用自己的专属会话。/);
409
+ assert.match(s.run(['agent', 'session', '--clear'], env).stdout, /会话已清掉,路由用自己的专属会话。/);
402
410
  assert.equal(s.run(['agent', 'session', 'a', 'b'], env).code, 2);
403
411
  assert.equal(s.run(['agent', 'sessions', 'x'], env).code, 2);
404
412
  });
@@ -193,7 +193,7 @@ test('check:只绑了 agent 跑定时任务、没装值守,不报值守的
193
193
  s.localEnv('# YZJ_BOT_AGENT="dsh"\n');
194
194
  const r2 = s.check({ ...s.stubs });
195
195
  assert.equal(r2.code, 1, r2.out);
196
- assert.match(r2.stdout, /schedule 里有任务(daily-plan、noon-checkin、evening-review、carryover、weekly-rhythm)却没绑 agent,到点一个也跑不了:work-rhythm agent bind <zcode\|dsh\|qoder\|claude>/);
196
+ assert.match(r2.stdout, /schedule 里有任务(daily-plan、noon-checkin、evening-review、carryover、weekly-rhythm)却没绑 agent,到点一个也跑不了:work-rhythm agent bind <zcode\|dsh\|qoder\|claude\|kimi>/);
197
197
  });
198
198
 
199
199
  test('check:值守装了之后,配的命令找不到时报出来', (t) => {
@@ -270,11 +270,16 @@ test('仓库保持通用:根目录出现工作目录才有的东西、个人
270
270
  write(path.join(repo, '00-config', 'profile.yaml'), 'setup:\n status: done\n');
271
271
  write(path.join(repo, '02-daily', '2026-01', '2026-01-01.md'), '# 2026-01-01\n');
272
272
  write(path.join(repo, 'collectors', 'local.env'), 'A=1\n');
273
+ // 交接文档(路由和执行者之间的任务书、回执)含用户原话,init 和 pack 会把 .agents/ 整个带走:仓库里不能有;别的文件不算
274
+ write(path.join(repo, '.agents', 'handoff', 'README.md'), '说明');
275
+ assert.ok(!problems().some((l) => l.includes('交接文档')), '别的文件不算');
276
+ write(path.join(repo, '.agents', 'handoff', 't-000001.result.md'), '# 回执');
273
277
  const found = problems();
274
- assert.equal(found.length, 3);
278
+ assert.equal(found.length, 4);
275
279
  assert.match(found.join('\n'), /仓库根目录里出现了 00-config:这个仓库只放 skill 和 CLI,不是工作目录/);
276
280
  assert.match(found.join('\n'), /仓库根目录里出现了 02-daily/);
277
281
  assert.match(found.join('\n'), /仓库里出现了个人配置 collectors\/local\.env/);
282
+ assert.match(found.join('\n'), /仓库里出现了交接文档 \.agents\/handoff\/t-\*\.md/);
278
283
  assert.ok(found.every((l) => !l.includes('templates/00-config')), 'templates/ 里的不算');
279
284
  });
280
285
 
@@ -17,7 +17,7 @@ const T = '\t';
17
17
 
18
18
  // 这些变量是各命令的配置,本机环境里如果碰巧有,会让用例的结果跟着变。跑命令时一律不带
19
19
  // CLAUDE、QODER 也抹掉:调用这个测试的 agent 会留自己的标记(ZCODE_*、CLAUDE_CODE_*、DSH_SESSION_ID),用例不能被它带偏
20
- const STRIP = /^(YZJ_|GIT_ACTIVITY_|FILE_ACTIVITY_|DSH_|STUB_|ZCODE_|WORK_RHYTHM_|DECISIONS_TODAY|LINKY_TYPES|CLAUDE|QODER)/;
20
+ const STRIP = /^(YZJ_|GIT_ACTIVITY_|FILE_ACTIVITY_|DSH_|STUB_|ZCODE_|WORK_RHYTHM_|DECISIONS_TODAY|LINKY_TYPES|CLAUDE|QODER|KIMI_)/;
21
21
  const { writeWorkdir } = require('../lib/template');
22
22
 
23
23
  // 用户级登记指向一个不存在的文件:用例不能被本机登记的工作目录带偏
@@ -113,6 +113,9 @@ function makeSandbox(t) {
113
113
  sandbox.stubs = (extra = {}) => {
114
114
  const stubs = require('./stubs');
115
115
  for (const [name, source] of Object.entries(stubs)) sandbox.stub(name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`), source);
116
+ // 假 agent 的「脑子」(router-helper.js):认路由和执行者那两种提示词
117
+ const helper = path.join(bin, 'fake-helper.js');
118
+ fs.copyFileSync(path.join(__dirname, 'router-helper.js'), helper);
116
119
  // 假的 DSH_HOME:里面只有桌面应用那份配置,一条无关的加两条模型的
117
120
  const home = path.join(root, 'dsh-home', 'profiles', 'web');
118
121
  fs.mkdirSync(home, { recursive: true });
@@ -149,11 +152,20 @@ function makeSandbox(t) {
149
152
  STUB_CALLS: file('calls.log'),
150
153
  STUB_ROBOT_TOKEN: 'stubtoken0123456789abcd',
151
154
  STUB_AGENT_CALLS: file('agent.calls'),
155
+ STUB_AGENT_ALL: file('agent.all'),
156
+ STUB_AGENT_LAST: file('agent.last'),
157
+ STUB_ZCODE_ALL: file('zcode.all'),
152
158
  STUB_ZCODE_ARGS: file('zcode.args'),
153
159
  STUB_QODER_ARGS: file('qoder.args'),
154
160
  STUB_CLAUDE_ARGS: file('claude.args'),
155
161
  STUB_DSH_ARGS: file('dsh.args'),
156
162
  STUB_DSH_ENV: file('dsh.env'),
163
+ STUB_KIMI_ARGS: file('kimi.args'),
164
+ STUB_KIMI_ENV: file('kimi.env'),
165
+ STUB_ROUTER_CALLS: file('router.calls'),
166
+ STUB_ROUTER_REPLY: file('router.reply'),
167
+ STUB_HELPER: helper,
168
+ KIMI_CLI: path.join(bin, 'fake-kimi'),
157
169
  STUB_APPROVAL_NEW_MS: String(Date.UTC(2026, 10, 27, 10, 0, 0)),
158
170
  STUB_APPROVAL_OLD_MS: String(Date.UTC(2026, 10, 16, 5, 30, 0)),
159
171
  DSH_HOME: path.join(root, 'dsh-home'),
@@ -126,11 +126,11 @@ test('listen handle:agent 失败时退出码为 5', async (t) => {
126
126
  assert.match(r.stderr, /没处理成功:退出码 1:agent 崩了/);
127
127
  });
128
128
 
129
- test('listen:agent 超过 YZJ_BOT_TIMEOUT 没返回时按失败处理', async (t) => {
129
+ test('listen:agent 超过 YZJ_BOT_TIMEOUT 没做完时按失败处理', async (t) => {
130
130
  const s = setup(t);
131
131
  const { hook, env } = await withHook(t, s);
132
132
  s.listen(['handle-frame', frame('me-0001', 'm4', '慢一点')], { ...env, STUB_AGENT: 'slow', YZJ_BOT_TIMEOUT: '1' });
133
- assert.equal(hook.contents().at(-1), '没处理成功:超过 1 秒没返回');
133
+ assert.equal(hook.contents().at(-1), '没处理成功:超过 1 秒没做完');
134
134
  });
135
135
 
136
136
  test('listen:agent 什么都没输出时按失败处理', async (t) => {
@@ -416,7 +416,7 @@ test('listen install / uninstall / status:值守跑在本地服务那一个进
416
416
  write(`${s.box.work}/collectors/local.env`, 'YZJ_MY_OPEN_ID="me-0001"\nYZJ_BOT_AGENT="dsh"\n');
417
417
  const home = path.join(s.box.root, 'home');
418
418
  fs.mkdirSync(path.join(home, 'Library', 'LaunchAgents'), { recursive: true });
419
- const env = { ...s.stubs, HOME: home, STUB_KEYCHAIN: 'ok', STUB_ROBOT_URL: 'http://127.0.0.1:1/send?yzjtoken=stubtoken0123456789abcd' };
419
+ const env = { ...s.stubs, HOME: home, STUB_KEYCHAIN: 'ok', STUB_LAUNCHCTL_RUNNING: '1', STUB_ROBOT_URL: 'http://127.0.0.1:1/send?yzjtoken=stubtoken0123456789abcd' };
420
420
  const agents = path.join(home, 'Library', 'LaunchAgents');
421
421
  // 老的单独常驻还在:install 要把它收掉
422
422
  write(path.join(agents, 'work-rhythm.bot.work.plist'), '<plist/>');
@@ -194,7 +194,9 @@ describe('rhythm start:服务在跑的时候', () => {
194
194
  const r = s.rhythm(['status']);
195
195
  assert.equal(r.code, 0, r.out);
196
196
  assert.match(r.stdout, /在跑(pid \d+),页面 http:\/\/127\.0\.0\.1:\d+\n/);
197
- assert.match(r.stdout, /接下来:\n[\d-]+ 周.-?\n/);
197
+ // 「接下来」那一行有没有任务都行:任务定在「离现在 6 小时 7 分之后」,傍晚跑会跨过午夜,那行就是「没有要跑的」;
198
+ // 任务本身在下一个断言里用 due --days 2 查
199
+ assert.match(r.stdout, /接下来:\n[\d-]+ 周./);
198
200
  // 往后两天里能看到那个任务
199
201
  assert.match(s.rhythm(['due', '--days', '2']).stdout, new RegExp(` ${farSpec.slice(4)} daily-plan\\n`));
200
202
  assert.equal(exists(`${s.box.work}/01-inbox/_rhythm/service.pid`), true);
@@ -236,13 +238,27 @@ describe('rhythm start:服务在跑的时候', () => {
236
238
  assert.match(hook.contents().at(-1), /「daily-plan」没跑完:退出码 1:agent 崩了/);
237
239
  });
238
240
 
239
- test('网页:今日、遗留打得开;没有的日子、越出范围的地址、写请求都拒掉', async () => {
241
+ test('网页:今日、遗留打得开,最近的日子和站内链接都对;没有的日子、越出范围的地址、写请求都拒掉', async () => {
240
242
  const base = `http://127.0.0.1:${port}`;
243
+ write(`${s.box.work}/02-daily/2026-11/2026-11-30.md`, '# 2026-11-30 周一\n\n## 计划\n\n- **今日重点**:\n 1. 整理接口 —— 建议 09:00–10:00,上午专注\n- **待你定**:\n 1. 要不要提前联调?\n > 对 AI 说「有什么要我定」就会来问。\n\n## 进展\n\n## 复盘\n\n- **今天的去处**:会议 1h · 编码 3h\n- **未完事项**:收尾已转入 [遗留待处理](../../03-carryover/CARRYOVER.md)。\n\n## 事件流\n\n| 时间 | 类型 | 事项 | 来源 | 项目 |\n|------|------|------|------|------|\n| 10:00 | 会议 | 周会(30min) | calendar-yzj | 导出 |\n\n## 备注\n\n- 17:00 同步:完成\n');
241
244
  const home = await fetch(`${base}/`);
242
245
  const html = await home.text();
243
246
  assert.equal(home.status, 200);
244
247
  assert.match(html, /写完导出接口文档/);
245
248
  assert.match(html, /<a href="\/rhythm">规律<\/a>/);
249
+ assert.ok(html.includes(`/day/${TODAY()}`), '今天的日期应出现在最近日期条里');
250
+ assert.ok(html.includes('/day/2026-11-30'), '历史月份目录里的每日文件也应列在最近日期条里');
251
+ const past = await (await fetch(`${base}/day/2026-11-30`)).text();
252
+ assert.ok(past.includes('class="kpi-grid"'));
253
+ assert.ok(past.includes('data-key="plan"'));
254
+ assert.ok(past.includes('data-key="pending"'));
255
+ assert.ok(past.includes('data-key="events"'));
256
+ assert.ok(past.includes('data-panel="pending"'));
257
+ assert.ok(past.includes('class="focus-list"'));
258
+ assert.ok(past.includes('class="callout-amber"'));
259
+ assert.ok(past.includes('class="card is-empty"'));
260
+ assert.ok(past.includes('class="timeline"'));
261
+ assert.ok(past.includes('<a href="/carryover">遗留待处理</a>'), '工作目录相对链接应转成站内路由');
246
262
  assert.equal((await fetch(`${base}/carryover`)).status, 200);
247
263
  assert.equal((await fetch(`${base}/day/1999-01-01`)).status, 404);
248
264
  assert.equal((await fetch(`${base}/reports/..%2F..%2F00-config%2Fprofile.yaml`)).status, 404);
@@ -344,13 +360,16 @@ test('rhythm:profile 的 agent-model / agent-effort 给定时任务另配一
344
360
  assert.equal(s.rhythm(['doctor'], env).code, 0, s.rhythm(['doctor'], env).out);
345
361
  const r = s.rhythm(['run', 'daily-plan'], env);
346
362
  assert.equal(r.code, 0, r.out);
347
- const patch = read(`${s.box.work}/01-inbox/_rhythm/dsh-headless.patch.yml`);
348
- assert.match(patch, / provider: opencode-go\n model: glm-5\.3-flash\n reasoningEffort: low\n/);
363
+ // 覆盖文件按模型和强度分文件名(路由和执行者用的模型不一样、并发跑的时候不互相覆盖):在 _rhythm 下按前缀找
364
+ const patchDir = `${s.box.work}/01-inbox/_rhythm`;
365
+ const patches = () => fs.readdirSync(patchDir).filter((n) => /^dsh-headless.*\.patch\.yml$/.test(n)).map((n) => read(path.join(patchDir, n)));
366
+ assert.ok(patches().some((p) => / provider: opencode-go\n model: glm-5\.3-flash\n reasoningEffort: low\n/.test(p)), patches().join('\n'));
349
367
  // 没配的时候沿用 local.env 的 YZJ_BOT_MODEL / YZJ_BOT_EFFORT
350
368
  write(profile, read(profile).replace(/^ agent-(model|effort):.*\n/gm, ''));
351
369
  write(`${s.box.work}/collectors/local.env`, 'YZJ_BOT_AGENT="dsh"\nYZJ_BOT_MODEL="opencode-go/deepseek-v4.1-flash"\nYZJ_BOT_EFFORT="high"\n');
352
370
  assert.equal(s.rhythm(['run', 'daily-plan'], env).code, 0);
353
- assert.match(read(`${s.box.work}/01-inbox/_rhythm/dsh-headless.patch.yml`), / model: deepseek-v4\.1-flash\n reasoningEffort: high\n/);
371
+ assert.ok(patches().some((p) => / model: deepseek-v4\.1-flash\n reasoningEffort: high\n/.test(p)), patches().join('\n'));
372
+ assert.equal(patches().length, 2, '两套模型各一份覆盖文件');
354
373
  });
355
374
 
356
375
  // ---------------------------------------------------------------- 值守跟着服务一起跑
@@ -377,7 +396,10 @@ test('rhythm:YZJ_BOT_LISTEN=1 时值守在服务的同一个进程里跑;配
377
396
  assert.match(botLog, /会话=值守自己的专属会话/);
378
397
  assert.equal((await fetch(`http://127.0.0.1:${port}/`)).status, 200);
379
398
  assert.match(s.rhythm(['status'], { ...botEnv, YZJ_BOT_LISTEN: '1' }).stdout, /值守:开着,最近 .*/);
380
- assert.match(s.rhythm(['doctor'], { ...botEnv, YZJ_BOT_LISTEN: '1', YZJ_MY_OPEN_ID: 'me-0001' }).stdout, /^$/);
399
+ // 没有问题;只有一行「注意」说路由没开(不算问题,退出码 0)
400
+ const fine = s.rhythm(['doctor'], { ...botEnv, YZJ_BOT_LISTEN: '1', YZJ_MY_OPEN_ID: 'me-0001' });
401
+ assert.equal(fine.code, 0, fine.out);
402
+ assert.match(fine.stdout, /^注意:路由没开(profile 的 rhythm\.router 没写)[\s\S]*\n$/);
381
403
  // 关着的时候什么都不起
382
404
  assert.match(s.rhythm(['status'], botEnv).stdout, /值守:关着/);
383
405
  // 配置不齐(没写我的 openId):doctor 报出来;服务照样起,只记「值守没开」
@@ -405,12 +427,24 @@ test('rhythm install:装的是服务那一个常驻,老的单独值守常驻
405
427
  const agents = path.join(home, 'Library', 'LaunchAgents');
406
428
  fs.mkdirSync(agents, { recursive: true });
407
429
  write(path.join(agents, 'work-rhythm.bot.work.plist'), '<plist/>');
408
- const env = { ...s.env, HOME: home };
430
+ const env = { ...s.env, HOME: home, STUB_LAUNCHCTL_RUNNING: '1' };
409
431
  assert.equal(s.rhythm(['install'], env).code, 0, s.rhythm(['install'], env).out);
432
+ // 装完核对过真的起来了(假的 launchctl 说在跑);plist 里绑的是真正的 node
433
+ assert.equal(require('../lib/launchd').plistNode(path.join(agents, 'work-rhythm.service.work.plist')), process.execPath);
434
+ assert.equal(s.rhythm(['doctor'], env).code, 0, s.rhythm(['doctor'], env).out);
435
+ // launchd 说没在跑:install 不报成功,带着日志说清
436
+ const notUp = s.rhythm(['install'], { ...s.env, HOME: home });
437
+ assert.equal(notUp.code, 5);
438
+ assert.match(notUp.stderr, /装是装上了,但 launchd 没能把它拉起来。先看 .*_rhythm\.launchd\.log/);
439
+ // 装坏的 plist(绑的是 DSH 的 Electron 包):doctor 报出来
440
+ write(path.join(agents, 'work-rhythm.service.work.plist'), '<key>ProgramArguments</key><array><string>/Users/x/.dsh-desktop/sidecar-node/1/DSH Node.app/Contents/MacOS/DSH Node</string></array>');
441
+ const bad = s.rhythm(['doctor'], env);
442
+ assert.equal(bad.code, 1);
443
+ assert.match(bad.stdout, /常驻的 plist 里绑的不是真正的 node(.*DSH Node\.app\/Contents\/MacOS\/DSH Node):work-rhythm rhythm uninstall 再 install 一次/);
410
444
  assert.ok(exists(path.join(agents, 'work-rhythm.service.work.plist')));
411
445
  assert.equal(exists(path.join(agents, 'work-rhythm.bot.work.plist')), false, '老的单独值守常驻收掉');
412
446
  assert.match(read(s.env.STUB_LAUNCHCTL), /bootout gui\/\d+\/work-rhythm\.bot\.work\n/);
413
- const restart = s.rhythm(['restart'], env);
447
+ const restart = s.rhythm(['restart'], { ...s.env, HOME: home });
414
448
  assert.equal(restart.code, 3, 'launchd 说没在跑就不重启');
415
449
  assert.match(restart.stderr, /服务不是 launchd 管的常驻/);
416
450
  const again = s.rhythm(['restart'], { ...env, STUB_LAUNCHCTL_RUNNING: '1' });
@@ -0,0 +1,80 @@
1
+ // 自测里假 agent 的「脑子」:认 work-rhythm 的两种提示词,决定该回什么。
2
+ // 路由那一轮(以「【work-rhythm 路由】」开头):按 STUB_ROUTER_MODE / STUB_ROUTER_REPLY 回一段决定
3
+ // 执行者那一句(「读 .agents/handoff/<短号>.md(任务书)…」):读任务书,算出回执的正文
4
+ // 各家假的命令行(stubs.js)拿到结果后按自己的输出格式包一层。不碰真实账号。
5
+ 'use strict';
6
+ const fs = require('node:fs');
7
+
8
+ const read = (rel) => {
9
+ try {
10
+ return fs.readFileSync(rel, 'utf8');
11
+ } catch {
12
+ return '';
13
+ }
14
+ };
15
+
16
+ // 默认的决定:消息类的原样转述(dispatch + 任务书),定时任务 dispatch,汇报 notify 回执正文
17
+ function defaultReply(prompt) {
18
+ const out = ['决定:'];
19
+ const sections = [];
20
+ for (const line of prompt.split('\n')) {
21
+ let m = /^\[(t-\d+)\] 来源=(message|manual) 时间=\S+ \S+ 原话:(.*)$/.exec(line);
22
+ if (m) {
23
+ out.push(`- ${m[1]} dispatch`);
24
+ sections.push(`## handoff ${m[1]}\n# 任务:转述\n\n把这句话原样回复给我:「${m[3]}」`);
25
+ continue;
26
+ }
27
+ m = /^\[(t-\d+)\] 来源=schedule /.exec(line);
28
+ if (m) {
29
+ out.push(`- ${m[1]} dispatch`);
30
+ continue;
31
+ }
32
+ m = /^\[(t-\d+)\] 来源=report 时间=\S+ \S+ 对应=(t-\d+) 结果=(成功|失败)(?: 用时=\d+s)?(?: 原因=(.*?))? 回执=(\S+)/.exec(line);
33
+ if (m) {
34
+ out.push(`- ${m[1]} notify`);
35
+ const body = read(m[5]).replace(/^# .*\n\n?(- .*\n)*\n?/, '').trim();
36
+ sections.push(`## notify ${m[1]}\n${m[3] === '成功' ? body : `没做成:${m[4] || ''}`}`);
37
+ }
38
+ }
39
+ return `${out.join('\n')}\n\n${sections.join('\n\n')}\n`;
40
+ }
41
+
42
+ // 执行者的回执正文:任务书里写了「把这句话原样回复给我:「…」」就回那句;定时任务回「做了:<标题>」
43
+ function workerText(taskRel) {
44
+ const task = read(taskRel);
45
+ const m = /把这句话原样回复给我:「(.*)」/.exec(task);
46
+ if (m) return m[1];
47
+ const title = /^#?\s*任务[::]\s*(.+)$/m.exec(task);
48
+ return `做了:${title ? title[1].trim().replace(/[。.]\s*$/, '') : '按任务书做完'}`;
49
+ }
50
+
51
+ // args 是假命令行收到的参数。返回 null(不是这两种提示词)或 { kind, text, taskRel, resultRel, delay }
52
+ function forArgs(args) {
53
+ const prompt = String(args[args.length - 1] || '');
54
+ if (prompt.startsWith('【work-rhythm 路由】')) {
55
+ try {
56
+ fs.appendFileSync(process.env.STUB_ROUTER_CALLS || '/dev/null', `${prompt}\n⏎⏎⏎\n`);
57
+ } catch {
58
+ // 没指定文件就不记
59
+ }
60
+ const mode = process.env.STUB_ROUTER_MODE || '';
61
+ if (mode === 'garbage') return { kind: 'router', text: '好的,我来想想怎么安排。' };
62
+ if (mode === 'timeout') return { kind: 'hang', delay: Number(process.env.STUB_ROUTER_DELAY) || 8, text: '太晚了' };
63
+ const file = process.env.STUB_ROUTER_REPLY || '';
64
+ if (file && fs.existsSync(file)) return { kind: 'router', text: fs.readFileSync(file, 'utf8') };
65
+ return { kind: 'router', text: defaultReply(prompt) };
66
+ }
67
+ const m = /^读 (\S+)(任务书),照它做完,把回执写到 (\S+);/.exec(prompt);
68
+ if (!m) return null;
69
+ return { kind: 'worker', text: workerText(m[1]), taskRel: m[1], resultRel: m[2] };
70
+ }
71
+
72
+ // 执行者自己写回执(STUB_WORKER_WRITES=1 时):真的执行者写文件,假的也写
73
+ function writeResult(resultRel, text) {
74
+ if (process.env.STUB_WORKER_WRITES !== '1') return false;
75
+ fs.mkdirSync(require('node:path').dirname(resultRel), { recursive: true });
76
+ fs.writeFileSync(resultRel, `# 回执\n\n${text}\n`);
77
+ return true;
78
+ }
79
+
80
+ module.exports = { forArgs, writeResult, defaultReply, workerText };