create-pmos 0.441.0 → 0.443.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 (87) 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/adler-seasons-art-test.js +106 -0
  7. package/workspace/adler-seasons-test.js +111 -0
  8. package/workspace/briefing-premium-board-test.js +19 -17
  9. package/workspace/briefing-premium-initiative-test.js +7 -4
  10. package/workspace/changelog.json +24 -0
  11. package/workspace/goals-clear-ui-test.js +249 -0
  12. package/workspace/guide/adler.md +10 -0
  13. package/workspace/guide/home.md +8 -1
  14. package/workspace/guide/metric-drafts.md +8 -2
  15. package/workspace/home-railcard-test.js +193 -0
  16. package/workspace/ini-workflow-test.js +6 -2
  17. package/workspace/intelligence-gaps-ui-test.js +16 -14
  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-goal-status.js +89 -6
  26. package/workspace/lib/routes-insights-premium.js +1 -1
  27. package/workspace/lib/routes-metric-drafts.js +26 -3
  28. package/workspace/lib/settings-store.js +38 -0
  29. package/workspace/metric-drafts-ui-test.js +7 -4
  30. package/workspace/okr-goals-ui-test.js +7 -5
  31. package/workspace/package-lock.json +2 -2
  32. package/workspace/package.json +1 -1
  33. package/workspace/premium-board-actions-test.js +2 -1
  34. package/workspace/premium-chat-attach-test.js +2 -0
  35. package/workspace/program-panel-test.js +1 -1
  36. package/workspace/public/pm/bd-ini-panel.js +2 -2
  37. package/workspace/public/pm/c3-ini-ui.js +1 -1
  38. package/workspace/public/pm/cozy-adler.css +21 -0
  39. package/workspace/public/pm/cozy-adler.js +415 -8
  40. package/workspace/public/pm/cozy-ev.css +16 -1
  41. package/workspace/public/pm/cozy-home.css +8 -0
  42. package/workspace/public/pm/cozy-insights.css +82 -0
  43. package/workspace/public/pm/cozy-live-pill.css +5 -0
  44. package/workspace/public/pm/cozy-news.js +1 -1
  45. package/workspace/public/pm/cozy-seasons.js +318 -0
  46. package/workspace/public/pm/cozy-settings.js +88 -5
  47. package/workspace/public/pm/cozy-today.css +15 -0
  48. package/workspace/public/pm/cozy-viewer.js +50 -18
  49. package/workspace/public/pm/cozy-vw-shell.css +4 -0
  50. package/workspace/public/pm/cozy.css +65 -0
  51. package/workspace/public/pm/dash-view.js +4 -2
  52. package/workspace/public/pm/goals-clear.js +258 -0
  53. package/workspace/public/pm/home-app.js +59 -5
  54. package/workspace/public/pm/home-chat.js +1 -1
  55. package/workspace/public/pm/home-day.js +7 -4
  56. package/workspace/public/pm/home-ini.js +2 -2
  57. package/workspace/public/pm/home-mentions.js +1 -1
  58. package/workspace/public/pm/home-today.js +51 -10
  59. package/workspace/public/pm/impact.js +1 -1
  60. package/workspace/public/pm/ini-groups.js +28 -17
  61. package/workspace/public/pm/ini-links.js +1 -1
  62. package/workspace/public/pm/ini-tasks.js +246 -48
  63. package/workspace/public/pm/ini-view-model.js +45 -16
  64. package/workspace/public/pm/ini-view.css +330 -1
  65. package/workspace/public/pm/ini-view.js +196 -83
  66. package/workspace/public/pm/metric-drafts.js +4 -1
  67. package/workspace/public/pm/mission.js +238 -0
  68. package/workspace/public/pm/premium-board.js +1 -1
  69. package/workspace/public/pm/premium-insights.js +178 -24
  70. package/workspace/public/pm/premium-welcome.js +2 -2
  71. package/workspace/public/pm/split-merge.js +1 -1
  72. package/workspace/public/pm/stage-line.js +2 -2
  73. package/workspace/server.js +6 -2
  74. package/workspace/skills/metric-read.skill +7 -5
  75. package/workspace/split-merge-ui-test.js +1 -1
  76. package/workspace/stage-card-test.js +56 -11
  77. package/workspace/task-links-test.js +2 -0
  78. package/workspace/task-milestones-test.js +5 -1
  79. package/workspace/task-plans-test.js +3 -3
  80. package/workspace/task-views-test.js +279 -37
  81. package/workspace/test-lists/adler-seasons-art.json +13 -0
  82. package/workspace/test-lists/batch18-adler-seasons.json +13 -0
  83. package/workspace/test-lists/goals-clear.json +15 -0
  84. package/workspace/test-lists/home-railcard.json +9 -0
  85. package/workspace/test-lists/mission.json +5 -0
  86. package/workspace/test-lists/viewer-tasks.json +5 -0
  87. package/workspace/tk-tasks-test.js +27 -32
@@ -3,14 +3,24 @@
3
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
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
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
6
+ * A RECIPE is on the kr-metrics record: recipe = { connector, query, cadence: hourly | daily | weekly | monthly, at?, day?, counts?, range? }
7
+ * (lib/metric-drafts.js recipeOf). A reading run reads each due recipe through
7
8
  * 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
9
  * 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
10
  * recipe row in lib/metric-drafts.js). A CSV or sheet export is the fallback when no connector reads it (parseCsv).
10
11
  *
11
12
  * 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)
13
+ * start { run, ws, rids, why } a run began; why ∈ due · test · press · compare. A test run reads a drafted row (rid = its row id) before the
14
+ * PM keeps it. A press (Read now) or compare run never moves the next scheduled read
15
+ * read { run, rid, value, day, source, num?, den?, segments?, period?, checks?, test? } one value read (a test read lands here only, never on a
16
+ * record). num and den are the two counts ("How it is counted"); segments [{ name, num, den }] its parts
17
+ * held { run, rid, value, day, source, num?, den?, segments?, period?, checks, why, ticket?, test? } batch 18 item 11: a value a check failed
18
+ * on. It is NOT on the record, so it never moves the dot, the line or "target reached"; ticket is the drafted
19
+ * Jira fix row
20
+ * filed { rid, held } the PM's "file it": the held reading (held = its at) went on the record after all
21
+ * compare { rid, value, period, ours, pct } the PM's own number for the goal (or a draft row), against Claude's
22
+ * reason { run?, rid, why, suggest?: { text, keep: mine | yours }, yours?: { what, query } } why the two differ (a segment, or a compare run)
23
+ * pick { rid, pick: mine | yours, before? } the PM's pick; yours rewrote counts.what and the query (before holds what they were)
14
24
  * cant { run, rid, why, fix? } the run could not read it; fix is the drafted row's id
15
25
  * end { run, ok, error? }
16
26
  * broke { rid, day, value, limit } a limit goal went over its limit: ONE push (the episode is open)
@@ -18,21 +28,38 @@
18
28
  *
