work-rhythm 0.2.15 → 0.2.21

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.
@@ -133,7 +133,7 @@ function refineBody(file) {
133
133
  '',
134
134
  '1. 读 00-config/sources.yaml:每个启用的源有「提炼成什么事件」的规则(extract)。',
135
135
  '2. 读 01-inbox/<源id>/<今天>/ 下各源的输出(刚同步过;哪个源没有目录就跳过)。',
136
- '3. 按各源的规则提炼事件,对照 docs/formats.md 的「事件流」:类型用词表里的词,一行一事、不记内容细节;项目能归就归。',
136
+ '3. 按各源的规则提炼事件,对照 docs/formats.md 的「事件流」:类型用词表里的词,一行一事、不记内容细节;项目能归就归;「索引」列填能回到工作现场的指针(如 01-inbox/<源id>/<今天>/具体文件名、ws=<工作区id> <分支>@<短hash>、工作项编号、文件路径或交接回执路径),没有就留空。',
137
137
  `4. 合并进今天每日文件(${file})的「## 事件流」:替换同来源同时段的旧事件,保留来源是「口述」的行,按时间排序;文件不存在就按格式创建。只改这一节。`,
138
138
  '5. 回执里写:各源分别提炼出几条、合并后事件流一共几条;哪个源的数据读不到就写「未取到」,不要编。',
139
139
  '',
@@ -163,35 +163,6 @@ function answerBody(c) {
163
163
  return lines.join('\n');
164
164
  }
165
165
 
166
- // 重点与待办的任务书:路由把一批新事件派出去时用(路由可以再补一段)。c.root 是工作目录
167
- function focusBody(c) {
168
- const list = (c.events || []).map((e) => `- ${e.time} ${e.type} ${e.item}${e.project ? `(${e.source},${e.project})` : e.source ? `(${e.source})` : ''}`).join('\n');
169
- const bad = (c.sources || []).filter((x) => !x.ok).map((x) => `${x.id}:${x.detail || `退出码 ${x.code}`}`).join(';');
170
- const file = dailyFile(c.root || '.', c.date || today());
171
- return [
172
- '# 任务:根据新到的事件更新今日重点和待办',
173
- '',
174
- `今天新到的事件(${(c.events || []).length} 条):`,
175
- list || '(没有新事件)',
176
- ...(bad ? ['', `这次采集有源没取到数据(回执里说清,涉及的事标「未取到」):${bad}`] : []),
177
- '',
178
- `1. 读今天每日文件(${file})的「## 计划」「## 事件流」「## 备注」,03-carryover/CARRYOVER.md 的未了结,05-goals/ 里进行中的目标。`,
179
- '2. 据此更新「## 计划」里的今日重点(不超过 3 条,每条带建议时间块和理由)。只改这一处;例行的事(通勤、打卡)不算重点。「待你定」不要再写进计划文件:需要我拿主意的事走下面的卡片。',
180
- '3. 需要我拿主意的事,逐件用 work-rhythm ask 丢出来(它会成一张卡,实时显示在今日页的「待你定」里)。先 work-rhythm ask list 看有没有同一件事还没答的,有就不重复问;没有就:',
181
- ' work-rhythm ask --json \'{"question":"<一句话的问题>","context":"<两三句背景:为什么现在要定、卡在哪>","options":[{"label":"<选项>","detail":"<一句话说明>","suggested":true},{"label":"<选项>"}],"record":"<我答了之后总结记到哪,如 03-carryover/CARRYOVER.md 的未了结>","item":"<不超过 30 字的短事项>"}\'',
182
- ' 2–4 个选项,其中一个标 suggested 并在 detail 里说理由;真没有可选的就不写 options(我会自己写回答)。没有要问的就不问。',
183
- '4. 回执按这个格式写(路由会转给用户,纯文本、不放链接):',
184
- ' 今日重点:',
185
- ' - …',
186
- ' 待办卡片(我会在今日页的「待你定」里点选项,不用你催):',
187
- ' 1. <事项>:<选项,标出建议的>',
188
- ' 2. …',
189
- ' 没有卡片就不写这一段。',
190
- '',
191
- '',
192
- ].join('\n');
193
- }
194
-
195
166
  // cfg 来自 rhythm.js 的 loadConfig(router、routerTimeout、workers、handoffKeep、historyKeep、taskTimeout、agentMode、agentModel、
196
167
  // agentEffort、push、quiet、links、baseUrl、serviceAlive、ack、botMode、botTimeout、replyMax、botPreamble、refine、refineInterval)。state 是 { data, save }
197
168
  function createEngine({ root, env, cfg, log = () => {}, push = async () => false, state, since = Date.now() }) {
@@ -216,38 +187,43 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
216
187
  let pumpScheduled = false; // 这个 tick 里已经排了一轮
217
188
  let msgBuf = null;
218
189
  let msgTimer = null;
219
- const activeProgress = new Map(); // id → { t, started, count }
190
+ const activeProgress = new Map(); // id → { t, started }
220
191
  let progressTimer = null;
192
+ let progressStepMs = 0;
193
+ const MAX_PROGRESS_STEP_MS = 30 * 60 * 1000; // 指数退避封顶 30 分钟
221
194
  function stopProgressTimer() {
222
- if (progressTimer) { clearInterval(progressTimer); progressTimer = null; }
195
+ if (progressTimer) { clearTimeout(progressTimer); progressTimer = null; }
196
+ progressStepMs = 0;
223
197
  }
224
- function ensureProgressTimer() {
225
- if (progressTimer || !cfg.progress || cfg.progress <= 0) return;
226
- const stepMs = Math.max(200, cfg.progress * 1000);
227
- progressTimer = setInterval(() => {
198
+ function scheduleNextProgress() {
199
+ if (closing || !activeProgress.size || !cfg.progress || cfg.progress <= 0) { stopProgressTimer(); return; }
200
+ const delay = progressStepMs || Math.max(200, cfg.progress * 1000);
201
+ progressTimer = setTimeout(() => {
202
+ progressTimer = null;
228
203
  if (closing || !activeProgress.size) { stopProgressTimer(); return; }
229
204
  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];
205
+ const all = [...activeProgress.values()];
206
+ if (all.length === 1) {
207
+ const { t, started } = all[0];
240
208
  send(t, `还在做(已经 ${humanDuration((now - started) / 1000)} · 工作区 ${t.ws || '工作目录'}):${t.title || t.id}。做完汇报。`, { mark: false });
241
209
  } else {
242
- const lines = ['手头有 ' + due.length + ' 件事还在做(做完汇报):'];
243
- due.forEach(({ t, started }, i) => {
210
+ const lines = ['手头有 ' + all.length + ' 件事还在做(做完汇报):'];
211
+ all.forEach(({ t, started }, i) => {
244
212
  lines.push(`${i + 1}. [工作区 ${t.ws || '工作目录'}] ${t.title || t.id}(已 ${humanDuration((now - started) / 1000)})`);
245
213
  });
246
214
  send(null, lines.join('\n'), { mark: false });
247
215
  }
248
- }, stepMs);
216
+ // 指数退避:前期密(90s → 3m → 6m → 12m → 24m),后期慢(封顶 30m),超长任务不再刷屏也不截断
217
+ progressStepMs = Math.min(delay * 2, MAX_PROGRESS_STEP_MS);
218
+ scheduleNextProgress();
219
+ }, delay);
249
220
  if (progressTimer.unref) progressTimer.unref();
250
221
  }
222
+ function ensureProgressTimer() {
223
+ if (progressTimer || !cfg.progress || cfg.progress <= 0) return;
224
+ progressStepMs = Math.max(200, cfg.progress * 1000);
225
+ scheduleNextProgress();
226
+ }
251
227
  function flushMessages() {
252
228
  if (msgTimer) { clearTimeout(msgTimer); msgTimer = null; }
253
229
  if (!msgBuf) return null;
@@ -263,7 +239,7 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
263
239
  // IM 来的话(message)分两种:路由判成 dispatch 的是「派人做事」,事要写文件,按定时任务的权限来(rhythm.agent-mode)——
264
240
  // 2026-12-02 用户决定,原来一律只读,结果派出去的人写不了、做不成;路由没开时的直答(fallback)还是 YZJ_BOT_AGENT_MODE,默认只读
265
241
  function terms(t, { byRouter = false } = {}) {
266
- if (t.kind === 'schedule' || t.kind === 'events') return { mode: cfg.agentMode, timeoutS: cfg.taskTimeout };
242
+ if (t.kind === 'schedule') return { mode: cfg.agentMode, timeoutS: cfg.taskTimeout };
267
243
  if (t.kind === 'message' && router && byRouter) return { mode: cfg.agentMode, timeoutS: cfg.taskTimeout };
268
244
  if (t.kind === 'answer') {
269
245
  const o = live.get(t.id) && live.get(t.id).ask && live.get(t.id).ask.from && triggers()[live.get(t.id).ask.from.trigger];
@@ -304,7 +280,6 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
304
280
  if (key && Object.values(triggers()).some((x) => x.key === key)) return null;
305
281
  const t = record(kind, { key, task, of, quiet });
306
282
  live.set(t.id, { text, taskFile, taskBody, taskTitle, mode, opening, linkTask, orig, ok, seconds, reason, events, sources, ask, date, root: eventRoot || root });
307
- if (kind === 'events') t.title = `新事件 ${(events || []).length} 条 → 今日重点与待办`;
308
283
  if (kind === 'answer' && ask) t.title = `回答:${ask.item || ask.question || ''}`;
309
284
  queue.push(t.id);
310
285
  save();
@@ -368,9 +343,9 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
368
343
  save();
369
344
  log('执行者结束', `${t.id} ${ok ? '成功' : r.stopped ? '叫停' : '失败'} ${r.seconds}s`);
370
345
  const c = live.get(t.id) || {};
371
- // 提炼是 CLI 自己起的一步:做完了不算汇报,算出新增的事件打包成一条 events 触发给路由
346
+ // 提炼是 CLI 自己起的一步,静默:做完不汇报
372
347
  if (t.kind === 'refine') {
373
- afterRefine(t, r, c);
348
+ afterRefine(t, r);
374
349
  return r;
375
350
  }
376
351
  // 被插话停掉的:不汇报,接着它重跑的那次会汇报
@@ -387,7 +362,7 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
387
362
  }
388
363
  enqueue('report', {
389
364
  key: `report-${t.id}`, of: t.id, ok, seconds: r.seconds, reason: r.stopped ? '用户叫停' : r.failed, quiet: t.quiet,
390
- opening: ok ? handoff.opening(resultBody(handoff.readText(handoff.resultPath(root, t.id)))) : '', linkTask: t.kind === 'schedule' ? t.task : t.kind === 'events' || t.kind === 'answer' ? 'todos' : '', orig: t, task: c.linkTask,
365
+ opening: ok ? handoff.opening(resultBody(handoff.readText(handoff.resultPath(root, t.id)))) : '', linkTask: t.kind === 'schedule' ? t.task : '', orig: t, task: c.linkTask,
391
366
  });
392
367
  return r;
393
368
  }
@@ -406,7 +381,7 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
406
381
  t.worker.startedAt = fmtStamp();
407
382
  save();
408
383
  // 我这边直接派出去的(消息、手动)跑得久就统一汇总说一声;定时任务的汇报本来就会来,不额外打扰
409
- const trackProgress = t.kind !== 'schedule' && !t.quiet && cfg.progress > 0;
384
+ const trackProgress = t.kind !== 'schedule' && !t.quiet && cfg.progress > 0; // 静默的(提炼、quiet 任务)不提示
410
385
  if (trackProgress) {
411
386
  activeProgress.set(t.id, { t, started: Date.now(), count: 0 });
412
387
  ensureProgressTimer();
@@ -456,7 +431,6 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
456
431
  t.wsPath = resolvedWs.path;
457
432
  }
458
433
  if (t.kind === 'schedule') body = `${s(c.taskBody)}${body ? `\n\n## 路由的补充\n\n${body}` : ''}\n\n${NOTE_BY_SERVICE}`;
459
- else if (t.kind === 'events') body = `${focusBody({ ...c, root })}${body ? `\n## 路由的补充\n\n${body}` : ''}\n\n${NOTE_BY_SERVICE}`;
460
434
  else if (t.kind === 'answer') body = `${answerBody(c)}${body ? `\n## 路由的补充\n\n${body}` : ''}\n\n${NOTE_BY_SERVICE}`;
461
435
  else if (t.kind === 'report') body = `# 任务:重做 ${t.of}\n\n上一次的结果:${c.ok ? handoff.opening(handoff.readText(handoff.resultPath(root, t.of))) : c.reason}\n旧任务书在 ${handoff.relTask(t.of)},旧回执在 ${handoff.relResult(t.of)},先读它们。\n\n${body || '按原任务书重做一遍。'}`;
462
436
  else if (!body) body = `# 任务:照用户的话做\n\n用户原话:「${c.text}」\n\n照它做。这是一句追问、单凭这句话做不了的话,在回执里说清楚缺什么。`;
@@ -607,46 +581,37 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
607
581
  pump();
608
582
  }
609
583
 
610
- // 定时采集之后(rhythm.js 调):有新数据、或者有源没取到,就起一轮提炼;做完把新增的事件打包给路由
584
+ // 定时采集之后(rhythm.js 调):有新数据就静默起一轮提炼,把新采到的数据炼成事件(带工作现场索引)并进事件流。
585
+ // 静默:不交给路由、不打扰用户;源没取到数据只记日志和监控(2026-12-03 用户决定,看板和提醒太多)
611
586
  async function afterSync({ results = [], changed = false } = {}) {
612
- if (!router || !cfg.refine) return null;
587
+ if (!cfg.refine) return null;
613
588
  const bad = results.filter((x) => !x.ok);
614
- // 没有新数据:不炼。有源出事就把采集状态直接给路由(不用等提炼),路由决定要不要告诉用户
589
+ if (bad.length) log('采集有源没取到', bad.map((x) => `${x.id}:${x.detail || `退出码 ${x.code}`}`).join(';'));
590
+ // 没有新数据:不炼
615
591
  if (!changed) {
616
592
  log('提炼跳过', '没有新数据');
617
- if (bad.length) enqueue('events', { key: `events-sync-${Date.now()}`, ok: true, events: [], sources: results, date: today(), root });
618
593
  return null;
619
594
  }
620
- // 新数据等够间隔再炼(rhythm.refine-interval 分钟);这期间有源出事也直接告诉路由
595
+ // 新数据等够间隔再炼(rhythm.refine-interval 分钟)
621
596
  const last = state.data.refinedAt;
622
597
  if (last && Date.now() - stampMs(last) < cfg.refineInterval * 60000) {
623
598
  log('提炼跳过', `上一次 ${last},不到 ${cfg.refineInterval} 分钟`);
624
- if (bad.length) enqueue('events', { key: `events-sync-${Date.now()}`, ok: true, events: [], sources: results, date: today(), root });
625
599
  return null;
626
600
  }
627
601
  const date = today();
628
- const t = record('refine', { key: `refine-${date}-${Date.now()}`, decision: 'refine', title: '把今天新采到的数据提炼成事件' });
629
- live.set(t.id, { results, date, before: new Set(dayEvents(root, date).map(eventKey)), root });
602
+ const t = record('refine', { key: `refine-${date}-${Date.now()}`, decision: 'refine', quiet: true, title: '把今天新采到的数据提炼成事件' });
603
+ live.set(t.id, { results, date, root });
630
604
  handoff.writeTask(root, { ...t, text: '' }, refineBody(dailyFile(root, date)), { mode: cfg.agentMode, timeoutS: cfg.taskTimeout });
631
605
  save();
632
606
  log('提炼开始', t.id);
633
607
  return launch(t, { mode: cfg.agentMode, timeoutS: cfg.taskTimeout });
634
608
  }
635
609
 
636
- // 提炼做完:比对话件里的事件流,新增的打包成 events 触发给路由。没新增、也没源出事就不打扰路由
637
- function afterRefine(t, r, c) {
610
+ // 提炼做完:只记一笔。失败只记日志和监控,不告诉用户(晚间复盘会自己再采一遍、炼一遍)
611
+ function afterRefine(t, r) {
638
612
  state.data.refinedAt = fmtStamp();
639
613
  save();
640
- const date = c.date || today();
641
- let events = [];
642
- if (r.ok) {
643
- const before = c.before || new Set();
644
- events = dayEvents(root, date).filter((e) => !before.has(eventKey(e)));
645
- log('提炼结束', `${t.id} 新增 ${events.length} 条事件`);
646
- }
647
- const bad = (c.results || []).filter((x) => !x.ok);
648
- if (!r.ok) enqueue('events', { key: `events-${t.id}`, of: t.id, ok: false, reason: r.failed, events: [], sources: c.results || [], date, root });
649
- else if (events.length || bad.length) enqueue('events', { key: `events-${t.id}`, of: t.id, ok: true, events, sources: c.results || [], date, root });
614
+ log('提炼结束', r.ok ? t.id : `${t.id} 失败:${r.failed || '未知原因'}`);
650
615
  }
651
616
 
652
617
  // 服务启动时:上次没跑完的执行者各补一份失败的回执,变成汇报交回路由;停服务时没来得及汇报的也补上
@@ -698,13 +663,10 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
698
663
  }
699
664
  const item = JSON.parse(fs.readFileSync(file, 'utf8'));
700
665
  fs.unlinkSync(file);
701
- // 执行者用 work-rhythm ask 丢出来的卡:直接把问题推给我、带着今日页的地址(实时显示在那儿),不花路由一轮
666
+ // 执行者 work-rhythm ask 丢出来的问题:不再推给我、也不成卡(2026-12-03 用户决定,「待你定」整块取消)。只记一笔日志和监控
702
667
  if (item.kind === 'ask') {
703
668
  const ask = asks.readAsk(root, item.ask);
704
- if (ask && !ask.answer) {
705
- log('待你定', `${ask.id} ${ask.item}`);
706
- send(null, `等你定:${asks.askSummary(ask)}${ask.context ? `\n${ask.context}` : ''}`, { linkTask: 'todos' });
707
- }
669
+ if (ask && !ask.answer) log('执行者想问', `${ask.id} ${ask.item || ''}`.trim());
708
670
  continue;
709
671
  }
710
672
  enqueue('manual', { key: `fired-${name.slice(0, -5)}`, text: s(item.text), mode: s(item.mode) || 'plan' });
@@ -749,7 +711,8 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
749
711
  afterSync,
750
712
  // 页面上答了一张卡:一条 answer 触发给路由(rhythm.js 调;ask 里带着答案)。
751
713
  // 去重键用卡片 id;老办法登记的「未答」行没有卡片文件(id 是空的),用事项——不然第二张就会被当成重复丢掉
752
- answer: (ask) => (router ? enqueue('answer', { key: `answer-${ask.id || ask.item}`, of: ask.from && ask.from.trigger ? ask.from.trigger : '', ask, root }) : null),
714
+ // 页面上答一张卡(work-rhythm ask 的卡):卡片这一块已经取消(2026-12-03),答了只记一笔,不再派活
715
+ answer: () => null,
753
716
  // 命令行走一遍:要发的文字交到这里,不真发
754
717
  setSink(fn) {
755
718
  sink = fn;
@@ -777,4 +740,4 @@ function createEngine({ root, env, cfg, log = () => {}, push = async () => false
777
740
  };
778
741
  }
779
742
 
780
- module.exports = { createEngine, appendHistory, pruneState, historyStats, fire, queueDir, resultBody, pendingCards, dayEvents, eventKey, refineBody, focusBody, ACK_TEXT, uid };
743
+ module.exports = { createEngine, appendHistory, pruneState, historyStats, fire, queueDir, resultBody, pendingCards, dayEvents, eventKey, refineBody, ACK_TEXT, uid };
@@ -70,7 +70,7 @@ function taskText(t, body, extra = {}) {
70
70
  `# 任务书 ${t.id}`,
71
71
  '',
72
72
  `- 来源:${source}`,
73
- `- 派给:执行者 · 权限 ${extra.mode || 'plan'} · 最多 ${extra.timeoutS || 300} 秒`,
73
+ `- 派给:执行者 · 权限 ${extra.mode || 'plan'} · ${extra.timeoutS > 0 ? `最多 ${extra.timeoutS} 秒` : '不限时'}`,
74
74
  `- ${t.kind === 'report' ? '重做自' : '续做自'}:${t.kind === 'report' ? t.of || '' : extra.continueOf || '无'}`,
75
75
  '',
76
76
  '## 要求',
@@ -79,7 +79,7 @@ function taskText(t, body, extra = {}) {
79
79
  '',
80
80
  '## 回执',
81
81
  '',
82
- `做完把结果写到 \`${relResult(t.id)}\`:做了什么、改了哪些文件、要留意什么、有几件事等我拿主意。`,
82
+ `做完把结果写到 \`${relResult(t.id)}\`:做了什么、改了哪些文件、要留意什么;要我拿主意的事单起一段「要我拿主意」,一句话一件事、带上你建议的选项。`,
83
83
  '取不到的数据写「未取到」,不要编。要改动外部系统(发消息、改日程、流转工作项)的事不要做,写进回执让我定。',
84
84
  '没有写权限就把同样内容作为最后一段话输出。纯文本,不放链接。不要向我提问,不要等待确认,不要自己发消息。',
85
85
  '',
@@ -18,15 +18,13 @@ const { logger } = require('./log');
18
18
  const { createAgent, roles, routerProblems } = require('./agent');
19
19
  const { createBot } = require('./bot');
20
20
  const { notifyChannel, pushText } = require('./notify');
21
- const { createEngine, appendHistory, pruneState, historyStats, uid, pendingCards } = require('./engine');
21
+ const { createEngine, appendHistory, pruneState, historyStats, uid } = require('./engine');
22
22
  const handoff = require('./handoff');
23
23
  const md = require('./markdown');
24
24
  const view = require('./view');
25
25
  const launchd = require('./launchd');
26
26
  const sync = require('../cmd/sync');
27
27
  const today = require('../cmd/today');
28
- const decisions = require('../cmd/decisions');
29
- const asks = require('./asks');
30
28
 
31
29
  const TICK_MS = 20000;
32
30
  const CATCH_UP_MS = 5 * 60 * 1000;
@@ -42,12 +40,11 @@ const LINKS = {
42
40
  'weekly-rhythm': { path: () => '/rhythm', label: '工作规律' },
43
41
  'alerts-morning': { path: (d) => `/reports/${d}-alerts.html`, label: '告警晨报' },
44
42
  // 一批新事件之后的「今日重点与待办」:地址给「决定」页(待办卡片在那里点),手机打不开,要在自己电脑上开
45
- 'todos': { path: () => '/#pending-decisions', label: '今日页「待你定」(在自己电脑的浏览器里打开)' },
46
43
  };
47
44
  const NAV = [['/', '今日'], ['/carryover', '遗留'], ['/decisions', '决定'], ['/rhythm', '规律'], ['/goals', '目标'], ['/reports', '报告'], ['/monitor', '监控']];
48
45
  const NEW_KEYS = [['workers', 'rhythm.workers'], ['router-timeout', 'rhythm.router-timeout'], ['handoff-keep', 'rhythm.handoff-keep'], ['history-keep', 'rhythm.history-keep']];
49
46
  // 状态文件的骨架:done(跑过的任务)、runs(各任务最近一次)、seq(触发短号的序号)、triggers(近两天的触发)、history(运行记录)、rounds(路由的轮数)
50
- const EMPTY_STATE = () => ({ done: {}, runs: {}, seq: 0, triggers: {}, history: [], rounds: [], sources: {}, refinedAt: '', syncDigest: { date: '', digest: '' }, cardsExpiredOn: '' });
47
+ const EMPTY_STATE = () => ({ done: {}, runs: {}, seq: 0, triggers: {}, history: [], rounds: [], sources: {}, refinedAt: '', syncDigest: { date: '', digest: '' } });
51
48
 
52
49
  const positiveInt = (value, fallback) => {
53
50
  const n = Number(value);
@@ -75,7 +72,7 @@ function loadConfig(root) {
75
72
  // 定时任务用的模型和思考强度(可选项,profile 里不写也行):不配就和值守一样,用 local.env 的 YZJ_BOT_MODEL / YZJ_BOT_EFFORT
76
73
  agentModel: typeof rhythm['agent-model'] === 'string' ? rhythm['agent-model'].trim() : '',
77
74
  agentEffort: typeof rhythm['agent-effort'] === 'string' ? rhythm['agent-effort'].trim() : '',
78
- taskTimeout: positiveInt(rhythm['task-timeout'], 1200),
75
+ taskTimeout: seconds(rhythm['task-timeout'], 0),
79
76
  syncTimeout: positiveInt(rhythm['sync-timeout'], 600),
80
77
  notifyChannel: typeof preferences.notify === 'string' ? preferences.notify.trim() : '',
81
78
  schedule,
@@ -474,9 +471,8 @@ function createRhythm({ root, env, packageRoot }) {
474
471
 
475
472
  function route(req, res) {
476
473
  // 唯一的写接口:本机今日页「待你定」卡片的回答
477
- if (req.method === 'POST' && /^\/api\/asks\/answer$/.test(String(req.url || '').split('?')[0])) return answerOnPage(req, res);
478
474
  if (req.method !== 'GET' && req.method !== 'HEAD') {
479
- return send(res, 405, md.page('只支持打开页面', view.renderDocPage('只支持打开页面', '', { empty: '这个服务只看记录;唯一能写的是今日页「待你定」卡片的回答。' }), navHtml()));
475
+ return send(res, 405, md.page('只支持打开页面', view.renderDocPage('只支持打开页面', '', { empty: '这个服务只看记录,不改任何东西。' }), navHtml()));
480
476
  }
481
477
  let pathname;
482
478
  try {
@@ -488,18 +484,9 @@ function createRhythm({ root, env, packageRoot }) {
488
484
  if (pathname === '/' || pathname === `/day/${now}`) {
489
485
  const dates = dailyDates();
490
486
  const text = readText(path.join(root, '02-daily', now.slice(0, 7), `${now}.md`));
491
- const cards = asks.cardsForPage(root, pendingCards);
492
- const body = view.renderDaily({ date: now, weekday: WEEKDAY_CN[new Date().getDay()], isToday: true, markdown: text, dates, asks: cards, token: webToken() });
487
+ const body = view.renderDaily({ date: now, weekday: WEEKDAY_CN[new Date().getDay()], isToday: true, markdown: text, dates });
493
488
  return send(res, 200, md.page(`今日 · ${now}`, body, navHtml('/')));
494
489
  }
495
- if (pathname === '/asks.html') {
496
- const cards = asks.cardsForPage(root, pendingCards);
497
- return send(res, 200, view.renderAsksFragment(cards), 'text/html; charset=utf-8');
498
- }
499
- if (pathname === '/asks.json') {
500
- const cards = asks.cardsForPage(root, pendingCards);
501
- return send(res, 200, `${JSON.stringify(cards, null, 1)}\n`, 'application/json; charset=utf-8');
502
- }
503
490
  let m = /^\/day\/(\d{4}-\d{2}-\d{2})$/.exec(pathname);
504
491
  if (m) {
505
492
  const date = m[1];
@@ -561,68 +548,6 @@ function createRhythm({ root, env, packageRoot }) {
561
548
  }
562
549
  }
563
550
 
564
- // ---------------------------------------------------------------- 「决定」页上的待办卡片:能点的
565
- // 网页服务开一个写接口(点选项 = 我的决定),靠两道闸防别的网页乱点:Host 头必须是本机(防 DNS 重绑定,上面),
566
- // 外加一个只在本机页面里的令牌:随机串存在 01-inbox/_rhythm/web-token,页面脚本带着它,接口只认带对的。
567
- // 别的网站的页面读不到 127.0.0.1 上的这个页面(同源策略),拿不到令牌,就用图片、表单点不动
568
- function webToken() {
569
- const file = path.join(STATE_DIR, 'web-token');
570
- try {
571
- const found = readText(file).trim();
572
- if (/^[0-9a-f]{32}$/.test(found)) return found;
573
- } catch {
574
- // 还没有,下面建一个
575
- }
576
- fs.mkdirSync(STATE_DIR, { recursive: true });
577
- const token = createHash('sha256').update(`${Date.now()}:${Math.random()}:${process.pid}`).digest('hex').slice(0, 32);
578
- fs.writeFileSync(file, `${token}\n`, { mode: 0o600 });
579
- return token;
580
- }
581
-
582
- // 今日页「待你定」卡片的回答:记下答案、更新 DECISIONS.md,并作为一条 answer 触发交给路由
583
- async function answerOnPage(req, res) {
584
- if (String(req.headers['x-wrj-token'] || '') !== webToken()) return send(res, 403, JSON.stringify({ error: '令牌不对:这个接口只给本机页面用' }), 'application/json; charset=utf-8');
585
- const body = await new Promise((resolve) => {
586
- let data = '';
587
- req.on('data', (c) => {
588
- data += c;
589
- if (data.length > 64 * 1024) req.destroy();
590
- });
591
- req.on('end', () => resolve(data));
592
- req.on('error', () => resolve(''));
593
- });
594
- let parsed;
595
- try {
596
- parsed = JSON.parse(body || '{}');
597
- } catch {
598
- return send(res, 400, JSON.stringify({ error: '请求体不是 JSON' }), 'application/json; charset=utf-8');
599
- }
600
- const id = String(parsed.id || '').trim();
601
- const item = String(parsed.item || '').trim();
602
- const choice = String(parsed.choice || '').trim();
603
- const note = String(parsed.note || '').trim();
604
- if (!choice || (!id && !item)) return send(res, 400, JSON.stringify({ error: '要写回答和卡片标识' }), 'application/json; charset=utf-8');
605
- let ask;
606
- if (id) {
607
- try {
608
- ask = await asks.answerAsk(root, id, { choice, note, by: 'page' }, { env, packageRoot, decisions });
609
- } catch (e) {
610
- return send(res, 409, JSON.stringify({ error: e.message || String(e) }), 'application/json; charset=utf-8');
611
- }
612
- } else {
613
- const err = [];
614
- const code = await decisions.run(['answer', item, choice], { root, cwd: root, env, packageRoot, stdout: { write() {} }, stderr: { write: (x) => err.push(String(x)) } });
615
- if (code !== 0) return send(res, 409, JSON.stringify({ error: tail(err.join(''), 300) || `decisions answer 退出码 ${code}` }), 'application/json; charset=utf-8');
616
- ask = { id: '', item, question: item, context: '', options: [], record: '03-carryover/DECISIONS.md', from: {}, answer: { choice, note, at: fmtStamp(), by: 'page' } };
617
- }
618
- let dispatched = false;
619
- const eng = engine || makeEngine();
620
- if (eng) {
621
- eng.answer(ask);
622
- dispatched = true;
623
- }
624
- return send(res, 200, JSON.stringify({ ok: true, id: ask.id, item: ask.item, choice, dispatched, message: dispatched ? '已记下,已交给路由继续处理。' : '已记下(路由未开启,仅记录)。' }), 'application/json; charset=utf-8');
625
- }
626
551
 
627
552
  // 只绑 127.0.0.1:页面带着工作记录,不给别的机器看
628
553
  const listen = (port) => new Promise((resolve, reject) => {
@@ -798,7 +723,7 @@ ${sourcesCard(d)}
798
723
  <span class="pill">workers: ${d.config.workers}</span>
799
724
  <span class="pill">refine: ${d.config.refine}</span>
800
725
  <span class="pill">refine-interval: ${d.config.refineInterval}m</span>
801
- <span class="pill">task-timeout: ${d.config.taskTimeout}s</span>
726
+ <span class="pill">task-timeout: ${d.config.taskTimeout ? `${d.config.taskTimeout}s` : '不限'}</span>
802
727
  <span class="pill">agent-mode: ${esc(d.config.agentMode)}</span>
803
728
  <span class="pill">handoff-keep: ${d.config.handoffKeep}d</span>
804
729
  <span class="pill">history-keep: ${d.config.historyKeep}d</span>
@@ -897,7 +822,7 @@ ${sourcesCard(d)}
897
822
  log('服务开始', `pid=${process.pid} 页面=${baseUrl()} agent=${env.YZJ_BOT_AGENT || '(没配)'}`);
898
823
  process.stdout.write(`页面:${baseUrl()} 停:work-rhythm rhythm stop\n`);
899
824
 
900
- // 值守(机器人的收消息一半)也在这里跑:一个后台进程管定时任务、推送、网页和值守。collectors/local.env 的 YZJ_BOT_LISTEN=1 才开;
825
+ // 值守(机器人的收消息一半)也在这里跑:一个后台进程管定时任务、推送、网页和值守。默认开着(collectors/local.env 写 YZJ_BOT_LISTEN=0 才关);
901
826
  // 配置有问题不拦着服务起,只记一笔——定时任务和网页照常
902
827
  let bot = null;
903
828
  let botTask = null;
@@ -954,25 +879,7 @@ ${sourcesCard(d)}
954
879
  }
955
880
  });
956
881
  };
957
- // 隔天过期:今天以前还没答的卡片标成「过期未答」。每天第一次看表时做一遍(服务一启动也会),做成了才记这一天
958
- let expiring = false;
959
- const expireOldCards = async () => {
960
- const day = fmtDate(new Date());
961
- if (state.cardsExpiredOn === day || expiring) return;
962
- expiring = true;
963
- try {
964
- const n = await asks.expireCards(root, { env, packageRoot, decisions, today: day });
965
- state.cardsExpiredOn = day;
966
- saveState(state);
967
- if (n) log('待你定', `${n} 张今天以前的卡片过期未答`);
968
- } catch (error) {
969
- log('卡片过期没做成', error && error.message ? error.message : String(error));
970
- } finally {
971
- expiring = false;
972
- }
973
- };
974
882
  const tick = () => {
975
- expireOldCards();
976
883
  if (eng) eng.tick();
977
884
  const now = new Date();
978
885
  for (const job of list) {
@@ -1047,7 +954,7 @@ ${sourcesCard(d)}
1047
954
 
1048
955
  // 值守要不要跟着服务一起开
1049
956
  function botWanted() {
1050
- return (env.YZJ_BOT_LISTEN || '').trim() === '1';
957
+ return (env.YZJ_BOT_LISTEN || '').trim() !== '0';
1051
958
  }
1052
959
 
1053
960
  function statusText() {
@@ -18,15 +18,13 @@ const PROMPT = `${handoff.MARKER}下面是到达的触发,前面是「手头
18
18
  - 来源=manual(用户从命令行塞进来的一句话):同 message。
19
19
  - 来源=schedule(用户自己定的定时任务):一律 dispatch,不用写任务书(CLI 直接用指令文件)。只有同一件事今天刚做过才 ignore。
20
20
  - 来源=report(执行者做完了):读回执,写 notify 告诉用户结果;失败了说清什么没做成、为什么;想让它重做就 dispatch 并写任务书。
21
- - 来源=events(定时采集之后一批新到的事件,外加这次采集的状态):这是「今天有什么新情况」的例行汇报。默认 dispatch,不用写任务书(CLI 用固定的任务书让执行者更新今日重点、用 work-rhythm ask 登记待办卡片);采集出了故障才在「## handoff」里补一句让执行者顺带说清哪个源没取到;新事件全是无关紧要的(通勤、打卡)可以 ignore。
22
- - 来源=answer(用户在页面上回答了一张待办卡片):看「原执行者」是不是还在「手头的事」里——在就 continue <原执行者短号>;不在就 dispatch,不用写任务书(CLI 会把原问题、我的回答、要记到哪里写成任务书交给执行者)。
23
- - message 里是在回答某张待办卡片(「1 选 2」这种):dispatch,task 写清是哪一条事项、选了第几个选项;执行者会 work-rhythm decisions answer 并照选项做。
21
+ - 时间:今天是 {今天}。用户说的「明早」「今晚」「下周一」「月底」这类相对时间,任务书里一律换算成具体日期(和几点,说清了的话),不要把原词照抄给执行者。
24
22
 
25
23
  二、七种决定(每条触发只能选一种)
26
- - dispatch:派人做。要写一个「## handoff <短号>」小节当任务书。日常事默认在工作目录跑;如果明确要在某个代码库/工程里干活且能从「可用工作区」里挑出,写成「- <短号> dispatch ws=<id>」。如果必须确定工作区但拿不准,不写 ws=,在任务书里让执行者用 work-rhythm ask 问用户(选项带上候选工作区和工作目录),确认后记进 work-rhythm workspace add 和今日事件流。
24
+ - dispatch:派人做。要写一个「## handoff <短号>」小节当任务书。日常事默认在工作目录跑;如果明确要在某个代码库/工程里干活且能从「可用工作区」里挑出,写成「- <短号> dispatch ws=<id>」。如果必须确定工作区但拿不准,写成 reply,问清楚是哪个工作区(把候选的列出来),我再派人。
27
25
  - reply:不用动手、一句话直接答。写「## reply <短号>」。只用于 message / manual。
28
26
  - ignore:不用处理。写「## ignore <短号>」和一句原因。
29
- - notify:给用户的话。写「## notify <短号>」。只用于 report。
27
+ - notify:给用户的话。写「## notify <短号>」。只用于 report。静默的任务(提炼、quiet 的定时任务)不会有汇报。
30
28
  - continue <短号>:这句话是接着「手头的事」里某一件做完的事继续追问,或者顺便再做一件相关事(不打断正在跑的,排在它后面单独回一次)。不用写任务书,CLI 会把原话交给原来那个执行者。
31
29
  - interrupt <短号>:某件事还在跑,用户又补充了条件、想法或改了要求,希望合在一起只回一次。CLI 会停掉它、带着新话重跑并压掉上一轮汇报。正在跑的事收到补充时优先选 interrupt,不要选 continue。
32
30
  - stop <短号>:用户不要某件正在跑的事了。
@@ -44,17 +42,18 @@ const PROMPT = `${handoff.MARKER}下面是到达的触发,前面是「手头
44
42
  任务书正文……
45
43
 
46
44
  ## reply <短号>
47
- 一句话……
45
+ 给人类在 IM 里看的回复:简洁明了,直说结论,不铺垫、不啰嗦……
48
46
 
49
47
  ## notify <短号>
50
- 给用户的话(纯文本,简短直接,不用表格、不放链接,要用户拿主意的事放在最后)……
48
+ 给人类在 IM 里看的话:纯文本、不用表格、不放链接。务必简洁明了、说清结论——先给结论和要做的事,去掉背景铺垫、内部过程和重复解释;一条一件事,以一眼看懂为准,要用户拍板的事简短列在最后……
51
49
 
52
50
  五、硬规则
53
51
  1. 每条触发都要有、且只有一个决定,写在最前面的「决定:」下面。
54
52
  2. 决定行写成「- <短号> <决定>」;小节标题严格是「## <决定> <短号>」。
55
53
  3. 任务书正文里不要出现「## reply / ignore / handoff / notify <短号>」这样的标题。
56
54
  4. continue / interrupt / stop 后面的短号,必须是「手头的事」里列出来的。
57
- 5. 标了「不推送」的汇报不能 notify。`;
55
+ 5. 标了「不推送」的汇报不能 notify。
56
+ 6. reply 和 notify 是直接发给人类看的,必须简洁明了、说得清晰:能三行说清不写十行,不汇报内部机制(如任务书、超时细节、重试次数),除非影响结论。`;
58
57
 
59
58
  const short = (stamp) => String(stamp || '').slice(5, 16);
60
59
  const readText = (file) => {
@@ -71,29 +70,21 @@ function triggerLine(t) {
71
70
  if (t.kind === 'message') return `[${t.id}] 来源=message 时间=${when} 原话:${t.text}`;
72
71
  if (t.kind === 'manual') return `[${t.id}] 来源=manual 时间=${when} 原话:${t.text}`;
73
72
  if (t.kind === 'schedule') return `[${t.id}] 来源=schedule 时间=${when} 任务=${t.task} 指令=${t.taskFile}${t.taskTitle ? `(${t.taskTitle})` : ''}`;
74
- if (t.kind === 'events') {
75
- const health = (t.sources || []).map((x) => `${x.id} ${x.ok ? '成功' : `失败:${x.detail || `退出码 ${x.code}`}`}`).join('、');
76
- const head = `[${t.id}] 来源=events 时间=${when} ${t.ok ? `新事件 ${(t.events || []).length} 条` : `提炼没成:${t.reason}`};这次采集:${health || '(没跑)'}`;
77
- const list = (t.events || []).slice(0, 40).map((e) => ` - ${e.time} ${e.type} ${e.item}(${[e.source, e.project].filter(Boolean).join(',')})`);
78
- return [head, ...list].join('\n');
79
- }
80
- if (t.kind === 'answer') {
81
- const a = t.ask || {};
82
- const ans = a.answer || {};
83
- return `[${t.id}] 来源=answer 时间=${when} 卡片=${a.id || '(老卡片)'}${t.of ? ` 原执行者=${t.of}` : ''} 问题:「${a.question || a.item || ''}」 回答:「${ans.choice || ''}」${ans.note ? ` 附言:「${ans.note}」` : ''}${a.record ? ` 记到:${a.record}` : ''}`;
84
- }
85
73
  const head = `[${t.id}] 来源=report 时间=${when} 对应=${t.of} 结果=${t.ok ? '成功' : '失败'}${t.ok ? ` 用时=${t.seconds}s` : ` 原因=${t.reason}`} 回执=${handoff.relResult(t.of)}${t.quiet ? '(不推送)' : ''}`;
86
74
  return t.ok ? `${head}\n 开头:${t.opening}` : head;
87
75
  }
88
76
 
89
77
  // 一轮的提示词:固定的说明 + 可用工作区(有的话)+ 手头的事 + 这一批触发。extra 是重试时的一句提醒
90
- function turnPrompt(triggers, open, extra = '', workspaces = null) {
91
- const lines = [PROMPT];
78
+ function turnPrompt(triggers, open, extra = '', workspaces = null, now = new Date()) {
79
+ const WEEK = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
80
+ const p2 = (n) => String(n).padStart(2, '0');
81
+ const todayText = `${now.getFullYear()}-${p2(now.getMonth() + 1)}-${p2(now.getDate())} ${WEEK[now.getDay()]},现在 ${p2(now.getHours())}:${p2(now.getMinutes())}`;
82
+ const lines = [PROMPT.split('{今天}').join(todayText)];
92
83
  if (extra) lines.push('', extra);
93
84
  const reg = (workspaces && workspaces.registered) || [];
94
85
  const scan = (workspaces && workspaces.scanned) || [];
95
86
  if (reg.length || scan.length) {
96
- lines.push('', '可用工作区(日常事默认在工作目录跑,不写 ws=;明确要进代码库/工程时在 dispatch 行加 ws=<id>;不确定选哪个时在任务书里让执行者用 work-rhythm ask 问用户并记录到工作目录):');
87
+ lines.push('', '可用工作区(日常事默认在工作目录跑,不写 ws=;明确要进代码库/工程时在 dispatch 行加 ws=<id>;拿不准是哪个就 reply 问我,把候选列出来):');
97
88
  for (const w of reg) lines.push(`- ${w.id}(已登记,${w.path})${w.note ? `:${w.note}` : ''}`);
98
89
  for (const w of scan) lines.push(`- ${w.id}(候选,${w.path})`);
99
90
  }
@@ -174,7 +165,7 @@ function createRouter({ root, env, role, timeoutS = 120, preamble = '', log = ()
174
165
  let extra = '';
175
166
  let lastReply = '';
176
167
  for (let attempt = 0; attempt < 2; attempt += 1) {
177
- const r = await turn(turnPrompt(triggers, open, extra, workspaces));
168
+ const r = await turn(turnPrompt(triggers, open, extra, workspaces, new Date()));
178
169
  if (r.failed) {
179
170
  last = { at: fmtStamp(), seconds: Math.round((Date.now() - started) / 1000), ok: false };
180
171
  return { ok: false, failed: r.failed, config: r.config, decisions: {}, missing: ids };