work-rhythm 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/.agents/notes/AGENTS.md +84 -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 +34 -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 +45 -0
  18. package/.agents/notes/pitfalls/2026-11-29-do-not-hand-roll-git-log.md +22 -0
  19. package/.agents/notes/pitfalls/2026-11-29-empty-or-partial-collector-output.md +23 -0
  20. package/.agents/notes/pitfalls/2026-11-29-skill-description-is-truncated.md +21 -0
  21. package/.agents/notes/pitfalls/2026-11-29-tool-shell-is-zsh.md +24 -0
  22. package/.agents/notes/pitfalls/2026-11-30-compare-timestamps-as-digits.md +22 -0
  23. package/.agents/notes/pitfalls/2026-11-30-message-search-lags-after-sending.md +18 -0
  24. package/.agents/notes/pitfalls/2026-11-30-rewriting-a-file-with-empty-output-after-tool-failure.md +20 -0
  25. package/.agents/notes/pitfalls/2026-11-30-secret-scan-false-positive-on-hyphenated-file-names.md +18 -0
  26. package/.agents/notes/pitfalls/2026-11-30-selftest-must-not-inherit-local-config.md +29 -0
  27. package/.agents/notes/pitfalls/2026-11-30-yzj-cli-list-limit-is-20.md +25 -0
  28. package/.agents/notes/pitfalls/2026-11-30-zsh-no-word-splitting-special-names.md +23 -0
  29. package/.agents/notes/pitfalls/2026-12-01-node-test-hooks-cannot-register-after-callbacks.md +22 -0
  30. package/.agents/notes/pitfalls/2026-12-01-spawning-node-test-inside-a-test-runs-nothing.md +18 -0
  31. package/.agents/skills/work-rhythm/SKILL.md +277 -0
  32. package/00-config/profile.example.yaml +54 -0
  33. package/00-config/sources.yaml +115 -0
  34. package/AGENTS.md +31 -0
  35. package/README.md +105 -2
  36. package/collectors/approval-yzj.js +114 -0
  37. package/collectors/calendar-yzj.js +48 -0
  38. package/collectors/file-activity.js +131 -0
  39. package/collectors/git-activity.js +105 -0
  40. package/collectors/im-yzj.js +151 -0
  41. package/collectors/linky-issues.js +88 -0
  42. package/collectors/local.env.example +52 -0
  43. package/docs/channels.md +95 -0
  44. package/docs/formats.md +285 -0
  45. package/docs/im-adapters.md +79 -0
  46. package/docs/scheduled-tasks.md +115 -0
  47. package/docs/sources.md +104 -0
  48. package/package.json +37 -4
  49. package/scripts/cli.js +98 -0
  50. package/scripts/cmd/check.js +297 -0
  51. package/scripts/cmd/collect.js +25 -0
  52. package/scripts/cmd/decisions.js +236 -0
  53. package/scripts/cmd/goals.js +145 -0
  54. package/scripts/cmd/init.js +53 -0
  55. package/scripts/cmd/listen.js +91 -0
  56. package/scripts/cmd/notify.js +42 -0
  57. package/scripts/cmd/pack.js +105 -0
  58. package/scripts/cmd/rhythm.js +102 -0
  59. package/scripts/cmd/selftest.js +23 -0
  60. package/scripts/cmd/sync.js +73 -0
  61. package/scripts/cmd/today.js +29 -0
  62. package/scripts/cmd/workdir.js +81 -0
  63. package/scripts/lib/agent.js +270 -0
  64. package/scripts/lib/bot.js +376 -0
  65. package/scripts/lib/collector.js +74 -0
  66. package/scripts/lib/config.js +250 -0
  67. package/scripts/lib/launchd.js +82 -0
  68. package/scripts/lib/log.js +22 -0
  69. package/scripts/lib/markdown.js +208 -0
  70. package/scripts/lib/notify.js +43 -0
  71. package/scripts/lib/rhythm.js +508 -0
  72. package/scripts/lib/robot.js +64 -0
  73. package/scripts/lib/run.js +151 -0
  74. package/scripts/lib/template.js +144 -0
  75. package/scripts/lib/workdir.js +89 -0
  76. package/scripts/test/check.test.js +217 -0
  77. package/scripts/test/collectors.test.js +574 -0
  78. package/scripts/test/config.test.js +119 -0
  79. package/scripts/test/decisions.test.js +129 -0
  80. package/scripts/test/fake-webhook.js +31 -0
  81. package/scripts/test/goals.test.js +109 -0
  82. package/scripts/test/harness.js +279 -0
  83. package/scripts/test/init.test.js +125 -0
  84. package/scripts/test/listen.test.js +362 -0
  85. package/scripts/test/notify.test.js +176 -0
  86. package/scripts/test/pack.test.js +141 -0
  87. package/scripts/test/rhythm.test.js +324 -0
  88. package/scripts/test/stubs.js +140 -0
  89. package/scripts/test/today.test.js +73 -0
  90. package/scripts/test/workdir.test.js +152 -0
  91. package/scripts/work-rhythm.js +18 -0
  92. package/tasks/alerts-morning.md +24 -0
  93. package/tasks/carryover.md +16 -0
  94. package/tasks/daily-plan.md +29 -0
  95. package/tasks/evening-review.md +27 -0
  96. package/tasks/linky-cost-check.md +13 -0
  97. package/tasks/linky-cost-fill.md +20 -0
  98. package/tasks/noon-checkin.md +15 -0
  99. package/tasks/weekly-rhythm.md +18 -0
  100. package/templates/03-carryover/CARRYOVER.md +14 -0
  101. package/templates/03-carryover/DECISIONS.md +10 -0
  102. package/templates/04-patterns/WORK_RHYTHM.md +16 -0
