work-rhythm 0.2.20 → 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.
@@ -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);
@@ -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) => {
@@ -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) {
@@ -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 <短号>:用户不要某件正在跑的事了。
@@ -72,29 +70,21 @@ function triggerLine(t) {
72
70
  if (t.kind === 'message') return `[${t.id}] 来源=message 时间=${when} 原话:${t.text}`;
73
71
  if (t.kind === 'manual') return `[${t.id}] 来源=manual 时间=${when} 原话:${t.text}`;
74
72
  if (t.kind === 'schedule') return `[${t.id}] 来源=schedule 时间=${when} 任务=${t.task} 指令=${t.taskFile}${t.taskTitle ? `(${t.taskTitle})` : ''}`;
75
- if (t.kind === 'events') {
76
- const health = (t.sources || []).map((x) => `${x.id} ${x.ok ? '成功' : `失败:${x.detail || `退出码 ${x.code}`}`}`).join('、');
77
- const head = `[${t.id}] 来源=events 时间=${when} ${t.ok ? `新事件 ${(t.events || []).length} 条` : `提炼没成:${t.reason}`};这次采集:${health || '(没跑)'}`;
78
- const list = (t.events || []).slice(0, 40).map((e) => ` - ${e.time} ${e.type} ${e.item}(${[e.source, e.project, e.ref].filter(Boolean).join(',')})`);
79
- return [head, ...list].join('\n');
80
- }
81
- if (t.kind === 'answer') {
82
- const a = t.ask || {};
83
- const ans = a.answer || {};
84
- 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}` : ''}`;
85
- }
86
73
  const head = `[${t.id}] 来源=report 时间=${when} 对应=${t.of} 结果=${t.ok ? '成功' : '失败'}${t.ok ? ` 用时=${t.seconds}s` : ` 原因=${t.reason}`} 回执=${handoff.relResult(t.of)}${t.quiet ? '(不推送)' : ''}`;
87
74
  return t.ok ? `${head}\n 开头:${t.opening}` : head;
88
75
  }
89
76
 
90
77
  // 一轮的提示词:固定的说明 + 可用工作区(有的话)+ 手头的事 + 这一批触发。extra 是重试时的一句提醒
91
- function turnPrompt(triggers, open, extra = '', workspaces = null) {
92
- 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)];
93
83
  if (extra) lines.push('', extra);
94
84
  const reg = (workspaces && workspaces.registered) || [];
95
85
  const scan = (workspaces && workspaces.scanned) || [];
96
86
  if (reg.length || scan.length) {
97
- lines.push('', '可用工作区(日常事默认在工作目录跑,不写 ws=;明确要进代码库/工程时在 dispatch 行加 ws=<id>;不确定选哪个时在任务书里让执行者用 work-rhythm ask 问用户并记录到工作目录):');
87
+ lines.push('', '可用工作区(日常事默认在工作目录跑,不写 ws=;明确要进代码库/工程时在 dispatch 行加 ws=<id>;拿不准是哪个就 reply 问我,把候选列出来):');
98
88
  for (const w of reg) lines.push(`- ${w.id}(已登记,${w.path})${w.note ? `:${w.note}` : ''}`);
99
89
  for (const w of scan) lines.push(`- ${w.id}(候选,${w.path})`);
100
90
  }
