create-pmos 0.442.0 → 0.444.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/package.json +25 -25
  2. package/payload/KIT-VERSION +1 -1
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/state/discoveries.md +1 -1
  6. package/workspace/briefing-premium-board-test.js +8 -2
  7. package/workspace/briefing-premium-insights-test.js +40 -38
  8. package/workspace/briefing-premium-test.js +2 -1
  9. package/workspace/changelog.json +24 -0
  10. package/workspace/goals-clear-ui-test.js +263 -0
  11. package/workspace/guide/home.md +12 -2
  12. package/workspace/guide/metric-drafts.md +8 -2
  13. package/workspace/home-railcard-test.js +193 -0
  14. package/workspace/intel-report-ui-test.js +1 -1
  15. package/workspace/intelligence-gaps-ui-test.js +16 -14
  16. package/workspace/lib/board-premium.js +1 -1
  17. package/workspace/lib/engine/boards.js +9 -2
  18. package/workspace/lib/engine/records/index.js +9 -2
  19. package/workspace/lib/initiative-layout.js +3 -1
  20. package/workspace/lib/insights-premium.js +22 -1
  21. package/workspace/lib/metric-drafts.js +37 -10
  22. package/workspace/lib/metric-read-runs.js +20 -13
  23. package/workspace/lib/metric-reads.js +208 -23
  24. package/workspace/lib/metrics-cli.js +62 -5
  25. package/workspace/lib/routes-boards.js +40 -1
  26. package/workspace/lib/routes-goal-status.js +89 -6
  27. package/workspace/lib/routes-insights-premium.js +1 -1
  28. package/workspace/lib/routes-metric-drafts.js +26 -3
  29. package/workspace/live-pill-round-test.js +178 -0
  30. package/workspace/metric-drafts-ui-test.js +5 -2
  31. package/workspace/okr-goals-ui-test.js +27 -23
  32. package/workspace/package-lock.json +2 -2
  33. package/workspace/package.json +1 -1
  34. package/workspace/panels-test.js +231 -0
  35. package/workspace/premium-board-actions-test.js +2 -2
  36. package/workspace/premium-rec-tab-test.js +2 -1
  37. package/workspace/premium-vw-item-test.js +10 -2
  38. package/workspace/premium-vw-jira-test.js +3 -0
  39. package/workspace/public/pm/bd-ini-panel.js +3 -2
  40. package/workspace/public/pm/cozy-adler.js +21 -0
  41. package/workspace/public/pm/cozy-divider.css +32 -0
  42. package/workspace/public/pm/cozy-divider.js +45 -0
  43. package/workspace/public/pm/cozy-insights.css +96 -0
  44. package/workspace/public/pm/cozy-live-pill.css +16 -17
  45. package/workspace/public/pm/cozy-live-pill.js +28 -17
  46. package/workspace/public/pm/cozy-panels.css +59 -0
  47. package/workspace/public/pm/cozy-panels.js +524 -0
  48. package/workspace/public/pm/cozy-today.css +15 -0
  49. package/workspace/public/pm/cozy-viewer.js +173 -69
  50. package/workspace/public/pm/cozy-vw-shell.css +4 -0
  51. package/workspace/public/pm/goals-clear.js +265 -0
  52. package/workspace/public/pm/home-app.js +73 -14
  53. package/workspace/public/pm/home-ini.js +9 -3
  54. package/workspace/public/pm/home-today.js +55 -12
  55. package/workspace/public/pm/ini-edit.js +401 -0
  56. package/workspace/public/pm/ini-groups.js +14 -8
  57. package/workspace/public/pm/ini-tasks.js +84 -26
  58. package/workspace/public/pm/ini-versions.js +18 -4
  59. package/workspace/public/pm/ini-view-model.js +45 -18
  60. package/workspace/public/pm/ini-view.css +117 -5
  61. package/workspace/public/pm/ini-view.js +51 -17
  62. package/workspace/public/pm/metric-drafts.js +4 -1
  63. package/workspace/public/pm/mission.js +11 -7
  64. package/workspace/public/pm/premium-board.js +8 -6
  65. package/workspace/public/pm/premium-insights.js +375 -59
  66. package/workspace/public/pm/task-card.css +2 -0
  67. package/workspace/public/pm/task-card.js +4 -1
  68. package/workspace/server.js +6 -2
  69. package/workspace/skills/metric-read.skill +7 -5
  70. package/workspace/stage-card-tasks-test.js +396 -0
  71. package/workspace/stage-card-test.js +12 -4
  72. package/workspace/task-delete-test.js +9 -1
  73. package/workspace/task-milestones-test.js +3 -3
  74. package/workspace/task-press-test.js +12 -4
  75. package/workspace/task-views-test.js +198 -5
  76. package/workspace/test-lists/batch18-live-pill-round.json +10 -0
  77. package/workspace/test-lists/batch18-panels.json +9 -0
  78. package/workspace/test-lists/goals-clear.json +15 -0
  79. package/workspace/test-lists/home-railcard.json +9 -0
  80. package/workspace/test-lists/stage-card-tasks.json +6 -0
  81. package/workspace/tk-tasks-test.js +2 -2
@@ -114,22 +114,24 @@ const WEEKLY = { view: 'view', weeks: 3, day: 'Mon', opens: 4 };
114
114
  ok('O in plain words, with the weeks it rests on, and the proposal\'s own presses', wk.t === 'You open this view every week. Shall I make it a report that drafts itself before Monday?' && /each of the last 3 weeks, most on Mondays/.test(wk.why) && wk.acts.join() === 'See the draft,Not now,Set it up', JSON.stringify(wk));
115
115
  await shot(p, 'gap3-strip-weekly', '#insHero');
116
116
 
