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,165 @@
1
+ // 路由和执行者之间传内容的交接文档,都放在工作目录的 .agents/handoff/ 下:任务书 t-000123.md、回执 t-000123.result.md。
2
+ // 提示词里只带路径,不带正文(docs/router-worker.md 的「交接文档」)。这里还管路由回复的解析:它回一段 Markdown,
3
+ // 先列决定行(「- t-000123 dispatch」),要文字的决定再各给一个小节(「## handoff t-000123」)。
4
+ // 文件名只认 t-数字.md 和 t-数字.result.md 两种,网页服务按这个放行。只用 node 自带的能力。
5
+ 'use strict';
6
+ const fs = require('node:fs');
7
+ const path = require('node:path');
8
+
9
+ const DIR = '.agents/handoff';
10
+ const NAME_RE = /^(t-\d+)(\.result)?\.md$/;
11
+ const ACTIONS = ['dispatch', 'continue', 'stop', 'interrupt', 'reply', 'ignore', 'notify'];
12
+ const SECTION_RE = /^##[ \t]+(reply|ignore|handoff|notify)[ \t]+(t-\d+)[ \t]*.*$/;
13
+ const DECISION_RE = /^[ \t]*-?[ \t]*(t-\d+)[ \t]+(dispatch|continue|stop|interrupt|reply|ignore|notify)(?:[ \t]+(t-\d+))?[ \t]*$/;
14
+ const MARKER = '【work-rhythm 路由】';
15
+ const DAY_MS = 24 * 3600 * 1000;
16
+
17
+ const dir = (root) => path.join(root, DIR);
18
+ const relTask = (id) => `${DIR}/${id}.md`;
19
+ const relResult = (id) => `${DIR}/${id}.result.md`;
20
+ const taskPath = (root, id) => path.join(dir(root), `${id}.md`);
21
+ const resultPath = (root, id) => path.join(dir(root), `${id}.result.md`);
22
+
23
+ const readText = (file) => {
24
+ try {
25
+ return fs.readFileSync(file, 'utf8');
26
+ } catch {
27
+ return '';
28
+ }
29
+ };
30
+
31
+ // 回执在不在、是不是空的
32
+ function resultReady(root, id) {
33
+ try {
34
+ return fs.statSync(resultPath(root, id)).size > 0;
35
+ } catch {
36
+ return false;
37
+ }
38
+ }
39
+
40
+ // 回执的开头几句:汇报给路由时带上,不用读文件就能判断要不要理它
41
+ function opening(text, max = 300) {
42
+ const flat = String(text || '').replace(/^#.*$/gm, '').replace(/\s+/g, ' ').trim();
43
+ return flat.length > max ? `${flat.slice(0, max)}…` : flat;
44
+ }
45
+
46
+ // 任务书的一级标题当这件事的标题(路由自己写的,不是原话)
47
+ function titleOf(body) {
48
+ const m = /^#[ \t]+(.+)$/m.exec(String(body || ''));
49
+ return m ? m[1].trim().slice(0, 60) : '';
50
+ }
51
+
52
+ function write(file, text) {
53
+ fs.mkdirSync(path.dirname(file), { recursive: true });
54
+ fs.writeFileSync(file, text);
55
+ return file;
56
+ }
57
+
58
+ // 任务书。t 是触发记录(id、kind、at、text…),body 是要求(路由写的 handoff 小节,或 tasks/<id>.md 的全文),extra 填表头
59
+ function taskText(t, body, extra = {}) {
60
+ const when = String(t.at || '').slice(5, 16);
61
+ const source = {
62
+ message: `message(云之家,${when})· 原话:「${t.text || ''}」`,
63
+ manual: `manual(命令行 trigger fire,${when})· 原话:「${t.text || ''}」`,
64
+ schedule: `schedule(到点 ${when})· 任务:${t.task || ''}(${t.taskFile || ''})`,
65
+ report: `report(${when})· 重做 ${t.of || ''} 那件事`,
66
+ }[t.kind] || t.kind;
67
+ const lines = [
68
+ `# 任务书 ${t.id}`,
69
+ '',
70
+ `- 来源:${source}`,
71
+ `- 派给:执行者 · 权限 ${extra.mode || 'plan'} · 最多 ${extra.timeoutS || 300} 秒`,
72
+ `- ${t.kind === 'report' ? '重做自' : '续做自'}:${t.kind === 'report' ? t.of || '' : extra.continueOf || '无'}`,
73
+ '',
74
+ '## 要求',
75
+ '',
76
+ String(body || '').trim(),
77
+ '',
78
+ '## 回执',
79
+ '',
80
+ `做完把结果写到 \`${relResult(t.id)}\`:做了什么、改了哪些文件、要留意什么、有几件事等我拿主意。`,
81
+ '取不到的数据写「未取到」,不要编。要改动外部系统(发消息、改日程、流转工作项)的事不要做,写进回执让我定。',
82
+ '没有写权限就把同样内容作为最后一段话输出。纯文本,不放链接。不要向我提问,不要等待确认,不要自己发消息。',
83
+ '',
84
+ ];
85
+ return lines.join('\n');
86
+ }
87
+
88
+ const writeTask = (root, t, body, extra) => write(taskPath(root, t.id), taskText(t, body, extra));
89
+
90
+ // 回执。执行者自己写的优先;它没写(只读、忘了、没跑成)时由 CLI 落盘,注明是谁写的
91
+ function resultText(id, body, { ok = true, reason = '', seconds = 0, agent = '', by = '' } = {}) {
92
+ const head = [
93
+ `# 回执 ${id}`,
94
+ '',
95
+ `- 结果:${ok ? '成功' : '失败'}${reason ? ` · 原因:${reason}` : ''}${seconds ? ` · 用时 ${seconds} 秒` : ''}${agent ? ` · 执行者 ${agent}` : ''}`,
96
+ `- ${by === 'cli' ? '由 CLI 从执行者最后的回答落盘' : by === 'cli-fail' ? '由 CLI 落盘(执行者没留下回执)' : '执行者写的'}`,
97
+ '',
98
+ ].join('\n');
99
+ return `${head}\n${String(body || '').trim()}\n`;
100
+ }
101
+
102
+ const writeResult = (root, id, body, meta) => write(resultPath(root, id), resultText(id, body, meta));
103
+
104
+ // 过期的交接文档清掉,返回清了几个。按文件的修改时间算
105
+ function cleanup(root, keepDays, now = Date.now()) {
106
+ const cutoff = now - keepDays * DAY_MS;
107
+ let names;
108
+ try {
109
+ names = fs.readdirSync(dir(root));
110
+ } catch {
111
+ return 0;
112
+ }
113
+ let removed = 0;
114
+ for (const name of names) {
115
+ if (!NAME_RE.test(name)) continue;
116
+ const file = path.join(dir(root), name);
117
+ try {
118
+ if (fs.statSync(file).mtimeMs < cutoff) {
119
+ fs.unlinkSync(file);
120
+ removed += 1;
121
+ }
122
+ } catch {
123
+ // 刚好被别的进程动了
124
+ }
125
+ }
126
+ return removed;
127
+ }
128
+
129
+ // 解析路由的回复 → 决定的数组 [{ id, action, target?, handoff?, text? }]。
130
+ // 决定行在任务书小节外面都认(任务书正文里的不认);只有小节没有决定行的,从小节标题认动作
131
+ function parseRouterReply(text) {
132
+ const found = {};
133
+ const pick = (id) => found[id] || (found[id] = { id });
134
+ let section = null; // 当前在哪个小节里:{ kind, id, lines }
135
+ const sections = [];
136
+ for (const raw of String(text || '').split('\n')) {
137
+ const m = SECTION_RE.exec(raw);
138
+ if (m) {
139
+ section = { kind: m[1], id: m[2], lines: [] };
140
+ sections.push(section);
141
+ continue;
142
+ }
143
+ if (section) section.lines.push(raw);
144
+ const d = (!section || section.kind !== 'handoff') ? DECISION_RE.exec(raw) : null;
145
+ if (d) {
146
+ const it = pick(d[1]);
147
+ it.action = d[2];
148
+ if (d[3]) it.target = d[3];
149
+ }
150
+ }
151
+ for (const s of sections) {
152
+ const it = pick(s.id);
153
+ it[s.kind] = s.lines.join('\n').trim();
154
+ if (!it.action) it.action = s.kind === 'handoff' ? 'dispatch' : s.kind;
155
+ }
156
+ return Object.values(found).map((it) => ({
157
+ id: it.id,
158
+ action: ACTIONS.includes(it.action) ? it.action : '',
159
+ target: it.target || '',
160
+ handoff: it.handoff || '',
161
+ text: it.reply || it.notify || it.ignore || '',
162
+ }));
163
+ }
164
+
165
+ module.exports = { DIR, NAME_RE, MARKER, dir, relTask, relResult, taskPath, resultPath, readText, resultReady, opening, titleOf, taskText, writeTask, resultText, writeResult, cleanup, parseRouterReply };
@@ -23,6 +23,26 @@ function bootout(kind, root) {
23
23
 
24
24
  const escapeXml = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
25
25
 
26
+ // 看着像 Electron 包的可执行文件(…/DSH Node.app/Contents/MacOS/DSH Node):靠 ELECTRON_RUN_AS_NODE 当 node 用,
27
+ // 被 launchd 直接拉起时找不到 helper app,启动即退
28
+ const looksLikeElectron = (file, env) => /\.app\//.test(file) || env.ELECTRON_RUN_AS_NODE === '1' && !/(^|\/)node$/.test(file);
29
+
30
+ // 写进 plist 的 node:要真正的 node。从桌面 agent(DSH、ZCode)的工具里跑 install 时 process.execPath 是它们自带的 Electron 包,
31
+ // 所以 execPath 看着像 Electron 就另找一个:先 PATH 上的 node,再 homebrew / usr/local 的常见位置。都找不到才用它,并让 doctor 报出来
32
+ function nodeForLaunchd(env = process.env) {
33
+ const current = process.execPath;
34
+ if (!looksLikeElectron(current, env)) return current;
35
+ const onPath = spawnSync('/usr/bin/which', ['node'], { encoding: 'utf8', env });
36
+ const candidates = [onPath.status === 0 ? onPath.stdout.trim() : '', '/opt/homebrew/bin/node', '/usr/local/bin/node'];
37
+ return candidates.find((c) => c && fs.existsSync(c) && !looksLikeElectron(c, env)) || current;
38
+ }
39
+
40
+ // 已经装好的 plist 里绑的是什么 node:读 ProgramArguments 的第一项
41
+ function plistNode(plist) {
42
+ const m = /<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]+)<\/string>/.exec(fs.readFileSync(plist, 'utf8'));
43
+ return m ? m[1] : '';
44
+ }
45
+
26
46
  // 写 plist 并装上。args 是子命令和它的参数(跟在入口后面)。日志写进 logFile