@@ -175,7 +165,7 @@ function createRouter({ root, env, role, timeoutS = 120, preamble = '', log = ()
175
165
  let extra = '';
176
166
  let lastReply = '';
177
167
  for (let attempt = 0; attempt < 2; attempt += 1) {
178
- const r = await turn(turnPrompt(triggers, open, extra, workspaces));
168
+ const r = await turn(turnPrompt(triggers, open, extra, workspaces, new Date()));
179
169
  if (r.failed) {
180
170
  last = { at: fmtStamp(), seconds: Math.round((Date.now() - started) / 1000), ok: false };
181
171
  return { ok: false, failed: r.failed, config: r.config, decisions: {}, missing: ids };
@@ -141,44 +141,8 @@ function renderFocusItem(text, idx) {
141
141
  return `<li class="focus-item"><span class="focus-num">${num}</span><div class="focus-body"><div class="focus-main">${md.inline(main, MD_OPTS)}</div>${subHtml}</div></li>`;
142
142
  }
143
143
 
144
- // 渲染「待你定」卡片列表片段(/asks.html 也直接返回这段,供今日页实时轮询)
145
- function renderAsksFragment(cards) {
146
- const list = Array.isArray(cards) ? cards : [];
147
- const sig = list.map((c) => `${c.id || c.item}:${c.at || c.date || ''}`).join('|');
148
- if (!list.length) {
149
- return `<div class="ask-list" data-ask-count="0" data-ask-sig=""><p class="muted">现在没有待你定的事。执行者用 <code>work-rhythm ask</code> 丢出问题后,这里会实时出现。</p></div>`;
150
- }
151
- const items = list.map((c, i) => {
152
- const opts = Array.isArray(c.options) ? c.options : [];
153
- const optsHtml = opts.length
154
- ? `<div class="ask-opts">${opts.map((o) => `<button type="button" class="ask-opt${o.suggested ? ' is-suggested' : ''}" data-choice="${esc(o.label)}"><span>${esc(o.label)}</span>${o.suggested ? '<span class="pill is-amber">建议</span>' : ''}${o.detail ? `<span class="ask-opt-detail">${esc(o.detail)}</span>` : ''}</button>`).join('')}</div>`
155
- : '';
156
- const notePlaceholder = opts.length ? '附言或自己写回答(可选,点按钮时会一起带上)' : '写下你的回答…';
157
- const formHtml = `<form class="ask-form"><input type="text" class="todo-input" name="note" placeholder="${esc(notePlaceholder)}" autocomplete="off"><button type="submit" class="ask-opt">提交</button></form>`;
158
- const meta = [c.at ? c.at.slice(5, 16) : (c.date || ''), c.from && c.from.trigger ? `来自 ${c.from.trigger}` : '', c.record ? `记到 ${c.record}` : ''].filter(Boolean).join(' · ');
159
- return `<article class="ask-card" data-ask-id="${esc(c.id || '')}" data-ask-item="${esc(c.item || c.question || '')}">
160
- <div class="ask-head"><div class="ask-q">${esc(c.question || c.item || '')}</div><span class="pill is-amber">#${i + 1}</span></div>
161
- ${c.context ? `<div class="ask-ctx">${md.inline(c.context, MD_OPTS)}</div>` : ''}
162
- ${meta ? `<div class="ask-meta">${esc(meta)}</div>` : ''}
163
- ${optsHtml}
164
- ${formHtml}
165
- <div class="ask-after" hidden></div>
166
- </article>`;
167
- }).join('\n');
168
- return `<div class="ask-list" data-ask-count="${list.length}" data-ask-sig="${esc(sig)}">${items}</div>`;
169
- }
170
-
171
- // 渲染「待你定」独立卡片(实时更新)
172
- function renderPendingCard(cards, { token = '', live = false } = {}) {
173
- const list = Array.isArray(cards) ? cards : [];
174
- const count = list.length;
175
- const body = `<div id="pending-decisions-body">${renderAsksFragment(list)}</div>`;
176
- const html = `<section class="card" id="pending-decisions" data-ask-token="${esc(token)}"${live ? ' data-ask-live="1"' : ''}><div class="card-head"><h2>待你定</h2><span class="pill${count ? ' is-amber' : ''}" id="pending-pill">${count} 件</span></div>${body}</section>`;
177
- return { count, html };
178
- }
179
-
180
144
  // 渲染「计划」小节(把待你定拆出给专属数字卡片后,在底部留一条快捷跳转)
181
- function renderPlanBlocks(title, blocks, pendingCount) {
145
+ function renderPlanBlocks(title, blocks) {
182
146
  if (!blocks.length) return emptyCard(title);
183
147
  const parts = [];
184
148
  for (const b of blocks) {
@@ -209,9 +173,6 @@ function renderPlanBlocks(title, blocks, pendingCount) {
209
173
  const childHtml = b.childText ? md.render(b.childText, MD_OPTS) : '';
210
174
  parts.push(`<div class="kv-row"><div class="kv-k">${dotClass ? `<span class="dot ${dotClass}"></span>` : ''}${esc(b.label)}</div><div class="kv-v">${headHtml}${childHtml}</div></div>`);
211
175
  }
212
- if (pendingCount > 0) {
213
- parts.push(`<button type="button" class="pending-hint-link" data-jump="pending"><span>还有 ${pendingCount} 件「待你定」需要拍板</span><span>查看明细 →</span></button>`);
214
- }
215
176
  return `<section class="card"><div class="card-head"><h2>${esc(title)}</h2></div><div class="section-stack">${parts.join('\n')}</div></section>`;
216
177
  }
217
178
 
@@ -369,95 +330,9 @@ function summarizeReview(blocks) {
369
330
  return blocks.length ? '晚间复盘' : '暂未复盘';
370
331
  }
371
332
 
372
- // 每日页客户端交互,两段各自独立:「待你定」的卡片(回答、实时刷新)和数字卡片(点一张切换明细、展开全部、按类型筛选、hash 记忆)。
333
+ // 每日页客户端交互:数字卡片(点一张切换明细、展开全部、按类型筛选、hash 记忆)。
373
334
  // 顺序不能反:今天还没有每日文件时没有数字卡片,那一段会直接返回,卡片那一段必须在它前面
374
335
  const DAY_SCRIPT = `<script>
375
- /* 「待你定」的卡片:点选项、提交回答、实时刷新。它不依赖下面的数字卡片——今天还没有每日文件时页面上没有数字卡片,卡片也要能答 */
376
- (function(){
377
- var askBox=document.getElementById('pending-decisions');
378
- if(askBox){
379
- var askToken=askBox.getAttribute('data-ask-token')||'';
380
- var askBody=document.getElementById('pending-decisions-body');
381
- var askPill=document.getElementById('pending-pill');
382
- var pendingKpi=document.querySelector('.kpi-card[data-key="pending"]');
383
- function syncCount(n){
384
- if(askPill){askPill.textContent=n+' 件';askPill.classList.toggle('is-amber',n>0);}
385
- if(pendingKpi){
386
- var num=pendingKpi.querySelector('.kpi-num');
387
- if(num)num.innerHTML=String(n)+'<span class="kpi-unit">件</span>';
388
- var sub=pendingKpi.querySelector('.kpi-sub');
389
- if(sub)sub.textContent=n>0?'需要你拍板 · 实时更新':'暂无待定 · 实时更新';
390
- pendingKpi.classList.toggle('is-empty-kpi',n===0);
391
- pendingKpi.classList.toggle('is-amber',n>0);
392
- }
393
- }
394
- function submitAsk(card,choice,note){
395
- if(!choice)return;
396
- var id=card.getAttribute('data-ask-id')||'';
397
- var item=card.getAttribute('data-ask-item')||'';
398
- var after=card.querySelector('.ask-after');
399
- var btns=[].slice.call(card.querySelectorAll('button,input'));
400
- btns.forEach(function(b){b.disabled=true;});
401
- fetch('/api/asks/answer',{
402
- method:'POST',
403
- headers:{'Content-Type':'application/json','X-Wrj-Token':askToken},
404
- body:JSON.stringify({id:id,item:item,choice:choice,note:note||''})
405
- }).then(function(r){return r.json().then(function(d){return {ok:r.ok,d:d};});}).then(function(res){
406
- if(!res.ok){
407
- btns.forEach(function(b){b.disabled=false;});
408
- if(after){after.hidden=false;after.className='ask-after is-err';after.textContent=(res.d&&res.d.error)||'提交失败';}
409
- return;
410
- }
411
- card.classList.add('is-done');
412
- if(after){after.hidden=false;after.className='ask-after';after.textContent=res.d.message||'已记下,已交给路由处理。';}
413
- setTimeout(pollAsks,1200);
414
- }).catch(function(e){
415
- btns.forEach(function(b){b.disabled=false;});
416
- if(after){after.hidden=false;after.className='ask-after is-err';after.textContent='网络错误:'+(e&&e.message||e);}
417
- });
418
- }
419
- askBox.addEventListener('click',function(ev){
420
- var btn=ev.target.closest('button.ask-opt[data-choice]');
421
- if(!btn)return;
422
- var card=btn.closest('.ask-card');
423
- if(!card||card.classList.contains('is-done'))return;
424
- btn.classList.add('is-picked');
425
- var inp=card.querySelector('input[name="note"]');
426
- submitAsk(card,btn.getAttribute('data-choice'),inp?inp.value.trim():'');
427
- });
428
- askBox.addEventListener('submit',function(ev){
429
- var form=ev.target.closest('form.ask-form');
430
- if(!form)return;
431
- ev.preventDefault();
432
- var card=form.closest('.ask-card');
433
- if(!card||card.classList.contains('is-done'))return;
434
- var inp=form.querySelector('input[name="note"]');
435
- var val=inp?inp.value.trim():'';
436
- if(!val)return;
437
- submitAsk(card,val,'');
438
- });
439
- function pollAsks(){
440
- if(askBox.getAttribute('data-ask-live')!=='1')return;
441
- if(document.visibilityState==='hidden')return;
442
- var active=document.activeElement;
443
- if(active&&askBox.contains(active)&&active.tagName==='INPUT'&&active.value.trim())return;
444
- fetch('/asks.html',{cache:'no-store'}).then(function(r){return r.ok?r.text():'';}).then(function(html){
445
- if(!html||!askBody)return;
446
- var tmp=document.createElement('div');tmp.innerHTML=html;
447
- var next=tmp.firstElementChild;
448
- var cur=askBody.firstElementChild;
449
- if(!next)return;
450
- var n=Number(next.getAttribute('data-ask-count')||'0');
451
- if(!cur||cur.getAttribute('data-ask-sig')!==next.getAttribute('data-ask-sig')){
452
- askBody.innerHTML=html;
453
- }
454
- syncCount(n);
455
- }).catch(function(){});
456
- }
457
- if(askBox.getAttribute('data-ask-live')==='1')setInterval(pollAsks,5000);
458
- }
459
- })();
460
- /* 数字卡片:点一张切换明细、展开全部、事件流按类型筛选、hash 记忆。没有每日文件时页面上没有它们,这一段什么都不做 */
461
336
  (function(){
462
337
  var cards=[].slice.call(document.querySelectorAll('.kpi-card[data-key]'));
463
338
  var panels=[].slice.call(document.querySelectorAll('.day-panel[data-panel]'));
@@ -508,7 +383,6 @@ if(toggle)toggle.addEventListener('click',function(){
508
383
  });
509
384
  var hash=(location.hash||'').replace(/^#/,'');
510
385
  if(hash==='all')showAll(false);
511
- else if(hash==='pending-decisions'&&cards.some(function(c){return c.getAttribute('data-key')==='pending';}))select('pending',false);
512
386
  else if(hash&&cards.some(function(c){return c.getAttribute('data-key')===hash;}))select(hash,false);
513
387
  })();
514
388
  </script>`;
@@ -524,7 +398,7 @@ function renderKpiCard(item, selected) {
524
398
  </button>`;
525
399
  }
526
400
 
527
- function renderDaily({ date, weekday, isToday, markdown, dates = [], asks = null, token = '' }) {
401
+ function renderDaily({ date, weekday, isToday, markdown, dates = [] }) {
528
402
  const [year, month, day] = String(date || '').split('-');
529
403
  const humanDate = month && day ? `${Number(month)} 月 ${Number(day)} 日` : date;
530
404
  // dates 按新到旧排序:prev 是更早的一天(下标 +1),next 是更新的一天(下标 -1)
@@ -537,36 +411,18 @@ function renderDaily({ date, weekday, isToday, markdown, dates = [], asks = null
537
411
  ? `<div class="day-strip" aria-label="最近的日子">${stripDates.map((d) => `<a class="day-chip${d === date ? ' is-current' : ''}" href="/day/${d}">${d.slice(5)}</a>`).join('')}</div>`
538
412
  : '<div class="day-strip"><span class="muted">还没有其他日期的文件</span></div>';
539
413
 
540
- const hasLiveAsks = Array.isArray(asks);
541
414
  if (!markdown) {
542
415
  const hero = `<header class="day-hero"><div class="day-hero-top"><div><div class="day-eyebrow"><span>${esc(year || '')}${year ? ' 年' : ''}</span>${isToday ? '<span class="pill is-accent">今天</span>' : ''}</div><div class="day-title"><h1>${esc(humanDate)}</h1><span class="day-weekday">${esc(weekday || '')}</span></div></div>${navArrows(false)}</div>${strip}</header>`;
543
416
  const empty = '<section class="card"><p class="muted">今天还没有每日文件。等定时任务跑完,或对 AI 说「做今天的计划」后,这里就会更新。</p></section>';
544
- const liveCard = hasLiveAsks ? `\n${renderPendingCard(asks, { token, live: Boolean(isToday) }).html}\n${DAY_SCRIPT}` : '';
545
- return `${hero}\n${empty}${liveCard}`;
417
+ return `${hero}\n${empty}\n${DAY_SCRIPT}`;
546
418
  }
547
419
 
548
420
  const doc = splitSections(markdown);
549
421
  const byTitle = new Map(doc.sections.map((s) => [s.title, s]));
550
422
  const items = [];
551
423
 
552
- // 1. 计划 & 待你定(今日页的「待你定」是实时卡片,不再读每日文件里的旧文字列表)
424
+ // 1. 计划(「待你定」这一块 2026-12-03 取消:需要我留意的事写在计划的「留意」里)
553
425
  const planSec = byTitle.get('计划');
554
- let pendingItem = null;
555
- const pendingCount = hasLiveAsks ? asks.length : 0;
556
- if (hasLiveAsks) {
557
- const p = renderPendingCard(asks, { token, live: Boolean(isToday) });
558
- pendingItem = {
559
- key: 'pending',
560
- label: '待你定',
561
- num: p.count,
562
- unit: '件',
563
- sub: p.count ? '需要你拍板 · 实时更新' : '暂无待定 · 实时更新',
564
- dot: 'is-amber',
565
- tone: p.count ? 'is-amber' : '',
566
- empty: p.count === 0,
567
- html: p.html,
568
- };
569
- }
570
426
  if (planSec) {
571
427
  const allBlocks = planSec.body ? parseLabeledBlocks(planSec.body) : [];
572
428
  const restBlocks = allBlocks.filter((b) => !(b.kind === 'kv' && b.label === '待你定'));
@@ -586,10 +442,9 @@ function renderDaily({ date, weekday, isToday, markdown, dates = [], asks = null
586
442
  dot: 'is-accent',
587
443
  tone: '',
588
444
  empty: !restBlocks.length,
589
- html: renderPlanBlocks(planSec.title, restBlocks, pendingCount),
445
+ html: renderPlanBlocks(planSec.title, restBlocks),
590
446
  });
591
447
  }
592
- if (pendingItem) items.push(pendingItem);
593
448
 
594
449
  // 2. 进展 & 复盘(进展为空且复盘有内容时,把进展空态收进复盘明细底部,保持顶部数字卡紧凑)
595
450
  const progSec = byTitle.get('进展');
@@ -734,4 +589,4 @@ function renderReports(files) {
734
589
  return `${head}\n<section class="card"><div class="report-list">${list}</div></section>`;
735
590
  }
736
591
 
737
- module.exports = { rewriteWorkspaceHref, renderDaily, renderAsksFragment, pageHead, renderDocPage, renderGoals, renderReports, MD_OPTS };
592
+ module.exports = { rewriteWorkspaceHref, renderDaily, pageHead, renderDocPage, renderGoals, renderReports, MD_OPTS };
@@ -193,7 +193,7 @@ test('check:只绑了 agent 跑定时任务、没装值守,不报值守的
193
193
  s.localEnv('# YZJ_BOT_AGENT="dsh"\n');
194
194
  const r2 = s.check({ ...s.stubs });
195
195
  assert.equal(r2.code, 1, r2.out);
196
- assert.match(r2.stdout, /schedule 里有任务(daily-plan、noon-checkin、evening-review、carryover、daily-persona、weekly-rhythm)却没绑 agent,到点一个也跑不了:work-rhythm agent bind <zcode\|dsh\|qoder\|claude\|kimi>/);
196
+ assert.match(r2.stdout, /schedule 里有任务(daily-plan、evening-review、daily-persona)却没绑 agent,到点一个也跑不了:work-rhythm agent bind <zcode\|dsh\|qoder\|claude\|kimi>/);
197
197
  });
198
198
 
199
199
  test('check:值守装了之后,配的命令找不到时报出来', (t) => {
@@ -37,7 +37,8 @@ describe('rhythm due', () => {
37
37
  s = setup(clean);
38
38
  s.set('daily-plan', '"08:50"');
39
39
  s.set('weekly-rhythm', '"Fri 16:30"');
40
- s.set('carryover', '""');
40
+ s.set('noon-checkin', '"12:30"');
41
+ s.set('weekly-rhythm', '"Fri 16:30"');
41
42
  s.set('sync', '"工作日 09:00-18:00 每 60 分钟"');
42
43
  });
43
44
  after(() => clean.run());
@@ -130,6 +131,7 @@ test('rhythm run:agent 失败时退出码为 5;没有这个任务也是 5',
130
131
  test('rhythm doctor:配置齐了时退出码为 0;时间写了却缺指令文件的任务报出来', (t) => {
131
132
  const s = setup(t);
132
133
  assert.equal(s.rhythm(['doctor']).code, 0, s.rhythm(['doctor']).out);
134
+ s.set('weekly-rhythm', '"Fri 16:30"');
133
135
  fs.renameSync(`${s.box.work}/tasks/weekly-rhythm.md`, `${s.box.root}/weekly-rhythm.md`);
134
136
  const r = s.rhythm(['doctor']);
135
137
  assert.equal(r.code, 1);
@@ -147,6 +149,7 @@ test('rhythm start:配置有问题时不起,退出码为 3,缺指令文件
147
149
  const s = setup(t);
148
150
  const port = await freePort();
149
151
  s.set('port', String(port));
152
+ s.set('weekly-rhythm', '"Fri 16:30"');
150
153
  fs.renameSync(`${s.box.work}/tasks/weekly-rhythm.md`, `${s.box.root}/weekly-rhythm.md`);
151
154
  s.set('notify', '""');
152
155
  const r = s.rhythm(['start'], { ...s.env, YZJ_BOT_AGENT: '' });
@@ -249,9 +252,8 @@ describe('rhythm start:服务在跑的时候', () => {
249
252
  assert.match(html, /<a href="\/rhythm">规律<\/a>/);
250
253
  assert.ok(html.includes(`/day/${TODAY()}`), '今天的日期应出现在最近日期条里');
251
254
  assert.ok(html.includes('/day/2026-11-30'), '历史月份目录里的每日文件也应列在最近日期条里');
252
- assert.ok(html.includes('data-key="pending"'), '今日页有实时的「待你定」卡片');
253
- assert.ok(html.includes('id="pending-decisions"'));
254
- assert.ok(html.includes('data-ask-live="1"'));
255
+ assert.ok(!html.includes('data-key="pending"') && !html.includes('id="pending-decisions"') && !html.includes('data-ask-live'), '今日页不再有「待你定」卡片(2026-12-03 取消)');
256
+ assert.equal((await fetch(`${base}/asks.html`)).status, 404, '卡片的接口也撤了');
255
257
  const past = await (await fetch(`${base}/day/2026-11-30`)).text();
256
258
  assert.ok(past.includes('class="kpi-grid"'));
257
259
  assert.ok(past.includes('data-key="plan"'));
@@ -293,60 +295,6 @@ describe('rhythm start:服务在跑的时候', () => {
293
295
  for (const name of ['服务', '路由', '执行者']) assert.match(monitor, new RegExp(`<section class="card">\\s*<div class="card-head"><h2>${name}</h2></div>`), `监控页的「${name}」应是普通卡片`);
294
296
  });
295
297
 
296
- // 把页面脚本放进一个最小的假 DOM 里跑:不依赖浏览器,就能看出「处理有没有绑上、点了以后发了什么」
297
- test('今日页「待你定」的卡片:今天还没有每日文件、页面上没有数字卡片时,点选项和提交回答照样能用(脚本在那种页面上也要绑上)', () => {
298
- const view = require('../lib/view');
299
- const vm = require('node:vm');
300
- const TOKEN = 'a'.repeat(32);
301
- const asks = [{ id: '', item: '周会定在哪天', question: '周会定在哪天', context: '', options: [{ label: '周二' }, { label: '周四' }], from: {}, answer: null }];
302
- const el = (attrs = {}) => ({
303
- attrs, listeners: {}, textContent: '', innerHTML: '', hidden: true, disabled: false, value: '', className: '',
304
- classList: { add() {}, remove() {}, toggle() {}, contains: () => false },
305
- getAttribute: (n) => (n in attrs ? attrs[n] : null),
306
- addEventListener(type, fn) { this.listeners[type] = fn; },
307
- querySelector: () => null, querySelectorAll: () => [], contains: () => false,
308
- });
309
- const run = (markdown) => {
310
- const html = view.renderDaily({ date: TODAY(), weekday: '三', isToday: true, markdown, dates: [], asks, token: TOKEN });
311
- const js = /<script>([\s\S]*?)<\/script>/.exec(html)[1];
312
- const calls = { fetch: [] };
313
- const askBox = el({ 'data-ask-token': TOKEN, 'data-ask-live': '1' });
314
- const byId = { 'pending-decisions': askBox, 'pending-decisions-body': el(), 'pending-pill': el() };
315
- const document = {
316
- querySelectorAll: (sel) => (markdown && sel === '.kpi-card[data-key]' ? [el({ 'data-key': 'plan' })] : []),
317
- querySelector: (sel) => (markdown && sel === '.day-panels' ? el() : null),
318
- getElementById: (id) => byId[id] || null,
319
- activeElement: null,
320
- visibilityState: 'visible',
321
- };
322
- const ctx = {
323
- document, location: { hash: '' }, history: {}, setInterval: () => 0, setTimeout: () => 0,
324
- fetch: (url, opts) => {
325
- calls.fetch.push({ url, token: opts.headers['X-Wrj-Token'], body: JSON.parse(opts.body) });
326
- return Promise.resolve({ ok: true, json: () => Promise.resolve({ message: '已记下' }) });
327
- },
328
- };
329
- vm.runInNewContext(js, vm.createContext(ctx));
330
- return { askBox, calls };
331
- };
332
- for (const [label, markdown] of [['还没有每日文件', ''], ['有每日文件', '# 今天\n\n## 计划\n\n- **今日重点**:\n 1. 做一件事\n\n## 进展\n\n## 复盘\n\n## 事件流\n\n## 备注\n\n']]) {
333
- const { askBox, calls } = run(markdown);
334
- assert.equal(typeof askBox.listeners.click, 'function', `${label}:点选项的处理没绑上`);
335
- assert.equal(typeof askBox.listeners.submit, 'function', `${label}:提交回答的处理没绑上`);
336
- const input = { value: ' 先对齐口径 ', disabled: false };
337
- const card = { ...el({ 'data-ask-id': '', 'data-ask-item': '周会定在哪天' }), querySelector: (s) => (s === 'input[name="note"]' ? input : null), querySelectorAll: () => [input] };
338
- const btn = { ...el({ 'data-choice': '周二' }), closest: () => card };
339
- askBox.listeners.click({ target: { closest: (s) => (s === 'button.ask-opt[data-choice]' ? btn : null) } });
340
- assert.deepEqual(calls.fetch, [{ url: '/api/asks/answer', token: TOKEN, body: { id: '', item: '周会定在哪天', choice: '周二', note: '先对齐口径' } }], `${label}:点选项应发出回答`);
341
- calls.fetch.length = 0;
342
- const form = { closest: () => card, querySelector: (s) => (s === 'input[name="note"]' ? { value: ' 周五再说 ' } : null) };
343
- let prevented = false;
344
- askBox.listeners.submit({ target: { closest: (s) => (s === 'form.ask-form' ? form : null) }, preventDefault: () => { prevented = true; } });
345
- assert.equal(prevented, true, `${label}:提交不能走表单的默认行为(那会整页刷新)`);
346
- assert.deepEqual(calls.fetch.map((c) => c.body), [{ id: '', item: '周会定在哪天', choice: '周五再说', note: '' }], `${label}:提交回答应发出回答`);
347
- }
348
- });
349
-
350
298
  test('stop 之后 status 说没在跑', async () => {
351
299
  const r = s.rhythm(['stop']);
352
300
  assert.match(r.stdout, /已让它停下(pid \d+)/);