create-pmos 0.433.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 (63) hide show
  1. package/package.json +13 -13
  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 +12 -0
  8. package/workspace/guide/index.md +1 -0
  9. package/workspace/guide/metric-drafts.md +21 -1
  10. package/workspace/guide/your-impact.md +58 -0
  11. package/workspace/impact-screens-test.js +149 -0
  12. package/workspace/intel-report-ui-test.js +1 -1
  13. package/workspace/intelligence-gaps-ui-test.js +13 -9
  14. package/workspace/lib/engine/outbox.js +1 -1
  15. package/workspace/lib/engine/records/index.js +11 -3
  16. package/workspace/lib/goal-status.js +199 -0
  17. package/workspace/lib/goal-watch.js +71 -0
  18. package/workspace/lib/headless.js +24 -2
  19. package/workspace/lib/impact-cli.js +72 -0
  20. package/workspace/lib/impact-runs.js +114 -0
  21. package/workspace/lib/impact.js +195 -0
  22. package/workspace/lib/insights-premium.js +43 -4
  23. package/workspace/lib/metric-draft-runs.js +33 -10
  24. package/workspace/lib/metric-drafts.js +118 -15
  25. package/workspace/lib/metric-read-runs.js +132 -0
  26. package/workspace/lib/metric-reads.js +129 -0
  27. package/workspace/lib/metrics-cli.js +100 -5
  28. package/workspace/lib/pmos-verbs.js +4 -1
  29. package/workspace/lib/route-modules.js +3 -0
  30. package/workspace/lib/routes-goal-status.js +111 -0
  31. package/workspace/lib/routes-impact-views.js +58 -0
  32. package/workspace/lib/routes-impact.js +91 -0
  33. package/workspace/lib/routes-insights-premium.js +20 -0
  34. package/workspace/lib/routes-metric-drafts.js +55 -4
  35. package/workspace/lib/routes-records.js +2 -0
  36. package/workspace/lib/settings-store.js +3 -0
  37. package/workspace/okr-goals-ui-test.js +175 -0
  38. package/workspace/package-lock.json +2 -2
  39. package/workspace/package.json +1 -1
  40. package/workspace/public/pm/bd-ini-panel.js +10 -2
  41. package/workspace/public/pm/cozy-adler.css +5 -0
  42. package/workspace/public/pm/cozy-adler.js +17 -9
  43. package/workspace/public/pm/cozy-insights.css +84 -0
  44. package/workspace/public/pm/cozy-settings.js +11 -1
  45. package/workspace/public/pm/home-app.js +61 -8
  46. package/workspace/public/pm/home-impact.css +16 -0
  47. package/workspace/public/pm/home-impact.js +72 -0
  48. package/workspace/public/pm/home-today.js +4 -2
  49. package/workspace/public/pm/impact.css +37 -0
  50. package/workspace/public/pm/impact.js +201 -0
  51. package/workspace/public/pm/okr-list.js +249 -0
  52. package/workspace/public/pm/premium-insights.js +222 -238
  53. package/workspace/public/pm/premium-vw-mtg.js +4 -1
  54. package/workspace/public/premium-intelligence.html +3 -2
  55. package/workspace/public/premium.html +1 -0
  56. package/workspace/server.js +56 -2
  57. package/workspace/skills/impact-detect.skill +46 -0
  58. package/workspace/skills/metric-read.skill +32 -0
  59. package/workspace/test-lists/goal-watch.json +9 -0
  60. package/workspace/test-lists/impact-screens.json +5 -0
  61. package/workspace/test-lists/impact-ui.json +9 -0
  62. package/workspace/test-lists/impact.json +9 -0
  63. package/workspace/test-lists/okr-goals-ui.json +5 -0
@@ -3,7 +3,7 @@
3
3
  * (initiative workspace-headless-jobs; PM decision 2026-10-11: keep Jev, no direct Claude API, background
4
4
  * jobs that need no human run headless).
5
5
  *
6
- * kindFor({ agent, origin, skill, env }) → 'notes' | 'skill' | 'ask' | 'drive' | 'scan-web' | 'scan-repo' | 'scan-research-web' | 'scan-research-repo' | 'report-setup' | 'report-find' | 'core-doc' | 'report-design' | 'report-structure-pull' | 'report-sample-fetch' | 'report-structure' | 'report-structure-dry' | 'ms-review' | 'propose' | 'metric-draft' | null (null: open a pane, as before)
6
+ * kindFor({ agent, origin, skill, env }) → 'notes' | 'skill' | 'ask' | 'drive' | 'scan-web' | 'scan-repo' | 'scan-research-web' | 'scan-research-repo' | 'report-setup' | 'report-find' | 'core-doc' | 'report-design' | 'report-structure-pull' | 'report-sample-fetch' | 'report-structure' | 'report-structure-dry' | 'ms-review' | 'propose' | 'metric-draft' | 'impact' | 'metric-read' | null (null: open a pane, as before)
7
7
  * argsFor(kind, { modelArgs, addDirs, writePaths }) → the argv after `claude` (writePaths: the one render file a report-design job may write;
8
8
  * for the skill kind, the folders the run may write in, from skillWriteDirs)
9
9
  * skillWriteDirs(skill, { root, scratch }) → the absolute folders a background skill run may write in: its scratch folder and the state folders its skill writes
@@ -61,6 +61,13 @@
61
61
  * `metric-draft:<ws>:<scope>:<id>:<run>`. It reads the repository, the stored reads and, where the PM's own settings allow it, the PM's sources through
62
62
  * connectors; its only write is `pmos metrics draft`, pinned by the server to that scope and run. Only the PM's ✓ keep writes a record. It sends nothing
63
63
  * and never runs in a pane.
64
+ * The `impact` kind is Claude's daily read of the PM's impact (batch 16 item 7, Your impact): origin `impact:<run>`. It reads the stored reads, the
65
+ * repository and, where the PM's own settings allow it, the PM's sources through connectors, for what people and systems did in reaction to the
66
+ * PM's work; its only write is `pmos impact add`, pinned by the server to this run and the person's own ledger. It sends nothing, posts nothing,
67
+ * reacts to nothing, and never runs in a pane.
68
+ * The `metric-read` kind is Claude reading the goals by themselves (feedback batch 16 item 6): origin `metric-read:<ws>:<run>`. It reads each goal's
69
+ * recipe through the PM's own connectors, where the PM's own settings allow it; its only write is `pmos metrics reading`, pinned by the server to
70
+ * that run and those goals: the value lands on the kr-metrics record with its source and time. It sends nothing and never runs in a pane.
64
71
  * The `report-structure` and `report-structure-dry` kinds are the report structure step (initiative report-structure): origins `report-structure:<id>` and