19
29
  * ledgerFile(dir) · readLines(file) · read(dir) · append(dir, actor, line, at)
20
30
  * 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 }] }
31
+ * R: { last: { at, ok, error?, value?, source? } | null, tried: day of the last try, triedAt: time of the last scheduled try,
32
+ * good: the last good read | null, failed: { at, why, fix } | null, checks, held: [open held], test: { at, ok, value?, …,
33
+ * checks?, held? } | null, compare: { … } | null, alert: { open, day, value, limit } | null, alerts: [{ kind, day, value }] }
23
34
  * 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
35
+ * dueOf(records, F, now, o) PURE → [rid] live records with a recipe whose next scheduled read has come, none of them in a running run. now is a
36
+ * day (YYYY-MM-DD, its local midnight) or a time (ms). o: { only: 'hourly' | 'other', hours: { start, end } }
37
+ * nextAfter(recipe, after, hours) PURE → ms the first scheduled read after `after` (ms). Hourly is on the hour, inside the working hours
38
+ * nextReadOf(rec, F, now, hours) PURE → ISO | null when the goal is read next (never earlier than now)
39
+ * rhythmOf(recipe) PURE → { cadence, at, day, txt, short } | null "every Monday 07:00" / "Every Monday"
40
+ * checksOf(o) PURE → [{ id: zero | jump | den | range, ok, text }] Claude's checks on one value before it is drawn.
41
+ * o: { value, num?, den?, segments?, prior: [value], unit, type, range }
42
+ * compareView(F, rid, unit) PURE → the compare a page draws: { value, txt, period, ours, oursTxt, apart, pct, differs, state, why?, suggest?, yours?, pick? }
43
+ * heldWhy(checks) · compareOf(ours, yours) · segmentReason(last) · fmt(v, unit)
25
44
  * alertStep(F, rid, reading) PURE → { kind: 'broke' | 'back', … } | null what to append after a reading (lib/goal-status.js readingOf)
26
45
  * 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)
46
+ * CADENCE_GAP days between two tries of a cadence (hourly 1/24, daily 1, weekly 7, monthly 30)
47
+ * WORK_HOURS the working hours an hourly goal is read in, when the server gives none (the day-check window's default)
48
+ * MIN_DEN · DIFF_PCT the smallest count below a rate that is trusted (30); the share two numbers may differ by and be the same (2%)
28
49
  */
29
50
  const fs = require('fs');
30
51
  const path = require('path');
31
52
 
32
53
  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 });
54
+ const KINDS = new Set(['start', 'read', 'cant', 'end', 'broke', 'back', 'held', 'filed', 'compare', 'reason', 'pick']);
55
+ const WHYS = ['due', 'test', 'press', 'compare'];
56
+ const OFF_RHYTHM = new Set(['press', 'compare']); // a run the PM asked for: it never moves the next scheduled read
57
+ const CADENCE_GAP = Object.freeze({ hourly: 1 / 24, daily: 1, weekly: 7, monthly: 30 });
58
+ const WORK_HOURS = Object.freeze({ start: '09:00', end: '18:00' }); // lib/proactive.js DAY_CHECK_DEFAULT
59
+ const MIN_DEN = 30;
60
+ const DIFF_PCT = 2;
61
+ const JUMP = 3;
62
+ const HOUR = 36e5;
36
63
  const DAY_RE = /^\d{4}-\d{2}-\d{2}$/;
37
64
  const DAY = 864e5;
38
65
  const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
@@ -57,9 +84,20 @@ function append(dir, actor, ev, at) {
57
84
  return line;
58
85
  }
59
86
 
87
+ const segsOf = (v) => (Array.isArray(v) ? v.filter((x) => isObj(x) && str(x.name) && fin(x.num) && fin(x.den)).slice(0, 8).map((x) => ({ name: one(x.name, 40), num: x.num, den: x.den })) : []);
88
+ const checksIn = (v) => (Array.isArray(v) ? v.filter((c) => isObj(c) && str(c.id)).map((c) => ({ id: c.id, ok: !!c.ok, text: one(c.text, 200) })) : null);
89
+ /** What one read or held line says about the value: its counts, parts, period and checks. */
90
+ function valueOf(l, at) {
91
+ 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) };
92
+ if (fin(l.num)) v.num = l.num; if (fin(l.den)) v.den = l.den;
93
+ const sg = segsOf(l.segments); if (sg.length) v.segments = sg;
94
+ if (str(l.period)) v.period = one(l.period, 40);
95
+ const ch = checksIn(l.checks); if (ch) v.checks = ch;
96
+ return v;
97
+ }
60
98
  function fold(lines) {
61
99
  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); };
100
+ const R = (rid) => { if (!rids.has(rid)) rids.set(rid, { last: null, tried: null, triedAt: null, good: null, failed: null, checks: null, held: [], test: null, compare: null, alert: null, alerts: [] }); return rids.get(rid); };
63
101
  for (const l of lines || []) {
64
102
  if (!isObj(l) || !KINDS.has(l.kind)) continue;
65
103
  const at = str(l.at);
@@ -67,13 +105,28 @@ function fold(lines) {
67
105
  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
106
  if (!str(l.rid)) continue;
69
107
  const x = R(l.rid), run = runs.get(str(l.run));
108
+ const test = !!l.test || !!(run && run.why === 'test');
109
+ const tried = () => { x.tried = at.slice(0, 10); if (!(run && OFF_RHYTHM.has(run.why))) x.triedAt = at; };
70
110
  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); }
111
+ const v = valueOf(l, at);
112
+ if (test) x.test = v; else { x.last = v; x.good = v; x.failed = null; x.checks = v.checks || null; tried(); }
113
+ } else if (l.kind === 'held' && fin(l.value)) {
114
+ const v = { ...valueOf(l, at), why: one(l.why, 300), ...(str(l.ticket) ? { ticket: l.ticket } : {}) };
115
+ if (test) x.test = { ...v, held: true }; else { x.held = x.held.filter((h) => h.at !== at); x.held.push(v); x.failed = null; x.checks = v.checks || null; tried(); }
116
+ } else if (l.kind === 'filed' && str(l.held)) {
117
+ const h = x.held.find((y) => y.at === l.held);
118
+ if (h) { x.held = x.held.filter((y) => y !== h); const v = { ...h, filedAt: at }; delete v.why; delete v.ticket; if (!x.good || String(v.day) >= String(x.good.day)) { x.good = v; x.last = v; } }
73
119
  } else if (l.kind === 'cant') {
74
120
  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 }); }
