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,114 @@
1
+ #!/usr/bin/env node
2
+ // 采集云之家里等我审批的流程:供 AI 提炼「审批」事件,也让每日计划知道有多少单子等着批
3
+ // 用法: node collectors/approval-yzj.js <输出目录> [起始日期 YYYY-MM-DD,用来判断哪些是之后新到的,默认今天]
4
+ // 输出: <输出目录>/approvals.tsv —— 单据类型、待办数、其中起始日之后新到的、最新一条的到达时间,按待办数倒序
5
+ // 前提: yzj-cli 已登录(yzj-cli auth login)
6
+ // 说明: 只留单据类型和数量,不留单据标题、申请人和金额。没取齐(拿到的条数少于 total)按失败处理:
7
+ // 半份清单不能当作「我有多少单子要批」。两次调用之间留间隔(YZJ_CALL_INTERVAL,默认 2 秒)。
8
+ 'use strict';
9
+ const fs = require('node:fs');
10
+ const path = require('node:path');
11
+ const { EXIT, UsageError, run, startOfDay, tail } = require('../scripts/lib/run');
12
+ const { context, needTool, tempDir, sleep, writeTsv } = require('../scripts/lib/collector');
13
+
14
+ const pad = (n) => String(n).padStart(2, '0');
15
+ const localMinutes = (epochSeconds) => {
16
+ const d = new Date(epochSeconds * 1000);
17
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
18
+ };
19
+
20
+ async function collect(argv) {
21
+ const ctx = context(argv, 'approval-yzj', 'approval-yzj.js <输出目录> [起始日期]');
22
+ const { out, since, env } = ctx;
23
+ const interval = Number(env.YZJ_CALL_INTERVAL === undefined ? 2 : env.YZJ_CALL_INTERVAL);
24
+ // 起始日 0 点的毫秒时间戳
25
+ let sinceMs;
26
+ try {
27
+ sinceMs = startOfDay(since);
28
+ } catch {
29
+ throw new UsageError(`approval-yzj: 无法识别日期 '${since}'`);
30
+ }
31
+ if (!needTool(ctx, 'yzj-cli')) return EXIT.MISSING_DEP;
32
+ // 原始分页先落到临时目录:工作目录里只留那张表,用完即删
33
+ const work = tempDir('approval-yzj-');
34
+ try {
35
+ // 每页最多 100 条,拿到 total 条为止
36
+ const pages = [];
37
+ let page = 1;
38
+ let got = 0;
39
+ let total = 0;
40
+ for (;;) {
41
+ if (page > 1) await sleep(Math.max(0, interval) * 1000);
42
+ const r = run('yzj-cli', ['approval', 'flow', 'list', '--type', 'todo', '--limit', '100', '--page', String(page)], { env });
43
+ if (r.code !== 0) {
44
+ ctx.note(`拉取失败(未登录?试试 yzj-cli auth login): ${tail(r.stderr, 300)}`);
45
+ return EXIT.FAILED;
46
+ }
47
+ let doc = null;
48
+ try {
49
+ doc = JSON.parse(r.stdout);
50
+ } catch {
51
+ doc = null;
52
+ }
53
+ const list = doc && doc.data && doc.data.list;
54
+ if (!doc || doc.success !== true || !Array.isArray(list) || typeof doc.data.total !== 'number') {
55
+ ctx.note('返回的结构不对,这份清单不能当作我要批的全部单子');
56
+ return EXIT.FAILED;
57
+ }
58
+ fs.writeFileSync(path.join(work, `page-${page}.json`), r.stdout);
59
+ pages.push(doc);
60
+ got += list.length;
61
+ total = doc.data.total;
62
+ if (!(list.length > 0 && got < total)) break;
63
+ page += 1;
64
+ if (page > 50) {
65
+ ctx.note(`翻了 50 页还没取齐(已 ${got}/${total}),这份清单不完整`);
66
+ return EXIT.FAILED;
67
+ }
68
+ }
69
+ if (got !== total) {
70
+ ctx.note(`没取齐(拿到 ${got} 条,共 ${total} 条),这份清单不能当作我要批的全部单子`);
71
+ return EXIT.FAILED;
72
+ }
73
+
74
+ // 单据类型取模板名;没有模板名的(「流程助手」的流程)只能记到应用名,它没有别的可区分字段
75
+ const groups = new Map();
76
+ for (const doc of pages) {
77
+ for (const item of doc.data.list) {
78
+ const type = String(item.templateName || '') !== '' ? item.templateName : (item.appName || '未知类型');
79
+ if (!groups.has(type)) groups.set(type, []);
80
+ groups.get(type).push(item);
81
+ }
82
+ }
83
+ const rows = [...groups.entries()].map(([type, items]) => {
84
+ const times = items.map((it) => Number(it.createTime) || 0);
85
+ const newest = Math.max(...times, 0);
86
+ return {
87
+ type,
88
+ pending: items.length,
89
+ fresh: items.filter((it) => (Number(it.createTime) || 0) >= sinceMs).length,
90
+ newest: newest / 1000,
91
+ };
92
+ }).sort((a, b) => (a.type < b.type ? -1 : a.type > b.type ? 1 : 0));
93
+ rows.sort((a, b) => b.pending - a.pending); // 稳定排序:待办数相同的仍按类型排
94
+ const table = rows.map((r) => [r.type, String(r.pending), String(r.fresh), localMinutes(Math.floor(r.newest))]);
95
+ fs.mkdirSync(out, { recursive: true });
96
+ writeTsv(path.join(out, 'approvals.tsv'), ['type', 'pending', 'new', 'newest'], table);
97
+ ctx.note(`待我审批 ${total} 条,其中 ${since} 之后新到 ${rows.reduce((s, r) => s + r.fresh, 0)} 条`);
98
+ return EXIT.OK;
99
+ } finally {
100
+ fs.rmSync(work, { recursive: true, force: true });
101
+ }
102
+ }
103
+
104
+ module.exports = { collect };
105
+
106
+ if (require.main === module) {
107
+ collect(process.argv.slice(2)).then(
108
+ (code) => process.exit(code),
109
+ (error) => {
110
+ process.stderr.write(`${error.message}\n`);
111
+ process.exit(error instanceof UsageError ? EXIT.USAGE : EXIT.FAILED);
112
+ },
113
+ );
114
+ }
@@ -0,0 +1,48 @@
1
+ #!/usr/bin/env node
2
+ // 采集云之家日程:拉取起始日起若干天的日程,供 AI 提炼「会议」事件
3
+ // 用法: node collectors/calendar-yzj.js <输出目录> [起始日期 YYYY-MM-DD,默认今天] [天数,默认 1]
4
+ // 输出: <输出目录>/events-<起始日期>.json
5
+ // 前提: yzj-cli 已登录(yzj-cli auth login)
6
+ 'use strict';
7
+ const fs = require('node:fs');
8
+ const path = require('node:path');
9
+ const { EXIT, UsageError, run, addDays, tail } = require('../scripts/lib/run');
10
+ const { context, needTool } = require('../scripts/lib/collector');
11
+
12
+ async function collect(argv) {
13
+ const ctx = context(argv, 'calendar-yzj', 'calendar-yzj.js <输出目录> [起始日期] [天数]');
14
+ const { out, since, env } = ctx;
15
+ const days = argv[2] === undefined ? 1 : Number(argv[2]);
16
+ if (!/^\d+$/.test(String(argv[2] ?? '1')) || days < 1) throw new UsageError(`calendar-yzj: 无法识别日期 '${since}'`);
17
+ let end = '';
18
+ try {
19
+ end = addDays(since, days - 1);
20
+ } catch {
21
+ end = '';
22
+ }
23
+ if (!end) throw new UsageError(`calendar-yzj: 无法识别日期 '${since}'`);
24
+ if (!needTool(ctx, 'yzj-cli')) return EXIT.MISSING_DEP;
25
+ const target = path.join(out, `events-${since}.json`);
26
+ fs.mkdirSync(out, { recursive: true });
27
+ const r = run('yzj-cli', ['calendar', 'event', 'list', '--start', since, '--end', end], { env });
28
+ if (r.code !== 0) {
29
+ ctx.note(`拉取失败(未登录?试试 yzj-cli auth login): ${tail(r.stderr, 300)}`);
30
+ fs.rmSync(target, { force: true }); // 同一天重复同步只留最新一份:失败时不留下上一次的旧文件
31
+ return EXIT.FAILED;
32
+ }
33
+ fs.writeFileSync(target, r.stdout);
34
+ ctx.note(`已拉取 ${since} 至 ${end} 的日程`);
35
+ return EXIT.OK;
36
+ }
37
+
38
+ module.exports = { collect };
39
+
40
+ if (require.main === module) {
41
+ collect(process.argv.slice(2)).then(
42
+ (code) => process.exit(code),
43
+ (error) => {
44
+ process.stderr.write(`${error.message}\n`);
45
+ process.exit(error instanceof UsageError ? EXIT.USAGE : EXIT.FAILED);
46
+ },
47
+ );
48
+ }
@@ -0,0 +1,131 @@
1
+ #!/usr/bin/env node
2
+ // 采集文件活动:列出 WORKSPACES 下自起始日起被修改的文件,按项目(工作区下的一级目录)和扩展名汇总
3
+ // 用法: node collectors/file-activity.js <输出目录> [起始日期 YYYY-MM-DD,默认今天]
4
+ // 输出: <输出目录>/summary.tsv(项目、文件数、主要扩展名、备注)和 files.txt(命中文件,最多 MAX_FILES 条)
5
+ // macOS 上优先用 Spotlight(快);索引有延迟或目录没被索引时,用逐层扫描补上或复核
6
+ // 配置: collectors/local.env 的 FILE_ACTIVITY_WORKSPACES(扫哪些目录,| 分隔;默认 ~/workspace)、
7
+ // FILE_ACTIVITY_IGNORE_EXTS(不关心的扩展名,| 分隔)
8
+ 'use strict';
9
+ const fs = require('node:fs');
10
+ const path = require('node:path');
11
+ const { EXIT, run, which, startOfDay, walkFiles } = require('../scripts/lib/run');
12
+ const { context, writeTsv } = require('../scripts/lib/collector');
13
+
14
+ const MAX_FILES = 300;
15
+ // 不关心的目录:版本库、依赖、构建产物、IDE 配置
16
+ const PRUNE = '.git node_modules dist build target out .venv venv .next .nuxt __pycache__ .cache .turbo coverage .pytest_cache .idea .vscode'.split(' ');
17
+ const DEFAULT_IGNORE = '.jsonl|.log|.map|.tsbuildinfo|.lock|.pid|.db|.sqlite|.gz|.zip|.tar|.bak|.tmp';
18
+ // 一个项目一天内改动的文件超过这个数,多半是运行或测试产物,而不是手改
19
+ const NOISE_THRESHOLD = 150;
20
+
21
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
22
+ const isDir = (p) => {
23
+ try {
24
+ return fs.statSync(p).isDirectory();
25
+ } catch {
26
+ return false;
27
+ }
28
+ };
29
+
30
+ async function collect(argv) {
31
+ const ctx = context(argv, 'file-activity', 'file-activity.js <输出目录> [起始日期]');
32
+ const { out, since, env, home } = ctx;
33
+ const workspaces = (env.FILE_ACTIVITY_WORKSPACES || path.join(home, 'workspace')).split('|').map((s) => s.trim()).filter(Boolean);
34
+ const ignoreExts = (env.FILE_ACTIVITY_IGNORE_EXTS || DEFAULT_IGNORE).split('|').map((s) => s.trim()).filter(Boolean);
35
+ const prune = new Set(PRUNE);
36
+ const pruned = new RegExp(`[/\\\\](${PRUNE.map(escapeRe).join('|')})([/\\\\]|$)`);
37
+ const sinceMs = startOfDay(since);
38
+ const recentMs = Date.now() - 30 * 60 * 1000;
39
+ const spotlight = which('mdfind', env) && which('mdls', env) ? which('mdfind', env) : '';
40
+
41
+ const files = [];
42
+ const counted = [];
43
+ let fast = 0;
44
+ let slow = 0;
45
+ let recheck = 0;
46
+ for (let ws of workspaces) {
47
+ if (!isDir(ws)) continue;
48
+ ws = ws.replace(/\/+$/, '');
49
+ // 工作区本身就是一个仓库时整个目录算一个项目;否则它下面的一级目录各算一个项目
50
+ const single = fs.existsSync(path.join(ws, '.git'));
51
+ const scan = (from) => walkFiles(ws, prune, from).filter((f) => !pruned.test(f)).sort();
52
+ let hits;
53
+ // 目录是不是被 Spotlight 索引:mdls 对没索引的目录回 (null)
54
+ const indexed = spotlight && run('mdls', ['-raw', '-name', 'kMDItemFSContentChangeDate', ws], { env }).stdout.trim() !== '(null)';
55
+ if (indexed) {
56
+ fast += 1;
57
+ // Spotlight 快,但有两处靠不住:索引有延迟,刚改的文件可能还没进去;目录没被索引时它不报错,
58
+ // 只是什么都不返回。所以最近 30 分钟改动的文件用逐层扫描补上,两路结果去重;它什么都没返回时整个改用逐层扫描。
59
+ // 查询串里的 $time 是 Spotlight 自己的语法,前面不能有反斜杠(bash 里要写 \$ 是为了不让 shell 展开;这里不经过 shell)
60
+ const found = run(spotlight, ['-onlyin', ws, `kMDItemFSContentChangeDate >= $time.iso(${since}) && kMDItemContentTypeTree != 'public.folder'`], { env })
61
+ .stdout.split('\n').filter(Boolean);
62
+ hits = [...new Set([...found, ...walkFiles(ws, prune, recentMs)])].filter((f) => !pruned.test(f)).sort();
63
+ if (!hits.length) {
64
+ recheck += 1;
65
+ hits = scan(sinceMs);
66
+ }
67
+ } else {
68
+ slow += 1;
69
+ hits = scan(sinceMs);
70
+ }
71
+ for (const f of hits) {
72
+ const dot = f.lastIndexOf('.');
73
+ const ext = dot >= 0 ? f.slice(dot) : '';
74
+ if (!/\/\.DS_Store$/.test(f) && !ignoreExts.includes(ext)) files.push(f);
75
+ }
76
+ if (!hits.length) continue;
77
+ // 项目 = 工作区下的一级目录;扩展名 = 文件名最后一个点之后(没有则记「无」)
78
+ const base = `${ws}/`;
79
+ const wsName = path.basename(ws);
80
+ for (const f of hits) {
81
+ const rel = f.startsWith(base) ? f.slice(base.length) : path.basename(f);
82
+ const fname = rel.slice(rel.lastIndexOf('/') + 1);
83
+ if (fname === '.DS_Store') continue;
84
+ const dot = fname.lastIndexOf('.');
85
+ const ext = dot > 0 ? fname.slice(dot).toLowerCase() : '(无)'; // 以点开头的文件名不算有扩展名
86
+ if (ignoreExts.includes(ext)) continue;
87
+ const proj = single || !rel.includes('/') ? wsName : `${wsName}/${rel.split('/')[0]}`;
88
+ counted.push([proj, ext]);
89
+ }
90
+ }
91
+
92
+ // 先数出「项目 × 扩展名」的条数,再按项目合并成一行,扩展名只留前三
93
+ const counts = new Map();
94
+ for (const [proj, ext] of counted) {
95
+ const key = `${proj}\t${ext}`;
96
+ counts.set(key, (counts.get(key) || 0) + 1);
97
+ }
98
+ const entries = [...counts.entries()].map(([key, n]) => {
99
+ const [proj, ext] = key.split('\t');
100
+ return { proj, ext, n };
101
+ }).sort((a, b) => (a.proj < b.proj ? -1 : a.proj > b.proj ? 1 : b.n - a.n));
102
+ const rows = [];
103
+ let cur = null;
104
+ for (const e of entries) {
105
+ if (!cur || cur.proj !== e.proj) {
106
+ cur = { proj: e.proj, total: 0, tops: [], n: 0 };
107
+ rows.push(cur);
108
+ }
109
+ cur.total += e.n;
110
+ cur.n += 1;
111
+ if (cur.n <= 3) cur.tops.push(`${e.ext} ${e.n}`);
112
+ }
113
+ const table = rows.map((r) => [r.proj, String(r.total), r.tops.join(' '), r.total > NOISE_THRESHOLD ? '文件数异常多,多半是运行或构建产物' : '']);
114
+ fs.mkdirSync(out, { recursive: true });
115
+ writeTsv(path.join(out, 'summary.tsv'), ['project', 'files', 'top_extensions', 'note'], table);
116
+ fs.writeFileSync(path.join(out, 'files.txt'), `${files.slice(0, MAX_FILES).join('\n')}${files.length ? '\n' : ''}`);
117
+ ctx.note(`自 ${since} 起 ${counted.length} 个文件改动,涉及 ${table.length} 个项目(Spotlight ${fast} 个目录,其中 ${recheck} 个没返回结果、已改用逐层扫描复核;逐层扫描 ${slow} 个目录)`);
118
+ return EXIT.OK;
119
+ }
120
+
121
+ module.exports = { collect };
122
+
123
+ if (require.main === module) {
124
+ collect(process.argv.slice(2)).then(
125
+ (code) => process.exit(code),
126
+ (error) => {
127
+ process.stderr.write(`file-activity: ${error && error.stack ? error.stack : String(error)}\n`);
128
+ process.exit(error && error.name === 'UsageError' ? EXIT.USAGE : EXIT.FAILED);
129
+ },
130
+ );
131
+ }
@@ -0,0 +1,105 @@
1
+ #!/usr/bin/env node
2
+ // 采集「我」的代码提交:遍历 WORKSPACES 下的 git 仓库,导出自起始日 00:00 以来我写的提交
3
+ // 子模块算在内,别的仓库的 worktree 不算(它的提交已经包含在主仓库里)
4
+ // 用法: node collectors/git-activity.js <输出目录> [起始日期 YYYY-MM-DD,默认今天]
5
+ // 输出: <输出目录>/commits.tsv —— 时间、仓库、短哈希、说明首行,按时间排序,同一提交只保留一行
6
+ // 旧提交被 rebase / cherry-pick 重新提交时不逐条列出,只压成一行汇总
7
+ // 配置: collectors/local.env 的 GIT_ACTIVITY_WORKSPACES(扫哪些目录,| 分隔;默认 ~/workspace)、
8
+ // GIT_ACTIVITY_AUTHORS(哪些邮箱或姓名算「我」,| 分隔;默认取全局 git 配置)
9
+ 'use strict';
10
+ const fs = require('node:fs');
11
+ const path = require('node:path');
12
+ const { EXIT, run } = require('../scripts/lib/run');
13
+ const { context, needTool, writeTsv } = require('../scripts/lib/collector');
14
+
15
+ const listDir = (dir) => {
16
+ try {
17
+ return fs.readdirSync(dir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => path.join(dir, d.name)).sort();
18
+ } catch {
19
+ return [];
20
+ }
21
+ };
22
+
23
+ // 按作者时间排,同一时间按仓库名排(字节序),和原来 LC_ALL=C sort 一致
24
+ const byTimeThenRepo = (a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : a[2] < b[2] ? -1 : a[2] > b[2] ? 1 : 0);
25
+
26
+ async function collect(argv) {
27
+ const ctx = context(argv, 'git-activity', 'git-activity.js <输出目录> [起始日期]');
28
+ const { out, since, env, home } = ctx;
29
+ const workspaces = (env.GIT_ACTIVITY_WORKSPACES || path.join(home, 'workspace')).split('|');
30
+ // 「我」= 全局 git 身份;公司邮箱等其它身份在 collectors/local.env 的 GIT_ACTIVITY_AUTHORS 里追加
31
+ let authors = env.GIT_ACTIVITY_AUTHORS;
32
+ if (authors === undefined) {
33
+ const email = run('git', ['config', '--global', 'user.email'], { env }).stdout.trim();
34
+ const name = run('git', ['config', '--global', 'user.name'], { env }).stdout.trim();
35
+ authors = `${email}|${name}`;
36
+ }
37
+ if (!needTool(ctx, 'git')) return EXIT.MISSING_DEP;
38
+ const authorList = authors.split('|').map((a) => a.trim()).filter(Boolean);
39
+ if (!authorList.length) {
40
+ ctx.note('无法确定作者身份,请在 collectors/local.env 设置 GIT_ACTIVITY_AUTHORS');
41
+ return EXIT.NOT_CONFIGURED;
42
+ }
43
+
44
+ const rows = [];
45
+ for (const ws of workspaces) {
46
+ if (!fs.existsSync(ws) || !fs.statSync(ws).isDirectory()) continue;
47
+ for (const repo of listDir(ws)) {
48
+ // .git 是目录的是主仓库。.git 是文件的有两种:子模块,和别的仓库的 worktree。
49
+ // worktree 的提交已经包含在主仓库的 --all 里,再数一遍就重复了,所以看它的 git 目录落在哪:
50
+ // 落在某个 .git/worktrees/ 下的是 worktree,跳过;其余的(例如父仓库的 .git/modules/<名字>)是子模块,算进来。
51
+ // 要扫到子模块,把它的上一层目录也列进 GIT_ACTIVITY_WORKSPACES,例如 "$HOME/workspace|$HOME/workspace/minutes"。
52
+ const dotGit = path.join(repo, '.git');
53
+ if (!fs.existsSync(dotGit)) continue;
54
+ if (!fs.statSync(dotGit).isDirectory()) {
55
+ const gitdir = run('git', ['-C', repo, 'rev-parse', '--absolute-git-dir'], { env }).stdout.trim();
56
+ if (!gitdir || /[/\\]\.git[/\\]worktrees[/\\]/.test(gitdir)) continue;
57
+ }
58
+ const name = path.basename(repo);
59
+ const authorArgs = authorList.map((a) => `--author=${a}`);
60
+ const log = run('git', ['-C', repo, 'log', '--all', ...authorArgs, `--since=${since} 00:00:00`, '--date=format-local:%F %T', `--pretty=format:%ad%x09%cd%x09${name}%x09%h%x09%s`], { env });
61
+ // 列:作者时间、提交时间、仓库、哈希、说明。按作者时间算「哪天写的」;
62
+ // 作者时间早于起始日但提交时间在之后的,是被重新提交的旧提交,按仓库压成一行。
63
+ for (const line of log.stdout.split('\n')) {
64
+ const f = line.split('\t');
65
+ if (f.length >= 5) rows.push(f);
66
+ }
67
+ }
68
+ }
69
+
70
+ rows.sort(byTimeThenRepo);
71
+ const seen = new Set();
72
+ const kept = [];
73
+ const carried = new Map();
74
+ for (const f of rows) {
75
+ if (seen.has(f[3])) continue;
76
+ seen.add(f[3], 1);
77
+ if (f[0] >= `${since} 00:00:00`) kept.push([f[0], f[2], f[3], f[4]]);
78
+ else {
79
+ const c = carried.get(f[2]) || { count: 0, last: '' };
80
+ c.count += 1;
81
+ if (f[1] > c.last) c.last = f[1];
82
+ carried.set(f[2], c);
83
+ }
84
+ }
85
+ const lines = kept;
86
+ for (const [repo, c] of carried) lines.push([c.last, repo, '-', `(rebase / cherry-pick:重新提交了 ${c.count} 个更早的提交)`]);
87
+ lines.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
88
+ writeTsv(path.join(out, 'commits.tsv'), ['time', 'repo', 'hash', 'subject'], lines);
89
+
90
+ const repos = new Set(lines.map((l) => l[1])).size;
91
+ ctx.note(`自 ${since} 起 ${lines.length} 条记录,涉及 ${repos} 个仓库`);
92
+ return EXIT.OK;
93
+ }
94
+
95
+ module.exports = { collect };
96
+
97
+ if (require.main === module) {
98
+ collect(process.argv.slice(2)).then(
99
+ (code) => process.exit(code),
100
+ (error) => {
101
+ process.stderr.write(`git-activity: ${error && error.stack ? error.stack : String(error)}\n`);
102
+ process.exit(error && error.name === 'UsageError' ? EXIT.USAGE : EXIT.FAILED);
103
+ },
104
+ );
105
+ }
@@ -0,0 +1,151 @@
1
+ #!/usr/bin/env node
2
+ // 采集云之家消息:拉取订阅会话里最近的 N 条消息(默认 20,也是 yzj-cli 0.1.8 的单页上限,再大会报参数错误),供 AI 提炼事件
3
+ // 用法: node collectors/im-yzj.js <输出目录> [起始日期 YYYY-MM-DD,默认今天。翻页时往前翻到这一天 0 点为止]
4
+ // 输出: <输出目录>/whoami.json、messages-<会话ID>.json —— 该会话取到的全部消息,按时间排序,同一 msgId 只留一条;
5
+ // data.coverage 记这次覆盖的时间段(from / to),下游写总结时要把它写明
6
+ // 前提: yzj-cli 已登录(yzj-cli auth login);collectors/local.env 里为这个源配置了会话 ID
7
+ // 源 id 是 im-yzj 时读 YZJ_GROUP_IDS;换成别的 id(例如 ops-yzj)读 YZJ_GROUP_IDS_<ID>(ID 转大写,- 换成 _)。
8
+ // 这样同一个脚本可以接多个源,各有各的会话和提炼规则。没配置会话 ID 时直接退出,不采集。
9
+ // 两次调用之间默认停 2 秒(YZJ_CALL_INTERVAL 可改):云之家连续调用会返回 10000429 请求过于频繁。
10
+ // 翻页: 每个会话默认只取最新的一页。消息多的群可以配页数,变量名的规则和会话 ID 一样
11
+ // (im-yzj 读 YZJ_MESSAGE_PAGES,别的源读 YZJ_MESSAGE_PAGES_<ID>),每页最多 20 条,往前翻到起始日 0 点为止。
12
+ // 配了多页就要求覆盖到起始日 0 点:翻完还差一截的按失败退出(退出码 5),不把半段当成一整天。只配 1 页时不做这个要求。
13
+ 'use strict';
14
+ const fs = require('node:fs');
15
+ const path = require('node:path');
16
+ const { EXIT, run } = require('../scripts/lib/run');
17
+ const { context, needTool, sleep } = require('../scripts/lib/collector');
18
+
19
+ // 这一页的消息列表;调用失败、或者返回的结构不对时是 null
20
+ function pageOf(r) {
21
+ if (r.code !== 0) return null;
22
+ try {
23
+ const doc = JSON.parse(r.stdout);
24
+ return doc.success === true && doc.data && Array.isArray(doc.data.list) ? doc.data.list : null;
25
+ } catch {
26
+ return null;
27
+ }
28
+ }
29
+
30
+ // 时间戳取成 14 位数字(到秒),按纯数字逐位比较,不受 locale 排序影响
31
+ const digits = (s) => String(s || '').replace(/\D/g, '').slice(0, 14);
32
+ const byTime = (a, b) => (String(a.sendTime) < String(b.sendTime) ? -1 : String(a.sendTime) > String(b.sendTime) ? 1 : 0);
33
+
34
+ async function collect(argv) {
35
+ const ctx = context(argv, 'im-yzj', 'im-yzj.js <输出目录> [起始日期]');
36
+ const { out, since, env } = ctx;
37
+ // 输出目录形如 01-inbox/<源id>/<日期>:从它反推这个源该读哪个变量
38
+ const sourceId = path.basename(path.dirname(out));
39
+ let groupVar;
40
+ let groupIds;
41
+ let pages;
42
+ let pagesVar;
43
+ if (sourceId === 'im-yzj') {
44
+ groupVar = 'YZJ_GROUP_IDS';
45
+ groupIds = env.YZJ_GROUP_IDS || '';
46
+ pagesVar = 'YZJ_MESSAGE_PAGES';
47
+ pages = env.YZJ_MESSAGE_PAGES || '1';
48
+ } else {
49
+ const key = sourceId.toUpperCase().replace(/-/g, '_');
50
+ groupVar = `YZJ_GROUP_IDS_${key}`;
51
+ groupIds = env[groupVar] || '';
52
+ pagesVar = `YZJ_MESSAGE_PAGES_${key}`;
53
+ pages = env[pagesVar] || env.YZJ_MESSAGE_PAGES || '1';
54
+ }
55
+ if (!/^[1-9]\d*$/.test(String(pages))) {
56
+ ctx.note(`${pagesVar} 要是正整数(现在是 '${pages}')`);
57
+ return EXIT.USAGE;
58
+ }
59
+ if (!String(groupIds).trim()) {
60
+ ctx.note(`未配置 ${groupVar}(collectors/local.env),不采集`);
61
+ return EXIT.NOT_CONFIGURED;
62
+ }
63
+ if (!needTool(ctx, 'yzj-cli')) return EXIT.MISSING_DEP;
64
+ const limit = env.YZJ_MESSAGE_LIMIT === undefined ? 20 : env.YZJ_MESSAGE_LIMIT;
65
+ const interval = Number(env.YZJ_CALL_INTERVAL === undefined ? 2 : env.YZJ_CALL_INTERVAL);
66
+ const sinceTs = digits(`${since} 00:00:00`);
67
+ let rc = EXIT.OK;
68
+ fs.mkdirSync(out, { recursive: true });
69
+ const whoami = run('yzj-cli', ['whoami'], { env });
70
+ if (whoami.code !== 0) {
71
+ ctx.note(`whoami 失败(未登录?试试 yzj-cli auth login): ${whoami.stderr.slice(0, 300)}`);
72
+ return EXIT.FAILED;
73
+ }
74
+ fs.writeFileSync(path.join(out, 'whoami.json'), whoami.stdout);
75
+
76
+ let lastWait = interval;
77
+ let first = true;
78
+ for (const gid of String(groupIds).split('|').map((s) => s.trim()).filter(Boolean)) {
79
+ const target = path.join(out, `messages-${gid}.json`);
80
+ // 同一天重复同步只留最新一份:先删掉上一次的,下面任何一步失败都不留下旧文件
81
+ fs.rmSync(target, { force: true });
82
+ const all = [];
83
+ const seen = new Set();
84
+ let page = 1;
85
+ let oldest = '';
86
+ let anchor = '';
87
+ let complete = false;
88
+ let failed = false;
89
+ while (true) {
90
+ // 每次调用之间留出间隔;失败后多等一会儿再试下一个
91
+ if (!first) await sleep(Math.max(0, lastWait) * 1000);
92
+ first = false;
93
+ const args = ['im', 'message', 'list', '--group-id', gid];
94
+ if (page === 1) args.push('--type', 'newest', '--limit', String(limit));
95
+ else args.push('--msg-id', anchor, '--type', 'old', '--limit', String(limit));
96
+ const r = run('yzj-cli', args, { env });
97
+ const messages = pageOf(r);
98
+ if (!messages) {
99
+ ctx.note(`会话 ${gid} 拉取失败: ${(r.stderr || r.stdout).slice(0, 300)}`);
100
+ lastWait = 5;
101
+ rc = EXIT.FAILED;
102
+ failed = true;
103
+ break;
104
+ }
105
+ // 这一页里有没有之前没见过的消息。一条都没有说明已经翻到这个会话的开头(接口改了、把锚点也算进来时也是这样)
106
+ const fresh = messages.filter((m) => m && m.msgId && !seen.has(m.msgId)).length;
107
+ for (const m of messages) {
108
+ if (!m || !m.msgId || seen.has(m.msgId)) continue;
109
+ seen.add(m.msgId);
110
+ all.push(m);
111
+ }
112
+ if (fresh === 0) {
113
+ complete = true;
114
+ break;
115
+ }
116
+ const oldestMsg = [...messages].sort(byTime)[0];
117
+ oldest = String(oldestMsg.sendTime);
118
+ anchor = String(oldestMsg.msgId);
119
+ // 只比到秒:时间带不带毫秒都能和起始日对齐。已经翻过起始日 0 点就停;时间字段读不出来时不下结论,接着翻
120
+ const oldestTs = digits(oldest);
121
+ if (/^\d{14}$/.test(oldestTs) && Number(oldestTs) < Number(sinceTs)) complete = true;
122
+ if (complete) break;
123
+ if (page >= Number(pages)) break;
124
+ page += 1;
125
+ }
126
+ if (failed) continue;
127
+ if (Number(pages) > 1 && !complete) {
128
+ ctx.note(`会话 ${gid} 翻了 ${page} 页只翻到 ${oldest},没覆盖到 ${since} 00:00;把 ${pagesVar} 调大再同步`);
129
+ rc = EXIT.FAILED;
130
+ continue;
131
+ }
132
+ all.sort(byTime);
133
+ const coverage = { from: all.length ? all[0].sendTime : null, to: all.length ? all[all.length - 1].sendTime : null };
134
+ fs.writeFileSync(target, `${JSON.stringify({ success: true, data: { groupId: gid, coverage, list: all } }, null, 2)}\n`);
135
+ lastWait = interval;
136
+ ctx.note(`会话 ${gid} 已拉取 ${all.length} 条(${page} 页),覆盖 ${coverage.from ?? '无'} 至 ${coverage.to ?? '无'}`);
137
+ }
138
+ return rc;
139
+ }
140
+
141
+ module.exports = { collect };
142
+
143
+ if (require.main === module) {
144
+ collect(process.argv.slice(2)).then(
145
+ (code) => process.exit(code),
146
+ (error) => {
147
+ process.stderr.write(`im-yzj: ${error && error.stack ? error.stack : String(error)}\n`);
148
+ process.exit(error && error.name === 'UsageError' ? EXIT.USAGE : EXIT.FAILED);
149
+ },
150
+ );
151
+ }
@@ -0,0 +1,88 @@
1
+ #!/usr/bin/env node
2
+ // 采集 Linky 上分配给我的未完成工作项:供 AI 提炼「工作项」事件,也给每日计划挑最该推进的那几条
3
+ // 用法: node collectors/linky-issues.js <输出目录> [起始日期 YYYY-MM-DD,只用于统计,默认今天]
4
+ // 输出: <输出目录>/issues.tsv —— 类型、编号、状态、状态分类、优先级、最近更新、模块、标题,按最近更新倒序
5
+ // 前提: linky 已登录(linky login)。要导出的类型可以在 collectors/local.env 里用 LINKY_TYPES 改,多个用 | 分隔
6
+ // 说明: 已经完成的(状态分类为 done)不导出,它们留在 Linky 里就够了。
7
+ // 导出不完整(complete=false)按失败处理:不完整的清单不能当作「我手上有多少事」。
8
+ 'use strict';
9
+ const fs = require('node:fs');
10
+ const path = require('node:path');
11
+ const { EXIT, run, tail } = require('../scripts/lib/run');
12
+ const { context, needTool, tempDir, readJson, writeTsv, tsv } = require('../scripts/lib/collector');
13
+
14
+ async function collect(argv) {
15
+ const ctx = context(argv, 'linky-issues', 'linky-issues.js <输出目录> [起始日期]');
16
+ const { out, since, env } = ctx;
17
+ const types = (env.LINKY_TYPES || 'bug|user_story|requirement|task').split('|').map((s) => s.trim()).filter(Boolean).join(',');
18
+ if (!needTool(ctx, 'linky')) return EXIT.MISSING_DEP;
19
+ // 原始导出先落到临时目录:工作目录里只留那张表,导出用完即删
20
+ const work = tempDir('linky-issues-');
21
+ try {
22
+ const r = run('linky', ['issue', 'export', '--type', types, '--all-visible', '--include-personal', '--filter', 'assignee_id:current_user', '--out-dir', path.join(work, 'export'), '--omit-rich-text'], { env });
23
+ // linky 的退出码:3 结果不完整,4 需要登录,5 无权限或工作区不可见。都算远端失败,原因分开说
24
+ if (r.code === 3) {
25
+ ctx.note('导出不完整(complete=false),这份清单不能当作我手上有多少事;稍后重试');
26
+ return EXIT.FAILED;
27
+ }
28
+ if (r.code === 4) {
29
+ ctx.note('linky 未登录,先运行 linky login');
30
+ return EXIT.FAILED;
31
+ }
32
+ if (r.code !== 0) {
33
+ ctx.note(`导出失败(退出码 ${r.code};5 表示无权限或工作区不可见): ${tail(r.stderr, 300)}`);
34
+ return EXIT.FAILED;
35
+ }
36
+ fs.writeFileSync(path.join(work, 'summary.json'), r.stdout);
37
+ const metaFile = fs.existsSync(path.join(work, 'export', 'meta.json')) ? path.join(work, 'export', 'meta.json') : path.join(work, 'summary.json');
38
+ const complete = (readJson(metaFile) || {}).complete;
39
+ if (complete !== true) {
40
+ ctx.note(`导出不完整(complete=${complete === undefined ? '未知' : complete}),这份清单不能当作我手上的全部工作项;稍后重试`);
41
+ return EXIT.FAILED;
42
+ }
43
+ const exportDir = path.join(work, 'export');
44
+ const rows = [];
45
+ for (const name of fs.readdirSync(exportDir).filter((n) => n.endsWith('.jsonl')).sort()) {
46
+ for (const line of fs.readFileSync(path.join(exportDir, name), 'utf8').split('\n')) {
47
+ if (!line.trim()) continue;
48
+ let item;
49
+ try {
50
+ item = JSON.parse(line);
51
+ } catch {
52
+ continue;
53
+ }
54
+ if (String((item.status && item.status.category) || '').toLowerCase() === 'done') continue;
55
+ rows.push([
56
+ item.type || '',
57
+ item.code || '',
58
+ (item.status && item.status.name) || '',
59
+ (item.status && item.status.category) || '',
60
+ (item.labels && item.labels.gf_priority) || '',
61
+ item.updated_at || '',
62
+ String((item.labels && item.labels.tf_module) || '').replace(/\s*[((][A-Za-z0-9-]+[))]\s*$/, ''),
63
+ String(item.title || '').replace(/[\t\n\r]/g, ' '),
64
+ ].map(tsv));
65
+ }
66
+ }
67
+ rows.sort((a, b) => (a[5] < b[5] ? 1 : a[5] > b[5] ? -1 : 0)); // 按最近更新倒序
68
+ fs.mkdirSync(out, { recursive: true });
69
+ writeTsv(path.join(out, 'issues.tsv'), ['type', 'code', 'status', 'category', 'priority', 'updated', 'module', 'title'], rows);
70
+ const touched = rows.filter((row) => row[5] >= since).length;
71
+ ctx.note(`未完成工作项 ${rows.length} 条,其中 ${since} 之后更新过 ${touched} 条`);
72
+ return EXIT.OK;
73
+ } finally {
74
+ fs.rmSync(work, { recursive: true, force: true });
75
+ }
76
+ }
77
+
78
+ module.exports = { collect };
79
+
80
+ if (require.main === module) {
81
+ collect(process.argv.slice(2)).then(
82
+ (code) => process.exit(code),
83
+ (error) => {
84
+ process.stderr.write(`linky-issues: ${error && error.stack ? error.stack : String(error)}\n`);
85
+ process.exit(error && error.name === 'UsageError' ? EXIT.USAGE : EXIT.FAILED);
86
+ },
87
+ );
88
+ }