create-pmos 0.313.0 → 0.315.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.
@@ -0,0 +1,101 @@
1
+ 'use strict';
2
+ /* board-metric-records.js — the two records behind the Board's Metrics card and its Insights twin (initiative briefing-premium-metrics, option C).
3
+ * THE ONE WRITER and THE ONE FOLD of <state>/board-metric-targets.jsonl and <state>/board-metric-history.jsonl.
4
+ *
5
+ * KEYS the four measures: corrections · merges · blocked · idle
6
+ * targetsFile(root) · historyFile(root)
7
+ * checkTarget(input) → { ok: true, value: { key, target } } | { ok: false, status, error } PURE (target null clears it)
8
+ * foldTargets(lines) → { [key]: { target, at, actor } } PURE: the last line of each key; a clear drops it
9
+ * targets(root) → the fold of the file
10
+ * saveTarget(root, input, actor, { now }) → { ok: true, targets } | { ok: false, status, error }
11
+ * dayOf(now) → 'YYYY-MM-DD' (UTC) PURE
12
+ * history(root) → [{ day, blocked, idle, open }] in day order, one per day (the first line of a day wins)
13
+ * record(root, { now, blocked, idle, open }) → true when it appended today's line, false when today already has one
14
+ *
15
+ * TARGETS. Lines { v: 1, ev: set | clear, key, target, actor, at }. The PM sets one on the Insights page; the Board and Insights both read it. A target is a
16
+ * number the PM typed: nothing here proposes one.
17
+ * HISTORY. Blocked and Idle come from the workflow engine, which keeps no history. From the first day the card is read, one line per UTC day records the
18
+ * counts, so their charts start on that day and never before it. Lines { v: 1, day, blocked, idle, open, at }. Both files are append-only and never
19
+ * rewritten; a torn line is skipped. */
20
+ const fs = require('fs');
21
+ const path = require('path');
22
+
23
+ const KEYS = ['corrections', 'merges', 'blocked', 'idle'];
24
+ const TARGET_MAX = 1e6;
25
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
26
+ const refuse = (status, error) => ({ ok: false, status, error });
27
+
28
+ function stateDir(root) {
29
+ const abs = path.resolve(String(root));
30
+ return path.join(abs, require('./report-draft.js').stateRel(abs));
31
+ }
32
+ const targetsFile = (root) => path.join(stateDir(root), 'board-metric-targets.jsonl');
33
+ const historyFile = (root) => path.join(stateDir(root), 'board-metric-history.jsonl');
34
+
35
+ function readLines(file) {
36
+ let text = '';
37
+ try { text = fs.readFileSync(file, 'utf8'); } catch { return []; }
38
+ const out = [];
39
+ for (const raw of text.split('\n')) {
40
+ if (!raw.trim()) continue;
41
+ try { const l = JSON.parse(raw); if (isObj(l)) out.push(l); } catch { /* a torn line is skipped */ }
42
+ }
43
+ return out;
44
+ }
45
+
46
+ function checkTarget(input) {
47
+ const i = isObj(input) ? input : {};
48
+ if (!KEYS.includes(i.key)) return refuse(400, 'Name the measure: corrections, merges, blocked or idle.');
49
+ if (i.target === null || i.target === '') return { ok: true, value: { key: i.key, target: null } };
50
+ const t = typeof i.target === 'number' ? i.target : typeof i.target === 'string' && i.target.trim() !== '' ? Number(i.target) : NaN;
51
+ if (!Number.isFinite(t) || t < 0 || t > TARGET_MAX) return refuse(400, 'The target must be a number of 0 or more.');
52
+ return { ok: true, value: { key: i.key, target: Math.round(t * 100) / 100 } };
53
+ }
54
+
55
+ function foldTargets(lines) {
56
+ const out = {};
57
+ for (const l of lines || []) {
58
+ if (!KEYS.includes(l.key)) continue;
59
+ if (l.ev === 'clear') delete out[l.key];
60
+ else if (l.ev === 'set' && typeof l.target === 'number' && Number.isFinite(l.target)) out[l.key] = { target: l.target, at: l.at || null, actor: l.actor || null };
61
+ }
62
+ return out;
63
+ }
64
+ const targets = (root) => foldTargets(readLines(targetsFile(root)));
65
+
66
+ /** THE SINGLE WRITER of board-metric-targets.jsonl. */
67
+ function saveTarget(root, input, actor, { now } = {}) {
68
+ const c = checkTarget(input);
69
+ if (!c.ok) return c;
70
+ const t = now == null ? Date.now() : now, v = c.value;
71
+ const line = v.target === null ? { v: 1, ev: 'clear', key: v.key, actor: actor || null, at: new Date(t).toISOString() } : { v: 1, ev: 'set', key: v.key, target: v.target, actor: actor || null, at: new Date(t).toISOString() };
72
+ const file = targetsFile(root);
73
+ fs.mkdirSync(path.dirname(file), { recursive: true });
74
+ fs.appendFileSync(file, JSON.stringify(line) + '\n');
75
+ return { ok: true, targets: targets(root) };
76
+ }
77
+
78
+ const dayOf = (now) => new Date(now).toISOString().slice(0, 10);
79
+ const count = (v) => Number.isInteger(v) && v >= 0;
80
+
81
+ function history(root) {
82
+ const seen = new Set(), out = [];
83
+ for (const l of readLines(historyFile(root))) {
84
+ if (typeof l.day !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(l.day) || seen.has(l.day) || !count(l.blocked) || !count(l.idle)) continue;
85
+ seen.add(l.day); out.push({ day: l.day, blocked: l.blocked, idle: l.idle, open: count(l.open) ? l.open : null });
86
+ }
87
+ return out.sort((a, z) => (a.day < z.day ? -1 : a.day > z.day ? 1 : 0));
88
+ }
89
+
90
+ /** THE SINGLE WRITER of board-metric-history.jsonl: today's counts, once a day. */
91
+ function record(root, { now, blocked, idle, open }) {
92
+ if (!count(blocked) || !count(idle)) return false;
93
+ const t = now == null ? Date.now() : now, day = dayOf(t);
94
+ if (history(root).some((h) => h.day === day)) return false;
95
+ const file = historyFile(root);
96
+ fs.mkdirSync(path.dirname(file), { recursive: true });
97
+ fs.appendFileSync(file, JSON.stringify({ v: 1, day, blocked, idle, open: count(open) ? open : null, at: new Date(t).toISOString() }) + '\n');
98
+ return true;
99
+ }
100
+
101
+ module.exports = { KEYS, targetsFile, historyFile, checkTarget, foldTargets, targets, saveTarget, dayOf, history, record };
@@ -1,20 +1,25 @@
1
1
  'use strict';