117
- /* ── E: a drafted metric edited in place ── */
118
- // a drafted North Star is the North Star card's hollow row now (batch 16 item 6), its ✎ beside its ✓
119
- await until(() => p.evaluate(() => !!document.querySelector('#nsRow [data-okd="edit"][data-row="md-ns"]')), 4000);
120
- await p.click('#nsRow [data-okd="edit"][data-row="md-ns"]');
121
- const e0 = await p.evaluate(() => { const r = document.querySelector('[data-dred="md-ns"]'); return r ? { f: [...r.querySelectorAll('[data-drf]')].map((x) => x.dataset.drf + '=' + x.value), acts: [...r.querySelectorAll('.acts a, .acts button')].map((b) => b.getAttribute('aria-label') + (b.textContent.trim() ? '!' : '')), focus: document.activeElement && document.activeElement.dataset.drf } : null; });
122
- ok('E ✎ turns the row into fields: name, target, source; ask in Home, ×, ✓, all icon-only; the name has the focus', !!e0 && e0.f.join('|') === 'name=Weekly signed-in shoppers|target=45000|source=Amplitude'
123
- && e0.acts.join() === 'Ask Claude in Home to change something else,Cancel the edit,Save Weekly signed-in shoppers' && e0.focus === 'name', JSON.stringify(e0));
124
- await shot(p, 'gap2-draft-edit', '#nsRow');
125
- await p.keyboard.press('Escape');
126
- ok('E Escape puts the row back', await until(() => p.evaluate(() => !document.querySelector('[data-dred]') && !!document.querySelector('#nsRow [data-okd="edit"][data-row="md-ns"]')), 2000));
127
- await p.click('#nsRow [data-okd="edit"][data-row="md-ns"]');
128
- await p.fill('[data-dred="md-ns"] [data-drf="name"]', 'Weekly shoppers');
129
- await p.fill('[data-dred="md-ns"] [data-drf="target"]', '48000');
130
- await p.click('[data-dred="md-ns"] [data-okd="save"]');
117
+ /* ── E: a drafted metric edited from its check panel ── */
118
+ // a drafted North Star is a row of the drafts table now (batch 18 item 11); ✎ is in its check panel
119
+ await until(() => p.evaluate(() => !!document.querySelector('#draftBox [data-gc-row="md-ns"]')), 4000);
120
+ const openEd = async () => { await p.click('#draftBox [data-gc-row="md-ns"] .gc-nm, #draftBox [data-gc-row="md-ns"] [role="cell"]'); await until(() => p.evaluate(() => !!document.querySelector('#czViewer [data-gc="edit"]')), 4000); await p.click('#czViewer [data-gc="edit"]'); };
121
+ await openEd();
122
+ const e0 = await until(() => p.evaluate(() => { const r = document.querySelector('#czViewer [data-gc-ed]'); return r ? { f: [...r.querySelectorAll('input')].map((x) => x.name + '=' + x.value), acts: [...r.querySelectorAll('.gc-foot a, .gc-foot button')].map((b) => b.getAttribute('aria-label') + (b.textContent.trim() ? '!' : '')), focus: document.activeElement && document.activeElement.name } : null; }), 3000);
123
+ ok('E ✎ turns the panel into fields: name, target, source; ask in Home, ×, ✓, all icon-only; the name has the focus', !!e0 && e0.f.join('|') === 'name=Weekly signed-in shoppers|target=45000|source=Amplitude'
124
+ && e0.acts.join() === 'Ask Claude in Home to change how it is counted,Cancel the edit,Save' && e0.focus === 'name', JSON.stringify(e0));
125
+ await shot(p, 'gap2-draft-edit', '#czViewer');
126
+ await p.click('#czViewer [data-gc="edit-x"]');
127
+ ok('E × puts the check back', await until(() => p.evaluate(() => !document.querySelector('#czViewer [data-gc-ed]') && !!document.querySelector('#czViewer [data-gc="edit"]')), 2000));
128
+ await p.click('#czViewer [data-gc="edit"]');
129
+ await p.fill('#czViewer [data-gc-ed] [name="name"]', 'Weekly shoppers');
130
+ await p.fill('#czViewer [data-gc-ed] [name="target"]', '48000');
131
+ await p.click('#czViewer [data-gc-ed] [type="submit"]');
131
132
  const ed = await until(() => A.posts.find((x) => x.path === '/api/metric-drafts/edit'), 3000);
132
133
  ok('E ✓ posts the edit with what was typed', !!ed && ed.body.row === 'md-ns' && ed.body.name === 'Weekly shoppers' && ed.body.target === '48000' && ed.body.source === 'Amplitude' && ed.body.scope === 'product', JSON.stringify(ed));
134
+ await p.keyboard.press('Escape');
133
135
 
134
136
  /* ── C: the program card (pm/metric-drafts.js) edits in place too ── */
135
137
  const c0 = await p.evaluate(async (ws) => {
@@ -316,7 +316,7 @@ function build(f) {
316
316
  // the start too: the Tasks Timeline draws a bar from the start to the due day (batch 9 item 5b)
317
317
  taskBy.get(w.ini).push({ uid: w.uid, title: clip(w.title || '', 160), status: w.status || 'To do', owner: w.owner || '', start: w.start || '', end: w.end || '', ...(w.from ? { from: { stage: w.from.stage, finish: w.from.finish } } : {}),
318
318
  // one view (feedback batch 6 item 1): its place in the breakdown, and a breakdown item's own stage and order
319
- ...(typeof w.section === 'string' ? { section: w.section } : {}), ...(w.itemStage ? { itemStage: w.itemStage } : {}), ...(Number.isFinite(w.order) ? { order: w.order } : {}), ...(w.store === 'item' ? { item: true } : {}), ...(w.milestone ? { milestone: true } : {}) });
319
+ ...(typeof w.section === 'string' ? { section: w.section } : {}), ...(w.itemStage ? { itemStage: w.itemStage } : {}), ...(Number.isFinite(w.order) ? { order: w.order } : {}), ...(Number.isFinite(w.rank) ? { rank: w.rank } : {}), ...(w.store === 'item' ? { item: true } : {}), ...(w.milestone ? { milestone: true } : {}) });
320
320
  }
321
321
  // the milestones of each initiative (feedback batch 11 item 3): its tasks flagged ◇, PMOS and Jira alike, at their due dates. Won't do and
322
322
  // Archived take one off the timeline; one with no due date is not drawn (the Tasks list asks for the date)
@@ -46,6 +46,9 @@
46
46
  * task-pin { task, pinned } the PM's pin on a milestone (feedback batch 13 item 4, XcalmA5Milestones):
47
47
  * true draws it on the Board timeline, false hides it, null goes back to the rule (only the initiative's last milestone).
48
48
  * `task` is a Board task, a breakdown item or a Jira key; the last line wins.
49
+ * task-order { initiative, section, tasks: [id] } the PM's order of the open tasks inside one stage of an
50
+ * initiative's breakdown (feedback batch 18 item 16, a drag in the stage list): the ids top to bottom. A task not named sorts after
51
+ * them. An empty list takes the order out (the urgency again). It never changes a task's status, dates or place; the last line wins.
49
52
  * ticket-dates { ref, start, due } the PM's own start and due days for a Jira ticket (feedback batch 11
50
53
  * item 23): kept in PMOS only, never written to Jira; '' clears one. They win over Jira's dates on the timeline; the last line wins.
51
54
  * ini-delete { id, title, tasks, items } the PM's Delete of an initiative (feedback batch 16 item 5d): it