121
+ if (test) x.test = v; else { x.last = v; x.failed = { at, why: v.error, ...(v.fix ? { fix: v.fix } : {}) }; tried(); }
122
+ } else if (l.kind === 'compare' && fin(l.value) && fin(l.ours)) {
123
+ x.compare = { at, value: l.value, period: one(l.period, 40), ours: l.ours, pct: fin(l.pct) ? l.pct : null, why: '', suggest: null, yours: null, pick: null };
124
+ } else if (l.kind === 'reason' && x.compare) {
125
+ if (str(l.why)) x.compare.why = one(l.why, 400);
126
+ if (isObj(l.suggest) && str(l.suggest.text)) x.compare.suggest = { text: one(l.suggest.text, 300), keep: l.suggest.keep === 'yours' ? 'yours' : 'mine' };
127
+ if (isObj(l.yours) && str(l.yours.what) && str(l.yours.query)) x.compare.yours = { what: one(l.yours.what, 300), query: String(l.yours.query).slice(0, 1200) };
128
+ } else if (l.kind === 'pick' && x.compare && (l.pick === 'mine' || l.pick === 'yours')) { x.compare.pick = l.pick; x.compare.pickAt = at; }
129
+ 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
130
  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
131
  }
79
132
  return { rids, runs };
@@ -81,20 +134,152 @@ function fold(lines) {
81
134
  function read(dir) { return fold(readLines(ledgerFile(dir))); }
82
135
  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
136
 
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 [];
137
+ /* ── the rhythm (batch 18 item 11): when a goal is read. Local time, as the PM lives it. ── */
138
+ const hmOf = (v) => { const m = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(String(v || '')); return m ? +m[1] * 60 + +m[2] : null; };
139
+ const WEEK = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
140
+ const DAY_NAME = { sun: 'Sunday', mon: 'Monday', tue: 'Tuesday', wed: 'Wednesday', thu: 'Thursday', fri: 'Friday', sat: 'Saturday' };
141
+ const localMs = (v) => { // a day is its local midnight; an ISO time or ms is itself
142
+ if (fin(v)) return v;
143
+ const s = String(v || ''), m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s);
144
+ if (m) return new Date(+m[1], +m[2] - 1, +m[3]).getTime();
145
+ const t = Date.parse(s); return Number.isFinite(t) ? t : null;
146
+ };
147
+ const at0 = (ms, min) => { const d = new Date(ms); d.setHours(0, 0, 0, 0); d.setMinutes(min || 0); return d.getTime(); };
148
+ const plusDays = (ms, n, min) => { const d = new Date(ms); d.setHours(0, 0, 0, 0); d.setDate(d.getDate() + n); d.setMinutes(min || 0); return d.getTime(); };
149
+
150
+ /** The first scheduled read strictly after `after` (ms). */
151
+ function nextAfter(recipe, after, hours = WORK_HOURS) {
152
+ const c = recipe && recipe.cadence, at = hmOf(recipe && recipe.at);
153
+ if (!fin(after)) return null;
154
+ if (c === 'hourly') {
155
+ const s = hmOf(hours && hours.start), e = hmOf(hours && hours.end);
156
+ let t = Math.floor(after / HOUR) * HOUR + HOUR;
157
+ for (let i = 0; i < 24 * 8; i++, t += HOUR) { const d = new Date(t), m = d.getHours() * 60 + d.getMinutes(); if (s === null || e === null || (m >= s && m < e)) return t; }
158
+ return null;
159
+ }
160
+ if (c === 'daily') { let t = at0(after, at || 0); if (t <= after) t = plusDays(after, 1, at || 0); return t; }
161
+ if (c === 'weekly') {
162
+ if (!WEEK.includes(recipe.day)) return plusDays(after, 7, at || 0); // no day: a week after the last try (as before)
163
+ for (let i = 0; i <= 7; i++) { const t = plusDays(after, i, at === null ? 0 : at); if (t > after && WEEK[new Date(t).getDay()] === recipe.day) return t; }
164
+ return null;
165
+ }
166
+ if (c === 'monthly') {
167
+ if (at === null) return plusDays(after, 30, 0); // no time: thirty days after the last try (as before)
168
+ const d = new Date(after), first = (y, mo) => new Date(y, mo, 1, 0, at).getTime();
169
+ const t = first(d.getFullYear(), d.getMonth()); return t > after ? t : first(d.getFullYear(), d.getMonth() + 1);
170
+ }
171
+ return null;
172
+ }
173
+ /** The last scheduled try: the ledger's (not a Read now) or a reading on the record (not one a Read now filed). */
174
+ function lastTryOf(rec, x) {
175
+ const ts = [];
176
+ if (x && x.triedAt) { const t = localMs(x.triedAt); if (t !== null) ts.push(t); }
177
+ for (const r of (rec && rec.readings) || []) {
178
+ if (!r || r.via === 'press') continue;
179
+ const t = r.read_at ? localMs(r.read_at) : localMs(String(r.at || '').slice(0, 10));
180
+ if (t !== null) ts.push(t);
181
+ }
182
+ return ts.length ? Math.max(...ts) : null;
183
+ }
184
+ /** The records a reading run reads now. A try that failed counts as a try: the next one is a rhythm later, so a broken source is not hammered.
185
+ * A Read now does not count: the scheduled read stays where it was. */
186
+ function dueOf(records, F, now, o = {}) {
187
+ const t = localMs(now); if (t === null) return [];
87
188
  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
189
  const out = [];
89
190
  for (const rec of records || []) {
90
191
  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);
192
+ const c = rec.recipe.cadence; if (!CADENCE_GAP[c]) continue;
193
+ if (o.only === 'hourly' && c !== 'hourly') continue;
194
+ if (o.only === 'other' && c === 'hourly') continue;
195
+ const last = lastTryOf(rec, F && F.rids.get(rec.rid));
196
+ if (last === null) { out.push(rec.rid); continue; }
197
+ const next = nextAfter(rec.recipe, last, o.hours || WORK_HOURS);
198
+ if (next !== null && t >= next) out.push(rec.rid);
95
199
  }
96
200
  return out;
97
201
  }