2
2
  /* lib/board-metrics-premium.js — the Metrics card of a tenant's premium Board (initiative briefing-premium-metrics).
3
3
  *
4
- * build(facts) → model PURE. facts = { now, repo, runs[]|null, commits[]|null (ms), inits[]|null, initsPending, missing[] }
5
- * read({ root, engine, now }) → model the card of one workspace's repository: its run log, its trunk's history, its workflow state.
4
+ * build(facts) → model PURE. facts = { now, repo, runs[]|null, commits[]|null (ms), inits[]|null, initsPending, missing[],
5
+ * weeks (8 | 26 | 52, default 8), targets { [key]: { target } }, history [{ day, blocked, idle }] }
6
+ * read({ root, engine, now, weeks }) → model the card of one workspace's repository: its run log, its trunk's history, its workflow state, the
7
+ * targets the PM set on Insights and the daily Blocked/Idle history (lib/board-metric-records.js). It
8
+ * appends today's Blocked/Idle line once the workflow state is known: that is the one write it makes.
6
9
  * weeksTo(now, n) → [{ from, to, label }] PURE. The n weeks (Monday to Sunday, UTC) that end with the week of `now`.
7
10
  *
8
11
  * THE RULE THE FILE FOLLOWS: a number is made only from a record of the repository it names. A source that cannot be read is "Not read", a
9
- * repository with no run log has "No runs yet", a week with too few runs is blank, and no target exists, so no tile is "on target" or "off target".
10
- * A tile that needs a look (kind warn or bad) is marked `look`; the page draws that with the mockup's chip and orange outline. Blocked and Idle keep no
11
- * history and have no chart. */
12
+ * repository with no run log has "No runs yet", a week with too few runs is blank. A target exists only where the PM set one on Insights; a tile with one
13
+ * carries `tg`, its gap and an on/off-target chip, and a tile without one is never called on or off target. A tile that is off target, or needs a look
14
+ * (kind warn or bad) with no target, is marked `look`; the page draws that with the mockup's chip and orange outline. Blocked and Idle have history only
15
+ * from the first day the card was read: earlier weeks are blank, never zero. */
12
16
  const fs = require('fs');
13
17
  const path = require('path');
14
18
  const { execFile } = require('child_process');
15
19
  const BP = require('./briefing-premium.js');
20
+ const Rec = require('./board-metric-records.js');
16
21
 
17
- const WEEKS = 8, MIN_RUNS = 10, DAY = 86400000, IDLE_DAYS = 30;
22
+ const WEEKS = 8, RANGES = [8, 26, 52], MIN_RUNS = 10, DAY = 86400000, IDLE_DAYS = 30;
18
23
  const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
19
24
  const day = (t) => { const d = new Date(t); return d.getUTCDate() + ' ' + MON[d.getUTCMonth()]; };
20
25
  const plural = (n, one, many) => (n === 1 ? one : many);
@@ -41,9 +46,10 @@ function change(prev, cur, dec) {
41
46
  }
42
47
 
43
48
  function build(f) {
44
- const now = f.now || Date.now(), W = weeksTo(now), missing = (f.missing || []).slice();
49
+ const now = f.now || Date.now(), N = RANGES.includes(f.weeks) ? f.weeks : WEEKS, W = weeksTo(now, N), missing = (f.missing || []).slice();
45
50
  const repo = f.repo || '';
46
51
  const tiles = [];
52
+ let counted = null; // today's Blocked/Idle counts, for the reader to keep
47
53
 
48
54
  // corrections per 100 runs
49
55
  if (f.runs === 'missing') tiles.push({ key: 'corrections', label: 'Corrections per 100 runs', absent: 'No runs yet', why: 'No agent run is logged in ' + repo + ' yet. Runs are read from planning/runs/agent-runs.jsonl.', def: DEFS.corrections });
@@ -54,7 +60,7 @@ function build(f) {
54
60
  return { n: rs.length, v: rs.length >= MIN_RUNS ? Math.round(rs.reduce((a, r) => a + Number(r.human_corrections), 0) / rs.length * 1000) / 10 : null };
55
61
  });
56
62
  const ser = per.map((p) => p.v), li = ser.map((v, i) => (v != null ? i : -1)).filter((i) => i >= 0).pop();
