work-rhythm 0.0.0-stage → 0.1.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.
Files changed (107) hide show
  1. package/.agents/notes/AGENTS.md +86 -0
  2. package/.agents/notes/decisions/2026-11-28-long-term-goals-ride-existing-tasks.md +36 -0
  3. package/.agents/notes/decisions/2026-11-29-building-a-workdir-means-cloning-the-template.md +25 -0
  4. package/.agents/notes/decisions/2026-11-29-find-workdir-cwd-first-then-registered.md +32 -0
  5. package/.agents/notes/decisions/2026-11-30-bot-inbound-uses-websocket-and-a-responder-command.md +48 -0
  6. package/.agents/notes/decisions/2026-11-30-cost-entry-writes-into-empty-cells-directly.md +25 -0
  7. package/.agents/notes/decisions/2026-11-30-dependencies-are-allowed-user-installs-missing-ones.md +30 -0
  8. package/.agents/notes/decisions/2026-11-30-markdown-is-the-record-html-is-only-a-view.md +25 -0
  9. package/.agents/notes/decisions/2026-11-30-message-channels-are-preset-in-the-skill.md +34 -0
  10. package/.agents/notes/decisions/2026-11-30-no-workdir-offers-to-create-one-by-default.md +35 -0
  11. package/.agents/notes/decisions/2026-11-30-paging-requires-coverage-only-when-enabled.md +27 -0
  12. package/.agents/notes/decisions/2026-11-30-pending-decisions-asked-in-a-chat-and-logged-briefly.md +39 -0
  13. package/.agents/notes/decisions/2026-11-30-push-via-personal-robot-webhook.md +33 -0
  14. package/.agents/notes/decisions/2026-11-30-scheduling-moves-to-a-local-service.md +37 -0
  15. package/.agents/notes/decisions/2026-11-30-skill-ships-with-its-template-in-a-zip.md +30 -0
  16. package/.agents/notes/decisions/2026-11-30-skill-stays-generic-user-provides-cli-or-mcp.md +25 -0
  17. package/.agents/notes/decisions/2026-12-01-everything-is-js-behind-work-rhythm.md +46 -0
  18. package/.agents/notes/decisions/2026-12-01-repo-is-not-a-workdir-templates-hold-workdir-files.md +29 -0
  19. package/.agents/notes/decisions/2026-12-01-repo-stays-generic-personal-data-lives-in-workdirs.md +32 -0
  20. package/.agents/notes/decisions/2026-12-01-workdir-is-not-a-git-repository.md +25 -0
  21. package/.agents/notes/pitfalls/2026-11-29-do-not-hand-roll-git-log.md +22 -0
  22. package/.agents/notes/pitfalls/2026-11-29-empty-or-partial-collector-output.md +23 -0
  23. package/.agents/notes/pitfalls/2026-11-29-skill-description-is-truncated.md +21 -0
  24. package/.agents/notes/pitfalls/2026-11-29-tool-shell-is-zsh.md +24 -0
  25. package/.agents/notes/pitfalls/2026-11-30-compare-timestamps-as-digits.md +22 -0
  26. package/.agents/notes/pitfalls/2026-11-30-message-search-lags-after-sending.md +18 -0
  27. package/.agents/notes/pitfalls/2026-11-30-rewriting-a-file-with-empty-output-after-tool-failure.md +20 -0
  28. package/.agents/notes/pitfalls/2026-11-30-secret-scan-false-positive-on-hyphenated-file-names.md +18 -0
  29. package/.agents/notes/pitfalls/2026-11-30-selftest-must-not-inherit-local-config.md +29 -0
  30. package/.agents/notes/pitfalls/2026-11-30-yzj-cli-list-limit-is-20.md +25 -0
  31. package/.agents/notes/pitfalls/2026-11-30-zsh-no-word-splitting-special-names.md +23 -0
  32. package/.agents/notes/pitfalls/2026-12-01-node-test-hooks-cannot-register-after-callbacks.md +22 -0
  33. package/.agents/notes/pitfalls/2026-12-01-spawning-node-test-inside-a-test-runs-nothing.md +18 -0
  34. package/.agents/skills/work-rhythm/SKILL.md +278 -0
  35. package/AGENTS.md +19 -0
  36. package/README.md +69 -2
  37. package/collectors/approval-yzj.js +114 -0
  38. package/collectors/calendar-yzj.js +48 -0
  39. package/collectors/file-activity.js +131 -0
  40. package/collectors/git-activity.js +105 -0
  41. package/collectors/im-yzj.js +151 -0
  42. package/collectors/linky-issues.js +88 -0
  43. package/collectors/local.env.example +52 -0
  44. package/docs/channels.md +95 -0
  45. package/docs/formats.md +285 -0
  46. package/docs/im-adapters.md +79 -0
  47. package/docs/scheduled-tasks.md +115 -0
  48. package/docs/sources.md +104 -0
  49. package/package.json +35 -4
  50. package/scripts/cli.js +101 -0
  51. package/scripts/cmd/check.js +330 -0
  52. package/scripts/cmd/collect.js +25 -0
  53. package/scripts/cmd/decisions.js +236 -0
  54. package/scripts/cmd/goals.js +145 -0
  55. package/scripts/cmd/init.js +49 -0
  56. package/scripts/cmd/listen.js +91 -0
  57. package/scripts/cmd/notify.js +42 -0
  58. package/scripts/cmd/pack.js +104 -0
  59. package/scripts/cmd/rhythm.js +102 -0
  60. package/scripts/cmd/selftest.js +23 -0
  61. package/scripts/cmd/sync.js +73 -0
  62. package/scripts/cmd/today.js +29 -0
  63. package/scripts/cmd/workdir.js +81 -0
  64. package/scripts/lib/agent.js +270 -0
  65. package/scripts/lib/bot.js +376 -0
  66. package/scripts/lib/collector.js +74 -0
  67. package/scripts/lib/config.js +250 -0
  68. package/scripts/lib/launchd.js +82 -0
  69. package/scripts/lib/log.js +22 -0
  70. package/scripts/lib/markdown.js +208 -0
  71. package/scripts/lib/notify.js +43 -0
  72. package/scripts/lib/rhythm.js +508 -0
  73. package/scripts/lib/robot.js +64 -0
  74. package/scripts/lib/run.js +151 -0
  75. package/scripts/lib/template.js +149 -0
  76. package/scripts/lib/workdir.js +98 -0
  77. package/scripts/test/check.test.js +279 -0
  78. package/scripts/test/collectors.test.js +574 -0
  79. package/scripts/test/config.test.js +118 -0
  80. package/scripts/test/decisions.test.js +129 -0
  81. package/scripts/test/fake-webhook.js +31 -0
  82. package/scripts/test/goals.test.js +109 -0
  83. package/scripts/test/harness.js +277 -0
  84. package/scripts/test/init.test.js +123 -0
  85. package/scripts/test/listen.test.js +362 -0
  86. package/scripts/test/notify.test.js +176 -0
  87. package/scripts/test/pack.test.js +141 -0
  88. package/scripts/test/rhythm.test.js +333 -0
  89. package/scripts/test/stubs.js +140 -0
  90. package/scripts/test/today.test.js +73 -0
  91. package/scripts/test/workdir.test.js +152 -0
  92. package/scripts/work-rhythm.js +18 -0
  93. package/tasks/alerts-morning.md +24 -0
  94. package/tasks/carryover.md +16 -0
  95. package/tasks/daily-plan.md +29 -0
  96. package/tasks/evening-review.md +27 -0
  97. package/tasks/linky-cost-check.md +13 -0
  98. package/tasks/linky-cost-fill.md +20 -0
  99. package/tasks/noon-checkin.md +15 -0
  100. package/tasks/weekly-rhythm.md +18 -0
  101. package/templates/00-config/profile.example.yaml +54 -0
  102. package/templates/00-config/sources.yaml +115 -0
  103. package/templates/03-carryover/CARRYOVER.md +14 -0
  104. package/templates/03-carryover/DECISIONS.md +10 -0
  105. package/templates/04-patterns/WORK_RHYTHM.md +16 -0
  106. package/templates/AGENTS.md +31 -0
  107. package/templates/README.md +73 -0