202
+ /** When the goal is read next: its next scheduled read, never earlier than now (an overdue read happens at the next tick). */
203
+ function nextReadOf(rec, F, now, hours = WORK_HOURS) {
204
+ if (!rec || !isObj(rec.recipe) || !CADENCE_GAP[rec.recipe.cadence]) return null;
205
+ const t = localMs(now); if (t === null) return null;
206
+ const last = lastTryOf(rec, F && F.rids.get(rec.rid));
207
+ let next = last === null ? t : nextAfter(rec.recipe, last, hours);
208
+ if (next === null) return null;
209
+ if (next < t) next = rec.recipe.cadence === 'hourly' ? (nextAfter(rec.recipe, t - 1, hours) || t) : t;
210
+ return new Date(next).toISOString();
211
+ }
212
+ /** How the page says the rhythm: txt for the panel and the Kept toast, short for the table column. */
213
+ function rhythmOf(recipe) {
214
+ if (!isObj(recipe) || !CADENCE_GAP[recipe.cadence]) return null;
215
+ const c = recipe.cadence, at = hmOf(recipe.at) !== null ? recipe.at : null, day = c === 'weekly' && WEEK.includes(recipe.day) ? recipe.day : null;
216
+ const tail = at ? ' ' + at : '';
217
+ let txt, short;
218
+ if (c === 'hourly') { txt = 'every hour in working hours'; short = 'Every hour'; }
219
+ else if (c === 'daily') { txt = 'every day' + tail; short = 'Every day'; }
220
+ else if (c === 'weekly') { txt = day ? 'every ' + DAY_NAME[day] + tail : 'every week'; short = day ? 'Every ' + DAY_NAME[day] : 'Every week'; }
221
+ else { txt = at ? 'on the 1st of each month' + tail : 'every month'; short = 'Every month'; }
222
+ return { cadence: c, at: c === 'hourly' ? null : at, day, txt, short };
223
+ }
224
+
225
+ /* ── Claude's checks on every reading (batch 18 item 11). A failed check holds the reading: it is filed as `held`, never on the record. ── */
226
+ const fmt = (v, unit) => { if (!fin(v)) return ''; const r = Math.abs(v) >= 100 ? Math.round(v) : Math.round(v * 10) / 10, s = Math.abs(r) >= 1000 ? r.toLocaleString('en-US') : String(r), u = String(unit || '').trim(); return u ? (/^[A-Za-z]/.test(u) ? s + ' ' + u : s + u) : s; };
227
+ const median = (xs) => { const a = xs.slice().sort((p, q) => p - q), n = a.length; return n ? (n % 2 ? a[(n - 1) / 2] : (a[n / 2 - 1] + a[n / 2]) / 2) : null; };
228
+ function checksOf(o = {}) {
229
+ const v = o.value, u = o.unit || '', prior = (o.prior || []).filter(fin), segs = segsOf(o.segments);
230
+ const isPct = u === '%' || o.type === 'Percentage';
231
+ const out = [];
232
+ // 1 a part that always reads 0 (the trial: app webview login success 0 of 904)
233
+ const zero = segs.filter((s) => s.num === 0 && s.den >= MIN_DEN);
234
+ const zeroRun = v === 0 && prior.length >= 2 && prior.slice(-2).every((p) => p === 0);
235
+ out.push(zero.length ? { id: 'zero', ok: false, text: zero[0].name + ' reads 0 of ' + fmt(zero[0].den) + '. It may never send the event, so it can never count.' }
236
+ : zeroRun ? { id: 'zero', ok: false, text: 'It read 0 three times in a row. The event may have stopped.' }
237
+ : { id: 'zero', ok: true, text: segs.length ? 'No part of it reads 0.' : 'It does not keep reading 0.' });
238
+ // 2 a jump: more than 3× or less than a third of the median of the last 3 readings
239
+ const m = median(prior.slice(-3));
240
+ if (m === null || m <= 0 || !fin(v)) out.push({ id: 'jump', ok: true, text: prior.length ? 'There is no usual level to compare it with yet.' : 'This is the first reading, so there is nothing to compare it with.' });
241
+ else if (v > m * JUMP || v < m / JUMP) out.push({ id: 'jump', ok: false, text: 'It reads ' + fmt(v, u) + ' against a usual ' + fmt(m, u) + ' (the middle of the last ' + Math.min(3, prior.length) + '). That is ' + (v > m ? 'more than 3 times higher' : 'less than a third') + '.' });
242
+ else out.push({ id: 'jump', ok: true, text: 'It is near its usual ' + fmt(m, u) + '.' });
243
+ // 3 the count below a rate: 0 or too small to trust
244
+ const den = o.den;
245
+ if (!fin(den)) out.push({ id: 'den', ok: true, text: 'It has no count below it to check.' });
246
+ else if (den === 0) out.push({ id: 'den', ok: false, text: 'It counts 0 ' + (o.den_label || 'in the count below it') + ', so there is nothing to divide.' });
247
+ else if (den < MIN_DEN) out.push({ id: 'den', ok: false, text: 'It counts only ' + fmt(den) + ' ' + (o.den_label || 'below it') + '. That is too few to trust.' });
248
+ else out.push({ id: 'den', ok: true, text: fmt(den) + ' ' + (o.den_label || 'below it') + ' is enough to trust.' });
249
+ // 4 a value it cannot possibly be
250
+ const rg = isObj(o.range) ? o.range : {}, min = fin(rg.min) ? rg.min : (isPct || ['Count', 'Duration'].includes(o.type) ? 0 : null), max = fin(rg.max) ? rg.max : isPct ? 100 : null;
251
+ if (fin(o.num) && fin(den) && den > 0 && o.num > den && (isPct || o.type === 'Percentage')) out.push({ id: 'range', ok: false, text: 'It counts ' + fmt(o.num) + ' ' + (o.num_label || 'above') + ' but only ' + fmt(den) + ' ' + (o.den_label || 'below') + '. The first cannot be more.' });
252
+ else if (fin(v) && ((min !== null && v < min) || (max !== null && v > max))) out.push({ id: 'range', ok: false, text: 'It reads ' + fmt(v, u) + ', outside what it can be (' + (min !== null ? fmt(min, u) : 'any') + ' to ' + (max !== null ? fmt(max, u) : 'any') + ').' });
253
+ else out.push({ id: 'range', ok: true, text: min !== null || max !== null ? 'It is inside what it can be.' : 'It has no limit to be inside.' });
254
+ return out;
255
+ }
256
+ const heldWhy = (checks) => (checks || []).filter((c) => !c.ok).map((c) => c.text).join(' ');
257
+ /** The PM's number against Claude's: differs when they are more than DIFF_PCT apart (of the PM's number). */
258
+ function compareOf(ours, yours, unit) {
259
+ if (!fin(ours) || !fin(yours)) return null;
260
+ const d = ours - yours, pct = yours !== 0 ? Math.round(Math.abs(d) / Math.abs(yours) * 1000) / 10 : (d === 0 ? 0 : 100);
261
+ return { ours, yours, diff: d, apart: fmt(Math.abs(d), unit), pct, differs: pct > DIFF_PCT };
262
+ }
263
+ /** A first reason, drafted from the last reading's parts at once: a part that reads 0 pulls the number down. */
264
+ function segmentReason(last, unit) {
265
+ const segs = (last && last.segments) || [];
266
+ const z = segs.find((s) => s.num === 0 && s.den >= MIN_DEN);
267
+ if (!z) return null;
268
+ const rest = segs.filter((s) => s !== z), n = rest.reduce((a, s) => a + s.num, 0), d = rest.reduce((a, s) => a + s.den, 0);
269
+ const without = d > 0 ? Math.round(n / d * 1000) / 10 : null;
270
+ return { why: z.name + ' reads 0 of ' + fmt(z.den) + ': it never sends the success event, so my number counts its ' + fmt(z.den) + ' as failures.' + (without !== null && (unit === '%' || !unit) ? ' Without it, I read ' + without + '%.' : ''),
271
+ suggest: { text: 'I suggest counting without ' + z.name + ' until it sends the event.', keep: 'yours' } };
272
+ }
273
+
274
+ /** The compare a page draws (contract §5): the PM's number, Claude's, how far apart, and why. */
275
+ function compareView(F, rid, unit) {
276
+ const x = F && F.rids.get(rid), c = x && x.compare; if (!c) return null;
277
+ const m = compareOf(c.ours, c.value, unit) || {};
278
+ let drafting = false; for (const r of F.runs.values()) if (r.why === 'compare' && !r.ended && r.rids.includes(rid) && r.at >= c.at) drafting = true;
279
+ const state = c.pick ? 'picked' : !m.differs ? 'same' : drafting ? 'drafting' : 'differs';
280
+ return { value: c.value, txt: fmt(c.value, unit), period: c.period, ours: c.ours, oursTxt: fmt(c.ours, unit), apart: m.apart, pct: m.pct, differs: !!m.differs, state,
281
+ ...(c.why ? { why: c.why } : {}), ...(c.suggest ? { suggest: c.suggest } : {}), ...(c.yours ? { yours: c.yours } : {}), ...(c.pick ? { pick: c.pick } : {}) };
282
+ }
98
283
 
