create-pmos 0.432.0 → 0.434.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 (70) 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-insights-test.js +63 -58
  7. package/workspace/changelog.json +24 -0
  8. package/workspace/guide/home.md +1 -1
  9. package/workspace/guide/index.md +1 -0
  10. package/workspace/guide/metric-drafts.md +21 -1
  11. package/workspace/guide/programs.md +1 -1
  12. package/workspace/guide/your-impact.md +58 -0
  13. package/workspace/impact-screens-test.js +149 -0
  14. package/workspace/intel-report-ui-test.js +1 -1
  15. package/workspace/intelligence-gaps-ui-test.js +13 -9
  16. package/workspace/lib/engine/outbox.js +1 -1
  17. package/workspace/lib/engine/records/index.js +11 -3
  18. package/workspace/lib/goal-status.js +199 -0
  19. package/workspace/lib/goal-watch.js +71 -0
  20. package/workspace/lib/headless.js +24 -2
  21. package/workspace/lib/impact-cli.js +72 -0
  22. package/workspace/lib/impact-runs.js +114 -0
  23. package/workspace/lib/impact.js +195 -0
  24. package/workspace/lib/insights-premium.js +43 -4
  25. package/workspace/lib/metric-draft-runs.js +33 -10
  26. package/workspace/lib/metric-drafts.js +118 -15
  27. package/workspace/lib/metric-read-runs.js +132 -0
  28. package/workspace/lib/metric-reads.js +129 -0
  29. package/workspace/lib/metrics-cli.js +100 -5
  30. package/workspace/lib/pmos-verbs.js +4 -1
  31. package/workspace/lib/route-modules.js +3 -0
  32. package/workspace/lib/routes-goal-status.js +111 -0
  33. package/workspace/lib/routes-impact-views.js +58 -0
  34. package/workspace/lib/routes-impact.js +91 -0
  35. package/workspace/lib/routes-insights-premium.js +20 -0
  36. package/workspace/lib/routes-metric-drafts.js +55 -4
  37. package/workspace/lib/routes-records.js +2 -0
  38. package/workspace/lib/settings-store.js +3 -0
  39. package/workspace/milestone-pins-test.js +8 -3
  40. package/workspace/okr-goals-ui-test.js +175 -0
  41. package/workspace/package-lock.json +2 -2
  42. package/workspace/package.json +1 -1
  43. package/workspace/product-lane-test.js +5 -5
  44. package/workspace/public/pm/bd-ini-panel.js +10 -2
  45. package/workspace/public/pm/bd-span.js +5 -4
  46. package/workspace/public/pm/cozy-adler.css +5 -0
  47. package/workspace/public/pm/cozy-adler.js +17 -9
  48. package/workspace/public/pm/cozy-insights.css +84 -0
  49. package/workspace/public/pm/cozy-settings.js +11 -1
  50. package/workspace/public/pm/home-app.js +61 -8
  51. package/workspace/public/pm/home-impact.css +16 -0
  52. package/workspace/public/pm/home-impact.js +72 -0
  53. package/workspace/public/pm/home-today.js +4 -2
  54. package/workspace/public/pm/impact.css +37 -0
  55. package/workspace/public/pm/impact.js +201 -0
  56. package/workspace/public/pm/okr-list.js +249 -0
  57. package/workspace/public/pm/premium-insights.js +222 -238
  58. package/workspace/public/pm/premium-vw-mtg.js +4 -1
  59. package/workspace/public/pm/stage-line.js +4 -3
  60. package/workspace/public/premium-intelligence.html +3 -2
  61. package/workspace/public/premium.html +1 -0
  62. package/workspace/server.js +56 -2
  63. package/workspace/skills/impact-detect.skill +46 -0
  64. package/workspace/skills/metric-read.skill +32 -0
  65. package/workspace/task-milestones-test.js +4 -3
  66. package/workspace/test-lists/goal-watch.json +9 -0
  67. package/workspace/test-lists/impact-screens.json +5 -0
  68. package/workspace/test-lists/impact-ui.json +9 -0
  69. package/workspace/test-lists/impact.json +9 -0
  70. package/workspace/test-lists/okr-goals-ui.json +5 -0
@@ -3,7 +3,8 @@
3
3
  *
4
4
  * off(env) → true when PMOS_METRIC_DRAFT=off (or 0, false, no)
5
5
  * quarterOf(day) → { start, end, prevStart, prevEnd } of the quarter `day` (YYYY-MM-DD) is in
6
- * dueOf(o) PURE → [{ scope, id, why, title }] the scopes of one workspace that need a draft now, in the order they start
6
+ * dueOf(o) PURE → [{ scope, id, why, title, gaps? }] the scopes of one workspace that need a draft now, in the order they start
7
+ * gapsOf({ krs, records }) PURE → [{ key, line }] the OKR review's gaps: a declared key result with no metric, a goal with no recipe
7
8
  * promptOf(skill, o) → the prompt of one run. o: { run, scope, id, why, title, today, facts: [line], kept: [line], dropped: [line] }
8
9
  * create(deps) → { tick(opts), start({ ws, scope, id, why, press, now }), stop(run), active() }
9
10
  *
@@ -13,6 +14,9 @@
13
14
  * goal a program charter (in this workspace) has no goal and no kr-metrics record with role program-goal for it
14
15
  * success an initiative has a PRD and no kr-metrics record with initiative: <id>. The first scan writes the epoch: an initiative that
15
16
  * had its PRD then is history, so only one that gets its PRD later is drafted unasked (the PM can press Draft again on any)
17
+ * review the OKR review (batch 16 item 6, "Claude runs the OKRs"): a key result the OKR files declare has no metric (a project-shaped
18
+ * goal), or a goal has no recipe to read it. The run drafts fixes (outcome, recipe, connect, …) with `pmos metrics draft fix`.
19
+ * It runs again only when the gaps change (their signature is on the start line), or the next day after a failed run.
16
20
  * A scope that was drafted once is not drafted again unasked; one whose last run failed tries again the next day. A retired record counts
17
21
  * as no record. "Draft again" (POST /api/metric-drafts/start) starts a run at once, why `press`.
18
22
  *
@@ -47,6 +51,16 @@ function quarterOf(day) {
47
51
  return { start: `${y}-${p2(q0)}-01`, end: `${y}-${p2(q0 + 2)}-${p2(lastDay(y, q0 + 2))}`, prevStart: `${py}-${p2(pq)}-01`, prevEnd: `${py}-${p2(pq + 2)}-${p2(lastDay(py, pq + 2))}` };
48
52
  }
49
53
  const live = (records) => (records || []).filter((r) => r && r.retired !== true);
