create-pmos 0.428.0 → 0.430.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.
- package/package.json +25 -25
- package/payload/KIT-VERSION +2 -2
- package/payload/planning/evals/eval-calibration.md +1 -1
- package/payload/planning/okrs/health-budgets.md +1 -1
- package/payload/state/discoveries.md +1 -1
- package/payload/state/log.md +1 -1
- package/workspace/briefing-premium-board-test.js +4 -4
- package/workspace/briefing-premium-insights-test.js +82 -61
- package/workspace/briefing-premium-metrics-test.js +5 -3
- package/workspace/briefing-premium-sources-test.js +5 -5
- package/workspace/briefing-premium-test.js +5 -4
- package/workspace/changelog.json +24 -0
- package/workspace/ev-everywhere-test.js +2 -2
- package/workspace/guide/adler.md +45 -0
- package/workspace/guide/briefing-premium.md +2 -0
- package/workspace/guide/home.md +4 -2
- package/workspace/guide/index.md +2 -0
- package/workspace/guide/metric-drafts.md +49 -0
- package/workspace/guide/programs.md +2 -0
- package/workspace/intel-report-ui-test.js +189 -0
- package/workspace/intelligence-gaps-ui-test.js +168 -0
- package/workspace/lib/board-metrics-premium.js +1 -1
- package/workspace/lib/headless.js +15 -2
- package/workspace/lib/initiative-writer.js +16 -2
- package/workspace/lib/insight-moves.js +135 -0
- package/workspace/lib/insights-premium.js +9 -4
- package/workspace/lib/insights-records.js +14 -5
- package/workspace/lib/intel-report.js +432 -0
- package/workspace/lib/metric-draft-runs.js +193 -0
- package/workspace/lib/metric-drafts.js +261 -0
- package/workspace/lib/metrics-cli.js +104 -0
- package/workspace/lib/page-opens.js +74 -0
- package/workspace/lib/pmos-verbs.js +3 -0
- package/workspace/lib/report-setups.js +29 -13
- package/workspace/lib/route-modules.js +3 -0
- package/workspace/lib/routes-insight-moves.js +119 -0
- package/workspace/lib/routes-insights-premium.js +12 -3
- package/workspace/lib/routes-insights-records.js +13 -5
- package/workspace/lib/routes-metric-drafts.js +150 -0
- package/workspace/lib/routes-page-opens.js +26 -0
- package/workspace/lib/routes-phone-day.js +13 -2
- package/workspace/lib/routes-report-setups.js +97 -3
- package/workspace/lib/routes-viewer.js +5 -2
- package/workspace/lib/settings-store.js +6 -0
- package/workspace/metric-drafts-ui-test.js +209 -0
- package/workspace/milestone-suggest-test.js +4 -4
- package/workspace/package-lock.json +2 -2
- package/workspace/package.json +1 -1
- package/workspace/premium-phone-card-test.js +8 -5
- package/workspace/premium-viewer-flicker-test.js +1 -1
- package/workspace/public/pm/bd-acts.js +3 -3
- package/workspace/public/pm/bd-pin-card.css +4 -4
- package/workspace/public/pm/bd-prog-panel.js +12 -7
- package/workspace/public/pm/bd-prog.js +2 -2
- package/workspace/public/pm/cozy-adler.css +82 -0
- package/workspace/public/pm/cozy-adler.js +270 -0
- package/workspace/public/pm/cozy-aud.css +1 -1
- package/workspace/public/pm/cozy-board.css +256 -256
- package/workspace/public/pm/cozy-ev.css +48 -45
- package/workspace/public/pm/cozy-evmodel.js +1 -1
- package/workspace/public/pm/cozy-home-rows.css +23 -23
- package/workspace/public/pm/cozy-home.css +211 -207
- package/workspace/public/pm/cozy-insights.css +221 -108
- package/workspace/public/pm/cozy-live-pill.css +5 -5
- package/workspace/public/pm/cozy-mtg-present.css +23 -23
- package/workspace/public/pm/cozy-nav.js +3 -1
- package/workspace/public/pm/cozy-news.js +2 -2
- package/workspace/public/pm/cozy-panel.css +29 -29
- package/workspace/public/pm/cozy-pick.css +5 -5
- package/workspace/public/pm/cozy-rec-now.css +20 -20
- package/workspace/public/pm/cozy-rec-present.css +11 -11
- package/workspace/public/pm/cozy-rec-tab.css +13 -13
- package/workspace/public/pm/cozy-search.js +4 -2
- package/workspace/public/pm/cozy-settings.js +16 -3
- package/workspace/public/pm/cozy-steps.css +9 -9
- package/workspace/public/pm/cozy-today.css +122 -71
- package/workspace/public/pm/cozy-viewer.css +7 -7
- package/workspace/public/pm/cozy-viewer.js +1 -1
- package/workspace/public/pm/cozy-vw-mtg.css +81 -81
- package/workspace/public/pm/cozy-vw-rp.css +53 -53
- package/workspace/public/pm/cozy-vw-shell.css +23 -23
- package/workspace/public/pm/cozy-vw.css +117 -117
- package/workspace/public/pm/cozy-xv.css +11 -11
- package/workspace/public/pm/cozy.css +34 -15
- package/workspace/public/pm/hi-pop.css +19 -19
- package/workspace/public/pm/home-app.js +33 -9
- package/workspace/public/pm/home-chat.js +10 -2
- package/workspace/public/pm/home-day.js +155 -27
- package/workspace/public/pm/home-ini.css +32 -32
- package/workspace/public/pm/home-line.css +7 -7
- package/workspace/public/pm/home-list.js +12 -1
- package/workspace/public/pm/home-phone-card.js +18 -15
- package/workspace/public/pm/home-today.js +5 -3
- package/workspace/public/pm/ini-view-model.js +1 -1
- package/workspace/public/pm/ini-view.css +108 -102
- package/workspace/public/pm/ini-view.js +22 -3
- package/workspace/public/pm/loose-props.css +13 -13
- package/workspace/public/pm/metric-drafts.css +89 -0
- package/workspace/public/pm/metric-drafts.js +204 -0
- package/workspace/public/pm/ms-suggest.css +8 -8
- package/workspace/public/pm/ms-suggest.js +2 -1
- package/workspace/public/pm/ov-view.css +12 -12
- package/workspace/public/pm/premium-board.js +2 -2
- package/workspace/public/pm/premium-chart-tab.js +6 -6
- package/workspace/public/pm/premium-insights.js +364 -107
- package/workspace/public/pm/premium-report-intel.css +56 -0
- package/workspace/public/pm/premium-report-intel.js +232 -0
- package/workspace/public/pm/premium-shell.js +2 -2
- package/workspace/public/pm/premium-vw-cal.js +1 -1
- package/workspace/public/pm/premium-vw-file.js +2 -2
- package/workspace/public/pm/premium-welcome.js +3 -2
- package/workspace/public/pm/premium.css +130 -128
- package/workspace/public/pm/prog-order.css +6 -6
- package/workspace/public/pm/program-charter.css +23 -23
- package/workspace/public/pm/program-model.js +7 -0
- package/workspace/public/pm/rp-parts.js +2 -2
- package/workspace/public/pm/sort-order.css +1 -1
- package/workspace/public/pm/split-merge.css +15 -15
- package/workspace/public/pm/split-merge.js +2 -1
- package/workspace/public/pm/task-card.css +21 -21
- package/workspace/public/pm/tk-tasks.css +37 -37
- package/workspace/public/pm/tk-view.css +6 -6
- package/workspace/public/pm/wf-page.css +28 -28
- package/workspace/public/premium-intelligence.html +82 -0
- package/workspace/server.js +38 -3
- package/workspace/skills/metric-draft.skill +47 -0
- package/workspace/test-lists/intel-report-ui.json +5 -0
- package/workspace/test-lists/intel-report.json +9 -0
- package/workspace/test-lists/intelligence-gaps-ui.json +5 -0
- package/workspace/test-lists/intelligence-gaps.json +5 -0
- package/workspace/test-lists/metric-drafts-ui.json +5 -0
- package/workspace/test-lists/metric-drafts.json +9 -0
- package/workspace/test-run.js +3 -0
- package/workspace/public/premium-insights.html +0 -81
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/* metric-draft-runs.js — Claude's runs that draft metrics without being asked (batch 15 item 1; lib/metric-drafts.js, contract metric-drafts-contract.md).
|
|
3
|
+
*
|
|
4
|
+
* off(env) → true when PMOS_METRIC_DRAFT=off (or 0, false, no)
|
|
5
|
+
* quarterOf(day) → { start, end, prevStart, prevEnd } of the quarter `day` (YYYY-MM-DD) is in
|
|
6
|
+
* dueOf(o) PURE → [{ scope, id, why, title }] the scopes of one workspace that need a draft now, in the order they start
|
|
7
|
+
* promptOf(skill, o) → the prompt of one run. o: { run, scope, id, why, title, today, facts: [line], kept: [line], dropped: [line] }
|
|
8
|
+
* create(deps) → { tick(opts), start({ ws, scope, id, why, press, now }), stop(run), active() }
|
|
9
|
+
*
|
|
10
|
+
* WHEN A RUN STARTS (headless kind `metric-draft`, origin `metric-draft:<ws>:<scope>:<id>:<run>`), with no press:
|
|
11
|
+
* north-star the product (the workspace) has no kr-metrics record with role north-star
|
|
12
|
+
* quarter the first 14 days of a quarter, once that quarter, when the last quarter had key results (role kr) to learn from
|
|
13
|
+
* goal a program charter (in this workspace) has no goal and no kr-metrics record with role program-goal for it
|
|
14
|
+
* success an initiative has a PRD and no kr-metrics record with initiative: <id>. The first scan writes the epoch: an initiative that
|
|
15
|
+
* had its PRD then is history, so only one that gets its PRD later is drafted unasked (the PM can press Draft again on any)
|
|
16
|
+
* A scope that was drafted once is not drafted again unasked; one whose last run failed tries again the next day. A retired record counts
|
|
17
|
+
* as no record. "Draft again" (POST /api/metric-drafts/start) starts a run at once, why `press`.
|
|
18
|
+
*
|
|
19
|
+
* WHAT THE RUN MAY DO (lib/headless.js kind `metric-draft`): read and search the repository and the stored reads, read through the PM's own
|
|
20
|
+
* connectors where the PM's Claude Code settings allow it, and file with `pmos metrics draft`, pinned by the server to this scope and run
|
|
21
|
+
* (PMOS_METRIC_DRAFT_FILE, _WS, _SCOPE, _ID, _RUN). It writes no record: only the PM's ✓ keep does. Nothing is sent.
|
|
22
|
+
*
|
|
23
|
+
* At most 2 runs at once for the machine; one per scope id; the scan of a workspace at most every 10 minutes. ■ Stop ends a run at once.
|
|
24
|
+
*
|
|
25
|
+
* deps: { workspaces() → [w], isLead(w), stateDirFor(w), records(w) → [kr-metrics record], programs(w) → [{ id, title, goal, milestones,
|
|
26
|
+
* members }] (the charters in this workspace), initiatives(w) → [{ id, title }] (those with a PRD), titleOf(w, scope, id) → string,
|
|
27
|
+
* facts(w, scope, id) → [line] (what the server knows: the charter, the PRD path, the members), open(now) → bool (the day-check
|
|
28
|
+
* window), headlessOff() → bool, env, promptFor(skillId) → skill body | null, spawn(spec), spawnNow(spec), stop(session), warn(what, err) }
|
|
29
|
+
*/
|
|
30
|
+
const crypto = require('crypto');
|
|
31
|
+
const MD = require('./metric-drafts.js');
|
|
32
|
+
|
|
33
|
+
const flagOff = (v) => /^(off|0|false|no)$/i.test(String(v || '').trim());
|
|
34
|
+
const off = (env) => flagOff((env || process.env).PMOS_METRIC_DRAFT);
|
|
35
|
+
const one = (s, n) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim().slice(0, n);
|
|
36
|
+
const MAX = 2;
|
|
37
|
+
const SCAN_MS = 10 * 60e3;
|
|
38
|
+
const QUARTER_DAYS = 14;
|
|
39
|
+
const localDay = (ms) => { const d = new Date(ms); return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0'); };
|
|
40
|
+
const p2 = (n) => String(n).padStart(2, '0');
|
|
41
|
+
const lastDay = (y, m) => new Date(Date.UTC(y, m, 0)).getUTCDate(); // m is 1..12
|
|
42
|
+
|
|
43
|
+
/** The quarter `day` is in, and the one before it. */
|
|
44
|
+
function quarterOf(day) {
|
|
45
|
+
const m = /^(\d{4})-(\d{2})/.exec(String(day || '')); if (!m) return null;
|
|
46
|
+
const y = +m[1], q0 = Math.floor((+m[2] - 1) / 3) * 3 + 1, py = q0 === 1 ? y - 1 : y, pq = q0 === 1 ? 10 : q0 - 3;
|
|
47
|
+
return { start: `${y}-${p2(q0)}-01`, end: `${y}-${p2(q0 + 2)}-${p2(lastDay(y, q0 + 2))}`, prevStart: `${py}-${p2(pq)}-01`, prevEnd: `${py}-${p2(pq + 2)}-${p2(lastDay(py, pq + 2))}` };
|
|
48
|
+
}
|
|
49
|
+
const live = (records) => (records || []).filter((r) => r && r.retired !== true);
|
|
50
|
+
/** Unasked, a scope is drafted once; a failed run tries again on a later day. */
|
|
51
|
+
function mayDraft(s, why, day) {
|
|
52
|
+
const runs = s ? s.runs.filter((r) => why === 'quarter' ? r.why === 'quarter' : r.why !== 'quarter') : [];
|
|
53
|
+
const last = runs[runs.length - 1];
|
|
54
|
+
if (!last) return true;
|
|
55
|
+
if (!last.ended) return false;
|
|
56
|
+
return !last.ok && !last.stopped && String(last.at).slice(0, 10) !== day;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* PURE. The scopes of one workspace that need a draft now.
|
|
61
|
+
* o: { ws, records: [kr-metrics], programs: [{ id, title, goal }], initiatives: [{ id, title }], F (the fold), today (YYYY-MM-DD local) }
|
|
62
|
+
*/
|
|
63
|
+
function dueOf(o) {
|
|
64
|
+
const out = [], F = o.F || { scopes: new Map(), epoch: null }, R = live(o.records), day = o.today;
|
|
65
|
+
const sOf = (scope, id) => F.scopes.get(MD.keyOf(scope, id));
|
|
66
|
+
if (!R.some((r) => r.role === 'north-star') && mayDraft(sOf('product', o.ws), 'north-star', day)) out.push({ scope: 'product', id: o.ws, why: 'north-star', title: o.wsTitle || o.ws });
|
|
67
|
+
const Q = quarterOf(day);
|
|
68
|
+
if (Q && day <= addDays(Q.start, QUARTER_DAYS - 1) && R.some((r) => r.role === 'kr' && r.by >= Q.prevStart && r.by <= Q.prevEnd)) {
|
|
69
|
+
const s = sOf('product', o.ws), done = s && s.runs.some((r) => r.why === 'quarter' && String(r.at).slice(0, 10) >= Q.start && (r.ok || !r.ended || String(r.at).slice(0, 10) === day));
|
|
70
|
+
if (!done && !out.some((x) => x.scope === 'product')) out.push({ scope: 'product', id: o.ws, why: 'quarter', title: o.wsTitle || o.ws });
|
|
71
|
+
}
|
|
72
|
+
for (const p of o.programs || []) {
|
|
73
|
+
if (!p || !p.id || one(p.goal, 200)) continue;
|
|
74
|
+
if (R.some((r) => r.program === p.id && r.role === 'program-goal')) continue;
|
|
75
|
+
if (mayDraft(sOf('program', p.id), 'goal', day)) out.push({ scope: 'program', id: p.id, why: 'goal', title: p.title || p.id });
|
|
76
|
+
}
|
|
77
|
+
const known = new Set((F.epoch && F.epoch.known) || []);
|
|
78
|
+
if (F.epoch) for (const i of o.initiatives || []) {
|
|
79
|
+
if (!i || !i.id || known.has(i.id)) continue;
|
|
80
|
+
if (R.some((r) => r.initiative === i.id)) continue;
|
|
81
|
+
if (mayDraft(sOf('initiative', i.id), 'success', day)) out.push({ scope: 'initiative', id: i.id, why: 'success', title: i.title || i.id });
|
|
82
|
+
}
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
function addDays(day, n) { const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(day); const d = new Date(Date.UTC(+m[1], +m[2] - 1, +m[3] + n)); return d.toISOString().slice(0, 10); }
|
|
86
|
+
|
|
87
|
+
const SHAPE = {
|
|
88
|
+
product: 'a North Star (1), Inputs (at most 3) and Guardrails (at most 2)',
|
|
89
|
+
quarter: 'next quarter\'s Key results (at most 5), from how the last quarter ended',
|
|
90
|
+
program: 'a Program goal (1, with checkpoints at its milestones), Rolls up from (one per product) and a Guardrail (at most 1)',
|
|
91
|
+
initiative: 'Proves it worked (1, read 4 weeks after release), an Early signal (at most 1) and a Guardrail (at most 1)',
|
|
92
|
+
};
|
|
93
|
+
function promptOf(skill, o) {
|
|
94
|
+
const list = (a, none) => (a && a.length ? a.map((x) => '- ' + x).join('\n') : '- ' + none);
|
|
95
|
+
const shape = o.why === 'quarter' ? SHAPE.quarter : SHAPE[o.scope];
|
|
96
|
+
return `${skill}\n\nThis run:\n- Run: ${o.run}\n- Scope: ${o.scope} ${o.id} · ${one(o.title, 140)}\n- Why it runs: ${MD.WHEN[o.why] || MD.WHEN.press} (${o.why})\n- Today: ${o.today}\n`
|
|
97
|
+
+ `- Draft: ${shape}. Groups: ${(o.why === 'quarter' ? ['Key results'] : MD.GROUPS[o.scope].filter((g) => g !== 'Key results')).join(', ')}.\n`
|
|
98
|
+
+ `- What PMOS knows:\n${list(o.facts, 'nothing more')}\n`
|
|
99
|
+
+ `- Already kept by the PM (do not draft these again):\n${list(o.kept, 'none')}\n`
|
|
100
|
+
+ `- Dropped by the PM (do not draft these again unless the evidence is new):\n${list(o.dropped, 'none')}\n\n`
|
|
101
|
+
+ 'File with `pmos metrics draft` only (the server pins this scope and run). Write no record. Send nothing.';
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function create(deps) {
|
|
105
|
+
const active = new Map(); // run → { ws, scope, id, dir, session }
|
|
106
|
+
const warn = deps.warn || (() => {});
|
|
107
|
+
const lastScan = new Map(); // ws → ms
|
|
108
|
+
|
|
109
|
+
function ended(run, r, now = Date.now()) {
|
|
110
|
+
const a = active.get(run); if (!a) return;
|
|
111
|
+
active.delete(run);
|
|
112
|
+
const s = MD.read(a.dir).scopes.get(MD.keyOf(a.scope, a.id));
|
|
113
|
+
if (!s || !s.run || s.run.run !== run || s.run.ended) return; // `pmos metrics draft end` or ■ Stop wrote it already
|
|
114
|
+
const res = (r && r.result) || {};
|
|
115
|
+
const ok = !!(r && !r.timedOut && !r.stopped && r.code === 0 && res.ok !== false && !res.isError);
|
|
116
|
+
try { MD.append(a.dir, null, { kind: 'end', scope: a.scope, id: a.id, run, ok, ...(ok ? {} : { error: one((r && r.note) || res.text || 'the run failed', 200) }) }, new Date(now).toISOString()); } catch (e) { warn('metric draft end', e); }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Start one run now. → { ok, run } | { ok: false, error, held? } */
|
|
120
|
+
function start({ ws, scope, id, why = 'press', press = true, now = Date.now() } = {}) {
|
|
121
|
+
if (off(deps.env) || (deps.headlessOff && deps.headlessOff())) return { ok: false, error: 'Claude\'s metric drafts are off (PMOS_METRIC_DRAFT or PMOS_HEADLESS).' };
|
|
122
|
+
if (!MD.SCOPES.includes(scope) || !id) return { ok: false, error: 'Say which product, program or initiative to draft for.' };
|
|
123
|
+
const w = (deps.workspaces() || []).find((x) => x.id === ws);
|
|
124
|
+
if (!w) return { ok: false, error: 'no such workspace' };
|
|
125
|
+
const dir = deps.stateDirFor(w);
|
|
126
|
+
if (!dir) return { ok: false, error: 'This repository has no PMOS state folder, so nothing can be drafted.' };
|
|
127
|
+
for (const [r, a] of active) if (a.ws === ws && a.scope === scope && a.id === id) return { ok: true, run: r, already: true };
|
|
128
|
+
if (active.size >= MAX) return { ok: false, held: true, error: 'Claude is drafting two others now. It drafts this one when one ends.' };
|
|
129
|
+
const skill = deps.promptFor('metric-draft');
|
|
130
|
+
if (!skill) return { ok: false, error: 'The metric-draft skill is not installed.' };
|
|
131
|
+
const run = 'md' + now.toString(36) + crypto.randomBytes(3).toString('hex');
|
|
132
|
+
const title = one((deps.titleOf && deps.titleOf(w, scope, id)) || id, 140);
|
|
133
|
+
const s = MD.read(dir).scopes.get(MD.keyOf(scope, id));
|
|
134
|
+
const rows = s ? [...s.rows.values()] : [];
|
|
135
|
+
const line = (r) => r.group + ' · ' + r.name + (r.targetTxt ? ' · ' + r.targetTxt : '');
|
|
136
|
+
let facts = [];
|
|
137
|
+
try { facts = (deps.facts && deps.facts(w, scope, id)) || []; } catch { facts = []; }
|
|
138
|
+
const prompt = promptOf(skill, { run, scope, id, why, title, today: localDay(now), facts, kept: rows.filter((r) => r.state === 'kept').map(line), dropped: rows.filter((r) => r.state === 'dropped').map(line) });
|
|
139
|
+
const go = press && deps.spawnNow ? deps.spawnNow : deps.spawn;
|
|
140
|
+
active.set(run, { ws, scope, id, dir, session: null });
|
|
141
|
+
let session = null;
|
|
142
|
+
try {
|
|
143
|
+
session = go({ name: 'Drafting metrics · ' + one(title, 60), ws, origin: `metric-draft:${ws}:${scope}:${id}:${run}`, initialInput: prompt + '\r', ...(scope === 'initiative' ? { initiative: id } : {}),
|
|
144
|
+
env: { PMOS_METRIC_DRAFT_FILE: MD.ledgerFile(dir), PMOS_METRIC_DRAFT_WS: ws, PMOS_METRIC_DRAFT_SCOPE: scope, PMOS_METRIC_DRAFT_ID: id, PMOS_METRIC_DRAFT_RUN: run }, onDone: (r) => ended(run, r) });
|
|
145
|
+
} catch (e) { warn('metric draft run', e); }
|
|
146
|
+
if (session && session.held) { active.delete(run); return { ok: false, held: true, error: 'Claude is busy with other runs. It tries again in a minute.' }; }
|
|
147
|
+
// the start line lands before the run's first `pmos metrics draft` (the run starts reading after this returns), stamped with the tick's clock
|
|
148
|
+
MD.append(dir, null, { kind: 'start', scope, id, run, why, title, when: MD.WHEN[why] || '' }, new Date(now).toISOString());
|
|
149
|
+
if (!session || session.state === 'exited' || session.headless !== 'metric-draft') {
|
|
150
|
+
if (session && session.headless !== 'metric-draft' && session.state !== 'exited' && deps.stop) { try { deps.stop(session); } catch { /* best effort */ } }
|
|
151
|
+
ended(run, { code: 1, note: (session && session.note) || 'the run could not start in the background', result: {} }, now);
|
|
152
|
+
return { ok: false, error: (session && session.note) || 'Claude could not start drafting.' };
|
|
153
|
+
}
|
|
154
|
+
const a = active.get(run); if (a) a.session = session;
|
|
155
|
+
return { ok: true, run };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function stop(run) { const a = active.get(run); if (a && a.session && deps.stop) deps.stop(a.session); }
|
|
159
|
+
|
|
160
|
+
function tick({ now = Date.now(), env } = {}) {
|
|
161
|
+
if (off(env || deps.env) || (deps.headlessOff && deps.headlessOff())) return { off: true };
|
|
162
|
+
if (active.size >= MAX) return { running: active.size };
|
|
163
|
+
let open = true;
|
|
164
|
+
try { open = deps.open ? !!deps.open(now) : true; } catch { open = true; }
|
|
165
|
+
if (!open) return { started: null, closed: true };
|
|
166
|
+
const day = localDay(now);
|
|
167
|
+
for (const w of deps.workspaces() || []) {
|
|
168
|
+
if (deps.isLead && !deps.isLead(w)) continue;
|
|
169
|
+
if (now - (lastScan.get(w.id) || -Infinity) < SCAN_MS) continue;
|
|
170
|
+
const dir = deps.stateDirFor(w); if (!dir) continue;
|
|
171
|
+
lastScan.set(w.id, now);
|
|
172
|
+
const F = MD.read(dir);
|
|
173
|
+
let records = [], programs = [], initiatives = [];
|
|
174
|
+
try { records = deps.records(w) || []; } catch (e) { warn('metric draft records', e); continue; }
|
|
175
|
+
try { programs = (deps.programs && deps.programs(w)) || []; } catch { programs = []; }
|
|
176
|
+
try { initiatives = (deps.initiatives && deps.initiatives(w)) || []; } catch { initiatives = []; }
|
|
177
|
+
// the first scan writes the epoch: the initiatives that have a PRD now are history (an old PRD is not a new one)
|
|
178
|
+
if (!F.epoch) { MD.append(dir, null, { kind: 'epoch', scope: null, id: null, known: initiatives.map((i) => i.id) }, new Date(now).toISOString()); F.epoch = { known: initiatives.map((i) => i.id) }; }
|
|
179
|
+
const due = dueOf({ ws: w.id, wsTitle: w.name || w.id, records, programs, initiatives, F, today: day });
|
|
180
|
+
for (const d of due) {
|
|
181
|
+
if ([...active.values()].some((a) => a.ws === w.id && a.scope === d.scope && a.id === d.id)) continue;
|
|
182
|
+
const r = start({ ws: w.id, scope: d.scope, id: d.id, why: d.why, press: false, now });
|
|
183
|
+
if (r.ok) return { started: d.scope + ':' + d.id, why: d.why };
|
|
184
|
+
if (r.held) { lastScan.delete(w.id); return { held: true }; }
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return { started: null };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
return { tick, start, stop, active: () => [...active.keys()], runOf: (ws, scope, id) => { for (const [r, a] of active) if (a.ws === ws && a.scope === scope && a.id === id) return r; return null; } };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
module.exports = { off, quarterOf, dueOf, promptOf, create, MAX, SCAN_MS, QUARTER_DAYS };
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/* metric-drafts.js — the metrics Claude drafts without being asked (batch 15 item 1, the Intelligence build; contract metric-drafts-contract.md,
|
|
3
|
+
* canvas Iq8Suggest and Iq9Draft). THE ONE WRITER and THE ONE FOLD of <state>/metric-drafts.jsonl. lib/routes-metric-drafts.js does the I/O;
|
|
4
|
+
* lib/metric-draft-runs.js starts the runs; lib/metrics-cli.js is what a run files with. Pure, with no clock of its own: every time comes in.
|
|
5
|
+
*
|
|
6
|
+
* THREE SCOPES, ONE LEDGER. A scope is { scope, id }:
|
|
7
|
+
* product id = the workspace id. No North Star: a North Star (1), Inputs (≤3) and Guardrails (≤2). At a quarter's start: Key results (≤5).
|
|
8
|
+
* program id = the program id. The charter has no goal: Program goal (1, with checkpoints at its milestones), Rolls up from (one per
|
|
9
|
+
* product, ≤8) and Guardrail (≤1).
|
|
10
|
+
* initiative id = the initiative id. It has a PRD and no success measure: Proves it worked (1, "4 weeks after release"), Early signal (≤1)
|
|
11
|
+
* and Guardrail (≤1).
|
|
12
|
+
*
|
|
13
|
+
* THE LEDGER. One line per event, { at, by, kind, scope, id, ... }:
|
|
14
|
+
* epoch { known: [initiative id] } the first scan: the initiatives that had a PRD then are history, never drafted unasked
|
|
15
|
+
* start { run, why, title, when } a run began; why ∈ north-star · quarter · goal · success · press
|
|
16
|
+
* step { run, step } the strip: 0 read · 1 shape · 2 measure · 3 target · 4 ready
|
|
17
|
+
* read { run, t, f, state } one source read; the last line for a title in a run wins (state done · now · wait)
|
|
18
|
+
* row { run, row } one drafted row (clean() shape); the last line for a row id wins
|
|
19
|
+
* end { run, ok, stopped?, error?, head?, sub?, src? } the run ended; `pmos metrics draft end` says the head, sub and sources
|
|
20
|
+
* keep { row, rid } ✓: the kr-metrics record it wrote
|
|
21
|
+
* drop { row } ✕
|
|
22
|
+
* undo { row, rid? } a kept row back to open (its record retired), or a dropped one back to open
|
|
23
|
+
* edit { row, set: { name?, target?, targetTxt?, source? } } the PM's inline edit of an open row (batch 16 item 1); a later run's row line replaces it
|
|
24
|
+
* A new run's start clears every row of the scope that was not kept: it drafts again. A kept row is the PM's and stays.
|
|
25
|
+
*
|
|
26
|
+
* ledgerFile(dir) · readLines(file) · read(dir) → fold · append(dir, actor, line, at)
|
|
27
|
+
* fold(lines) PURE → { scopes: Map key → S, epoch } S: { scope, id, title, when, run, runs, rows: Map, head, sub, src }
|
|
28
|
+
* viewOf(F, scope, id, o) PURE → the GET body (no ok): { scope, id, title, when, run: { state, step, reads }, rows, head, sub, src }
|
|
29
|
+
* clean(scope, input) → { row } | { error } what `pmos metrics draft row` checks
|
|
30
|
+
* keepFields(scope, id, row, o) → { fields, reading } | { error } the kr-metrics record a ✓ writes
|
|
31
|
+
* editOf(row, input) → { set } | { error } what the inline edit may change: name, target, source (lib/routes-metric-drafts.js /edit)
|
|
32
|
+
* rowId(scope, id, group, name) · keyOf(scope, id) · countIn(S, run, group)
|
|
33
|
+
* SCOPES · GROUPS · LIMITS · ROLES · TYPES · STEPS · WHEN
|
|
34
|
+
*/
|
|
35
|
+
const fs = require('fs');
|
|
36
|
+
const path = require('path');
|
|
37
|
+
const crypto = require('crypto');
|
|
38
|
+
|
|
39
|
+
const LEDGER = 'metric-drafts.jsonl';
|
|
40
|
+
const KINDS = new Set(['epoch', 'start', 'step', 'read', 'row', 'end', 'keep', 'drop', 'undo', 'edit']);
|
|
41
|
+
const SCOPES = ['product', 'program', 'initiative'];
|
|
42
|
+
const GROUPS = { product: ['North Star', 'Inputs', 'Guardrails', 'Key results'], program: ['Program goal', 'Rolls up from', 'Guardrail'], initiative: ['Proves it worked', 'Early signal', 'Guardrail'] };
|
|
43
|
+
const LIMITS = { 'North Star': 1, Inputs: 3, Guardrails: 2, 'Key results': 5, 'Program goal': 1, 'Rolls up from': 8, Guardrail: 1, 'Proves it worked': 1, 'Early signal': 1 };
|
|
44
|
+
const ROLES = {
|
|
45
|
+
product: { 'North Star': 'north-star', Inputs: 'input', Guardrails: 'guardrail', 'Key results': 'kr' },
|
|
46
|
+
program: { 'Program goal': 'program-goal', 'Rolls up from': 'rollup', Guardrail: 'guardrail' },
|
|
47
|
+
initiative: { 'Proves it worked': 'success', 'Early signal': 'signal', Guardrail: 'guardrail' },
|
|
48
|
+
};
|
|
49
|
+
const TYPES = ['Count', 'Percentage', 'Amount', 'Duration', 'Done or not', 'Stay within'];
|
|
50
|
+
const UNIT_OF = { Percentage: '%', Duration: 'days', Amount: '$', Count: '' };
|
|
51
|
+
const STEPS = ['read', 'shape', 'measure', 'target', 'ready'];
|
|
52
|
+
const READ_STATES = ['done', 'now', 'wait'];
|
|
53
|
+
const WHYS = ['north-star', 'quarter', 'goal', 'success', 'press'];
|
|
54
|
+
/** The "when" line of each trigger, as the page says it. */
|
|
55
|
+
const WHEN = {
|
|
56
|
+
'north-star': 'A product was connected with no North Star',
|
|
57
|
+
quarter: 'A new quarter started',
|
|
58
|
+
goal: 'The program charter has no goal',
|
|
59
|
+
success: 'The initiative has a PRD and no success measure',
|
|
60
|
+
press: 'You asked me to draft again',
|
|
61
|
+
};
|
|
62
|
+
const WINDOW = '4 weeks after release';
|
|
63
|
+
const DAY_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
64
|
+
const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
|
|
65
|
+
const str = (v) => (typeof v === 'string' ? v : '');
|
|
66
|
+
const one = (v, n) => String(v == null ? '' : v).replace(/\s+/g, ' ').trim().slice(0, n);
|
|
67
|
+
const fin = (v) => typeof v === 'number' && Number.isFinite(v);
|
|
68
|
+
const hash = (s) => crypto.createHash('sha1').update(String(s)).digest('hex').slice(0, 10);
|
|
69
|
+
const keyOf = (scope, id) => scope + ':' + id;
|
|
70
|
+
const rowId = (scope, id, group, name) => 'md-' + hash([scope, id, group, String(name || '').toLowerCase()].join('|'));
|
|
71
|
+
|
|
72
|
+
/* ── the ledger ── */
|
|
73
|
+
function ledgerFile(dir) { return dir ? path.join(dir, LEDGER) : null; }
|
|
74
|
+
function readLines(file) {
|
|
75
|
+
if (!file) return [];
|
|
76
|
+
let text = '';
|
|
77
|
+
try { text = fs.readFileSync(file, 'utf8'); } catch { return []; }
|
|
78
|
+
const out = [];
|
|
79
|
+
for (const raw of text.split('\n')) { if (!raw.trim()) continue; try { const l = JSON.parse(raw); if (isObj(l) && KINDS.has(l.kind)) out.push(l); } catch { /* a torn line is skipped */ } }
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
function read(dir) { return fold(readLines(ledgerFile(dir))); }
|
|
83
|
+
/** One line. `at` is the caller's clock (an ISO string); the writer has none of its own. */
|
|
84
|
+
function append(dir, actor, ev, at) {
|
|
85
|
+
const line = { at: at || null, by: (actor && actor.by) || null, ...ev };
|
|
86
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
87
|
+
fs.appendFileSync(ledgerFile(dir), JSON.stringify(line) + '\n');
|
|
88
|
+
return line;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/* ── what a run may file (`pmos metrics draft row`): every number with its source, a missing event with its ticket ── */
|
|
92
|
+
const LIM = { name: 80, txt: 40, why: 160, source: 40, key: 24, text: 400, unit: 12, pillar: 80, label: 40 };
|
|
93
|
+
const numOrNull = (v) => (v === null || v === undefined || v === '' ? { v: null } : fin(v) ? { v } : { error: true });
|
|
94
|
+
/** → { row } | { error }. input: { group, name, type, now, nowTxt, target, targetTxt, by, why, source, ticket, checkpoints, direction, unit, pillar } */
|
|
95
|
+
function clean(scope, input) {
|
|
96
|
+
if (!SCOPES.includes(scope)) return { error: 'scope is one of ' + SCOPES.join(', ') };
|
|
97
|
+
if (!isObj(input)) return { error: 'a row is a JSON object' };
|
|
98
|
+
const group = str(input.group);
|
|
99
|
+
if (!GROUPS[scope].includes(group)) return { error: `group of a ${scope} is one of: ${GROUPS[scope].join(', ')}` };
|
|
100
|
+
const name = one(input.name, LIM.name);
|
|
101
|
+
if (!name) return { error: 'name is the metric, in a few words' };
|
|
102
|
+
const type = str(input.type);
|
|
103
|
+
if (!TYPES.includes(type)) return { error: 'type is one of: ' + TYPES.join(', ') };
|
|
104
|
+
const why = one(input.why, LIM.why);
|
|
105
|
+
if (!why) return { error: 'why is one line: the reason for this metric and its target' };
|
|
106
|
+
const now = numOrNull(input.now), target = numOrNull(input.target);
|
|
107
|
+
if (now.error) return { error: 'now is a number from the readings, or null when no event counts it' };
|
|
108
|
+
if (target.error) return { error: 'target is a number, or null for Done or not' };
|
|
109
|
+
const source = one(input.source, LIM.source);
|
|
110
|
+
let ticket = null;
|
|
111
|
+
if (input.ticket != null) {
|
|
112
|
+
if (!isObj(input.ticket) || !one(input.ticket.key, LIM.key) || !one(input.ticket.text, LIM.text)) return { error: 'ticket is { key, text }: the drafted ticket for the missing event' };
|
|
113
|
+
ticket = { key: one(input.ticket.key, LIM.key), text: one(input.ticket.text, LIM.text) };
|
|
114
|
+
}
|
|
115
|
+
// every number comes from real readings: a "now" names where it was read; no event to count it is said with the drafted ticket
|
|
116
|
+
if (now.v == null && !ticket && type !== 'Done or not') return { error: 'now is null only with a ticket: { key, text } drafts the event that would count it' };
|
|
117
|
+
if (now.v != null && !source) return { error: 'a measured now names its source (Amplitude, Jira, …)' };
|
|
118
|
+
if (target.v == null && type !== 'Done or not') return { error: 'target is a number: from the baseline and past launches' };
|
|
119
|
+
const by = input.by == null || input.by === '' ? null : String(input.by);
|
|
120
|
+
if (by != null && !DAY_RE.test(by)) return { error: 'by is YYYY-MM-DD' };
|
|
121
|
+
if (by == null && type !== 'Stay within') return { error: 'by is the date the target is due (YYYY-MM-DD); only a Stay within guardrail may have none' };
|
|
122
|
+
if (now.v != null && target.v != null && now.v === target.v) return { error: type === 'Stay within' ? 'the limit equals the reading now: give the limit the evidence says (the worst week of the last 8, a service level)' : 'the target equals now: a target moves the metric' };
|
|
123
|
+
const direction = ['up', 'down'].includes(input.direction) ? input.direction : null;
|
|
124
|
+
const checkpoints = [];
|
|
125
|
+
if (input.checkpoints != null) {
|
|
126
|
+
if (!Array.isArray(input.checkpoints) || input.checkpoints.length > 6) return { error: 'checkpoints is a list of at most 6 { by, target, label }' };
|
|
127
|
+
for (const c of input.checkpoints) {
|
|
128
|
+
if (!isObj(c) || !DAY_RE.test(String(c.by || '')) || !fin(c.target)) return { error: 'each checkpoint is { by: YYYY-MM-DD, target: number, label }' };
|
|
129
|
+
checkpoints.push({ by: String(c.by), target: c.target, label: one(c.label, LIM.label) });
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
const row = { group, name, type, now: now.v, nowTxt: one(input.nowTxt, LIM.txt) || (now.v == null ? '—' : String(now.v)), target: target.v,
|
|
133
|
+
targetTxt: one(input.targetTxt, LIM.txt) || (target.v == null ? 'Done' : String(target.v)), by, why, source, ticket };
|
|
134
|
+
if (checkpoints.length) row.checkpoints = checkpoints;
|
|
135
|
+
if (direction) row.direction = direction;
|
|
136
|
+
const unit = one(input.unit, LIM.unit); if (unit) row.unit = unit;
|
|
137
|
+
const pillar = one(input.pillar, LIM.pillar); if (pillar && group === 'Key results') row.pillar = pillar;
|
|
138
|
+
return { row };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/* ── the PM's inline edit of an open draft (batch 16 item 1): its name, its target and where it is measured. The rest (why, now, the group) stays
|
|
142
|
+
* Claude's: a change to those is asked of Claude in Home's chat. The target keeps the draft's own way of writing it ("≤ 3%", "$1,200"): the first
|
|
143
|
+
* number in it is replaced. ── */
|
|
144
|
+
const EDIT_KEYS = ['name', 'target', 'targetTxt', 'source'];
|
|
145
|
+
function editOf(row, input) {
|
|
146
|
+
if (!isObj(row)) return { error: 'There is no such draft.' };
|
|
147
|
+
if (!isObj(input)) return { error: 'An edit is { name?, target?, source? }.' };
|
|
148
|
+
const set = {};
|
|
149
|
+
if (input.name !== undefined) { const n = one(input.name, LIM.name); if (!n) return { error: 'The name is the metric, in a few words.' }; if (n !== row.name) set.name = n; }
|
|
150
|
+
if (input.target !== undefined && row.type !== 'Done or not') {
|
|
151
|
+
const t = typeof input.target === 'string' && input.target.trim() !== '' ? Number(input.target.replace(/[,\s]/g, '')) : input.target;
|
|
152
|
+
if (!fin(t)) return { error: 'The target is a number.' };
|
|
153
|
+
if (fin(row.now) && t === row.now) return { error: row.type === 'Stay within' ? 'The limit equals the reading now. Give it room.' : 'The target equals Now, so there is nothing to move.' };
|
|
154
|
+
if (t !== row.target) {
|
|
155
|
+
set.target = t;
|
|
156
|
+
const was = String(row.targetTxt || ''), m = /-?\d[\d,]*(\.\d+)?/.exec(was);
|
|
157
|
+
set.targetTxt = one(m ? was.slice(0, m.index) + String(t) + was.slice(m.index + m[0].length) : String(t), LIM.txt);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
if (input.source !== undefined) {
|
|
161
|
+
const src = one(input.source, LIM.source);
|
|
162
|
+
if (!src && row.now != null) return { error: 'A measured Now names its source (Amplitude, Jira, …).' };
|
|
163
|
+
if (src !== (row.source || '')) set.source = src;
|
|
164
|
+
}
|
|
165
|
+
return { set };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/* ── the fold ── */
|
|
169
|
+
const blank = (scope, id) => ({ scope, id, title: '', when: '', run: null, runs: [], rows: new Map(), head: '', sub: '', src: '' });
|
|
170
|
+
function fold(lines) {
|
|
171
|
+
const scopes = new Map();
|
|
172
|
+
let epoch = null;
|
|
173
|
+
const S = (l) => { const k = keyOf(l.scope, l.id); if (!scopes.has(k)) scopes.set(k, blank(l.scope, l.id)); return scopes.get(k); };
|
|
174
|
+
for (const l of lines || []) {
|
|
175
|
+
if (!isObj(l) || !KINDS.has(l.kind)) continue;
|
|
176
|
+
if (l.kind === 'epoch') { if (!epoch) epoch = { at: str(l.at), known: Array.isArray(l.known) ? l.known.map(String) : [] }; continue; }
|
|
177
|
+
if (!SCOPES.includes(l.scope) || !str(l.id)) continue;
|
|
178
|
+
const s = S(l), cur = s.run && s.run.run === l.run ? s.run : null;
|
|
179
|
+
if (l.kind === 'start' && str(l.run)) {
|
|
180
|
+
s.run = { run: l.run, why: WHYS.includes(l.why) ? l.why : 'press', at: str(l.at), step: 0, reads: [], ended: false, ok: null, stopped: false, error: '' };
|
|
181
|
+
s.runs.push(s.run);
|
|
182
|
+
s.title = one(l.title, 140) || s.title || l.id; s.when = one(l.when, 140) || WHEN[s.run.why] || '';
|
|
183
|
+
s.head = ''; s.sub = ''; s.src = '';
|
|
184
|
+
for (const [rid, r] of s.rows) if (r.state !== 'kept') s.rows.delete(rid);
|
|
185
|
+
} else if (l.kind === 'step' && cur && !cur.ended) { const n = Number(l.step); if (Number.isInteger(n) && n >= 0 && n <= 4) cur.step = Math.max(cur.step, n); }
|
|
186
|
+
else if (l.kind === 'read' && cur && !cur.ended && str(l.t)) {
|
|
187
|
+
const r = { t: one(l.t, 60), f: one(l.f, 200), state: READ_STATES.includes(l.state) ? l.state : 'done' };
|
|
188
|
+
const i = cur.reads.findIndex((x) => x.t === r.t);
|
|
189
|
+
if (i >= 0) cur.reads[i] = r; else cur.reads.push(r);
|
|
190
|
+
} else if (l.kind === 'row' && cur && !cur.ended && isObj(l.row) && str(l.row.id)) {
|
|
191
|
+
const was = s.rows.get(l.row.id);
|
|
192
|
+
if (was && was.state === 'kept') continue; // the PM kept it: a run never changes what the PM kept
|
|
193
|
+
s.rows.set(l.row.id, { ...l.row, state: 'open', run: l.run, at: str(l.at) });
|
|
194
|
+
} else if (l.kind === 'end' && cur && !cur.ended) {
|
|
195
|
+
Object.assign(cur, { ended: true, ok: !!l.ok, stopped: !!l.stopped, error: one(l.error, 200), endAt: str(l.at) });
|
|
196
|
+
if (cur.ok && !cur.stopped) cur.step = 4;
|
|
197
|
+
if (str(l.head)) s.head = one(l.head, 200);
|
|
198
|
+
if (str(l.sub)) s.sub = one(l.sub, 300);
|
|
199
|
+
if (str(l.src)) s.src = one(l.src, 300);
|
|
200
|
+
} else if (l.kind === 'keep' && str(l.row)) { const r = s.rows.get(l.row); if (r && r.state === 'open') Object.assign(r, { state: 'kept', rid: str(l.rid) || null }); }
|
|
201
|
+
else if (l.kind === 'edit' && str(l.row) && isObj(l.set)) { const r = s.rows.get(l.row); if (r && r.state === 'open') for (const k of EDIT_KEYS) if (l.set[k] !== undefined) r[k] = l.set[k]; }
|
|
202
|
+
else if (l.kind === 'drop' && str(l.row)) { const r = s.rows.get(l.row); if (r && r.state === 'open') r.state = 'dropped'; }
|
|
203
|
+
else if (l.kind === 'undo' && str(l.row)) { const r = s.rows.get(l.row); if (r && r.state !== 'open') { r.state = 'open'; delete r.rid; } }
|
|
204
|
+
}
|
|
205
|
+
return { scopes, epoch };
|
|
206
|
+
}
|
|
207
|
+
/** How many rows of a group one run filed (the limits are per run). */
|
|
208
|
+
function countIn(s, run, group) { let n = 0; if (s) for (const r of s.rows.values()) if (r.run === run && r.group === group) n++; return n; }
|
|
209
|
+
|
|
210
|
+
const ROW_KEYS = ['id', 'group', 'name', 'type', 'now', 'nowTxt', 'target', 'targetTxt', 'by', 'why', 'source', 'ticket', 'checkpoints', 'state', 'rid', 'direction', 'unit', 'pillar'];
|
|
211
|
+
/** The GET body (without ok). o: { off } (PMOS_METRIC_DRAFT=off). Zero is silence: no run and no row is run.state idle and rows []. */
|
|
212
|
+
function viewOf(F, scope, id, o = {}) {
|
|
213
|
+
const s = (F && F.scopes.get(keyOf(scope, id))) || blank(scope, id);
|
|
214
|
+
const R = s.run, order = GROUPS[scope] || [];
|
|
215
|
+
const rows = [...s.rows.values()].sort((a, b) => order.indexOf(a.group) - order.indexOf(b.group)).map((r) => {
|
|
216
|
+
const out = {}; for (const k of ROW_KEYS) if (r[k] !== undefined) out[k] = r[k];
|
|
217
|
+
if (out.ticket === undefined) out.ticket = null;
|
|
218
|
+
return out;
|
|
219
|
+
});
|
|
220
|
+
let state = 'idle';
|
|
221
|
+
if (R && !R.ended) state = 'running';
|
|
222
|
+
else if (R && !R.ok && !R.stopped) state = 'failed';
|
|
223
|
+
else if (rows.length) state = 'ready';
|
|
224
|
+
if (o.off && state !== 'running') state = 'off';
|
|
225
|
+
return { scope, id, title: s.title || id, when: s.when, run: { state, step: R ? R.step : 0, reads: R && state !== 'off' ? R.reads.slice() : [], ...(R ? { id: R.run, why: R.why, at: R.at } : {}), ...(R && R.error ? { error: R.error } : {}) },
|
|
226
|
+
rows, head: s.head, sub: s.sub, src: s.src };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/* ── ✓ keep: the kr-metrics record (scripts/records). A KR metric needs a baseline, a target and a date, so, as lib/insights-goals.js does:
|
|
230
|
+
* Done or not baseline 0 (not done) or now, target 1; Stay within the reading now and its limit, always on to the year's end when it has no date;
|
|
231
|
+
* no event yet (now null) baseline 0 with measured: false and the ticket, so the page says it waits for the event and never shows the 0 as read ── */
|
|
232
|
+
function keepFields(scope, id, row, o = {}) {
|
|
233
|
+
if (!isObj(row) || !SCOPES.includes(scope)) return { error: 'no such draft' };
|
|
234
|
+
const role = (ROLES[scope] || {})[row.group];
|
|
235
|
+
if (!role) return { error: 'This draft has no group, so it cannot be kept.' };
|
|
236
|
+
const type = row.type, now = fin(row.now) ? row.now : null;
|
|
237
|
+
let baseline, target, direction, by = row.by || null;
|
|
238
|
+
const f = { metric: row.name, type, role };
|
|
239
|
+
if (type === 'Done or not') { baseline = now == null ? 0 : now ? 1 : 0; target = 1; direction = 'up'; f.unit = 'done'; }
|
|
240
|
+
else {
|
|
241
|
+
target = row.target;
|
|
242
|
+
if (!fin(target)) return { error: 'This draft has no target, so it cannot be kept.' };
|
|
243
|
+
baseline = now == null ? 0 : now;
|
|
244
|
+
direction = row.direction || (now == null ? 'up' : target >= now ? 'up' : 'down');
|
|
245
|
+
if (type === 'Stay within') { f.limit = direction === 'down' ? 'ceiling' : 'floor'; if (!by) { by = String(o.today || '').slice(0, 4) + '-12-31'; f.always_on = true; } }
|
|
246
|
+
f.unit = row.unit || UNIT_OF[type] || '';
|
|
247
|
+
}
|
|
248
|
+
if (!DAY_RE.test(String(by || ''))) return { error: 'This draft has no date, so it cannot be kept.' };
|
|
249
|
+
if (baseline === target) return { error: 'The target equals the baseline, so there is nothing to move. Drop it or draft again.' };
|
|
250
|
+
Object.assign(f, { baseline, target, by, direction, source: row.source || '', why: row.why || '' });
|
|
251
|
+
if (now == null && type !== 'Done or not') f.measured = false;
|
|
252
|
+
if (row.ticket) f.ticket = { key: row.ticket.key, text: row.ticket.text };
|
|
253
|
+
if (row.pillar) f.pillar = row.pillar;
|
|
254
|
+
if (scope === 'program') { f.program = id; if (Array.isArray(row.checkpoints) && row.checkpoints.length) f.checkpoints = row.checkpoints.map((c) => ({ by: c.by, target: c.target, label: c.label || '' })); }
|
|
255
|
+
if (scope === 'initiative') { f.initiative = id; f.window = WINDOW; }
|
|
256
|
+
if (scope === 'product') f.product = id;
|
|
257
|
+
f.draft = row.id;
|
|
258
|
+
return { fields: f, reading: now != null && DAY_RE.test(String(o.today || '')) ? { at: o.today, value: now } : null };
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
module.exports = { LEDGER, SCOPES, GROUPS, LIMITS, ROLES, TYPES, STEPS, WHEN, WHYS, WINDOW, ledgerFile, readLines, read, append, fold, viewOf, clean, keepFields, editOf, rowId, keyOf, countIn };
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/* metrics-cli.js — `pmos metrics draft`: the one write of Claude's metric-draft run (batch 15 item 1; lib/metric-drafts.js, lib/metric-draft-runs.js).
|
|
3
|
+
* What it files waits on the page as a draft until the PM's ✓ keep, which alone writes the kr-metrics record.
|
|
4
|
+
*
|
|
5
|
+
* pmos metrics draft read "<source>" --found "<one line>" [--state done|now|wait] one source read, for the strip's first step
|
|
6
|
+
* pmos metrics draft step shape|measure|target|ready the strip moves on
|
|
7
|
+
* pmos metrics draft row --json <file|-> one drafted row, or a list of them
|
|
8
|
+
* pmos metrics draft end --head "<line>" [--sub "<line>"] [--src "<a · b · c>"] the run is done: what the page says on top
|
|
9
|
+
* pmos metrics draft status what this scope holds: open, kept and dropped
|
|
10
|
+
*
|
|
11
|
+
* The server pins the scope, the run and the ledger in the run's environment (PMOS_METRIC_DRAFT_FILE, _WS, _SCOPE, _ID, _RUN); outside such
|
|
12
|
+
* a run the verb refuses: the PM keeps and drops on the page. A row the PM kept is not filed again. Exit codes: 0 filed, 1 refused, 2 usage.
|
|
13
|
+
* It writes no record and sends nothing. */
|
|
14
|
+
const fs = require('fs');
|
|
15
|
+
const MD = require('./metric-drafts.js');
|
|
16
|
+
|
|
17
|
+
const COMMANDS = { metrics: ['draft'] };
|
|
18
|
+
const SUBS = ['read', 'step', 'row', 'end', 'status'];
|
|
19
|
+
const USAGE = [
|
|
20
|
+
'usage: pmos metrics draft read|step|row|end|status — the metrics Claude drafts for the PM to keep or drop',
|
|
21
|
+
' pmos metrics draft read "<source>" --found "<what it says, one line>" [--state done|now|wait]',
|
|
22
|
+
' pmos metrics draft step shape|measure|target|ready',
|
|
23
|
+
' pmos metrics draft row --json <file|->',
|
|
24
|
+
' { "group", "name", "type": "' + MD.TYPES.join('" | "') + '", "now": <number from the readings> | null,',
|
|
25
|
+
' "nowTxt", "target", "targetTxt", "by": "YYYY-MM-DD", "why": "<one line>", "source": "Amplitude",',
|
|
26
|
+
' "ticket": { "key", "text" } (only when no event counts it, with now null), "checkpoints"?: [{ "by", "target", "label" }],',
|
|
27
|
+
' "direction"?: "up" | "down", "unit"?, "pillar"? (Key results) }',
|
|
28
|
+
' pmos metrics draft end --head "<I drafted …>" [--sub "<where it comes from>"] [--src "<Product brief · Amplitude>"]',
|
|
29
|
+
' pmos metrics draft status',
|
|
30
|
+
'Every number comes from a real reading. The PM keeps or drops each row on the page. Nothing is sent.',
|
|
31
|
+
];
|
|
32
|
+
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; };
|
|
33
|
+
function readJson(src, stdin) {
|
|
34
|
+
let text;
|
|
35
|
+
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)}` }; }
|
|
36
|
+
try { return { body: JSON.parse(text) }; } catch { return { error: 'the input is not JSON' }; }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function run(argv, { say = (s) => console.log(s), env = process.env, stdin, now = Date.now() } = {}) {
|
|
40
|
+
const args = argv[0] === 'metrics' ? argv.slice(1) : argv.slice();
|
|
41
|
+
if (!args[0] || ['help', '--help', '-h'].includes(args[0])) { for (const l of USAGE) say(l); return args[0] ? 0 : 1; }
|
|
42
|
+
if (args[0] !== 'draft') { say(`unknown metrics command "${args[0]}". Use: pmos metrics draft ${SUBS.join('|')}`); return 2; }
|
|
43
|
+
const sub = args[1];
|
|
44
|
+
if (!sub || ['help', '--help', '-h'].includes(sub)) { for (const l of USAGE) say(l); return sub ? 0 : 1; }
|
|
45
|
+
if (!SUBS.includes(sub)) { say(`unknown draft command "${sub}". Use one of: ${SUBS.join(', ')}`); return 2; }
|
|
46
|
+
const file = env.PMOS_METRIC_DRAFT_FILE, runId = env.PMOS_METRIC_DRAFT_RUN, scope = env.PMOS_METRIC_DRAFT_SCOPE, id = env.PMOS_METRIC_DRAFT_ID;
|
|
47
|
+
if (!file || !runId || !MD.SCOPES.includes(scope) || !id) { say('✗ pmos metrics draft is for Claude\'s metric-draft run. The PM keeps and drops drafts on the page.'); return 1; }
|
|
48
|
+
const F = MD.fold(MD.readLines(file)), s = F.scopes.get(MD.keyOf(scope, id));
|
|
49
|
+
const at = new Date(now).toISOString();
|
|
50
|
+
const line = (ev) => { fs.appendFileSync(file, JSON.stringify({ at, by: null, scope, id, run: runId, ...ev }) + '\n'); };
|
|
51
|
+
|
|
52
|
+
if (sub === 'status') {
|
|
53
|
+
if (!s || !s.rows.size) say('nothing drafted for ' + scope + ' ' + id);
|
|
54
|
+
else for (const r of s.rows.values()) say(`${r.state.padEnd(7)} ${r.id} · ${r.group} · ${r.name} · now ${r.nowTxt} · target ${r.targetTxt}`);
|
|
55
|
+
return 0;
|
|
56
|
+
}
|
|
57
|
+
if (!s || !s.run || s.run.run !== runId || s.run.ended) { say('✗ this run is not drafting now. It ended, or the PM pressed Stop. File nothing more.'); return 1; }
|
|
58
|
+
const pos = args.slice(2).filter((x, i, a) => !x.startsWith('--') && !(i > 0 && a[i - 1].startsWith('--')));
|
|
59
|
+
|
|
60
|
+
if (sub === 'read') {
|
|
61
|
+
const t = String(pos[0] || '').replace(/\s+/g, ' ').trim().slice(0, 60), f = flag(args, 'found'), state = flag(args, 'state') || 'done';
|
|
62
|
+
if (!t || typeof f !== 'string' || !f.trim()) { say('usage: pmos metrics draft read "<source>" --found "<what it says, one line>" [--state done|now|wait]'); return 2; }
|
|
63
|
+
if (!['done', 'now', 'wait'].includes(state)) { say('✗ --state is done, now or wait'); return 2; }
|
|
64
|
+
line({ kind: 'read', t, f: f.replace(/\s+/g, ' ').trim().slice(0, 200), state });
|
|
65
|
+
say(`read ${t}`);
|
|
66
|
+
return 0;
|
|
67
|
+
}
|
|
68
|
+
if (sub === 'step') {
|
|
69
|
+
const n = MD.STEPS.indexOf(String(pos[0] || ''));
|
|
70
|
+
if (n < 1) { say('usage: pmos metrics draft step shape|measure|target|ready'); return 2; }
|
|
71
|
+
line({ kind: 'step', step: n });
|
|
72
|
+
say(`step ${MD.STEPS[n]}`);
|
|
73
|
+
return 0;
|
|
74
|
+
}
|
|
75
|
+
if (sub === 'end') {
|
|
76
|
+
const head = flag(args, 'head');
|
|
77
|
+
if (typeof head !== 'string' || !head.trim()) { say('usage: pmos metrics draft end --head "<I drafted …>" [--sub "<line>"] [--src "<a · b>"]'); return 2; }
|
|
78
|
+
const opt = (k) => { const v = flag(args, k); return typeof v === 'string' ? v.replace(/\s+/g, ' ').trim().slice(0, 300) : ''; };
|
|
79
|
+
if (![...s.rows.values()].some((r) => r.run === runId)) { say('✗ this run filed no row. File the rows first, or end with nothing: stop and say why in your answer.'); return 1; }
|
|
80
|
+
line({ kind: 'end', ok: true, head: head.replace(/\s+/g, ' ').trim().slice(0, 200), sub: opt('sub'), src: opt('src') });
|
|
81
|
+
say('ended: ready for the PM');
|
|
82
|
+
return 0;
|
|
83
|
+
}
|
|
84
|
+
// row
|
|
85
|
+
const jsonAt = args.indexOf('--json'), src = jsonAt >= 0 ? args[jsonAt + 1] : null;
|
|
86
|
+
if (!src) { say('usage: pmos metrics draft row --json <file|->'); return 2; }
|
|
87
|
+
const r = readJson(src, stdin); if (r.error) { say('✗ ' + r.error); return 1; }
|
|
88
|
+
let bad = 0;
|
|
89
|
+
const filed = new Map(); // group → rows filed in this call (the limits are per run)
|
|
90
|
+
for (const x of Array.isArray(r.body) ? r.body : [r.body]) {
|
|
91
|
+
const c = MD.clean(scope, x);
|
|
92
|
+
if (c.error) { say(`✗ refused: ${c.error}`); bad++; continue; }
|
|
93
|
+
const rid = MD.rowId(scope, id, c.row.group, c.row.name), was = s.rows.get(rid);
|
|
94
|
+
if (was && was.state === 'kept') { say(`kept ${rid}: the PM kept "${c.row.name}" already. Draft something new.`); continue; }
|
|
95
|
+
const n = MD.countIn(s, runId, c.row.group) + (filed.get(c.row.group) || 0) - (was && was.run === runId ? 1 : 0);
|
|
96
|
+
if (n >= MD.LIMITS[c.row.group]) { say(`✗ refused: ${c.row.group} takes at most ${MD.LIMITS[c.row.group]} in one run`); bad++; continue; }
|
|
97
|
+
line({ kind: 'row', row: { id: rid, ...c.row } });
|
|
98
|
+
if (!(was && was.run === runId)) filed.set(c.row.group, (filed.get(c.row.group) || 0) + 1);
|
|
99
|
+
say(`filed ${rid} · ${c.row.group} · ${c.row.name}${c.row.ticket ? ' · ticket ' + c.row.ticket.key + ' drafted' : ''}`);
|
|
100
|
+
}
|
|
101
|
+
return bad ? 1 : 0;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
module.exports = { run, COMMANDS, USAGE, SUBS };
|