57
- if (li == null) tiles.push({ key: 'corrections', label: 'Corrections per 100 runs', absent: 'No weeks yet', why: 'No week of the last ' + WEEKS + ' has ' + MIN_RUNS + ' runs with a logged correction count. ' + f.runs.length + ' ' + plural(f.runs.length, 'run is', 'runs are') + ' on record in all.', def: DEFS.corrections });
63
+ if (li == null) tiles.push({ key: 'corrections', label: 'Corrections per 100 runs', absent: 'No weeks yet', why: 'No week of the last ' + N + ' has ' + MIN_RUNS + ' runs with a logged correction count. ' + f.runs.length + ' ' + plural(f.runs.length, 'run is', 'runs are') + ' on record in all.', def: DEFS.corrections });
58
64
  else {
59
65
  const ch = li > 0 ? change(ser[li - 1], ser[li], 1) : null;
60
66
  tiles.push({ key: 'corrections', label: 'Corrections per 100 runs', value: ser[li].toFixed(1), text: 'week to ' + W[li].label + ', ' + per[li].n + ' runs', kind: ch ? (ch.d === 0 ? '' : ch.good ? 'ok' : 'warn') : '', ser, wk: W.map((w) => w.label), nt: per.map((p) => (p.n ? p.n + ' ' + plural(p.n, 'run', 'runs') : '')), dec: 1, suf: '', change: ch, def: DEFS.corrections, lowBetter: true });
@@ -68,37 +74,57 @@ function build(f) {
68
74
  tiles.push({ key: 'merges', label: 'Merged a week', value: String(ser[li]), text: 'to the trunk, week to ' + W[li].label, kind: '', ser, wk: W.map((w) => w.label), nt: ser.map(() => ''), dec: 0, suf: '', change: li > 0 ? (() => { const d = ser[li] - ser[li - 1]; return { d, good: d > 0, txt: (d === 0 ? 'No change' : (d > 0 ? 'Up ' : 'Down ') + Math.abs(d)) + ' vs last week' }; })() : null, def: DEFS.merges, lowBetter: false });
69
75
  }
70
76
 
71
- // blocked, idle
77
+ // blocked, idle: today's count, and earlier weeks from the daily history that starts on the first day the card was read
72
78
  const waiting = (key, label, def) => ({ key, label, absent: f.initsPending ? 'Reading' : 'Not read', why: f.initsPending ? 'The workflow engine is deriving the initiatives of ' + repo + '. This tile fills in when it ends.' : 'The workflow engine could not be run in ' + repo + '.', def, pending: !!f.initsPending });
73
79
  if (!f.inits) { tiles.push(waiting('blocked', 'Blocked', DEFS.blocked), waiting('idle', 'Idle for a month', DEFS.idle)); }
74
80
  else {
75
81
  const open = f.inits.filter((i) => !i.accepted && !i.stopped);
76
82
  const blocked = open.filter((i) => (i.steps || []).some((s) => s.status === 'blocked')).length;
77
83
  const idle = open.filter((i) => { const t = Date.parse(i.last_activity); return !Number.isFinite(t) || now - t > IDLE_DAYS * DAY; }).length;
78
- tiles.push(
79
- { key: 'blocked', label: 'Blocked', value: String(blocked), text: 'of ' + open.length + ' open. No history is kept', kind: blocked ? 'bad' : '', def: DEFS.blocked, lowBetter: true },
80
- { key: 'idle', label: 'Idle for a month', value: String(idle), text: 'of ' + open.length + ' open. No history is kept', kind: idle ? 'warn' : '', def: DEFS.idle, lowBetter: true },
81
- );
84
+ const hist = (f.history || []).filter((h) => Date.parse(h.day) < W[W.length - 1].from); // this week is today's live count
85
+ const first = (f.history || []).length ? Date.parse(f.history[0].day) : now;
86
+ const since = Rec.dayOf(Math.min(first, now)) === Rec.dayOf(now) ? 'history starts today' : 'history starts ' + day(Math.min(first, now));
87
+ const serOf = (k, live) => W.map((w, j) => { if (j === W.length - 1) return live; const inWk = hist.filter((h) => { const t = Date.parse(h.day); return t >= w.from && t < w.to; }); return inWk.length ? inWk[inWk.length - 1][k] : null; });
88
+ const hTile = (key, label, live, kind, def) => {
89
+ const ser = serOf(key, live), prev = ser.length > 1 ? ser[ser.length - 2] : null;
90
+ const ch = prev == null ? null : (() => { const d = live - prev; return { d, good: d < 0, txt: (d === 0 ? 'No change' : (d > 0 ? 'Up ' : 'Down ') + Math.abs(d)) + ' vs last week' }; })();
91
+ return { key, label, value: String(live), text: 'of ' + open.length + ' open · ' + since, kind, ser, wk: W.map((w) => w.label), nt: ser.map(() => ''), dec: 0, suf: '', change: ch, since, def, lowBetter: true };
92
+ };
93
+ tiles.push(hTile('blocked', 'Blocked', blocked, blocked ? 'bad' : '', DEFS.blocked), hTile('idle', 'Idle for a month', idle, idle ? 'warn' : '', DEFS.idle));
94
+ counted = { blocked, idle, open: open.length };
95
+ }
96
+
97
+ // targets the PM set on Insights: a chip, a gap and the dashed line, only where one exists
98
+ const T = f.targets || {};
99
+ for (const t of tiles) {
100
+ const tg = T[t.key] && Number.isFinite(T[t.key].target) ? T[t.key].target : null;
101
+ if (t.absent || tg == null) continue;
102
+ const v = Number(t.value), dec = t.dec || 0, ok = t.lowBetter ? v <= tg : v >= tg, gap = Math.abs(v - tg);
103
+ Object.assign(t, { tg, ok, gap: gap.toFixed(dec), chip: ok ? 'On target' : gap.toFixed(dec) + (t.lowBetter ? ' over' : ' short'), targetTxt: 'target ' + tg.toFixed(dec), kind: ok ? 'ok' : 'warn' });
82
104
  }
83
105
 
84
106
  // one row per tile for the read-only agent (key board:metric-<tile>), in the shape the Board's own rows have
85
107
  const rows = tiles.map((t) => {
86
- const say = t.absent ? t.label + ' is not shown: ' + t.why : t.label + ' is ' + t.value + ', ' + t.text + '.' + (t.change ? ' ' + t.change.txt + '.' : '');
87
- const facts = [['Measure', t.label], ['Now', t.absent ? t.absent : t.value], ['Counted from', repo], ['Better when', t.lowBetter ? 'Lower' : t.lowBetter === false ? 'Higher' : '']]
108
+ const say = t.absent ? t.label + ' is not shown: ' + t.why : t.label + ' is ' + t.value + ', ' + t.text + '.' + (t.change ? ' ' + t.change.txt + '.' : '') + (t.tg != null ? ' The target is ' + t.tg + ': ' + (t.ok ? 'on target' : t.chip) + '.' : '');
109
+ const facts = [['Measure', t.label], ['Now', t.absent ? t.absent : t.value], ['Target', t.tg != null ? String(t.tg) : ''], ['Counted from', repo], ['Better when', t.lowBetter ? 'Lower' : t.lowBetter === false ? 'Higher' : '']]
88
110
  .concat(t.ser ? t.ser.map((v, j) => [t.wk[j], v == null ? 'No runs' : String(v)]) : []).filter((x) => x[1] !== '');
89
111
  t.rowKey = 'board:metric-' + t.key;
90
112
  return { key: t.rowKey, id: null, title: t.label, sub: 'Metric · ' + repo, dialog: { say, facts, files: [] } };
91
113
  });
92
- tiles.forEach((t) => { t.look = t.kind === 'warn' || t.kind === 'bad'; });
93
- const look = tiles.filter((t) => t.look).length;
114
+ tiles.forEach((t) => { t.look = t.tg != null ? !t.ok : t.kind === 'warn' || t.kind === 'bad'; });
115
+ const look = tiles.filter((t) => t.look).length, withTg = tiles.filter((t) => t.tg != null).length;
94
116
  const lead = look ? look + ' of ' + tiles.length + ' need a look.' : '';
95
- const body = 'Each chart is one measure over the last ' + WEEKS + ' weeks. No measure here has a target, so none is on or off target. Orange needs a look. Press a measure for its definition and values. A week with fewer than ' + MIN_RUNS + ' runs is left blank.';
117
+ const body = 'Each chart is one measure over the last ' + N + ' weeks. ' + (withTg
118
+ ? 'The dashed line is the target set on Insights. Orange is off target or needs a look.' + (withTg < tiles.length ? ' ' + (tiles.length - withTg) + ' ' + plural(tiles.length - withTg, 'measure has', 'measures have') + ' no target.' : '')
119
+ : 'No measure here has a target yet, so none is on or off target. Orange needs a look.')
120
+ + ' Press a measure for its definition and values. A week with fewer than ' + MIN_RUNS + ' runs is left blank. Blocked and idle are kept from the first day this card was read.';
96
121
  return {
97
122
  state: 'ready', pending: !!f.initsPending, repo,
98
123
  header: missing.length ? 'not read: ' + missing.join(', ') : 'counted from ' + repo,
99
124
  look, lead, body,
100
- hint: (lead ? lead + ' ' : '') + body + ' For the KR measures and your own set of charts, open Insights.',
101
- note: 'Counted from ' + repo + ': corrections from planning/runs/agent-runs.jsonl, merges from the history of its trunk, blocked and idle from its workflow state, in weeks to ' + W[W.length - 1].label + '. A week with fewer than ' + MIN_RUNS + ' runs is blank. Blocked and idle keep no history.',
125
+ weeks: N, counted,
126
+ hint: (lead ? lead + ' ' : '') + body + ' To set a target, or for longer ranges, open Insights.',
127
+ note: 'Counted from ' + repo + ': corrections from planning/runs/agent-runs.jsonl, merges from the history of its trunk, blocked and idle from its workflow state, in weeks to ' + W[W.length - 1].label + '. A week with fewer than ' + MIN_RUNS + ' runs is blank. Blocked and idle are kept once a day from the first day this card was read; earlier weeks are blank.',
102
128
  tiles, rows,
103
129
  };
104
130
  }