54
+ /** The OKR review's gaps. krs: the key results the OKR files declare, [{ value, label }] (lib/initiative-rows.js anchorsOf list). A record names a
55
+ * key result by kr (its anchor), its rid, or its metric name. */
56
+ function gapsOf({ krs, records } = {}) {
57
+ const R = live(records), out = [];
58
+ const named = (k) => R.some((r) => [r.kr, r.rid, r.metric].some((x) => x && (String(x) === k.value || String(x) === k.label || String(x).toLowerCase() === String(k.label || '').replace(/^\S+\s+/, '').toLowerCase())));
59
+ for (const k of krs || []) if (k && k.value && !named(k)) out.push({ key: 'kr:' + k.value, line: 'Key result ' + one(k.value, 60) + ' has no metric. Its text: "' + one(k.label, 160) + '". If it names a project, draft it as an outcome.' });
60
+ for (const r of R) if (r.role !== 'watch' && !(r.recipe && r.recipe.connector)) out.push({ key: 'recipe:' + r.rid, line: 'Goal ' + r.rid + ' · ' + one(r.metric, 100) + ' has no recipe, so I cannot read it by myself.' });
61
+ return out;
62
+ }
63
+ const sigOfGaps = (gaps) => crypto.createHash('sha1').update((gaps || []).map((g) => g.key).sort().join('|')).digest('hex').slice(0, 12);
50
64
  /** Unasked, a scope is drafted once; a failed run tries again on a later day. */