@@ -0,0 +1,279 @@
1
+ // 自测的夹具:搭一次性的工作目录、起 work-rhythm 命令、放假的命令行工具。
2
+ // 自测只认模板的默认状态,不能被本机的个人配置带偏(2026-11-30 实测:带着真实的 local.env、sources.yaml 和决定记录,用例成片失败)。
3
+ // 所以工作目录从空白模板搭:profile 用 profile.example.yaml,sources.yaml 只开两个本机源,遗留和决定两张表清空
4
+ 'use strict';
5
+ const { spawn, spawnSync } = require('node:child_process');
6
+ const fs = require('node:fs');
7
+ const net = require('node:net');
8
+ const os = require('node:os');
9
+ const path = require('node:path');
10
+
11
+ const PACKAGE_ROOT = path.resolve(__dirname, '..', '..');
12
+ const MANIFEST = JSON.parse(fs.readFileSync(path.join(PACKAGE_ROOT, 'package.json'), 'utf8'));
13
+ const NAME = MANIFEST.name;
14
+ const VERSION = MANIFEST.version;
15
+ const BIN = path.join(PACKAGE_ROOT, 'scripts', 'work-rhythm.js');
16
+ const T = '\t';
17
+
18
+ // 这些变量是各命令的配置,本机环境里如果碰巧有,会让用例的结果跟着变。跑命令时一律不带
19
+ const STRIP = /^(YZJ_|GIT_ACTIVITY_|FILE_ACTIVITY_|DSH_|STUB_|ZCODE_CLI|WORK_RHYTHM_|DECISIONS_TODAY|LINKY_TYPES)/;
20
+ const { writeWorkdir } = require('../lib/template');
21
+
22
+ // 用户级登记指向一个不存在的文件:用例不能被本机登记的工作目录带偏
23
+ const NO_CONFIG = path.join(os.tmpdir(), 'work-rhythm-selftest-no-config.yaml');
24
+
25
+ function baseEnv(extra = {}) {
26
+ const env = {};
27
+ for (const [k, v] of Object.entries(process.env)) {
28
+ if (!STRIP.test(k)) env[k] = v;
29
+ }
30
+ return { WORK_RHYTHM_CONFIG: NO_CONFIG, ...env, ...extra };
31
+ }
32
+
33
+ function run(args, { cwd = PACKAGE_ROOT, env = {}, input, timeout = 120000 } = {}) {
34
+ const r = spawnSync(process.execPath, [BIN, ...args], { cwd, env: baseEnv(env), encoding: 'utf8', input, timeout, maxBuffer: 64 * 1024 * 1024 });
35
+ return {
36
+ code: r.error ? -1 : r.status,
37
+ stdout: r.stdout || '',
38
+ stderr: r.stderr || '',
39
+ out: `${r.stdout || ''}${r.stderr || ''}`,
40
+ };
41
+ }
42
+
43
+ // sources.yaml:只打开两个本机源(代码提交、文件改动),其余关着(假命令行跑不了云之家、Linky)
44
+ function cleanSources() {
45
+ const lines = read(path.join(PACKAGE_ROOT, '00-config', 'sources.yaml')).split('\n');
46
+ let keep = false;
47
+ return lines.map((line) => {
48
+ if (/^\s*-?\s*id:/.test(line)) {
49
+ keep = /git-activity|file-activity/.test(line);
50
+ return line;
51
+ }
52
+ if (/^\s*enabled:/.test(line)) return line.replace(/(true|false)\s*$/, keep ? 'true' : 'false');
53
+ return line;
54
+ }).join('\n');
55
+ }
56
+
57
+ // before() 这类钩子拿到的上下文没有 after(至少 node 26 还是这样),夹具要靠它登记收尾。
58
+ // 用这个顶上:after 先记下来,run() 的时候按登记的反过来执行(后登记的先跑),配合 describe 的 after() 用
59
+ function hookContext() {
60
+ const callbacks = [];
61
+ return {
62
+ after(fn) {
63
+ callbacks.push(fn);
64
+ },
65
+ async run() {
66
+ for (const fn of callbacks.reverse()) await fn();
67
+ },
68
+ };
69
+ }
70
+
71
+ // 搭一个一次性目录 root(放夹具和假的命令行工具)和里面的工作目录 work。t.after 负责清掉
72
+ function makeSandbox(t) {
73
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'work-rhythm-test-'));
74
+ // 收尾时把起过的子进程(本地服务)先杀掉再删目录:用例没来得及停的服务不能留着,否则它会在被删掉的目录里一直跑
75
+ t.after(() => {
76
+ for (const child of procs) {
77
+ try {
78
+ child.kill('SIGKILL');
79
+ } catch {
80
+ // 已经退了
81
+ }
82
+ }
83
+ fs.rmSync(root, { recursive: true, force: true });
84
+ });
85
+ const work = path.join(root, 'work');
86
+ const bin = path.join(root, 'bin');
87
+ // work 先建一个空目录:没铺工作目录的用例也要能站在里面跑命令
88
+ fs.mkdirSync(work, { recursive: true });
89
+ fs.mkdirSync(bin, { recursive: true });
90
+ const procs = [];
91
+ const sandbox = { root, work, bin, calls: path.join(root, 'calls.log') };
92
+ sandbox.workdir = (options = {}) => makeWorkdir(work, options);
93
+ // 环境变量在假工具的 PATH 上再叠加:每个用例都带着假的 security,自测碰不到真的钥匙串、发不到真的机器人
94
+ sandbox.run = (args, options = {}) => run(args, { cwd: work, ...options, env: { ...sandbox.stubEnv, ...(options.env || {}) } });
95
+ // 假的命令行工具:写成可执行文件放进 bin,跑命令时把 bin 放到 PATH 最前面
96
+ sandbox.stub = (name, source) => {
97
+ const file = path.join(bin, name);
98
+ fs.writeFileSync(file, `#!/usr/bin/env node\n${source}\n`);
99
+ fs.chmodSync(file, 0o755);
100
+ return file;
101
+ };
102
+ sandbox.stubEnv = { PATH: `${bin}${path.delimiter}${process.env.PATH}` };
103
+ // 钥匙串的假工具一开始就装上:STUB_KEYCHAIN 不是 ok 时它和真的一样报找不到
104
+ sandbox.stub('security', require('./stubs').security);
105
+ // 起一个一直跑着的子进程(本地服务、假 webhook),读到想要的那行文字再往下走
106
+ sandbox.spawn = (args, { env = {} } = {}) => {
107
+ const proc = startProcess([BIN, ...args], { cwd: work, env: baseEnv({ ...sandbox.stubEnv, ...env }) });
108
+ procs.push(proc.child);
109
+ return proc;
110
+ };
111
+ // 把一套假的工具都装上,返回它们要的环境变量
112
+ sandbox.stubs = (extra = {}) => {
113
+ const stubs = require('./stubs');
114
+ for (const [name, source] of Object.entries(stubs)) sandbox.stub(name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`), source);
115
+ // 假的 DSH_HOME:里面只有桌面应用那份配置,一条无关的加两条模型的
116
+ const home = path.join(root, 'dsh-home', 'profiles', 'web');
117
+ fs.mkdirSync(home, { recursive: true });
118
+ fs.writeFileSync(path.join(home, 'cordis.patch.yml'), [
119
+ '# 自测用的 DSH 配置:第一条无关,后两条是模型',
120
+ '- id: ui-theme',
121
+ ' name: "@deepseek-ai/dsh-client-ui-theme"',
122
+ ' config:',
123
+ ' preference: dark',
124
+ '- id: agent-default-model',
125
+ ' name: "@deepseek-ai/dsh-agent-default-model"',
126
+ ' config:',
127
+ ' provider: opencode-go',
128
+ ' model: deepseek-v4.1-flash',
129
+ '- id: llm-pi-ai',
130
+ ' name: "@deepseek-ai/dsh-llm-pi-ai"',
131
+ ' config:',
132
+ ' providers:',
133
+ ' opencode-go:',
134
+ ' apiKeyEnv: OPENCODE_GO_API_KEY',
135
+ '',
136
+ ].join('\n'));
137
+ const file = (name) => path.join(root, name);
138
+ return {
139
+ ...sandbox.stubEnv,
140
+ STUB_CALLS: file('calls.log'),
141
+ STUB_ROBOT_TOKEN: 'stubtoken0123456789abcd',
142
+ STUB_AGENT_CALLS: file('agent.calls'),
143
+ STUB_ZCODE_ARGS: file('zcode.args'),
144
+ STUB_DSH_ARGS: file('dsh.args'),
145
+ STUB_DSH_ENV: file('dsh.env'),
146
+ STUB_APPROVAL_NEW_MS: String(Date.UTC(2026, 10, 27, 10, 0, 0)),
147
+ STUB_APPROVAL_OLD_MS: String(Date.UTC(2026, 10, 16, 5, 30, 0)),
148
+ DSH_HOME: path.join(root, 'dsh-home'),
149
+ DSH_NODE: path.join(bin, 'fake-dsh-node'),
150
+ DSH_CLI: path.join(bin, 'fake-dsh'),
151
+ ZCODE_CLI: path.join(bin, 'fake-zcode'),
152
+ STUB_MDFIND_LOG: file('mdfind.log'),
153
+ ...extra,
154
+ };
155
+ };
156
+ sandbox.read = (name) => read(path.join(root, name));
157
+ return sandbox;
158
+ }
159
+
160
+ // 搭一个工作目录,和 work-rhythm init 铺出来的一样(走同一个函数),只是 sources.yaml 换成 cleanSources()。
161
+ // profile 默认是空白模板;写 'real' 用这个仓库自己填好的那份
162
+ function makeWorkdir(dir, { profile = 'example' } = {}) {
163
+ fs.mkdirSync(dir, { recursive: true });
164
+ const problems = writeWorkdir(dir, PACKAGE_ROOT);
165
+ if (problems.length) throw new Error(`铺出来的工作目录不是空白的:${problems.join(';')}`);
166
+ fs.writeFileSync(path.join(dir, '00-config', 'sources.yaml'), cleanSources());
167
+ if (profile !== 'example') fs.writeFileSync(path.join(dir, '00-config', 'profile.yaml'), read(path.join(PACKAGE_ROOT, '00-config', 'profile.yaml')));
168
+ return dir;
169
+ }
170
+
171
+ // 读文件里的文本;没有这个文件返回空串
172
+ const read = (file) => {
173
+ try {
174
+ return fs.readFileSync(file, 'utf8');
175
+ } catch {
176
+ return '';
177
+ }
178
+ };
179
+ const exists = (file) => fs.existsSync(file);
180
+ const write = (file, text) => {
181
+ fs.mkdirSync(path.dirname(file), { recursive: true });
182
+ fs.writeFileSync(file, text);
183
+ };
184
+
185
+ // 从某个日期到今天相隔几天(按本地时间的正午算,和 goals 的算法一致)
186
+ function daysSince(date) {
187
+ const now = new Date();
188
+ const to = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 12).getTime();
189
+ const from = new Date(Number(date.slice(0, 4)), Number(date.slice(5, 7)) - 1, Number(date.slice(8, 10)), 12).getTime();
190
+ return Math.round((to - from) / 86400000);
191
+ }
192
+
193
+ // 起一个子进程,返回 { child, text(), waitFor(text, ms), exited }。text() 是到目前为标准输出和标准错误合起来的文字
194
+ function startProcess(command, { cwd, env }) {
195
+ const child = spawn(command[0], command.slice(1), { cwd, env, stdio: ['ignore', 'pipe', 'pipe'] });
196
+ let out = '';
197
+ child.stdout.on('data', (c) => {
198
+ out += c;
199
+ });
200
+ child.stderr.on('data', (c) => {
201
+ out += c;
202
+ });
203
+ const exited = new Promise((resolve) => child.on('exit', (code) => resolve(code)));
204
+ return {
205
+ child,
206
+ exited,
207
+ text: () => out,
208
+ async waitFor(text, ms = 10000) {
209
+ const until = Date.now() + ms;
210
+ while (!out.includes(text) && Date.now() < until) {
211
+ await new Promise((resolve) => setTimeout(resolve, 50));
212
+ }
213
+ return out.includes(text);
214
+ },
215
+ };
216
+ }
217
+
218
+ // 假的机器人 Webhook(fake-webhook.js):work-rhythm 推过来的请求都落到它这里,记在 root/webhook.log。
219
+ // 返回 { url(带假 token 的发送地址), requests()(每个请求的时间、路径、请求体), contents()(发过的文字,按先后), clear() }
220
+ async function webhook(t, { mode = 'ok' } = {}) {
221
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'work-rhythm-webhook-'));
222
+ const bin = path.join(root, 'fake-webhook');
223
+ fs.writeFileSync(bin, fs.readFileSync(path.join(__dirname, 'fake-webhook.js')));
224
+ fs.chmodSync(bin, 0o755);
225
+ const log = path.join(root, 'requests.log');
226
+ fs.writeFileSync(log, '');
227
+ const proc = startProcess([process.execPath, bin], { cwd: root, env: baseEnv({ STUB_WEBHOOK: mode, STUB_WEBHOOK_LOG: log }) });
228
+ const port = await new Promise((resolve, reject) => {
229
+ const timer = setTimeout(() => reject(new Error('假 webhook 没起来')), 10000);
230
+ proc.child.stdout.once('data', (c) => {
231
+ clearTimeout(timer);
232
+ resolve(String(c).trim());
233
+ });
234
+ });
235
+ t.after(() => {
236
+ proc.child.kill('SIGTERM');
237
+ fs.rmSync(root, { recursive: true, force: true });
238
+ });
239
+ const requests = () => read(log).split('\n').filter(Boolean).map((line) => JSON.parse(line));
240
+ return {
241
+ url: `http://127.0.0.1:${port}/gateway/robot/webhook/send?yzjtype=0&yzjtoken=stubtoken0123456789abcd`,
242
+ requests,
243
+ contents: () => requests().map((r) => (r.body ? JSON.parse(r.body).content : '')),
244
+ clear: () => fs.writeFileSync(log, ''),
245
+ };
246
+ }
247
+
248
+ // 起一个子进程并等它结束,不经过 shell。给测试里用 git 搭夹具
249
+ const GIT_ENV = { GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_SYSTEM: '/dev/null' };
250
+ const git = (cwd, args, env = {}) => spawnSync('git', args, { cwd, env: { ...process.env, ...env }, encoding: 'utf8' });
251
+
252
+ // 建一个临时 git 仓库,identity 为 true 时里面有一条今天的提交,作者是 selftest@example.com
253
+ function gitRepo(dir, { identity = true } = {}) {
254
+ fs.mkdirSync(dir, { recursive: true });
255
+ const r = git(dir, ['init', '-q'], GIT_ENV);
256
+ if (r.status !== 0) throw new Error(r.stderr);
257
+ if (identity) {
258
+ git(dir, ['-c', 'user.name=Selftest', '-c', 'user.email=selftest@example.com', '-c', 'commit.gpgsign=false', 'commit', '-q', '--allow-empty', '-m', '导出接口联调修复', `--date=${new Date().toISOString()}`], GIT_ENV);
259
+ }
260
+ return dir;
261
+ }
262
+
263
+ // 一个现在空着的端口
264
+ const freePort = () => new Promise((resolve) => {
265
+ const server = net.createServer();
266
+ server.listen(0, '127.0.0.1', () => {
267
+ const { port } = server.address();
268
+ server.close(() => resolve(port));
269
+ });
270
+ });
271
+
272
+ // 改 profile.yaml 里的一个键:同一缩进的那一行整个换掉(值自己带引号)
273
+ function setKey(text, key, value) {
274
+ const re = new RegExp(`^(\\s*)${key}:[^\\n]*$`, 'm');
275
+ if (!re.test(text)) throw new Error(`profile.yaml 里没有键 ${key}`);
276
+ return text.replace(re, (m, indent) => `${indent}${key}: ${value}`);
277
+ }
278
+
279
+ module.exports = { PACKAGE_ROOT, NAME, VERSION, BIN, T, NO_CONFIG, baseEnv, run, startProcess, hookContext, webhook, freePort, setKey, git, GIT_ENV, gitRepo, cleanSources, makeSandbox, makeWorkdir, read, exists, write, daysSince };
@@ -0,0 +1,125 @@
1
+ 'use strict';
2
+ const { test } = require('node:test');
3
+ const assert = require('node:assert/strict');
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+ const { PACKAGE_ROOT, makeSandbox, cleanSources, git, GIT_ENV, gitRepo, run: rawRun, read, exists, write } = require('./harness');
7
+
8
+ const TODAY = () => {
9
+ const d = new Date();
10
+ const p = (n) => String(n).padStart(2, '0');
11
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
12
+ };
13
+
14
+ // 新工作目录里该有什么:配置、文档、任务指令、记录、笔记和 skill;不该有脚本和内置采集器
15
+ const EXPECTED = [
16
+ '00-config/profile.yaml', '00-config/profile.example.yaml', '00-config/sources.yaml', 'AGENTS.md', 'README.md', '.gitignore', 'CLAUDE.md',
17
+ 'docs/formats.md', 'docs/channels.md', 'tasks/daily-plan.md', 'collectors/local.env.example',
18
+ '03-carryover/CARRYOVER.md', '03-carryover/DECISIONS.md', '04-patterns/WORK_RHYTHM.md',
19
+ '.agents/skills/work-rhythm/SKILL.md', '.agents/notes/AGENTS.md', '02-daily/.gitkeep', '05-goals/.gitkeep',
20
+ ];
21
+ const NOT_EXPECTED = ['scripts', 'templates', 'collectors/git-activity.js', 'collectors/im-yzj.sh', '01-inbox', 'collectors/local.env', '02-daily/.gitkeep.md'];
22
+
23
+ test('init:用包里的模板建出工作目录,git init 一个不连远程的本地仓库,并登记', (t) => {
24
+ const box = makeSandbox(t);
25
+ const cfg = path.join(box.root, 'wr-config.yaml');
26
+ const target = path.join(box.root, 'home', 'new-wd');
27
+ const r = rawRun(['init', target], { cwd: box.root, env: { WORK_RHYTHM_CONFIG: cfg } });
28
+ assert.equal(r.code, 0, r.out);
29
+ const real = fs.realpathSync(target);
30
+ assert.equal(r.stdout, `WORKDIR=${real}\n`);
31
+ assert.match(r.stderr, /init: 已新建 .*new-wd:个人信息是空白的、数据源全部关着、没有记录、不连任何远程\n下一步:.*「开始引导」/);
32
+ for (const f of EXPECTED) assert.ok(exists(path.join(target, f)), `缺 ${f}`);
33
+ for (const f of NOT_EXPECTED) assert.ok(!exists(path.join(target, f)), `不该有 ${f}`);
34
+ assert.match(read(`${target}/00-config/profile.yaml`), /^ status: new\b/m);
35
+ assert.equal(read(`${target}/00-config/profile.yaml`), read(`${target}/00-config/profile.example.yaml`));
36
+ assert.ok(!/enabled:\s*true/.test(read(`${target}/00-config/sources.yaml`)), '数据源要全部关着');
37
+ assert.match(read(`${target}/03-carryover/DECISIONS.md`), /^\| 日期 \| 事项/m);
38
+ assert.ok(!/^\| \d/m.test(read(`${target}/03-carryover/DECISIONS.md`)), '模板里不带记录');
39
+ assert.match(read(`${target}/.gitignore`), /01-inbox\/\n[\s\S]*collectors\/local\.env/);
40
+ assert.ok(fs.lstatSync(`${target}/CLAUDE.md`).isSymbolicLink(), 'CLAUDE.md 是指向 AGENTS.md 的软链');
41
+ assert.ok(exists(`${target}/.git`));
42
+ assert.equal(git(target, ['remote'], GIT_ENV).stdout.trim(), '', '不连任何远程');
43
+ assert.equal(read(cfg), `workdir: ${real}\n`);
44
+ });
45
+
46
+ test('init:相对路径按当前目录算,上级目录没有就一起建;目录已经存在、参数不对时退出码为 2', (t) => {
47
+ const box = makeSandbox(t);
48
+ const cfg = path.join(box.root, 'wr-config.yaml');
49
+ const env = { WORK_RHYTHM_CONFIG: cfg };
50
+ const r = rawRun(['init', './my-work'], { cwd: box.root, env });
51
+ assert.equal(r.code, 0, r.out);
52
+ assert.equal(r.stdout, `WORKDIR=${fs.realpathSync(path.join(box.root, 'my-work'))}\n`);
53
+ const deep = rawRun(['init', path.join(box.root, 'no', 'such', 'dir', 'x')], { cwd: box.root, env });
54
+ assert.equal(deep.code, 0, deep.out);
55
+ assert.ok(exists(path.join(box.root, 'no', 'such', 'dir', 'x', '00-config', 'profile.yaml')));
56
+ const again = rawRun(['init', path.join(box.root, 'my-work')], { cwd: box.root, env });
57
+ assert.equal(again.code, 2);
58
+ assert.match(again.stderr, /已经存在。拿它当工作目录用 work-rhythm workdir register;要新建就换个位置/);
59
+ assert.equal(rawRun(['init'], { cwd: box.root, env }).code, 2);
60
+ assert.equal(rawRun(['init', 'a', 'b'], { cwd: box.root, env }).code, 2);
61
+ });
62
+
63
+ test('init:建出来的工作目录里 work-rhythm 的命令都能用:check、today、sync', (t) => {
64
+ const box = makeSandbox(t);
65
+ const cfg = path.join(box.root, 'wr-config.yaml');
66
+ const target = path.join(box.root, 'home', 'demo');
67
+ assert.equal(rawRun(['init', target], { cwd: box.root, env: { WORK_RHYTHM_CONFIG: cfg } }).code, 0);
68
+ // 站在里面,不用 --workdir:往上找得到,也不靠登记
69
+ const chk = rawRun(['check'], { cwd: target, env: { WORK_RHYTHM_CONFIG: path.join(box.root, 'none.yaml') } });
70
+ assert.equal(chk.code, 0, chk.out);
71
+ assert.match(chk.stdout, /== 1\/6 脚本语法 ==\n[\s\S]*== 6\/6 笔记格式 ==\n全部通过\n/);
72
+ assert.equal(rawRun(['today'], { cwd: target }).stdout, `DATE=${TODAY()}\nWEEKDAY=${['日', '一', '二', '三', '四', '五', '六'][new Date().getDay()]}\nDAILY_FILE=02-daily/${TODAY().slice(0, 7)}/${TODAY()}.md\nIS_WORKDAY=1\n`);
73
+ // 采集:内置采集器在包里,工作目录里没有它们也能跑
74
+ const ws = path.join(box.root, 'ws');
75
+ gitRepo(path.join(ws, 'demo'));
76
+ write(path.join(target, '00-config', 'sources.yaml'), cleanSources());
77
+ write(path.join(target, 'collectors', 'local.env'), `GIT_ACTIVITY_WORKSPACES="${ws}"\nGIT_ACTIVITY_AUTHORS="selftest@example.com"\nFILE_ACTIVITY_WORKSPACES="${ws}"\n`);
78
+ const sync = rawRun(['sync'], { cwd: target, env: { ...box.stubs() } });
79
+ assert.equal(sync.code, 0, sync.out);
80
+ assert.match(sync.stdout, /ok git-activity\nok file-activity\n/);
81
+ assert.ok(exists(path.join(target, '01-inbox', 'git-activity', TODAY(), 'commits.tsv')));
82
+ assert.equal(rawRun(['goals', 'list'], { cwd: target }).code, 0);
83
+ assert.equal(rawRun(['decisions', 'list'], { cwd: target }).code, 0);
84
+ });
85
+
86
+ // ---------------------------------------------------------------- 模板本身
87
+ const { writeWorkdir, blankProblems, blankText, GITIGNORE } = require('../lib/template');
88
+
89
+ test('template:包不完整时说清缺哪份;空白核对认得出带记录、带配置、没关源的目录', (t) => {
90
+ const box = makeSandbox(t);
91
+ write(path.join(box.root, 'pkg', 'docs', 'a.md'), 'x');
92
+ assert.throws(() => writeWorkdir(path.join(box.root, 'w'), path.join(box.root, 'pkg')), /这个包不完整:没有 00-config\/profile\.example\.yaml。重新安装一次 work-rhythm/);
93
+ // 真铺出来的是空白的(夹具为了跑采集会打开两个本机源,所以这里自己铺一份)
94
+ const dir = path.join(box.root, 'fresh');
95
+ fs.mkdirSync(dir);
96
+ assert.deepEqual(writeWorkdir(dir, PACKAGE_ROOT), []);
97
+ assert.deepEqual(blankProblems(dir), []);
98
+ write(`${dir}/02-daily/2026-01/2026-01-01.md`, '# 2026-01-01\n');
99
+ write(`${dir}/05-goals/x.md`, '---\nid: x\n---\n');
100
+ write(`${dir}/collectors/local.env`, 'A=1\n');
101
+ write(`${dir}/01-inbox/x`, '');
102
+ fs.appendFileSync(`${dir}/03-carryover/CARRYOVER.md`, '| 2026-01-01 | 旧 | 复盘 | P1 | 待开始 | 0 | |\n');
103
+ write(`${dir}/00-config/sources.yaml`, read(`${dir}/00-config/sources.yaml`).replace(/^(\s*enabled:\s*)false/gm, '$1true'));
104
+ write(`${dir}/00-config/profile.yaml`, read(`${dir}/00-config/profile.yaml`).replace('status: new', 'status: done'));
105
+ assert.deepEqual(blankProblems(dir), [
106
+ 'profile.yaml 不是空白状态(setup.status 应为 new)',
107
+ '数据源没有全部关掉',
108
+ '02-daily 里带了 1 个记录文件',
109
+ '05-goals 里带了 1 个记录文件',
110
+ '03-carryover/CARRYOVER.md 里带了记录',
111
+ '带了不该带的 collectors/local.env',
112
+ '带了不该带的 01-inbox',
113
+ ]);
114
+ assert.match(GITIGNORE, /01-inbox\/\n[\s\S]*collectors\/local\.env/);
115
+ });
116
+
117
+ test('template:空白化的几条规则', () => {
118
+ assert.equal(blankText('03-carryover/DECISIONS.md', '# t\n\n| 日期 |\n|---|---|\n| 2026-01-01 | a |\n| 01-01 | b |\n'), '# t\n\n| 日期 |\n|---|---|\n');
119
+ assert.equal(blankText('00-config/sources.yaml', 'a:\n enabled: true # 开\n enabled: false\n enabled: true\n'), 'a:\n enabled: false\n enabled: false\n enabled: false\n');
120
+ const rhythm = '# 我的规律\n\n> 说明\n\n数据范围:近 30 天(12 个工作日)\n\n## 时间节律\n\n- 早上写代码\n- 下午开会\n\n## 固定承诺\n\n(x)\n\n## 对计划的含义\n\n内容\n';
121
+ assert.equal(blankText('04-patterns/WORK_RHYTHM.md', rhythm), '# 我的规律\n\n> 说明\n\n数据范围:尚未开始(0 个带事件的工作日)\n\n## 时间节律\n\n## 固定承诺\n\n## 对计划的含义\n');
122
+ // 已经是空白的,原样不变
123
+ const blank = read(path.join(PACKAGE_ROOT, 'templates', '04-patterns', 'WORK_RHYTHM.md'));
124
+ assert.equal(blankText('04-patterns/WORK_RHYTHM.md', blank), blank);
125
+ });