work-rhythm 0.2.13 → 0.2.15

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "work-rhythm",
3
- "version": "0.2.13",
3
+ "version": "0.2.15",
4
4
  "description": "个人工作目录:记录每天的工作事件、按订阅源采集数据、做计划和复盘;带本地服务(定时采集、定时整理、经消息渠道推送、本机网页)",
5
5
  "license": "UNLICENSED",
6
6
  "type": "commonjs",
package/scripts/cli.js CHANGED
@@ -26,6 +26,7 @@ const COMMANDS = {
26
26
  rhythm: 'rhythm start|stop|status|due|run|serve|render|doctor|install|uninstall 本地服务:定时采集、定时整理、推送、网页、监控中心',
27
27
  trigger: 'trigger list|show|fire 触发:看路由和执行者处理过的事,手动塞一条进去(rhythm.router 开着时)',
28
28
  ask: 'ask - | --json … | list | show 问我一句话:问题以 JSON 丢出来,今日页「待你定」成一张卡;我答了之后回到路由',
29
+ workspace: 'workspace list | scan | add | remove 管理路由可用的工作区(代码库/工程目录)',
29
30
  agent: 'agent [bind [router|worker] [名字]|test|doctor] 路由、执行者、值守用哪个 agent:检测本机的、绑定、试一句',
30
31
  workdir: 'workdir [register|find|config|blank] 工作目录在哪:找、登记、扫描本机;不带子命令是找',
31
32
  init: 'init <目录> 新建一个工作目录(空白模板、登记)',
@@ -0,0 +1,72 @@
1
+ // 工作区(ws)管理命令:work-rhythm workspace list | scan | add <id> <路径> [--note …] [--agent …] | remove <id>
2
+ 'use strict';
3
+ const { EXIT, UsageError } = require('../lib/run');
4
+ const { settings } = require('../lib/config');
5
+ const ws = require('../lib/workspace');
6
+
7
+ const USAGE = `work-rhythm workspace <子命令> —— 管理路由可用的工作区(代码库/工程目录)
8
+
9
+ 用法:
10
+ work-rhythm workspace list [--json]
11
+ 列出已登记的工作区(00-config/workspaces.json)
12
+ work-rhythm workspace scan [--json]
13
+ 扫描本机候选工作区(GIT_ACTIVITY_WORKSPACES 与 ~/workspace 下的 git 仓库,按最近活跃排序)
14
+ work-rhythm workspace add <id> <路径> [--note <说明>] [--agent <agent>]
15
+ 登记或更新一个工作区
16
+ work-rhythm workspace remove <id>
17
+ 移除一个已登记的工作区
18
+
19
+ 退出码: 0 完成;2 用法不对;3 找不到工作目录。`;
20
+
21
+ module.exports = {
22
+ usage: USAGE,
23
+ async run(args, ctx) {
24
+ const { root, stdout, env } = ctx;
25
+ const [sub, ...rest] = args;
26
+ const json = rest.includes('--json');
27
+ const clean = rest.filter((x) => x !== '--json');
28
+ if (sub === 'list') {
29
+ const list = ws.loadRegistered(root);
30
+ if (json) {
31
+ stdout.write(`${JSON.stringify(list, null, 2)}\n`);
32
+ return EXIT.OK;
33
+ }
34
+ stdout.write('id\tpath\tagent\tnote\n');
35
+ for (const w of list) stdout.write(`${w.id}\t${w.path}\t${w.agent}\t${w.note}\n`);
36
+ return EXIT.OK;
37
+ }
38
+ if (sub === 'scan') {
39
+ const { registered, scanned } = ws.discoverWorkspaces(root, settings(root, env));
40
+ if (json) {
41
+ stdout.write(`${JSON.stringify({ registered, scanned }, null, 2)}\n`);
42
+ return EXIT.OK;
43
+ }
44
+ stdout.write('status\tid\tpath\tnote\n');
45
+ for (const w of registered) stdout.write(`已登记\t${w.id}\t${w.path}\t${w.note}\n`);
46
+ for (const w of scanned) stdout.write(`候选\t${w.id}\t${w.path}\t${w.note}\n`);
47
+ return EXIT.OK;
48
+ }
49
+ if (sub === 'add') {
50
+ const [id, dir, ...flags] = clean;
51
+ if (!id || !dir) throw new UsageError(USAGE);
52
+ let note = '';
53
+ let agent = '';
54
+ for (let i = 0; i < flags.length; i += 1) {
55
+ if (flags[i] === '--note' && flags[i + 1] !== undefined) { note = flags[++i]; }
56
+ else if (flags[i] === '--agent' && flags[i + 1] !== undefined) { agent = flags[++i]; }
57
+ else throw new UsageError(USAGE);
58
+ }
59
+ const item = ws.addWorkspace(root, { id, dir, note, agent });
60
+ stdout.write(`已登记工作区 ${item.id} → ${item.path}${item.note ? `(${item.note})` : ''}\n`);
61
+ return EXIT.OK;
62
+ }
63
+ if (sub === 'remove') {
64
+ const [id] = clean;
65
+ if (!id) throw new UsageError(USAGE);
66
+ const ok = ws.removeWorkspace(root, id);
67
+ stdout.write(ok ? `已移除工作区 ${id}\n` : `没有登记过工作区 ${id}\n`);
68
+ return EXIT.OK;
69
+ }
70
+ throw new UsageError(USAGE);
71
+ },
72
+ };
@@ -15,10 +15,11 @@ const { createRouter } = require('./router');
15
15
  const { createPool, runWorker } = require('./worker');
16
16
  const { parseEvents } = require('../cmd/events');
17
17
  const asks = require('./asks');
18
+ const ws = require('./workspace');
18
19
 
19
20
  const ACK_TEXT = '收到,正在处理,稍等。'; // 和值守(bot.js)那句一样
20
21
  // 上一句还没答完又来一句(插话):先回这句,告诉他会和上一句一起考虑
21
- const ACK_MORE_TEXT = '收到,上一句还在答,这句会和它一起考虑。';
22
+ const ACK_MORE_TEXT = '收到,正在处理,稍等。';
22
23
  const TRIGGER_KEEP_DAYS = 2;
23
24
  const OPEN_MAX = 10;
24
25
  const OPEN_MS = 24 * 3600 * 1000;
@@ -213,6 +214,47 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
213
214
  let busy = false;
214
215
  let closing = false; // 服务在停:不再交给路由
215
216
  let pumpScheduled = false; // 这个 tick 里已经排了一轮
217
+ let msgBuf = null;
218
+ let msgTimer = null;
219
+ const activeProgress = new Map(); // id → { t, started, count }
220
+ let progressTimer = null;
221
+ function stopProgressTimer() {
222
+ if (progressTimer) { clearInterval(progressTimer); progressTimer = null; }
223
+ }
224
+ function ensureProgressTimer() {
225
+ if (progressTimer || !cfg.progress || cfg.progress <= 0) return;
226
+ const stepMs = Math.max(200, cfg.progress * 1000);
227
+ progressTimer = setInterval(() => {
228
+ if (closing || !activeProgress.size) { stopProgressTimer(); return; }
229
+ const now = Date.now();
230
+ const due = [];
231
+ for (const item of activeProgress.values()) {
232
+ if (item.count >= cfg.progressMax) continue;
233
+ if (now - item.started < stepMs * 0.8) continue;
234
+ due.push(item);
235
+ }
236
+ if (!due.length) return;
237
+ for (const item of due) item.count += 1;
238
+ if (due.length === 1) {
239
+ const { t, started } = due[0];
240
+ send(t, `还在做(已经 ${humanDuration((now - started) / 1000)} · 工作区 ${t.ws || '工作目录'}):${t.title || t.id}。做完汇报。`, { mark: false });
241
+ } else {
242
+ const lines = ['手头有 ' + due.length + ' 件事还在做(做完汇报):'];
243
+ due.forEach(({ t, started }, i) => {
244
+ lines.push(`${i + 1}. [工作区 ${t.ws || '工作目录'}] ${t.title || t.id}(已 ${humanDuration((now - started) / 1000)})`);
245
+ });
246
+ send(null, lines.join('\n'), { mark: false });
247
+ }
248
+ }, stepMs);
249
+ if (progressTimer.unref) progressTimer.unref();
250
+ }
251
+ function flushMessages() {
252
+ if (msgTimer) { clearTimeout(msgTimer); msgTimer = null; }
253
+ if (!msgBuf) return null;
254
+ const b = msgBuf;
255
+ msgBuf = null;
256
+ return enqueue('message', { key: b.keys[0], text: b.texts.join('\n'), mode: cfg.botMode });
257
+ }
216
258
  let sink = null;
217
259
  const pool = createPool({ limit: cfg.workers });
218
260
  const router = cfg.router ? createRouter({ root, env, role: routerSpec, timeoutS: cfg.routerTimeout, preamble: cfg.botPreamble || '', log }) : null;
@@ -242,7 +284,7 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
242
284
  function openItems() {
243
285
  const now = Date.now();
244
286
  const act = [...pool.running().map((e) => e.id), ...pool.queued()];
245
- const row = (x) => ({ id: x.id, status: STATUS_CN[x.worker.status] || '在跑', at: x.at, title: x.title || '' });
287
+ const row = (x) => ({ id: x.id, status: STATUS_CN[x.worker.status] || '在跑', at: x.at, title: x.title || '', ws: x.ws || '' });
246
288
  const done = Object.values(triggers()).filter((x) => x.worker && ['ok', 'failed', 'stopped'].includes(x.worker.status) && now - stampMs(x.worker.endedAt || x.at) < OPEN_MS).sort((a, b) => b.at.localeCompare(a.at));
247
289
  return [...act.map((id) => triggers()[id]).filter(Boolean).map(row), ...done.map(row)].slice(0, OPEN_MAX);
248
290
  }
@@ -351,8 +393,9 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
351
393
  }