27
47
  function install({ kind, root, entry, args, logFile }) {
28
48
  needLaunchd();
@@ -34,14 +54,14 @@ function install({ kind, root, entry, args, logFile }) {
34
54
  <key>Label</key><string>${escapeXml(label(kind, root))}</string>
35
55
  <key>ProgramArguments</key>
36
56
  <array>
37
- <string>${escapeXml(process.execPath)}</string>
57
+ <string>${escapeXml(nodeForLaunchd())}</string>
38
58
  <string>${escapeXml(entry)}</string>
39
59
  ${args.map((a) => ` <string>${escapeXml(a)}</string>`).join('\n')}
40
60
  </array>
41
61
  <key>WorkingDirectory</key><string>${escapeXml(root)}</string>
42
62
  <key>EnvironmentVariables</key>
43
63
  <dict>
44
- <key>PATH</key><string>${escapeXml(path.dirname(process.execPath))}:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
64
+ <key>PATH</key><string>${escapeXml(path.dirname(nodeForLaunchd()))}:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
45
65
  <key>HOME</key><string>${escapeXml(os.homedir())}</string>
46
66
  <key>LANG</key><string>zh_CN.UTF-8</string>
47
67
  </dict>
@@ -61,6 +81,32 @@ ${args.map((a) => ` <string>${escapeXml(a)}</string>`).join('\n')}
61
81
  return plist;
62
82
  }
63
83
 
84
+ // 装完核对它真的起来了:launchd 拉起失败(绑错了 node、端口被占)时 install 也会报「已装成常驻」,要等几秒看一眼。
85
+ // 返回问题(空串就是起来了)
86
+ function startupProblem(kind, root, logFile, { waitMs = 4000 } = {}) {
87
+ const until = Date.now() + waitMs;
88
+ const syncWait = (ms) => spawnSync(process.execPath, ['-e', `setTimeout(() => {}, ${ms})`]);
89
+ let last = '';
90
+ for (;;) {
91
+ const s = status(kind, root);
92
+ if (s.running) return '';
93
+ last = tail(readText(logFile), 300);
94
+ if (Date.now() >= until) break;
95
+ syncWait(500);
96
+ }
97
+ const node = plistNode(plistPath(kind, root));
98
+ const why = looksLikeElectron(node, {}) ? `plist 里绑的不是真正的 node(${node})` : '';
99
+ return `装是装上了,但 launchd 没能把它拉起来${why ? `:${why}` : ''}。先看 ${logFile}${last ? `,最后几行是:${last}` : ''}`;
100
+ }
101
+
102
+ const readText = (file) => {
103
+ try {
104
+ return fs.readFileSync(file, 'utf8');
105
+ } catch {
106
+ return '';
107
+ }
108
+ };
109
+
64
110
  function uninstall(kind, root) {
65
111
  needLaunchd();
66
112
  bootout(kind, root);
@@ -86,4 +132,4 @@ function status(kind, root) {
86
132
  return { running: r.status === 0, pid: pid ? Number(pid[1]) : 0 };
87
133
  }
88
134
 
89
- module.exports = { label, plistPath, install, uninstall, kickstart, status };
135
+ module.exports = { label, plistPath, looksLikeElectron, nodeForLaunchd, plistNode, install, uninstall, kickstart, startupProblem, status };