51
65
  function mayDraft(s, why, day) {
52
66
  const runs = s ? s.runs.filter((r) => why === 'quarter' ? r.why === 'quarter' : r.why !== 'quarter') : [];
@@ -74,6 +88,11 @@ function dueOf(o) {
74
88
  if (R.some((r) => r.program === p.id && r.role === 'program-goal')) continue;
75
89
  if (mayDraft(sOf('program', p.id), 'goal', day)) out.push({ scope: 'program', id: p.id, why: 'goal', title: p.title || p.id });
76
90
  }
91
+ // the OKR review: once per set of gaps; a failed run tries again the next day
92
+ if ((o.gaps || []).length && !out.some((x) => x.scope === 'product')) {
93
+ const sig = sigOfGaps(o.gaps), s = sOf('product', o.ws), runs = s ? s.runs.filter((r) => r.why === 'review' && r.gaps === sig) : [], last = runs[runs.length - 1];
94
+ if (!last || (last.ended && !last.ok && !last.stopped && String(last.at).slice(0, 10) !== day)) out.push({ scope: 'product', id: o.ws, why: 'review', title: o.wsTitle || o.ws, gaps: o.gaps, sig });
95
+ }
77
96
  const known = new Set((F.epoch && F.epoch.known) || []);
78
97
  if (F.epoch) for (const i of o.initiatives || []) {
79
98
  if (!i || !i.id || known.has(i.id)) continue;
@@ -89,12 +108,14 @@ const SHAPE = {
89
108
  quarter: 'next quarter\'s Key results (at most 5), from how the last quarter ended',
90
109
  program: 'a Program goal (1, with checkpoints at its milestones), Rolls up from (one per product) and a Guardrail (at most 1)',
91
110
  initiative: 'Proves it worked (1, read 4 weeks after release), an Early signal (at most 1) and a Guardrail (at most 1)',
111
+ review: 'fixes for the gaps below (at most 12), filed with `pmos metrics draft fix`: an outcome for a key result that names a project, a recipe for a goal with no way to be read, connect for a source that is not connected',
92
112
  };
93
113
  function promptOf(skill, o) {
94
114
  const list = (a, none) => (a && a.length ? a.map((x) => '- ' + x).join('\n') : '- ' + none);
95
- const shape = o.why === 'quarter' ? SHAPE.quarter : SHAPE[o.scope];
115
+ const shape = o.why === 'quarter' ? SHAPE.quarter : o.why === 'review' ? SHAPE.review : SHAPE[o.scope];
96
116
  return `${skill}\n\nThis run:\n- Run: ${o.run}\n- Scope: ${o.scope} ${o.id} · ${one(o.title, 140)}\n- Why it runs: ${MD.WHEN[o.why] || MD.WHEN.press} (${o.why})\n- Today: ${o.today}\n`
97
- + `- Draft: ${shape}. Groups: ${(o.why === 'quarter' ? ['Key results'] : MD.GROUPS[o.scope].filter((g) => g !== 'Key results')).join(', ')}.\n`
117
+ + `- Draft: ${shape}.${o.why === 'review' ? ' Fix kinds: ' + MD.FIXES.join(', ') + '.' : ' Groups: ' + (o.why === 'quarter' ? ['Key results'] : MD.GROUPS[o.scope].filter((g) => g !== 'Key results')).join(', ') + '.'}\n`
118
+ + (o.why === 'review' ? `- The gaps:\n${list((o.gaps || []).map((g) => g.line), 'none')}\n` : '')
98
119
  + `- What PMOS knows:\n${list(o.facts, 'nothing more')}\n`
99
120
  + `- Already kept by the PM (do not draft these again):\n${list(o.kept, 'none')}\n`
100
121
  + `- Dropped by the PM (do not draft these again unless the evidence is new):\n${list(o.dropped, 'none')}\n\n`
@@ -117,7 +138,7 @@ function create(deps) {
117
138
  }
118
139
 
119
140
  /** Start one run now. → { ok, run } | { ok: false, error, held? } */
120
- function start({ ws, scope, id, why = 'press', press = true, now = Date.now() } = {}) {
141
+ function start({ ws, scope, id, why = 'press', press = true, now = Date.now(), gaps = null, sig = null } = {}) {
121
142
  if (off(deps.env) || (deps.headlessOff && deps.headlessOff())) return { ok: false, error: 'Claude\'s metric drafts are off (PMOS_METRIC_DRAFT or PMOS_HEADLESS).' };
122
143
  if (!MD.SCOPES.includes(scope) || !id) return { ok: false, error: 'Say which product, program or initiative to draft for.' };
123
144
  const w = (deps.workspaces() || []).find((x) => x.id === ws);
@@ -135,7 +156,8 @@ function create(deps) {
135
156
  const line = (r) => r.group + ' · ' + r.name + (r.targetTxt ? ' · ' + r.targetTxt : '');
136
157
  let facts = [];
137
158
  try { facts = (deps.facts && deps.facts(w, scope, id)) || []; } catch { facts = []; }
138
- const prompt = promptOf(skill, { run, scope, id, why, title, today: localDay(now), facts, kept: rows.filter((r) => r.state === 'kept').map(line), dropped: rows.filter((r) => r.state === 'dropped').map(line) });
159
+ const shown = (r) => (r.kind && r.kind !== 'metric' ? r.kind + ' · ' + r.text : line(r));
160
+ const prompt = promptOf(skill, { run, scope, id, why, title, today: localDay(now), facts, gaps, kept: rows.filter((r) => r.state === 'kept').map(shown), dropped: rows.filter((r) => r.state === 'dropped').map(shown) });
139
161
  const go = press && deps.spawnNow ? deps.spawnNow : deps.spawn;
140
162
  active.set(run, { ws, scope, id, dir, session: null });
141
163
  let session = null;
@@ -145,7 +167,7 @@ function create(deps) {
145
167
  } catch (e) { warn('metric draft run', e); }
146
168
  if (session && session.held) { active.delete(run); return { ok: false, held: true, error: 'Claude is busy with other runs. It tries again in a minute.' }; }
147
169
  // the start line lands before the run's first `pmos metrics draft` (the run starts reading after this returns), stamped with the tick's clock
148
- MD.append(dir, null, { kind: 'start', scope, id, run, why, title, when: MD.WHEN[why] || '' }, new Date(now).toISOString());
170
+ MD.append(dir, null, { kind: 'start', scope, id, run, why, title, when: MD.WHEN[why] || '', ...(sig ? { gaps: sig } : {}) }, new Date(now).toISOString());
149
171
  if (!session || session.state === 'exited' || session.headless !== 'metric-draft') {
150
172
  if (session && session.headless !== 'metric-draft' && session.state !== 'exited' && deps.stop) { try { deps.stop(session); } catch { /* best effort */ } }
151
173
  ended(run, { code: 1, note: (session && session.note) || 'the run could not start in the background', result: {} }, now);
@@ -170,16 +192,17 @@ function create(deps) {
170
192
  const dir = deps.stateDirFor(w); if (!dir) continue;
171
193
  lastScan.set(w.id, now);
172
194
  const F = MD.read(dir);
173
- let records = [], programs = [], initiatives = [];
195
+ let records = [], programs = [], initiatives = [], krs = [];
174
196
  try { records = deps.records(w) || []; } catch (e) { warn('metric draft records', e); continue; }
175
197
  try { programs = (deps.programs && deps.programs(w)) || []; } catch { programs = []; }
176
198
  try { initiatives = (deps.initiatives && deps.initiatives(w)) || []; } catch { initiatives = []; }
199
+ try { krs = (deps.krs && deps.krs(w)) || []; } catch { krs = []; }
177
200
  // the first scan writes the epoch: the initiatives that have a PRD now are history (an old PRD is not a new one)
178
201
  if (!F.epoch) { MD.append(dir, null, { kind: 'epoch', scope: null, id: null, known: initiatives.map((i) => i.id) }, new Date(now).toISOString()); F.epoch = { known: initiatives.map((i) => i.id) }; }
179
- const due = dueOf({ ws: w.id, wsTitle: w.name || w.id, records, programs, initiatives, F, today: day });
202
+ const due = dueOf({ ws: w.id, wsTitle: w.name || w.id, records, programs, initiatives, F, today: day, gaps: gapsOf({ krs, records }) });
180
203
  for (const d of due) {
181
204
  if ([...active.values()].some((a) => a.ws === w.id && a.scope === d.scope && a.id === d.id)) continue;
182
- const r = start({ ws: w.id, scope: d.scope, id: d.id, why: d.why, press: false, now });
205
+ const r = start({ ws: w.id, scope: d.scope, id: d.id, why: d.why, press: false, now, gaps: d.gaps || null, sig: d.sig || null });
183
206
  if (r.ok) return { started: d.scope + ':' + d.id, why: d.why };
184
207
  if (r.held) { lastScan.delete(w.id); return { held: true }; }
185
208
  }
@@ -190,4 +213,4 @@ function create(deps) {
190
213
  return { tick, start, stop, active: () => [...active.keys()], runOf: (ws, scope, id) => { for (const [r, a] of active) if (a.ws === ws && a.scope === scope && a.id === id) return r; return null; } };
191
214
  }
192
215
 
193
- module.exports = { off, quarterOf, dueOf, promptOf, create, MAX, SCAN_MS, QUARTER_DAYS };
216
+ module.exports = { off, quarterOf, dueOf, gapsOf, promptOf, create, MAX, SCAN_MS, QUARTER_DAYS };
@@ -12,32 +12,51 @@
12
12
  *
13
13
  * THE LEDGER. One line per event, { at, by, kind, scope, id, ... }:
14
14
  * epoch { known: [initiative id] } the first scan: the initiatives that had a PRD then are history, never drafted unasked
15
- * start { run, why, title, when } a run began; why ∈ north-star · quarter · goal · success · press
15
+ * start { run, why, title, when, gaps? } a run began; why ∈ north-star · quarter · goal · success · review · press. A review
16
+ * run (batch 16 item 6) carries the signature of the gaps it was started for
16
17
  * step { run, step } the strip: 0 read · 1 shape · 2 measure · 3 target · 4 ready
17
18
  * read { run, t, f, state } one source read; the last line for a title in a run wins (state done · now · wait)
18
19
  * row { run, row } one drafted row (clean() shape); the last line for a row id wins
19
20
  * end { run, ok, stopped?, error?, head?, sub?, src? } the run ended; `pmos metrics draft end` says the head, sub and sources
20
- * keep { row, rid } ✓: the kr-metrics record it wrote
21
+ * keep { row, rid, before?, outbox? } ✓: the kr-metrics record it wrote; a fix that edits a record keeps the fields it replaced
22
+ * (before), a chase or a ticket the outbox entry it queued, so Undo puts them back
21
23
  * drop { row } ✕
22
24
  * undo { row, rid? } a kept row back to open (its record retired), or a dropped one back to open
23
25
  * edit { row, set: { name?, target?, targetTxt?, source? } } the PM's inline edit of an open row (batch 16 item 1); a later run's row line replaces it
24
- * A new run's start clears every row of the scope that was not kept: it drafts again. A kept row is the PM's and stays.
26
+ * fix { row, src } a STANDING fix (batch 16 item 6): filed outside a draft run, by the reading run (src read: a
27
+ * goal it could not read) or by the goal watch (src watch: an owner, a chase, a rollback ticket)
28
+ * clear { row } a standing fix whose reason is gone (the goal was read, the limit is back under): it leaves
29
+ * A new run's start clears every row of the scope that was neither kept nor standing: it drafts again. A kept row is the PM's and stays.
30
+ *
31
+ * TWO SORTS OF ROW (batch 16 item 6, "Claude runs the OKRs"). Every row has `kind`:
32
+ * metric a new metric (the rows above: group, name, type, now, target, …); ✓ adds a kr-metrics record
33
+ * outcome a project-shaped goal rewritten as an outcome: goal = the KR anchor, old = its project title, metric = the new metric row
34
+ * (group Key results); ✓ adds the record with kr: <anchor> and was: <old>
35
+ * next-quarter next quarter's goal: metric = the row; ✓ adds the record
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
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
+ * ticket goal, ticket = { title, text, project? }; ✓ puts the ticket in the outbox (channel jira-write)
40
+ * carry goal, by (the new date), target?; ✓ moves the record on to next quarter
41
+ * owner goal, owner = { name, from: jira | pm }; ✓ sets the record's owner
42
+ * A fix row says itself in `text` (one line), `why` (the evidence) and `act` (the ✓'s label: Keep, Send, Connect Amplitude, Send to Jira).
25
43
  *
26
44
  * ledgerFile(dir) · readLines(file) · read(dir) → fold · append(dir, actor, line, at)
27
45
  * fold(lines) PURE → { scopes: Map key → S, epoch } S: { scope, id, title, when, run, runs, rows: Map, head, sub, src }
28
46
  * viewOf(F, scope, id, o) PURE → the GET body (no ok): { scope, id, title, when, run: { state, step, reads }, rows, head, sub, src }
29
47
  * clean(scope, input) → { row } | { error } what `pmos metrics draft row` checks
48
+ * cleanFix(scope, id, input) → { row } | { error } what `pmos metrics draft fix` and `pmos metrics reading --cant` check (row.id set)
30
49
  * keepFields(scope, id, row, o) → { fields, reading } | { error } the kr-metrics record a ✓ writes
31
50
  * editOf(row, input) → { set } | { error } what the inline edit may change: name, target, source (lib/routes-metric-drafts.js /edit)
32
51
  * rowId(scope, id, group, name) · keyOf(scope, id) · countIn(S, run, group)
33
- * SCOPES · GROUPS · LIMITS · ROLES · TYPES · STEPS · WHEN
52
+ * SCOPES · GROUPS · LIMITS · ROLES · TYPES · STEPS · WHEN · FIXES · CADENCES · FIX_LIMIT
34
53
  */
35
54
  const fs = require('fs');
36
55
  const path = require('path');
37
56
  const crypto = require('crypto');
38
57
 
39
58
  const LEDGER = 'metric-drafts.jsonl';
40
- const KINDS = new Set(['epoch', 'start', 'step', 'read', 'row', 'end', 'keep', 'drop', 'undo', 'edit']);
59
+ const KINDS = new Set(['epoch', 'start', 'step', 'read', 'row', 'end', 'keep', 'drop', 'undo', 'edit', 'fix', 'clear']);
41
60
  const SCOPES = ['product', 'program', 'initiative'];
42
61
  const GROUPS = { product: ['North Star', 'Inputs', 'Guardrails', 'Key results'], program: ['Program goal', 'Rolls up from', 'Guardrail'], initiative: ['Proves it worked', 'Early signal', 'Guardrail'] };
43
62
  const LIMITS = { 'North Star': 1, Inputs: 3, Guardrails: 2, 'Key results': 5, 'Program goal': 1, 'Rolls up from': 8, Guardrail: 1, 'Proves it worked': 1, 'Early signal': 1 };
@@ -50,13 +69,18 @@ const TYPES = ['Count', 'Percentage', 'Amount', 'Duration', 'Done or not', 'Stay
50
69
  const UNIT_OF = { Percentage: '%', Duration: 'days', Amount: '$', Count: '' };
51
70
  const STEPS = ['read', 'shape', 'measure', 'target', 'ready'];
52
71
  const READ_STATES = ['done', 'now', 'wait'];
53
- const WHYS = ['north-star', 'quarter', 'goal', 'success', 'press'];
72
+ const WHYS = ['north-star', 'quarter', 'goal', 'success', 'review', 'press'];
73
+ const FIXES = ['outcome', 'connect', 'recipe', 'chase', 'ticket', 'next-quarter', 'carry', 'owner'];
74
+ const CADENCES = ['daily', 'weekly', 'monthly'];
75
+ const FIX_LIMIT = 12; // fix rows one run may file
76
+ const ACT = { outcome: 'Keep', 'next-quarter': 'Keep', recipe: 'Keep', carry: 'Keep', owner: 'Keep', chase: 'Send', ticket: 'Send to Jira' };
54
77
  /** The "when" line of each trigger, as the page says it. */
55
78
  const WHEN = {
56
79
  'north-star': 'A product was connected with no North Star',
57
80
  quarter: 'A new quarter started',
58
81
  goal: 'The program charter has no goal',
59
82
  success: 'The initiative has a PRD and no success measure',
83
+ review: 'Some goals have no metric, or no way to read them',
60
84
  press: 'You asked me to draft again',
61
85
  };
62
86
  const WINDOW = '4 weeks after release';
@@ -138,14 +162,77 @@ function clean(scope, input) {
138
162
  return { row };
139
163
  }
140
164
 
165
+ /* ── 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 };
167
+ /** → { row } | { error }. id is the scope's id, for the row's id. */
168
+ function cleanFix(scope, id, input) {
169
+ if (!SCOPES.includes(scope)) return { error: 'scope is one of ' + SCOPES.join(', ') };
170
+ if (!isObj(input)) return { error: 'a fix is a JSON object' };
171
+ const kind = str(input.kind);
172
+ if (!FIXES.includes(kind)) return { error: 'kind is one of: ' + FIXES.join(', ') };
173
+ const text = one(input.text, FLIM.text), why = one(input.why, FLIM.why), goal = one(input.goal, FLIM.goal) || null;
174
+ if (!text) return { error: 'text is the fix in one line, as the PM reads it' };
175
+ if (!why) return { error: 'why is the evidence, in one line' };
176
+ const row = { kind, goal, text, why };
177
+ const old = one(input.old, FLIM.old); if (old) row.old = old;
178
+ let key = '';
179
+ if (kind === 'outcome' || kind === 'next-quarter') {
180
+ if (kind === 'outcome' && (!goal || !old)) return { error: 'an outcome names its goal (the KR) and its old, project-shaped title (old)' };
181
+ const m = clean(scope, { ...(isObj(input.metric) ? input.metric : {}), group: 'Key results' });
182
+ if (m.error) return { error: 'metric: ' + m.error };
183
+ row.metric = m.row; key = m.row.name.toLowerCase();
184
+ if (input.recipe != null) { const r = recipeOf(input.recipe); if (r.error) return r; row.recipe = r.recipe; }
185
+ } else if (kind === 'connect') {
186
+ const c = one(input.connector, FLIM.connector); if (!c) return { error: 'connector names the source to connect (Amplitude, Jira, …)' };
187
+ row.connector = c; key = c.toLowerCase();
188
+ } else {
189
+ if (!goal) return { error: 'goal is the id of the goal (its kr-metrics record) this fix repairs' };
190
+ if (kind === 'recipe') { const r = recipeOf(input.recipe); if (r.error) return r; row.recipe = r.recipe; key = r.recipe.connector.toLowerCase(); }
191
+ else if (kind === 'chase') {
192
+ const to = one(input.to, FLIM.to), body = one(input.body, FLIM.body);
193
+ if (!to || !body) return { error: 'a chase is { to: the owner, body: the note }' };
194
+ Object.assign(row, { to, body, channel: input.channel === 'jira-write' ? 'jira-write' : 'team-note' });
195
+ if (row.channel === 'jira-write') { const e = one(input.epic, FLIM.project); if (!e) return { error: 'a chase on Jira names its epic' }; row.epic = e; }
196
+ key = to.toLowerCase();
197
+ } else if (kind === 'ticket') {
198
+ const t = isObj(input.ticket) ? input.ticket : {}, title = one(t.title, FLIM.title), tx = one(t.text, FLIM.body);
199
+ if (!title || !tx) return { error: 'ticket is { title, text, project? }' };
200
+ row.ticket = { title, text: tx }; const pj = one(t.project, FLIM.project); if (pj) row.ticket.project = pj;
201
+ key = title.toLowerCase();
202
+ } else if (kind === 'carry') {
203
+ const by = str(input.by); if (!DAY_RE.test(by)) return { error: 'by is the new date, YYYY-MM-DD' };
204
+ row.by = by; if (input.target != null) { if (!fin(input.target)) return { error: 'target is a number' }; row.target = input.target; }
205
+ } else if (kind === 'owner') {
206
+ const o = isObj(input.owner) ? input.owner : {}, name = one(o.name, FLIM.to);
207
+ if (!name) return { error: 'owner is { name, from: jira | pm }' };
208
+ row.owner = { name, from: o.from === 'pm' ? 'pm' : 'jira' }; key = name.toLowerCase();
209
+ }
210
+ }
211
+ row.act = one(input.act, FLIM.act) || (kind === 'connect' ? 'Connect ' + row.connector : ACT[kind]);
212
+ row.id = 'fx-' + hash([scope, id, kind, goal || '', key].join('|'));
213
+ return { row };
214
+ }
215
+ function recipeOf(r) {
216
+ 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;
218
+ if (!connector || !query) return { error: 'a recipe names its connector and its query' };
219
+ if (!cadence) return { error: 'cadence is one of ' + CADENCES.join(', ') };
220
+ return { recipe: { connector, query, cadence } };
221
+ }
222
+
141
223
  /* ── 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
142
224
  * 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
143
225
  * number in it is replaced. ── */
144
- const EDIT_KEYS = ['name', 'target', 'targetTxt', 'source'];
226
+ const EDIT_KEYS = ['name', 'target', 'targetTxt', 'source', 'text', 'body'];
145
227
  function editOf(row, input) {
146
228
  if (!isObj(row)) return { error: 'There is no such draft.' };
147
229
  if (!isObj(input)) return { error: 'An edit is { name?, target?, source? }.' };
148
230
  const set = {};
231
+ if (row.kind && row.kind !== 'metric') { // a fix row: its line, and a chase's note (the rest is Claude's evidence)
232
+ if (input.text !== undefined) { const t = one(input.text, FLIM.text); if (!t) return { error: 'The line says the fix.' }; if (t !== row.text) set.text = t; }
233
+ if (input.body !== undefined && row.kind === 'chase') { const b = one(input.body, FLIM.body); if (!b) return { error: 'The note has words in it.' }; if (b !== row.body) set.body = b; }
234
+ return { set };
235
+ }
149
236
  if (input.name !== undefined) { const n = one(input.name, LIM.name); if (!n) return { error: 'The name is the metric, in a few words.' }; if (n !== row.name) set.name = n; }
150
237
  if (input.target !== undefined && row.type !== 'Done or not') {
151
238
  const t = typeof input.target === 'string' && input.target.trim() !== '' ? Number(input.target.replace(/[,\s]/g, '')) : input.target;
@@ -177,11 +264,11 @@ function fold(lines) {
177
264
  if (!SCOPES.includes(l.scope) || !str(l.id)) continue;
178
265
  const s = S(l), cur = s.run && s.run.run === l.run ? s.run : null;
179
266
  if (l.kind === 'start' && str(l.run)) {
180
- s.run = { run: l.run, why: WHYS.includes(l.why) ? l.why : 'press', at: str(l.at), step: 0, reads: [], ended: false, ok: null, stopped: false, error: '' };
267
+ s.run = { run: l.run, why: WHYS.includes(l.why) ? l.why : 'press', at: str(l.at), step: 0, reads: [], ended: false, ok: null, stopped: false, error: '', gaps: str(l.gaps) };
181
268
  s.runs.push(s.run);
182
269
  s.title = one(l.title, 140) || s.title || l.id; s.when = one(l.when, 140) || WHEN[s.run.why] || '';
183
270
  s.head = ''; s.sub = ''; s.src = '';
184
- for (const [rid, r] of s.rows) if (r.state !== 'kept') s.rows.delete(rid);
271
+ for (const [rid, r] of s.rows) if (r.state !== 'kept' && !r.standing) s.rows.delete(rid);
185
272
  } else if (l.kind === 'step' && cur && !cur.ended) { const n = Number(l.step); if (Number.isInteger(n) && n >= 0 && n <= 4) cur.step = Math.max(cur.step, n); }
186
273
  else if (l.kind === 'read' && cur && !cur.ended && str(l.t)) {
187
274
  const r = { t: one(l.t, 60), f: one(l.f, 200), state: READ_STATES.includes(l.state) ? l.state : 'done' };
@@ -190,31 +277,44 @@ function fold(lines) {
190
277
  } else if (l.kind === 'row' && cur && !cur.ended && isObj(l.row) && str(l.row.id)) {
191
278
  const was = s.rows.get(l.row.id);
192
279
  if (was && was.state === 'kept') continue; // the PM kept it: a run never changes what the PM kept
193
- s.rows.set(l.row.id, { ...l.row, state: 'open', run: l.run, at: str(l.at) });
280
+ s.rows.set(l.row.id, { kind: 'metric', ...l.row, state: 'open', run: l.run, at: str(l.at) });
281
+ } else if (l.kind === 'fix' && isObj(l.row) && str(l.row.id)) {
282
+ const was = s.rows.get(l.row.id);
283
+ if (was && was.state !== 'open') continue; // kept or dropped: a standing fix is filed once; the PM's answer stands
284
+ s.rows.set(l.row.id, { ...l.row, state: 'open', run: null, standing: one(l.src, 20) || 'watch', at: str(l.at) });
285
+ } else if (l.kind === 'clear' && str(l.row)) {
286
+ const r = s.rows.get(l.row); if (r && r.state === 'open') s.rows.delete(l.row);
194
287
  } else if (l.kind === 'end' && cur && !cur.ended) {
195
288
  Object.assign(cur, { ended: true, ok: !!l.ok, stopped: !!l.stopped, error: one(l.error, 200), endAt: str(l.at) });
196
289
  if (cur.ok && !cur.stopped) cur.step = 4;
197
290
  if (str(l.head)) s.head = one(l.head, 200);
198
291
  if (str(l.sub)) s.sub = one(l.sub, 300);
199
292
  if (str(l.src)) s.src = one(l.src, 300);
200
- } else if (l.kind === 'keep' && str(l.row)) { const r = s.rows.get(l.row); if (r && r.state === 'open') Object.assign(r, { state: 'kept', rid: str(l.rid) || null }); }
293
+ } else if (l.kind === 'keep' && str(l.row)) {
294
+ const r = s.rows.get(l.row);
295
+ if (r && r.state === 'open') Object.assign(r, { state: 'kept', rid: str(l.rid) || null }, isObj(l.before) ? { before: l.before } : {}, str(l.outbox) ? { outbox: l.outbox } : {});
296
+ }
201
297
  else if (l.kind === 'edit' && str(l.row) && isObj(l.set)) { const r = s.rows.get(l.row); if (r && r.state === 'open') for (const k of EDIT_KEYS) if (l.set[k] !== undefined) r[k] = l.set[k]; }
202
298
  else if (l.kind === 'drop' && str(l.row)) { const r = s.rows.get(l.row); if (r && r.state === 'open') r.state = 'dropped'; }
203
- else if (l.kind === 'undo' && str(l.row)) { const r = s.rows.get(l.row); if (r && r.state !== 'open') { r.state = 'open'; delete r.rid; } }
299
+ else if (l.kind === 'undo' && str(l.row)) { const r = s.rows.get(l.row); if (r && r.state !== 'open') { r.state = 'open'; delete r.rid; delete r.before; delete r.outbox; } }
204
300
  }
205
301
  return { scopes, epoch };
206
302
  }
207
303
  /** How many rows of a group one run filed (the limits are per run). */
208
304
  function countIn(s, run, group) { let n = 0; if (s) for (const r of s.rows.values()) if (r.run === run && r.group === group) n++; return n; }
209
305
 
210
- const ROW_KEYS = ['id', 'group', 'name', 'type', 'now', 'nowTxt', 'target', 'targetTxt', 'by', 'why', 'source', 'ticket', 'checkpoints', 'state', 'rid', 'direction', 'unit', 'pillar'];
306
+ const ROW_KEYS = ['id', 'kind', 'goal', 'text', 'old', 'act', 'metric', 'recipe', 'connector', 'to', 'body', 'channel', 'epic', 'owner', 'standing', 'test',
307
+ 'group', 'name', 'type', 'now', 'nowTxt', 'target', 'targetTxt', 'by', 'why', 'source', 'ticket', 'checkpoints', 'state', 'rid', 'direction', 'unit', 'pillar'];
211
308
  /** The GET body (without ok). o: { off } (PMOS_METRIC_DRAFT=off). Zero is silence: no run and no row is run.state idle and rows []. */
212
309
  function viewOf(F, scope, id, o = {}) {
213
310
  const s = (F && F.scopes.get(keyOf(scope, id))) || blank(scope, id);
214
311
  const R = s.run, order = GROUPS[scope] || [];
215
- const rows = [...s.rows.values()].sort((a, b) => order.indexOf(a.group) - order.indexOf(b.group)).map((r) => {
312
+ const rank = (r) => (r.kind && r.kind !== 'metric' ? order.length + FIXES.indexOf(r.kind) : order.indexOf(r.group));
313
+ const rows = [...s.rows.values()].sort((a, b) => rank(a) - rank(b)).map((r) => {
216
314
  const out = {}; for (const k of ROW_KEYS) if (r[k] !== undefined) out[k] = r[k];
315
+ if (out.kind === undefined) out.kind = 'metric';
217
316
  if (out.ticket === undefined) out.ticket = null;
317
+ if (out.goal === undefined) out.goal = null;
218
318
  return out;
219
319
  });
220
320
  let state = 'idle';
@@ -258,4 +358,7 @@ function keepFields(scope, id, row, o = {}) {
258
358
  return { fields: f, reading: now != null && DAY_RE.test(String(o.today || '')) ? { at: o.today, value: now } : null };
259
359
  }
260
360
 
261
- module.exports = { LEDGER, SCOPES, GROUPS, LIMITS, ROLES, TYPES, STEPS, WHEN, WHYS, WINDOW, ledgerFile, readLines, read, append, fold, viewOf, clean, keepFields, editOf, rowId, keyOf, countIn };
361
+ /** How many fix rows one run filed. */
362
+ 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
+
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 };
@@ -0,0 +1,132 @@
1
+ 'use strict';
2
+ /* metric-read-runs.js — Claude's runs that read the goals by themselves (feedback batch 16 item 6, gap 1; lib/metric-reads.js holds the ledger).
3
+ *
4
+ * off(env) → true when PMOS_METRIC_READ=off (or 0, false, no)
5
+ * promptOf(skill, o) → the prompt of one run. o: { run, why, today, items: [{ rid, title, unit, recipe, test }] }
6
+ * create(deps) → { tick(opts), start({ ws, rids, why, now }), stop(run), active(), runOf(ws) }
7
+ *
8
+ * WHEN A RUN STARTS (headless kind `metric-read`, origin `metric-read:<ws>:<run>`):
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
+ * 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
12
+ * 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
+ * every 10 minutes, inside the day-check window. ■ Stop ends a run at once.
14
+ *
15
+ * WHAT THE RUN MAY DO (lib/headless.js kind `metric-read`): read through the PM's own connectors where the PM's Claude Code settings allow it, and
16
+ * file with `pmos metrics reading`, pinned by the server to this workspace, run and set of goals (PMOS_METRIC_READ_FILE, _RECORDS, _DRAFTS, _WS,
17
+ * _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
+ * 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
+ *
20
+ * deps: { workspaces(), isLead(w), stateDirFor(w), recordsDir(w), records(w) → [kr-metrics record], open(now), headlessOff(), env,
21
+ * promptFor(skillId), spawn(spec), spawnNow(spec), stop(session), afterRead(w, rids) (the alert check and the bell), warn(what, err),
22
+ * draftsFile(w) → the metric-drafts ledger, testItems(w, rids) → [{ rid, title, unit, recipe }] for drafted rows }
23
+ */
24
+ const crypto = require('crypto');
25
+ const MR = require('./metric-reads.js');
26
+
27
+ const flagOff = (v) => /^(off|0|false|no)$/i.test(String(v || '').trim());
28
+ const off = (env) => flagOff((env || process.env).PMOS_METRIC_READ);
29
+ const one = (s, n) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim().slice(0, n);
30
+ const MAX = 2;
31
+ const PER_RUN = 8;
32
+ const SCAN_MS = 10 * 60e3;
33
+ 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
+
35
+ 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`
38
+ + `- Today: ${o.today}\n- Read these goals, each with its own recipe:\n${lines.join('\n') || '- none'}\n\n`
39
+ + 'File with `pmos metrics reading` only (the server pins this run and these goals). Write no other record. Send nothing.';
40
+ }
41
+
42
+ function create(deps) {
43
+ const active = new Map(); // run → { ws, rids, dir, session, test }
44
+ const warn = deps.warn || (() => {});
45
+ const lastScan = new Map();
46
+
47
+ function ended(run, r, now = Date.now()) {
48
+ const a = active.get(run); if (!a) return;
49
+ active.delete(run);
50
+ const F = MR.read(a.dir), R = F.runs.get(run);
51
+ const ok = !!(r && !r.timedOut && !r.stopped && r.code === 0);
52
+ const at = new Date(now).toISOString();
53
+ // a goal this run did not file is said honestly: not read
54
+ 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)) {
56
+ 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
+ }
58
+ 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); } }
60
+ }
61
+
62
+ /** Start one run now. → { ok, run } | { ok: false, error, held? } */
63
+ function start({ ws, rids, why = 'press', now = Date.now() } = {}) {
64
+ 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
+ const w = (deps.workspaces() || []).find((x) => x.id === ws);
66
+ if (!w) return { ok: false, error: 'no such workspace' };
67
+ const dir = deps.stateDirFor(w);
68
+ if (!dir) return { ok: false, error: 'This repository has no PMOS state folder, so nothing can be read.' };
69
+ 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
+ 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';
72
+ let items = [];
73
+ if (test) { try { items = (deps.testItems && deps.testItems(w, rids)) || []; } catch { items = []; } }
74
+ else {
75
+ let recs = []; try { recs = deps.records(w) || []; } catch (e) { warn('metric read records', e); }
76
+ 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
+ }
78
+ items = items.filter((x) => x && x.recipe && x.recipe.connector && x.recipe.query).slice(0, PER_RUN);
79
+ 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
+ const skill = deps.promptFor('metric-read');
81
+ if (!skill) return { ok: false, error: 'The metric-read skill is not installed.' };
82
+ const run = 'mr' + now.toString(36) + crypto.randomBytes(3).toString('hex');
83
+ const ids = items.map((x) => x.rid);
84
+ const prompt = promptOf(skill, { run, why, today: localDay(now), items });
85
+ const go = why !== 'due' && deps.spawnNow ? deps.spawnNow : deps.spawn;
86
+ active.set(run, { ws, w, rids: ids, dir, session: null, test });
87
+ let session = null;
88
+ try {
89
+ session = go({ name: 'Reading goals · ' + one(w.name || ws, 60), ws, origin: `metric-read:${ws}:${run}`, initialInput: prompt + '\r',
90
+ env: { PMOS_METRIC_READ_FILE: MR.ledgerFile(dir), PMOS_METRIC_READ_RECORDS: deps.recordsDir(w), PMOS_METRIC_READ_DRAFTS: (deps.draftsFile && deps.draftsFile(w)) || '',
91
+ PMOS_METRIC_READ_WS: ws, PMOS_METRIC_READ_RUN: run, PMOS_METRIC_READ_RIDS: ids.join(','), PMOS_METRIC_READ_TEST: test ? '1' : '' }, onDone: (r) => ended(run, r) });
92
+ } catch (e) { warn('metric read run', e); }
93
+ if (session && session.held) { active.delete(run); return { ok: false, held: true, error: 'Claude is busy with other runs. It tries again in a minute.' }; }
94
+ // the start line lands before the run's first `pmos metrics reading` (the run starts reading after this returns)
95
+ MR.append(dir, null, { kind: 'start', run, ws, rids: ids, why }, new Date(now).toISOString());
96
+ if (!session || session.state === 'exited' || session.headless !== 'metric-read') {
97
+ if (session && session.headless !== 'metric-read' && session.state !== 'exited' && deps.stop) { try { deps.stop(session); } catch { /* best effort */ } }
98
+ ended(run, { code: 1, note: (session && session.note) || 'the run could not start in the background' }, now);
99
+ return { ok: false, error: (session && session.note) || 'Claude could not start reading.' };
100
+ }
101
+ const a = active.get(run); if (a) a.session = session;
102
+ return { ok: true, run, rids: ids };
103
+ }
104
+
105
+ function stop(run) { const a = active.get(run); if (a && a.session && deps.stop) deps.stop(a.session); }
106
+
107
+ function tick({ now = Date.now(), env } = {}) {
108
+ if (off(env || deps.env) || (deps.headlessOff && deps.headlessOff())) return { off: true };
109
+ if (active.size >= MAX) return { running: active.size };
110
+ let open = true;
111
+ try { open = deps.open ? !!deps.open(now) : true; } catch { open = true; }
112
+ if (!open) return { started: null, closed: true };
113
+ const day = localDay(now);
114
+ for (const w of deps.workspaces() || []) {
115
+ if (deps.isLead && !deps.isLead(w)) continue;
116
+ if (now - (lastScan.get(w.id) || -Infinity) < SCAN_MS) continue;
117
+ const dir = deps.stateDirFor(w); if (!dir) continue;
118
+ lastScan.set(w.id, now);
119
+ 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);
121
+ if (!due.length) continue;
122
+ const r = start({ ws: w.id, rids: due.slice(0, PER_RUN), why: 'due', now });
123
+ if (r.ok) return { started: w.id, rids: r.rids };
124
+ if (r.held) { lastScan.delete(w.id); return { held: true }; }
125
+ }
126
+ return { started: null };
127
+ }
128
+
129
+ return { tick, start, stop, active: () => [...active.keys()], runOf: (ws) => { for (const [r, a] of active) if (a.ws === ws) return r; return null; } };
130
+ }
131
+
132
+ module.exports = { off, promptOf, create, MAX, PER_RUN, SCAN_MS };
@@ -0,0 +1,129 @@
1
+ 'use strict';
2
+ /* metric-reads.js — how Claude reads the goals by itself (feedback batch 16 item 6, "Claude runs the OKRs", gaps 1 and 7). THE ONE WRITER and THE
3
+ * ONE FOLD of <state>/metric-reads.jsonl. lib/metric-read-runs.js starts the runs; `pmos metrics reading` (lib/metrics-cli.js) is what a run
4
+ * files with; lib/routes-goal-status.js reads it. Pure apart from the ledger file, with no clock of its own: every time comes in.
5
+ *
6
+ * A RECIPE is on the kr-metrics record: recipe = { connector, query, cadence: daily | weekly | monthly }. A reading run reads each due recipe through
7
+ * the PM's own Claude Code connectors and files the value with its source and time (the reading lands on the record, scripts/records addReading,
8
+ * with source, via run and read_at). A source it cannot read is said honestly (a `cant` line) and comes with a drafted fix (a standing connect or
9
+ * recipe row in lib/metric-drafts.js). A CSV or sheet export is the fallback when no connector reads it (parseCsv).
10
+ *
11
+ * THE LEDGER. One line per event, { at, by, kind, ... }:
12
+ * start { run, ws, rids, why } a run began; why ∈ due · test · press. A test run reads a drafted row (rid = its row id) before the PM keeps it
13
+ * read { run, rid, value, day, source, test? } one value read (a test read lands here only, never on a record)
14
+ * cant { run, rid, why, fix? } the run could not read it; fix is the drafted row's id
15
+ * end { run, ok, error? }
16
+ * broke { rid, day, value, limit } a limit goal went over its limit: ONE push (the episode is open)
17
+ * back { rid, day, value } the limit goal is back within it: one closing line (the episode closes)
18
+ *
19
+ * ledgerFile(dir) · readLines(file) · read(dir) · append(dir, actor, line, at)
20
+ * fold(lines) PURE → { rids: Map rid → R, runs: Map run → { run, ws, rids, why, at, ended, ok, error } }
21
+ * R: { last: { at, ok, error?, value?, source? } | null, tried: day of the last try, test: { at, ok, value?, source?, error? } | null,
22
+ * alert: { open, day, value, limit } | null, alerts: [{ kind, day, value }] }
23
+ * lastOf(F, rid) → R.last, the recipe's `last` on the page
24
+ * dueOf(records, F, today) PURE → [rid] live records with a recipe whose cadence has passed since the last try, none of them in a running run
25
+ * alertStep(F, rid, reading) PURE → { kind: 'broke' | 'back', … } | null what to append after a reading (lib/goal-status.js readingOf)
26
+ * parseCsv(text) → { rows: [{ at, value }] } | { error } two columns: a date and a number; a header line is skipped
27
+ * CADENCE_GAP days between two tries of a cadence (daily 1, weekly 7, monthly 30)
28
+ */
29
+ const fs = require('fs');
30
+ const path = require('path');
31
+
32
+ const LEDGER = 'metric-reads.jsonl';
33
+ const KINDS = new Set(['start', 'read', 'cant', 'end', 'broke', 'back']);
34
+ const WHYS = ['due', 'test', 'press'];
35
+ const CADENCE_GAP = Object.freeze({ daily: 1, weekly: 7, monthly: 30 });
36
+ const DAY_RE = /^\d{4}-\d{2}-\d{2}$/;
37
+ const DAY = 864e5;
38
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
39
+ const str = (v) => (typeof v === 'string' ? v : '');
40
+ const one = (v, n) => String(v == null ? '' : v).replace(/\s+/g, ' ').trim().slice(0, n);
41
+ const fin = (v) => typeof v === 'number' && Number.isFinite(v);
42
+ const ms = (v) => { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(v || '')); return m ? Date.UTC(+m[1], +m[2] - 1, +m[3]) : null; };
43
+
44
+ function ledgerFile(dir) { return dir ? path.join(dir, LEDGER) : null; }
45
+ function readLines(file) {
46
+ if (!file) return [];
47
+ let text = '';
48
+ try { text = fs.readFileSync(file, 'utf8'); } catch { return []; }
49
+ const out = [];
50
+ for (const raw of text.split('\n')) { if (!raw.trim()) continue; try { const l = JSON.parse(raw); if (isObj(l) && KINDS.has(l.kind)) out.push(l); } catch { /* a torn line is skipped */ } }
51
+ return out;
52
+ }
53
+ function append(dir, actor, ev, at) {
54
+ const line = { at: at || null, by: (actor && actor.by) || null, ...ev };
55
+ fs.mkdirSync(dir, { recursive: true });
56
+ fs.appendFileSync(ledgerFile(dir), JSON.stringify(line) + '\n');
57
+ return line;
58
+ }
59
+
60
+ function fold(lines) {
61
+ const rids = new Map(), runs = new Map();
62
+ const R = (rid) => { if (!rids.has(rid)) rids.set(rid, { last: null, tried: null, test: null, alert: null, alerts: [] }); return rids.get(rid); };
63
+ for (const l of lines || []) {
64
+ if (!isObj(l) || !KINDS.has(l.kind)) continue;
65
+ const at = str(l.at);
66
+ if (l.kind === 'start' && str(l.run)) { runs.set(l.run, { run: l.run, ws: str(l.ws), rids: Array.isArray(l.rids) ? l.rids.map(String) : [], why: WHYS.includes(l.why) ? l.why : 'due', at, ended: false, ok: null, error: '' }); continue; }
67
+ if (l.kind === 'end' && str(l.run)) { const r = runs.get(l.run); if (r && !r.ended) Object.assign(r, { ended: true, ok: !!l.ok, error: one(l.error, 200), endAt: at }); continue; }
68
+ if (!str(l.rid)) continue;
69
+ const x = R(l.rid), run = runs.get(str(l.run));
70
+ if (l.kind === 'read' && fin(l.value)) {
71
+ const v = { at, ok: true, value: l.value, day: DAY_RE.test(str(l.day)) ? l.day : at.slice(0, 10), source: one(l.source, 200) };
72
+ if (l.test) x.test = v; else { x.last = v; x.tried = at.slice(0, 10); }
73
+ } else if (l.kind === 'cant') {
74
+ const v = { at, ok: false, error: one(l.why, 200), ...(str(l.fix) ? { fix: l.fix } : {}) };
75
+ if (l.test || (run && run.why === 'test')) x.test = v; else { x.last = v; x.tried = at.slice(0, 10); }
76
+ } else if (l.kind === 'broke') { x.alert = { open: true, day: str(l.day), value: l.value, limit: l.limit, at }; x.alerts.push({ kind: 'broke', day: str(l.day), value: l.value, at }); }
77
+ else if (l.kind === 'back') { if (x.alert) x.alert = { ...x.alert, open: false, backDay: str(l.day), backValue: l.value }; x.alerts.push({ kind: 'back', day: str(l.day), value: l.value, at }); }
78
+ }
79
+ return { rids, runs };
80
+ }
81
+ function read(dir) { return fold(readLines(ledgerFile(dir))); }
82
+ const lastOf = (F, rid) => { const x = F && F.rids.get(rid); return x && x.last ? { at: x.last.at, ok: x.last.ok, ...(x.last.ok ? {} : { error: x.last.error }) } : null; };
83
+
84
+ /** The records a reading run reads now. A try that failed counts as a try: the next one is a cadence later, so a broken source is not hammered. */
85
+ function dueOf(records, F, today) {
86
+ const t = ms(today); if (t === null) return [];
87
+ const busy = new Set(); for (const r of (F && F.runs.values()) || []) if (!r.ended) for (const id of r.rids) busy.add(id);
88
+ const out = [];
89
+ for (const rec of records || []) {
90
+ if (!rec || rec.retired === true || !isObj(rec.recipe) || busy.has(rec.rid)) continue;
91
+ const gap = CADENCE_GAP[rec.recipe.cadence]; if (!gap) continue;
92
+ const x = F && F.rids.get(rec.rid);
93
+ const lastDay = [x && x.tried, ...((rec.readings || []).map((r) => String(r.at || '').slice(0, 10)))].filter((d) => DAY_RE.test(d || '')).sort().pop();
94
+ if (!lastDay || (t - ms(lastDay)) / DAY >= gap) out.push(rec.rid);
95
+ }
96
+ return out;
97
+ }
98
+
99
+ /** After a reading of a limit goal: open an episode when it breaks (one push), close it when it is back. reading: lib/goal-status.js readingOf. */
100
+ function alertStep(F, rid, reading) {
101
+ const x = F && F.rids.get(rid), open = !!(x && x.alert && x.alert.open);
102
+ if (!reading || !reading.at) return null;
103
+ if (reading.dot === 'broken' && !open) return { kind: 'broke', rid, day: reading.at, value: reading.value, limit: reading.limit };
104
+ if (reading.dot !== 'broken' && reading.dot !== 'none' && open) return { kind: 'back', rid, day: reading.at, value: reading.value };
105
+ return null;
106
+ }
107
+
108
+ /** A CSV or sheet export: a date and a number on each line. "2026-10-21,61.2" · "2026-10-21;61,2" · a header line and blank lines are skipped. */
109
+ function parseCsv(text) {
110
+ const rows = [], bad = [];
111
+ const lines = String(text || '').split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
112
+ if (!lines.length) return { error: 'The file is empty.' };
113
+ if (lines.length > 400) return { error: 'The file has more than 400 lines. Export the last year or less.' };
114
+ lines.forEach((l, i) => {
115
+ const sep = l.includes('\t') ? '\t' : l.includes(';') ? ';' : ',';
116
+ const [a, b] = l.split(sep).map((c) => c.trim().replace(/^"|"$/g, ''));
117
+ const day = /^\d{4}-\d{2}-\d{2}/.test(a || '') ? a.slice(0, 10) : null;
118
+ const v = b == null ? NaN : Number(sep === ';' ? b.replace(/\./g, '').replace(',', '.') : b.replace(/[,%\s]/g, ''));
119
+ if (!day || ms(day) === null || !fin(v)) { if (i > 0 || day) bad.push(i + 1); return; }
120
+ rows.push({ at: day, value: v });
121
+ });
122
+ if (bad.length) return { error: 'Line ' + bad.slice(0, 3).join(', ') + ' does not hold a date (YYYY-MM-DD) and a number.' };
123
+ if (!rows.length) return { error: 'No line holds a date (YYYY-MM-DD) and a number.' };
124
+ const seen = new Set(), out = [];
125
+ for (const r of rows.sort((a, b) => a.at.localeCompare(b.at))) { if (seen.has(r.at)) continue; seen.add(r.at); out.push(r); }
126
+ return { rows: out };
127
+ }
128
+
129
+ module.exports = { LEDGER, WHYS, CADENCE_GAP, ledgerFile, readLines, read, append, fold, lastOf, dueOf, alertStep, parseCsv };