352
394
 
353
395
  // 排一个执行者。after 给了就等那件事做完再起(续做一件还在跑的事)
354
- function launch(t, { mode, timeoutS, resume = '', after = '' }) {
355
- t.worker = { status: 'queued', mode, timeoutS, agent: workerSpec.agent, model: workerSpec.model, effort: workerSpec.effort, sessionId: resume || '' };
396
+ function launch(t, { mode, timeoutS, resume = '', after = '', cwd = '', agentOverride = '' }) {
397
+ const spec = agentOverride ? { ...workerSpec, agent: agentOverride } : workerSpec;
398
+ t.worker = { status: 'queued', mode, timeoutS, agent: spec.agent, model: spec.model, effort: spec.effort, sessionId: resume || '', ws: t.ws || '' };
356
399
  save();
357
400
  const start = () => {
358
401
  // 续做排在后面起:起的时候再读原来那件的会话 id(它可能到做完才有)
@@ -362,16 +405,16 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
362
405
  t.worker.status = 'running';
363
406
  t.worker.startedAt = fmtStamp();
364
407
  save();
365
- // 我这边直接派出去的(消息、手动)跑得久就先说一声;定时任务的汇报本来就会来,不额外打扰
366
- const started = Date.now();
367
- const pings = t.kind === 'schedule' || t.quiet ? { stop() {} } : progressPings({
368
- firstS: cfg.progress, everyS: cfg.progress * 2, max: cfg.progressMax,
369
- say: () => send(t, `还在做(已经 ${humanDuration((Date.now() - started) / 1000)}):${t.title || t.id}。做完汇报。`, { mark: false }),
370
- });
408
+ // 我这边直接派出去的(消息、手动)跑得久就统一汇总说一声;定时任务的汇报本来就会来,不额外打扰
409
+ const trackProgress = t.kind !== 'schedule' && !t.quiet && cfg.progress > 0;
410
+ if (trackProgress) {
411
+ activeProgress.set(t.id, { t, started: Date.now(), count: 0 });
412
+ ensureProgressTimer();
413
+ }
371
414
  let r;
372
415
  try {
373
416
  r = await runWorker({
374
- root, env, log, id: t.id, mode, timeoutS, idleS: cfg.workerIdle, spec: workerSpec, resume: sid, extraEnv: { WRJ_TRIGGER: t.id, WRJ_ROLE: 'worker' },
417
+ root, cwd: cwd || root, env, log, id: t.id, mode, timeoutS, idleS: cfg.workerIdle, spec, resume: sid, extraEnv: { WRJ_TRIGGER: t.id, WRJ_ROLE: 'worker' },
375
418
  onSession: (sid) => {
376
419
  if (t.worker.sessionId !== sid) {
377
420
  t.worker.sessionId = sid;
@@ -381,7 +424,10 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
381
424
  onKill: (fn) => ctrl.setKill(fn),
382
425
  });
383
426
  } finally {
384
- pings.stop();
427
+ if (trackProgress) {
428
+ activeProgress.delete(t.id);
429
+ if (!activeProgress.size) stopProgressTimer();
430
+ }
385
431
  }
386
432
  return finishWorker(t, r);
387
433
  }, { kind: t.kind, task: t.task || '' });
@@ -401,9 +447,14 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
401
447
  }
402
448
 
403
449
  // 交给执行者:写任务书、起运行。路由没给任务书的(或者退路),拿原话或指令文件当任务书
404
- function dispatch(t, c, handoffBody, byRouter = false) {
450
+ function dispatch(t, c, handoffBody, byRouter = false, wsId = '') {
405
451
  let body = s(handoffBody);
406
452
  const { mode, timeoutS } = terms(t, { byRouter });
453
+ const resolvedWs = wsId ? ws.discoverWorkspaces(root, env).resolve(wsId) : null;
454
+ if (resolvedWs) {
455
+ t.ws = resolvedWs.id;
456
+ t.wsPath = resolvedWs.path;
457
+ }
407
458
  if (t.kind === 'schedule') body = `${s(c.taskBody)}${body ? `\n\n## 路由的补充\n\n${body}` : ''}\n\n${NOTE_BY_SERVICE}`;
408
459
  else if (t.kind === 'events') body = `${focusBody({ ...c, root })}${body ? `\n## 路由的补充\n\n${body}` : ''}\n\n${NOTE_BY_SERVICE}`;
409
460
  else if (t.kind === 'answer') body = `${answerBody(c)}${body ? `\n## 路由的补充\n\n${body}` : ''}\n\n${NOTE_BY_SERVICE}`;
@@ -415,7 +466,7 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
415
466
  // 消息一来先回一句「收到」,路由慢的话我不用干等
416
467
  if (t.kind === 'message' && cfg.ack && !t.acked) send(null, ACK_TEXT, { mark: false });
417
468
  // 派出去就接着派下一条,不等它做完(汇报会自己排回来)
418
- launch(t, { mode, timeoutS });
469
+ launch(t, { mode, timeoutS, cwd: t.wsPath || root, agentOverride: resolvedWs && resolvedWs.agent ? resolvedWs.agent : '' });
419
470
  return undefined;
420
471
  }
421
472
 
@@ -432,9 +483,10 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
432
483
  const timeoutS = (target.worker && target.worker.timeoutS) || cfg.taskTimeout;
433
484
  t.title = `${target.title || targetId}(续)`;
434
485
  t.of = targetId;
486
+ if (target.ws) { t.ws = target.ws; t.wsPath = target.wsPath || ''; }
435
487
  handoff.writeTask(root, { ...t, text: c.text }, body, { mode, timeoutS, continueOf: targetId });
436
488
  save();
437
- launch(t, { mode, timeoutS, resume: (target.worker && target.worker.sessionId) || '', after: isActive(targetId) ? targetId : '' });
489
+ launch(t, { mode, timeoutS, resume: (target.worker && target.worker.sessionId) || '', after: isActive(targetId) ? targetId : '', cwd: t.wsPath || root });
438
490
  return undefined;
439
491
  }
440
492
 
@@ -450,12 +502,13 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
450
502
  const resume = target.worker.sessionId || '';
451
503
  t.title = `${target.title || targetId}(插话)`;
452
504
  t.of = targetId;
505
+ if (target.ws) { t.ws = target.ws; t.wsPath = target.wsPath || ''; }
453
506
  target.suppressReport = true;
454
507
  pool.stop(targetId, '用户插话,改了要求');
455
508
  handoff.writeTask(root, { ...t, text: c.text }, body, { mode, timeoutS, continueOf: targetId });
456
509
  save();
457
510
  log('插话', `${t.id} 停掉 ${targetId} 带着新要求重跑`);
458
- launch(t, { mode, timeoutS, resume });
511
+ launch(t, { mode, timeoutS, resume, cwd: t.wsPath || root });
459
512
  return undefined;
460
513
  }
461
514
 
@@ -493,7 +546,7 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
493
546
 
494
547
  async function act(t, c, d) {
495
548
  t.decision = d.action;
496
- if (d.action === 'dispatch') return dispatch(t, c, d.handoff, true);
549
+ if (d.action === 'dispatch') return dispatch(t, c, d.handoff, true, d.ws || '');
497
550
  if (d.action === 'continue') return continueWith(t, c, d.target);
498
551
  if (d.action === 'interrupt') return interruptWith(t, c, d.target);
499
552
  if (d.action === 'stop') return stopTask(t, d.target);
@@ -529,7 +582,7 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
529
582
  let result = null;
530
583
  if (router) {
531
584
  const batch = ids.map((id) => triggers()[id]).filter(Boolean);
532
- result = await router.decide(batch.map(view), openItems());
585
+ result = await router.decide(batch.map(view), openItems(), ws.discoverWorkspaces(root, env));
533
586
  state.data.rounds = [...(state.data.rounds || []), { at: fmtStamp(), uid: uid(), ok: result.ok, n: batch.length, seconds: (router.last() || {}).seconds || 0 }];
534
587
  log(result.ok ? '路由出决定' : '路由没出决定', `${batch.length} 条${result.ok ? '' : `:${result.failed}`}`);
535
588
  }
@@ -615,6 +668,10 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
615
668
  // 服务要停了:在跑的执行者是子进程,得收掉(最多等 3 秒)。之后不再交给路由
616
669
  async function shutdown() {
617
670
  closing = true;
671
+ if (msgTimer) { clearTimeout(msgTimer); msgTimer = null; }
672
+ msgBuf = null;
673
+ activeProgress.clear();
674
+ stopProgressTimer();
618
675
  for (const id of pool.queued()) pool.stop(id, '服务停止时中断');
619
676
  for (const e of pool.running()) pool.stop(e.id, '服务停止时中断');
620
677
  const pending = [...dones.values()];
@@ -671,7 +728,20 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
671
728
 
672
729
  return {
673
730
  enqueue,
674
- message: (m) => enqueue('message', { key: `msg-${m.msgId}`, text: s(m.content), mode: cfg.botMode }),
731
+ message: (m) => {
732
+ const key = `msg-${m.msgId}`;
733
+ const text = s(m.content);
734
+ const debounceS = Number(cfg.messageDebounce) || 0;
735
+ if (!debounceS || !router) return enqueue('message', { key, text, mode: cfg.botMode });
736
+ if (Object.values(triggers()).some((x) => x.key === key) || (msgBuf && msgBuf.keys.includes(key))) return null;
737
+ if (!msgBuf) msgBuf = { keys: [key], texts: [text], firstAt: Date.now() };
738
+ else { msgBuf.keys.push(key); msgBuf.texts.push(text); }
739
+ if (msgTimer) clearTimeout(msgTimer);
740
+ const waitMs = Math.min(debounceS * 1000, Math.max(0, 20000 - (Date.now() - msgBuf.firstAt)));
741
+ msgTimer = setTimeout(flushMessages, waitMs);
742
+ return null;
743
+ },
744
+ flushMessages,
675
745
  schedule: (job, taskBody, taskTitle) => enqueue('schedule', { key: job.key, task: job.id, taskFile: `tasks/${job.id}.md`, taskBody, taskTitle, quiet: cfg.quiet.includes(job.id) }),
676
746
  recover,
677
747
  shutdown,
@@ -10,7 +10,7 @@ const DIR = '.agents/handoff';
10
10
  const NAME_RE = /^(t-\d+)(\.result)?\.md$/;
11
11
  const ACTIONS = ['dispatch', 'continue', 'stop', 'interrupt', 'reply', 'ignore', 'notify'];
12
12
  const SECTION_RE = /^##[ \t]+(reply|ignore|handoff|notify)[ \t]+(t-\d+)[ \t]*.*$/;
13
- const DECISION_RE = /^[ \t]*-?[ \t]*(t-\d+)[ \t]+(dispatch|continue|stop|interrupt|reply|ignore|notify)(?:[ \t]+(t-\d+))?[ \t]*$/;
13
+ const DECISION_RE = /^[ \t]*-?[ \t]*(t-\d+)[ \t]+(dispatch|continue|stop|interrupt|reply|ignore|notify)(?:[ \t]+(t-\d+))?(?:[ \t]+ws=([A-Za-z0-9._-]+))?[ \t]*$/;
14
14
  const MARKER = '【work-rhythm 路由】';
15
15
  const DAY_MS = 24 * 3600 * 1000;
16
16
 
@@ -148,6 +148,7 @@ function parseRouterReply(text) {
148
148
  const it = pick(d[1]);
149
149
  it.action = d[2];
150
150
  if (d[3]) it.target = d[3];
151
+ if (d[4]) it.ws = d[4];
151
152
  }
152
153
  }
153
154
  for (const s of sections) {
@@ -159,6 +160,7 @@ function parseRouterReply(text) {
159
160
  id: it.id,
160
161
  action: ACTIONS.includes(it.action) ? it.action : '',
161
162
  target: it.target || '',
163
+ ws: it.ws || '',
162
164
  handoff: it.handoff || '',
163
165
  text: it.reply || it.notify || it.ignore || '',
164
166
  }));
@@ -146,6 +146,7 @@ function createRhythm({ root, env, packageRoot }) {
146
146
  workerIdle: idle === 0 ? 0 : Math.max(600, idle),
147
147
  progress: seconds(env.YZJ_BOT_PROGRESS, 90),
148
148
  progressMax: positiveInt(env.YZJ_BOT_PROGRESS_MAX, 3),
149
+ messageDebounce: seconds(env.YZJ_BOT_DEBOUNCE, 8),
149
150
  replyMax: positiveInt(env.YZJ_BOT_REPLY_MAX, 2000),
150
151
  botPreamble: (env.YZJ_BOT_PREAMBLE || '').trim(),
151
152
  links: LINKS,
@@ -23,12 +23,12 @@ const PROMPT = `${handoff.MARKER}下面是到达的触发,前面是「手头
23
23
  - message 里是在回答某张待办卡片(「1 选 2」这种):dispatch,task 写清是哪一条事项、选了第几个选项;执行者会 work-rhythm decisions answer 并照选项做。
24
24
 
25
25
  二、七种决定(每条触发只能选一种)
26
- - dispatch:派人做。要写一个「## handoff <短号>」小节当任务书。
26
+ - dispatch:派人做。要写一个「## handoff <短号>」小节当任务书。日常事默认在工作目录跑;如果明确要在某个代码库/工程里干活且能从「可用工作区」里挑出,写成「- <短号> dispatch ws=<id>」。如果必须确定工作区但拿不准,不写 ws=,在任务书里让执行者用 work-rhythm ask 问用户(选项带上候选工作区和工作目录),确认后记进 work-rhythm workspace add 和今日事件流。
27
27
  - reply:不用动手、一句话直接答。写「## reply <短号>」。只用于 message / manual。
28
28
  - ignore:不用处理。写「## ignore <短号>」和一句原因。
29
29
  - notify:给用户的话。写「## notify <短号>」。只用于 report。
30
- - continue <短号>:这句话是接着「手头的事」里某一件说的(追问、补充,不改它在做的)。不用写任务书,CLI 会把原话交给原来那个执行者;那件还在跑就排在它后面。
31
- - interrupt <短号>:这句话改了某件正在跑的事的要求(改主意、纠正),等它做完就来不及。CLI 会停掉它、带着新要求重跑。不用写任务书。
30
+ - continue <短号>:这句话是接着「手头的事」里某一件做完的事继续追问,或者顺便再做一件相关事(不打断正在跑的,排在它后面单独回一次)。不用写任务书,CLI 会把原话交给原来那个执行者。
31
+ - interrupt <短号>:某件事还在跑,用户又补充了条件、想法或改了要求,希望合在一起只回一次。CLI 会停掉它、带着新话重跑并压掉上一轮汇报。正在跑的事收到补充时优先选 interrupt,不要选 continue。
32
32
  - stop <短号>:用户不要某件正在跑的事了。
33
33
 
34
34
  三、任务书怎么写(dispatch 的时候)
@@ -86,13 +86,20 @@ function triggerLine(t) {
86
86
  return t.ok ? `${head}\n 开头:${t.opening}` : head;
87
87
  }
88
88
 
89
- // 一轮的提示词:固定的说明 + 手头的事 + 这一批触发。extra 是重试时的一句提醒
90
- function turnPrompt(triggers, open, extra = '') {
89
+ // 一轮的提示词:固定的说明 + 可用工作区(有的话)+ 手头的事 + 这一批触发。extra 是重试时的一句提醒
90
+ function turnPrompt(triggers, open, extra = '', workspaces = null) {
91
91
  const lines = [PROMPT];
92
92
  if (extra) lines.push('', extra);
93
+ const reg = (workspaces && workspaces.registered) || [];
94
+ const scan = (workspaces && workspaces.scanned) || [];
95
+ if (reg.length || scan.length) {
96
+ lines.push('', '可用工作区(日常事默认在工作目录跑,不写 ws=;明确要进代码库/工程时在 dispatch 行加 ws=<id>;不确定选哪个时在任务书里让执行者用 work-rhythm ask 问用户并记录到工作目录):');
97
+ for (const w of reg) lines.push(`- ${w.id}(已登记,${w.path})${w.note ? `:${w.note}` : ''}`);
98
+ for (const w of scan) lines.push(`- ${w.id}(候选,${w.path})`);
99
+ }
93
100
  lines.push('', '手头的事(在跑的和今天做完的):');
94
101
  if (!open.length) lines.push('- (没有)');
95
- for (const o of open) lines.push(`- ${o.id} ${o.status},${short(o.at)}:${o.title || '(没写标题)'}`);
102
+ for (const o of open) lines.push(`- ${o.id} ${o.status},${short(o.at)}:${o.title || '(没写标题)'}${o.ws ? ` [ws=${o.ws}]` : ''}`);
96
103
  lines.push('', '触发:');
97
104
  for (const t of triggers) lines.push(triggerLine(t));
98
105
  return lines.join('\n');
@@ -161,13 +168,13 @@ function createRouter({ root, env, role, timeoutS = 120, preamble = '', log = ()
161
168
  }
162
169
 
163
170
  // 对一批触发出决定。解析不出来、或者漏了触发,带着一句提醒再来一轮;再不行返回 ok 为 false(missing 是漏掉的短号)
164
- async function decide(triggers, open) {
171
+ async function decide(triggers, open, workspaces = null) {
165
172
  const started = Date.now();
166
173
  const ids = triggers.map((t) => t.id);
167
174
  let extra = '';
168
175
  let lastReply = '';
169
176
  for (let attempt = 0; attempt < 2; attempt += 1) {
170
- const r = await turn(turnPrompt(triggers, open, extra));
177
+ const r = await turn(turnPrompt(triggers, open, extra, workspaces));
171
178
  if (r.failed) {
172
179
  last = { at: fmtStamp(), seconds: Math.round((Date.now() - started) / 1000), ok: false };
173
180
  return { ok: false, failed: r.failed, config: r.config, decisions: {}, missing: ids };
@@ -58,6 +58,8 @@ function resolveRoot({ cwd = process.cwd(), option = '', env = process.env, pack
58
58
  if (option) return { root: path.resolve(option), source: 'option', problem: '' };
59
59
  const up = findUp(cwd);
60
60
  if (up) return { root: up, source: 'cwd', problem: '' };
61
+ const fromEnv = env && env.WRJ_WORKDIR ? path.resolve(String(env.WRJ_WORKDIR).trim()) : '';
62
+ if (fromEnv && isWorkdir(fromEnv)) return { root: fromEnv, source: 'env', problem: '' };
61
63
  if (insidePackage(cwd, packageRoot)) return { root: path.resolve(packageRoot), source: 'package', problem: '' };
62
64
  const reg = registered(env);
63
65
  if (reg && isWorkdir(reg)) return { root: reg, source: 'pointer', problem: '' };
@@ -8,19 +8,25 @@ const handoff = require('./handoff');
8
8
 
9
9
  const WORKER_STATE_DIR = ['01-inbox', '_rhythm', 'workers'];
10
10
 
11
- // 给执行者的那一句
12
- function workerPrompt(id) {
13
- return `读 ${handoff.relTask(id)}(任务书),照它做完,把回执写到 ${handoff.relResult(id)};没有写权限就把回执作为你最后一段话输出。不要向我提问,不要等待确认,不要自己发消息。`;
11
+ // 给执行者的那一句:在工作目录里跑用相对路径,跨工作区跑用绝对路径(交接文档仍在工作目录里)
12
+ function workerPrompt(id, { root = '', cwd = '' } = {}) {
13
+ const cross = root && cwd && path.resolve(cwd) !== path.resolve(root);
14
+ const task = cross ? handoff.taskPath(root, id) : handoff.relTask(id);
15
+ const result = cross ? handoff.resultPath(root, id) : handoff.relResult(id);
16
+ return `读 ${task}(任务书),照它做完,把回执写到 ${result};没有写权限就把回执作为你最后一段话输出。不要向我提问,不要等待确认,不要自己发消息。`;
14
17
  }
15
18
 
16
- // 跑一个执行者。spec 是 { agent, model, effort };resume 给了就接着那个会话跑(续做),接不上时自动改开新会话(上下文在任务书里)。
19
+ // 跑一个执行者。spec 是 { agent, model, effort };cwd 是运行目录(默认工作目录 root,指定工作区时切过去);
20
+ // resume 给了就接着那个会话跑(续做),接不上时自动改开新会话(上下文在任务书里)。
17
21
  // 返回 { ok, failed, stopped, reply, sessionId, seconds, config, partial };onSession 在拿到会话 id 时调(监控页上一开始就能看到),onKill 把停它的办法交出去。
18
22
  // idleS 是静默闸:执行者可能长时间不出声(跑构建、跑测试),给得比值守宽
19
- async function runWorker({ root, env, log = () => {}, id, mode, timeoutS, idleS = 0, spec, resume = '', onSession = () => {}, onKill = () => {}, extraEnv = {} }) {
20
- const agent = createAgent({ root, agent: spec.agent, mode, timeoutS, idleS, log, env, model: spec.model, effort: spec.effort });
23
+ async function runWorker({ root, cwd = '', env, log = () => {}, id, mode, timeoutS, idleS = 0, spec, resume = '', onSession = () => {}, onKill = () => {}, extraEnv = {} }) {
24
+ const runDir = cwd ? path.resolve(cwd) : root;
25
+ const agent = createAgent({ root: runDir, agent: spec.agent, mode, timeoutS, idleS, log, env, model: spec.model, effort: spec.effort });
21
26
  const started = Date.now();
22
- // extraEnv:执行者的环境里多带几样(WRJ_TRIGGER 是哪条触发的——它调 work-rhythm ask 时据此记「谁问的」)
23
- const handle = agent.start(workerPrompt(id), { session: resume, onSession, stateDir: path.join(root, ...WORKER_STATE_DIR), extraEnv });
27
+ // extraEnv:执行者的环境里多带几样(WRJ_TRIGGER 是哪条触发的;WRJ_WORKDIR 指向工作目录,跨 ws 时调 work-rhythm ask/decisions/workspace 找得到)
28
+ const mergedEnv = { WRJ_WORKDIR: root, ...extraEnv };
29
+ const handle = agent.start(workerPrompt(id, { root, cwd: runDir }), { session: resume, onSession, stateDir: path.join(root, ...WORKER_STATE_DIR), extraEnv: mergedEnv });
24
30
  onKill(handle.kill);
25
31
  const r = await handle.done;
26
32
  return {
@@ -0,0 +1,144 @@
1
+ // 工作区(ws)管理与扫描:让路由知道本机有哪些代码库/工程目录,派执行者时可以直接切到对应目录干活。
2
+ // 已登记的存 00-config/workspaces.json(结构简单、程序读写不碰 profile.yaml 的手写格式);
3
+ // 扫描从 GIT_ACTIVITY_WORKSPACES、~/workspace 下的 git 仓库取候选,按最近活跃时间排。
4
+ 'use strict';
5
+ const fs = require('node:fs');
6
+ const path = require('node:path');
7
+ const { writeFileAtomic, UsageError } = require('./run');
8
+
9
+ const WS_FILE = ['00-config', 'workspaces.json'];
10
+ const ID_RE = /^[A-Za-z0-9._-]{1,64}$/;
11
+ const SCAN_LIMIT = 20;
12
+
13
+ const wsFile = (root) => path.join(root, ...WS_FILE);
14
+
15
+ function loadRegistered(root) {
16
+ try {
17
+ const data = JSON.parse(fs.readFileSync(wsFile(root), 'utf8'));
18
+ if (!Array.isArray(data)) return [];
19
+ return data
20
+ .filter((x) => x && typeof x === 'object' && x.id && x.path)
21
+ .map((x) => ({
22
+ id: String(x.id).trim(),
23
+ path: path.resolve(String(x.path).trim()),
24
+ note: String(x.note || '').trim(),
25
+ agent: String(x.agent || '').trim(),
26
+ }));
27
+ } catch {
28
+ return [];
29
+ }
30
+ }
31
+
32
+ function saveRegistered(root, list) {
33
+ writeFileAtomic(wsFile(root), `${JSON.stringify(list, null, 2)}\n`);
34
+ }
35
+
36
+ function addWorkspace(root, { id, dir, note = '', agent = '' }) {
37
+ const cleanId = String(id || '').trim();
38
+ if (!ID_RE.test(cleanId)) throw new UsageError(`工作区 id 不合法(只用字母、数字、._-,1–64 字):${cleanId || '(空)'}`);
39
+ const full = path.resolve(String(dir || '').trim());
40
+ if (!full || !fs.existsSync(full) || !fs.statSync(full).isDirectory()) {
41
+ throw new UsageError(`目录不存在:${dir || '(空)'}`);
42
+ }
43
+ const list = loadRegistered(root);
44
+ const item = { id: cleanId, path: full, note: String(note || '').trim(), agent: String(agent || '').trim() };
45
+ const idx = list.findIndex((x) => x.id === cleanId);
46
+ if (idx >= 0) list[idx] = item;
47
+ else list.push(item);
48
+ saveRegistered(root, list);
49
+ return item;
50
+ }
51
+
52
+ function removeWorkspace(root, id) {
53
+ const cleanId = String(id || '').trim();
54
+ const list = loadRegistered(root);
55
+ const next = list.filter((x) => x.id !== cleanId);
56
+ if (next.length === list.length) return false;
57
+ saveRegistered(root, next);
58
+ return true;
59
+ }
60
+
61
+ // 扫描本机候选工作区:GIT_ACTIVITY_WORKSPACES + ~/workspace(或 env.WRJ_WS_SCAN_DIRS)下的 git 仓库
62
+ function scanCandidates(root, env = process.env) {
63
+ const home = env.HOME || '';
64
+ const roots = new Set();
65
+ const addDirs = (raw) => {
66
+ for (const part of String(raw || '').split(/[:\n,;]+/)) {
67
+ const p = part.trim().replace(/^~(?=\/|$)/, home);
68
+ if (p) roots.add(path.resolve(p));
69
+ }
70
+ };
71
+ if (env.WRJ_WS_SCAN_DIRS) addDirs(env.WRJ_WS_SCAN_DIRS);
72
+ else {
73
+ addDirs(env.GIT_ACTIVITY_WORKSPACES);
74
+ if (home) roots.add(path.join(home, 'workspace'));
75
+ }
76
+
77
+ const rootResolved = path.resolve(root);
78
+ const registered = loadRegistered(root);
79
+ const byPath = new Map(registered.map((w) => [w.path, w]));
80
+ const byId = new Set(registered.map((w) => w.id));
81
+ const found = [];
82
+
83
+ const consider = (dir) => {
84
+ const full = path.resolve(dir);
85
+ if (full === rootResolved || byPath.has(full)) return;
86
+ const gitDir = path.join(full, '.git');
87
+ if (!fs.existsSync(gitDir)) return;
88
+ let mtime = 0;
89
+ try {
90
+ mtime = Math.max(fs.statSync(full).mtimeMs, fs.statSync(gitDir).mtimeMs);
91
+ } catch {
92
+ mtime = 0;
93
+ }
94
+ const base = path.basename(full);
95
+ if (!ID_RE.test(base) || byId.has(base)) return;
96
+ byPath.set(full, { id: base, path: full });
97
+ byId.add(base);
98
+ found.push({ id: base, path: full, note: '', agent: '', mtime });
99
+ };
100
+
101
+ for (const dir of roots) {
102
+ if (!fs.existsSync(dir)) continue;
103
+ let stat;
104
+ try {
105
+ stat = fs.statSync(dir);
106
+ } catch {
107
+ continue;
108
+ }
109
+ if (!stat.isDirectory()) continue;
110
+ if (fs.existsSync(path.join(dir, '.git'))) {
111
+ consider(dir);
112
+ continue;
113
+ }
114
+ let entries;
115
+ try {
116
+ entries = fs.readdirSync(dir, { withFileTypes: true });
117
+ } catch {
118
+ continue;
119
+ }
120
+ for (const e of entries) {
121
+ if (!e.isDirectory() || e.name.startsWith('.')) continue;
122
+ consider(path.join(dir, e.name));
123
+ }
124
+ }
125
+
126
+ found.sort((a, b) => b.mtime - a.mtime);
127
+ return found.slice(0, SCAN_LIMIT).map(({ id, path: p, note, agent }) => ({ id, path: p, note, agent }));
128
+ }
129
+
130
+ // 给路由用的合并视图:{ registered, scanned, resolve(id) }
131
+ function discoverWorkspaces(root, env = process.env) {
132
+ const registered = loadRegistered(root);
133
+ const scanned = scanCandidates(root, env);
134
+ const all = new Map();
135
+ for (const w of registered) all.set(w.id, { ...w, registered: true });
136
+ for (const w of scanned) if (!all.has(w.id)) all.set(w.id, { ...w, registered: false });
137
+ return {
138
+ registered,
139
+ scanned,
140
+ resolve: (id) => (id ? all.get(String(id).trim()) || null : null),
141
+ };
142
+ }
143
+
144
+ module.exports = { WS_FILE, ID_RE, loadRegistered, saveRegistered, addWorkspace, removeWorkspace, scanCandidates, discoverWorkspaces };
@@ -21,7 +21,7 @@ function setup(t) {
21
21
  const profile = `${box.work}/00-config/profile.yaml`;
22
22
  write(profile, setKey(read(profile), 'notify', '"yzj-robot"'));
23
23
  const stubs = box.stubs();
24
- const s = { box, profile, stubs, env: { ...stubs, STUB_KEYCHAIN: 'ok', STUB_ROBOT_URL: DUMMY_URL, YZJ_MY_OPEN_ID: 'me-0001' } };
24
+ const s = { box, profile, stubs, env: { ...stubs, STUB_KEYCHAIN: 'ok', STUB_ROBOT_URL: DUMMY_URL, YZJ_MY_OPEN_ID: 'me-0001', YZJ_BOT_DEBOUNCE: '0' } };
25
25
  s.run = (args, env = {}) => box.run(args, { env: { ...s.env, ...env } });
26
26
  s.set = (key, value) => write(profile, setKey(read(profile), key, value));
27
27
  s.routerOn = () => write(profile, read(profile).replace(/^( quiet:.*)$/m, '$1\n router: true'));
@@ -518,7 +518,7 @@ test('路由模式插话:有执行者在跑时新来的话立刻回「收到
518
518
  write(reply, '决定:\n- t-000002 interrupt t-000001\n');
519
519
  eng.message({ msgId: 'm2', content: '等等,项目名改成导出改造' });
520
520
  await wait(300);
521
- assert.deepEqual(hook.contents(), ['收到,正在处理,稍等。', ACK_MORE], '执行者还在跑,这句的「收到」立刻到');
521
+ assert.deepEqual(hook.contents(), ['收到,正在处理,稍等。', '收到,正在处理,稍等。'], '执行者还在跑,这句的「收到」立刻到');
522
522
  assert.ok(await eng.waitIdle(30000), '没等到做完');
523
523
  const st = svc.store.data.triggers;
524
524
  assert.equal(st['t-000001'].worker.status, 'stopped');
@@ -847,3 +847,72 @@ test('今日页「待你定」实时更新:页面点选项后记入卡片与 D
847
847
  assert.equal(JSON.parse(read(`${s.box.work}/01-inbox/_rhythm/asks/${ownId}.json`)).answer.choice, ownWords);
848
848
  assert.match(read(file), new RegExp(`\\| 导出边界怎么处理 \\| ①发上游 ②周会提 \\| ${ownWords} \\|`));
849
849
  });
850
+
851
+ test('IM 连发防抖合批:短时间内连发两句合成一条 message 触发,只进一轮路由、回一次', async (t) => {
852
+ const s = setup(t);
853
+ s.routerOn();
854
+ s.bind(`YZJ_BOT_AGENT="${CUSTOM(s.box)}"\n`);
855
+ const svc = s.service({ YZJ_BOT_DEBOUNCE: '1' });
856
+ const eng = svc.makeEngine();
857
+ const sent = [];
858
+ eng.setSink((text) => sent.push(text));
859
+ eng.message({ msgId: 'd1', content: '有没有什么体验比较好的办法?' });
860
+ await new Promise((r) => setTimeout(r, 150));
861
+ eng.message({ msgId: 'd2', content: '过程中就开始识别并且过滤?' });
862
+ // 防抖窗口还没到,触发还没入队
863
+ assert.equal(Object.keys(svc.store.data.triggers).length, 0);
864
+ await new Promise((r) => setTimeout(r, 1200));
865
+ assert.ok(await eng.waitIdle(20000));
866
+ const msgs = Object.values(svc.store.data.triggers).filter((x) => x.kind === 'message');
867
+ assert.equal(msgs.length, 1, '两句合成了一条触发');
868
+ assert.match(s.task(msgs[0].id), /有没有什么体验比较好的办法?\n过程中就开始识别并且过滤?/);
869
+ assert.equal(sent.filter((x) => !x.startsWith('收到')).length, 1, '只回了一次');
870
+ });
871
+
872
+ test('工作区扫描、登记与跨 ws 路由:路由看到候选工作区并选 ws=<id>,执行者在目标目录跑,进度提示带工作区', async (t) => {
873
+ const s = setup(t);
874
+ s.routerOn();
875
+ s.bind(`YZJ_BOT_AGENT="${CUSTOM(s.box)}"\n`);
876
+ const baseDir = path.dirname(s.box.work);
877
+ const repoDir = path.join(baseDir, 'demo-repo');
878
+ fs.mkdirSync(path.join(repoDir, '.git'), { recursive: true });
879
+ // workspace scan 能扫到候选,add / list / remove 正常
880
+ const scan = s.run(['workspace', 'scan', '--json'], { WRJ_WS_SCAN_DIRS: baseDir });
881
+ assert.equal(scan.code, 0, scan.out);
882
+ assert.ok(JSON.parse(scan.stdout).scanned.some((w) => w.id === 'demo-repo'));
883
+ assert.equal(s.run(['workspace', 'add', 'demo-repo', repoDir, '--note', '示例仓库']).code, 0);
884
+ assert.match(s.run(['workspace', 'list']).stdout, /demo-repo\t.*demo-repo\t\t示例仓库/);
885
+ // parseRouterReply 认 ws=
886
+ const parsed = parseRouterReply('决定:\n- t-000001 dispatch ws=demo-repo\n\n## handoff t-000001\n# 任务:查仓库\n\n检查仓库。\n');
887
+ assert.equal(parsed[0].ws, 'demo-repo');
888
+ // 跑一轮:路由提示词里带着 demo-repo,选了 ws=demo-repo 后执行者记录 ws 且进度提示带工作区
889
+ const reply = `${baseDir}/ws-reply.txt`;
890
+ write(reply, '决定:\n- t-000001 dispatch ws=demo-repo\n\n## handoff t-000001\n# 任务:查仓库\n\n把这句话原样回复给我:「在 demo-repo 里跑完了」\n');
891
+ const svc = s.service({ STUB_ROUTER_REPLY: reply, WRJ_WS_SCAN_DIRS: baseDir, YZJ_BOT_PROGRESS: '1', STUB_WORKER_DELAY: '2' });
892
+ const eng = svc.makeEngine();
893
+ const sent = [];
894
+ eng.setSink((text) => sent.push(text));
895
+ eng.message({ msgId: 'w1', content: '去 demo-repo 查一下' });
896
+ assert.ok(await eng.waitIdle(20000));
897
+ assert.match(s.routerCalls()[0], /可用工作区[\s\S]*demo-repo(已登记/);
898
+ const trig = svc.store.data.triggers['t-000001'];
899
+ assert.equal(trig.ws, 'demo-repo');
900
+ assert.equal(trig.worker.ws, 'demo-repo');
901
+ assert.ok(sent.some((x) => x.includes('工作区 demo-repo')), `进度提示应带工作区,实际:${JSON.stringify(sent)}`);
902
+ });
903
+
904
+ test('并发任务进度汇总:同时跑 2 个执行者时,进度提示合成一条消息,不刷屏', async (t) => {
905
+ const s = setup(t);
906
+ s.routerOn();
907
+ s.bind(`YZJ_BOT_AGENT="${CUSTOM(s.box)}"\n`);
908
+ const svc = s.service({ YZJ_BOT_PROGRESS: '1', YZJ_BOT_PROGRESS_MAX: '1', STUB_WORKER_DELAY: '2' });
909
+ const eng = svc.makeEngine();
910
+ const sent = [];
911
+ eng.setSink((text) => sent.push(text));
912
+ eng.message({ msgId: 'p1', content: '第一件事' });
913
+ eng.message({ msgId: 'p2', content: '第二件事' });
914
+ assert.ok(await eng.waitIdle(20000));
915
+ const summary = sent.filter((x) => x.startsWith('手头有 2 件事还在做'));
916
+ assert.equal(summary.length, 1, `应汇总成 1 条进度消息,实际:${JSON.stringify(sent)}`);
917
+ assert.match(summary[0], /1\. \[工作区 工作目录\][\s\S]*2\. \[工作区 工作目录\]/);
918
+ });