@@ -0,0 +1,508 @@
1
+ // work-rhythm 本地服务的实现,入口是 work-rhythm rhythm(用法写在 cmd/rhythm.js)。四件事:
2
+ // 1 定时采集:按 profile 的 rhythm.sync 跑一遍 sync,数据落 01-inbox/;
3
+ // 2 定时整理:按 profile 的 schedule 把 tasks/<id>.md 的指令交给 agent 跑一遍(怎么调起 agent 见 agent.js);
4
+ // 3 推送:整理完把 agent 的总结经消息渠道(notify.js)发给我,附一个本机地址;
5
+ // 4 看页面:只绑 127.0.0.1 的网页服务,把工作目录里的 Markdown 现渲染成 HTML(markdown.js)。
6
+ // 任务是一个个子进程跑的,调度不被堵住;一次只跑一个,后面的排队。错过的任务在 5 分钟内还会补跑,再久就不追了。
7
+ // 只用 node 自带的能力。日志写 01-inbox/_rhythm.log,状态写 01-inbox/_rhythm/state.json。
8
+ 'use strict';
9
+ const { spawn } = require('node:child_process');
10
+ const fs = require('node:fs');
11
+ const http = require('node:http');
12
+ const path = require('node:path');
13
+ const { EXIT, Fail, fmtDate, fmtStamp, pad, tail, readText, writeFileAtomic } = require('./run');
14
+ const { loadProfile } = require('./config');
15
+ const { logger } = require('./log');
16
+ const { createAgent } = require('./agent');
17
+ const { notifyChannel, pushText } = require('./notify');
18
+ const md = require('./markdown');
19
+ const launchd = require('./launchd');
20
+ const sync = require('../cmd/sync');
21
+ const today = require('../cmd/today');
22
+
23
+ const TICK_MS = 20000;
24
+ const CATCH_UP_MS = 5 * 60 * 1000;
25
+ const WEEKDAYS = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 };
26
+ const WEEKDAY_CN = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
27
+ // 这些要等我回答,不当定时任务:推送里会说有几件等我定,我对任何一个能读到这个工作目录的 agent 说「有什么要我定」就开始
28
+ const NOT_SERVICE_TASKS = ['ask-decisions'];
29
+ // 任务跑完推送时附哪个页面(本机网页服务上的地址)
30
+ const LINKS = {
31
+ 'daily-plan': { path: (d) => `/day/${d}`, label: '今天的文件' },
32
+ 'noon-checkin': { path: (d) => `/day/${d}`, label: '今天的文件' },
33
+ 'evening-review': { path: (d) => `/day/${d}`, label: '今天的文件' },
34
+ 'weekly-rhythm': { path: () => '/rhythm', label: '工作规律' },
35
+ 'alerts-morning': { path: (d) => `/reports/${d}-alerts.html`, label: '告警晨报' },
36
+ };
37
+ const NAV = [['/', '今日'], ['/carryover', '遗留'], ['/decisions', '决定'], ['/rhythm', '规律'], ['/goals', '目标'], ['/reports', '报告']];
38
+
39
+ const positiveInt = (value, fallback) => {
40
+ const n = Number(value);
41
+ return Number.isInteger(n) && n > 0 ? n : fallback;
42
+ };
43
+ const hhmm = (d) => `${pad(d.getHours())}:${pad(d.getMinutes())}`;
44
+ const asList = (value) => (Array.isArray(value) ? value.map((v) => String(v).trim()).filter(Boolean) : []);
45
+
46
+ // ---------------------------------------------------------------- 配置
47
+ function loadConfig(root) {
48
+ const profile = loadProfile(root);
49
+ const rhythm = profile.rhythm && typeof profile.rhythm === 'object' ? profile.rhythm : {};
50
+ const preferences = profile.preferences && typeof profile.preferences === 'object' ? profile.preferences : {};
51
+ const schedule = profile.schedule && typeof profile.schedule === 'object' ? profile.schedule : {};
52
+ return {
53
+ sync: typeof rhythm.sync === 'string' ? rhythm.sync.trim() : '',
54
+ port: positiveInt(rhythm.port, 8787),
55
+ push: rhythm.push !== false,
56
+ quiet: asList(rhythm.quiet),
57
+ agentMode: typeof rhythm['agent-mode'] === 'string' && rhythm['agent-mode'].trim() ? rhythm['agent-mode'].trim() : 'edit',
58
+ taskTimeout: positiveInt(rhythm['task-timeout'], 1200),
59
+ syncTimeout: positiveInt(rhythm['sync-timeout'], 600),
60
+ notifyChannel: typeof preferences.notify === 'string' ? preferences.notify.trim() : '',
61
+ schedule,
62
+ };
63
+ }
64
+
65
+ // 时间的写法:"08:50"(工作日)、"Fri 16:30"、"工作日 09:00-18:00 每 30 分钟"。空串是关着(返回 null)
66
+ function parseSpec(spec) {
67
+ const s = String(spec || '').trim();
68
+ if (!s) return null;
69
+ let m = /^(?:工作日\s*)?(\d{1,2}):(\d{2})\s*-\s*(\d{1,2}):(\d{2})\s*每\s*(\d+)\s*分钟$/.exec(s);
70
+ if (m) {
71
+ const start = Number(m[1]) * 60 + Number(m[2]);
72
+ const end = Number(m[3]) * 60 + Number(m[4]);
73
+ const every = Number(m[5]);
74
+ if (start >= end || every < 1) return { problem: `时间段不对:${s}` };
75
+ return { kind: 'interval', workdaysOnly: true, start, end, every };
76
+ }
77
+ m = /^(工作日\s*)?([A-Za-z]{3})\s+(\d{1,2}):(\d{2})$/.exec(s);
78
+ if (m) {
79
+ const weekday = WEEKDAYS[m[2][0].toUpperCase() + m[2].slice(1, 3).toLowerCase()];
80
+ if (weekday === undefined) return { problem: `不认识的星期:${s}` };
81
+ return { kind: 'weekly', weekday, minute: Number(m[3]) * 60 + Number(m[4]), workdaysOnly: Boolean(m[1]) };
82
+ }
83
+ m = /^(?:工作日\s*)?(\d{1,2}):(\d{2})$/.exec(s);
84
+ if (m) {
85
+ if (Number(m[1]) > 23 || Number(m[2]) > 59) return { problem: `时间不对:${s}` };
86
+ return { kind: 'daily', workdaysOnly: true, minute: Number(m[1]) * 60 + Number(m[2]) };
87
+ }
88
+ return { problem: `看不懂时间写法「${s}」:支持 "08:50"、"Fri 16:30"、"工作日 09:00-18:00 每 30 分钟"` };
89
+ }
90
+
91
+ // 建一个本地服务对象。env 是设置(环境变量,上面盖一层 local.env),YZJ_BOT_AGENT 在里面
92
+ function createRhythm({ root, env, packageRoot }) {
93
+ const STATE_DIR = path.join(root, '01-inbox', '_rhythm');
94
+ const STATE_FILE = path.join(STATE_DIR, 'state.json');
95
+ const PID_FILE = path.join(STATE_DIR, 'service.pid');
96
+ const LOG_FILE = path.join(root, '01-inbox', '_rhythm.log');
97
+ const LAUNCHD_LOG = path.join(root, '01-inbox', '_rhythm.launchd.log');
98
+ const ENTRY = path.join(packageRoot, 'scripts', 'work-rhythm.js');
99
+ const log = logger(LOG_FILE);
100
+ const cfg = loadConfig(root);
101
+ const baseUrl = () => `http://127.0.0.1:${cfg.port}`;
102
+
103
+ // 某一天上不上班:以 work-rhythm today 为准(作息、放假都由它判),同一天只问一次
104
+ const workdayCache = {};
105
+ function isWorkday(date) {
106
+ if (!(date in workdayCache)) workdayCache[date] = today.resolve(root, date).isWorkday;
107
+ return workdayCache[date];
108
+ }
109
+
110
+ // 某一天会触发的时间点(分钟数)
111
+ function timesOn(spec, d) {
112
+ if (!spec || spec.problem) return [];
113
+ if (spec.kind === 'weekly') {
114
+ if (d.getDay() !== spec.weekday) return [];
115
+ if (spec.workdaysOnly && !isWorkday(fmtDate(d))) return [];
116
+ return [spec.minute];
117
+ }
118
+ if (spec.workdaysOnly && !isWorkday(fmtDate(d))) return [];
119
+ if (spec.kind === 'daily') return [spec.minute];
120
+ const out = [];
121
+ for (let m = spec.start; m <= spec.end; m += spec.every) out.push(m);
122
+ return out;
123
+ }
124
+
125
+ // 服务要调度的所有条目:sync 加 schedule 里开着、又有指令文件的(缺指令文件的留给 doctor 报)
126
+ function jobs() {
127
+ const out = [];
128
+ if (cfg.sync) out.push({ id: 'sync', kind: 'sync', spec: parseSpec(cfg.sync) });
129
+ for (const [id, specText] of Object.entries(cfg.schedule)) {
130
+ if (NOT_SERVICE_TASKS.includes(id)) continue;
131
+ const spec = parseSpec(specText);
132
+ if (!spec) continue;
133
+ out.push({ id, kind: 'task', spec, hasPrompt: fs.existsSync(path.join(root, 'tasks', `${id}.md`)) });
134
+ }
135
+ return out;
136
+ }
137
+
138
+ // 从某个时间起几天里什么时候跑什么,一行一天
139
+ function due(from, days) {
140
+ const list = jobs();
141
+ const lines = [];
142
+ for (let i = 0; i < days; i += 1) {
143
+ const d = new Date(from);
144
+ d.setDate(d.getDate() + i);
145
+ d.setHours(0, 0, 0, 0);
146
+ const items = [];
147
+ for (const job of list) {
148
+ if (job.spec && job.spec.problem) {
149
+ items.push(['!!', `${job.id}(${job.spec.problem})`]);
150
+ continue;
151
+ }
152
+ for (const minute of timesOn(job.spec, d)) items.push([`${pad(Math.floor(minute / 60))}:${pad(minute % 60)}`, job.id]);
153
+ }
154
+ items.sort((a, b) => a[0].localeCompare(b[0]));
155
+ const date = fmtDate(d);
156
+ lines.push(`${date} ${WEEKDAY_CN[d.getDay()]}${isWorkday(date) ? '' : '(不上班)'}${items.length ? '' : ' 没有要跑的'}`);
157
+ for (const [time, id] of items) lines.push(` ${time} ${id}`);
158
+ }
159
+ return lines.join('\n');
160
+ }
161
+
162
+ // ---------------------------------------------------------------- 状态
163
+ function loadState() {
164
+ try {
165
+ const state = JSON.parse(fs.readFileSync(STATE_FILE, 'utf8'));
166
+ return { done: (state && state.done) || {}, runs: (state && state.runs) || {} };
167
+ } catch {
168
+ return { done: {}, runs: {} };
169
+ }
170
+ }
171
+
172
+ function saveState(state) {
173
+ fs.mkdirSync(STATE_DIR, { recursive: true });
174
+ const cutoff = Date.now() - 2 * 24 * 3600 * 1000;
175
+ for (const [key, at] of Object.entries(state.done)) {
176
+ if (new Date(key.split('@')[1]).getTime() < cutoff) delete state.done[key];
177
+ }
178
+ writeFileAtomic(STATE_FILE, `${JSON.stringify(state, null, 1)}\n`);
179
+ }
180
+
181
+ function serviceAlive() {
182
+ const pid = Number(readText(PID_FILE).trim());
183
+ if (!pid) return false;
184
+ try {
185
+ process.kill(pid, 0);
186
+ return true;
187
+ } catch {
188
+ return false;
189
+ }
190
+ }
191
+
192
+ // ---------------------------------------------------------------- 采集、任务、推送
193
+ // 跑一遍 sync(在同一个进程里),最多等 cfg.syncTimeout 秒
194
+ async function runSync() {
195
+ const t0 = Date.now();
196
+ const chunks = [];
197
+ const capture = { write: (s) => (chunks.push(String(s)), true) };
198
+ const fail = await sync.run([], { root, cwd: root, env, stdout: capture, stderr: capture, packageRoot }, { deadlineMs: t0 + cfg.syncTimeout * 1000 });
199
+ const seconds = Math.round((Date.now() - t0) / 1000);
200
+ const out = chunks.join('');
201
+ if (fail) return { ok: false, failed: `退出码 ${fail}:${tail(out, 300)}`, seconds };
202
+ return { ok: true, seconds, detail: tail(chunks.join(''), 300).replace(/\n/g, ' · ') };
203
+ }
204
+
205
+ // 经消息渠道发一段文字。渠道留空时什么都不发(不算失败);发不出去记日志
206
+ async function push(text) {
207
+ const r = await pushText(root, text, { env });
208
+ if (r.skipped) {
209
+ log('没配消息渠道,不推送');
210
+ return false;
211
+ }
212
+ if (!r.ok) log('推送失败', r.reason);
213
+ return r.ok;
214
+ }
215
+
216
+ // 跑一个任务:指令交给 agent,要推送的话把总结发给我。返回 { ok, seconds, summary?, pushed?, failed? }
217
+ async function runTask(id, wantPush) {
218
+ const file = path.join(root, 'tasks', `${id}.md`);
219
+ if (!fs.existsSync(file)) return { ok: false, failed: `缺 ${path.relative(root, file)}` };
220
+ const prompt = fs.readFileSync(file, 'utf8');
221
+ const willPush = wantPush && cfg.push && !cfg.quiet.includes(id);
222
+ // 服务会替它推送时在指令末尾注明,免得它自己再发一遍
223
+ const full = willPush ? `${prompt}\n\n(这次运行由 work-rhythm rhythm 发起:你最后写的那段总结会被它推送给用户,你自己不要再发。)` : prompt;
224
+ const agent = createAgent({ root, agent: env.YZJ_BOT_AGENT, mode: cfg.agentMode, timeoutS: cfg.taskTimeout, log, env });
225
+ const t0 = Date.now();
226
+ const r = agent.run(full, { stateDir: STATE_DIR });
227
+ const seconds = Math.round((Date.now() - t0) / 1000);
228
+ if (r.failed) {
229
+ if (willPush) await push(`「${id}」没跑完:${r.failed}`);
230
+ return { ok: false, failed: r.failed, seconds };
231
+ }
232
+ let pushed = false;
233
+ if (willPush) {
234
+ let text = r.reply.trim();
235
+ const link = LINKS[id];
236
+ // 服务没在跑时地址打不开,不附
237
+ if (link && serviceAlive()) text += `\n\n→ ${link.label}:${baseUrl()}${link.path(fmtDate(new Date()))}`;
238
+ pushed = await push(text);
239
+ }
240
+ return { ok: true, seconds, summary: r.reply.trim(), pushed };
241
+ }
242
+
243
+ // 立刻跑一次:sync 或某个任务。结果打到标准输出,返回退出码
244
+ async function runJob(id, wantPush) {
245
+ if (id === 'sync') {
246
+ const r = await runSync();
247
+ log('采集', r.ok ? `用时 ${r.seconds}s ${r.detail}` : `失败 ${r.failed}`);
248
+ process.stdout.write(r.ok ? `采集完成,用时 ${r.seconds} 秒。\n${r.detail}\n` : `采集失败:${r.failed}\n`);
249
+ return r.ok ? EXIT.OK : EXIT.FAILED;
250
+ }
251
+ const r = await runTask(id, wantPush);
252
+ log('任务', `${id} ${r.ok ? `成功 用时 ${r.seconds}s${r.pushed ? ' 已推送' : ''}` : `失败 ${r.failed}`}`);
253
+ process.stdout.write(r.ok ? `${r.summary}\n${r.pushed ? '\n(已推送)\n' : ''}` : `没跑成:${r.failed}\n`);
254
+ return r.ok ? EXIT.OK : EXIT.FAILED;
255
+ }
256
+
257
+ // 调度器用它:任务另起一个子进程跑(带着 --push),不堵住计时
258
+ function startJob(job) {
259
+ fs.mkdirSync(STATE_DIR, { recursive: true });
260
+ const fd = fs.openSync(LOG_FILE, 'a');
261
+ const child = spawn(process.execPath, [ENTRY, 'rhythm', 'run', job.id, '--push', '--workdir', root], { cwd: root, env, stdio: ['ignore', fd, fd] });
262
+ fs.closeSync(fd);
263
+ log('开始跑', `${job.id} pid=${child.pid}`);
264
+ return child;
265
+ }
266
+
267
+ // ---------------------------------------------------------------- 网页服务
268
+ const navHtml = () => NAV.map(([href, label]) => `<a href="${href}">${label}</a>`).join('');
269
+
270
+ function send(res, status, body, type = 'text/html; charset=utf-8') {
271
+ res.writeHead(status, { 'Content-Type': type, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
272
+ res.end(body);
273
+ }
274
+
275
+ const notFound = (res, what) => send(res, 404, md.page('没有这个页面', `<p class="muted">${md.escapeHtml(what)}</p>`, navHtml()));
276
+
277
+ function listFiles(dir, filter) {
278
+ try {
279
+ return fs.readdirSync(dir, { withFileTypes: true }).filter((d) => d.isFile() && filter(d.name)).map((d) => d.name).sort().reverse();
280
+ } catch {
281
+ return [];
282
+ }
283
+ }
284
+
285
+ function dailyDates() {
286
+ const dates = [];
287
+ for (const month of listFiles(path.join(root, '02-daily'), (n) => /^\d{4}-\d{2}$/.test(n)).reverse()) {
288
+ for (const f of listFiles(path.join(root, '02-daily', month), (n) => /^\d{4}-\d{2}-\d{2}\.md$/.test(n))) dates.push(f.slice(0, -3));
289
+ }
290
+ return dates.sort().reverse();
291
+ }
292
+
293
+ // 读到就渲染,读不到就回 404
294
+ function showMarkdown(res, rel, title) {
295
+ const text = readText(path.join(root, rel));
296
+ if (!text) notFound(res, `${rel} 还没有`);
297
+ else send(res, 200, md.page(title, md.render(text), navHtml()));
298
+ }
299
+
300
+ function route(req, res) {
301
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
302
+ return send(res, 405, md.page('只支持打开页面', '<p class="muted">这个服务只用来查看。</p>', navHtml()));
303
+ }
304
+ let pathname;
305
+ try {
306
+ pathname = decodeURIComponent(new URL(req.url, 'http://127.0.0.1').pathname);
307
+ } catch {
308
+ return notFound(res, '地址不对');
309
+ }
310
+ const now = fmtDate(new Date());
311
+ if (pathname === '/' || pathname === `/day/${now}`) {
312
+ const recent = dailyDates().slice(0, 14).map((d) => `<a href="/day/${d}">${d}</a>`).join(' · ');
313
+ const text = readText(path.join(root, '02-daily', now.slice(0, 7), `${now}.md`));
314
+ const head = `<p class="muted">${now} ${WEEKDAY_CN[new Date().getDay()]} · 最近的日子:${recent || '还没有每日文件'}</p>`;
315
+ return send(res, 200, md.page('今日', head + md.render(text || '今天还没有文件。'), navHtml()));
316
+ }
317
+ let m = /^\/day\/(\d{4}-\d{2}-\d{2})$/.exec(pathname);
318
+ if (m) return showMarkdown(res, `02-daily/${m[1].slice(0, 7)}/${m[1]}.md`, m[1]);
319
+ if (pathname === '/carryover') return showMarkdown(res, '03-carryover/CARRYOVER.md', '遗留待处理');
320
+ if (pathname === '/decisions') return showMarkdown(res, '03-carryover/DECISIONS.md', '待决与决定');
321
+ if (pathname === '/rhythm') return showMarkdown(res, '04-patterns/WORK_RHYTHM.md', '工作规律');
322
+ if (pathname === '/goals') {
323
+ const files = listFiles(path.join(root, '05-goals'), (n) => /^[\w-]+\.md$/.test(n));
324
+ if (!files.length) return notFound(res, '还没有进行中的目标');
325
+ return send(res, 200, md.page('长期目标', files.map((f) => `<hr>\n${md.render(readText(path.join(root, '05-goals', f)))}`).join('\n'), navHtml()));
326
+ }
327
+ if (pathname === '/reports') {
328
+ const files = listFiles(path.join(root, '01-inbox', 'reports'), (n) => /^[\w.-]+\.html$/.test(n));
329
+ return send(res, 200, md.page('报告', files.length ? md.render(files.map((f) => `- [${f}](/reports/${f})`).join('\n')) : '<p class="muted">还没有报告</p>', navHtml()));
330
+ }
331
+ m = /^\/reports\/([\w.-]+\.html)$/.exec(pathname);
332
+ if (m) {
333
+ const file = path.join(root, '01-inbox', 'reports', m[1]);
334
+ if (!fs.existsSync(file)) return notFound(res, `没有 ${m[1]}`);
335
+ return send(res, 200, fs.readFileSync(file));
336
+ }
337
+ return notFound(res, pathname);
338
+ }
339
+
340
+ function handleRequest(req, res) {
341
+ try {
342
+ route(req, res);
343
+ } catch (error) {
344
+ // 单个请求出错不能把服务带崩
345
+ log('页面出错', `${req.url} ${error.message}`);
346
+ try {
347
+ send(res, 500, md.page('页面出错了', `<p class="muted">${md.escapeHtml(String(error.message))}</p>`, navHtml()));
348
+ } catch {
349
+ // 连响应都发不出去就算了
350
+ }
351
+ }
352
+ }
353
+
354
+ // 只绑 127.0.0.1:页面带着工作记录,不给别的机器看
355
+ const listen = (port) => new Promise((resolve, reject) => {
356
+ const server = http.createServer(handleRequest);
357
+ server.on('error', reject);
358
+ server.listen(port, '127.0.0.1', () => resolve(server));
359
+ });
360
+
361
+ // 把一份 Markdown 渲染成页面
362
+ function render(file) {
363
+ const full = path.resolve(root, file);
364
+ if (!fs.existsSync(full)) throw new Fail(EXIT.USAGE, `没有这个文件:${file}`);
365
+ return md.page(path.basename(full), md.render(fs.readFileSync(full, 'utf8')), navHtml());
366
+ }
367
+
368
+ // 配置和依赖的问题,一条一个字符串。strict 为 false 时不把「缺指令文件的任务」算进去:起服务时到点跳过就是了
369
+ function doctorProblems({ strict = true } = {}) {
370
+ const problems = [];
371
+ for (const [id, specText] of Object.entries(cfg.schedule)) {
372
+ if (NOT_SERVICE_TASKS.includes(id)) continue;
373
+ const spec = parseSpec(specText);
374
+ if (!spec) continue;
375
+ if (spec.problem) problems.push(`任务 ${id} 的时间${spec.problem}`);
376
+ else if (!fs.existsSync(path.join(root, 'tasks', `${id}.md`)) && strict) problems.push(`任务 ${id} 的时间写了「${specText}」,但缺 tasks/${id}.md,没法跑`);
377
+ }
378
+ if (cfg.sync && parseSpec(cfg.sync).problem) problems.push(`采集的时间${parseSpec(cfg.sync).problem}`);
379
+ if (!(cfg.port >= 1024 && cfg.port <= 65535)) problems.push(`rhythm.port 要是 1024 到 65535 之间的整数(现在是 ${cfg.port})`);
380
+ // 只有真有任务要跑时,agent 和推送才必须配好;只采集、只看页面的用不着
381
+ if (jobs().some((job) => job.kind === 'task' && job.hasPrompt)) {
382
+ problems.push(...createAgent({ root, agent: env.YZJ_BOT_AGENT, mode: cfg.agentMode, env }).doctor());
383
+ if (cfg.push && !cfg.notifyChannel) problems.push('rhythm.push 开着,但 preferences.notify 没配消息渠道:要么配一个,要么把 push 写成 false');
384
+ }
385
+ return problems;
386
+ }
387
+
388
+ // 前台跑:定时采集、定时整理、推送、网页服务。每 tickMs 看一次表(默认 20 秒)。收到 SIGINT / SIGTERM 后退出,返回退出码
389
+ async function start({ tickMs = TICK_MS } = {}) {
390
+ if (serviceAlive()) throw new Fail(EXIT.NOT_CONFIGURED, '服务已经在跑了(work-rhythm rhythm status 看详情)');
391
+ const problems = doctorProblems({ strict: false }).filter((p) => !p.startsWith('任务 '));
392
+ if (problems.length) throw new Fail(EXIT.NOT_CONFIGURED, `配置有问题,先跑 work-rhythm rhythm doctor:\n${problems.join('\n')}`);
393
+ const server = await listen(cfg.port).catch((error) => {
394
+ throw new Fail(EXIT.FAILED, `网页服务起不来(${cfg.port} 端口):${error.message}`);
395
+ });
396
+ fs.mkdirSync(STATE_DIR, { recursive: true });
397
+ fs.writeFileSync(PID_FILE, `${process.pid}\n`);
398
+ log('服务开始', `pid=${process.pid} 页面=${baseUrl()} agent=${env.YZJ_BOT_AGENT || '(没配)'}`);
399
+ process.stdout.write(`页面:${baseUrl()} 停:work-rhythm rhythm stop\n`);
400
+
401
+ const list = jobs();
402
+ const state = loadState();
403
+ let running = null;
404
+ const queue = [];
405
+ const startNext = () => {
406
+ if (running || !queue.length) return;
407
+ const job = queue.shift();
408
+ running = startJob(job);
409
+ running.on('exit', (code) => {
410
+ state.runs[job.id] = { at: fmtStamp(), ok: code === 0, code };
411
+ saveState(state);
412
+ log('跑完', `${job.id} rc=${code}`);
413
+ running = null;
414
+ startNext();
415
+ });
416
+ };
417
+ const tick = () => {
418
+ const now = new Date();
419
+ for (const job of list) {
420
+ for (const minute of timesOn(job.spec, now)) {
421
+ const at = new Date(now);
422
+ at.setHours(Math.floor(minute / 60), minute % 60, 0, 0);
423
+ if (at > now || now - at >= CATCH_UP_MS) continue;
424
+ const key = `${job.id}@${at.toISOString()}`;
425
+ if (state.done[key]) continue;
426
+ state.done[key] = fmtStamp();
427
+ saveState(state);
428
+ if (job.kind === 'task' && !job.hasPrompt) {
429
+ log('跳过', `${job.id}:缺 tasks/${job.id}.md`);
430
+ continue;
431
+ }
432
+ log('到点', `${job.id} ${hhmm(at)}`);
433
+ queue.push(job);
434
+ }
435
+ }
436
+ startNext();
437
+ };
438
+ tick();
439
+ const timer = setInterval(tick, tickMs);
440
+ await new Promise((resolve) => {
441
+ const stop = (signal) => {
442
+ log(`收到 ${signal},服务结束`);
443
+ clearInterval(timer);
444
+ if (running) running.kill('SIGTERM');
445
+ try {
446
+ fs.unlinkSync(PID_FILE);
447
+ } catch {
448
+ // 已经没了
449
+ }
450
+ server.close(() => resolve());
451
+ setTimeout(resolve, 1500).unref();
452
+ };
453
+ process.on('SIGINT', () => stop('SIGINT'));
454
+ process.on('SIGTERM', () => stop('SIGTERM'));
455
+ });
456
+ return EXIT.OK;
457
+ }
458
+
459
+ // 只起网页服务
460
+ async function serve(port) {
461
+ const server = await listen(port);
462
+ process.stdout.write(`LISTENING http://127.0.0.1:${server.address().port}\n`);
463
+ await new Promise((resolve) => {
464
+ const stop = () => server.close(() => resolve());
465
+ process.on('SIGINT', stop);
466
+ process.on('SIGTERM', stop);
467
+ });
468
+ return EXIT.OK;
469
+ }
470
+
471
+ function stop() {
472
+ const pid = Number(readText(PID_FILE).trim());
473
+ if (!pid || !serviceAlive()) return '没在跑。';
474
+ process.kill(pid, 'SIGTERM');
475
+ return `已让它停下(pid ${pid})。`;
476
+ }
477
+
478
+ function statusText() {
479
+ const lines = [serviceAlive() ? `在跑(pid ${readText(PID_FILE).trim()}),页面 ${baseUrl()}` : '没在跑。'];
480
+ const runs = Object.entries(loadState().runs).sort((a, b) => a[1].at.localeCompare(b[1].at)).slice(-5);
481
+ if (runs.length) lines.push(`最近:${runs.map(([id, r]) => `${id} ${r.at} ${r.ok ? '成功' : `失败(${r.code})`}`).join(';')}`);
482
+ lines.push(`接下来:\n${due(new Date(), 1)}`);
483
+ return lines.join('\n');
484
+ }
485
+
486
+ return {
487
+ cfg,
488
+ log,
489
+ stateDir: STATE_DIR,
490
+ baseUrl,
491
+ serviceAlive,
492
+ due,
493
+ render,
494
+ runJob,
495
+ start,
496
+ serve,
497
+ stop,
498
+ statusText,
499
+ doctorProblems,
500
+ launchd: {
501
+ install: () => launchd.install({ kind: 'service', root, entry: ENTRY, args: ['rhythm', 'start', '--workdir', root], logFile: LAUNCHD_LOG }),
502
+ uninstall: () => launchd.uninstall('service', root),
503
+ },
504
+ launchdLog: LAUNCHD_LOG,
505
+ };
506
+ }
507
+
508
+ module.exports = { createRhythm, loadConfig, parseSpec, LINKS, NOT_SERVICE_TASKS };
@@ -0,0 +1,64 @@
1
+ // 云之家个人机器人这一条渠道的出口:地址取自系统钥匙串,往它 POST 一段文本,消息带「[有人@你]」的提醒。
2
+ // 只用 node 自带的能力(fetch、起子进程读钥匙串),不依赖 curl 和 jq。密钥不打印:报错里带回的 token 会打码
3
+ 'use strict';
4
+ const { EXIT, which, run } = require('./run');
5
+
6
+ const DEFAULT_SERVICE = 'work-rhythm-yzj-robot-webhook';
7
+
8
+ const serviceName = (env) => (env.YZJ_ROBOT_KEYCHAIN_SERVICE || '').trim() || DEFAULT_SERVICE;
9
+
10
+ // 钥匙串里有没有这一项:只查有没有,不把地址读出来,更不打印
11
+ function hasWebhook(env) {
12
+ return !!which('security', env) && run('security', ['find-generic-password', '-s', serviceName(env)], { env }).code === 0;
13
+ }
14
+
15
+ // 取发送地址(含 token)。地址只在内存里用,不打印。返回 { webhook },取不到时 { code, problem }
16
+ function findWebhook(env) {
17
+ const svc = serviceName(env);
18
+ if (!which('security', env)) return { code: EXIT.MISSING_DEP, problem: '消息渠道 yzj-robot 需要 security(系统钥匙串的命令),本机没有' };
19
+ const r = run('security', ['find-generic-password', '-s', svc, '-w'], { env });
20
+ const webhook = r.code === 0 ? r.stdout.trim() : '';
21
+ if (!webhook) {
22
+ return {
23
+ code: EXIT.NOT_CONFIGURED,
24
+ problem: `钥匙串里没有 ${svc}。建好个人机器人后,在自己的终端运行下面这条,按提示粘贴 Webhook 地址(不回显,不进任何文件):\n security add-generic-password -a "$USER" -s ${svc} -U -w\n 步骤见 docs/channels.md「云之家」`,
25
+ };
26
+ }
27
+ return { webhook };
28
+ }
29
+
30
+ // 地址、报错里带回的 token 不外露
31
+ const mask = (text) => String(text).replace(/(yzjtoken=)[A-Za-z0-9%._~-]+/gi, '$1<已打码>');
32
+
33
+ // 发一段文本给一个 openId。返回 { ok, status, body, text };没发出去时 ok 为 false、status 为 0、error 说明原因
34
+ async function postRobot(webhook, body, { fetchImpl = fetch, timeoutMs = 20000 } = {}) {
35
+ let timer;
36
+ const timeout = new Promise((_, reject) => {
37
+ timer = setTimeout(() => reject(new Error(`请求超时(${Math.round(timeoutMs / 1000)} 秒)`)), timeoutMs);
38
+ });
39
+ let response;
40
+ try {
41
+ response = await Promise.race([
42
+ fetchImpl(webhook, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }),
43
+ timeout,
44
+ ]);
45
+ } catch (error) {
46
+ // fetch 断连时只说 fetch failed,真正的原因(ECONNREFUSED、ENOTFOUND…)在 cause 里:有 code 用 code,没有就从它的话里找
47
+ const cause = error && error.cause;
48
+ const code = cause && (cause.code || (/E[A-Z]{3,}/.exec(cause.message || '') || [])[0]);
49
+ return { ok: false, status: 0, error: `${error && error.message ? error.message : String(error)}${code ? `(${code})` : ''}`, body: null, text: '' };
50
+ } finally {
51
+ clearTimeout(timer);
52
+ }
53
+ const text = await response.text();
54
+ let doc = null;
55
+ try {
56
+ doc = JSON.parse(text);
57
+ } catch {
58
+ doc = null;
59
+ }
60
+ // HTTP 200 不算数,要看返回里的 success
61
+ return { ok: response.ok && doc && doc.success === true, status: response.status, body: doc, text };
62
+ }
63
+
64
+ module.exports = { DEFAULT_SERVICE, serviceName, hasWebhook, findWebhook, mask, postRobot };