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,297 @@
1
+ // 改完脚本、配置或文档后跑一遍:脚本语法、文档内链、预算、配置自检、疑似密钥、笔记格式。
2
+ // 全部通过时退出码为 0;有未通过的项退出码为 1,每项都指出来。只读,不修改任何文件。
3
+ // 用法: work-rhythm check
4
+ 'use strict';
5
+ const fs = require('node:fs');
6
+ const path = require('node:path');
7
+ const vm = require('node:vm');
8
+ const { EXIT, UsageError, run: spawn, which, walkFiles, readText, tail } = require('../lib/run');
9
+ const { loadSources, settings, lintLocalEnv } = require('../lib/config');
10
+ const { notifyChannel } = require('../lib/notify');
11
+ const { hasWebhook, serviceName } = require('../lib/robot');
12
+ const { resolveCollector } = require('./sync');
13
+ const { createBot } = require('../lib/bot');
14
+ const { BLANK, GITIGNORE, blankText } = require('../lib/template');
15
+
16
+ const SKILL_KEYS = ['name', 'description', 'when_to_use', 'license', 'metadata'];
17
+ const SKIP_DIRS = new Set(['.git', '01-inbox', 'node_modules']);
18
+ // 内置采集器各要什么:tools 是 PATH 上要有的命令,var 是 local.env 里一定要有的变量(源 id 不是采集器自己的名字时加 _<ID> 后缀)
19
+ const NEEDS = {
20
+ 'im-yzj': { tools: [], var: 'YZJ_GROUP_IDS' },
21
+ 'linky-issues': { tools: ['linky'] },
22
+ 'calendar-yzj': { tools: ['yzj-cli'] },
23
+ 'approval-yzj': { tools: ['yzj-cli'] },
24
+ };
25
+
26
+ const filledLines = (file) => readText(file).split('\n').filter((l) => l.length).length;
27
+
28
+ function listDir(dir, files = false) {
29
+ try {
30
+ return fs.readdirSync(dir, { withFileTypes: true }).filter((d) => (files ? d.isFile() : d.isDirectory())).map((d) => d.name);
31
+ } catch {
32
+ return [];
33
+ }
34
+ }
35
+
36
+ // 把一个 JS 文件编译一遍但不运行:有语法错就返回错误信息,没有返回空串。开头的 #! 要先去掉
37
+ function syntaxError(file) {
38
+ try {
39
+ new vm.Script(readText(file).replace(/^#![^\n]*/, ''), { filename: file });
40
+ return '';
41
+ } catch (error) {
42
+ return tail(String(error && error.message ? error.message : error), 200);
43
+ }
44
+ }
45
+
46
+ // 1 脚本语法。查的是 work-rhythm 自己(包里的 scripts/、collectors/)和工作目录里自己加的脚本:
47
+ // 采集器、skill 里带的脚本,用什么语言写都行。返回没通过的个数
48
+ function checkSyntax({ root, packageRoot, say }) {
49
+ const files = new Set();
50
+ const add = (file) => {
51
+ if (/\.(js|mjs|cjs|sh|py)$/.test(file)) files.add(file);
52
+ };
53
+ for (const dir of ['scripts', 'collectors']) walkFiles(path.join(packageRoot, dir), SKIP_DIRS, 0).forEach(add);
54
+ // 工作目录里的 collectors/ 只看自己加的那几个(local.env 之类不是脚本)
55
+ for (const name of listDir(path.join(root, 'collectors'), true)) add(path.join(root, 'collectors', name));
56
+ for (const skill of listDir(path.join(root, '.agents', 'skills'))) walkFiles(path.join(root, '.agents', 'skills', skill, 'scripts'), SKIP_DIRS, 0).forEach(add);
57
+ let bad = 0;
58
+ const sorted = [...files].sort();
59
+ for (const file of sorted.filter((f) => /\.(js|mjs|cjs)$/.test(f))) {
60
+ const problem = syntaxError(file);
61
+ if (!problem) continue;
62
+ say(problem);
63
+ say(`语法错误 ${path.relative(root, file)}`);
64
+ bad += 1;
65
+ }
66
+ // 用 shell、Python 写的:有对应的解释器就查一遍,没有就报缺依赖
67
+ const others = [
68
+ ['sh', 'bash', (f) => spawn('bash', ['-n', f]).code === 0],
69
+ ['py', 'python3', (f) => spawn('python3', ['-c', 'import ast, sys; ast.parse(open(sys.argv[1], encoding="utf-8").read(), sys.argv[1])', f]).code === 0],
70
+ ];
71
+ for (const [ext, tool, passes] of others) {
72
+ for (const file of sorted.filter((f) => f.endsWith(`.${ext}`))) {
73
+ if (!which(tool)) say(`${path.relative(root, file)} 需要 ${tool},本机没有`);
74
+ else if (passes(file)) continue;
75
+ else say(`语法错误 ${path.relative(root, file)}`);
76
+ bad += 1;
77
+ }
78
+ }
79
+ return bad;
80
+ }
81
+
82
+ // 2 文档内链:相对链接指向的文件在不在。代码块里的内容是示例,不检查;别的协议(http、mailto…)不管
83
+ function checkLinks({ root, packageRoot, say }) {
84
+ const broken = [];
85
+ // templates/ 里的文件是铺进工作目录之后才有相对位置的(03-carryover/…),在这里查没有意义
86
+ for (const file of walkFiles(root, new Set([...SKIP_DIRS, 'templates']), 0)) {
87
+ if (!file.endsWith('.md')) continue;
88
+ let fenced = false;
89
+ for (const line of readText(file).split('\n')) {
90
+ if (/^\s*```/.test(line)) {
91
+ fenced = !fenced;
92
+ continue;
93
+ }
94
+ if (fenced) continue;
95
+ for (const m of line.matchAll(/\]\(([^)]+)\)/g)) {
96
+ const link = m[1].trim().replace(/\s+"[^"]*"$/, '').replace(/#.*$/, '');
97
+ if (!link || /^[a-z][a-z0-9+.-]*:/i.test(link)) continue;
98
+ // 工作目录里的文档也会指向这个包里的文件(脚本不在工作目录里):工作目录里没有的,再到包里找一次
99
+ const target = path.resolve(path.dirname(file), decodeURIComponent(link));
100
+ const inPackage = path.resolve(packageRoot, path.relative(root, target));
101
+ if (!fs.existsSync(target) && (path.relative(root, target).startsWith('..') || !fs.existsSync(inPackage))) broken.push(`断链 ./${path.relative(root, file)} -> ${link}`);
102
+ }
103
+ }
104
+ }
105
+ broken.forEach(say);
106
+ return broken.length;
107
+ }
108
+
109
+ // 3 预算:SKILL.md 不超过 500 个非空行;AGENTS.md 不超过 60 行、standing orders 不超过 10 条。
110
+ // skill 的头部:ZCode 只认 name、description、when_to_use、license、metadata 五个键,而且只把 description 的前约 250 个字符交给模型——
111
+ // skill 装上了不等于会被调用
112
+ function checkBudgets({ root, say }) {
113
+ const bad = [];
114
+ const skill = path.join(root, '.agents', 'skills', 'work-rhythm', 'SKILL.md');
115
+ if (fs.existsSync(skill)) {
116
+ if (filledLines(skill) >= 500) bad.push('SKILL.md 超过 500 个非空行');
117
+ const lines = readText(skill).split('\n');
118
+ const end = lines.indexOf('---', 1);
119
+ const front = lines[0] === '---' && end > 0 ? lines.slice(1, end) : [];
120
+ const isKey = (l) => /^[A-Za-z_][A-Za-z0-9_]*:/.test(l);
121
+ const unknown = [...new Set(front.filter((l) => isKey(l)).map((l) => /^([A-Za-z_][A-Za-z0-9_]*):/.exec(l)[1]))].filter((k) => !SKILL_KEYS.includes(k));
122
+ if (unknown.length) bad.push(`SKILL.md 的头部有 ZCode 不认识的键:${unknown.join(' ')}(会被忽略;其他信息放进 metadata)`);
123
+ // 描述可能是一行带引号的字符串,也可能是 > 或 | 起头的多行;到下一个键为止,拼成一行再数字符
124
+ const at = front.findIndex((l) => /^description:/.test(l));
125
+ const parts = [];
126
+ if (at >= 0) {
127
+ parts.push(front[at].replace(/^description:\s*/, ''));
128
+ for (const l of front.slice(at + 1)) {
129
+ if (isKey(l)) break;
130
+ parts.push(l.replace(/^\s*[|>][-+]?\s*/, ' ').replace(/^\s+/, ' '));
131
+ }
132
+ }
133
+ const desc = parts.join('').trim().replace(/^"/, '').replace(/"$/, '').trim();
134
+ const len = Array.from(desc).length;
135
+ if (len > 250) bad.push(`SKILL.md 的 description 超过 250 个字符(现在 ${len}),超出的部分模型看不到:把触发场景放到最前面`);
136
+ }
137
+ const agents = path.join(root, 'AGENTS.md');
138
+ if (fs.existsSync(agents)) {
139
+ if (filledLines(agents) > 60) bad.push('AGENTS.md 超过 60 个非空行');
140
+ const lines = readText(agents).split('\n');
141
+ const from = lines.indexOf('## Standing orders');
142
+ let orders = 0;
143
+ for (const l of from < 0 ? [] : lines.slice(from + 1)) {
144
+ if (/^## /.test(l)) break;
145
+ if (/^- ./.test(l)) orders += 1;
146
+ }
147
+ if (orders > 10) bad.push('AGENTS.md 的 standing orders 超过 10 条');
148
+ }
149
+ bad.forEach(say);
150
+ return bad.length;
151
+ }
152
+
153
+ // 4 配置自检:profile 没缺字段、local.env 写得对、启用的源有采集器、变量和依赖、消息渠道和值守配好了。
154
+ // 定时任务是无人值守的,问题要在这里先暴露
155
+ function checkConfig({ root, packageRoot, env, say }) {
156
+ const bad = [];
157
+ // profile.yaml 不能缺 profile.example.yaml(空白模板)里声明的字段:模板加了新字段,填好的那份要跟上。多出来的字段是个人加的,不管
158
+ const example = path.join(root, '00-config', 'profile.example.yaml');
159
+ const profile = path.join(root, '00-config', 'profile.yaml');
160
+ if (fs.existsSync(example) && fs.existsSync(profile)) {
161
+ const keys = (file) => new Set(readText(file).split('\n').map((l) => /^\s*([A-Za-z_][A-Za-z0-9_-]*):/.exec(l.replace(/\s#.*$/, ''))).filter(Boolean).map((m) => m[1]));
162
+ const missing = [...keys(example)].filter((k) => !keys(profile).has(k));
163
+ if (missing.length) bad.push(`00-config/profile.yaml 缺了这些字段(对照 profile.example.yaml 补上): ${missing.sort().join(' ')}`);
164
+ }
165
+ // local.env 写得对不对:引用了未定义的变量、不是 KEY=VALUE 的行。有问题时采集脚本读到的配置就不是你以为的那份
166
+ const hasLocalEnv = fs.existsSync(path.join(root, 'collectors', 'local.env'));
167
+ const envProblems = hasLocalEnv ? lintLocalEnv(readText(path.join(root, 'collectors', 'local.env')), env) : [];
168
+ envProblems.forEach((p) => bad.push(`collectors/local.env ${p}`));
169
+ const values = envProblems.length ? {} : settings(root, env);
170
+ // 模板约定:每个源里 enabled 写在 collector 之前。只看已启用的源
171
+ for (const src of loadSources(root)) {
172
+ if (!src.enabled || src.collector === 'none') continue;
173
+ if (!resolveCollector(root, packageRoot, src.collector)) {
174
+ bad.push(`已启用的源 ${src.id} 缺采集脚本: ${src.collector}(关掉它,或把脚本补上)`);
175
+ continue;
176
+ }
177
+ const needs = NEEDS[src.collector];
178
+ if (!needs) continue;
179
+ for (const tool of needs.tools) {
180
+ if (!which(tool, env)) bad.push(`已启用的源 ${src.id} 需要 ${tool},本机没有`);
181
+ }
182
+ if (needs.var) {
183
+ // 源 id 是 im-yzj 时读 YZJ_GROUP_IDS,别的 id 读 YZJ_GROUP_IDS_<ID>
184
+ const name = src.id === 'im-yzj' ? needs.var : `${needs.var}_${src.id.toUpperCase().replace(/-/g, '_')}`;
185
+ if (!hasLocalEnv) bad.push(`已启用的源 ${src.id} 需要 collectors/local.env(从 local.env.example 复制后填写 ${name})`);
186
+ else if (!envProblems.length && !(values[name] || '').trim()) bad.push(`已启用的源 ${src.id} 没有配置 ${name}(collectors/local.env)`);
187
+ }
188
+ }
189
+ // 消息渠道(docs/channels.md):preferences.notify 写了内置渠道时,钥匙串里要有地址、依赖要装好。
190
+ // 只查钥匙串里有没有这一项,不把地址读出来,更不打印。别的值这里不管(notify 会报「不认识的渠道」)
191
+ const channel = notifyChannel(root);
192
+ if (channel === 'yzj-robot') {
193
+ if (!which('security', env)) bad.push(`消息渠道 ${channel} 需要 security,本机没有`);
194
+ else if (!hasWebhook(env)) bad.push(`消息渠道 ${channel}:钥匙串里没有 ${serviceName(env)}(开通步骤见 docs/channels.md「云之家」)`);
195
+ }
196
+ // 值守(work-rhythm listen,渠道的收消息一半):配了 YZJ_BOT_AGENT 才检查。查什么由它自己的 doctor 说了算,这里不重复一遍
197
+ if (!envProblems.length && (values.YZJ_BOT_AGENT || '').trim()) bad.push(...createBot({ root, env: values }).doctorProblems());
198
+ bad.forEach(say);
199
+ return bad.length;
200
+ }
201
+
202
+ // 5 疑似密钥:范围是会提交进仓库的内容;01-inbox/ 本来就不入库。只报位置,不打印内容。
203
+ // yzjtoken 是云之家机器人 Webhook 地址里的凭据;机器人会话的第一条消息里就有完整地址,容易被人顺手抄进备注或笔记
204
+ const SECRET = /sk-[A-Za-z0-9_-]{16,}|appSecret|accessToken|password\s*[:=]|BEGIN [A-Z ]*PRIVATE KEY|yzjtoken=[0-9A-Za-z]{8,}/;
205
+
206
+ function checkSecrets({ root, say }) {
207
+ const hits = [];
208
+ for (const dir of ['00-config', '02-daily', '03-carryover', '04-patterns', '05-goals', '.agents']) {
209
+ for (const file of walkFiles(path.join(root, dir), SKIP_DIRS, 0)) {
210
+ const text = readText(file);
211
+ if (text.includes('\0')) continue; // 不是文本的不管
212
+ text.split('\n').forEach((line, n) => {
213
+ if (SECRET.test(line)) hits.push(`${path.relative(root, file)}:${n + 1}`);
214
+ });
215
+ }
216
+ }
217
+ if (hits.length) {
218
+ say('疑似密钥,先删掉再提交(下面只是位置):');
219
+ hits.forEach(say);
220
+ }
221
+ return hits.length;
222
+ }
223
+
224
+ // 6 笔记格式。.agents/notes/ 下的两类笔记。路径是 <类别>/yyyy-mm-dd-<英文短横线标题>.md;
225
+ // 踩坑笔记带 Verified(怎么重新确认坑还在)、Origin(在哪、怎么发现的)和固定的三节,决策笔记带 Decided 和四节。规则见 .agents/notes/AGENTS.md。
226
+ function checkNotes({ root, say }) {
227
+ const bad = [];
228
+ const need = (file, what) => bad.push(`笔记 ${file}:${what}`);
229
+ for (const [kind, dateKey, sections] of [
230
+ ['pitfalls', null, ['现象', '原因', '怎么做']],
231
+ ['decisions', 'Decided', ['Problem', 'Decision', 'Alternatives considered', 'Consequences']],
232
+ ]) {
233
+ const dir = path.join(root, '.agents', 'notes', kind);
234
+ for (const name of listDir(dir, true).sort()) {
235
+ const rel = `.agents/notes/${kind}/${name}`;
236
+ if (!/^[0-9]{4}-[0-9]{2}-[0-9]{2}-[a-z0-9][a-z0-9-]*\.md$/.test(name)) {
237
+ need(rel, '文件名应为 yyyy-mm-dd-<英文短横线标题>.md');
238
+ continue;
239
+ }
240
+ const lines = readText(path.join(dir, name)).split('\n');
241
+ const head = lines.slice(0, 6);
242
+ if (kind === 'pitfalls') {
243
+ if (!head.some((l) => /^Verified: [0-9]{4}-[0-9]{2}-[0-9]{2}/.test(l))) need(rel, '前 6 行里没有「Verified: yyyy-mm-dd · <重新确认这个坑还在的方法>」');
244
+ if (!head.some((l) => /^Origin: [0-9]{4}-[0-9]{2}-[0-9]{2}/.test(l))) need(rel, '前 6 行里没有「Origin: yyyy-mm-dd · <在哪踩的> · <怎么发现的>」');
245
+ } else if (!head.some((l) => new RegExp(`^${dateKey}: [0-9]{4}-[0-9]{2}-[0-9]{2}`).test(l))) {
246
+ need(rel, '前 6 行里没有「Decided: yyyy-mm-dd」');
247
+ }
248
+ for (const s of sections) {
249
+ if (!lines.includes(`## ${s}`)) need(rel, `缺少小节「## ${s}」`);
250
+ }
251
+ }
252
+ }
253
+ bad.forEach(say);
254
+ return bad.length;
255
+ }
256
+
257
+ // 7 模板。只在开发这个包的目录里查:templates/ 下空白的记录要和根目录那份空白化之后一致——改了表头或说明,两边要一起改;
258
+ // profile.example.yaml 得是空白状态;.gitignore 和代码里那份一致
259
+ function checkTemplates({ root, packageRoot, say }) {
260
+ if (path.resolve(root) !== path.resolve(packageRoot)) return 0;
261
+ const bad = [];
262
+ for (const rel of BLANK) {
263
+ const template = readText(path.join(packageRoot, 'templates', rel));
264
+ if (!template) bad.push(`templates/${rel} 不存在`);
265
+ else if (template !== blankText(rel, readText(path.join(root, rel)))) bad.push(`templates/${rel} 和 ${rel} 空白化之后不一致(改了表头或说明,两边要一起改)`);
266
+ }
267
+ if (!/^ status: new\b/m.test(readText(path.join(packageRoot, '00-config', 'profile.example.yaml')))) bad.push('00-config/profile.example.yaml 不是空白状态(setup.status 应为 new)');
268
+ // 工作目录的 .gitignore 写在 lib/template.js 里(见那里的说明),要和根目录的一致
269
+ if (readText(path.join(root, '.gitignore')) !== GITIGNORE) bad.push('.gitignore 和 lib/template.js 里的 GITIGNORE 不一致(两边要一起改)');
270
+ bad.forEach(say);
271
+ return bad.length;
272
+ }
273
+
274
+ const STEPS = [
275
+ ['脚本语法', checkSyntax],
276
+ ['文档内链', checkLinks],
277
+ ['预算', checkBudgets],
278
+ ['配置自检', checkConfig],
279
+ ['疑似密钥', checkSecrets],
280
+ ['笔记格式', checkNotes],
281
+ ];
282
+
283
+ async function run(args, ctx) {
284
+ if (args.length) throw new UsageError('用法: work-rhythm check');
285
+ const { root, packageRoot, stdout, env } = ctx;
286
+ const say = (text = '') => stdout.write(`${text}\n`);
287
+ const steps = path.resolve(root) === path.resolve(packageRoot) ? [...STEPS, ['模板(开发时)', checkTemplates]] : STEPS;
288
+ let bad = 0;
289
+ for (const [i, [title, check]] of steps.entries()) {
290
+ say(`== ${i + 1}/${steps.length} ${title} ==`);
291
+ bad += check({ root, packageRoot, env: settings(root, env), say });
292
+ }
293
+ say(bad ? `${bad} 项未通过` : '全部通过');
294
+ return bad ? 1 : EXIT.OK;
295
+ }
296
+
297
+ module.exports = { usage: '用法: work-rhythm check 改完脚本、配置或文档后跑一遍,只读', run };
@@ -0,0 +1,25 @@
1
+ // 直接跑一个采集器:任务指令里「取今日日程」「取告警」这类只要某一个源的数据时用
2
+ // 用法: work-rhythm collect <源id> <输出目录> [采集器自己的参数…,一般是起始日期 YYYY-MM-DD]
3
+ // 输出目录写成 01-inbox/<源id>/<日期>:和 im-yzj 共用脚本的源(如 ops-yzj)靠它认出自己该读哪个变量。
4
+ // sources.yaml 里有的源按它登记的采集器跑,没有的把 <源id> 当成内置采集器的 id
5
+ 'use strict';
6
+ const path = require('node:path');
7
+ const { EXIT, UsageError } = require('../lib/run');
8
+ const { loadSources } = require('../lib/config');
9
+ const { resolveCollector, spawnCollector } = require('./sync');
10
+
11
+ module.exports = {
12
+ usage: '用法: work-rhythm collect <源id> <输出目录> [起始日期]',
13
+ async run(args, ctx) {
14
+ const { root, env, packageRoot } = ctx;
15
+ const [id, out] = args;
16
+ if (!id || !out) throw new UsageError(module.exports.usage);
17
+ const source = loadSources(root).find((s) => s.id === id);
18
+ const collector = resolveCollector(root, packageRoot, source ? source.collector : id);
19
+ if (!collector) throw new UsageError(`没有 ${id} 这个采集器,sources.yaml 里也没有这个源`);
20
+ const r = spawnCollector(collector, [path.resolve(out), ...args.slice(2)], { cwd: root, env: { ...env, WORK_RHYTHM_ROOT: root } });
21
+ if (r.stdout) ctx.stdout.write(r.stdout);
22
+ if (r.stderr) ctx.stderr.write(r.stderr);
23
+ return r.code === 0 ? EXIT.OK : r.code > 0 && r.code < 126 ? r.code : EXIT.FAILED;
24
+ },
25
+ };
@@ -0,0 +1,236 @@
1
+ // 待决与决定的记录。03-carryover/DECISIONS.md 一次决定一行,只记结论;KEEP_DAYS 天以前的行挪到 archive/DECISIONS-<年-月>.md
2
+ // work-rhythm decisions add --item <事项> --options <选项> --choice <决定> [--reason <理由>] [--by <我|AI|一起>] [--date <YYYY-MM-DD>]
3
+ // work-rhythm decisions answer <事项> <决定> [--reason <理由>] [--by <我|AI|一起>] 把最近一条「未答」改成我的决定
4
+ // work-rhythm decisions done <事项> <落实> 给最近一条事项相符、还没写落实的行补上落实
5
+ // work-rhythm decisions list [天数] [--today] 最近 N 天(默认 60)的决定,连归档一起查;--today 只看今天的。制表符分隔,第一行是表头
6
+ // work-rhythm decisions archive [天数] 把 N 天(默认 60)以前的行挪到归档文件;add 之后会自动做一遍
7
+ // 每个字段都有字数上限(LIMITS),超了或者含竖线、制表符、换行,按参数错误退出(2):这份记录要能一眼扫完。
8
+ // --date 和环境变量 DECISIONS_TODAY 是给自测用的,平时不用管。格式见 docs/formats.md 的「待决与决定」。
9
+ 'use strict';
10
+ const fs = require('node:fs');
11
+ const path = require('node:path');
12
+ const { EXIT, addDays, today, writeFileAtomic } = require('../lib/run');
13
+
14
+ const USAGE = `用法: work-rhythm decisions <子命令>
15
+ add --item <事项> [--options <选项>] --choice <决定> [--reason <理由>] [--by <我|AI|一起>] [--date <YYYY-MM-DD>]
16
+ answer <事项> <决定> [--reason <理由>] [--by <我|AI|一起>]
17
+ done <事项> <落实>
18
+ list [天数] [--today]
19
+ archive [天数]`;
20
+
21
+ const KEEP_DAYS = 60;
22
+ const COLUMNS = ['日期', '事项', '选项', '决定', '理由', '谁来做', '落实'];
23
+ const LIMITS = { 事项: 30, 选项: 60, 决定: 12, 理由: 30, 谁来做: 6, 落实: 30 };
24
+ const UNANSWERED = '未答';
25
+ const ROW = /^\| (\d{4}-\d{2}-\d{2}) \|/;
26
+ const SEPARATOR = /^\|[-:|]+\|$/;
27
+ const ARCHIVE_NAME = /^DECISIONS-(\d{4}-\d{2})\.md$/;
28
+ const HEADER = '| 日期 | 事项 | 选项 | 决定 | 理由 | 谁来做 | 落实 |\n|------|------|------|------|------|--------|------|';
29
+
30
+ // 参数错误:消息打给用户,退出码 2
31
+ class Fail extends Error {}
32
+
33
+ const splitLines = (text) => {
34
+ const lines = text.replace(/\r\n?/g, '\n').split('\n');
35
+ if (lines.length && lines[lines.length - 1] === '') lines.pop();
36
+ return lines;
37
+ };
38
+
39
+ // 今天;自测可以用环境变量 DECISIONS_TODAY 指定
40
+ function todayOf(env) {
41
+ const value = env.DECISIONS_TODAY;
42
+ if (!value) return today();
43
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) throw new Fail(`无法识别日期「${value}」(格式应为 YYYY-MM-DD)`);
44
+ return value;
45
+ }
46
+
47
+ // 去掉首尾空白;含竖线、制表符、换行,或超过字数上限的,拒收
48
+ function clean(name, value) {
49
+ const v = String(value ?? '').trim();
50
+ if (/[|\t\r\n]/.test(v)) throw new Fail(`${name}里不能有竖线、制表符或换行`);
51
+ const len = Array.from(v).length;
52
+ if (len > LIMITS[name]) throw new Fail(`${name}太长了(${len} 字,上限 ${LIMITS[name]} 字):只记结论,长话留在别处`);
53
+ return v;
54
+ }
55
+
56
+ function days(text) {
57
+ if (text === undefined) return KEEP_DAYS;
58
+ if (!/^\d+$/.test(text) || Number(text) <= 0) throw new Fail(`天数应为正整数,收到「${text}」`);
59
+ return Number(text);
60
+ }
61
+
62
+ const cellsOf = (line) => line.trim().replace(/^\|+/, '').replace(/\|+$/, '').split('|').map((cell) => cell.trim());
63
+ const rowOf = (cells) => `| ${cells.join(' | ')} |`;
64
+
65
+ // 把 keep_days 天以前的行挪到所属月份的归档文件,返回挪了几行
66
+ function archive(file, keepDays, env) {
67
+ if (!fs.existsSync(file)) return 0;
68
+ const cutoff = addDays(todayOf(env), -keepDays);
69
+ const keep = [];
70
+ const moved = [];
71
+ for (const line of splitLines(fs.readFileSync(file, 'utf8'))) {
72
+ const m = ROW.exec(line);
73
+ if (m && m[1] < cutoff) moved.push(line);
74
+ else keep.push(line);
75
+ }
76
+ const byMonth = new Map();
77
+ for (const line of moved) {
78
+ const month = ROW.exec(line)[1].slice(0, 7);
79
+ if (!byMonth.has(month)) byMonth.set(month, []);
80
+ byMonth.get(month).push(line);
81
+ }
82
+ const dir = path.join(path.dirname(file), 'archive');
83
+ // 先追加到归档、后改原文件:中途出错最多是归档里多一份,不会丢行
84
+ for (const [month, rows] of [...byMonth.entries()].sort()) {
85
+ const target = path.join(dir, `DECISIONS-${month}.md`);
86
+ if (!fs.existsSync(target)) {
87
+ fs.mkdirSync(dir, { recursive: true });
88
+ fs.writeFileSync(target, `# 决定归档 · ${month}\n\n由 \`work-rhythm decisions archive\` 从 [DECISIONS.md](../DECISIONS.md) 挪过来的行,只追加不修改。格式见 \`docs/formats.md\` 的「待决与决定」。\n\n${HEADER}\n`);
89
+ }
90
+ fs.appendFileSync(target, `${rows.join('\n')}\n`);
91
+ }
92
+ if (moved.length) writeFileAtomic(file, `${keep.join('\n')}\n`);
93
+ return moved.length;
94
+ }
95
+
96
+ // --flag value 这种选项;位置参数按顺序留下
97
+ function parseFlags(args, names) {
98
+ const opts = {};
99
+ const positional = [];
100
+ for (let i = 0; i < args.length; i += 1) {
101
+ const a = args[i];
102
+ if (names.includes(a)) {
103
+ if (i + 1 >= args.length) throw new Fail(`选项 ${a} 后面要跟一个值`);
104
+ opts[a.slice(2)] = args[++i];
105
+ } else if (a.startsWith('--') && names.includes(`${a}=`)) {
106
+ const [k, v] = a.slice(2).split(/=(.*)/);
107
+ opts[k] = v ?? '';
108
+ } else if (a.startsWith('--') && !names.includes(a)) {
109
+ throw new Fail(`不认识的选项 ${a}\n${USAGE}`);
110
+ } else positional.push(a);
111
+ }
112
+ return { opts, positional };
113
+ }
114
+
115
+ module.exports = {
116
+ usage: USAGE,
117
+ archive,
118
+ async run(args, ctx) {
119
+ const { root, stdout, stderr, env } = ctx;
120
+ const file = path.join(root, '03-carryover', 'DECISIONS.md');
121
+ const [sub, ...rest] = args;
122
+ const needFile = () => {
123
+ if (!fs.existsSync(file)) throw new Fail('找不到 03-carryover/DECISIONS.md');
124
+ };
125
+ const read = () => splitLines(fs.readFileSync(file, 'utf8'));
126
+ try {
127
+ if (sub === 'add') {
128
+ const { opts } = parseFlags(rest, ['--item', '--options', '--choice', '--reason', '--by', '--date']);
129
+ if (opts.item === undefined || opts.choice === undefined) throw new Fail(`add 需要写明 --item 和 --choice\n${USAGE}`);
130
+ const date = opts.date ? todayOf({ DECISIONS_TODAY: opts.date }) : todayOf(env);
131
+ const item = clean('事项', opts.item);
132
+ const choice = clean('决定', opts.choice);
133
+ if (!item) throw new Fail('缺少 --item(事项,一句话)');
134
+ if (!choice) throw new Fail('缺少 --choice(决定;没回答写「未答」)');
135
+ needFile();
136
+ const cells = [date, item, clean('选项', opts.options), choice, clean('理由', opts.reason), clean('谁来做', opts.by), ''];
137
+ const lines = read();
138
+ // 新行插在表格的最后一行后面;表里还没有行,就插在表头的分隔线后面
139
+ let index = 0;
140
+ lines.forEach((line, n) => {
141
+ if (ROW.test(line) || SEPARATOR.test(line)) index = n;
142
+ });
143
+ lines.splice(index + 1, 0, rowOf(cells));
144
+ writeFileAtomic(file, `${lines.join('\n')}\n`);
145
+ stderr.write(`已记:${date} ${item} → ${choice}\n`);
146
+ const moved = archive(file, KEEP_DAYS, env);
147
+ if (moved) stderr.write(`归档了 ${moved} 行(挪到了 03-carryover/archive/)\n`);
148
+ return EXIT.OK;
149
+ }
150
+ if (sub === 'archive') {
151
+ if (rest.length > 1) throw new Fail(USAGE);
152
+ const moved = archive(file, days(rest[0]), env);
153
+ if (moved) stderr.write(`decisions: 归档了 ${moved} 行(挪到了 03-carryover/archive/)\n`);
154
+ return EXIT.OK;
155
+ }
156
+ if (sub === 'list') {
157
+ const onlyToday = rest.includes('--today');
158
+ const rest2 = rest.filter((a) => a !== '--today');
159
+ if (rest2.length > 1) throw new Fail(USAGE);
160
+ const since = onlyToday ? todayOf(env) : addDays(todayOf(env), -days(rest2[0]));
161
+ stdout.write(`${COLUMNS.join('\t')}\n`);
162
+ // 归档文件按月份命名,只看窗口起点那个月及以后的;DECISIONS.md 是现在的,总是看
163
+ const dir = path.join(root, '03-carryover', 'archive');
164
+ const files = [];
165
+ let names = [];
166
+ try {
167
+ names = fs.readdirSync(dir).sort();
168
+ } catch {
169
+ names = [];
170
+ }
171
+ for (const name of names) {
172
+ const m = ARCHIVE_NAME.exec(name);
173
+ if (m && m[1] >= since.slice(0, 7)) files.push(path.join(dir, name));
174
+ }
175
+ if (fs.existsSync(file)) files.push(file);
176
+ for (const f of files) {
177
+ for (const line of splitLines(fs.readFileSync(f, 'utf8'))) {
178
+ const m = ROW.exec(line);
179
+ if (!m || m[1] < since) continue;
180
+ const cells = cellsOf(line);
181
+ while (cells.length < COLUMNS.length) cells.push('');
182
+ stdout.write(`${cells.slice(0, COLUMNS.length).join('\t')}\n`);
183
+ }
184
+ }
185
+ return EXIT.OK;
186
+ }
187
+ if (sub === 'answer' || sub === 'done') {
188
+ const { opts, positional } = parseFlags(rest, ['--reason', '--by']);
189
+ if (positional.length < 2) throw new Fail(`${sub} 要写 <事项> 和<${sub === 'answer' ? '决定' : '落实'}>\n${USAGE}`);
190
+ const item = clean('事项', positional[0]);
191
+ needFile();
192
+ const lines = read();
193
+ let hit = -1;
194
+ // 同一件事问过几次时,改的是最近的那一条
195
+ lines.forEach((line, n) => {
196
+ if (!ROW.test(line)) return;
197
+ const cells = cellsOf(line);
198
+ if (cells.length >= COLUMNS.length && cells[1] === item && (sub === 'answer' ? cells[3] === UNANSWERED : cells[6] === '')) hit = n;
199
+ });
200
+ if (hit < 0) {
201
+ throw new Fail(sub === 'answer'
202
+ ? `没有「${item}」的未答记录;没问过、是我直接说的决定,用 add 记一条`
203
+ : `没找到事项为「${item}」且还没写落实的那一行`);
204
+ }
205
+ const cells = cellsOf(lines[hit]);
206
+ if (sub === 'answer') {
207
+ const choice = clean('决定', positional[1]);
208
+ if (!choice) throw new Fail('缺少决定');
209
+ if (choice === UNANSWERED) throw new Fail(`决定不能还是「${UNANSWERED}」`);
210
+ cells[0] = todayOf(env); // 日期记我拿主意的那天
211
+ cells[3] = choice;
212
+ const reason = clean('理由', opts.reason);
213
+ const by = clean('谁来做', opts.by);
214
+ if (reason) cells[4] = reason;
215
+ if (by) cells[5] = by;
216
+ lines[hit] = rowOf(cells);
217
+ writeFileAtomic(file, `${lines.join('\n')}\n`);
218
+ stderr.write(`已记:${cells[0]} ${item} → ${choice}\n`);
219
+ } else {
220
+ const result = clean('落实', positional[1]);
221
+ if (!result) throw new Fail('缺少落实结果');
222
+ cells[6] = result;
223
+ lines[hit] = rowOf(cells);
224
+ writeFileAtomic(file, `${lines.join('\n')}\n`);
225
+ stderr.write(`已记落实:${item} → ${result}\n`);
226
+ }
227
+ return EXIT.OK;
228
+ }
229
+ throw new Fail(USAGE);
230
+ } catch (error) {
231
+ if (!(error instanceof Fail)) throw error;
232
+ stderr.write(`decisions: ${error.message}\n`);
233
+ return EXIT.USAGE;
234
+ }
235
+ },
236
+ };