create-pmos 0.313.0 → 0.314.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-pmos",
3
- "version": "0.313.0",
3
+ "version": "0.314.0",
4
4
  "description": "Scaffold the PMOS portable kit — run the PMOS product-management workflow (initiative → lane-fit spec → contract → build → three gates, with work-type lanes for features, research, maintenance, incidents, and content) entirely inside your own repo, with all state as git-versioned files. Includes `workflow-sweep`, which audits the state every board derives from and separates real defects from work you simply have not done. `create-pmos workspace` also installs + launches the local Terminal Workspace GUI. No database, no network, no telemetry.",
5
5
  "license": "MIT",
6
6
  "bin": {
@@ -1,3 +1,3 @@
1
- kernel-source: pmos@36b0e23
1
+ kernel-source: pmos@9637351
2
2
  assembled: 2026-10-19
3
3
  mode: vendor
@@ -2,7 +2,7 @@
2
2
  type: Reference
3
3
  title: "Eval calibration log"
4
4
  description: "Append-only record of every PM override of an evaluator verdict."
5
- generated: {by: process:create-pmos, at: "2026-10-19T13:24:33Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-19T13:37:58Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -2,7 +2,7 @@
2
2
  type: Reference
3
3
  title: "Health budgets"
4
4
  description: "Closed registry of health-budget anchors (D59), edited only by the PM."
5
- generated: {by: process:create-pmos, at: "2026-10-19T13:24:33Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-19T13:37:58Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -2,7 +2,7 @@
2
2
  type: Reference
3
3
  title: "Discoveries and friction log"
4
4
  description: "Append-only record of what runs discovered and where the process rubbed."
5
- generated: {by: process:create-pmos, at: "2026-10-19T13:24:33Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-19T13:37:58Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -129,7 +129,7 @@ const MOCKUP = path.join(__dirname, '..', 'prototype', 'premium-ux-concept', 'br
129
129
  { const R = await open(); await R.page.locator('#repDocs .dmo').first().click(); ok('I8 a report opens in the page\'s reader, not the console (premium-report-read R1)', await until(() => R.page.evaluate(() => document.querySelector('#dlg').classList.contains('rdrd') && document.querySelector('#dlg').classList.contains('on')), 5000) && /premium-insights\.html/.test(R.page.url()), R.page.url());
130
130
  await R.page.click('#dClose'); await R.page.click('#repOpen'); ok('I8 the Reports tab link still opens the console to edit or issue', await until(() => /\/console\.html\?tab=rep/.test(R.page.url()), 5000), R.page.url()); await R.ctx.close(); }
131
131
  /* I9 labels */
132
- ok('I9 no demo label, and the foot says what is left out', !(await p.evaluate(() => /demo/i.test(document.querySelector('main.stage').textContent))) && /Left out: run-based charts/.test(await txt('#foot')) && /Real data/.test(await txt('#snap')));
132
+ ok('I9 no demo label, and the foot says what is left out', !(await p.evaluate(() => /demo/i.test(document.querySelector('main.stage').textContent))) && /Left out: any measure no record holds/.test(await txt('#foot')) && /Board measures card/.test(await txt('#foot')) && /Real data/.test(await txt('#snap')));
133
133
  ok('I9 the page makes no write request on its own', A.posts.length === 0, A.posts.join());
134
134
  /* I10 empty */
135
135
  {
@@ -3,7 +3,7 @@
3
3
  /* briefing-premium-metrics-test.js — the Metrics card of the premium Board (initiative briefing-premium-metrics; planning/prd/briefing-premium-metrics-prd.md M1 to M10).
4
4
  * Serves the real page from the real server. The Board's answer and the card's answer are served from fixtures (the card's model is built by
5
5
  * lib/board-metrics-premium.js from made-up runs, commits and initiatives); the last blocks ask the real route and compare the card with the mockup.
6
- * C1 place and absence · C2 tiles · C3 reading a week · C4 dialog and agent · C5 pending and failure · C6 floors · C7 the real route · C8 fidelity */
6
+ * C1 place and absence · C2 tiles · C3 reading a week · C4 dialog and agent · C5 pending and failure · C6 floors · C7 the real route · C8 fidelity · C9 targets on the Board · C10 the Insights twin */
7
7
  const fs = require('fs');
8
8
  const path = require('path');
9
9
  const { spawn } = require('child_process');
@@ -71,7 +71,7 @@ const ready = (model) => ({ status: 200, body: { ok: true, state: 'ready', model
71
71
  /* C2 */
72
72
  const tiles = await p.evaluate(() => [...document.querySelectorAll('#metBody .mt1')].map((t) => ({ l: t.querySelector('span').textContent, v: t.querySelector('.mval').textContent, c: t.querySelector('.mwk').textContent, chart: !!t.querySelector('svg'), cls: t.className, chg: (t.querySelector('.mchg') || {}).textContent || '' })));
73
73
  ok('C2 the first tile is the latest week with its run count, and how it changed', tiles[0].l === 'Corrections per 100 runs' && tiles[0].v === '10.0' && /^week to .+, 10 runs$/.test(tiles[0].c) && tiles[0].chg === '▼ Down 15.0 vs last week' && tiles[0].chart && /\bok\b/.test(tiles[0].cls), JSON.stringify(tiles[0]));
74
- ok('C2 merges, blocked and idle are counted; blocked and idle have no chart and say no history is kept', tiles[1].v === '3' && tiles[1].chart && tiles[2].v === '1' && tiles[2].c === 'of 3 open. No history is kept' && !tiles[2].chart && tiles[3].v === '1' && !tiles[3].chart && /\bbad\b/.test(tiles[2].cls) && /\bwarn\b/.test(tiles[3].cls), JSON.stringify(tiles));
74
+ ok('C2 merges, blocked and idle are counted; blocked and idle chart from today and say plainly that their history starts today', tiles[1].v === '3' && tiles[1].chart && tiles[2].v === '1' && tiles[2].c === 'of 3 open · history starts today' && tiles[2].chart && tiles[3].v === '1' && tiles[3].c === 'of 3 open · history starts today' && tiles[3].chart && /\bbad\b/.test(tiles[2].cls) && /\bwarn\b/.test(tiles[3].cls), JSON.stringify(tiles));
75
75
  const per = await p.evaluate(() => [...document.querySelectorAll('#perTabs button')].map((b) => b.textContent + ':' + b.getAttribute('aria-pressed') + ':' + (b.getAttribute('aria-disabled') || '')).join('|'));
76
76
  ok('C2 only Week is available; Day and Month are disabled', per === 'Day:false:true|Week:true:|Month:false:true', per);
77
77
  ok('C2 no target, on-target chip, dashed line or demo label is drawn; the lead line says no measure has a target', await p.evaluate(() => !document.querySelector('#cMet .mchip.ok, #cMet .tg, #cMet .tgl') && !/on target|demo|dashed/i.test(document.querySelector('#metBody').textContent) && /No measure here has a target/.test(document.querySelector('#metHint').textContent)));
@@ -108,7 +108,7 @@ const ready = (model) => ({ status: 200, body: { ok: true, state: 'ready', model
108
108
  ok('C4 a question posts the metric\'s key and the text', await until(() => A.posts.length > n0 && A.posts[A.posts.length - 1].path === '/api/briefing-premium/ask' && A.posts[A.posts.length - 1].body.key === 'board:metric-corrections' && A.posts[A.posts.length - 1].body.text === 'Why did it fall?'), JSON.stringify(A.posts.slice(-1)));
109
109
  await p.keyboard.press('Escape'); await until(() => p.evaluate(() => !document.querySelector('#dlg').classList.contains('on')));
110
110
  await p.locator('#metBody .mt1').nth(2).click(); await until(() => p.evaluate(() => document.querySelector('#dlg').classList.contains('on'))); await sleep(400);
111
- ok('C4 a tile without a chart opens its definition too', await p.evaluate(() => document.querySelector('#dTitle').textContent === 'Blocked' && /blocked step/.test(document.querySelector('#oMain .lede').textContent) && document.querySelectorAll('#oMain .vtb div').length === 0));
111
+ ok('C4 Blocked opens its definition, and the weeks before its history started read Not kept yet', await p.evaluate(() => { const v = [...document.querySelectorAll('#oMain .vtb div b')].map((b) => b.textContent); return document.querySelector('#dTitle').textContent === 'Blocked' && /blocked step/.test(document.querySelector('#oMain .lede').textContent) && v.length === 8 && v.slice(0, 7).every((x) => x === 'Not kept yet') && v[7] === '1'; }));
112
112
  await p.keyboard.press('Escape'); await until(() => p.evaluate(() => !document.querySelector('#dlg').classList.contains('on')));
113
113
  await p.click('#perTabs [data-per="day"]', { force: true }); ok('C4 a disabled period says why and changes nothing', await until(() => p.evaluate(() => /by week only/.test(document.querySelector('#toast').textContent))) && await p.evaluate(() => document.querySelector('#perTabs [data-per="week"]').getAttribute('aria-pressed') === 'true'));
114
114
  ok('0 no page error', A.errors.length === 0, A.errors.join(' | '));
@@ -148,6 +148,44 @@ const ready = (model) => ({ status: 200, body: { ok: true, state: 'ready', model
148
148
  await ctx.close();
149
149
  }
150
150
 
151
+ /* C9 a target set on Insights draws on the Board */
152
+ {
153
+ const R = await open({ answers: () => ready(metrics({ targets: { corrections: { target: 12 }, merges: { target: 5 } } })) }), q = R.page;
154
+ await until(() => q.evaluate(() => document.querySelectorAll('#metBody .mt1').length === 4));
155
+ const t = await q.evaluate(() => [...document.querySelectorAll('#metBody .mt1')].map((x) => ({ chip: (x.querySelector('.mchip') || {}).textContent || '', cls: (x.querySelector('.mchip') || {}).className || '', tg: !!x.querySelector('svg .tg'), tgl: !!x.querySelector('.tgl'), tgt: (x.querySelector('.mtg') || {}).textContent || '', off: x.classList.contains('off') })));
156
+ ok('C9 a measure on target carries the On target chip, its target and the dashed line, with no outline', t[0].chip === 'On target' && /\bok\b/.test(t[0].cls) && t[0].tg && t[0].tgl && t[0].tgt === 'target 12.0' && !t[0].off, JSON.stringify(t[0]));
157
+ ok('C9 a measure off target carries its gap, the dashed line and the orange outline', t[1].chip === '2 short' && /\bwarn\b/.test(t[1].cls) && t[1].tg && t[1].tgt === 'target 5' && t[1].off, JSON.stringify(t[1]));
158
+ ok('C9 a measure with no target draws no dashed line, and the lead line says the line is the target set on Insights', !t[2].tg && !t[3].tg && await q.evaluate(() => /The dashed line is the target set on Insights/.test(document.querySelector('#metHint').textContent)), JSON.stringify(t.slice(2)));
159
+ await q.locator('#metBody .mt1').first().click(); await until(() => q.evaluate(() => document.querySelector('#dlg').classList.contains('on'))); await sleep(300);
160
+ ok('C9 the dialog names the target and the gap', await q.evaluate(() => { const g = [...document.querySelectorAll('#oMain .kv2 span')].map((s) => s.textContent).join('|'); return /Target\|12\.0/.test(g) && /Gap\|On target/.test(g); }));
161
+ ok('C9 no page error', R.errors.length === 0, R.errors.join(' | '));
162
+ await R.ctx.close();
163
+ }
164
+
165
+ /* C10 the Insights page shows the same measures, and a target saved there is sent for the Board */
166
+ {
167
+ const IP = require('./lib/insights-premium.js'), IF = require('./fixtures/insights-premium-facts.js');
168
+ const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } }), q = await ctx.newPage(), errs = [], saves = [], asked = [];
169
+ let tg = {};
170
+ q.on('pageerror', (e) => errs.push(String((e && e.message) || e)));
171
+ await q.route('**/api/insights-premium*', (r) => r.fulfill({ contentType: 'application/json', body: JSON.stringify({ ok: true, state: 'ready', model: IP.build(IF.facts()), as_of: 1 }) }));
172
+ await q.route('**/api/board-metrics-premium*', (r) => { asked.push(new URL(r.request().url()).searchParams.get('weeks')); return r.fulfill({ contentType: 'application/json', body: JSON.stringify(ready(metrics({ targets: tg })).body) }); });
173
+ await q.route('**/api/board-metric-targets/save', (r) => { const b = JSON.parse(r.request().postData() || '{}'); saves.push(b); tg = b.target == null ? {} : { [b.key]: { target: Number(b.target) } }; return r.fulfill({ contentType: 'application/json', body: JSON.stringify({ ok: true, targets: tg }) }); });
174
+ await q.route('**/api/briefing-premium/**', (r) => r.fulfill({ contentType: 'application/json', body: '{"ok":true,"turns":[],"working":false}' }));
175
+ await q.goto(BASE + '/premium-insights.html');
176
+ const up = await until(() => q.evaluate(() => !document.querySelector('#cBm').hidden && document.querySelectorAll('#bmBody .mt1').length === 4), 20000);
177
+ ok('C10 Insights draws the Board measures card with the same four tiles as the Board', up && await q.evaluate(() => [...document.querySelectorAll('#bmBody .mt1 .mval')].map((v) => v.textContent).join('|') === '10.0|3|1|1' && /counted from idpf/.test(document.querySelector('#bmCap').textContent)));
178
+ ok('C10 Blocked and Idle say plainly on their charts that history starts today', await q.evaluate(() => [...document.querySelectorAll('#bmBody .mt1')].slice(2).every((t) => !!t.querySelector('svg') && t.querySelector('.mwk').textContent === 'of 3 open · history starts today')));
179
+ await q.locator('#bmRange [data-w="26"]').click();
180
+ ok('C10 a longer range asks for 26 weeks', await until(() => asked.includes('26')) && await until(() => q.evaluate(() => document.querySelector('#bmRange [data-w="26"]').getAttribute('aria-pressed') === 'true')), JSON.stringify(asked));
181
+ await q.locator('#bmBody .mt1').nth(1).click(); await until(() => q.evaluate(() => document.querySelector('#dlg').classList.contains('on'))); await sleep(300);
182
+ await q.fill('#bmT', '5'); await q.click('#bmGo');
183
+ ok('C10 Save target sends the measure and the number for this board', await until(() => saves.length === 1) && saves[0].ws === 'w1' && saves[0].key === 'merges' && saves[0].target === '5', JSON.stringify(saves));
184
+ ok('C10 the card redraws with the target: its gap chip, dashed line and outline', await until(() => q.evaluate(() => { const t = document.querySelectorAll('#bmBody .mt1')[1]; return t && (t.querySelector('.mchip') || {}).textContent === '2 short' && !!t.querySelector('svg .tg') && t.classList.contains('off'); })));
185
+ ok('C10 no page error', errs.length === 0, errs.join(' | '));
186
+ await ctx.close();
187
+ }
188
+
151
189
  /* C8 fidelity against the mockup */
152
190
  if (!fs.existsSync(MOCKUP)) ok('C8 the mockup is in the repository', false, MOCKUP);
153
191
  else {
@@ -243,7 +243,7 @@ Board is the third place on the rail, at `/premium-board.html`. It reads what th
243
243
  - **By stage** has one column for each stage of the board's workflow with the board's own count and its first five initiatives.
244
244
  - **List** and **Timeline** show ten tasks a page with Previous and Next; **By stage** shows six cards a column with Show more. **Timeline** draws a bar for each initiative that has both a start and an end date, with the days left or over, and counts the rest. With no dates on record it says so and draws nothing.
245
245
  - **Sprint** appears when an agent session has read Jira for the board. Otherwise it says there is none. **Coming up** shows the next release, from the releases ledger.
246
- - **Metrics** appears above the Initiatives card on the board of any workspace except the home one (PMOS itself), and counts from that workspace's own repository. It has four tiles. **Corrections per 100 runs** is the corrections logged on the week's runs in `planning/runs/agent-runs.jsonl`; a week with fewer than 10 runs is left blank. **Merged a week** counts the commits on the first-parent line of the trunk. **Blocked** and **Idle for a month** come from the workflow engine and keep no history, so they have no chart. Move over a chart, or use the arrow keys, to read a week. A tile that cannot be counted says **Not read** and why; a repository with no run log says **No runs yet**. The line above the tiles starts with how many tiles need a look, and those tiles have a **Needs a look** chip and an orange outline. The line ends with **open Insights**, which opens the same board's Insights page. Press a tile for its definition and values, with the read-only agent beside it. There are no targets, and Day and Month are off. It was tested only on made-up repositories, not on a real IDPF or microsite repository.
246
+ - **Metrics** appears above the Initiatives card on the board of any workspace except the home one (PMOS itself), and counts from that workspace's own repository. It has four tiles. **Corrections per 100 runs** is the corrections logged on the week's runs in `planning/runs/agent-runs.jsonl`; a week with fewer than 10 runs is left blank. **Merged a week** counts the commits on the first-parent line of the trunk. **Blocked** and **Idle for a month** come from the workflow engine, which keeps no history. From the first day the card is read, PMOS keeps their counts once a day in the workspace's state folder (`board-metric-history.jsonl`), so their charts start on that day and their caption says **history starts today** (later, the date). Earlier weeks read **Not kept yet**. Move over a chart, or use the arrow keys, to read a week. A tile that cannot be counted says **Not read** and why; a repository with no run log says **No runs yet**. The line above the tiles starts with how many tiles need a look, and those tiles have a **Needs a look** chip and an orange outline. The line ends with **open Insights**, which opens the same board's Insights page. Press a tile for its definition and values, with the read-only agent beside it. A target is set on Insights, not here. A measure with a target shows it under the value, draws it as a dashed line, and carries **On target** or its gap (for example **2 short**); off target, it also has the orange outline. A measure without a target draws no line. Day and Month are off. It was tested only on made-up repositories, not on a real IDPF or microsite repository.
247
247
  - **The crumb** at the top names the board. With more than one board a menu switches between them, and the sparkle opens the board in the dialog with the read-only agent.
248
248
  - **Core documents** lists the board's documents with their state, cadence and writer, a summary (drafts to review, not started, up to date), a progress bar, a filter and a search. A document with a file opens in the dialog, read only, with its path and state; a draft there has **Issue it**, which marks it issued through the console's own route and sends nothing, and **Draft it again**, which starts a new draft that replaces this one (a board draft has no Edit tab). **Draft it** starts the existing read-only run that writes a draft and sends nothing; **Draft the N not started** does that for each document that can be drafted. **Set it up** and **Open** go to the console. **Add a document** opens a form (title, who writes it, where it lives) and saves a document the core set does not cover on the board's record, in `custom-docs.jsonl`. A document with no link reads "Not started". A document with a link to Confluence or Google Docs reads "Linked" and shows its address. PMOS does not read or sync the linked page, so a linked document is never counted as up to date. Issue and Drop are not on this page.
249
249
  - **Opening an initiative.** A click on an initiative opens its page (see "Initiative page"). The **Page / Popup** switch in the header changes that: Popup opens the initiative's dialog instead, which shows its record as a grid and the path of its file, with the read-only agent beside it. The choice is kept in this browser. The dialog holds no press.
@@ -285,6 +285,7 @@ Insights is the fourth place on the rail, at `/premium-insights.html`. It reads
285
285
  - **Choose a deck or a document, and read the design brief.** On the Design tab, the **Format** chip offers **Deck** and **Document** for the next version. Versions you already made keep their form. Once a design is saved, a **Design brief** chip shows what PMOS reads each cycle: your description, your samples, the reference version, and what stays the same, what changes and what PMOS learned. The cycles drafted to match it are checked on the report itself.
286
286
  - **Point, make the next version, compare.** On the Design tab, click any part of a slide to attach a request to that spot: a numbered pin appears, and you type the request under the preview (**Point and say**; the switch turns pointing off). **Make the next version** sends the typed line and every pinned request to PMOS, which makes the next version; the pins are cleared once it starts. **Compare two** shows the same slide of two versions side by side; pick the version on each side.
287
287
  - **What stands out.** Up to three plain sentences taken from the series: behind its line for three readings in a row, behind and still moving away from the target, closing in, slipped, reached its target, or a large one-step move. There is no forecast and no cause.
288
+ - **Board measures.** The same four tiles as the Board's Metrics card, counted from the board's repository and drawn the same way. Choose **8 weeks**, **26 weeks** or **52 weeks**; the page keeps your choice. Press a measure to read its definition and values and to set its target: type a number and press **Save target**, or press **Clear target**. For Corrections, Blocked and Idle, lower is better, so the target is the most you accept; for Merged a week it is the least. The target goes to the workspace's state folder (`board-metric-targets.jsonl`) and the Board draws it too. An agent session cannot set one.
288
289
  - **No series recorded.** A KR metric with one reading or none is listed with the reason and is not drawn.
289
290
  - **Ask PMOS to set up a report.** Type what the report is for and press **Ask**. A background run proposes a report and does nothing else. The request is listed as Working, then Ready to review. A ready request opens with its proposal: **Set it up**, **Change it** (say what to change; the run revises it), or **Cancel**.
290
291
  - **Found in your work.** Up to three reports PMOS found in your calendar, mail or documents, each with why and what it saw. **Set it up** records the report and drafts its first cycle as a file. **Not a report** hides it and records it after 5 seconds, unless you press **Undo**. If the finding changed while the window was open, the window says what happened. It was already set up, it was marked not a report, or a new scan replaced it. The list is read again. Close the window and open the report from the list. If PMOS does not hear back, the window says nothing was recorded. Press the button to try again.
@@ -292,7 +293,7 @@ Insights is the fourth place on the rail, at `/premium-insights.html`. It reads
292
293
  - **Documents.** The report files of the workspace, with cadence, slot and whether each is a draft or issued. Pressing one opens it on the page at the normal dialog size, with a status line (Draft or Issued, the saved design version, the file). The **slide deck / Document** menu picks the view: a deck is a title slide, then one slide for each section, with the arrow keys and a strip of slides; a document is a page. The **Read** menu holds **Present**, which shows the slide on the whole screen (the arrow keys move and Escape stops), and **Print or save as PDF**, which prints one slide to a page. **Download** gives PowerPoint, Word, Excel, CSV or the Markdown file; the files carry the words, not the look. **Open in the console** is where a document is edited or issued. Nothing is sent from this page.
293
294
  - **Shape a report's look.** On a draft, **Add a sample** takes a PDF, PowerPoint, Word, PNG or JPG file to follow. Say how it should look in the conversation; PMOS draws the next design version (D1, D2, …) and says what it changed. Press a version to go back to it. **This is it** saves the version shown as the report's design, and PMOS draws the cycle to match. An issued cycle is frozen with its look.
294
295
 
295
- Not built: a second measure next to a chart, bar highlights, speaker notes and notes on a slide, changing a set-up report's audience, format or schedule, tile sizes and free layout, the finder's settings, run-based charts such as corrections per 100 runs (they belong to the Board's Metrics card), and any measure no record holds. The console's own dashboards are separate and unchanged. KR metric records belong to a workspace, so every board of a workspace shows the same charts.
296
+ Not built: a second measure next to a chart, bar highlights, speaker notes and notes on a slide, changing a set-up report's audience, format or schedule, tile sizes and free layout, the finder's settings, and any measure no record holds. The console's own dashboards are separate and unchanged. KR metric records belong to a workspace, so every board of a workspace shows the same charts.
296
297
 
297
298
  ## Welcome
298
299
 
@@ -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 };
@@ -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.314.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.314.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.314.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",
@@ -7,6 +7,7 @@ import { pmPost } from './http.js';
7
7
  import { $, $$, esc, openDlg, closeDlg, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, CHECK, AI, store, crumbHtml, wireCrumb, kv, H, openAddDoc } from './premium-shell.js';
8
8
  import { issueBody } from './premium-doc-edit.js';
9
9
  import { mountDocSheet } from './premium-doc-sheet.js';
10
+ import * as MT from './premium-metric-tiles.js';
10
11
  import { dotsBtn, openMenu, closeMenu, menuKey, asksHtml, onAsks, openIniForm } from './premium-acts.js';
11
12
 
12
13
  const MODE_KEY = 'pmos.premium.openAs';
@@ -227,44 +228,15 @@ load();
227
228
  * Reads GET /api/board-metrics-premium?ws= apart from the board's own answer and draws lib/board-metrics-premium.js's tiles: a number and a chart only
228
229
  * where a record counted one, "Not read" where it could not be. A tile opens the standard dialog. Nothing here writes. */
229
230
  let MM = null, metTimer = null; // the Metrics card's model and its re-read timer
230
- const MET_GEO = { W: 220, H: 60, P: 5 };
231
- const metGeo = (m) => { const n = m.ser.length, { W, H: Ht, P } = MET_GEO, vs = m.ser.filter((v) => v != null), lo = Math.min(...vs), hi = Math.max(...vs), sp = hi - lo || 1; return { n, W, H: Ht, P, X: (j) => P + j * (W - 2 * P) / (n - 1), Y: (v) => P + (1 - (v - lo) / sp) * (Ht - 2 * P) }; };
232
- const metFmt = (m, v) => (+v).toFixed(m.dec) + (m.suf || '');
233
-
234
- function metTileHtml(t, i) {
235
- if (t.absent) return `<div class="mt1" data-m="${i}" data-op="m:${i}" tabindex="0" role="button" aria-label="${esc(t.label)}: ${esc(t.absent)}. ${esc(t.why)}"><span>${esc(t.label)}</span><b class="mval">${esc(t.absent)}</b><em class="mwk">${esc(t.why)}</em></div>`;
236
- const lab = t.look ? `<span class="mlab">${esc(t.label)}<i class="mchip warn">Needs a look</i></span>` : `<span>${esc(t.label)}</span>`, off = t.look ? ' off' : '';
237
- const chg = t.change ? `<span class="mchg ${t.change.d === 0 ? '' : t.change.good ? 'good' : 'bad'}">${t.change.d === 0 ? '' : t.change.d > 0 ? '▲ ' : '▼ '}${esc(t.change.txt)}</span>` : '';
238
- if (!t.ser) return `<div class="mt1 ${t.kind}${off}" data-m="${i}" data-op="m:${i}" tabindex="0" role="button" aria-label="${esc(t.label)}, ${esc(t.value)}, ${esc(t.text)}${t.look ? ', needs a look' : ''}">${lab}<b class="mval">${esc(t.value)}</b><em class="mwk">${esc(t.text)}</em></div>`;
239
- const g = metGeo(t); let ln = '', op = false;
240
- t.ser.forEach((v, j) => { if (v == null) { op = false; return; } ln += (op ? 'L' : 'M') + g.X(j).toFixed(1) + ',' + g.Y(v).toFixed(1); op = true; });
241
- const f = Math.max(0, t.ser.findIndex((v) => v != null)), gap = t.ser.slice(f).some((v) => v == null), n1 = g.n - 1, lastJ = t.ser.reduce((a, v, j) => (v != null ? j : a), f);
242
- return `<div class="mt1 mch ${t.kind}${off}" data-m="${i}" data-op="m:${i}" tabindex="0" role="button" aria-label="${esc(t.label)} over eight weeks, now ${esc(t.value)}${t.look ? ', needs a look' : ''}. Use the arrow keys to read each week.">${lab}<b class="mval">${esc(t.value)}</b><em class="mwk">${esc(t.text)}</em>${chg}`
243
- + `<svg viewBox="0 0 ${g.W} ${g.H}">${f > 0 ? `<line class="gp" x1="${g.X(0)}" x2="${g.X(f)}" y1="${g.H - g.P}" y2="${g.H - g.P}"/>` : ''}${gap ? '' : `<path class="ar" d="${ln}L${g.X(n1)},${g.H}L${g.X(f)},${g.H}Z"/>`}<path class="ln2" d="${ln}"/><line class="cx" x1="0" x2="0" y1="0" y2="${g.H}"/><circle class="dt" cx="${g.X(lastJ)}" cy="${g.Y(t.ser[lastJ])}" r="3.5"/></svg>`
244
- + `<span class="mfoot"><i>${esc(t.wk[0])}</i><i>${esc(t.wk[t.wk.length - 1])}</i></span></div>`;
245
- }
246
-
247
- /** Read one week of a chart tile: the guide line and dot move, the value and caption change. */
248
- function metChartAt(el, j) {
249
- const t = MM.tiles[+el.dataset.m]; if (!t || !t.ser) return;
250
- const g = metGeo(t); j = j == null ? t.ser.reduce((a, v, k) => (v != null ? k : a), 0) : Math.max(0, Math.min(g.n - 1, j));
251
- const v = t.ser[j], has = v != null, x = g.X(j), y = has ? g.Y(v) : 0, now = j === t.ser.reduce((a, w, k) => (w != null ? k : a), 0);
252
- const cx = $('.cx', el), dt = $('.dt', el);
253
- cx.setAttribute('x1', x); cx.setAttribute('x2', x); dt.setAttribute('cx', x); dt.setAttribute('cy', y); dt.style.opacity = has ? '' : '0';
254
- el.classList.toggle('hv', !now); el.dataset.j = j;
255
- const val = now ? t.value : has ? metFmt(t, v) : 'No runs', cap = now ? t.text : 'Week to ' + t.wk[j] + (t.nt[j] ? ' · ' + t.nt[j] : '');
256
- $('.mval', el).textContent = val; $('.mwk', el).textContent = cap;
257
- el.setAttribute('aria-label', t.label + ', ' + (now ? 'now ' : '') + val + ', ' + cap + '. Use the arrow keys to read each week.');
258
- }
259
231
 
260
232
  function metDraw() {
261
233
  const card = $('#cMet'); if (!MM) { card.hidden = true; return; }
262
234
  card.hidden = false;
263
235
  $('#metCap').textContent = MM.header;
264
236
  const ins = '/premium-insights.html' + (M.board.ws ? '?ws=' + encodeURIComponent(M.board.ws) + (M.board.id ? '&board=' + encodeURIComponent(M.board.id) : '') : '');
265
- $('#metHint').innerHTML = (MM.lead ? `<b class="mflag">${esc(MM.lead)}</b> ` : '') + esc(MM.body || MM.hint) + ` For the KR measures and your own set of charts, <a class="lk" id="metIns" href="${esc(ins)}">open Insights</a>.`;
237
+ $('#metHint').innerHTML = (MM.lead ? `<b class="mflag">${esc(MM.lead)}</b> ` : '') + esc(MM.body || MM.hint) + ` To set a target, or for longer ranges, <a class="lk" id="metIns" href="${esc(ins)}">open Insights</a>.`;
266
238
  $('#metBody').style.gridTemplateColumns = 'repeat(' + Math.min(4, MM.tiles.length) + ',minmax(0,1fr))';
267
- $('#metBody').innerHTML = MM.tiles.map(metTileHtml).join('');
239
+ $('#metBody').innerHTML = MM.tiles.map(MT.tileHtml).join('');
268
240
  $('#metNote').textContent = MM.note;
269
241
  pillOf($('#perTabs'));
270
242
  }
@@ -272,26 +244,15 @@ function metDraw() {
272
244
  function metOpenTile(i) {
273
245
  const t = MM.tiles[i], r = MM.rows[i]; if (!t || !r) return;
274
246
  const d = r.dialog;
275
- const rows = t.absent ? [['Now', t.absent], ['Why', t.why], ['Counted from', MM.repo]]
276
- : [['Now', t.value], ['Counted', t.text], ['Change', t.change ? t.change.txt : ''], ['Better when', t.lowBetter ? 'Lower' : t.lowBetter === false ? 'Higher' : ''], ['Period', t.ser ? 'Week · last 8 weeks' : 'Now'], ['Source', MM.repo]];
277
- const vals = t.ser ? H('Values') + `<div class="vtb">${t.ser.map((v, j) => `<div><span>${esc(t.wk[j])}</span><b>${v == null ? 'No runs' : esc(metFmt(t, v))}</b></div>`).join('')}</div>` : '';
247
+ const rows = MT.factRows(t, MM.repo, MM.weeks);
248
+ const vals = t.ser ? H('Values') + `<div class="vtb">${t.ser.map((v, j) => `<div><span>${esc(t.wk[j])}</span><b>${v == null ? (t.since ? 'Not kept yet' : 'No runs') : esc(MT.fmt(t, v))}</b></div>`).join('')}</div>` : '';
278
249
  const pane = `<article class="paper doc"><p class="lede" style="margin:0 0 10px">${esc(t.def)}</p>${kv(rows)}${vals}<p class="note" style="margin-top:12px">${esc(MM.note)}</p></article>`;
279
250
  openDlg({ eye: 'Measure · real data', title: t.label, sub: MM.repo, say: d.say, stream: turnA(logHtml({ logTitle: 'Read from the repository', log: ['Read the repository\'s own records', 'Counted them by week', 'Changed nothing'] })) + turnA(ptx(d.say)), noteKey: r.key, pane, label: 'Measure' });
280
251
  loadThread(r.key);
281
252
  }
282
253
 
283
- const metIdx = (e) => { const t = e.target.closest('[data-m]'); return t ? t : null; };
284
- const metBody = () => $('#metBody');
285
254
  function metWire() {
286
- metBody().addEventListener('click', (e) => { const t = metIdx(e); if (t) metOpenTile(+t.dataset.m); });
287
- metBody().addEventListener('keydown', (e) => {
288
- const t = metIdx(e); if (!t) return;
289
- if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); metOpenTile(+t.dataset.m); return; }
290
- if (!t.classList.contains('mch') || !/^Arrow(Left|Right)$/.test(e.key)) return;
291
- e.preventDefault(); const m = MM.tiles[+t.dataset.m], now = t.dataset.j == null ? m.ser.length - 1 : +t.dataset.j; metChartAt(t, now + (e.key === 'ArrowLeft' ? -1 : 1));
292
- });
293
- metBody().addEventListener('pointermove', (e) => { const t = metIdx(e); if (!t || !t.classList.contains('mch')) return; const s = $('svg', t).getBoundingClientRect(), m = MM.tiles[+t.dataset.m], g = metGeo(m); metChartAt(t, Math.round(((e.clientX - s.left) / s.width * g.W - g.P) / (g.W - 2 * g.P) * (g.n - 1))); });
294
- metBody().addEventListener('pointerout', (e) => { const t = metIdx(e); if (t && t.classList.contains('mch') && !t.contains(e.relatedTarget)) metChartAt(t, null); });
255
+ MT.wireTiles($('#metBody'), () => MM.tiles, metOpenTile);
295
256
  $('#perTabs').addEventListener('click', (e) => { const b = e.target.closest('[aria-disabled="true"]'); if (b) toast('PMOS counts runs and merges by week only.'); });
296
257
  }
297
258
 
@@ -10,6 +10,7 @@ import { $, $$, esc, openDlg, closeDlg, toast, loadThread, onScroll, wireRail, l
10
10
  import { pmPost, pmGet } from './http.js';
11
11
  import { openStudio } from './premium-studio.js';
12
12
  import { openReport } from './premium-report-read.js';
13
+ import * as MT from './premium-metric-tiles.js';
13
14
 
14
15
  let M = null; // the model
15
16
  let dash = 'all'; // the dashboard on screen
@@ -363,6 +364,57 @@ function openChart(c) {
363
364
  }
364
365
  $('#dBody').addEventListener('click', (e) => { const lt = e.target.closest('#logT'); if (lt) { const c = $('#alog').classList.toggle('col'); lt.setAttribute('aria-expanded', !c); } });
365
366
 
367
+ /* ── the Board measures card (initiative briefing-premium-metrics, option C) ─────────────────────────────────────────
368
+ * The Board's four measures from GET /api/board-metrics-premium?ws=&weeks=, drawn with the Board's own tiles over 8, 26 or 52 weeks. A measure's dialog
369
+ * holds the page's one target press: POST /api/board-metric-targets/save, which the Board then draws as the chip, the dashed line and the outline. */
370
+ let BM = null, bmWeeks = 8, bmTimer = null;
371
+ const BM_KEY = 'pmos.premium.bmWeeks';
372
+ try { const w = Number(localStorage.getItem(BM_KEY)); if ([8, 26, 52].includes(w)) bmWeeks = w; } catch { /* a blocked store keeps 8 weeks */ }
373
+ function bmDraw() {
374
+ const card = $('#cBm'); card.hidden = false;
375
+ $$('#bmRange button').forEach((b) => b.setAttribute('aria-pressed', String(+b.dataset.w === bmWeeks))); pillOf($('#bmRange'));
376
+ if (!BM) return;
377
+ $('#bmCap').textContent = BM.header;
378
+ $('#bmHint').innerHTML = (BM.lead ? `<b class="mflag">${esc(BM.lead)}</b> ` : '') + esc(BM.body) + ' Press a measure to set its target. The Board draws the same target.';
379
+ $('#bmBody').style.gridTemplateColumns = 'repeat(' + Math.min(4, BM.tiles.length) + ',minmax(0,1fr))';
380
+ $('#bmBody').innerHTML = BM.tiles.map(MT.tileHtml).join('');
381
+ $('#bmNote').textContent = BM.note;
382
+ }
383
+ async function bmLoad() {
384
+ clearTimeout(bmTimer);
385
+ if (!M || !M.board || !M.board.ws) { $('#cBm').hidden = true; return; }
386
+ let r = null;
387
+ try { const res = await fetch('/api/board-metrics-premium?ws=' + encodeURIComponent(M.board.ws) + '&weeks=' + bmWeeks, { credentials: 'same-origin' }); r = await res.json(); } catch { r = null; }
388
+ if (!r || !r.ok || r.state !== 'ready') { BM = null; bmDraw(); $('#bmCap').textContent = 'not read'; $('#bmHint').textContent = 'The Board measures could not be read, so none is shown.' + (r && r.error ? ' The reason: ' + r.error : ''); $('#bmBody').innerHTML = ''; $('#bmNote').textContent = ''; return; }
389
+ BM = r.model; bmDraw();
390
+ if (BM.pending) bmTimer = setTimeout(bmLoad, 4000); // the workflow engine is still deriving Blocked and Idle
391
+ }
392
+ function bmOpen(i) {
393
+ const t = BM && BM.tiles[i]; if (!t) return;
394
+ const vals = t.ser ? `<h3 class="sh">Values</h3><div class="vtb">${t.ser.map((v, j) => `<div><span>${esc(t.wk[j])}</span><b>${v == null ? (t.since ? 'Not kept yet' : 'No runs') : esc(MT.fmt(t, v))}</b></div>`).join('')}</div>` : '';
395
+ const form = t.absent ? `<p class="note" style="margin:12px 0 0">A target can be set once this measure is counted.</p>`
396
+ : `<div class="addf" style="margin-top:14px"><label>Target (${t.lowBetter ? 'at most' : 'at least'})<input id="bmT" inputmode="decimal" maxlength="12" value="${t.tg != null ? esc(String(t.tg)) : ''}" placeholder="For example: ${t.key === 'corrections' ? '10' : t.key === 'merges' ? '5' : '0'}"></label>
397
+ <p class="note" id="bmM" role="status" style="margin:0;min-height:1.2em"></p><div class="cact"><button class="cta" id="bmGo">Save target</button>${t.tg != null ? '<button class="cta alt" id="bmClr">Clear target</button>' : ''}</div></div>`;
398
+ const pane = `<article class="paper doc"><p class="lede" style="margin:0 0 10px">${esc(t.def)}</p>${kv(MT.factRows(t, BM.repo, BM.weeks))}${form}${vals}<p class="note" style="margin-top:12px">${esc(BM.note)}</p></article>`;
399
+ const say = t.tg != null ? `The target is ${t.tg}. Change it or clear it here; the Board draws it too.` : 'No target is set. Type one and save it; the Board draws it too.';
400
+ openDlg({ eye: 'Board measure · real data', title: t.label, sub: BM.repo, say, stream: turnA(ptx(say)), noteKey: null, pane, label: 'Measure' });
401
+ $('#askF').hidden = true;
402
+ $('#oMain').onchange = null;
403
+ $('#oMain').onclick = async (e) => {
404
+ const go = e.target.closest('#bmGo'), clr = e.target.closest('#bmClr'); if (!go && !clr) return;
405
+ const target = clr ? null : $('#bmT').value.trim();
406
+ if (go && target === '') { $('#bmM').textContent = 'Type a number first.'; return; }
407
+ (go || clr).disabled = true; $('#bmM').textContent = 'Saving.';
408
+ const res = await pmPost('/api/board-metric-targets/save', { ws: M.board.ws, key: t.key, target });
409
+ (go || clr).disabled = false;
410
+ if (!res || res.ok !== true) { $('#bmM').textContent = (res && res.error) || 'The target could not be saved.'; return; }
411
+ closeDlg(); toast(clr ? 'The target of ' + t.label + ' is cleared.' : 'The target of ' + t.label + ' is ' + target + '.');
412
+ bmLoad();
413
+ };
414
+ }
415
+ MT.wireTiles($('#bmBody'), () => (BM ? BM.tiles : []), bmOpen);
416
+ $('#bmRange').addEventListener('click', (e) => { const b = e.target.closest('[data-w]'); if (!b || +b.dataset.w === bmWeeks) return; bmWeeks = +b.dataset.w; try { localStorage.setItem(BM_KEY, String(bmWeeks)); } catch { /* not kept */ } bmDraw(); bmLoad(); });
417
+
366
418
  /* ── load ─────────────────────────────────────────────────────────────────────────────────────────────────────── */
367
419
  function draw() { drawHead(); if (!M.dashboards.some((d) => d.id === dash)) dash = 'all'; drawDash(); drawReps(); drawDock(); onScroll(); }
368
420
  async function load() {
@@ -375,7 +427,7 @@ async function load() {
375
427
  setTimeout(load, 15000);
376
428
  return;
377
429
  }
378
- M = r.model; draw();
430
+ M = r.model; draw(); bmLoad();
379
431
  }
380
432
  $('#brief').textContent = 'Reading the records.';
381
433
  load();
@@ -0,0 +1,68 @@
1
+ /* pm/premium-metric-tiles.js — the tiles of the Board's four measures (initiative briefing-premium-metrics), drawn the same way on the Board's Metrics
2
+ * card and on the Insights page's Board measures card. It draws lib/board-metrics-premium.js's tiles: a number and a chart only where a record counted
3
+ * one, "Not read" where it could not be, and a target's chip, dashed line and outline only where the PM set one on Insights. Nothing here writes.
4
+ *
5
+ * tileHtml(t, i) → one tile's HTML
6
+ * chartAt(el, t, j) → read week j of a chart tile (null: the latest week)
7
+ * wireTiles(body, tiles, open) → pointer and arrow-key reading, Enter and press to open(i) */
8
+ import { $, esc } from './premium-shell.js';
9
+
10
+ const GEO = { W: 220, H: 60, P: 5 };
11
+ export function geo(m) {
12
+ const n = m.ser.length, { W, H, P } = GEO, vs = m.ser.filter((v) => v != null).concat(m.tg != null ? [m.tg] : []);
13
+ const lo = Math.min(...vs), hi = Math.max(...vs), sp = hi - lo || 1;
14
+ return { n, W, H, P, X: (j) => (n > 1 ? P + j * (W - 2 * P) / (n - 1) : W / 2), Y: (v) => P + (1 - (v - lo) / sp) * (H - 2 * P) };
15
+ }
16
+ export const fmt = (m, v) => (+v).toFixed(m.dec) + (m.suf || '');
17
+ const lastJ = (t) => t.ser.reduce((a, v, j) => (v != null ? j : a), 0);
18
+
19
+ export function tileHtml(t, i) {
20
+ if (t.absent) return `<div class="mt1" data-m="${i}" data-op="m:${i}" tabindex="0" role="button" aria-label="${esc(t.label)}: ${esc(t.absent)}. ${esc(t.why)}"><span>${esc(t.label)}</span><b class="mval">${esc(t.absent)}</b><em class="mwk">${esc(t.why)}</em></div>`;
21
+ const chip = t.tg != null ? `<i class="mchip ${t.ok ? 'ok' : 'warn'}">${esc(t.chip)}</i>` : t.look ? '<i class="mchip warn">Needs a look</i>' : '';
22
+ const lab = chip ? `<span class="mlab">${esc(t.label)}${chip}</span>` : `<span>${esc(t.label)}</span>`, off = t.look ? ' off' : '';
23
+ const tgt = t.tg != null ? `<em class="mtg">${esc(t.targetTxt)}</em>` : '';
24
+ const chg = t.change ? `<span class="mchg ${t.change.d === 0 ? '' : t.change.good ? 'good' : 'bad'}">${t.change.d === 0 ? '' : t.change.d > 0 ? '▲ ' : '▼ '}${esc(t.change.txt)}</span>` : '';
25
+ const say = (t.look ? ', needs a look' : '') + (t.tg != null ? ', ' + t.targetTxt + ', ' + t.chip : '');
26
+ if (!t.ser) return `<div class="mt1 ${t.kind}${off}" data-m="${i}" data-op="m:${i}" tabindex="0" role="button" aria-label="${esc(t.label)}, ${esc(t.value)}, ${esc(t.text)}${esc(say)}">${lab}<b class="mval">${esc(t.value)}</b><em class="mwk">${esc(t.text)}</em>${tgt}</div>`;
27
+ const g = geo(t); let ln = '', op = false;
28
+ t.ser.forEach((v, j) => { if (v == null) { op = false; return; } ln += (op ? 'L' : 'M') + g.X(j).toFixed(1) + ',' + g.Y(v).toFixed(1); op = true; });
29
+ const f = Math.max(0, t.ser.findIndex((v) => v != null)), gap = t.ser.slice(f).some((v) => v == null), n1 = g.n - 1, lj = lastJ(t);
30
+ const tgl = t.tg != null ? `<line class="tg" x1="${g.P}" x2="${g.W - g.P}" y1="${g.Y(t.tg).toFixed(1)}" y2="${g.Y(t.tg).toFixed(1)}"/>` : '';
31
+ return `<div class="mt1 mch ${t.kind}${off}" data-m="${i}" data-op="m:${i}" tabindex="0" role="button" aria-label="${esc(t.label)} over ${t.ser.length} weeks, now ${esc(t.value)}${esc(say)}. Use the arrow keys to read each week.">${lab}<b class="mval">${esc(t.value)}</b><em class="mwk">${esc(t.text)}</em>${tgt}${chg}`
32
+ + `<svg viewBox="0 0 ${g.W} ${g.H}">${f > 0 ? `<line class="gp" x1="${g.X(0)}" x2="${g.X(f)}" y1="${g.H - g.P}" y2="${g.H - g.P}"/>` : ''}${gap || f === n1 ? '' : `<path class="ar" d="${ln}L${g.X(n1)},${g.H}L${g.X(f)},${g.H}Z"/>`}${tgl}<path class="ln2" d="${ln}"/><line class="cx" x1="0" x2="0" y1="0" y2="${g.H}"/><circle class="dt" cx="${g.X(lj)}" cy="${g.Y(t.ser[lj])}" r="3.5"/></svg>`
33
+ + `<span class="mfoot"><i>${esc(t.wk[0])}</i>${t.tg != null ? '<i class="tgl">dashed line is the target</i>' : ''}<i>${esc(t.wk[t.wk.length - 1])}</i></span></div>`;
34
+ }
35
+
36
+ /** Read one week of a chart tile: the guide line and dot move, the value and caption change. */
37
+ export function chartAt(el, t, j) {
38
+ if (!t || !t.ser) return;
39
+ const g = geo(t), lj = lastJ(t); j = j == null ? lj : Math.max(0, Math.min(g.n - 1, j));
40
+ const v = t.ser[j], has = v != null, x = g.X(j), y = has ? g.Y(v) : 0, now = j === lj;
41
+ const cx = $('.cx', el), dt = $('.dt', el);
42
+ cx.setAttribute('x1', x); cx.setAttribute('x2', x); dt.setAttribute('cx', x); dt.setAttribute('cy', y); dt.style.opacity = has ? '' : '0';
43
+ el.classList.toggle('hv', !now); el.dataset.j = j;
44
+ const none = t.since ? 'Not kept yet' : 'No runs';
45
+ const val = now ? t.value : has ? fmt(t, v) : none, cap = now ? t.text : 'Week to ' + t.wk[j] + (t.nt[j] ? ' · ' + t.nt[j] : '') + (has && t.tg != null ? ' · ' + t.targetTxt : '');
46
+ $('.mval', el).textContent = val; $('.mwk', el).textContent = cap;
47
+ el.setAttribute('aria-label', t.label + ', ' + (now ? 'now ' : '') + val + ', ' + cap + '. Use the arrow keys to read each week.');
48
+ }
49
+
50
+ /** Pointer and arrow-key reading of the chart tiles in `body`, and Enter, Space or a press to open(i). tiles() gives the tiles drawn now. */
51
+ export function wireTiles(body, tiles, open) {
52
+ const at = (e) => e.target.closest('[data-m]');
53
+ body.addEventListener('click', (e) => { const t = at(e); if (t) open(+t.dataset.m); });
54
+ body.addEventListener('keydown', (e) => {
55
+ const t = at(e); if (!t) return;
56
+ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); open(+t.dataset.m); return; }
57
+ if (!t.classList.contains('mch') || !/^Arrow(Left|Right)$/.test(e.key)) return;
58
+ e.preventDefault(); const m = tiles()[+t.dataset.m], now = t.dataset.j == null ? lastJ(m) : +t.dataset.j; chartAt(t, m, now + (e.key === 'ArrowLeft' ? -1 : 1));
59
+ });
60
+ body.addEventListener('pointermove', (e) => { const t = at(e); if (!t || !t.classList.contains('mch')) return; const s = $('svg', t).getBoundingClientRect(), m = tiles()[+t.dataset.m], g = geo(m); chartAt(t, m, Math.round(((e.clientX - s.left) / s.width * g.W - g.P) / (g.W - 2 * g.P) * (g.n - 1))); });
61
+ body.addEventListener('pointerout', (e) => { const t = at(e); if (t && t.classList.contains('mch') && !t.contains(e.relatedTarget)) chartAt(t, tiles()[+t.dataset.m], null); });
62
+ }
63
+
64
+ /** The rows of a measure's dialog: what it is now, its target and gap where one is set, how it changed, and where it was counted. */
65
+ export function factRows(t, repo, weeks) {
66
+ return t.absent ? [['Now', t.absent], ['Why', t.why], ['Counted from', repo]]
67
+ : [['Now', t.value], ['Counted', t.text], ['Target', t.tg != null ? fmt(t, t.tg) : 'None set. Set one on Insights'], ['Gap', t.tg != null ? (t.ok ? 'On target' : t.chip + ' the target') : ''], ['Change', t.change ? t.change.txt : ''], ['Better when', t.lowBetter ? 'Lower' : t.lowBetter === false ? 'Higher' : ''], ['Period', 'Week · last ' + (weeks || 8) + ' weeks'], ['Source', repo]].filter((r) => r[1] !== '');
68
+ }
@@ -5,7 +5,7 @@
5
5
  <meta name="pmos-nonce" content="" />
6
6
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
7
7
  <title>PMOS · Insights</title>
8
- <!-- The premium Insights (initiative briefing-premium-insights, slice 9). The fourth place on the rail, in the Briefing's shell. It reads GET /api/insights-premium, built from the KR metric records and the report files the console's Reports tab reads. It presses nothing and writes nothing. -->
8
+ <!-- The premium Insights (initiative briefing-premium-insights, slice 9). The fourth place on the rail, in the Briefing's shell. It reads GET /api/insights-premium, built from the KR metric records and the report files the console's Reports tab reads, and GET /api/board-metrics-premium for the Board measures card, whose one press sets a target (POST /api/board-metric-targets/save). -->
9
9
  <link rel="preload" href="/vendor/geist-var.woff2" as="font" type="font/woff2" crossorigin />
10
10
  <link rel="stylesheet" href="/pm/premium.css" />
11
11
  <link rel="stylesheet" href="/pm/premium-insights.css" />
@@ -41,6 +41,12 @@
41
41
  <button class="glass round" id="theme" aria-label="Switch light or dark"><svg class="i" viewBox="0 0 24 24"><path d="M20 14.5A8 8 0 0 1 9.5 4 8 8 0 1 0 20 14.5z"/></svg></button></div>
42
42
  </header>
43
43
  <section class="hero hero-slim"><p class="brief rise" style="--d:2" id="brief" aria-live="polite"></p></section>
44
+ <section class="card rise" style="--d:4" id="cBm" aria-labelledby="hBm" hidden>
45
+ <div class="ch"><span class="ic"><svg class="i" viewBox="0 0 24 24"><path d="M4 20V10M10 20V4M16 20v-8M22 20H2"/></svg></span><h2 id="hBm">Board measures</h2><small id="bmCap"></small><div class="seg mper" id="bmRange" role="group" aria-label="Range"><i class="pill"></i><button data-w="8" aria-pressed="true">8 weeks</button><button data-w="26" aria-pressed="false">26 weeks</button><button data-w="52" aria-pressed="false">52 weeks</button></div></div>
46
+ <p class="mhint" id="bmHint"></p>
47
+ <div class="bt2 ibt" id="bmBody"></div>
48
+ <p class="note" id="bmNote"></p>
49
+ </section>
44
50
  <div class="nl">
45
51
  <div class="nlc">
46
52
  <section class="card rise" style="--d:5" id="cDash" aria-labelledby="hDash">
@@ -57,7 +63,7 @@
57
63
  </section>
58
64
  </aside>
59
65
  </div>
60
- <p class="foot" id="foot">Charts read the KR metric records of this workspace and never invent a number. A press here records only what it says: a dashboard or a chart in the workspace's state folder, a report setup, request or dismissal in the report ledger, or a report's look in its design folder. Left out: run-based charts such as corrections per 100 runs (they belong to the Board's Metrics card), and any measure no record holds. Nothing is sent from this page.</p>
66
+ <p class="foot" id="foot">Charts read the KR metric records of this workspace and never invent a number. A press here records only what it says: a dashboard or a chart in the workspace's state folder, a report setup, request or dismissal in the report ledger, or a report's look in its design folder. The Board measures card counts the Board's four measures from the repository, over 8, 26 or 52 weeks; a target set there is saved in the workspace's state folder and drawn on the Board too. Left out: any measure no record holds. Nothing is sent from this page.</p>
61
67
  </main>
62
68
  <noscript>This page needs JavaScript.</noscript>
63
69
  <script type="module" src="/pm/premium-insights.js"></script>