65
72
  * `report-structure-dry:<id>`. A turn proposes or refines the plan of a report (sources, charts, outline); a dry run tries a saved version on the last complete
66
73
  * period. Each reads the repository and, where the PM's own Claude Code settings allow it, reads through connectors (none is named in the list, as for
@@ -107,6 +114,11 @@ const PROPOSE_ORIGINS = Object.freeze(['propose:']);
107
114
  // batch 15 item 1: Claude drafts the metrics of a product, a program or an initiative (origin `metric-draft:<ws>:<scope>:<id>:<run>`,
108
115
  // lib/metric-draft-runs.js). Its only write is `pmos metrics draft`, pinned by the server to that scope and run.
109
116
  const METRIC_DRAFT_ORIGINS = Object.freeze(['metric-draft:']);
117
+ // batch 16 item 7: Claude's daily impact read (origin `impact:<run>`, lib/impact-runs.js). Its only write is `pmos impact add`, pinned to that run.
118
+ const IMPACT_ORIGINS = Object.freeze(['impact:']);
119
+ // batch 16 item 6: Claude reads the goals with their recipes (origin `metric-read:<ws>:<run>`, lib/metric-read-runs.js). Its only write is
120
+ // `pmos metrics reading`, pinned by the server to that run and those goals.
121
+ const METRIC_READ_ORIGINS = Object.freeze(['metric-read:']);
110
122
  // report-design-studio: a studio turn, a cycle render or a re-render to match (origin `report-design:<cadence>`).
111
123
  const REPORT_DESIGN_ORIGINS = Object.freeze(['report-design:']);
112
124
  // report-design-studio: reading ONE linked Google or Confluence file through the PM's own connectors (origin `report-sample-fetch:<cadence>:<sampleId>`).
