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,151 @@
1
+ // 各处都要用的小工具:起子进程、日期、退出码、读写文件。只用 node 自带的能力。
2
+ 'use strict';
3
+ const { spawnSync } = require('node:child_process');
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+
7
+ // 所有命令统一的退出码
8
+ const EXIT = { OK: 0, USAGE: 2, NOT_CONFIGURED: 3, MISSING_DEP: 4, FAILED: 5 };
9
+
10
+ // 命令没跑成:带着退出码抛出,入口统一把消息打给用户、按这个退出码结束
11
+ class Fail extends Error {
12
+ constructor(code, message) {
13
+ super(message);
14
+ this.name = 'Fail';
15
+ this.code = code;
16
+ }
17
+ }
18
+
19
+ // 用法不对、参数不合法:消息打给用户,退出码 2
20
+ class UsageError extends Fail {
21
+ constructor(message) {
22
+ super(EXIT.USAGE, message);
23
+ this.name = 'UsageError';
24
+ }
25
+ }
26
+
27
+ // 本地时间某一天的正午。用正午是为了算星期和相隔天数时不受夏令时影响
28
+ function noon(date) {
29
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(date || '').trim());
30
+ if (!m) return null;
31
+ const d = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]), 12);
32
+ // 2026-13-40 这种会被 Date 自动进位,要挡回去
33
+ if (d.getFullYear() !== Number(m[1]) || d.getMonth() !== Number(m[2]) - 1 || d.getDate() !== Number(m[3])) return null;
34
+ return d;
35
+ }
36
+
37
+ const pad = (n) => String(n).padStart(2, '0');
38
+ const fmtDate = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
39
+ const fmtStamp = (d = new Date()) => `${fmtDate(d)} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
40
+ const today = () => fmtDate(new Date());
41
+
42
+ function parseDate(text, what = '日期') {
43
+ const d = noon(text);
44
+ if (!d) throw new UsageError(`无法识别${what}「${text}」(格式应为 YYYY-MM-DD)`);
45
+ return d;
46
+ }
47
+
48
+ function addDays(date, n) {
49
+ const d = noon(date);
50
+ d.setDate(d.getDate() + n);
51
+ return fmtDate(d);
52
+ }
53
+
54
+ // to 比 from 晚几天
55
+ function daysBetween(from, to) {
56
+ return Math.round((noon(to) - noon(from)) / 86400000);
57
+ }
58
+
59
+ const WEEKDAY_CN = ['日', '一', '二', '三', '四', '五', '六'];
60
+ const WEEKDAY_EN = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
61
+ const weekdayCn = (date) => WEEKDAY_CN[noon(date).getDay()];
62
+ const weekdayAbbr = (date) => WEEKDAY_EN[noon(date).getDay()];
63
+
64
+ // 起一个子进程并等它结束。不经过 shell:参数原样传过去,不会被空格、引号拆开
65
+ function run(command, args, { cwd, env = process.env, timeout, input, maxBuffer } = {}) {
66
+ let r;
67
+ try {
68
+ r = spawnSync(command, args, {
69
+ cwd, env, encoding: 'utf8', input, timeout: timeout ? timeout * 1000 : undefined,
70
+ killSignal: 'SIGTERM', maxBuffer: maxBuffer || 64 * 1024 * 1024,
71
+ });
72
+ } catch (error) {
73
+ return { code: null, error, stdout: '', stderr: '', timedOut: false };
74
+ }
75
+ if (r.error) return { code: null, error: r.error, stdout: r.stdout || '', stderr: r.stderr || '', timedOut: r.error.code === 'ETIMEDOUT' };
76
+ return { code: r.status, signal: r.signal, error: null, stdout: r.stdout || '', stderr: r.stderr || '', timedOut: false };
77
+ }
78
+
79
+ function isExecutable(file) {
80
+ try {
81
+ fs.accessSync(file, fs.constants.X_OK);
82
+ return fs.statSync(file).isFile();
83
+ } catch {
84
+ return false;
85
+ }
86
+ }
87
+
88
+ // 命令在不在 PATH 上:在就返回它的完整路径,不在返回空串
89
+ function which(name, env = process.env) {
90
+ if (name.includes('/')) return isExecutable(name) ? path.resolve(name) : '';
91
+ for (const dir of (env.PATH || '').split(path.delimiter)) {
92
+ if (dir && isExecutable(path.join(dir, name))) return path.join(dir, name);
93
+ }
94
+ return '';
95
+ }
96
+
97
+ function readText(file) {
98
+ try {
99
+ return fs.readFileSync(file, 'utf8');
100
+ } catch {
101
+ return '';
102
+ }
103
+ }
104
+
105
+ // 先写到同目录的临时文件再改名:写一半出错也不会留下半份
106
+ function writeFileAtomic(file, content) {
107
+ fs.mkdirSync(path.dirname(file), { recursive: true });
108
+ const tmp = `${file}.tmp`;
109
+ fs.writeFileSync(tmp, content);
110
+ fs.renameSync(tmp, file);
111
+ }
112
+
113
+ function tail(text, max = 200) {
114
+ const s = String(text || '').trim();
115
+ return s.length > max ? s.slice(-max) : s;
116
+ }
117
+
118
+ // 本地时间某一天 0 点的时间戳
119
+ function startOfDay(date) {
120
+ const d = noon(date);
121
+ d.setHours(0, 0, 0, 0);
122
+ return d.getTime();
123
+ }
124
+
125
+ // 逐层扫目录,返回指定时间之后改过的普通文件(不跟符号链接)。名字在 prune 里的目录和文件跳过
126
+ function walkFiles(root, prune, sinceMs, out = []) {
127
+ let entries;
128
+ try {
129
+ entries = fs.readdirSync(root, { withFileTypes: true });
130
+ } catch {
131
+ return out;
132
+ }
133
+ for (const entry of entries) {
134
+ if (prune.has(entry.name)) continue;
135
+ const full = path.join(root, entry.name);
136
+ let st;
137
+ try {
138
+ st = fs.lstatSync(full);
139
+ } catch {
140
+ continue;
141
+ }
142
+ if (st.isDirectory()) walkFiles(full, prune, sinceMs, out);
143
+ else if (st.isFile() && st.mtimeMs >= sinceMs) out.push(full);
144
+ }
145
+ return out;
146
+ }
147
+
148
+ module.exports = {
149
+ EXIT, Fail, UsageError, noon, pad, fmtDate, fmtStamp, today, parseDate, addDays, daysBetween,
150
+ weekdayCn, weekdayAbbr, run, which, isExecutable, readText, writeFileAtomic, tail, startOfDay, walkFiles,
151
+ };
@@ -0,0 +1,144 @@
1
+ // 新工作目录里的东西从哪来,以及怎么把一个用过的目录清成空白的。
2
+ // 包里带着的文件分三种:
3
+ // 共用的(SHARED):文档、任务指令、给 agent 的笔记和 skill、说明、profile 的空白模板、sources.yaml 的清单、local.env 的样例——工作目录和包里是同一份;
4
+ // 空白的记录(BLANK,在 templates/ 下):遗留、决定、规律画像。包里不带根目录下用过的那几份,只带空白的;
5
+ // 现生成的:profile.yaml(就是 profile.example.yaml)、sources.yaml(清单照搬,全部关着,引导时逐个确认再打开)、两个 .gitkeep。
6
+ // 脚本和内置采集器不进工作目录:它们在包里,sources.yaml 用 id 引用。升级就是升级这个包
7
+ 'use strict';
8
+ const fs = require('node:fs');
9
+ const path = require('node:path');
10
+ const { readText, walkFiles } = require('./run');
11
+
12
+ const SHARED = ['00-config/profile.example.yaml', '00-config/sources.yaml', 'docs', 'tasks', '.agents', 'README.md', 'AGENTS.md', 'collectors/local.env.example'];
13
+ // 工作目录的 .gitignore。不靠包里带的那份:老版本的 npm 打包时会把根目录的 .gitignore 改名成 .npmignore,各版本行为不一致,写在代码里最稳。开发时 check 核对它和根目录的一致
14
+ const GITIGNORE = `# 各系统的原始快照:可重新拉取,且含聊天原文等细节,不入库
15
+ 01-inbox/
16
+
17
+ # 本机的配置(订阅的会话 ID、让哪个 agent 回复等)
18
+ collectors/local.env
19
+
20
+ .DS_Store
21
+ `;
22
+ const BLANK = ['03-carryover/CARRYOVER.md', '03-carryover/DECISIONS.md', '04-patterns/WORK_RHYTHM.md'];
23
+ const KEEPS = ['02-daily/.gitkeep', '05-goals/.gitkeep'];
24
+
25
+ // 表里以日期开头的行是记录,表头和分隔线留着
26
+ const blankCarryover = (text) => text.split('\n').filter((line) => !/^\| \d/.test(line)).join('\n');
27
+
28
+ // 规律画像只留标题、引用的说明行、「数据范围」一行和各小节的标题,小节里的内容清掉。
29
+ // 已经是空白的文件经过它原样不变(开发时用它核对 templates/ 没走样)
30
+ function blankRhythm(text) {
31
+ const out = [];
32
+ const blank = () => {
33
+ if (out.length && out[out.length - 1] !== '') out.push('');
34
+ };
35
+ for (const line of text.split('\n')) {
36
+ if (line.startsWith('## ')) {
37
+ blank();
38
+ out.push(line);
39
+ } else if (!line.trim()) blank();
40
+ else if (line.startsWith('# ')) out.push(line);
41
+ else if (line.startsWith('> ')) out.push(line);
42
+ else if (line.startsWith('数据范围')) {
43
+ blank();
44
+ out.push('数据范围:尚未开始(0 个带事件的工作日)');
45
+ }
46
+ }
47
+ return `${out.join('\n').replace(/\n+$/, '')}\n`;
48
+ }
49
+
50
+ // 数据源全部关掉(引导到第 4 步时逐个确认再打开)
51
+ const blankSources = (text) => text.replace(/^(\s*enabled:\s*)true\b.*$/gm, '$1false');
52
+
53
+ function blankText(rel, text) {
54
+ if (rel.endsWith('CARRYOVER.md') || rel.endsWith('DECISIONS.md')) return blankCarryover(text);
55
+ if (rel === '04-patterns/WORK_RHYTHM.md') return blankRhythm(text);
56
+ if (rel === '00-config/sources.yaml') return blankSources(text);
57
+ return text;
58
+ }
59
+
60
+ // 一个目录是不是空白的工作目录。返回问题的列表,空数组就是空白。
61
+ // 打包、init 之后、开发时的自检都用它核对:任何一项不对都不该往外发
62
+ function blankProblems(dir) {
63
+ const problems = [];
64
+ const text = (rel) => readText(path.join(dir, rel));
65
+ if (!fs.existsSync(path.join(dir, '00-config', 'profile.example.yaml'))) problems.push('没有 00-config/profile.example.yaml');
66
+ if (!fs.existsSync(path.join(dir, '00-config', 'profile.yaml'))) problems.push('没有 00-config/profile.yaml');
67
+ else if (!/^ status: new\b/m.test(text('00-config/profile.yaml'))) problems.push('profile.yaml 不是空白状态(setup.status 应为 new)');
68
+ if (!fs.existsSync(path.join(dir, '00-config', 'sources.yaml'))) problems.push('没有 00-config/sources.yaml');
69
+ else if (/^\s*enabled:\s*true\b/m.test(text('00-config/sources.yaml'))) problems.push('数据源没有全部关掉');
70
+ for (const dirName of ['02-daily', '05-goals']) {
71
+ const files = walkFiles(path.join(dir, dirName), new Set(), 0).filter((f) => f.endsWith('.md'));
72
+ if (files.length) problems.push(`${dirName} 里带了 ${files.length} 个记录文件`);
73
+ }
74
+ for (const rel of BLANK) {
75
+ if (/^\| \d/m.test(text(rel))) problems.push(`${rel} 里带了记录`);
76
+ }
77
+ for (const bad of ['.git', 'collectors/local.env', '01-inbox']) {
78
+ if (fs.existsSync(path.join(dir, bad))) problems.push(`带了不该带的 ${bad}`);
79
+ }
80
+ return problems;
81
+ }
82
+
83
+ // 把一个目录清成空白的工作目录:个人信息换成空白模板、数据源全关、记录不留、本机配置和原始数据删掉。
84
+ // 只处理目录里已有的文件,缺的不补。返回退出码
85
+ function blank(dir) {
86
+ const profileExample = path.join(dir, '00-config', 'profile.example.yaml');
87
+ const sources = path.join(dir, '00-config', 'sources.yaml');
88
+ if (!fs.existsSync(profileExample)) throw new Error(`${dir} 里没有 00-config/profile.example.yaml,清不了个人信息`);
89
+ if (!fs.existsSync(sources)) throw new Error(`${dir} 里没有 00-config/sources.yaml`);
90
+ fs.writeFileSync(path.join(dir, '00-config', 'profile.yaml'), fs.readFileSync(profileExample));
91
+ for (const rel of ['00-config/sources.yaml', ...BLANK]) {
92
+ const file = path.join(dir, rel);
93
+ if (fs.existsSync(file)) fs.writeFileSync(file, blankText(rel, fs.readFileSync(file, 'utf8')));
94
+ }
95
+ for (const dirName of ['02-daily', '05-goals']) {
96
+ const base = path.join(dir, dirName);
97
+ for (const file of walkFiles(base, new Set(), 0).filter((f) => f.endsWith('.md'))) fs.rmSync(file, { force: true });
98
+ // 删空的月份目录也收掉,只留顶层
99
+ for (const month of listDir(base)) {
100
+ if (fs.readdirSync(path.join(base, month)).length === 0) fs.rmdirSync(path.join(base, month));
101
+ }
102
+ }
103
+ for (const bad of ['03-carryover/archive', 'collectors/local.env', '01-inbox']) fs.rmSync(path.join(dir, bad), { recursive: true, force: true });
104
+ return 0;
105
+ }
106
+
107
+ function listDir(dir) {
108
+ try {
109
+ return fs.readdirSync(dir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name);
110
+ } catch {
111
+ return [];
112
+ }
113
+ }
114
+
115
+ function copyEntry(from, to) {
116
+ const stat = fs.statSync(from);
117
+ if (stat.isDirectory()) {
118
+ fs.mkdirSync(to, { recursive: true });
119
+ for (const entry of fs.readdirSync(from, { withFileTypes: true })) copyEntry(path.join(from, entry.name), path.join(to, entry.name));
120
+ } else if (stat.isFile()) {
121
+ fs.mkdirSync(path.dirname(to), { recursive: true });
122
+ fs.copyFileSync(from, to);
123
+ }
124
+ }
125
+
126
+ // 用包里的模板铺出一个空白的工作目录(目录本身要先建好)。返回空白核对没通过的问题;空数组就是铺好了
127
+ function writeWorkdir(dir, packageRoot) {
128
+ for (const rel of [...SHARED, ...BLANK.map((f) => `templates/${f}`)]) {
129
+ const from = path.join(packageRoot, rel);
130
+ if (!fs.existsSync(from)) throw new Error(`这个包不完整:没有 ${rel}。重新安装一次 work-rhythm`);
131
+ copyEntry(from, path.join(dir, rel.replace(/^templates\//, '')));
132
+ }
133
+ fs.writeFileSync(path.join(dir, '.gitignore'), GITIGNORE);
134
+ for (const keep of KEEPS) {
135
+ fs.mkdirSync(path.dirname(path.join(dir, keep)), { recursive: true });
136
+ fs.writeFileSync(path.join(dir, keep), '');
137
+ }
138
+ fs.writeFileSync(path.join(dir, '00-config', 'profile.yaml'), fs.readFileSync(path.join(dir, '00-config', 'profile.example.yaml')));
139
+ const sources = path.join(dir, '00-config', 'sources.yaml');
140
+ fs.writeFileSync(sources, blankSources(fs.readFileSync(sources, 'utf8')));
141
+ return blankProblems(dir);
142
+ }
143
+
144
+ module.exports = { SHARED, BLANK, KEEPS, GITIGNORE, blankCarryover, blankRhythm, blankSources, blankText, blankProblems, blank, writeWorkdir };
@@ -0,0 +1,89 @@
1
+ // 工作目录在哪:从当前目录往上找带 00-config/profile.yaml 的目录,找不到看用户级的登记;登记、扫描也在这里。
2
+ // 用户级配置默认在 ~/.config/work-rhythm/config.yaml,可用环境变量 WORK_RHYTHM_CONFIG 改位置。
3
+ // work-rhythm 的每个命令都靠它定作用在哪个目录上(cli.js);skill 的「找工作目录」也是它
4
+ 'use strict';
5
+ const fs = require('node:fs');
6
+ const path = require('node:path');
7
+ const { readText, writeFileAtomic } = require('./run');
8
+
9
+ const MARKER = '00-config/profile.yaml';
10
+ const isWorkdir = (dir) => !!dir && fs.existsSync(path.join(dir, MARKER));
11
+
12
+ const configPath = (env = process.env) => env.WORK_RHYTHM_CONFIG || path.join(env.XDG_CONFIG_HOME || path.join(env.HOME || '', '.config'), 'work-rhythm', 'config.yaml');
13
+
14
+ // 登记的路径(~ 开头的换成 HOME);没登记返回空串
15
+ function registered(env = process.env) {
16
+ const m = readText(configPath(env)).split('\n').map((l) => /^\s*workdir:\s*(.*)$/.exec(l)).find(Boolean);
17
+ if (!m) return '';
18
+ const value = m[1].replace(/\s#.*$/, '').trim().replace(/^["']|["']$/g, '');
19
+ return value.replace(/^~(?=\/|$)/, env.HOME || '');
20
+ }
21
+
22
+ // 登记为工作目录:只改配置里的 workdir 那一行,别的内容原样保留。返回绝对路径
23
+ function register(dir, env = process.env) {
24
+ const file = configPath(env);
25
+ const lines = readText(file).split('\n');
26
+ const at = lines.findIndex((l) => /^\s*workdir:/.test(l));
27
+ if (at >= 0) lines[at] = `${/^\s*/.exec(lines[at])[0]}workdir: ${dir}`;
28
+ else {
29
+ if (lines.length > 1 || lines[0]) lines.push(`workdir: ${dir}`);
30
+ else lines[0] = `workdir: ${dir}`;
31
+ }
32
+ writeFileAtomic(file, `${lines.join('\n').replace(/\n*$/, '')}\n`);
33
+ return dir;
34
+ }
35
+
36
+ // 从某个目录往上找第一个工作目录;找不到返回空串
37
+ function findUp(start) {
38
+ let dir = path.resolve(start);
39
+ for (;;) {
40
+ if (isWorkdir(dir)) return dir;
41
+ const parent = path.dirname(dir);
42
+ if (parent === dir) return '';
43
+ dir = parent;
44
+ }
45
+ }
46
+
47
+ // 命令作用在哪个目录:--workdir 指定的优先,其次从当前目录往上找,再看登记。
48
+ // 返回 { root, source: 'option' | 'cwd' | 'pointer' | 'none', problem };登记了但用不了时 problem 说明原因
49
+ function resolveRoot({ cwd = process.cwd(), option = '', env = process.env } = {}) {
50
+ if (option) return { root: path.resolve(option), source: 'option', problem: '' };
51
+ const up = findUp(cwd);
52
+ if (up) return { root: up, source: 'cwd', problem: '' };
53
+ const reg = registered(env);
54
+ if (reg && isWorkdir(reg)) return { root: reg, source: 'pointer', problem: '' };
55
+ return {
56
+ root: '',
57
+ source: 'none',
58
+ problem: reg ? `登记的工作目录不可用: ${reg}(重新登记: work-rhythm workdir register <路径>)` : '',
59
+ };
60
+ }
61
+
62
+ // 扫描几个目录,列出里面的工作目录(带 00-config/profile.yaml 的)。跳过系统目录、依赖目录和版本库,最多往下 6 层。
63
+ // 每个是 { dir, status, name }:status 是 setup.status,name 是 identity.name
64
+ function findAll(starts, home) {
65
+ const SKIP = new Set(['Library', '.Trash', 'node_modules', '.git', '.cache', '.npm']);
66
+ const found = new Map();
67
+ const walk = (dir, depth) => {
68
+ let entries;
69
+ try {
70
+ entries = fs.readdirSync(dir, { withFileTypes: true });
71
+ } catch {
72
+ return;
73
+ }
74
+ for (const entry of entries) {
75
+ const full = path.join(dir, entry.name);
76
+ if (entry.isDirectory()) {
77
+ if (!SKIP.has(entry.name) && depth < 6) walk(full, depth + 1);
78
+ } else if (entry.name === 'profile.yaml' && path.basename(dir) === '00-config' && entry.isFile()) {
79
+ const work = path.dirname(dir);
80
+ const profile = require('./config').loadProfile(work);
81
+ if (!found.has(work)) found.set(work, { dir: work, status: profile.setup && profile.setup.status || '', name: profile.identity && profile.identity.name || '' });
82
+ }
83
+ }
84
+ };
85
+ for (const start of starts.length ? starts : [home]) walk(path.resolve(start), 1);
86
+ return [...found.values()].sort((a, b) => (a.dir < b.dir ? -1 : 1));
87
+ }
88
+
89
+ module.exports = { MARKER, isWorkdir, configPath, registered, register, findUp, resolveRoot, findAll };
@@ -0,0 +1,217 @@
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 { makeSandbox, read, write, setKey } = require('./harness');
7
+
8
+ // 搭工作目录(空白模板)。check 的退出码:0 全部通过,1 有未通过的项
9
+ function setup(t) {
10
+ const box = makeSandbox(t);
11
+ box.workdir();
12
+ const profile = `${box.work}/00-config/profile.yaml`;
13
+ const sources = `${box.work}/00-config/sources.yaml`;
14
+ const stubs = box.stubs();
15
+ return {
16
+ box,
17
+ stubs,
18
+ profile,
19
+ sources,
20
+ setNotify: (value) => write(profile, setKey(read(profile), 'notify', value)),
21
+ localEnv: (text) => write(`${box.work}/collectors/local.env`, text),
22
+ check: (env = { STUB_KEYCHAIN: 'no' }) => box.run(['check'], { env }),
23
+ };
24
+ }
25
+
26
+ test('check:干净的模板上全部通过', (t) => {
27
+ const s = setup(t);
28
+ const r = s.check();
29
+ assert.equal(r.code, 0, r.out);
30
+ assert.match(r.stdout, /== 1\/6 脚本语法 ==\n== 2\/6 文档内链 ==\n== 3\/6 预算 ==\n== 4\/6 配置自检 ==\n== 5\/6 疑似密钥 ==\n== 6\/6 笔记格式 ==\n全部通过\n/);
31
+ assert.equal(r.stderr, '');
32
+ });
33
+
34
+ test('check:报出没配置的源、缺脚本的源、疑似密钥(含机器人 Webhook 的 token,只报位置)和断链', (t) => {
35
+ const s = setup(t);
36
+ write(s.sources, `${read(s.sources)}
37
+
38
+ - id: im-probe
39
+ name: 自测用
40
+ enabled: true
41
+ collector: im-yzj
42
+ cadence: on-demand
43
+ extract: |
44
+ 仅用于自测。
45
+
46
+ - id: nofile
47
+ name: 自测用
48
+ enabled: true
49
+ collector: collectors/nope.sh
50
+ cadence: on-demand
51
+ extract: |
52
+ 仅用于自测。
53
+ `);
54
+ write(`${s.box.work}/02-daily/2026-11/2026-11-27.md`, '# 2026-11-27\n\n## 备注\n\n- 密钥 sk-abcdefghijklmnop1234 不该出现在这里\n- 机器人地址 https://www.yunzhijia.com/gateway/robot/webhook/send?yzjtype=0&yzjtoken=abcdef0123456789abcd\n');
55
+ write(`${s.box.work}/docs/broken.md`, '[断链](nope.md)\n');
56
+ const r = s.check();
57
+ assert.equal(r.code, 1);
58
+ assert.match(r.stdout, /已启用的源 im-probe 需要 collectors\/local.env(从 local.env.example 复制后填写 YZJ_GROUP_IDS_IM_PROBE)/);
59
+ assert.match(r.stdout, /已启用的源 nofile 缺采集脚本: collectors\/nope.sh(关掉它,或把脚本补上)/);
60
+ assert.match(r.stdout, /疑似密钥,先删掉再提交(下面只是位置):\n02-daily\/2026-11\/2026-11-27.md:5\n02-daily\/2026-11\/2026-11-27.md:6\n/);
61
+ assert.match(r.stdout, /断链 \.\/docs\/broken.md -> nope.md/);
62
+ assert.ok(!r.stdout.includes('sk-abcdefghijklmnop1234'));
63
+ assert.ok(!r.stdout.includes('abcdef0123456789abcd'));
64
+ // 断链 1、源 2、密钥 2(两行各算一处)
65
+ assert.match(r.stdout, /5 项未通过\n/);
66
+ });
67
+
68
+ test('check:源用内置采集器时,变量在 local.env 里配了就不报;要的命令没装就报', (t) => {
69
+ const s = setup(t);
70
+ let text = read(s.sources).replace(/(\n\s*- id: linky-issues[\s\S]*?enabled:) false/, '$1 true');
71
+ assert.notEqual(text, read(s.sources), 'sources.yaml 里没找到 linky-issues');
72
+ write(s.sources, text);
73
+ s.localEnv('YZJ_GROUP_IDS_IM_PROBE="g1|g2"\n');
74
+ // PATH 上没有假的 linky(也不带 stubs)
75
+ const r = s.check({ PATH: '/usr/bin:/bin' });
76
+ assert.equal(r.code, 1, r.out);
77
+ assert.match(r.stdout, /已启用的源 linky-issues 需要 linky,本机没有/);
78
+ // 装上就好
79
+ assert.equal(s.check({ ...s.stubs, PATH: `${s.box.bin}:/usr/bin:/bin` }).code, 0);
80
+ });
81
+
82
+ test('check:local.env 引用未定义变量、写法不对时报出来', (t) => {
83
+ const s = setup(t);
84
+ s.localEnv('GIT_ACTIVITY_WORKSPACES="$HOME/ws"\nFILE_ACTIVITY_WORKSPACES="$UNDEFINED_THING/x"\n这一行不是赋值\n');
85
+ const r = s.check();
86
+ assert.equal(r.code, 1);
87
+ assert.match(r.stdout, /collectors\/local.env 第 2 行引用了未定义的变量 UNDEFINED_THING/);
88
+ assert.match(r.stdout, /collectors\/local.env 第 3 行不是 KEY=VALUE 的写法:这一行不是赋值/);
89
+ assert.ok(!r.stdout.includes('第 1 行'), '$HOME 是有定义的');
90
+ });
91
+
92
+ test('check:自己写的采集器有语法错时报出来', (t) => {
93
+ const s = setup(t);
94
+ write(`${s.box.work}/collectors/broken.js`, 'const = 1;\n');
95
+ const r = s.check();
96
+ assert.equal(r.code, 1);
97
+ assert.match(r.stdout, /Unexpected token '='\n语法错误 collectors\/broken\.js\n/);
98
+ });
99
+
100
+ test('check:报出文件名不对、没有 Verified、缺小节的踩坑笔记', (t) => {
101
+ const s = setup(t);
102
+ const dir = `${s.box.work}/.agents/notes/pitfalls`;
103
+ write(`${dir}/nodate.md`, '# 没写怎么验证的笔记\n\n## 现象\n\nx\n');
104
+ write(`${dir}/2026-11-29-incomplete.md`, '# 缺了小节的笔记\n\n## 现象\n\nx\n');
105
+ // 头部信息夹在 front matter 里(第 3、4 行)也算有
106
+ write(`${dir}/2026-11-28-frontmatter.md`, '---\ntitle: x\nVerified: 2026-11-28 · 再跑一遍\nOrigin: 2026-11-28 · 自测 · 跑出来\n---\n\n# 带头部信息的笔记\n\n## 现象\n\n## 原因\n\n## 怎么做\n');
107
+ const r = s.check();
108
+ assert.equal(r.code, 1, r.out);
109
+ assert.match(r.stdout, /笔记 \.agents\/notes\/pitfalls\/nodate\.md:文件名应为 yyyy-mm-dd-<英文短横线标题>\.md\n/);
110
+ assert.match(r.stdout, /incomplete\.md:前 6 行里没有「Verified: yyyy-mm-dd · <重新确认这个坑还在的方法>」/);
111
+ assert.match(r.stdout, /incomplete\.md:前 6 行里没有「Origin: yyyy-mm-dd · <在哪踩的> · <怎么发现的>」/);
112
+ assert.match(r.stdout, /incomplete\.md:缺少小节「## 原因」/);
113
+ assert.match(r.stdout, /incomplete\.md:缺少小节「## 怎么做」/);
114
+ assert.ok(!r.stdout.includes('frontmatter.md'), '头部信息写在 front matter 里也算有');
115
+ // 文件名不对的只报文件名,不再往下查
116
+ assert.equal(r.stdout.split('\n').filter((l) => l.includes('nodate.md')).length, 1);
117
+ assert.match(r.stdout, /5 项未通过\n/);
118
+ });
119
+
120
+ test('check:报出 skill 头部里不认识的键和过长的 description', (t) => {
121
+ const s = setup(t);
122
+ const skill = `${s.box.work}/.agents/skills/work-rhythm/SKILL.md`;
123
+ const original = read(skill);
124
+ const padded = original.replace(/^(description: "[^"]*)"$/m, `$1${'追加的说明文字'.repeat(20)}"`);
125
+ assert.notEqual(padded, original, '没找到 description 那一行');
126
+ write(skill, padded.replace(/^name: work-rhythm$/m, 'name: work-rhythm\nversion: 9'));
127
+ const r = s.check();
128
+ assert.equal(r.code, 1, r.out);
129
+ assert.match(r.stdout, /SKILL\.md 的头部有 ZCode 不认识的键:version(会被忽略;其他信息放进 metadata)/);
130
+ assert.match(r.stdout, /SKILL\.md 的 description 超过 250 个字符(现在 \d+),超出的部分模型看不到/);
131
+ });
132
+
133
+ test('check:SKILL.md 太长、AGENTS.md 的行数和 standing orders 超了也报', (t) => {
134
+ const s = setup(t);
135
+ const skill = `${s.box.work}/.agents/skills/work-rhythm/SKILL.md`;
136
+ write(skill, `${read(skill)}\n${Array.from({ length: 600 }, () => '填充').join('\n')}\n`);
137
+ write(`${s.box.work}/AGENTS.md`, `# x\n\n## Standing orders\n\n${Array.from({ length: 11 }, () => '- 一条').join('\n')}\n`);
138
+ const r = s.check();
139
+ assert.match(r.stdout, /SKILL\.md 超过 500 个非空行/);
140
+ assert.match(r.stdout, /AGENTS\.md 的 standing orders 超过 10 条/);
141
+ assert.ok(!r.stdout.includes('AGENTS.md 超过 60 个非空行'), 'AGENTS.md 没到 60 行');
142
+ });
143
+
144
+ test('check:profile.yaml 缺了空白模板里声明的字段时报出来', (t) => {
145
+ const s = setup(t);
146
+ const original = read(s.profile);
147
+ write(s.profile, original.split('\n').filter((l) => !/^\s*notify:/.test(l)).join('\n'));
148
+ const r = s.check();
149
+ assert.equal(r.code, 1);
150
+ assert.match(r.stdout, /00-config\/profile\.yaml 缺了这些字段(对照 profile\.example\.yaml 补上): notify/);
151
+ assert.ok(!r.stdout.includes('alerts-morning'), '个人多加的字段不管');
152
+ });
153
+
154
+ test('check:消息渠道 yzj-robot 配了、钥匙串里却没有地址时报出来,不打印地址', (t) => {
155
+ const s = setup(t);
156
+ s.setNotify('yzj-robot');
157
+ const r = s.check({ STUB_KEYCHAIN: 'no' });
158
+ assert.equal(r.code, 1);
159
+ assert.match(r.stdout, /消息渠道 yzj-robot:钥匙串里没有 work-rhythm-yzj-robot-webhook(开通步骤见 docs\/channels\.md「云之家」)/);
160
+ assert.ok(!r.stdout.includes('stubtoken'));
161
+ assert.equal(s.check({ STUB_KEYCHAIN: 'ok' }).code, 0);
162
+ });
163
+
164
+ test('check:没装 security 时报出来', (t) => {
165
+ const s = setup(t);
166
+ s.setNotify('yzj-robot');
167
+ const empty = path.join(s.box.root, 'empty-bin');
168
+ fs.mkdirSync(empty, { recursive: true });
169
+ // PATH 上有 node 和 bash、没有 security(它在 /usr/bin 里)
170
+ const r = s.check({ PATH: `${path.dirname(process.execPath)}:/bin:${empty}` });
171
+ assert.equal(r.code, 1, r.out);
172
+ assert.match(r.stdout, /消息渠道 yzj-robot 需要 security,本机没有/);
173
+ });
174
+
175
+ test('check:值守配的命令找不到时报出来', (t) => {
176
+ const s = setup(t);
177
+ s.setNotify('yzj-robot');
178
+ s.localEnv('YZJ_BOT_AGENT="/nonexistent/agent x"\nYZJ_MY_OPEN_ID="me-0001"\n');
179
+ const r = s.check({ STUB_KEYCHAIN: 'ok' });
180
+ assert.equal(r.code, 1);
181
+ assert.match(r.stdout, /YZJ_BOT_AGENT 的命令找不到: \/nonexistent\/agent/);
182
+ assert.ok(!r.stdout.includes('值守属于 yzj-robot 渠道'));
183
+ });
184
+
185
+ test('check:值守没写我的 openId 时报出来', (t) => {
186
+ const s = setup(t);
187
+ s.setNotify('yzj-robot');
188
+ s.localEnv('YZJ_BOT_AGENT="zcode"\n');
189
+ const r = s.check({ STUB_KEYCHAIN: 'ok' });
190
+ assert.match(r.stdout, /要写 YZJ_MY_OPEN_ID/);
191
+ assert.ok(!r.stdout.includes('值守属于 yzj-robot 渠道'));
192
+ });
193
+
194
+ test('check:notify 不是 yzj-robot 却配了值守时报出来;值守配好之后不再报它', (t) => {
195
+ const s = setup(t);
196
+ s.localEnv(`YZJ_BOT_AGENT="zcode"\nYZJ_MY_OPEN_ID="me-0001"\nZCODE_CLI="${s.stubs.ZCODE_CLI}"\n`);
197
+ s.setNotify('""');
198
+ assert.match(s.check({ STUB_KEYCHAIN: 'ok' }).stdout, /值守属于 yzj-robot 渠道:preferences\.notify 要设成 yzj-robot/);
199
+ s.setNotify('yzj-robot');
200
+ const ok = s.check({ STUB_KEYCHAIN: 'ok' });
201
+ assert.equal(ok.code, 0, ok.out);
202
+ assert.ok(!ok.stdout.includes('值守'));
203
+ });
204
+
205
+ test('check:值守配了 dsh 却找不到它的配置时报出来', (t) => {
206
+ const s = setup(t);
207
+ s.setNotify('yzj-robot');
208
+ s.localEnv(`YZJ_BOT_AGENT="dsh"\nYZJ_MY_OPEN_ID="me-0001"\nDSH_HOME="${s.box.root}/no-such-home"\nDSH_NODE="${path.join(s.box.bin, 'fake-dsh-node')}"\nDSH_CLI="${path.join(s.box.bin, 'fake-dsh')}"\n`);
209
+ const r = s.check({ STUB_KEYCHAIN: 'ok' });
210
+ assert.equal(r.code, 1);
211
+ assert.match(r.stdout, /找不到 DSH 的配置/);
212
+ });
213
+
214
+ test('check:用法不对时退出码为 2', (t) => {
215
+ const s = setup(t);
216
+ assert.equal(s.box.run(['check', '什么']).code, 2);
217
+ });