99
284
  /** 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
285
  function alertStep(F, rid, reading) {
@@ -126,4 +311,4 @@ function parseCsv(text) {
126
311
  return { rows: out };
127
312
  }
128
313
 
129
- module.exports = { LEDGER, WHYS, CADENCE_GAP, ledgerFile, readLines, read, append, fold, lastOf, dueOf, alertStep, parseCsv };
314
+ module.exports = { LEDGER, WHYS, CADENCE_GAP, WORK_HOURS, MIN_DEN, DIFF_PCT, ledgerFile, readLines, read, append, fold, lastOf, dueOf, nextAfter, nextReadOf, lastTryOf, rhythmOf, checksOf, heldWhy, compareOf, compareView, segmentReason, fmt, alertStep, parseCsv };
@@ -11,7 +11,11 @@
11
11
  * pmos metrics draft fix --json <file|-> one fix row, or a list (kinds: lib/metric-drafts.js FIXES)
12
12
  *
13
13
  * pmos metrics reading list the goals this run reads, with their recipes
14
- * pmos metrics reading <rid> <value> --source "<connector · what>" [--day YYYY-MM-DD] one value read: on the record, with its source and time
14
+ * pmos metrics reading <rid> <value> --source "<connector · what>" [--day YYYY-MM-DD] [--num N --den D] [--segments "web=597/733,app=0/904"]
15
+ * [--period "<week of 19 Oct>"] one value read: Claude's checks run first (lib/metric-reads.js checksOf). It lands on the
16
+ * record with its source, time and counts; a value a check fails on is HELD (ledger only, with a drafted Jira ticket)
17
+ * pmos metrics reading <rid> --why "<why the PM's number differs>" [--suggest mine|yours --suggest-text "<one line>"]
18
+ * [--yours-what "<how the PM counts it>" --yours-query "<the query that counts it that way>"] a compare run only
15
19
  * pmos metrics reading <rid> --cant "<why>" [--fix connect|recipe --connector <name> [--query "<q>" --cadence daily|weekly|monthly]]
16
20
  * could not read it, said honestly, with the drafted fix
17
21
  * The reading run's environment pins its ledger, its records folder, its run and its goals (PMOS_METRIC_READ_FILE, _RECORDS, _DRAFTS, _WS, _RUN,
@@ -42,8 +46,9 @@ const USAGE = [
42
46
  ' "why": "<the evidence, one line>", "old"?, "metric"? (outcome, next-quarter: a Key results row), "recipe"? { "connector", "query", "cadence" },',
43
47
  ' "connector"? (connect), "to", "body" (chase), "ticket"? { "title", "text", "project"? }, "by"?, "target"? (carry), "owner"? { "name", "from" } }',
44
48
  ' pmos metrics reading list',
45
- ' pmos metrics reading <rid> <value> --source "<connector · what you read>" [--day YYYY-MM-DD]',
46
- ' pmos metrics reading <rid> --cant "<why>" [--fix connect|recipe --connector <name> [--query "<q>" --cadence daily|weekly|monthly]]',
49
+ ' pmos metrics reading <rid> <value> --source "<connector · what you read>" [--day YYYY-MM-DD] [--num N --den D] [--segments "web=597/733,app=0/904"] [--period "<week of 19 Oct>"]',
50
+ ' pmos metrics reading <rid> --why "<why the numbers differ>" [--suggest mine|yours --suggest-text "<one line>"] [--yours-what "<how the PM counts it>" --yours-query "<query>"] (a compare run)',
51
+ ' pmos metrics reading <rid> --cant "<why>" [--fix connect|recipe --connector <name> [--query "<q>" --cadence hourly|daily|weekly|monthly]]',
47
52
  'Every number comes from a real reading. The PM keeps or drops each row on the page. Nothing is sent.',
48
53
  ];
49
54
  const DAY_RE = /^\d{4}-\d{2}-\d{2}$/;
@@ -89,6 +94,19 @@ function reading(args, { say, env, now }) {
89
94
  say(`not read ${rid}${fixId ? ' · fix ' + fixId + ' drafted' : ''}`);
90
95
  return 0;
91
96
  }
97
+ const why = flag(args, 'why');
98
+ if (why !== undefined) { // a compare run (batch 18 item 11): why the PM's number and Claude's differ, and how the PM counts it
99
+ if (R.why !== 'compare') { say('✗ --why is for a compare run. This run reads the goals.'); return 1; }
100
+ if (typeof why !== 'string' || !why.trim()) { say('usage: pmos metrics reading <rid> --why "<why the numbers differ>"'); return 2; }
101
+ const sg = flag(args, 'suggest'), st = flag(args, 'suggest-text'), yw = flag(args, 'yours-what'), yq = flag(args, 'yours-query');
102
+ if (sg !== undefined && sg !== 'mine' && sg !== 'yours') { say('✗ --suggest is mine or yours'); return 2; }
103
+ const ev = { kind: 'reason', why: why.replace(/\s+/g, ' ').trim().slice(0, 400) };
104
+ if (sg !== undefined && typeof st === 'string' && st.trim()) ev.suggest = { text: st.replace(/\s+/g, ' ').trim().slice(0, 300), keep: sg };
105
+ if (typeof yw === 'string' && yw.trim() && typeof yq === 'string' && yq.trim()) ev.yours = { what: yw.replace(/\s+/g, ' ').trim().slice(0, 300), query: yq.trim().slice(0, 1200) };
106
+ lineOut(ev);
107
+ say(`why ${rid} differs · filed`);
108
+ return 0;
109
+ }
92
110
  const v = Number(args[1]);
93
111
  if (args[1] === undefined || !Number.isFinite(v)) { say('usage: pmos metrics reading <rid> <value> --source "<connector · what>" [--day YYYY-MM-DD]'); return 2; }
94
112
  const source = flag(args, 'source');
@@ -96,13 +114,52 @@ function reading(args, { say, env, now }) {
96
114
  const day = flag(args, 'day') === undefined ? localDay(now) : String(flag(args, 'day'));
97
115
  if (!DAY_RE.test(day) || day > localDay(now)) { say('✗ --day is YYYY-MM-DD, today or before'); return 2; }
98
116
  const src = source.replace(/\s+/g, ' ').trim().slice(0, 200);
117
+ // the counts, the parts and the period (batch 18 item 11): "How it is counted" files them beside the value; a reading without them still files
118
+ const nf = (k) => { const x = flag(args, k); return x === undefined ? undefined : Number(x); };
119
+ const num = nf('num'), den = nf('den');
120
+ if ((num !== undefined && !(Number.isFinite(num) && num >= 0)) || (den !== undefined && !(Number.isFinite(den) && den >= 0))) { say('✗ --num and --den are counts, 0 or more'); return 2; }
121
+ let segments = [];
122
+ const sf = flag(args, 'segments');
123
+ if (sf !== undefined) {
124
+ for (const part of String(sf === true ? '' : sf).split(',').map((x) => x.trim()).filter(Boolean)) {
125
+ const m = /^(.+?)=(\d+(?:\.\d+)?)\/(\d+(?:\.\d+)?)$/.exec(part);
126
+ if (!m) { say('✗ --segments is "name=num/den,name=num/den", for example "web=597/733,app webview=0/904"'); return 2; }
127
+ segments.push({ name: m[1].trim().slice(0, 40), num: Number(m[2]), den: Number(m[3]) });
128
+ }
129
+ segments = segments.slice(0, 8);
130
+ }
131
+ const period = typeof flag(args, 'period') === 'string' ? flag(args, 'period').replace(/\s+/g, ' ').trim().slice(0, 40) : '';
132
+ // what the checks need: the goal (or the drafted row), its earlier good readings, its unit, type, range and count names
133
+ let goal = null;
134
+ if (test) {
135
+ try { const S = MD.read(require('path').dirname(env.PMOS_METRIC_READ_DRAFTS || '.')).scopes.get(MD.keyOf('product', ws)); const row = S && S.rows.get(rid); if (row) goal = { readings: [], unit: (row.metric && row.metric.unit) || row.unit || '', type: (row.metric && row.metric.type) || row.type, recipe: row.recipe || null }; } catch { goal = null; }
136
+ } else { try { goal = records().list(root, 'kr-metrics').find((x) => x.rid === rid) || null; } catch { goal = null; } }
137
+ const rc = (goal && goal.recipe) || {}, cn = rc.counts || {};
138
+ const checks = MR.checksOf({ value: v, num, den, segments, prior: ((goal && goal.readings) || []).map((x) => Number(x.value)), unit: (goal && goal.unit) || '', type: goal && goal.type, range: rc.range, num_label: cn.num_label, den_label: cn.den_label });
139
+ const extra = { ...(num !== undefined ? { num } : {}), ...(den !== undefined ? { den } : {}), ...(segments.length ? { segments } : {}), ...(period ? { period } : {}), checks };
140
+ const failed = checks.filter((c) => !c.ok);
141
+ if (failed.length) {
142
+ // HELD: never on the record, so it never moves the dot, the line or "target reached". A drafted Jira ticket asks the owner to look.
143
+ const why = MR.heldWhy(checks);
144
+ let ticket = null;
145
+ if (!test && env.PMOS_METRIC_READ_DRAFTS && ws) {
146
+ const name = (goal && goal.metric) || rid;
147
+ const c = MD.cleanFix('product', ws, { kind: 'ticket', goal: rid, text: 'Ask the owner of ' + String(name).slice(0, 60) + ' to check this reading before I draw it.', why: why.slice(0, 200),
148
+ ticket: { title: String(name).slice(0, 80) + ' read strangely on ' + day, text: String(name).slice(0, 80) + ' read ' + v + ' on ' + day + ' (' + src + '). I held it: ' + why.slice(0, 400) + ' Please check the tracking and say if the number is real.' } });
149
+ if (!c.error) { try { require('fs').appendFileSync(env.PMOS_METRIC_READ_DRAFTS, JSON.stringify({ at, by: null, kind: 'fix', scope: 'product', id: ws, row: c.row, src: 'read' }) + '\n'); ticket = c.row.id; } catch { ticket = null; } }
150
+ }
151
+ lineOut({ kind: 'held', value: v, day, source: src, ...extra, why, ...(ticket ? { ticket } : {}) });
152
+ say(`held ${rid} · ${v} on ${day} · ${why}`);
153
+ return 0;
154
+ }
99
155
  if (!test) {
100
156
  const L = require(require('./repo-script.js').repoScript('trust/ledger.js'));
101
157
  const actor = L.actorFrom({ env, isTTY: !!(process.stdout && process.stdout.isTTY) }) || { by: 'claude-code/metric-read', via: 'cli' };
102
- let r; try { r = records().addReading(root, rid, { at: day, value: v, source: src, via: 'run', read_at: at }, actor, 'Claude read it with its recipe'); } catch (e) { r = { ok: false, reasons: [String((e && e.message) || e).slice(0, 160)] }; }
158
+ const reading = { at: day, value: v, source: src, via: R.why === 'press' ? 'press' : 'run', read_at: at, ...(num !== undefined ? { num } : {}), ...(den !== undefined ? { den } : {}), ...(period ? { period } : {}) };
159
+ let r; try { r = records().addReading(root, rid, reading, actor, R.why === 'press' ? 'Claude read it now, as the PM asked' : 'Claude read it with its recipe'); } catch (e) { r = { ok: false, reasons: [String((e && e.message) || e).slice(0, 160)] }; }
103
160
  if (!r.ok) { say('✗ refused: ' + r.reasons.join('; ')); return 1; }
104
161
  }
105
- lineOut({ kind: 'read', value: v, day, source: src });
162
+ lineOut({ kind: 'read', value: v, day, source: src, ...extra });
106
163
  say(`${test ? 'test read' : 'read'} ${rid} · ${v} on ${day} · ${src}`);
107
164
  return 0;
108
165
  }
@@ -5,8 +5,16 @@
5
5
  * GET /api/goal-status?ws=<id> → { ok, on, behind: [title], broken: [title], close: [title], none, dots: [{ id, title, dot }], line }
6
6
  * the product page's Goals line: the same status as Intelligence's goal list, never initiative risk
7
7
  * POST /api/goals/notify { ws, id, notify: push | intel | quiet } → { ok } the goal Viewer ⋯: how a broken limit reaches the PM
8
- * POST /api/goal-status/recipe { ws, id, recipe: { connector, query, cadence } | null, close_band? } → { ok } how the goal is read, and its band
9
- * POST /api/goal-status/read { ws, id? } → { ok, run, rids } Read now: one goal, or every goal with a recipe
8
+ * POST /api/goal-status/recipe { ws, id, recipe: recipeOf shape | null, rhythm?: { cadence, at?, day? }, close_band? } → { ok, rhythm? }
9
+ * how the goal is read, and its band. rhythm alone changes only how often (batch 18 item 11)
10
+ * POST /api/goal-status/read { ws, id? } → { ok, run, rids } Read now: one goal (any time; the next scheduled read stays), or every goal
11
+ *
12
+ * Batch 18 item 11 (goals made clear; contract next18/11-okr-clarity/api-contract.md):
13
+ * POST /api/goal-status/file-held { ws, id, held } → { ok } held = the held reading's at; the PM's "file it": a held reading goes on the record after all; its ticket clears
14
+ * POST /api/goal-status/compare { ws, goal | id, value, period? } → { ok, pct, apart, differs, compare } the PM's own number. goal is a
15
+ * record rid or a drafted row id. Over 2% apart: a first reason from the reading's parts at once, and a
16
+ * compare run that finds why (its --why lands on the GET's compare)
17
+ * POST /api/goal-status/compare-pick { ws, goal, pick: mine | yours } → { ok, counts, query } yours rewrites counts.what and the query
10
18
  * POST /api/goal-status/test { ws, rows: [draft row id] } → { ok, run, rids } a test read of drafted rows before the ✓ (no record is written)
11
19
  * POST /api/goal-status/csv { ws, id, csv, source? } → { ok, added, skipped } the fallback: a CSV or sheet export's readings, via csv
12
20
  *
@@ -44,6 +52,72 @@ function afterRead(ctx, w, rids, now = Date.now()) {
44
52
  tell: (rec, reading) => { if (ctx.tellGoalAlert) ctx.tellGoalAlert(w, rec, reading); } });
45
53
  }
46
54
 
55
+ /* ── batch 18 item 11: a held reading filed after all, and the PM's own number ── */
56
+ const draftRowOf = (dir, ws, rowId) => { try { const S = MD.read(dir).scopes.get(MD.keyOf('product', ws)); const r = S && S.rows.get(rowId); return r && r.state === 'open' ? r : null; } catch { return null; } };
57
+ function heldOrCompare(ctx, w, what, body, { root, id, rec }) {
58
+ const dir = dirOf(ctx, w);
59
+ if (!dir) return bad(409, 'This repository has no PMOS state folder.');
60
+ const now = new Date().toISOString(), F = MR.read(dir), x = F.rids.get(id) || null;
61
+ const row = rec ? null : draftRowOf(dir, w.id, id);
62
+ if (!rec && !row) return bad(404, 'There is no such goal.');
63
+ if (what === 'file-held') {
64
+ if (!rec) return bad(404, 'There is no such goal.');
65
+ const h = x && x.held.find((y) => y.at === text(body.held)); // held = the held reading's at (a body may not carry `at`: pm-guard)
66
+ if (!h) return bad(404, 'There is no such held reading. It may be filed already.');
67
+ const reading = { at: h.day, value: h.value, source: h.source || 'held reading', via: 'held', read_at: h.at };
68
+ for (const k of ['num', 'den']) if (Number.isFinite(h[k])) reading[k] = h[k];
69
+ if (h.period) reading.period = h.period;
70
+ const r = records().addReading(root, rec.rid, reading, UI(), 'The PM filed a reading Claude held');
71
+ if (!r.ok) return bad(400, (r.reasons || []).join('; '));
72
+ MR.append(dir, UI(), { kind: 'filed', rid: rec.rid, held: h.at }, now);
73
+ if (h.ticket) { try { MD.append(dir, UI(), { kind: 'clear', scope: 'product', id: w.id, row: h.ticket }, now); } catch { /* the ticket stays a draft */ } }
74
+ try { afterRead(ctx, w, [rec.rid]); } catch { /* the reading stands */ }
75
+ return { status: 200, body: { ok: true } };
76
+ }
77
+ const recipe = rec ? rec.recipe : row.recipe, unit = rec ? rec.unit || '' : (row.metric && row.metric.unit) || row.unit || '';
78
+ if (what === 'compare') {
79
+ const yours = typeof body.value === 'string' ? Number(body.value.replace(/[,\s%]/g, '')) : body.value;
80
+ if (!Number.isFinite(yours)) return bad(400, 'value is your number.');
81
+ const period = text(body.period).replace(/\s+/g, ' ').trim().slice(0, 40);
82
+ const last = rec ? ((x && x.good) || (() => { const rs = (rec.readings || []); const l = rs[rs.length - 1]; return l ? { value: Number(l.value), day: String(l.at).slice(0, 10) } : null; })()) : (x && x.test && x.test.ok ? x.test : null);
83
+ if (!last || !Number.isFinite(last.value)) return bad(409, rec ? 'I have not read this goal yet, so there is nothing to compare.' : 'Read it first (↻), then compare.');
84
+ const c = MR.compareOf(last.value, yours, unit);
85
+ MR.append(dir, UI(), { kind: 'compare', rid: id, value: yours, period, ours: last.value, pct: c.pct }, now);
86
+ let drafting = false;
87
+ if (c.differs) {
88
+ const sr = MR.segmentReason(last, unit);
89
+ if (sr) {
90
+ const z = ((last.segments || []).find((y) => y.num === 0 && y.den >= MR.MIN_DEN) || {}).name || 'that part';
91
+ const what0 = (recipe && recipe.counts && recipe.counts.what) || '';
92
+ MR.append(dir, UI(), { kind: 'reason', rid: id, why: sr.why, suggest: sr.suggest,
93
+ ...(recipe ? { yours: { what: (what0 ? what0.replace(/\.?\s*$/, '. ') : '') + 'It leaves out ' + z + ', which never sends the success event.', query: recipe.query + '\n-- leave out ' + z + ': it never sends the success event' } } : {}) }, now);
94
+ }
95
+ if (ctx.metricReadRuns && recipe) {
96
+ const r = ctx.metricReadRuns.start({ ws: w.id, rids: [id], why: 'compare', compare: { value: yours, period, ours: last.value, draft: !rec } });
97
+ drafting = !!(r && r.ok);
98
+ }
99
+ }
100
+ const view = MR.compareView(MR.read(dir), id, unit);
101
+ return { status: 200, body: { ok: true, pct: c.pct, apart: c.apart, differs: c.differs, drafting, compare: view } };
102
+ }
103
+ // compare-pick
104
+ const cmp = x && x.compare;
105
+ if (!cmp) return bad(409, 'Compare your number first.');
106
+ if (body.pick !== 'mine' && body.pick !== 'yours') return bad(400, 'pick is mine or yours');
107
+ let next = recipe || null, before = null;
108
+ if (body.pick === 'yours') {
109
+ if (!cmp.yours) return bad(409, 'I have not worked out how you count it yet. Wait for my reason, then pick.');
110
+ if (!recipe) return bad(409, 'This goal has no way to be read yet.');
111
+ before = { what: (recipe.counts && recipe.counts.what) || '', query: recipe.query };
112
+ const r = MD.recipeOf({ ...recipe, query: cmp.yours.query, counts: { ...(recipe.counts || {}), what: cmp.yours.what } });
113
+ if (r.error) return bad(400, r.error);
114
+ next = r.recipe;
115
+ if (rec) { let e; try { e = records().edit(root, 'kr-metrics', rec.rid, { recipe: next }, UI(), 'Counted your way, after you compared your number'); } catch (y) { e = { ok: false, reasons: [String((y && y.message) || y).slice(0, 160)] }; } if (!e.ok) return bad(400, (e.reasons || []).join('; ')); }
116
+ else MD.append(dir, UI(), { kind: 'edit', scope: 'product', id: w.id, row: row.id, set: { recipe: next } }, now);
117
+ }
118
+ MR.append(dir, UI(), { kind: 'pick', rid: id, pick: body.pick, ...(before ? { before } : {}) }, now);
119
+ return { status: 200, body: { ok: true, counts: (next && next.counts) || null, query: next ? next.query : '' } };
120
+ }
47
121
  async function handle(req, res, url, ctx) {
48
122
  const send = (r) => { ctx.json(res, r.body, r.status); return true; };
49
123
  if (url.pathname === '/api/goal-status') {
@@ -53,7 +127,7 @@ async function handle(req, res, url, ctx) {
53
127
  try { return send({ status: 200, body: { ok: true, ...summaryFor(ctx, w, todayIso()) } }); } catch (e) { return send(bad(500, 'The goals could not be read: ' + String((e && e.message) || e).slice(0, 160))); }
54
128
  }
55
129
  const what = url.pathname === '/api/goals/notify' ? 'notify' : url.pathname.replace(/^\/api\/goal-status\/?/, '');
56
- if (!['notify', 'recipe', 'read', 'test', 'csv'].includes(what)) return send(bad(404, 'no such goal-status route'));
130
+ if (!['notify', 'recipe', 'read', 'test', 'csv', 'file-held', 'compare', 'compare-pick'].includes(what)) return send(bad(404, 'no such goal-status route'));
57
131
  if (req.method !== 'POST') return send(bad(405, 'POST only'));
58
132
  if (req.headers && req.headers['x-pmos-session']) return send(bad(403, 'Only the PM changes how a goal is read or told, from the page. A run files readings with pmos metrics reading.'));
59
133
  const got = await ctx.readJson(req);
@@ -63,7 +137,7 @@ async function handle(req, res, url, ctx) {
63
137
  if (!g.ok) return send(bad(g.status, g.error));
64
138
  const w = wsOf(ctx, text(body.ws));
65
139
  if (!w) return send(bad(404, 'no such workspace'));
66
- const root = recordsDirFor(ctx, w.id), id = text(body.id);
140
+ const root = recordsDirFor(ctx, w.id), id = text(body.id) || text(body.goal);
67
141
  const rec = id ? liveRecords(ctx, w).find((r) => r.rid === id) : null;
68
142
  const edit = (fields, why) => { let e; try { e = records().edit(root, 'kr-metrics', id, fields, UI(), why); } catch (x) { e = { ok: false, reasons: [String((x && x.message) || x).slice(0, 160)] }; } return e.ok ? { status: 200, body: { ok: true } } : bad(400, (e.reasons || []).join('; ')); };
69
143
 
@@ -77,9 +151,17 @@ async function handle(req, res, url, ctx) {
77
151
  const set = {};
78
152
  if (body.recipe === null) set.recipe = null;
79
153
  else if (body.recipe !== undefined) { const r = MD.recipeOf(body.recipe); if (r.error) return send(bad(400, r.error)); set.recipe = r.recipe; }
154
+ else if (body.rhythm !== undefined) { // how often only: the rest of the recipe stays
155
+ if (!rec.recipe || !body.rhythm || typeof body.rhythm !== 'object') return send(bad(400, rec.recipe ? 'rhythm is { cadence, at?, day? }' : 'This goal has no way to be read yet.'));
156
+ const { at: _a, day: _d, ...keep } = rec.recipe;
157
+ const r = MD.recipeOf({ ...keep, cadence: body.rhythm.cadence, at: body.rhythm.at, day: body.rhythm.day });
158
+ if (r.error) return send(bad(400, r.error)); set.recipe = r.recipe;
159
+ }
80
160
  if (body.close_band !== undefined) { const b = Number(body.close_band); if (!Number.isFinite(b) || b < 0) return send(bad(400, 'close_band is a number, 0 or more')); set.close_band = b; }
81
- if (!Object.keys(set).length) return send(bad(400, 'Say the recipe or the close band.'));
82
- return send(edit(set, 'How Claude reads this goal'));
161
+ if (!Object.keys(set).length) return send(bad(400, 'Say the recipe, the rhythm or the close band.'));
162
+ const out = edit(set, body.recipe === undefined && body.rhythm !== undefined ? 'How often Claude reads this goal' : 'How Claude reads this goal');
163
+ if (out.status === 200 && set.recipe) out.body.rhythm = MR.rhythmOf(set.recipe);
164
+ return send(out);
83
165
  }
84
166
  if (what === 'read' || what === 'test') {
85
167
  if (!ctx.metricReadRuns) return send(bad(503, 'Claude\'s runs are off on this server.'));
@@ -92,6 +174,7 @@ async function handle(req, res, url, ctx) {
92
174
  const r = ctx.metricReadRuns.start({ ws: w.id, rids, why: what === 'test' ? 'test' : 'press' });
93
175
  return send(r && r.ok ? { status: 200, body: { ok: true, run: r.run, rids: r.rids } } : bad(409, (r && r.error) || 'Claude could not start reading.'));
94
176
  }
177
+ if (what === 'file-held' || what === 'compare' || what === 'compare-pick') return send(heldOrCompare(ctx, w, what, body, { root, id, rec }));
95
178
  // csv: the fallback when no connector reads it
96
179
  if (!rec) return send(bad(404, 'There is no such goal.'));
97
180
  const p = MR.parseCsv(text(body.csv));
@@ -101,7 +101,7 @@ module.exports = {
101
101
  wdir = ctx.stateDirFor ? ctx.stateDirFor(ctx.getWs(pick.ws)) : null;
102
102
  const R = require(repoScript('records/index.js')), lines = R.readLines(R.fileOf(recordsDirFor(ctx, ws), 'kr-metrics')), GW = require('./goal-watch.js');
103
103
  const history = Object.fromEntries(Object.keys(goalMeta).map((rid) => [rid, GW.historyOf(lines, rid)]));
104
- watch = { reads: wdir ? require('./metric-reads.js').read(wdir) : null, history, drafts: wdir ? openDrafts(wdir, pick.ws) : 0 };
104
+ watch = { reads: wdir ? require('./metric-reads.js').read(wdir) : null, history, drafts: wdir ? openDrafts(wdir, pick.ws) : 0, now: Date.now(), hours: ctx.metricReadHours ? ctx.metricReadHours() : undefined };
105
105
  } catch { watch = null; }
106
106
  }
107
107
  const model = Insights.build({