@@ -171,7 +174,7 @@ function foundOf(f) {
171
174
  const sources = Array.isArray(f.sources) ? f.sources.filter((x) => x && typeof x.ref === 'string').slice(0, 8).map((x) => ({ label: String(x.label || ''), ref: x.ref })) : [];
172
175
  return { why: typeof f.why === 'string' ? f.why : '', sources, match: typeof f.match === 'string' && f.match ? f.match : null, scan: typeof f.scan === 'string' ? f.scan : null, run: typeof f.run === 'string' ? f.run : null };
173
176
  }
174
- const KINDS = new Set(['board', 'workflow', 'move', 'assign', 'ask', 'ask-accept', 'ask-decline', 'ask-more', 'ini-workflow', 'task', 'task-update', 'task-remove', 'task-restore', 'ticket-note', 'ini-epics', 'ini-archive', 'ini-notdup', 'ini-wf', 'ini-end', 'stage-judge', 'ini-auto', 'task-section', 'task-milestone', 'task-pin', 'ticket-dates',
177
+ const KINDS = new Set(['board', 'workflow', 'move', 'assign', 'ask', 'ask-accept', 'ask-decline', 'ask-more', 'ini-workflow', 'task', 'task-update', 'task-remove', 'task-restore', 'ticket-note', 'ini-epics', 'ini-archive', 'ini-notdup', 'ini-wf', 'ini-end', 'stage-judge', 'ini-auto', 'task-section', 'task-milestone', 'task-pin', 'ticket-dates', 'task-order',
175
178
  // split or merge initiatives (feedback batch 11 item 14): a Jira ticket moved to another initiative, the split and merge records with their Undo, Claude's suggestion dismissed
176
179
  'ticket-move', 'ini-split', 'ini-merge', 'ini-sm-undo', 'ini-suggest',
177
180
  // Delete an initiative with its tasks, and its Undo (feedback batch 16 item 5d)
@@ -206,6 +209,7 @@ function fold(events) {
206
209
  const tasks = new Map(); // task id → { id, board, initiative, title, epic, owner, state, start, due, at, by, history }
207
210
  const sections = new Map(); // task id → the stage key its breakdown section is ('' = Not in a stage); the last task-section line wins
208
211
  const milestones = new Map(); // task id (or Jira key) → true | false: the PM's milestone flag; the last task-milestone line wins
212
+ const orders = new Map(); // key(initiative, section) → the task ids in the PM's order inside that stage; the last task-order line wins
209
213
  const pins = new Map(); // task id (or Jira key) → true | false: the PM's pin on a milestone; a null line takes it out (the rule again)
210
214
  const removed = new Map(); // task id → the task a task-remove took out, so a task-restore (Delete's Undo) puts it back
211
215
  const ticketNotes = new Map(); // key(board, Jira key) → the PM's notes on that ticket (the last ticket-note line wins)
@@ -301,6 +305,9 @@ function fold(events) {
301
305
  sections.set(e.task, e.section);
302
306
  } else if (e.kind === 'task-milestone' && typeof e.task === 'string' && e.task && typeof e.milestone === 'boolean') {
303
307
  milestones.set(e.task, e.milestone);
308
+ } else if (e.kind === 'task-order' && typeof e.initiative === 'string' && e.initiative && typeof e.section === 'string' && Array.isArray(e.tasks)) {
309
+ const ids = e.tasks.filter((x) => typeof x === 'string' && x);
310
+ if (ids.length) orders.set(key(e.initiative, e.section), ids); else orders.delete(key(e.initiative, e.section));
304
311
  } else if (e.kind === 'task-pin' && typeof e.task === 'string' && e.task && (typeof e.pinned === 'boolean' || e.pinned === null)) {
305
312
  if (e.pinned === null) pins.delete(e.task); else pins.set(e.task, e.pinned);
306
313
  } else if (e.kind === 'ticket-dates' && b && typeof e.ref === 'string' && JIRA_KEY_RE.test(e.ref)) {
@@ -366,7 +373,7 @@ function fold(events) {
366
373
  suggestNo.set(e.id, { kind: e.of === 'merge' ? 'merge' : 'split', fp: e.fp, at: e.at || null });
367
374
  }
368
375
  }
369
- return { boards, moves, assigns, asks, stages, iniWorkflows, tasks, removed, sections, milestones, pins, ticketNotes, ticketDates, epics, archives, deleted, notDup, iniWf, ends, judged, autoOver, ticketMoves, smOps, smUndone, suggestNo, events: list };
376
+ return { boards, moves, assigns, asks, stages, iniWorkflows, tasks, removed, sections, orders, milestones, pins, ticketNotes, ticketDates, epics, archives, deleted, notDup, iniWf, ends, judged, autoOver, ticketMoves, smOps, smUndone, suggestNo, events: list };
370
377
  }
371
378
 
372
379
  /** The stages an initiative runs on a board: its own workflow when one is recorded, else the board's. */
@@ -11,7 +11,8 @@
11
11
  * its own). A line is { id (ULID), kind: 'add'|'edit'|'reading', rid, fields, why, by, via }.
12
12
  * add creates record `rid` with `fields` edit merges `fields` into it (latest edit wins per field)
13
13
  * reading (kr-metrics only) one actual reading { at, value } of the KR metric `rid`, with where it was read when the caller knows it:
14
- * source (one line: "Amplitude · checkout_login_success / checkout_view"), via (run | csv | pm), read_at (ISO time of the read)
14
+ * source (one line: "Amplitude · checkout_login_success / checkout_view"), via (run | press | held | csv | pm), read_at (ISO time of
15
+ * the read), period (the period it counts, one line), num and den (the two counts of a rate)
15
16
  * The actor comes from the call path (ledger.actorFrom), never from a field.
16
17
  *
17
18
  * LINKS. ideas, hypotheses, decisions and bets carry `initiative` (initiative id) and `parent_kr`; signals link by those.
@@ -24,6 +25,8 @@ const DATE = /^\d{4}-\d{2}-\d{2}$/;
24
25
  const num = (v) => typeof v === 'number' && Number.isFinite(v);
25
26
  const text = (v) => typeof v === 'string' && v.trim() !== '';
26
27
  const HORIZONS = ['now', 'next', 'later'];
28
+ /** A KR metric that must stay within a limit (a guardrail): it may have no `by`, since it is always on. */
29
+ const isLimit = (f) => f.type === 'Stay within' || f.limit === 'ceiling' || f.limit === 'floor' || f.always_on === true;
27
30
 
28
31
  // required: name -> predicate and the reason shown when it fails. `fix` rules run on the merged record.
29
32
  const KINDS = {
@@ -51,6 +54,7 @@ function validate(kind, fields) {
51
54
  const reasons = [];
52
55
  const f = fields && typeof fields === 'object' ? fields : {};
53
56
  for (const [name, [ok, label]] of Object.entries(spec(kind).required)) {
57
+ if (kind === 'kr-metrics' && name === 'by' && f.by == null && isLimit(f)) continue; // a guardrail is always on: no end date (batch 18 item 11)
54
58
  if (!(name in f) || f[name] == null || !ok(f[name])) reasons.push('missing or invalid: ' + label);
55
59
  }
56
60
  if (kind === 'kr-metrics' && f.by && f.baseline === f.target && num(f.baseline)) reasons.push('target equals baseline');
@@ -70,6 +74,7 @@ function fold(kind, lines) {
70
74
  else if (e.kind === 'reading' && by.has(e.rid) && e.fields) {
71
75
  const x = { at: e.fields.at, value: e.fields.value };
72
76
  for (const k of PROVENANCE) if (typeof e.fields[k] === 'string' && e.fields[k]) x[k] = e.fields[k];
77
+ for (const k of COUNTS) if (num(e.fields[k])) x[k] = e.fields[k];
73
78
  by.get(e.rid).readings.push(x);
74
79
  }
75
80
  }
@@ -103,12 +108,14 @@ function edit(root, kind, rid, fields, actor, why) {
103
108
  if (!v.ok) return { ok: false, reasons: v.reasons };
104
109
  return write(root, kind, { kind: 'edit', rid, fields, why: why || 'edited' }, actor);
105
110
  }
106
- const PROVENANCE = ['source', 'via', 'read_at'];
111
+ const PROVENANCE = ['source', 'via', 'read_at', 'period'];
112
+ const COUNTS = ['num', 'den']; // batch 18 item 11: the two counts of a rate, beside its value ("How it is counted")
107
113
  function addReading(root, rid, reading, actor, why) {
108
114
  if (!reading || !DATE.test(String(reading.at)) || !num(reading.value)) return { ok: false, reasons: ['a reading needs at (YYYY-MM-DD) and value (number)'] };
109
115
  if (!list(root, 'kr-metrics').some((r) => r.rid === rid)) return { ok: false, reasons: ['no such KR metric: ' + rid] };
110
116
  const fields = { at: reading.at, value: reading.value };
111
117
  for (const k of PROVENANCE) if (typeof reading[k] === 'string' && reading[k].trim()) fields[k] = reading[k].replace(/\s+/g, ' ').trim().slice(0, 200);
118
+ for (const k of COUNTS) if (num(reading[k])) fields[k] = reading[k];
112
119
  return write(root, 'kr-metrics', { kind: 'reading', rid, fields, why: why || 'reading' }, actor);
113
120
  }
114
121
 
@@ -64,7 +64,9 @@ function eventOf(b) {
64
64
  switch (o.kind) {
65
65
  case 'auto': if (typeof o.on !== 'boolean') return { ok: false, error: 'on is true or false' }; return { ok: true, event: { ...base, on: o.on } };
66
66
  case 'hold': { const s = name(o.stage); if (!s) return { ok: false, error: 'stage names the stage' }; return { ok: true, event: { ...base, stage: s } }; }
67
- case 'by': if (!BY.includes(o.by)) return { ok: false, error: 'by is one of ' + BY.join(', ') }; return { ok: true, event: { ...base, by: o.by } };
67
+ // the page sends the pick as grouping: 'by' is a writer field the press guard refuses in any body (lib/pm-guard.js), so a Group by
68
+ // press never saved (Wawan 12:07, "can't go back"); the line keeps by
69
+ case 'by': { const g = o.grouping !== undefined ? o.grouping : o.by; if (!BY.includes(g)) return { ok: false, error: 'grouping is one of ' + BY.join(', ') }; return { ok: true, event: { ...base, by: g } }; }
68
70
  case 'groups': if (!Array.isArray(o.names)) return { ok: false, error: 'names is a list of group names' }; return { ok: true, event: { ...base, names: names(o.names) } };
69
71
  case 'rename': { const f = name(o.from), t = name(o.to); if (!f || !t) return { ok: false, error: 'from and to name the group' }; return { ok: true, event: { ...base, from: f, to: t } }; }
70
72
  case 'place': if (!TASK_RE.test(String(o.task || ''))) return { ok: false, error: 'task names a task' }; return { ok: true, event: { ...base, task: o.task, group: name(o.group) } };
@@ -22,6 +22,7 @@
22
22
 
23
23
  const IG = require('./insights-goals.js');
24
24
  const GS = require('./goal-status.js'); // batch 16 item 6: the one status of a goal, from its readings
25
+ const MR = require('./metric-reads.js');
25
26
  const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
26
27
  const isoDay = (v) => { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(v || '')); return m ? Date.UTC(+m[1], +m[2] - 1, +m[3]) : null; };
27
28
  const shortDate = (v) => { const t = isoDay(v); if (t === null) return ''; const d = new Date(t); return d.getUTCDate() + ' ' + MON[d.getUTCMonth()]; };
@@ -307,13 +308,33 @@ const ROLES = ['north-star', 'input', 'guardrail', 'kr', 'program-goal', 'rollup
307
308
  const NOTIFY = ['push', 'intel', 'quiet'];
308
309
  /** batch 16 item 6 ("Claude runs the OKRs"): what the goal list and the goal Viewer read on each goal, beside today's fields. The dot is the
309
310
  * reading's (lib/goal-status.js), never an initiative's delivery status. w: { reads (lib/metric-reads.js fold), history: { rid: [{ at, text }] } } */
311
+ /** Batch 18 item 11 (goals made clear; contract next18/11-okr-clarity/api-contract.md §3, §5): how the goal is counted, how often it is read,
312
+ * its last good reading, the next read, Claude's checks, what was held, the failed try and the PM's own number. Zero is silence: each is null
313
+ * (or []) when there is nothing to say. */
314
+ function readFields(rec, rx, R, w, rid) {
315
+ const u = rec.unit || '', fmt = MR.fmt;
316
+ const rs = GS.readingsOf(rec), lastRec = rs.length ? rs[rs.length - 1] : null;
317
+ const good = R && R.good && (!lastRec || String(R.good.day) >= lastRec.at) ? R.good : null;
318
+ const lastRead = good ? { at: good.filedAt || good.at, value: good.value, txt: fmt(good.value, u), day: good.day, source: good.source || '', ...(Number.isFinite(good.num) ? { num: good.num } : {}), ...(Number.isFinite(good.den) ? { den: good.den } : {}), ...(good.period ? { period: good.period } : {}) }
319
+ : lastRec ? { at: lastRec.read_at || lastRec.at, value: lastRec.value, txt: fmt(lastRec.value, u), day: lastRec.at, source: lastRec.source || '', ...(Number.isFinite(lastRec.num) ? { num: lastRec.num } : {}), ...(Number.isFinite(lastRec.den) ? { den: lastRec.den } : {}), ...(lastRec.period ? { period: lastRec.period } : {}) } : null;
320
+ const counts = rx && rx.counts ? { ...rx.counts, ...(lastRead && Number.isFinite(lastRead.num) ? { num: lastRead.num } : {}), ...(lastRead && Number.isFinite(lastRead.den) ? { den: lastRead.den } : {}) } : null;
321
+ const held = R ? R.held.slice().reverse().map((h) => ({ at: h.at, day: h.day, value: h.value, txt: fmt(h.value, u), source: h.source || '', ...(Number.isFinite(h.num) ? { num: h.num } : {}), ...(Number.isFinite(h.den) ? { den: h.den } : {}), ...(h.period ? { period: h.period } : {}), why: h.why || '', checks: h.checks || [], ...(h.ticket ? { ticket: h.ticket } : {}) })) : [];
322
+ const failed = R && R.failed ? { at: R.failed.at, why: R.failed.why, ...(R.failed.fix ? { fix: { row: R.failed.fix } } : {}) } : null;
323
+ const F = w && w.reads;
324
+ const recFull = rx ? Object.assign({}, rec, { recipe: rx }) : rec;
325
+ return { counts, rhythm: rx ? MR.rhythmOf(rx) : null, lastRead, nextRead: rx && w ? MR.nextReadOf(recFull, F, w.now || Date.now(), w.hours) : null, checks: (R && R.checks) || null, held, failed,
326
+ compare: F ? MR.compareView(F, rid, u) : null };
327
+ }
310
328
  function watchFields(x, o, todayIso, w) {
311
329
  // the outcome's own baseline, target, date and unit first: a goal's meta may hold only what New goal keeps (6-B, 2026-10-28)
312
330
  const rec = Object.assign({ target: o.target, baseline: o.start, by: o.by, unit: o.unit }, x, { readings: (x && x.readings) || (o.readings || []).map((r) => ({ at: r.at, value: r.v })) });
313
331
  const R = w && w.reads ? w.reads.rids.get(o.id) : null;
314
- const recipe = x && x.recipe && typeof x.recipe === 'object' && x.recipe.connector ? { connector: String(x.recipe.connector), query: String(x.recipe.query || ''), cadence: x.recipe.cadence || 'weekly',
332
+ const rx = x && x.recipe && typeof x.recipe === 'object' && x.recipe.connector ? x.recipe : null;
333
+ const recipe = rx ? { connector: String(rx.connector), query: String(rx.query || ''), cadence: rx.cadence || 'weekly',
334
+ ...(rx.at ? { at: rx.at } : {}), ...(rx.day ? { day: rx.day } : {}), ...(rx.where ? { where: rx.where } : {}), ...(rx.url ? { url: rx.url } : {}), ...(rx.counts ? { counts: rx.counts } : {}),
315
335
  last: R && R.last ? { at: R.last.at, ok: R.last.ok, ...(R.last.ok ? {} : { error: R.last.error }) } : null } : null;
316
336
  return { reading: GS.readingOf(rec, todayIso), recipe, who: GS.whoOf(x || {}), notify: NOTIFY.includes(x && x.notify) ? x.notify : 'intel',
337
+ ...readFields(rec, rx, R, w, o.id),
317
338
  was: x && typeof x.was === 'string' && x.was ? clip(x.was, 200) : null, defn: x && typeof x.defn === 'string' ? clip(x.defn, 400) : '',
318
339
  history: (w && w.history && w.history[o.id]) || [], kr: x && typeof x.kr === 'string' ? x.kr : null, budget: x && typeof x.budget === 'string' ? x.budget : null,
319
340
  alert: R && R.alert && R.alert.open ? { day: R.alert.day, value: R.alert.value, limit: R.alert.limit } : null };
@@ -34,7 +34,7 @@
34
34
  * (group Key results); ✓ adds the record with kr: <anchor> and was: <old>
35
35
  * next-quarter next quarter's goal: metric = the row; ✓ adds the record
36
36
  * connect connector = the source to connect; ✓ is the PM's go to Settings › Connectors (nothing is written but the keep)
37
- * recipe goal = a kr-metrics rid, recipe = { connector, query, cadence }; ✓ sets the record's recipe
37
+ * recipe goal = a kr-metrics rid, recipe = recipeOf (connector, query, cadence, at, day, counts …); ✓ sets the record's recipe
38
38
  * chase goal, to (the owner), body (the thankful note), channel; ✓ puts the note in the outbox: nothing is sent until the PM's Send
39
39
  * ticket goal, ticket = { title, text, project? }; ✓ puts the ticket in the outbox (channel jira-write)
40
40
  * carry goal, by (the new date), target?; ✓ moves the record on to next quarter
@@ -71,7 +71,8 @@ const STEPS = ['read', 'shape', 'measure', 'target', 'ready'];
71
71
  const READ_STATES = ['done', 'now', 'wait'];
72
72
  const WHYS = ['north-star', 'quarter', 'goal', 'success', 'review', 'press'];
73
73
  const FIXES = ['outcome', 'connect', 'recipe', 'chase', 'ticket', 'next-quarter', 'carry', 'owner'];
74
- const CADENCES = ['daily', 'weekly', 'monthly'];
74
+ const CADENCES = ['hourly', 'daily', 'weekly', 'monthly']; // hourly: batch 18 item 11, in working hours only (lib/metric-reads.js)
75
+ const WEEKDAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
75
76
  const FIX_LIMIT = 12; // fix rows one run may file
76
77
  const ACT = { outcome: 'Keep', 'next-quarter': 'Keep', recipe: 'Keep', carry: 'Keep', owner: 'Keep', chase: 'Send', ticket: 'Send to Jira' };
77
78
  /** The "when" line of each trigger, as the page says it. */
@@ -159,11 +160,12 @@ function clean(scope, input) {
159
160
  if (direction) row.direction = direction;
160
161
  const unit = one(input.unit, LIM.unit); if (unit) row.unit = unit;
161
162
  const pillar = one(input.pillar, LIM.pillar); if (pillar && group === 'Key results') row.pillar = pillar;
163
+ if (input.recipe != null) { const r = recipeOf(input.recipe); if (r.error) return { error: 'recipe: ' + r.error }; row.recipe = r.recipe; } // batch 18 item 11: how it is counted and how often, before the ✓
162
164
  return { row };
163
165
  }
164
166
 
165
167
  /* ── a fix row (batch 16 item 6): what Claude drafts to repair a goal. Every kind says itself in one line; the evidence is `why`. ── */
166
- const FLIM = { goal: 80, text: 200, why: 200, old: 200, act: 40, connector: 40, query: 300, to: 60, body: 600, title: 120, project: 24 };
168
+ const FLIM = { goal: 80, text: 200, why: 200, old: 200, act: 40, connector: 40, query: 1200, to: 60, body: 600, title: 120, project: 24 };
167
169
  /** → { row } | { error }. id is the scope's id, for the row's id. */
168
170
  function cleanFix(scope, id, input) {
169
171
  if (!SCOPES.includes(scope)) return { error: 'scope is one of ' + SCOPES.join(', ') };
@@ -212,18 +214,42 @@ function cleanFix(scope, id, input) {
212
214
  row.id = 'fx-' + hash([scope, id, kind, goal || '', key].join('|'));
213
215
  return { row };
214
216
  }
217
+ /** How a goal is read (batch 18 item 11 adds the rhythm and the counts): { connector, query, cadence, at?, day?, where?, url?, counts?, range? }.
218
+ * at "HH:MM" for daily, weekly and monthly; day mon … sun for weekly; counts { what, num_label, den_label } is "How it is counted" in words and
219
+ * in the names of its two counts; range { min?, max? } is what a value can possibly be (a % is 0–100 without it). */
220
+ const TIME_RE = /^([01]\d|2[0-3]):[0-5]\d$/;
221
+ const RLIM = { what: 300, label: 60, where: 120, url: 400 };
222
+ function countsOf(c) {
223
+ if (c == null) return { counts: null };
224
+ if (!isObj(c)) return { error: 'counts is { what, num_label, den_label }' };
225
+ const what = one(c.what, RLIM.what);
226
+ if (!what) return { error: 'counts.what says in one sentence how it is counted' };
227
+ return { counts: { what, num_label: one(c.num_label, RLIM.label), den_label: one(c.den_label, RLIM.label) } };
228
+ }
215
229
  function recipeOf(r) {
216
230
  if (!isObj(r)) return { error: 'recipe is { connector, query, cadence }' };
217
- const connector = one(r.connector, FLIM.connector), query = one(r.query, FLIM.query), cadence = CADENCES.includes(r.cadence) ? r.cadence : null;
231
+ const connector = one(r.connector, FLIM.connector), query = String(r.query == null ? '' : r.query).replace(/[ \t]+/g, ' ').trim().slice(0, FLIM.query), cadence = CADENCES.includes(r.cadence) ? r.cadence : null;
218
232
  if (!connector || !query) return { error: 'a recipe names its connector and its query' };
219
233
  if (!cadence) return { error: 'cadence is one of ' + CADENCES.join(', ') };
220
- return { recipe: { connector, query, cadence } };
234
+ const out = { connector, query, cadence };
235
+ if (r.at != null && r.at !== '' && cadence !== 'hourly') { if (!TIME_RE.test(String(r.at))) return { error: 'at is the time of day, HH:MM' }; out.at = String(r.at); }
236
+ if (r.day != null && r.day !== '' && cadence === 'weekly') { const d = String(r.day).toLowerCase().slice(0, 3); if (!WEEKDAYS.includes(d)) return { error: 'day is one of ' + WEEKDAYS.join(', ') }; out.day = d; }
237
+ const where = one(r.where, RLIM.where); if (where) out.where = where;
238
+ if (r.url != null && r.url !== '') { const u = one(r.url, RLIM.url); if (!/^https:\/\/\S+$/.test(u)) return { error: 'url is an https address' }; out.url = u; }
239
+ const c = countsOf(r.counts); if (c.error) return c; if (c.counts) out.counts = c.counts;
240
+ if (r.range != null) {
241
+ if (!isObj(r.range)) return { error: 'range is { min?, max? }' };
242
+ const range = {}; for (const k of ['min', 'max']) if (r.range[k] != null) { if (!fin(r.range[k])) return { error: 'range.' + k + ' is a number' }; range[k] = r.range[k]; }
243
+ if (fin(range.min) && fin(range.max) && range.min >= range.max) return { error: 'range.min is below range.max' };
244
+ if (Object.keys(range).length) out.range = range;
245
+ }
246
+ return { recipe: out };
221
247
  }
222
248
 
223
249
  /* ── the PM's inline edit of an open draft (batch 16 item 1): its name, its target and where it is measured. The rest (why, now, the group) stays
224
250
  * Claude's: a change to those is asked of Claude in Home's chat. The target keeps the draft's own way of writing it ("≤ 3%", "$1,200"): the first
225
251
  * number in it is replaced. ── */
226
- const EDIT_KEYS = ['name', 'target', 'targetTxt', 'source', 'text', 'body'];
252
+ const EDIT_KEYS = ['name', 'target', 'targetTxt', 'source', 'text', 'body', 'recipe']; // recipe: only the compare pick (lib/routes-goal-status.js)
227
253
  function editOf(row, input) {
228
254
  if (!isObj(row)) return { error: 'There is no such draft.' };
229
255
  if (!isObj(input)) return { error: 'An edit is { name?, target?, source? }.' };
@@ -342,18 +368,19 @@ function keepFields(scope, id, row, o = {}) {
342
368
  if (!fin(target)) return { error: 'This draft has no target, so it cannot be kept.' };
343
369
  baseline = now == null ? 0 : now;
344
370
  direction = row.direction || (now == null ? 'up' : target >= now ? 'up' : 'down');
345
- if (type === 'Stay within') { f.limit = direction === 'down' ? 'ceiling' : 'floor'; if (!by) { by = String(o.today || '').slice(0, 4) + '-12-31'; f.always_on = true; } }
371
+ if (type === 'Stay within') { f.limit = direction === 'down' ? 'ceiling' : 'floor'; if (!by) f.always_on = true; } // batch 18 item 11: a limit is always on, with no made-up date
346
372
  f.unit = row.unit || UNIT_OF[type] || '';
347
373
  }
348
- if (!DAY_RE.test(String(by || ''))) return { error: 'This draft has no date, so it cannot be kept.' };
374
+ if (!DAY_RE.test(String(by || '')) && !f.always_on) return { error: 'This draft has no date, so it cannot be kept.' };
349
375
  if (baseline === target) return { error: 'The target equals the baseline, so there is nothing to move. Drop it or draft again.' };
350
- Object.assign(f, { baseline, target, by, direction, source: row.source || '', why: row.why || '' });
376
+ Object.assign(f, { baseline, target, ...(by ? { by } : {}), direction, source: row.source || '', why: row.why || '' });
351
377
  if (now == null && type !== 'Done or not') f.measured = false;
352
378
  if (row.ticket) f.ticket = { key: row.ticket.key, text: row.ticket.text };
353
379
  if (row.pillar) f.pillar = row.pillar;
354
380
  if (scope === 'program') { f.program = id; if (Array.isArray(row.checkpoints) && row.checkpoints.length) f.checkpoints = row.checkpoints.map((c) => ({ by: c.by, target: c.target, label: c.label || '' })); }
355
381
  if (scope === 'initiative') { f.initiative = id; f.window = WINDOW; }
356
382
  if (scope === 'product') f.product = id;
383
+ if (row.recipe) f.recipe = row.recipe;
357
384
  f.draft = row.id;
358
385
  return { fields: f, reading: now != null && DAY_RE.test(String(o.today || '')) ? { at: o.today, value: now } : null };
359
386
  }
@@ -361,4 +388,4 @@ function keepFields(scope, id, row, o = {}) {
361
388
  /** How many fix rows one run filed. */
362
389
  function fixesIn(s, run) { let n = 0; if (s) for (const r of s.rows.values()) if (r.run === run && r.kind && r.kind !== 'metric') n++; return n; }
363
390
 
364
- module.exports = { LEDGER, SCOPES, GROUPS, LIMITS, ROLES, TYPES, STEPS, WHEN, WHYS, WINDOW, FIXES, CADENCES, FIX_LIMIT, ledgerFile, readLines, read, append, fold, viewOf, clean, cleanFix, recipeOf, keepFields, editOf, rowId, keyOf, countIn, fixesIn };
391
+ module.exports = { LEDGER, SCOPES, GROUPS, LIMITS, ROLES, TYPES, STEPS, WHEN, WHYS, WINDOW, FIXES, CADENCES, WEEKDAYS, FIX_LIMIT, countsOf, ledgerFile, readLines, read, append, fold, viewOf, clean, cleanFix, recipeOf, keepFields, editOf, rowId, keyOf, countIn, fixesIn };
@@ -8,7 +8,10 @@
8
8
  * WHEN A RUN STARTS (headless kind `metric-read`, origin `metric-read:<ws>:<run>`):
9
9
  * due a live kr-metrics record has a recipe, and its cadence (daily, weekly, monthly) has passed since its last try (lib/metric-reads.js dueOf)
10
10
  * test the PM's page asks for a test read of drafted rows before the ✓ (POST /api/goal-status/test): their rids are the draft row ids
11
- * press Read now on the goal Viewer
11
+ * press Read now on the goal Viewer or Intelligence, any time: it ignores the rhythm and never moves the next scheduled read
12
+ * compare the PM's own number differs from Claude's by more than 2% (POST /api/goal-status/compare): the run finds why, with `--why`
13
+ * Batch 18 item 11: an HOURLY goal reads on the hour inside the working hours (deps.workOpen, the day-check window); every other rhythm reads
14
+ * when deep work is open (deps.open: at night or when the PM is idle, lib/driver-run.js deepOpen).
12
15
  * One run reads at most 8 goals of one workspace. At most 2 runs at once for the machine, one per workspace; the scan of a workspace at most
13
16
  * every 10 minutes, inside the day-check window. ■ Stop ends a run at once.
14
17
  *
@@ -17,7 +20,8 @@
17
20
  * _RUN, _RIDS, _TEST). A value lands on the record with its source and time; a test value lands only in the ledger. Nothing is sent.
18
21
  * When the run ends, a goal it neither read nor said it could not read is filed as not read ("the run ended before it read this").
19
22
  *
20
- * deps: { workspaces(), isLead(w), stateDirFor(w), recordsDir(w), records(w) → [kr-metrics record], open(now), headlessOff(), env,
23
+ * deps: { workspaces(), isLead(w), stateDirFor(w), recordsDir(w), records(w) → [kr-metrics record], open(now), workOpen(now), hours() → { start, end },
24
+ * headlessOff(), env,
21
25
  * promptFor(skillId), spawn(spec), spawnNow(spec), stop(session), afterRead(w, rids) (the alert check and the bell), warn(what, err),
22
26
  * draftsFile(w) → the metric-drafts ledger, testItems(w, rids) → [{ rid, title, unit, recipe }] for drafted rows }
23
27
  */
@@ -33,8 +37,8 @@ const SCAN_MS = 10 * 60e3;
33
37
  const localDay = (ms) => { const d = new Date(ms); return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0'); };
34
38
 
35
39
  function promptOf(skill, o) {
36
- const lines = (o.items || []).map((x) => `- ${x.rid} · ${one(x.title, 120)}${x.unit ? ' · unit ' + one(x.unit, 12) : ''} · read with ${one(x.recipe && x.recipe.connector, 40)}: ${one(x.recipe && x.recipe.query, 300)} · cadence ${(x.recipe && x.recipe.cadence) || 'weekly'}`);
37
- return `${skill}\n\nThis run:\n- Run: ${o.run}\n- Why it runs: ${o.why === 'test' ? 'a test read before the PM keeps these drafts (file with --test semantics: the server pins it)' : o.why === 'press' ? 'the PM asked to read now' : 'the cadence of these goals has passed'}\n`
40
+ const lines = (o.items || []).map((x) => `- ${x.rid} · ${one(x.title, 120)}${x.unit ? ' · unit ' + one(x.unit, 12) : ''} · read with ${one(x.recipe && x.recipe.connector, 40)}: ${one(x.recipe && x.recipe.query, 1200)} · cadence ${(x.recipe && x.recipe.cadence) || 'weekly'}${x.recipe && x.recipe.counts ? ` · counted as: ${one(x.recipe.counts.what, 300)}${x.recipe.counts.num_label ? ` (${one(x.recipe.counts.num_label, 60)}${x.recipe.counts.den_label ? ' ÷ ' + one(x.recipe.counts.den_label, 60) : ''})` : ''}` : ''}${x.compare ? ` · COMPARE: the PM's number is ${x.compare.value}${x.compare.period ? ' for ' + one(x.compare.period, 40) : ''}; mine was ${x.compare.ours}` : ''}`);
41
+ return `${skill}\n\nThis run:\n- Run: ${o.run}\n- Why it runs: ${o.why === 'test' ? 'a test read before the PM keeps these drafts (file with --test semantics: the server pins it)' : o.why === 'press' ? 'the PM asked to read now' : o.why === 'compare' ? 'the PM\'s own number differs from mine: find why, and file it with --why (file no value)' : 'the cadence of these goals has passed'}\n`
38
42
  + `- Today: ${o.today}\n- Read these goals, each with its own recipe:\n${lines.join('\n') || '- none'}\n\n`
39
43
  + 'File with `pmos metrics reading` only (the server pins this run and these goals). Write no other record. Send nothing.';
40
44
  }
@@ -52,15 +56,15 @@ function create(deps) {
52
56
  const at = new Date(now).toISOString();
53
57
  // a goal this run did not file is said honestly: not read
54
58
  const filed = new Set(MR.readLines(MR.ledgerFile(a.dir)).filter((l) => l.run === run && (l.kind === 'read' || l.kind === 'cant')).map((l) => l.rid));
55
- for (const rid of a.rids) if (!filed.has(rid)) {
59
+ if (a.why !== 'compare') for (const rid of a.rids) if (!filed.has(rid)) { // a compare run files a reason, never a value
56
60
  try { MR.append(a.dir, null, { kind: 'cant', run, rid, why: r && r.stopped ? 'You stopped the run before it read this.' : 'The run ended before it read this.', ...(a.test ? { test: true } : {}) }, at); } catch (e) { warn('metric read cant', e); }
57
61
  }
58
62
  if (R && !R.ended) { try { MR.append(a.dir, null, { kind: 'end', run, ok, ...(ok ? {} : { error: one((r && r.note) || 'the run failed', 200) }) }, at); } catch (e) { warn('metric read end', e); } }
59
- if (!a.test && deps.afterRead) { try { deps.afterRead(a.w, a.rids, now); } catch (e) { warn('metric read after', e); } }
63
+ if (!a.test && a.why !== 'compare' && deps.afterRead) { try { deps.afterRead(a.w, a.rids, now); } catch (e) { warn('metric read after', e); } }
60
64
  }
61
65
 
62
66
  /** Start one run now. → { ok, run } | { ok: false, error, held? } */
63
- function start({ ws, rids, why = 'press', now = Date.now() } = {}) {
67
+ function start({ ws, rids, why = 'press', now = Date.now(), compare = null } = {}) {
64
68
  if (off(deps.env) || (deps.headlessOff && deps.headlessOff())) return { ok: false, error: 'Claude\'s goal readings are off (PMOS_METRIC_READ or PMOS_HEADLESS).' };
65
69
  const w = (deps.workspaces() || []).find((x) => x.id === ws);
66
70
  if (!w) return { ok: false, error: 'no such workspace' };
@@ -68,7 +72,7 @@ function create(deps) {
68
72
  if (!dir) return { ok: false, error: 'This repository has no PMOS state folder, so nothing can be read.' };
69
73
  for (const [r, a] of active) if (a.ws === ws) return { ok: false, held: true, already: r, error: 'Claude is reading this product\'s goals now. It reads these when that run ends.' };
70
74
  if (active.size >= MAX) return { ok: false, held: true, error: 'Claude is reading two other products now. It reads these when one ends.' };
71
- const test = why === 'test';
75
+ const test = why === 'test' || !!(compare && compare.draft);
72
76
  let items = [];
73
77
  if (test) { try { items = (deps.testItems && deps.testItems(w, rids)) || []; } catch { items = []; } }
74
78
  else {
@@ -76,6 +80,7 @@ function create(deps) {
76
80
  items = (rids || []).map((rid) => recs.find((x) => x.rid === rid)).filter((x) => x && x.recipe).map((x) => ({ rid: x.rid, title: x.metric || x.rid, unit: x.unit || '', recipe: x.recipe }));
77
81
  }
78
82
  items = items.filter((x) => x && x.recipe && x.recipe.connector && x.recipe.query).slice(0, PER_RUN);
83
+ if (compare) items = items.slice(0, 1).map((x) => ({ ...x, compare }));
79
84
  if (!items.length) return { ok: false, error: test ? 'These drafts have no way to be read yet.' : 'These goals have no recipe to read them with.' };
80
85
  const skill = deps.promptFor('metric-read');
81
86
  if (!skill) return { ok: false, error: 'The metric-read skill is not installed.' };
@@ -83,7 +88,7 @@ function create(deps) {
83
88
  const ids = items.map((x) => x.rid);
84
89
  const prompt = promptOf(skill, { run, why, today: localDay(now), items });
85
90
  const go = why !== 'due' && deps.spawnNow ? deps.spawnNow : deps.spawn;
86
- active.set(run, { ws, w, rids: ids, dir, session: null, test });
91
+ active.set(run, { ws, w, rids: ids, dir, session: null, test, why });
87
92
  let session = null;
88
93
  try {
89
94
  session = go({ name: 'Reading goals · ' + one(w.name || ws, 60), ws, origin: `metric-read:${ws}:${run}`, initialInput: prompt + '\r',
@@ -107,17 +112,19 @@ function create(deps) {
107
112
  function tick({ now = Date.now(), env } = {}) {
108
113
  if (off(env || deps.env) || (deps.headlessOff && deps.headlessOff())) return { off: true };
109
114
  if (active.size >= MAX) return { running: active.size };
110
- let open = true;
115
+ let open = true, work = false;
111
116
  try { open = deps.open ? !!deps.open(now) : true; } catch { open = true; }
112
- if (!open) return { started: null, closed: true };
113
- const day = localDay(now);
117
+ try { work = deps.workOpen ? !!deps.workOpen(now) : false; } catch { work = false; }
118
+ if (!open && !work) return { started: null, closed: true };
119
+ let hours; try { hours = deps.hours ? deps.hours() : undefined; } catch { hours = undefined; }
120
+ const only = open && work ? undefined : open ? 'other' : 'hourly'; // hourly goals in the working hours, the rest when deep work is open
114
121
  for (const w of deps.workspaces() || []) {
115
122
  if (deps.isLead && !deps.isLead(w)) continue;
116
123
  if (now - (lastScan.get(w.id) || -Infinity) < SCAN_MS) continue;
117
124
  const dir = deps.stateDirFor(w); if (!dir) continue;
118
125
  lastScan.set(w.id, now);
119
126
  let recs = []; try { recs = deps.records(w) || []; } catch (e) { warn('metric read records', e); continue; }
120
- const due = MR.dueOf(recs, MR.read(dir), day);
127
+ const due = MR.dueOf(recs, MR.read(dir), now, { only, hours });
121
128
  if (!due.length) continue;
122
129
  const r = start({ ws: w.id, rids: due.slice(0, PER_RUN), why: 'due', now });
123
130
  if (r.ok) return { started: w.id, rids: r.rids };