@@ -166,6 +178,14 @@ const TOOLS = Object.freeze({
166
178
  // no web fetch, nothing that sends; it never writes a record (only the PM's ✓ keep does).
167
179
  'metric-draft': Object.freeze(['Read', 'Glob', 'Grep', 'Bash(pmos metrics draft *)', 'Bash(pmos initiative export *)', 'Bash(pmos initiative list *)',
168
180
  'Bash(pmos source show *)', 'Bash(pmos source status *)', 'Bash(git log *)', 'Bash(date *)']),
181
+ // The impact run (lib/impact-runs.js): read and search the repository and the stored reads, and the one verb that files an item. The PM's
182
+ // Slack, mail and Jira are read through the PM's own connectors only where the PM's settings allow it. No Write, no Edit, no web fetch,
183
+ // nothing that sends, posts or reacts.
184
+ impact: Object.freeze(['Read', 'Glob', 'Grep', 'Bash(pmos impact *)', 'Bash(pmos source show *)', 'Bash(pmos source status *)', 'Bash(pmos initiative list *)',
185
+ 'Bash(pmos initiative export *)', 'Bash(git log *)', 'Bash(date *)']),
186
+ // The reading run (lib/metric-read-runs.js): read and search, and the one verb that files a reading. The PM's analytics and Jira are read through
187
+ // the PM's own connectors only where the PM's settings allow it. No Write, no Edit, no web fetch, nothing that sends.
188
+ 'metric-read': Object.freeze(['Read', 'Glob', 'Grep', 'Bash(pmos metrics reading *)', 'Bash(pmos source show *)', 'Bash(pmos source status *)', 'Bash(date *)']),
169
189
  // The design run: read and search only. Its one write, the render file, is added per run by argsFor (writePaths). No Bash, no web, nothing that sends.
170
190
  'report-design': Object.freeze(['Read', 'Glob', 'Grep']),
171
191
  // The link fetch run: Read, and its one write (the text copy of the linked file) is added per run by argsFor. No Bash, no web, no connector tool named.
@@ -204,6 +224,8 @@ function kindFor({ agent, origin, skill, env } = {}) {
204
224
  if (MS_REVIEW_ORIGINS.some((p) => o.startsWith(p))) return 'ms-review';
205
225
  if (PROPOSE_ORIGINS.some((p) => o.startsWith(p))) return 'propose';
206
226
  if (METRIC_DRAFT_ORIGINS.some((p) => o.startsWith(p))) return 'metric-draft';
227
+ if (IMPACT_ORIGINS.some((p) => o.startsWith(p))) return 'impact';
228
+ if (METRIC_READ_ORIGINS.some((p) => o.startsWith(p))) return 'metric-read';
207
229
  if (REPORT_DESIGN_ORIGINS.some((p) => o.startsWith(p))) return 'report-design';
208
230
  if (REPORT_SAMPLE_FETCH_ORIGINS.some((p) => o.startsWith(p))) return 'report-sample-fetch';
209
231
  // 'report-structure-dry:' is not a prefix of 'report-structure:' (the colon differs), so the two are told apart by their prefix alone
@@ -365,4 +387,4 @@ function logLines(r, exitCode) {
365
387
  return out;
366
388
  }
367
389
 
368
- module.exports = { HEADLESS_SKILLS, HEADLESS_ORIGINS, ASK_ORIGINS, DRIVE_ORIGINS, SCAN_WEB_ORIGINS, SCAN_REPO_ORIGINS, SCAN_RESEARCH_WEB_ORIGINS, SCAN_RESEARCH_REPO_ORIGINS, WEB_KINDS, REPORT_SETUP_ORIGINS, REPORT_FIND_ORIGINS, CORE_DOC_ORIGINS, REPORT_DESIGN_ORIGINS, REPORT_SAMPLE_FETCH_ORIGINS, REPORT_STRUCTURE_ORIGINS, REPORT_STRUCTURE_DRY_ORIGINS, METRIC_DRAFT_ORIGINS, TOOLS, SKILL_WRITE_DIRS, DEFAULT_TIMEOUT_MS, kindFor, argsFor, skillWriteDirs, timeoutMs, parseResult, streamLines, outcomeOf, signedOut, SIGNED_OUT_WHY, logLines, switchedOff };
390
+ module.exports = { HEADLESS_SKILLS, HEADLESS_ORIGINS, ASK_ORIGINS, DRIVE_ORIGINS, SCAN_WEB_ORIGINS, SCAN_REPO_ORIGINS, SCAN_RESEARCH_WEB_ORIGINS, SCAN_RESEARCH_REPO_ORIGINS, WEB_KINDS, REPORT_SETUP_ORIGINS, REPORT_FIND_ORIGINS, CORE_DOC_ORIGINS, REPORT_DESIGN_ORIGINS, REPORT_SAMPLE_FETCH_ORIGINS, REPORT_STRUCTURE_ORIGINS, REPORT_STRUCTURE_DRY_ORIGINS, METRIC_DRAFT_ORIGINS, IMPACT_ORIGINS, TOOLS, SKILL_WRITE_DIRS, DEFAULT_TIMEOUT_MS, kindFor, argsFor, skillWriteDirs, timeoutMs, parseResult, streamLines, outcomeOf, signedOut, SIGNED_OUT_WHY, logLines, switchedOff };
@@ -0,0 +1,72 @@
1
+ 'use strict';
2
+ /* impact-cli.js — `pmos impact`: the one write of Claude's impact run (feedback batch 16 item 7; lib/impact.js, lib/impact-runs.js).
3
+ * What it files waits for the PM's ✓ or ✕ in the weekly check in Home's chat. Only a ✓ item counts.
4
+ *
5
+ * pmos impact add --json <file|-> one item, or a list of them: { kind, text, who, at, source: { url, type, label } }
6
+ * pmos impact end [--error "<why>"] the run is done
7
+ * pmos impact status what the ledger holds for this week and the last: so the run does not file the same thing twice
8
+ *
9
+ * The server pins the run and the ledger in the run's environment (PMOS_IMPACT_FILE, PMOS_IMPACT_RUN); outside such a run the verb
10
+ * refuses. An item the PM checked is not filed again. Exit codes: 0 filed, 1 refused, 2 usage. It sends nothing. */
11
+ const fs = require('fs');
12
+ const IM = require('./impact.js');
13
+
14
+ const COMMANDS = { impact: ['add', 'end', 'status'] };
15
+ const SUBS = COMMANDS.impact;
16
+ const USAGE = [
17
+ 'usage: pmos impact add|end|status — what Claude\'s impact run files for the PM to check (✓ real, ✕ not real)',
18
+ ' pmos impact add --json <file|->',
19
+ ' { "kind": "' + IM.KINDS.join('" | "') + '", "text": "<one plain sentence, no counts>", "who": "<a name, or empty>",',
20
+ ' "at": "<ISO 8601, when it happened>", "source": { "url": "<https link>", "type": "' + IM.SOURCE_TYPES.join('" | "') + '", "label": "Slack · #idpf-data" } }',
21
+ ' pmos impact end [--error "<why the run could not finish>"]',
22
+ ' pmos impact status',
23
+ 'Only what a person or a system outside you did in reaction to your work. Never Claude\'s own work. No source, no item. Nothing is sent.',
24
+ ];
25
+ const flag = (args, k) => { const i = args.indexOf('--' + k); return i >= 0 ? (args[i + 1] === undefined || args[i + 1].startsWith('--') ? true : args[i + 1]) : undefined; };
26
+ function readJson(src, stdin) {
27
+ let text;
28
+ try { text = src === '-' ? (stdin !== undefined ? String(stdin) : fs.readFileSync(0, 'utf8')) : fs.readFileSync(src, 'utf8'); } catch (e) { return { error: `could not read ${src}: ${String((e && e.message) || e).slice(0, 120)}` }; }
29
+ try { return { body: JSON.parse(text) }; } catch { return { error: 'the input is not JSON' }; }
30
+ }
31
+
32
+ async function run(argv, { say = (s) => console.log(s), env = process.env, stdin, now = Date.now() } = {}) {
33
+ const args = argv[0] === 'impact' ? argv.slice(1) : argv.slice();
34
+ const sub = args[0];
35
+ if (!sub || ['help', '--help', '-h'].includes(sub)) { for (const l of USAGE) say(l); return sub ? 0 : 1; }
36
+ if (!SUBS.includes(sub)) { say(`unknown impact command "${sub}". Use one of: ${SUBS.join(', ')}`); return 2; }
37
+ const file = env.PMOS_IMPACT_FILE, runId = env.PMOS_IMPACT_RUN;
38
+ if (!file || !runId) { say('✗ pmos impact is for Claude\'s impact run. The PM checks each item in Home\'s chat.'); return 1; }
39
+ const F = IM.fold(IM.readLines(file));
40
+ const at = new Date(now).toISOString();
41
+ const line = (ev) => { fs.appendFileSync(file, JSON.stringify({ at, by: null, run: runId, ...ev }) + '\n', { mode: 0o600 }); };
42
+
43
+ if (sub === 'status') {
44
+ const today = IM.dayOf(now), week = IM.weekOf(today), last = IM.addDays(week, -7);
45
+ const mine = [...F.items.values()].filter((it) => IM.weekOf(IM.dayOf(Date.parse(it.at))) >= last);
46
+ if (!mine.length) say('nothing filed since ' + last);
47
+ for (const it of mine) say(`${it.real === true ? 'real ' : it.real === false ? 'not ' : 'open '} ${it.id} · ${it.kind} · ${it.text} · ${it.source.url}`);
48
+ return 0;
49
+ }
50
+ const r = F.runs.find((x) => x.run === runId);
51
+ if (!r || r.ended) { say('✗ this run is not reading now. It ended. File nothing more.'); return 1; }
52
+ if (sub === 'end') { const e = flag(args, 'error'); line({ kind: 'end', ok: typeof e !== 'string', ...(typeof e === 'string' ? { error: e.slice(0, 200) } : {}) }); say('done'); return 0; }
53
+
54
+ const src = flag(args, 'json');
55
+ if (typeof src !== 'string') { say('usage: pmos impact add --json <file|->'); return 2; }
56
+ const j = readJson(src, stdin);
57
+ if (j.error) { say('✗ ' + j.error); return 2; }
58
+ const list = Array.isArray(j.body) ? j.body : [j.body];
59
+ if (!list.length || list.length > 40) { say('✗ file 1 to 40 items at once'); return 2; }
60
+ let bad = 0;
61
+ for (const x of list) {
62
+ const c = IM.clean(x);
63
+ if (c.error) { bad++; say('✗ ' + c.error + (x && x.text ? ' · ' + String(x.text).slice(0, 60) : '')); continue; }
64
+ const was = F.items.get(c.item.id);
65
+ if (was && was.real !== null) { say(`· ${c.item.id} was checked already: not filed again`); continue; }
66
+ line({ kind: 'item', item: c.item });
67
+ say(`filed ${c.item.id} · ${c.item.kind} · ${c.item.text}`);
68
+ }
69
+ return bad ? 1 : 0;
70
+ }
71
+
72
+ module.exports = { run, COMMANDS, USAGE, SUBS };
@@ -0,0 +1,114 @@
1
+ 'use strict';
2
+ /* impact-runs.js — Claude's daily impact run (feedback batch 16 item 7; lib/impact.js, skill impact-detect).
3
+ *
4
+ * off(env) → true when PMOS_IMPACT=off (or 0, false, no)
5
+ * dueOf(F, today) PURE → true when no run started today and the switch is on (the caller checks the switch)
6
+ * sinceOf(F, today) PURE → the first day the run reads from: the day of the last run that ended well, else 8 days back
7
+ * promptOf(skill, o) → the prompt. o: { run, today, since, facts: [line], filed: [line], notReal: [line] }
8
+ * create(deps) → { tick(opts), start({ now, press }), active() }
9
+ *
10
+ * ONE RUN A DAY, for the person (not per product): headless kind `impact`, origin `impact:<run>`, in the home workspace. It reads the
11
+ * stored reads (`pmos source show`), the repository and, where the PM's own Claude Code settings allow it, the PM's connectors, for what
12
+ * people and systems outside the PM did in reaction to the PM's work. Its only write is `pmos impact add`, pinned by the server to this run
13
+ * and the person's ledger (PMOS_IMPACT_FILE, PMOS_IMPACT_RUN). It sends nothing, posts nothing and reacts to nothing.
14
+ *
15
+ * It never runs when Settings › General › Your impact is off (deps.on() false), when PMOS_IMPACT or PMOS_HEADLESS is off, or outside the
16
+ * day-check window. A run that failed tries again the next day.
17
+ *
18
+ * deps: { runtime() → the runtime folder, on() → bool (impact.on), homeWs() → w, open(now) → bool, headlessOff() → bool, env,
19
+ * promptFor(skillId) → skill body | null, facts() → [line], spawn(spec), spawnNow(spec), stop(session), warn(what, err) }
20
+ */
21
+ const crypto = require('crypto');
22
+ const IM = require('./impact.js');
23
+
24
+ const flagOff = (v) => /^(off|0|false|no)$/i.test(String(v || '').trim());
25
+ const off = (env) => flagOff((env || process.env).PMOS_IMPACT);
26
+ const one = (s, n) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim().slice(0, n);
27
+ const BACK_DAYS = 8;
28
+
29
+ const dayAt = (at) => { const t = Date.parse(at); return Number.isFinite(t) ? IM.dayOf(t) : ''; };
30
+ function dueOf(F, today) { return !(F.runs || []).some((r) => dayAt(r.at) === today); }
31
+ function sinceOf(F, today) {
32
+ const ok = (F.runs || []).filter((r) => r.ended && r.ok).map((r) => dayAt(r.at)).filter(Boolean).sort();
33
+ const floor = IM.addDays(today, -BACK_DAYS);
34
+ return ok.length && ok[ok.length - 1] > floor ? ok[ok.length - 1] : floor;
35
+ }
36
+ function promptOf(skill, o) {
37
+ const list = (a, none) => (a && a.length ? a.map((x) => '- ' + x).join('\n') : '- ' + none);
38
+ return `${skill}\n\nThis run:\n- Run: ${o.run}\n- Today: ${o.today}\n- Read from: ${o.since} to today\n`
39
+ + `- What PMOS knows:\n${list(o.facts, 'nothing more')}\n`
40
+ + `- Filed already (do not file these again):\n${list(o.filed, 'none')}\n`
41
+ + `- The PM said these were not real (do not file anything like them):\n${list(o.notReal, 'none')}\n\n`
42
+ + 'File with `pmos impact add` only (the server pins this run). End with `pmos impact end`. Send nothing.';
43
+ }
44
+
45
+ function create(deps) {
46
+ const warn = deps.warn || (() => {});
47
+ let active = null; // { run, dir, session }
48
+ const dirNow = () => IM.dirOf(deps.runtime && deps.runtime());
49
+ const isOn = () => { try { return !!deps.on(); } catch { return false; } };
50
+
51
+ function ended(run, r, now = Date.now()) {
52
+ if (!active || active.run !== run) return;
53
+ const dir = active.dir; active = null;
54
+ const x = IM.read(dir).runs.find((y) => y.run === run);
55
+ if (!x || x.ended) return; // `pmos impact end` wrote it already
56
+ const res = (r && r.result) || {};
57
+ const ok = !!(r && !r.timedOut && !r.stopped && r.code === 0 && res.ok !== false && !res.isError);
58
+ try { IM.append(dir, null, { kind: 'end', run, ok, ...(ok ? {} : { error: one((r && r.note) || res.text || 'the run failed', 200) }) }, new Date(now).toISOString()); } catch (e) { warn('impact end', e); }
59
+ }
60
+
61
+ /** Start the run now. → { ok, run } | { ok: false, error, held? } */
62
+ function start({ now = Date.now(), press = false } = {}) {
63
+ if (!isOn()) return { ok: false, error: 'Your impact is off in Settings.' };
64
+ if (off(deps.env) || (deps.headlessOff && deps.headlessOff())) return { ok: false, error: 'Background runs are off (PMOS_IMPACT or PMOS_HEADLESS).' };
65
+ if (active) return { ok: true, run: active.run, already: true };
66
+ const dir = dirNow(); if (!dir) return { ok: false, error: 'There is no runtime folder.' };
67
+ const w = deps.homeWs && deps.homeWs(); if (!w) return { ok: false, error: 'There is no workspace to run in.' };
68
+ const skill = deps.promptFor('impact-detect');
69
+ if (!skill) return { ok: false, error: 'The impact-detect skill is not installed.' };
70
+ const F = IM.read(dir), today = IM.dayOf(now);
71
+ const run = 'im' + now.toString(36) + crypto.randomBytes(3).toString('hex');
72
+ const recent = [...F.items.values()].filter((it) => dayAt(it.at) >= IM.addDays(today, -21));
73
+ const line = (it) => it.kind + ' · ' + it.text + ' · ' + it.source.url;
74
+ let facts = [];
75
+ try { facts = (deps.facts && deps.facts()) || []; } catch { facts = []; }
76
+ const prompt = promptOf(skill, { run, today, since: sinceOf(F, today), facts, filed: recent.filter((x) => x.real !== false).map(line), notReal: recent.filter((x) => x.real === false).map(line) });
77
+ const go = press && deps.spawnNow ? deps.spawnNow : deps.spawn;
78
+ active = { run, dir, session: null };
79
+ let session = null;
80
+ try {
81
+ session = go({ name: 'Reading your impact', ws: w.id, origin: 'impact:' + run, initialInput: prompt + '\r',
82
+ env: { PMOS_IMPACT_FILE: IM.ledgerFile(dir), PMOS_IMPACT_RUN: run }, onDone: (r) => ended(run, r) });
83
+ } catch (e) { warn('impact run', e); }
84
+ if (session && session.held) { active = null; return { ok: false, held: true, error: 'Claude is busy with other runs. It tries again later.' }; }
85
+ IM.append(dir, null, { kind: 'run', run }, new Date(now).toISOString());
86
+ if (!session || session.state === 'exited' || session.headless !== 'impact') {
87
+ if (session && session.headless !== 'impact' && session.state !== 'exited' && deps.stop) { try { deps.stop(session); } catch { /* best effort */ } }
88
+ ended(run, { code: 1, note: (session && session.note) || 'the run could not start in the background', result: {} }, now);
89
+ return { ok: false, error: (session && session.note) || 'Claude could not start reading.' };
90
+ }
91
+ if (active) active.session = session;
92
+ return { ok: true, run };
93
+ }
94
+
95
+ function tick({ now = Date.now() } = {}) {
96
+ if (!isOn()) { stopAll(); return { off: true }; } // the switch went off: a run that is reading stops at the next tick
97
+ if (off(deps.env) || (deps.headlessOff && deps.headlessOff())) return { off: true };
98
+ if (active) return { running: true };
99
+ let open = true;
100
+ try { open = deps.open ? !!deps.open(now) : true; } catch { open = true; }
101
+ if (!open) return { started: null, closed: true };
102
+ const dir = dirNow(); if (!dir) return { started: null };
103
+ if (!dueOf(IM.read(dir), IM.dayOf(now))) return { started: null };
104
+ const r = start({ now });
105
+ return r.ok ? { started: r.run } : { started: null, error: r.error, held: !!r.held };
106
+ }
107
+
108
+ /** The switch went off: stop a run that is reading. */
109
+ function stopAll() { if (active && active.session && deps.stop) { try { deps.stop(active.session); } catch { /* best effort */ } } }
110
+
111
+ return { tick, start, stopAll, active: () => (active ? active.run : null) };
112
+ }
113
+
114
+ module.exports = { off, dueOf, sinceOf, promptOf, create, BACK_DAYS };
@@ -0,0 +1,195 @@
1
+ 'use strict';
2
+ /* impact.js — "Your impact" (feedback batch 16 item 7, the gamification design; brief next16/briefs/7-your-impact-build.md, contract
3
+ * 7-impact-api.md; canvas In development GmP1Ledger, GmP1Switch). THE ONE WRITER and THE ONE FOLD of <runtime>/impact/impact.jsonl.
4
+ * lib/routes-impact.js does the I/O; lib/impact-runs.js starts the detection run; lib/impact-cli.js is what that run files with.
5
+ * Pure, with no clock of its own: every time comes in.
6
+ *
7
+ * PRIVATE. The ledger is per person, in the runtime folder beside settings.json: outside every repository, so no commit, sync or teammate
8
+ * reads it. Nothing here sends anything. An item is something a person or a system outside you did in reaction to your work (a thanks, a
9
+ * ticket that moved after your decision, a spec used, a KR that moved after your initiative delivered), with the source to open it. Never
10
+ * logins, ticks, time, messages sent, or Claude's own work.
11
+ *
12
+ * NO NUMBERS LEAVE THIS FILE. The views carry words: grow is rest · bud · leaf · full; the gate is measuring · open · short. The gate's rate
13
+ * is written to the ledger (the brief's "record the rate") and never shown.
14
+ *
15
+ * THE LEDGER. One line per event, { at, by, kind, ... }:
16
+ * run { run } the detection run started
17
+ * item { run, item } one item it filed (clean() shape); the last line for an id wins until it is checked
18
+ * end { run, ok, error? } the run ended
19
+ * verdict { id, real: true | false } the PM's ✓ or ✕ in the weekly check
20
+ * undo { id } a row back to unchecked
21
+ * seen { ids } read on a Phase 2 surface; ends its celebration
22
+ * gate { state, real, judged, weeks } the gate changed: measuring → open (and stays), or → short
23
+ *
24
+ * dirOf(runtime) · ledgerFile(dir) · readLines(file) · read(dir) → fold · append(dir, actor, line, at)
25
+ * fold(lines) PURE → { items: Map id → item, runs: [run], gate }
26
+ * clean(input) → { item } | { error } what `pmos impact add` checks
27
+ * weekOf(day, start) · labelOf(week, thisWeek) · dayOf(ms)
28
+ * gateOf(F, thisWeek) PURE → { state, real, judged, weeks }
29
+ * weekView(F, o) · weeksView(F, o) · checkView(F, o) PURE → the GET bodies (no ok, no on)
30
+ * KINDS · SOURCE_TYPES · GROW
31
+ */
32
+ const fs = require('fs');
33
+ const path = require('path');
34
+ const crypto = require('crypto');
35
+
36
+ const LEDGER = 'impact.jsonl';
37
+ const LINES = new Set(['run', 'item', 'end', 'verdict', 'undo', 'seen', 'gate']);
38
+ const KINDS = ['thanks', 'unblock', 'used', 'kr'];
39
+ const SOURCE_TYPES = ['slack', 'mail', 'jira', 'doc', 'meeting', 'kr', 'board', 'initiative'];
40
+ const GROW = ['rest', 'bud', 'leaf', 'full'];
41
+ const GATE_ITEMS = 10, GATE_WEEKS = 2; // at least 9 of 10 items real, across two weekly checks
42
+ const DAY_RE = /^\d{4}-\d{2}-\d{2}$/;
43
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
44
+ const str = (v) => (typeof v === 'string' ? v : '');
45
+ const one = (v, n) => String(v == null ? '' : v).replace(/\s+/g, ' ').trim().slice(0, n);
46
+ const hash = (s) => crypto.createHash('sha1').update(String(s)).digest('hex').slice(0, 10);
47
+ const p2 = (n) => String(n).padStart(2, '0');
48
+ const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
49
+
50
+ /* ── days and weeks (local days, YYYY-MM-DD; a week is named by its first day) ── */
51
+ const dayOf = (ms) => { const d = new Date(ms); return d.getFullYear() + '-' + p2(d.getMonth() + 1) + '-' + p2(d.getDate()); };
52
+ const utc = (day) => { const m = DAY_RE.exec(day) ? day.split('-').map(Number) : null; return m ? Date.UTC(m[0], m[1] - 1, m[2]) : NaN; };
53
+ const addDays = (day, n) => new Date(utc(day) + n * 864e5).toISOString().slice(0, 10);
54
+ /** The first day of the week `day` is in. start: 'mon' (default) or 'sun' (Settings › Time › week start). */
55
+ function weekOf(day, start = 'mon') {
56
+ const t = utc(day); if (!Number.isFinite(t)) return '';
57
+ const dow = new Date(t).getUTCDay(), back = start === 'sun' ? dow : (dow + 6) % 7;
58
+ return addDays(day, -back);
59
+ }
60
+ function labelOf(week, thisWeek) {
61
+ if (week === thisWeek) return 'This week';
62
+ if (week === addDays(thisWeek, -7)) return 'Last week';
63
+ const m = week.split('-').map(Number);
64
+ return 'Week of ' + m[2] + ' ' + MON[m[1] - 1] + (week.slice(0, 4) === thisWeek.slice(0, 4) ? '' : ' ' + m[0]);
65
+ }
66
+
67
+ /* ── the ledger ── */
68
+ const dirOf = (runtime) => (runtime ? path.join(runtime, 'impact') : null);
69
+ function ledgerFile(dir) { return dir ? path.join(dir, LEDGER) : null; }
70
+ function readLines(file) {
71
+ if (!file) return [];
72
+ let text = '';
73
+ try { text = fs.readFileSync(file, 'utf8'); } catch { return []; }
74
+ const out = [];
75
+ for (const raw of text.split('\n')) { if (!raw.trim()) continue; try { const l = JSON.parse(raw); if (isObj(l) && LINES.has(l.kind)) out.push(l); } catch { /* a torn line is skipped */ } }
76
+ return out;
77
+ }
78
+ function read(dir) { return fold(readLines(ledgerFile(dir))); }
79
+ /** One line. `at` is the caller's clock (an ISO string). The folder and the file are the person's own: mode 0700 and 0600. */
80
+ function append(dir, actor, ev, at) {
81
+ const line = { at: at || null, by: (actor && actor.by) || null, ...ev };
82
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
83
+ fs.appendFileSync(ledgerFile(dir), JSON.stringify(line) + '\n', { mode: 0o600 });
84
+ return line;
85
+ }
86
+
87
+ /* ── what the run may file (`pmos impact add`) ── */
88
+ const LIM = { text: 200, who: 60, label: 80, url: 600 };
89
+ // A count of what you did or who you helped is a score by another name (rule 3). A KR's own reading ("31% to 35%") is the KR, not a count.
90
+ const COUNT_RE = /\b\d+\s*(?:people|persons?|engineers?|devs?|developers?|teams?|leaves|leaf|points?|times|thanks|items?|helped|tickets?|stakeholders?|users? helped)\b|\b(?:streak|score|level|rank)\b/i;
91
+ const urlOk = (u) => /^https:\/\/[^\s]+$/i.test(u) || /^\/[^\s/][^\s]*$/.test(u);
92
+ /** → { item } | { error }. input: { kind, text, who, at, source: { url, type, label } } */
93
+ function clean(input) {
94
+ if (!isObj(input)) return { error: 'an item is a JSON object' };
95
+ const kind = str(input.kind);
96
+ if (!KINDS.includes(kind)) return { error: 'kind is one of: ' + KINDS.join(', ') };
97
+ const text = one(input.text, LIM.text);
98
+ if (!text) return { error: 'text is one plain sentence: what happened because of your work' };
99
+ if (COUNT_RE.test(text)) return { error: 'text has a count or a score. Say what happened in plain words, with no number of people or things.' };
100
+ const s = input.source;
101
+ if (!isObj(s)) return { error: 'source is { url, type, label }: no source, no item' };
102
+ const url = one(s.url, LIM.url);
103
+ if (!url || !urlOk(url)) return { error: 'source.url is the https link to the message, ticket or document (or a PMOS link that starts with /)' };
104
+ const type = str(s.type);
105
+ if (!SOURCE_TYPES.includes(type)) return { error: 'source.type is one of: ' + SOURCE_TYPES.join(', ') };
106
+ const label = one(s.label, LIM.label);
107
+ if (!label) return { error: 'source.label says where it is, for example "Slack · #idpf-data"' };
108
+ const at = str(input.at);
109
+ if (!at || !Number.isFinite(Date.parse(at))) return { error: 'at is when it happened (ISO 8601)' };
110
+ const who = one(input.who, LIM.who);
111
+ if (/\d/.test(who)) return { error: 'who is a name only' };
112
+ const id = 'im-' + hash(kind + '|' + url);
113
+ return { item: { id, kind, text, who, at: new Date(Date.parse(at)).toISOString(), source: { url, type, label } } };
114
+ }
115
+
116
+ /* ── the fold ── */
117
+ function fold(lines) {
118
+ const items = new Map(), runs = [];
119
+ let gate = { state: 'measuring' };
120
+ const runOf = (id) => runs.find((r) => r.run === id);
121
+ for (const l of lines || []) {
122
+ if (!isObj(l) || !LINES.has(l.kind)) continue;
123
+ if (l.kind === 'run' && str(l.run)) runs.push({ run: l.run, at: str(l.at), ended: false, ok: null, error: '' });
124
+ else if (l.kind === 'end' && str(l.run)) { const r = runOf(l.run); if (r && !r.ended) Object.assign(r, { ended: true, ok: !!l.ok, error: one(l.error, 200), endAt: str(l.at) }); }
125
+ else if (l.kind === 'item' && isObj(l.item) && str(l.item.id)) {
126
+ const c = clean(l.item); if (!c.item || c.item.id !== l.item.id) continue; // a line that does not pass today's rules is not an item
127
+ const was = items.get(c.item.id);
128
+ if (was && was.real !== null) continue; // the PM checked it: a later run never changes it
129
+ items.set(c.item.id, { ...c.item, real: null, read: false, filed: str(l.at), run: str(l.run) });
130
+ } else if (l.kind === 'verdict' && str(l.id)) { const it = items.get(l.id); if (it && typeof l.real === 'boolean') { it.real = l.real; it.checkedAt = str(l.at); } }
131
+ else if (l.kind === 'undo' && str(l.id)) { const it = items.get(l.id); if (it) { it.real = null; it.read = false; } }
132
+ else if (l.kind === 'seen' && Array.isArray(l.ids)) { for (const id of l.ids) { const it = items.get(String(id)); if (it && it.real === true) it.read = true; } }
133
+ else if (l.kind === 'gate' && ['measuring', 'open', 'short'].includes(l.state)) { if (gate.state !== 'open') gate = { state: l.state, at: str(l.at) }; }
134
+ }
135
+ return { items, runs, gate };
136
+ }
137
+
138
+ const weekIs = (it, start) => weekOf(dayOf(Date.parse(it.at)), start);
139
+ const byNewest = (a, b) => (a.at < b.at ? 1 : a.at > b.at ? -1 : 0);
140
+ const shown = (it) => ({ id: it.id, week: it.week, kind: it.kind, text: it.text, who: it.who, source: { ...it.source }, at: it.at, real: it.real, read: !!it.read });
141
+ function itemsByWeek(F, start) {
142
+ const m = new Map();
143
+ for (const it of F.items.values()) { const w = weekIs(it, start); if (!m.has(w)) m.set(w, []); m.get(w).push({ ...it, week: w }); }
144
+ return m;
145
+ }
146
+
147
+ /** PURE. The gate before Phase 2: a checked week is a finished week whose every item has ✓ or ✕. Across the checked weeks, at least 9 of 10
148
+ * judged items real, over at least two weeks and ten items: open (and it stays open once written). Ten or more judged and under 9 of 10: short. */
149
+ function gateOf(F, thisWeek, start = 'mon') {
150
+ const W = itemsByWeek(F, start);
151
+ let real = 0, judged = 0, weeks = 0;
152
+ for (const [w, list] of W) {
153
+ if (w >= thisWeek || !list.length || list.some((x) => x.real === null)) continue;
154
+ weeks++; judged += list.length; real += list.filter((x) => x.real === true).length;
155
+ }
156
+ if (F.gate && F.gate.state === 'open') return { state: 'open', real, judged, weeks };
157
+ const state = weeks < GATE_WEEKS || judged < GATE_ITEMS ? 'measuring' : real * 10 >= judged * 9 ? 'open' : 'short';
158
+ return { state, real, judged, weeks };
159
+ }
160
+ const growOf = (n) => GROW[n <= 0 ? 0 : n === 1 ? 1 : n <= 3 ? 2 : 3];
161
+
162
+ /** PURE. GET /api/impact/week. o: { week?, today, start } */
163
+ function weekView(F, o) {
164
+ const thisWeek = weekOf(o.today, o.start), week = o.week && DAY_RE.test(o.week) ? weekOf(o.week, o.start) : thisWeek;
165
+ const live = gateOf(F, thisWeek, o.start).state === 'open';
166
+ const real = live ? (itemsByWeek(F, o.start).get(week) || []).filter((x) => x.real === true).sort(byNewest) : [];
167
+ const cel = real.find((x) => !x.read);
168
+ return { live, first: F.items.size === 0, week, from: week, to: addDays(week, 6), label: labelOf(week, thisWeek), grow: growOf(real.length),
169
+ celebrate: cel ? cel.id : null, quiet: real.length === 0, items: real.map(shown) };
170
+ }
171
+ /** PURE. GET /api/impact/weeks: newest first, from the first week the ledger has to this week. Quiet weeks rest; nothing is lost. */
172
+ function weeksView(F, o) {
173
+ const thisWeek = weekOf(o.today, o.start);
174
+ const live = gateOf(F, thisWeek, o.start).state === 'open';
175
+ if (!live) return { live, weeks: [] };
176
+ const W = itemsByWeek(F, o.start), all = [...W.keys()].filter((w) => w <= thisWeek).sort();
177
+ const weeks = [];
178
+ if (all.length) for (let w = thisWeek; w >= all[0]; w = addDays(w, -7)) {
179
+ const real = (W.get(w) || []).filter((x) => x.real === true).sort(byNewest);
180
+ weeks.push({ week: w, from: w, to: addDays(w, 6), label: labelOf(w, thisWeek), quiet: real.length === 0, items: real.map(shown) });
181
+ }
182
+ return { live, weeks };
183
+ }
184
+ /** PURE. GET /api/impact/check: the oldest finished week with a row not checked yet, all its rows (checked ones keep their mark). */
185
+ function checkView(F, o) {
186
+ const thisWeek = weekOf(o.today, o.start), W = itemsByWeek(F, o.start);
187
+ const gate = gateOf(F, thisWeek, o.start).state;
188
+ const open = [...W.keys()].filter((w) => w < thisWeek && W.get(w).some((x) => x.real === null)).sort();
189
+ if (!open.length) return { due: false, week: null, label: '', items: [], gate };
190
+ const week = open[0];
191
+ return { due: true, week, label: labelOf(week, thisWeek), items: W.get(week).sort(byNewest).map(shown), gate };
192
+ }
193
+
194
+ module.exports = { LEDGER, KINDS, SOURCE_TYPES, GROW, GATE_ITEMS, GATE_WEEKS, COUNT_RE, dirOf, ledgerFile, readLines, read, append, clean, fold,
195
+ weekOf, labelOf, dayOf, addDays, gateOf, weekView, weeksView, checkView };
@@ -21,6 +21,7 @@
21
21
  * measure short of its target with a target date ahead, a straight line through its last four readings carried to that date. Its method is stated. Run-based series (corrections per 100 runs, merges a week) belong to the Board's Metrics card and are not built here (PRD decision 4). */
22
22
 
23
23
  const IG = require('./insights-goals.js');
24
+ const GS = require('./goal-status.js'); // batch 16 item 6: the one status of a goal, from its readings
24
25
  const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
25
26
  const isoDay = (v) => { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(v || '')); return m ? Date.UTC(+m[1], +m[2] - 1, +m[3]) : null; };
26
27
  const shortDate = (v) => { const t = isoDay(v); if (t === null) return ''; const d = new Date(t); return d.getUTCDate() + ' ' + MON[d.getUTCMonth()]; };
@@ -302,8 +303,23 @@ function milestoneOf(r, i) {
302
303
  /** One goal per KR metric record, with or without a series. `today` is a day in ms (UTC midnight). */
303
304
  /** A KR metric record's role on Intelligence (batch 15 item 1): the North Star, an input or a guardrail of it, a key result, or a program's or an
304
305
  * initiative's own measure (lib/metric-drafts.js writes them on a ✓). A record with none is a key result. */
305
- const ROLES = ['north-star', 'input', 'guardrail', 'kr', 'program-goal', 'rollup', 'success', 'signal'];
306
- function goalsOf(outcomes, charts, inits, today, meta) {
306
+ const ROLES = ['north-star', 'input', 'guardrail', 'kr', 'program-goal', 'rollup', 'success', 'signal', 'watch'];
307
+ const NOTIFY = ['push', 'intel', 'quiet'];
308
+ /** batch 16 item 6 ("Claude runs the OKRs"): what the goal list and the goal Viewer read on each goal, beside today's fields. The dot is the
309
+ * reading's (lib/goal-status.js), never an initiative's delivery status. w: { reads (lib/metric-reads.js fold), history: { rid: [{ at, text }] } } */
310
+ function watchFields(x, o, todayIso, w) {
311
+ // the outcome's own baseline, target, date and unit first: a goal's meta may hold only what New goal keeps (6-B, 2026-10-28)
312
+ const rec = Object.assign({ target: o.target, baseline: o.start, by: o.by, unit: o.unit }, x, { readings: (x && x.readings) || (o.readings || []).map((r) => ({ at: r.at, value: r.v })) });
313
+ const R = w && w.reads ? w.reads.rids.get(o.id) : null;
314
+ const recipe = x && x.recipe && typeof x.recipe === 'object' && x.recipe.connector ? { connector: String(x.recipe.connector), query: String(x.recipe.query || ''), cadence: x.recipe.cadence || 'weekly',
315
+ last: R && R.last ? { at: R.last.at, ok: R.last.ok, ...(R.last.ok ? {} : { error: R.last.error }) } : null } : null;
316
+ return { reading: GS.readingOf(rec, todayIso), recipe, who: GS.whoOf(x || {}), notify: NOTIFY.includes(x && x.notify) ? x.notify : 'intel',
317
+ was: x && typeof x.was === 'string' && x.was ? clip(x.was, 200) : null, defn: x && typeof x.defn === 'string' ? clip(x.defn, 400) : '',
318
+ history: (w && w.history && w.history[o.id]) || [], kr: x && typeof x.kr === 'string' ? x.kr : null, budget: x && typeof x.budget === 'string' ? x.budget : null,
319
+ alert: R && R.alert && R.alert.open ? { day: R.alert.day, value: R.alert.value, limit: R.alert.limit } : null };
320
+ }
321
+ function goalsOf(outcomes, charts, inits, today, meta, w) {
322
+ const todayIso = new Date(today).toISOString().slice(0, 10);
307
323
  return outcomes.map((o) => {
308
324
  const x = (meta && meta[o.id]) || {}; // the fields New goal keeps on the record (lib/insights-goals.js goalFields)
309
325
  const c = charts.find((x) => x.id === o.id) || null;
@@ -346,9 +362,19 @@ function goalsOf(outcomes, charts, inits, today, meta) {
346
362
  now, nowTxt: now !== null ? num(now, u) : '', target: tgt, targetTxt: tgt !== null ? num(tgt, u) : '', by: byAt ? shortDate(byAt) : '', byAt, fromAt,
347
363
  done, timeGone, tone: STATE_TONE[o.status] || 'q', state: o.status || 'unscored', chip: (CHIP[o.status] || ['No line scored'])[0], reason: o.reason || '',
348
364
  proj: p ? { atDue: r1(p.atDue), reaches: p.reaches, toward: p.toward } : null, pace, readings: rs.length, moves,
365
+ ...watchFields(x, o, todayIso, w),
349
366
  };
350
367
  });
351
368
  }
369
+ /** The ✦ line and the open limit alert (batch 16 item 6). drafts: the product's open drafts (lib/metric-drafts.js), counted by the route. */
370
+ function okrOf(model, drafts) {
371
+ const goals = (model.goals || []).filter((g) => g.role !== 'watch');
372
+ const a = goals.find((g) => g.alert);
373
+ const alert = a ? { rid: a.id, title: a.title, at: a.alert.day, txt: a.reading.txt, line: a.reading.line } : null;
374
+ // the owner the page shows is the goal's owner string: a goal with one has an owner on the ✦ line too
375
+ const named = goals.map((g) => (g.who || !g.owner ? g : Object.assign({}, g, { who: { name: g.owner, initials: GS.initials(g.owner), from: 'pm' } })));
376
+ return { line: GS.lineOf({ goals: named, drafts, alert, moved: GS.movedOf(named) }), alert };
377
+ }
352
378
  /** Shipped work (Deliver, Monitor, Evaluate, or done) against what its anchor goal promised. PURE. */
353
379
  function outcomesOf(inits, goals, outcomes, verdicts, todayIso) {
354
380
  const ORDER = ['verdict', 'window', 'decided'];
@@ -378,6 +404,16 @@ function budgetsOf(inits, registry) {
378
404
  return { id, anchor: 'health:' + id, title: id, moves, covers: b ? b.covers : '', cap: b ? b.cap : null, declared: !!b, reading: b && Array.isArray(inits) ? IG.budgetReading(b, inits) : null };
379
405
  });
380
406
  }
407
+ /** batch 16 item 6: a budget's limit reading comes from the kr-metrics record that names it (budget: <id>, a Stay within). With none, its dot is
408
+ * none. `reading` stays today's initiative share (lib/insights-goals.js budgetReading); the limit reading is `limit`. */
409
+ function budgetWatch(budgets, goals) {
410
+ for (const b of budgets || []) {
411
+ const g = (goals || []).find((x) => x.budget === b.id) || null;
412
+ Object.assign(b, { goal: g ? g.id : null, limit: g ? g.reading : { dot: 'none', at: null, ageDays: null, stale: false, txt: '', line: '', value: null }, recipe: g ? g.recipe : null,
413
+ who: g ? g.who : null, notify: g ? g.notify : 'intel', outcome: b.covers || (g ? g.title : '') });
414
+ }
415
+ return budgets;
416
+ }
381
417
 
382
418
  function build(facts) {
383
419
  const f = facts || {};
@@ -416,12 +452,15 @@ function build(facts) {
416
452
  };
417
453
  const today = isoDay(new Date(fin(f.now) ? f.now : Date.now()).toISOString()) || 0;
418
454
  model.today = new Date(today).toISOString().slice(0, 10);
419
- model.goals = goalsOf(outcomes, charts, f.initiatives || [], today, f.goalMeta || {});
455
+ model.goals = goalsOf(outcomes, charts, f.initiatives || [], today, f.goalMeta || {}, f.watch || null);
420
456
  model.initiativesRead = Array.isArray(f.initiatives);
421
457
  const ins = f.ins || { charts: {}, verdicts: {}, targets: {} }, bid = board.id || '';
422
458
  model.outcomes = outcomesOf(f.initiatives || [], model.goals, outcomes, ins.verdicts[bid] || {}, model.today);
423
459
  model.budgets = budgetsOf(f.initiatives || [], f.budgets || []);
424
460
  model.budgetsRead = Array.isArray(f.budgets);
461
+ budgetWatch(model.budgets, model.goals);
462
+ model.metrics = GS.metricsOf(model.goals);
463
+ model.okr = okrOf(model, (f.watch && f.watch.drafts) || 0);
425
464
  model.lateNow = Array.isArray(f.initiatives) ? f.initiatives.filter((r) => r && r.status === 'late').length : null;
426
465
  model.trends = Object.assign(IG.trendsOf(Array.isArray(f.initiatives) ? f.initiatives : null, model.today), { targets: ins.targets || {}, tiles: ins.tiles || {} });
427
466
  model.chartSet = ins.charts[bid] || {}; // { [dashboard]: { [goal]: { form, range, compare, target, forecast, note } } }
@@ -430,4 +469,4 @@ function build(facts) {
430
469
  return model;
431
470
  }
432
471
 
433
- module.exports = { lifeIndex, goalType, goalsOf, outcomesOf, budgetsOf, mdDate, build, peekModel, chartOf, mineOf, findingsOf, findingsOfChart, projectionOf, leadOf, shortDate, num };
472
+ module.exports = { okrOf, watchFields, budgetWatch, lifeIndex, goalType, goalsOf, outcomesOf, budgetsOf, mdDate, build, peekModel, chartOf, mineOf, findingsOf, findingsOfChart, projectionOf, leadOf, shortDate, num };