@@ -107,8 +133,8 @@ function build(f) {
107
133
  const git = (args) => new Promise((res) => execFile('git', args, { maxBuffer: 64 * 1024 * 1024, timeout: 60000 }, (e, out) => res(e ? null : String(out))));
108
134
  const kept = new Map(); // root → { key, inits, inflight }
109
135
 
110
- async function readCommits(root, now) {
111
- const since = new Date(weeksTo(now)[0].from).toISOString();
136
+ async function readCommits(root, now, n = WEEKS) {
137
+ const since = new Date(weeksTo(now, n)[0].from).toISOString();
112
138
  const ref = (await git(['-C', root, 'rev-parse', '--verify', '-q', 'origin/main'])) ? 'origin/main' : 'HEAD';
113
139
  const out = await git(['-C', root, 'log', '--first-parent', '--since=' + since, '--format=%ct', ref]);
114
140
  return out === null ? null : out.split('\n').filter(Boolean).map((x) => Number(x) * 1000);
@@ -121,7 +147,7 @@ function readRuns(root) {
121
147
  }
122
148
 
123
149
  /** The card of one repository. Runs and history are read at once; the workflow state is slow, so it is derived in the background and kept until the repository changes. */
124
- async function read({ root, engine, now = Date.now() }) {
150
+ async function read({ root, engine, now = Date.now(), weeks = WEEKS }) {
125
151
  const k = kept.get(root) || { key: null, inits: null, inflight: false }; kept.set(root, k);
126
152
  const key = await BP.repoKey(root);
127
153
  if (!k.inflight && engine && (!k.inits || k.key !== key)) {
@@ -129,10 +155,15 @@ async function read({ root, engine, now = Date.now() }) {
129
155
  BP.readInitiatives({ root, engine }).then((inits) => { if (inits) { k.inits = inits; k.key = key; } }).catch(() => { }).finally(() => { k.inflight = false; });
130
156
  }
131
157
  const repo = path.basename(root);
132
- const model = build({ now, repo, runs: readRuns(root), commits: await readCommits(root, now), inits: k.inits, initsPending: !!engine && !k.inits && k.inflight });
158
+ const N = RANGES.includes(weeks) ? weeks : WEEKS;
159
+ let targets = {}, history = [];
160
+ try { targets = Rec.targets(root); } catch { /* no target file reads as none */ }
161
+ try { history = Rec.history(root); } catch { /* no history reads as none */ }
162
+ const model = build({ now, repo, weeks: N, runs: readRuns(root), commits: await readCommits(root, now, N), inits: k.inits, initsPending: !!engine && !k.inits && k.inflight, targets, history });
163
+ if (model.counted) { try { Rec.record(root, Object.assign({ now }, model.counted)); } catch { /* a read-only folder keeps no history */ } }
133
164
  return model;
134
165
  }
135
166
 
136
167
  const forget = () => kept.clear();
137
168
 
138
- module.exports = { build, read, weeksTo, forget, MIN_RUNS };
169
+ module.exports = { build, read, weeksTo, forget, MIN_RUNS, RANGES };
@@ -6,9 +6,11 @@
6
6
  *
7
7
  * THE RULE THE FILE FOLLOWS (as lib/briefing-premium.js): a sentence, a count or a chip is made only from a field of an item. A clause with no
8
8
  * record is left out. The hero, the card headers and the dock read ONE definition of "to clear": inbox + today + agent drafts to review (M9).
9
- * The tray is the PM's own unsorted captures: an item the PM added (source local) that no date or flag has placed yet, so it waits in the inbox
10
- * placement. It is not counted as work to clear until the PM places it. The shelf, the capacity figure and the week bars of the mockup have no record
11
- * behind them and are not built (PRD D15, amended by the PM 2026-10-17 to add the tray).
9
+ * The PM's own unsorted captures (an item the PM added, source local, that no date or flag has placed yet) wait in the inbox beside the items
10
+ * from Jira and Slack. They are not counted as work to clear until the PM places it. The shelf, the capacity figure and the week bars of the mockup
11
+ * have no record behind them and are not built (PRD D15, amended by the PM 2026-10-17 to add the captures).
12
+ * The Work queue (PM, 2026-10-19): one card holds what On your plate, With agents and the tray held, as tabs. No item shows in two tabs except
13
+ * Kept, which is a mark on an item and not a place.
12
14
  * An agent draft is the agent's text: it is shown labelled and is never counted as done. */
13
15
 
14
16
  const WORDS = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve'];
@@ -118,7 +120,7 @@ function fridayOf({ today, work, tray, ready, review }) {
118
120
  const first = (a) => (a[0] ? 'work:' + (a[0].it ? a[0].it.id : a[0].id) : null);
119
121
  const steps = [
120
122
  { key: 'inbox', label: 'Sort the inbox', n: (work.inbox || []).length, first: first(work.inbox || []) },
121
- { key: 'tray', label: 'Place your tray', n: tray.length, first: first(tray) },
123
+ { key: 'tray', label: 'Place what you added', n: tray.length, first: first(tray) },
122
124
  { key: 'waiting', label: 'Check who owes you', n: (work.waiting || []).length, first: first(work.waiting || []) },
123
125
  { key: 'drafts', label: 'Review agent drafts', n: ready.length, first: first(ready) },
124
126
  { key: 'stale', label: 'Look at what sat untouched', n: review.length, first: first(review) },
@@ -133,7 +135,7 @@ function rowOf(it, list, v, inReview, focusIds) {
133
135
  const sub = [srcLabel(it) + (it.key && it.source !== 'local' ? ' ' + it.key : ''), it.priority, it.waiting_on ? 'waiting on ' + it.waiting_on : null, (it.steps || []).length ? (it.steps || []).length + ' ' + plural((it.steps || []).length, 'step', 'steps') + ((it.steps || []).some((x) => x.who === 'agent-does' || x.who === 'agent-drafts') ? ' · agent can do ' + (it.steps || []).filter((x) => x.who !== 'you').length : '') : null].filter(Boolean).join(' · ');
134
136
  const days = it.waiting_since ? daysBetween(String(it.waiting_since).slice(0, 10), today) : null;
135
137
  const facts = [
136
- ['From', srcLabel(it)], ['Place', list === 'upcoming' ? 'Upcoming' : list.charAt(0).toUpperCase() + list.slice(1)], ['Due', it.due ? shortDate(it.due) + (overdue ? ' (overdue)' : '') : ''],
138
+ ['From', srcLabel(it)], ['Place', list === 'upcoming' ? 'Upcoming' : list === 'tray' ? 'Inbox, added by you' : list.charAt(0).toUpperCase() + list.slice(1)], ['Due', it.due ? shortDate(it.due) + (overdue ? ' (overdue)' : '') : ''],
137
139
  ['Priority', it.priority], ['Waiting on', it.waiting_on], ['Waiting since', it.waiting_since ? shortDate(String(it.waiting_since).slice(0, 10)) + (days != null ? ' (' + days + ' ' + plural(days, 'day', 'days') + ')' : '') : ''],
138
140
  ['Not before', it.defer && it.defer > today ? shortDate(it.defer) : ''], ['Added', it.created_at ? shortDate(String(it.created_at).slice(0, 10)) : ''], ['Last touched', it.touched_at ? shortDate(String(it.touched_at).slice(0, 10)) : ''],
139
141
  ].filter((x) => x[1]);
@@ -144,7 +146,7 @@ function rowOf(it, list, v, inReview, focusIds) {
144
146
  if (list !== 'waiting') actions.push('waiting');
145
147
  actions.push('remove');
146
148
  if (inReview) actions.push('keep');
147
- const say = overdue ? 'This was due ' + shortDate(it.due) + ' and is still open.' : list === 'tray' ? 'You threw this in. It has no date or place yet. Place it, or drop it.' : list === 'inbox' ? 'This is new and has no date or place yet.' : list === 'waiting' ? 'You are waiting on ' + (it.waiting_on || 'someone') + (days != null ? ' for ' + days + ' ' + plural(days, 'day', 'days') : '') + '.' : 'This is on your list.';
149
+ const say = overdue ? 'This was due ' + shortDate(it.due) + ' and is still open.' : list === 'tray' ? 'You added this. It has no date or place yet. Place it, or drop it.' : list === 'inbox' ? 'This is new and has no date or place yet.' : list === 'waiting' ? 'You are waiting on ' + (it.waiting_on || 'someone') + (days != null ? ' for ' + days + ' ' + plural(days, 'day', 'days') : '') + '.' : 'This is on your list.';
148
150
  const { sug, cta } = suggestOf(it, list, today, overdue);
149
151
  return {
150
152
  key: 'work:' + it.id, id: it.id, list, title: clip(it.title, 140), sub: sub + (added && (list === 'inbox' || list === 'tray') ? ' · added ' + added : ''), chip, overdue, src: srcLabel(it), sug, cta,
@@ -202,7 +204,7 @@ function build({ v, now, events }) {
202
204
  if (first.length) line1.push(...first);
203
205
  for (const b of bits) { if (line1.length) line1.push({ t: ', ' }); line1.push(...b); }
204
206
  if (line1.length) { line1.push({ t: '.' }); add(line1, [].concat(work.inbox.map((i) => i.id), overdue.map((x) => x.it.id), dueToday.map((i) => i.id))); }
205
- if (tray.length) add([{ t: num(tray.length), s: true }, { t: ' ' + plural(tray.length, 'thing you threw in waits', 'things you threw in wait') + ' in your tray.' }], tray.map((i) => i.id));
207
+ if (tray.length) add([{ t: num(tray.length), s: true }, { t: ' ' + plural(tray.length, 'thing you added waits', 'things you added wait') + ' to be placed.' }], tray.map((i) => i.id));
206
208
  if ((work.waiting || []).length) add([{ t: num(work.waiting.length), s: true }, { t: ' ' + plural(work.waiting.length, 'person owes', 'people owe') + ' you something' + (longest != null ? ', the longest for ' : '.') }].concat(longest != null ? [{ t: longest + ' ' + plural(longest, 'day', 'days'), s: true }, { t: '.' }] : []), work.waiting.map((i) => i.id));
207
209
  if (ready.length) add([{ t: num(ready.length), s: true }, { t: ' agent ' + plural(ready.length, 'draft needs', 'drafts need') + ' your review.' }], ready.map((x) => x.it.id));
208
210
  if ((v.review || []).length) add([{ t: num(v.review.length), s: true }, { t: ' ' + plural(v.review.length, 'item has', 'items have') + ' sat untouched for ' + v.review_days + ' days.' }], v.review.map((i) => i.id));
@@ -219,24 +221,37 @@ function build({ v, now, events }) {
219
221
  const agentBy = {};
220
222
  for (const [k, xs] of [['running', running], ['failed', failed], ['ready', ready]]) agentBy[k] = { more: Math.max(0, xs.length - MAX_PER), rows: xs.slice(0, MAX_PER).map((x) => rowOf(x.it, x.list, v, reviewIds.has(x.it.id), focusIds)) };
221
223
  const trayRows = tray.slice(0, MAX_PER).map((it) => rowOf(it, 'tray', v, reviewIds.has(it.id), focusIds));
222
- const shelf = shelfOf();
223
- const rowsAll = [].concat(...sections.map((s) => s.rows), waitingRows, agentRows, ...Object.values(agentBy).map((g) => g.rows), trayRows, ...shelf.tabs.map((t) => t.rows));
224
- /* The tray as tabs, from the item records alone: To place, Ready (an agent draft is ready), Working (an agent runs), Kept (a Keep press was recorded), Used (done in the last 7 days), Compost (untouched for the review days). */
225
- function shelfOf() {
224
+ for (const r of trayRows) if (reviewIds.has(r.id)) r.stale = true;
225
+ const queue = queueOf();
226
+ const rowsAll = [...new Set([].concat(...sections.map((s) => s.rows), waitingRows, agentRows, ...Object.values(agentBy).map((g) => g.rows), trayRows, ...queue.tabs.map((t) => [].concat(...t.groups.map((g) => g.rows)))))]; // the queue's tabs reuse the section rows
227
+ /* The Work queue: one card, one tab for each place a thing waits, from the item records alone. Today, Inbox (new from Jira and Slack, then what
228
+ * the PM added), Agents (a draft ready, a run working or failed), Upcoming, Someday, Kept (a Keep press was recorded) and Done (done in the last
229
+ * 7 days). Answers and ideas an agent files on its own have no record, so no tab holds them. */
230
+ function queueOf() {
226
231
  const loc = (v.items || all.map((x) => x.it)).filter(isLocal);
227
- const rowFor = (it, cta) => { const r = rowOf(it, 'tray', v, reviewIds.has(it.id), focusIds); r.cta = cta; return r; };
228
232
  const week = daysAgo(today, 7);
229
- const open = loc.filter((it) => !it.done);
233
+ const grp = (key, label, n, rows, more, hint) => ({ key, label, n, rows, more, hint: hint || '' });
234
+ const sec = (k) => sections.find((s) => s.key === k);
235
+ const listTab = (k, label, note) => { const s = sec(k); return { key: k, label, n: s.n, groups: [grp(k, '', s.n, s.rows, s.more)], note }; };
236
+ const kept = loc.filter((it) => !it.done && it.kept_at), done = loc.filter((it) => it.done && String(it.done_at || '').slice(0, 10) >= week);
237
+ const placeOf = (it) => (it.done ? 'done' : (all.find((x) => x.it.id === it.id) || { list: 'tray' }).list);
238
+ const recRows = (items) => items.slice(0, MAX_PER).map((it) => rowOf(it, placeOf(it), v, reviewIds.has(it.id), focusIds));
239
+ const agN = ready.length + running.length + failed.filter((x) => !ready.includes(x)).length;
240
+ const inbox = sec('inbox');
230
241
  const tabs = [
231
- ['place', 'To place', tray.filter((it) => !isReady(it) && !isRunning(it) && !reviewIds.has(it.id)), { label: 'Today', act: 'today' }],
232
- ['ready', 'Ready', tray.filter(isReady), { label: 'Review', act: 'open' }],
233
- ['working', 'Working', tray.filter(isRunning), null],
234
- ['kept', 'Kept', open.filter((it) => it.kept_at), { label: 'Use it', act: 'done' }],
235
- ['used', 'Used', loc.filter((it) => it.done && String(it.done_at || '').slice(0, 10) >= week), null],
236
- ['compost', 'Compost', tray.filter((it) => reviewIds.has(it.id)), { label: 'Let go', act: 'letgo' }],
242
+ listTab('today', 'Today', 'What you placed for today. "Do this first" marks an overdue item only.'),
243
+ { key: 'inbox', label: 'Inbox', n: inbox.n + tray.length, groups: [grp('new', 'New from Jira and Slack', inbox.n, inbox.rows, inbox.more, 'counts to clear'), grp('mine', 'Added by you', tray.length, trayRows, Math.max(0, tray.length - MAX_PER), 'not counted until you place it')],
244
+ note: 'Everything new or not yet placed. Open one to place it: Today, later, waiting on someone, or drop it. What you added counts to clear only once you place it.' },
245
+ { key: 'agents', label: 'Agents', n: agN, groups: [grp('agents', '', agN, agentRows, Math.max(0, agN - MAX_PER))], by: agentBy, counts: { running: running.length, failed: failed.length, ready: ready.length }, note: HOLD.agent },
246
+ listTab('upcoming', 'Upcoming', 'Items with a later date.'),
247
+ listTab('someday', 'Someday', 'Items you parked with no date.'),
248
+ { key: 'kept', label: 'Kept', n: kept.length, groups: [grp('kept', '', kept.length, recRows(kept), Math.max(0, kept.length - MAX_PER))], note: 'Items you pressed Keep on. They stay where they were placed; this tab gathers them.' },
249
+ { key: 'done', label: 'Done', n: done.length, groups: [grp('done', '', done.length, recRows(done), Math.max(0, done.length - MAX_PER))], note: 'What you added and marked done in the last 7 days. Items from Jira or Slack close there, not here.' },
237
250
  ];
238
- return { tabs: tabs.map(([key, label, items, cta]) => ({ key, label, n: items.length, more: Math.max(0, items.length - MAX_PER), rows: items.slice(0, MAX_PER).map((it) => rowFor(it, cta)) })),
239
- note: 'Tabs come from your items: a draft ready, an agent running, a Keep you pressed, an item done this week, or one untouched for ' + (v.review_days || 7) + ' days. Answers and ideas an agent files on its own are not shown: PMOS holds no record of them.' };
251
+ const start = (tabs.find((t) => t.key === 'today' && t.n) || tabs.find((t) => t.n) || tabs[0]).key;
252
+ const bits = [ready.length ? num(ready.length) + ' ' + plural(ready.length, 'draft', 'drafts') + ' to review' : null, tray.length ? tray.length + ' to place' : null].filter(Boolean);
253
+ return { title: 'Work queue', n: clear, cap: bits, tabs, start,
254
+ note: 'Each item comes from your list. A date shows only when one was set, and PMOS does not guess a place. Nothing changes in Jira or Slack from here. Answers and ideas an agent files on its own are not shown: PMOS holds no record of them.' };
240
255
  }
241
256
  const firstToday = sections[1].rows[0];
242
257
  const model = {
@@ -245,12 +260,11 @@ function build({ v, now, events }) {
245
260
  hero, empty,
246
261
  capture: { placeholder: 'Add anything: "Reply to Rina about SSO by Friday"', hint: 'One line. The date and priority are read from it.' },
247
262
  plate: { title: 'On your plate', cap: clear + ' to clear', n: clear, sections, note: 'Each item comes from your list. A suggestion shows only when an agent offered it, a draft is ready, or a date says so; PMOS does not guess a place. A date shows only when one was set. Nothing changes in Jira or Slack from here.' },
248
- tray: { title: 'Your tray', cap: tray.length ? tray.length + ' to place' : 'empty', n: tray.length, more: Math.max(0, tray.length - MAX_PER), rows: trayRows, note: 'Anything you add lands here first. Open one to place it: Today, Later, waiting on someone, or drop it. Nothing here counts as work to clear until you place it.' },
249
263
  agents: { title: 'With agents', cap: ready.length ? num(ready.length) + ' to review' : running.length ? num(running.length) + ' running' : 'nothing running', counts: { running: running.length, ready: ready.length, failed: failed.length }, rows: agentRows, by: agentBy, hold: HOLD.agent },
250
264
  waiting: { title: 'Waiting on others', cap: longest != null ? 'longest ' + longest + ' ' + plural(longest, 'day', 'days') : (work.waiting || []).length ? num(work.waiting.length) + ' waiting' : '', n: (work.waiting || []).length, more: Math.max(0, (work.waiting || []).length - MAX_PER), rows: waitingRows },
251
265
  review: { n: (v.review || []).length, days: v.review_days, ids: (v.review || []).map((i) => i.id) },
252
266
  dock: { needs: clear, label: 'to clear', next: firstToday ? firstToday.title : (sections[0].rows[0] ? sections[0].rows[0].title : null) },
253
- shelf,
267
+ queue,
254
268
  friday: fridayOf({ today, work, tray, ready, review: v.review || [] }),
255
269
  week: weekOf({ today, items: v.items || all.map((x) => x.it), events }),
256
270
  focus, jobs,
@@ -84,6 +84,7 @@ const MODULES = Object.freeze([
84
84
  'routes-core-docs', // core-documents: the core documents of each level, Draft it (a core-doc run), Issue it and Drop (core-docs.jsonl)
85
85
  'routes-custom-docs', // briefing-premium-adddoc: the documents the PM adds beyond the core set, Add a document (custom-docs.jsonl)
86
86
  'routes-premium-dashboards', // briefing-premium-reports: the dashboards the PM makes on premium Insights (premium-dashboards.jsonl; page-press POST save)
87
+ 'routes-board-metric-targets', // briefing-premium-metrics option C: the targets of the Board's four measures, set on premium Insights (board-metric-targets.jsonl; page-press POST save)
87
88
  'routes-premium-charts', // premium-studio-chart: the charts the PM makes in the Insight Studio (premium-charts.jsonl; page-press POST save)
88
89
  'routes-report-design', // report-design-studio: the design studio (describe, samples, turns, versions, This is it), cycle renders and decisions, speaker notes and pins
89
90
  'routes-report-structure', // report-structure: the structure step (turns, versions, Use this structure, sources and their checks, dry run) and the chart store (GET /api/charts)
@@ -0,0 +1,33 @@
1
+ 'use strict';
2
+ /* routes-board-metric-targets.js — the targets the PM sets for the Board's four measures on the premium Insights page (initiative briefing-premium-metrics, option C).
3
+ *
4
+ * POST /api/board-metric-targets/save { ws, key, target } → { ok, targets }
5
+ * one `set` line (or a `clear` line when target is null or empty) in <state>/board-metric-targets.jsonl (lib/board-metric-records.js, the one writer)
6
+ *
7
+ * The Board and Insights read the targets through GET /api/board-metrics-premium, so this module has no GET.
8
+ * WHO WRITES. As routes-premium-dashboards.js: an agent session header is refused (403), and pm-guard requirePagePress checks the launch nonce and the page's
9
+ * origin. The route stores the number the PM typed and nothing else. */
10
+ const guard = require('./pm-guard.js');
11
+ const Rec = require('./board-metric-records.js');
12
+
13
+ const bad = (status, error) => ({ status, body: { ok: false, error } });
14
+
15
+ async function handle(req, res, url, ctx) {
16
+ const send = (r) => { ctx.json(res, r.body, r.status); return true; };
17
+ if (url.pathname !== '/api/board-metric-targets/save') return send(bad(404, 'no such board-metric-targets route'));
18
+ if (req.method !== 'POST') return send(bad(405, 'POST only'));
19
+ const read = await ctx.readJson(req);
20
+ if (!read.ok) return send(bad(400, 'the body is not JSON'));
21
+ const body = read.body || {};
22
+ if (req.headers && req.headers['x-pmos-session']) return send(bad(403, 'an agent session cannot set a target. Only a press on the page does'));
23
+ const g = guard.requirePagePress(req, body);
24
+ if (!g.ok) return send(bad(g.status, g.error));
25
+ const id = typeof body.ws === 'string' ? body.ws : '';
26
+ const w = ctx.getWs(id || null);
27
+ if (!w || !w.root || (id && w.id !== id)) return send(bad(404, 'no such workspace'));
28
+ const r = Rec.saveTarget(w.root, body, g.actor, { now: Date.now() });
29
+ if (!r.ok) return send(bad(r.status, r.error));
30
+ return send({ status: 200, body: { ok: true, targets: r.targets } });
31
+ }
32
+
33
+ module.exports = { prefixes: ['/api/board-metric-targets'], handle };
@@ -28,15 +28,16 @@ async function via(mod, pathAndQuery, req, ctx) {
28
28
  }
29
29
  const qs = (o) => '?' + Object.entries(o).filter(([, v]) => v != null && v !== '').map(([k, v]) => k + '=' + encodeURIComponent(v)).join('&');
30
30
 
31
- /** GET /api/board-metrics-premium?ws=<id> — the Metrics card of a tenant's Board (initiative briefing-premium-metrics). Read-only, and apart from the Board's own
32
- * route so the Board never waits for it. Every board has the card, the PMOS board's counted from the PMOS repository. */
31
+ /** GET /api/board-metrics-premium?ws=<id>[&weeks=8|26|52] — the Metrics card of a tenant's Board (initiative briefing-premium-metrics), and the same measures
32
+ * on Insights over a longer range. Apart from the Board's own route so the Board never waits for it. Its one write is the once-a-day Blocked/Idle history line
33
+ * (lib/board-metric-records.js record). Every board has the card, the PMOS board's counted from the PMOS repository. */
33
34
  async function metrics(req, res, url, ctx) {
34
35
  if (req.method !== 'GET') { ctx.json(res, { ok: false, error: 'GET only' }, 405); return true; }
35
36
  try {
36
37
  const w = ctx.getWs && ctx.getWs(url.searchParams.get('ws') || null);
37
38
  if (!w || !w.root) { ctx.json(res, { ok: false, state: 'error', error: 'that workspace is not registered' }, 404); return true; }
38
39
  const engine = ENGINE_PATHS.find((p) => fs.existsSync(p)) || null;
39
- const model = await Metrics.read({ root: w.root, engine, now: Date.now() });
40
+ const model = await Metrics.read({ root: w.root, engine, now: Date.now(), weeks: Number(url.searchParams.get('weeks')) || undefined });
40
41
  // the read-only agent finds a tile's row in the Board's model
41
42
  const bm = BoardP.peekModel(); if (bm && Array.isArray(bm.rows)) bm.rows = bm.rows.filter((r) => !/^board:metric-/.test(r.key)).concat(model.rows);
42
43
  ctx.json(res, { ok: true, state: 'ready', model, as_of: Date.now() });
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.313.0",
3
+ "version": "0.315.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.313.0",
9
+ "version": "0.315.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.313.0",
3
+ "version": "0.315.0",
4
4
  "private": true,
5
5
  "description": "PMOS Terminal Workspace — local companion hosting real PTYs beside the library and gates (D62)",
6
6
  "license": "MIT",