create-pmos 0.429.0 → 0.431.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/package.json +25 -25
  2. package/payload/KIT-VERSION +2 -2
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/state/discoveries.md +1 -1
  6. package/payload/state/log.md +1 -1
  7. package/workspace/briefing-premium-board-test.js +2 -2
  8. package/workspace/briefing-premium-insights-test.js +1 -1
  9. package/workspace/changelog.json +24 -0
  10. package/workspace/guide/adler.md +45 -0
  11. package/workspace/guide/briefing-premium.md +2 -0
  12. package/workspace/guide/home.md +4 -4
  13. package/workspace/guide/index.md +1 -0
  14. package/workspace/guide/metric-drafts.md +2 -1
  15. package/workspace/guide/programs.md +4 -2
  16. package/workspace/intelligence-gaps-ui-test.js +168 -0
  17. package/workspace/lib/initiative-writer.js +16 -2
  18. package/workspace/lib/insight-moves.js +135 -0
  19. package/workspace/lib/insights-premium.js +4 -3
  20. package/workspace/lib/intel-report.js +16 -3
  21. package/workspace/lib/metric-drafts.js +32 -2
  22. package/workspace/lib/page-opens.js +74 -0
  23. package/workspace/lib/report-setups.js +1 -1
  24. package/workspace/lib/route-modules.js +2 -0
  25. package/workspace/lib/routes-insight-moves.js +119 -0
  26. package/workspace/lib/routes-insights-premium.js +10 -1
  27. package/workspace/lib/routes-metric-drafts.js +10 -1
  28. package/workspace/lib/routes-page-opens.js +26 -0
  29. package/workspace/lib/routes-report-setups.js +6 -1
  30. package/workspace/lib/settings-store.js +6 -0
  31. package/workspace/metric-drafts-ui-test.js +4 -4
  32. package/workspace/milestone-suggest-test.js +4 -4
  33. package/workspace/package-lock.json +2 -2
  34. package/workspace/package.json +1 -1
  35. package/workspace/premium-viewer-flicker-test.js +1 -1
  36. package/workspace/public/pm/bd-prog-panel.js +3 -3
  37. package/workspace/public/pm/bd-prog.js +2 -2
  38. package/workspace/public/pm/bd-span.js +17 -14
  39. package/workspace/public/pm/cozy-adler.css +82 -0
  40. package/workspace/public/pm/cozy-adler.js +270 -0
  41. package/workspace/public/pm/cozy-ev.css +3 -0
  42. package/workspace/public/pm/cozy-home.css +4 -0
  43. package/workspace/public/pm/cozy-insights.css +15 -1
  44. package/workspace/public/pm/cozy-nav.js +2 -0
  45. package/workspace/public/pm/cozy-search.js +4 -2
  46. package/workspace/public/pm/cozy-settings.js +15 -2
  47. package/workspace/public/pm/cozy-today.css +15 -0
  48. package/workspace/public/pm/cozy.css +16 -0
  49. package/workspace/public/pm/home-app.js +7 -9
  50. package/workspace/public/pm/home-chat.js +10 -2
  51. package/workspace/public/pm/home-day.js +39 -16
  52. package/workspace/public/pm/home-today.js +5 -3
  53. package/workspace/public/pm/ini-view-model.js +1 -1
  54. package/workspace/public/pm/ini-view.css +6 -0
  55. package/workspace/public/pm/ini-view.js +13 -0
  56. package/workspace/public/pm/metric-drafts.css +7 -0
  57. package/workspace/public/pm/metric-drafts.js +46 -7
  58. package/workspace/public/pm/ms-suggest.js +2 -1
  59. package/workspace/public/pm/premium-board.js +2 -2
  60. package/workspace/public/pm/premium-insights.js +76 -10
  61. package/workspace/public/pm/premium-vw-cal.js +1 -1
  62. package/workspace/public/pm/premium-welcome.js +3 -2
  63. package/workspace/public/pm/premium.css +3 -0
  64. package/workspace/public/pm/program-model.js +7 -0
  65. package/workspace/public/pm/split-merge.js +2 -1
  66. package/workspace/public/pm/stage-line.js +7 -5
  67. package/workspace/public/premium-intelligence.html +1 -1
  68. package/workspace/test-lists/intelligence-gaps-ui.json +5 -0
  69. package/workspace/test-lists/intelligence-gaps.json +5 -0
  70. package/workspace/test-lists/milestone-label.json +5 -0
@@ -0,0 +1,135 @@
1
+ 'use strict';
2
+ /* insight-moves.js — the drafted move of a ✦ strip finding on Intelligence (feedback batch 16 item 1, the first 0.429.0 gap). The strip said a
3
+ * goal is behind and stopped there; now each finding about a goal that is behind carries at most ONE drafted fix. Claude recommends it, the PM's ✓
4
+ * makes it through the normal file-mode writer, and Undo takes it back. lib/routes-insight-moves.js does the I/O. THE ONE WRITER and THE ONE FOLD
5
+ * of <state>/insight-moves.jsonl. Pure apart from the ledger file, with no clock of its own: every time comes in.
6
+ *
7
+ * THE MOVES, tried in this order; the first that fits is the one drafted, and a finding with none draws no ✓ (zero is silence):
8
+ * chase an active initiative that moves the goal is past its end date, has an owner and a Jira epic: a comment asking the owner for a new
9
+ * date goes to the outbox (channel jira-write). Nothing is sent: it waits in the outbox for the PM's own Send.
10
+ * anchor nothing active moves the goal, and one active initiative of the board has no anchor that resolves while its title shares a word with
11
+ * the goal: its parent_kr is set to the goal (an anchor the OKR files declare, the same check as any anchor change).
12
+ * date the goal will miss its target at this pace and the straight line reaches the target on a later day: the KR metric record's `by`
13
+ * moves to that day.
14
+ * Every number in a move is a field of a record or the projection the finding already states. No move is made from a guess about a cause.
15
+ *
16
+ * THE LEDGER. One line per event, { at, by, kind, sig, ... }:
17
+ * apply { sig, move, undo } the PM's ✓: what was written and what puts it back (date: { by }; anchor: { from }; chase: { entry })
18
+ * undo { sig } the Undo of the last apply of that sig
19
+ *
20
+ * draftFor(finding, model, o) PURE → the move or null. o: { initiatives (the board rows), anchorOk(text) → bool, today (YYYY-MM-DD) }
21
+ * draftAll(model, o) PURE → the model's insight and its `more` each given `move` (null when none), each marked `done` when applied
22
+ * sigOf(move) · fold(lines) → Map sig → { state: applied|undone, at, undo, move } · read(dir) · append(dir, actor, line, at) · ledgerFile(dir)
23
+ */
24
+ const fs = require('fs');
25
+ const path = require('path');
26
+ const crypto = require('crypto');
27
+
28
+ const LEDGER = 'insight-moves.jsonl';
29
+ const KINDS = new Set(['apply', 'undo']);
30
+ const BEHIND = new Set(['stuck', 'worse', 'off', 'stall', 'miss', 'closing']);
31
+ const MON = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
32
+ const DAY_RE = /^\d{4}-\d{2}-\d{2}$/;
33
+ const DAY = 864e5;
34
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
35
+ const str = (v) => (typeof v === 'string' ? v : '');
36
+ const ms = (v) => { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(v || '')); return m ? Date.UTC(+m[1], +m[2] - 1, +m[3]) : null; };
37
+ /** 12 January 2027: a date in full, as the reports write it. */
38
+ const full = (v) => { const t = ms(v); if (t === null) return ''; const d = new Date(t); return d.getUTCDate() + ' ' + MON[d.getUTCMonth()] + ' ' + d.getUTCFullYear(); };
39
+ const clip = (s, n) => { s = String(s == null ? '' : s).replace(/\s+/g, ' ').trim(); return s.length > n ? s.slice(0, n - 1).trimEnd() + '…' : s; };
40
+ const hash = (s) => crypto.createHash('sha1').update(String(s)).digest('hex').slice(0, 12);
41
+ const first = (s) => String(s || '').trim().split(/\s+/)[0] || '';
42
+
43
+ /* ── the words a title shares with a goal: four letters or more, the small words left out ── */
44
+ const STOP = new Set(['with', 'from', 'that', 'this', 'into', 'over', 'more', 'less', 'than', 'your', 'their', 'what', 'when', 'week', 'weeks', 'month',
45
+ 'rate', 'time', 'days', 'count', 'total', 'number', 'percent', 'goal', 'metric', 'make', 'new', 'improve', 'increase', 'reduce', 'better', 'faster']);
46
+ const wordsOf = (s) => [...new Set((String(s || '').toLowerCase().match(/[a-z][a-z0-9]{3,}/g) || []).filter((w) => !STOP.has(w)))];
47
+ const shared = (a, b) => { const B = new Set(wordsOf(b)); return wordsOf(a).filter((w) => B.has(w)); };
48
+
49
+ const ACTIVE = (r) => r && r.status !== 'done' && r.status !== 'cancelled' && !(typeof r.idx === 'number' && r.idx >= 6);
50
+ const sigOf = (m) => 'mv-' + hash([m.kind, m.goal, m.ini || '', m.to || m.epic || ''].join('|'));
51
+
52
+ /** The one move for a finding, or null. */
53
+ function draftFor(f, model, o = {}) {
54
+ if (!isObj(f) || !BEHIND.has(f.kind) || !f.chart) return null;
55
+ const goal = ((model && model.goals) || []).find((g) => g && g.key === f.chart);
56
+ if (!goal || !goal.id) return null;
57
+ const today = DAY_RE.test(str(o.today)) ? o.today : null, t0 = ms(today);
58
+ const active = (goal.moves || []).filter(ACTIVE);
59
+ // chase: the initiative most days past its end, with someone to ask and a ticket to ask on
60
+ if (t0 !== null) {
61
+ const late = active.filter((r) => r.owner && r.epic && ms(r.endAt) !== null && ms(r.endAt) < t0).sort((a, b) => ms(a.endAt) - ms(b.endAt))[0];
62
+ if (late) {
63
+ const days = Math.round((t0 - ms(late.endAt)) / DAY), who = clip(late.owner, 40);
64
+ const body = 'Hi ' + first(who) + ', ' + clip(late.title, 80) + ' was due on ' + full(late.endAt) + ' and is ' + days + (days === 1 ? ' day' : ' days') + ' over. '
65
+ + clip(goal.title, 80) + ' is behind its line' + (goal.nowTxt ? ' at ' + goal.nowTxt : '') + (goal.targetTxt ? ' against a target of ' + goal.targetTxt : '') + '. What is the new date?';
66
+ const m = { kind: 'chase', goal: goal.id, ini: late.id, owner: who, epic: late.epic, days, body,
67
+ text: 'Ask ' + who + ' for a new date on ' + clip(late.title, 60) + ', ' + days + (days === 1 ? ' day' : ' days') + ' over.',
68
+ label: 'Put the comment to ' + who + ' in the outbox', said: 'The comment to ' + who + ' is in the outbox. Nothing is sent until you send it.' };
69
+ return Object.assign(m, { sig: sigOf(m) });
70
+ }
71
+ }
72
+ // anchor: nothing active moves the goal; the one board initiative with no working anchor whose title shares a word with the goal
73
+ if (!active.length && typeof o.anchorOk === 'function') {
74
+ const to = [goal.id, goal.title].find((x) => x && o.anchorOk(x)) || null;
75
+ if (to) {
76
+ const hits = (o.initiatives || []).filter((r) => r && r.id && ACTIVE({ status: r.status }) && !(r.anchor && o.anchorOk(r.anchor)))
77
+ .map((r) => ({ r, w: shared(r.title || r.id, goal.title) })).filter((x) => x.w.length);
78
+ if (hits.length === 1) { // two or more candidates is a guess: none is drafted
79
+ const { r, w } = hits[0];
80
+ const m = { kind: 'anchor', goal: goal.id, ini: String(r.id), from: str(r.anchor), to,
81
+ text: 'Anchor ' + clip(r.title || r.id, 60) + ' to ' + clip(goal.title, 60) + '. Nothing moves this goal, and the title shares "' + w[0] + '".',
82
+ label: 'Anchor ' + clip(r.title || r.id, 60) + ' to this goal', said: clip(r.title || r.id, 60) + ' now moves ' + clip(goal.title, 60) + '.' };
83
+ return Object.assign(m, { sig: sigOf(m) });
84
+ }
85
+ }
86
+ }
87
+ // date: the line through the last readings reaches the target, later than the record's date
88
+ if (f.kind === 'miss' && DAY_RE.test(str(f.whenAt)) && DAY_RE.test(str(goal.byAt)) && f.whenAt > goal.byAt) {
89
+ const m = { kind: 'date', goal: goal.id, from: goal.byAt, to: f.whenAt,
90
+ text: 'Move the target date of ' + clip(goal.title, 60) + ' from ' + full(goal.byAt) + ' to ' + full(f.whenAt) + ', when it gets there at this pace.',
91
+ label: 'Move the target date to ' + full(f.whenAt), said: 'The target date is ' + full(f.whenAt) + ' now.' };
92
+ return Object.assign(m, { sig: sigOf(m) });
93
+ }
94
+ return null;
95
+ }
96
+
97
+ /** The insight and its `more`, each with `move` (null when none). A move the PM already made, and did not undo, is marked done with its day. */
98
+ function draftAll(model, o = {}) {
99
+ const I = model && model.insight;
100
+ if (!I || I.none) return model;
101
+ const F = o.ledger || new Map();
102
+ const one = (f) => { const m = draftFor(f, model, o); if (m) { const x = F.get(m.sig); if (x && x.state === 'applied') m.done = { at: x.at }; } return m; };
103
+ I.move = one({ kind: I.kind, chart: I.chart, whenAt: I.whenAt });
104
+ for (const x of I.more || []) x.move = one(x);
105
+ return model;
106
+ }
107
+
108
+ /* ── the ledger ── */
109
+ function ledgerFile(dir) { return dir ? path.join(dir, LEDGER) : null; }
110
+ function readLines(file) {
111
+ if (!file) return [];
112
+ let text = '';
113
+ try { text = fs.readFileSync(file, 'utf8'); } catch { return []; }
114
+ const out = [];
115
+ for (const raw of text.split('\n')) { if (!raw.trim()) continue; try { const l = JSON.parse(raw); if (isObj(l) && KINDS.has(l.kind) && str(l.sig)) out.push(l); } catch { /* a torn line is skipped */ } }
116
+ return out;
117
+ }
118
+ function fold(lines) {
119
+ const F = new Map();
120
+ for (const l of lines || []) {
121
+ if (!isObj(l) || !KINDS.has(l.kind) || !str(l.sig)) continue;
122
+ if (l.kind === 'apply') F.set(l.sig, { state: 'applied', at: str(l.at), undo: isObj(l.undo) ? l.undo : {}, move: isObj(l.move) ? l.move : {} });
123
+ else { const x = F.get(l.sig); if (x && x.state === 'applied') x.state = 'undone'; }
124
+ }
125
+ return F;
126
+ }
127
+ function read(dir) { return fold(readLines(ledgerFile(dir))); }
128
+ function append(dir, actor, ev, at) {
129
+ const line = { at: at || null, by: (actor && actor.by) || null, ...ev };
130
+ fs.mkdirSync(dir, { recursive: true });
131
+ fs.appendFileSync(ledgerFile(dir), JSON.stringify(line) + '\n');
132
+ return line;
133
+ }
134
+
135
+ module.exports = { LEDGER, BEHIND, draftFor, draftAll, sigOf, wordsOf, shared, ledgerFile, readLines, fold, read, append, full };
@@ -125,6 +125,7 @@ function findingsOfChart(c) {
125
125
  if (p && !p.toward) f.push({ kind: 'stall', score: c.pivot ? 101 : 96, text: c.title + ' will miss its ' + tg + ' target on ' + c.by + ' unless it turns.', proj: true,
126
126
  why: (c.pivot ? 'It has been behind its line at three readings in a row. ' : '') + 'Over its last ' + p.n + ' readings it went ' + move(p.from.v, p.now) + ', which is ' + (p.perWeek === 0 ? 'no move' : 'away from the target') + '. A straight line through them never reaches ' + tg + '.' });
127
127
  else if (p && !p.reaches) f.push({ kind: 'miss', score: 95, text: c.title + ' will miss its ' + tg + ' target on ' + c.by + ' at this pace.', proj: true,
128
+ whenAt: p.when && p.when - isoDay(c.lastAt) < 5 * 365 * DAY ? new Date(p.when).toISOString().slice(0, 10) : null, // batch 16: the day the line reaches the target, for a drafted date move
128
129
  why: 'It is at ' + num(now, u) + ' and moving ' + amount(Math.abs(p.perWeek), u) + ' a week toward it, so it reaches about ' + num(r1(p.atDue), u) + ' by ' + c.by + ', ' + amount(r1(p.short), u) + ' short.'
129
130
  + (p.when && p.when - isoDay(c.lastAt) < 5 * 365 * DAY ? ' At this pace it gets there around ' + dayTxt(p.when) + '.' : '') });
130
131
  else if (p) f.push({ kind: 'course', score: 62, text: c.title + ' is short of its target but on course to reach ' + tg + by + '.', proj: true,
@@ -234,8 +235,8 @@ function insightOf(charts, findings, total) {
234
235
  const head = findings[0] || null;
235
236
  return { none: false, off, total: charts.length, asOf: shortDate(last), calm: !head,
236
237
  text: head ? head.text : charts.some((c) => c.target !== null) ? 'Nothing stands out. No measure moved much, and none is far behind its line.' : 'Nothing stands out. No measure here has a target, so the series can only be described.',
237
- why: head ? head.why : '', chart: head ? head.chart : null, kind: head ? head.kind : 'calm', proj: !!(head && head.proj),
238
- more: findings.slice(1, 3).map((x) => ({ text: x.text, chart: x.chart })) };
238
+ why: head ? head.why : '', chart: head ? head.chart : null, kind: head ? head.kind : 'calm', proj: !!(head && head.proj), whenAt: (head && head.whenAt) || null,
239
+ more: findings.slice(1, 3).map((x) => ({ text: x.text, why: x.why || '', chart: x.chart, kind: x.kind, whenAt: x.whenAt || null })) };
239
240
  }
240
241
 
241
242
  /** The opening sentence of a report file (insights-one-list L6): the first prose paragraph after the frontmatter, past headings, lists, tables, quotes, code
@@ -287,7 +288,7 @@ const anchorHits = (a, o) => !!a && (String(a) === String(o.id) || String(a) ===
287
288
  function initOf(r) {
288
289
  const i = lifeIndex(r.stage);
289
290
  return { id: String(r.id), title: clip(r.title || r.id, 120), stage: r.stage || '', idx: i, stageLabel: i >= 0 ? LIFE_LABEL[i] : (r.stage || ''), status: r.status || '', lane: r.lane || '',
290
- owner: r.owner || '', end: r.end ? shortDate(r.end) : '', endAt: r.end ? String(r.end).slice(0, 10) : null, anchor: r.anchor || '',
291
+ owner: r.owner || '', end: r.end ? shortDate(r.end) : '', endAt: r.end ? String(r.end).slice(0, 10) : null, anchor: r.anchor || '', epic: Array.isArray(r.epics) && r.epics.length ? String(r.epics[0]) : null,
291
292
  startAt: r.start ? String(r.start).slice(0, 10) : null, skipped: IG.skippedOf(r.warnings), milestone: milestoneOf(r, i) };
292
293
  }
293
294
  /** The milestone an initiative works toward next, for the goal Viewer's "Moved by" (canvas OvViewers "Goal"): the first milestone stage of its
@@ -242,10 +242,23 @@ const nameOf = (name, s) => clip((name || 'Intelligence') + ' ' + ({ daily: 'dai
242
242
 
243
243
  // ── the ✦ strip proposals (RfA1, RfA6) ───────────────────────────────────────────────────────────────────────────────────────
244
244
  /** A report the data suggests on its own. `found`: a Library "Found in your work" pattern (the same numbers sent again and again).
245
- * `period-end`: the goals in view reach their date within 14 days, so a review is due. "The same view opened weekly" is not proposed: no
246
- * record of page opens is kept. `dismissed` holds the ids the PM said Not now to. */
247
- function proposalsOf(model, { findings = [], dismissed = [], now = Date.now() } = {}) {
245
+ * `period-end`: the goals in view reach their date within 14 days, so a review is due.
246
+ * `opened`: the same view opened in each of the last three weeks (feedback batch 16 item 1; lib/page-opens.js weeklyOf, read from the PM's own
247
+ * page opens, local only). Proposed only when that record says so, and never for a view a report already covers (`covered`: the setups'
248
+ * Intelligence scopes). `dismissed` holds the ids the PM said Not now to. */
249
+ function proposalsOf(model, { findings = [], dismissed = [], now = Date.now(), weekly = null, covered = [] } = {}) {
248
250
  const out = [], no = new Set(dismissed || []);
251
+ if (weekly && SCOPE_RE.test(String(weekly.view)) && !new Set(covered || []).has(weekly.view)) {
252
+ const D = weekly.view.startsWith('dashboard:') ? ((model && model.dashboards) || []).find((d) => d.id === weekly.view.slice(10)) : null;
253
+ const id = 'opened:' + weekly.view;
254
+ if ((D || weekly.view === 'view') && !no.has(id)) {
255
+ const name = D ? D.name : (model && model.board && model.board.name) || 'Intelligence', DN = { Mon: 'Monday', Tue: 'Tuesday', Wed: 'Wednesday', Thu: 'Thursday', Fri: 'Friday', Sat: 'Saturday', Sun: 'Sunday' };
256
+ out.push({ kind: 'opened', id, scope: weekly.view, name: nameOf(name, { cadence: 'weekly' }),
257
+ text: 'You open ' + (D ? 'the ' + clip(D.name, 40) + ' dashboard' : 'this view') + ' every week. Shall I make it a report that drafts itself' + (DN[weekly.day] ? ' before ' + DN[weekly.day] : '') + '?',
258
+ why: 'You opened it in each of the last ' + weekly.weeks + ' weeks' + (DN[weekly.day] ? ', most on ' + DN[weekly.day] + 's' : '') + '.',
259
+ defaults: { name: nameOf(name, { cadence: 'weekly' }), audience: '', schedule: { cadence: 'weekly', day: DN[weekly.day] ? weekly.day : 'Mon', time: '08:00' }, output: 'pdf', finding: null, from: null } });
260
+ }
261
+ }
249
262
  const f = (findings || []).find((x) => x && x.proposal && x.proposal.audience && !no.has('found:' + x.id));
250
263
  if (f) {
251
264
  const ev = (f.evidence || [])[0];
@@ -20,6 +20,7 @@
20
20
  * keep { row, rid } ✓: the kr-metrics record it wrote
21
21
  * drop { row } ✕
22
22
  * undo { row, rid? } a kept row back to open (its record retired), or a dropped one back to open
23
+ * edit { row, set: { name?, target?, targetTxt?, source? } } the PM's inline edit of an open row (batch 16 item 1); a later run's row line replaces it
23
24
  * A new run's start clears every row of the scope that was not kept: it drafts again. A kept row is the PM's and stays.
24
25
  *
25
26
  * ledgerFile(dir) · readLines(file) · read(dir) → fold · append(dir, actor, line, at)
@@ -27,6 +28,7 @@
27
28
  * viewOf(F, scope, id, o) PURE → the GET body (no ok): { scope, id, title, when, run: { state, step, reads }, rows, head, sub, src }
28
29
  * clean(scope, input) → { row } | { error } what `pmos metrics draft row` checks
29
30
  * keepFields(scope, id, row, o) → { fields, reading } | { error } the kr-metrics record a ✓ writes
31
+ * editOf(row, input) → { set } | { error } what the inline edit may change: name, target, source (lib/routes-metric-drafts.js /edit)
30
32
  * rowId(scope, id, group, name) · keyOf(scope, id) · countIn(S, run, group)
31
33
  * SCOPES · GROUPS · LIMITS · ROLES · TYPES · STEPS · WHEN
32
34
  */
@@ -35,7 +37,7 @@ const path = require('path');
35
37
  const crypto = require('crypto');
36
38
 
37
39
  const LEDGER = 'metric-drafts.jsonl';
38
- const KINDS = new Set(['epoch', 'start', 'step', 'read', 'row', 'end', 'keep', 'drop', 'undo']);
40
+ const KINDS = new Set(['epoch', 'start', 'step', 'read', 'row', 'end', 'keep', 'drop', 'undo', 'edit']);
39
41
  const SCOPES = ['product', 'program', 'initiative'];
40
42
  const GROUPS = { product: ['North Star', 'Inputs', 'Guardrails', 'Key results'], program: ['Program goal', 'Rolls up from', 'Guardrail'], initiative: ['Proves it worked', 'Early signal', 'Guardrail'] };
41
43
  const LIMITS = { 'North Star': 1, Inputs: 3, Guardrails: 2, 'Key results': 5, 'Program goal': 1, 'Rolls up from': 8, Guardrail: 1, 'Proves it worked': 1, 'Early signal': 1 };
@@ -136,6 +138,33 @@ function clean(scope, input) {
136
138
  return { row };
137
139
  }
138
140
 
141
+ /* ── the PM's inline edit of an open draft (batch 16 item 1): its name, its target and where it is measured. The rest (why, now, the group) stays
142
+ * Claude's: a change to those is asked of Claude in Home's chat. The target keeps the draft's own way of writing it ("≤ 3%", "$1,200"): the first
143
+ * number in it is replaced. ── */
144
+ const EDIT_KEYS = ['name', 'target', 'targetTxt', 'source'];
145
+ function editOf(row, input) {
146
+ if (!isObj(row)) return { error: 'There is no such draft.' };
147
+ if (!isObj(input)) return { error: 'An edit is { name?, target?, source? }.' };
148
+ const set = {};
149
+ if (input.name !== undefined) { const n = one(input.name, LIM.name); if (!n) return { error: 'The name is the metric, in a few words.' }; if (n !== row.name) set.name = n; }
150
+ if (input.target !== undefined && row.type !== 'Done or not') {
151
+ const t = typeof input.target === 'string' && input.target.trim() !== '' ? Number(input.target.replace(/[,\s]/g, '')) : input.target;
152
+ if (!fin(t)) return { error: 'The target is a number.' };
153
+ if (fin(row.now) && t === row.now) return { error: row.type === 'Stay within' ? 'The limit equals the reading now. Give it room.' : 'The target equals Now, so there is nothing to move.' };
154
+ if (t !== row.target) {
155
+ set.target = t;
156
+ const was = String(row.targetTxt || ''), m = /-?\d[\d,]*(\.\d+)?/.exec(was);
157
+ set.targetTxt = one(m ? was.slice(0, m.index) + String(t) + was.slice(m.index + m[0].length) : String(t), LIM.txt);
158
+ }
159
+ }
160
+ if (input.source !== undefined) {
161
+ const src = one(input.source, LIM.source);
162
+ if (!src && row.now != null) return { error: 'A measured Now names its source (Amplitude, Jira, …).' };
163
+ if (src !== (row.source || '')) set.source = src;
164
+ }
165
+ return { set };
166
+ }
167
+
139
168
  /* ── the fold ── */
140
169
  const blank = (scope, id) => ({ scope, id, title: '', when: '', run: null, runs: [], rows: new Map(), head: '', sub: '', src: '' });
141
170
  function fold(lines) {
@@ -169,6 +198,7 @@ function fold(lines) {
169
198
  if (str(l.sub)) s.sub = one(l.sub, 300);
170
199
  if (str(l.src)) s.src = one(l.src, 300);
171
200
  } else if (l.kind === 'keep' && str(l.row)) { const r = s.rows.get(l.row); if (r && r.state === 'open') Object.assign(r, { state: 'kept', rid: str(l.rid) || null }); }
201
+ else if (l.kind === 'edit' && str(l.row) && isObj(l.set)) { const r = s.rows.get(l.row); if (r && r.state === 'open') for (const k of EDIT_KEYS) if (l.set[k] !== undefined) r[k] = l.set[k]; }
172
202
  else if (l.kind === 'drop' && str(l.row)) { const r = s.rows.get(l.row); if (r && r.state === 'open') r.state = 'dropped'; }
173
203
  else if (l.kind === 'undo' && str(l.row)) { const r = s.rows.get(l.row); if (r && r.state !== 'open') { r.state = 'open'; delete r.rid; } }
174
204
  }
@@ -228,4 +258,4 @@ function keepFields(scope, id, row, o = {}) {
228
258
  return { fields: f, reading: now != null && DAY_RE.test(String(o.today || '')) ? { at: o.today, value: now } : null };
229
259
  }
230
260
 
231
- module.exports = { LEDGER, SCOPES, GROUPS, LIMITS, ROLES, TYPES, STEPS, WHEN, WHYS, WINDOW, ledgerFile, readLines, read, append, fold, viewOf, clean, keepFields, rowId, keyOf, countIn };
261
+ module.exports = { LEDGER, SCOPES, GROUPS, LIMITS, ROLES, TYPES, STEPS, WHEN, WHYS, WINDOW, ledgerFile, readLines, read, append, fold, viewOf, clean, keepFields, editOf, rowId, keyOf, countIn };
@@ -0,0 +1,74 @@
1
+ 'use strict';
2
+ /* page-opens.js — the pages the PM opens, by day (feedback batch 16 item 1, the third 0.429.0 gap). The ✦ strip on Intelligence may propose
3
+ * "You open this every week. Shall I make it a report?" only when this record says so (honest state). THE ONE WRITER and THE ONE FOLD of
4
+ * <runtime>/page-opens.jsonl. LOCAL ONLY: the file is in the workspace's runtime folder on this computer, never in the repository, and nothing
5
+ * reads it but the proposal below. No clock of its own: every time comes in.
6
+ *
7
+ * THE LEDGER. One line per page, view and day, { at, ws, page, view }. A second open of the same view on the same day writes nothing.
8
+ * page 'intelligence' (PAGES) view 'view' (the whole page) or 'dashboard:<id>' (a saved dashboard on screen), as lib/intel-report.js scopes
9
+ *
10
+ * record(dir, { ws, page, view }, at) → { ok, wrote } | { ok: false, error }
11
+ * readLines(dir) · ledgerFile(dir)
12
+ * weeklyOf(lines, { ws, page, now, weeks }) PURE → { view, weeks, day, opens } | null
13
+ * the view opened in each of the last `weeks` calendar weeks (Monday to Sunday; 3 by default), the week now counted when it has an open.
14
+ * `day` is the weekday it is opened on most (Mon…Sun), so a report can be ready before it. Two views that both qualify: the one opened more.
15
+ */
16
+ const fs = require('fs');
17
+ const path = require('path');
18
+
19
+ const FILE = 'page-opens.jsonl';
20
+ const PAGES = ['intelligence'];
21
+ const VIEW_RE = /^(view|dashboard:[A-Za-z0-9._:-]{1,100})$/;
22
+ const WS_RE = /^[A-Za-z0-9._-]{1,120}$/;
23
+ const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
24
+ const DAY = 864e5;
25
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
26
+ const dayOf = (at) => String(at || '').slice(0, 10);
27
+
28
+ function ledgerFile(dir) { return dir ? path.join(dir, FILE) : null; }
29
+ function readLines(dir) {
30
+ const f = ledgerFile(dir); if (!f) return [];
31
+ let text = '';
32
+ try { text = fs.readFileSync(f, 'utf8'); } catch { return []; }
33
+ const out = [];
34
+ for (const raw of text.split('\n')) { if (!raw.trim()) continue; try { const l = JSON.parse(raw); if (isObj(l) && typeof l.at === 'string' && PAGES.includes(l.page) && VIEW_RE.test(String(l.view))) out.push(l); } catch { /* a torn line is skipped */ } }
35
+ return out;
36
+ }
37
+ function record(dir, o, at) {
38
+ if (!dir) return { ok: false, error: 'This workspace has no runtime folder, so the open is not recorded.' };
39
+ if (!isObj(o) || !WS_RE.test(String(o.ws || ''))) return { ok: false, error: 'ws names the workspace' };
40
+ if (!PAGES.includes(o.page)) return { ok: false, error: 'page is one of: ' + PAGES.join(', ') };
41
+ const view = o.view == null || o.view === '' ? 'view' : String(o.view);
42
+ if (!VIEW_RE.test(view)) return { ok: false, error: 'view is view or dashboard:<id>' };
43
+ const d = dayOf(at);
44
+ if (readLines(dir).some((l) => l.ws === o.ws && l.page === o.page && l.view === view && dayOf(l.at) === d)) return { ok: true, wrote: false };
45
+ fs.mkdirSync(dir, { recursive: true });
46
+ fs.appendFileSync(ledgerFile(dir), JSON.stringify({ at, ws: o.ws, page: o.page, view }) + '\n');
47
+ return { ok: true, wrote: true };
48
+ }
49
+
50
+ /** The Monday (UTC) of the week a time falls in. */
51
+ const mondayOf = (t) => { const d = new Date(t), back = (d.getUTCDay() + 6) % 7; return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()) - back * DAY; };
52
+ function weeklyOf(lines, { ws, page = 'intelligence', now = Date.now(), weeks = 3 } = {}) {
53
+ const L = (lines || []).filter((l) => l && l.ws === ws && l.page === page && !Number.isNaN(Date.parse(l.at)));
54
+ if (!L.length) return null;
55
+ const thisWeek = mondayOf(now);
56
+ const byView = new Map();
57
+ for (const l of L) { if (!byView.has(l.view)) byView.set(l.view, []); byView.get(l.view).push(Date.parse(l.at)); }
58
+ let best = null;
59
+ for (const [view, T] of byView) {
60
+ const wk = new Set(T.map(mondayOf));
61
+ // the run of weeks ending this week (or last week, when this week has no open yet)
62
+ let end = wk.has(thisWeek) ? thisWeek : thisWeek - 7 * DAY, n = 0;
63
+ while (wk.has(end - n * 7 * DAY)) n++;
64
+ if (n < weeks) continue;
65
+ const from = end - (n - 1) * 7 * DAY, inRun = T.filter((t) => t >= from), count = new Array(7).fill(0);
66
+ for (const t of inRun) count[new Date(t).getUTCDay()]++;
67
+ const top = count.indexOf(Math.max(...count));
68
+ const cand = { view, weeks: n, day: DAYS[top], opens: inRun.length };
69
+ if (!best || cand.opens > best.opens) best = cand;
70
+ }
71
+ return best;
72
+ }
73
+
74
+ module.exports = { FILE, PAGES, VIEW_RE, ledgerFile, readLines, record, weeklyOf };
@@ -710,7 +710,7 @@ function dismissFinding(file, { id, name, by, now }) {
710
710
  }
711
711
  /** Not now on a report the Intelligence ✦ strip proposed: that proposal is not offered again. */
712
712
  function stripDismiss(file, { id, by, now }) {
713
- if (typeof id !== 'string' || !/^(found:rf-[0-9a-f]{10}|period-end:\d{4}-\d{2}-\d{2})$/.test(id)) return refuse(400, 'id is a proposal of the strip: found:<finding> or period-end:<date>');
713
+ if (typeof id !== 'string' || !/^(found:rf-[0-9a-f]{10}|period-end:\d{4}-\d{2}-\d{2}|opened:(view|dashboard:[A-Za-z0-9._:-]{1,100}))$/.test(id)) return refuse(400, 'id is a proposal of the strip: found:<finding>, period-end:<date> or opened:<view>');
714
714
  if (fold(readLines(file)).stripDismissed.has(id)) return { ok: true, unchanged: true };
715
715
  append(file, { ev: 'strip-dismiss', id }, { now, by });
716
716
  return { ok: true };
@@ -100,6 +100,8 @@ const MODULES = Object.freeze([
100
100
  'routes-premium-charts', // premium-studio-chart: the charts the PM makes in the Insight Studio (premium-charts.jsonl; page-press POST save)
101
101
  'routes-report-design', // report-design-studio: the design studio (describe, samples, turns, versions, This is it), cycle renders and decisions, speaker notes and pins
102
102
  '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)
103
+ 'routes-insight-moves', // batch 16 item 1: the ✓ and Undo of a drafted move on the Intelligence ✦ strip (insight-moves.jsonl; date, anchor, chase to the outbox)
104
+ 'routes-page-opens', // batch 16 item 1: the pages the PM opens, by day, local only (runtime page-opens.jsonl); drives the weekly report proposal
103
105
  'routes-metric-drafts', // batch 15 item 1: the metrics Claude drafts unasked for a product, a program or an initiative; ✓ keep writes kr-metrics (metric-drafts.jsonl; page-press POST)
104
106
  'routes-refresh', // data-refresh-settings: Settings › Data refresh: what refreshes, when, the refresh log, Refresh now
105
107
  ]);
@@ -0,0 +1,119 @@
1
+ 'use strict';
2
+ /* routes-insight-moves.js — the ✓ and the Undo of a ✦ strip move on Intelligence (feedback batch 16 item 1; the drafts are lib/insight-moves.js).
3
+ *
4
+ * POST /api/insight-moves/apply { ws, board, sig } → { ok, sig, kind, said } ✓: the move the strip shows now, made through its writer
5
+ * POST /api/insight-moves/undo { ws, sig } → { ok, sig } the last ✓ of that move, taken back
6
+ *
7
+ * The page sends only the move's sig. The route builds Intelligence again (GET /api/insights-premium, the page's own read) and makes the move it
8
+ * finds under that sig, so a stale page or a crafted body can never write a move Claude did not draft. A sig that is no longer drafted is 409.
9
+ *
10
+ * THE WRITERS, the same ones the rest of PMOS uses:
11
+ * date scripts/records edit of the KR metric record: { by } Undo: { by: the day it had }
12
+ * anchor lib/initiative-writer.js setAnchor (PM-only act 'anchor', pm-guard) Undo: restoreAnchor, the line exactly as it was
13
+ * chase scripts/outbox.js draftOutbox → lib/outbox-store.js, channel jira-write Undo: the outbox entry discarded (a sent entry stays: 409)
14
+ * Each ✓ and each Undo is one line of <state>/insight-moves.jsonl. With no state folder every write answers 409. Nothing is sent outward. */
15
+ const guard = require('./pm-guard.js');
16
+ const MV = require('./insight-moves.js');
17
+ const { repoScript } = require('./repo-script.js');
18
+ const { recordsDirFor } = require('./records-dir.js');
19
+
20
+ const text = (v) => (typeof v === 'string' ? v : '');
21
+ const bad = (status, error) => ({ status, body: { ok: false, error } });
22
+ const records = () => require(repoScript('records/index.js'));
23
+ const UI = () => require(repoScript('trust/ledger.js')).actorFrom({ ui: true });
24
+ const NO_STATE = 'This repository has no PMOS state folder (pmos/state, state or .pmos). Nothing is saved until the folder exists.';
25
+ const dirOf = (ctx, w) => { try { return ctx.stateDirFor ? ctx.stateDirFor(w) : null; } catch { return null; } };
26
+
27
+ /** The Intelligence model, read the way the page reads it. */
28
+ async function modelOf(req, ctx, ws, board) {
29
+ let out = null;
30
+ const c = Object.assign({}, ctx, { json: (res, obj) => { out = obj; } });
31
+ const q = new URLSearchParams(); if (ws) q.set('ws', ws); if (board) q.set('board', board);
32
+ await require('./routes-insights-premium.js').handle({ method: 'GET', headers: (req && req.headers) || {} }, {}, new URL('http://local/api/insights-premium?' + q.toString()), c);
33
+ return out && out.ok ? out.model : null;
34
+ }
35
+ const movesIn = (m) => { const I = (m && m.insight) || {}; return [I.move].concat((I.more || []).map((x) => x.move)).filter(Boolean); };
36
+
37
+ function write(ctx, w, mv, actor) {
38
+ if (mv.kind === 'date') {
39
+ let e;
40
+ try { e = records().edit(recordsDirFor(ctx, w.id), 'kr-metrics', mv.goal, { by: mv.to }, UI(), 'Moved the target date Claude drafted on Intelligence'); } catch (x) { e = { ok: false, reasons: [String((x && x.message) || x).slice(0, 160)] }; }
41
+ return e.ok ? { undo: { by: mv.from } } : { error: 'The date could not be moved: ' + (e.reasons || []).join('; ') };
42
+ }
43
+ if (mv.kind === 'anchor') {
44
+ const r = require('./initiative-writer.js').setAnchor(w.root, mv.ini, mv.to, { actor });
45
+ return r.ok ? { undo: { from: r.from || '' } } : { error: r.error || 'The anchor could not be set.' };
46
+ }
47
+ if (mv.kind === 'chase') {
48
+ if (!ctx.runtimeDir) return { error: 'This workspace has no outbox, so the comment could not be drafted.' };
49
+ try {
50
+ const e = require(repoScript('outbox.js')).draftOutbox({ channel: 'jira-write', recipient: mv.epic, subject: 'A new date for ' + mv.ini, body: mv.body, origin: 'pm' });
51
+ const entry = { id: 'out-' + require('crypto').randomBytes(6).toString('hex'), ...e };
52
+ require('./outbox-store.js').appendEvent(ctx.runtimeDir, { event: 'queued', ...entry }, new Date());
53
+ return { undo: { entry: entry.id } };
54
+ } catch (x) { return { error: 'The comment could not go to the outbox: ' + String((x && x.message) || x).slice(0, 160) }; }
55
+ }
56
+ return { error: 'There is no such move.' };
57
+ }
58
+
59
+ function unwrite(ctx, w, x, actor, req) {
60
+ const mv = x.move || {}, u = x.undo || {};
61
+ if (mv.kind === 'date') {
62
+ let e;
63
+ try { e = records().edit(recordsDirFor(ctx, w.id), 'kr-metrics', mv.goal, { by: u.by }, UI(), 'Undo of a moved target date'); } catch (y) { e = { ok: false, reasons: [String((y && y.message) || y).slice(0, 160)] }; }
64
+ return e.ok ? {} : { error: 'The date could not be put back: ' + (e.reasons || []).join('; ') };
65
+ }
66
+ if (mv.kind === 'anchor') {
67
+ const r = require('./initiative-writer.js').restoreAnchor(w.root, mv.ini, u.from || '', { actor });
68
+ return r.ok ? {} : { error: r.error || 'The anchor could not be put back.' };
69
+ }
70
+ if (mv.kind === 'chase') {
71
+ const r = require('./routes-outbox.js').discard(req, { id: u.entry }, ctx.runtimeDir);
72
+ return r.status === 200 ? {} : { status: r.status, error: (r.body && r.body.error) === 'a sent entry is a record and is not discarded' ? 'The comment was sent already, so it cannot be taken back.' : 'The comment could not be taken out of the outbox.' };
73
+ }
74
+ return { error: 'There is no such move.' };
75
+ }
76
+
77
+ async function handle(req, res, url, ctx) {
78
+ const send = (r) => { ctx.json(res, r.body, r.status); return true; };
79
+ const what = url.pathname.replace(/^\/api\/insight-moves\/?/, '');
80
+ if (!['apply', 'undo'].includes(what)) return send(bad(404, 'no such insight-moves route'));
81
+ if (req.method !== 'POST') return send(bad(405, 'POST only'));
82
+ const read = await ctx.readJson(req);
83
+ if (!read.ok) return send(bad(400, 'the body is not JSON'));
84
+ const body = read.body || {};
85
+ let w = null;
86
+ try { w = ctx.getWs(text(body.ws) || null); } catch { w = null; }
87
+ if (!w || (body.ws && w.id !== body.ws)) return send(bad(404, 'no such workspace'));
88
+ const sig = text(body.sig);
89
+ if (!/^mv-[0-9a-f]{12}$/.test(sig)) return send(bad(400, 'sig names the move the strip shows'));
90
+ const dir = dirOf(ctx, w);
91
+ if (!dir) return send(bad(409, NO_STATE));
92
+ const at = () => new Date().toISOString();
93
+
94
+ if (what === 'apply') {
95
+ const m = await self.modelOf(req, ctx, w.id, text(body.board) || null);
96
+ if (!m) return send(bad(500, 'Intelligence could not be read, so nothing was changed.'));
97
+ const mv = movesIn(m).find((x) => x.sig === sig);
98
+ if (!mv) return send(bad(409, 'That move is no longer drafted. Nothing changed.'));
99
+ if (mv.done) return send(bad(409, 'You made this move already.'));
100
+ const g = mv.kind === 'anchor' ? guard.requirePmPress(req, body, { act: 'anchor' }) : guard.requirePagePress(req, body);
101
+ if (!g.ok) return send(bad(g.status, g.error));
102
+ const r = write(ctx, w, mv, g.actor);
103
+ if (r.error) return send(bad(400, r.error));
104
+ const move = { kind: mv.kind, goal: mv.goal, ...(mv.ini ? { ini: mv.ini } : {}), ...(mv.to ? { to: mv.to } : {}), ...(mv.epic ? { epic: mv.epic } : {}) };
105
+ MV.append(dir, g.actor, { kind: 'apply', sig, move, undo: r.undo }, at());
106
+ return send({ status: 200, body: { ok: true, sig, kind: mv.kind, said: mv.said } });
107
+ }
108
+ // undo
109
+ const x = MV.read(dir).get(sig);
110
+ if (!x || x.state !== 'applied') return send(bad(409, 'There is nothing to undo.'));
111
+ const g = x.move.kind === 'anchor' ? guard.requirePmPress(req, body, { act: 'anchor' }) : guard.requirePagePress(req, body);
112
+ if (!g.ok) return send(bad(g.status, g.error));
113
+ const r = unwrite(ctx, w, x, g.actor, req);
114
+ if (r.error) return send(bad(r.status || 400, r.error));
115
+ MV.append(dir, g.actor, { kind: 'undo', sig }, at());
116
+ return send({ status: 200, body: { ok: true, sig } });
117
+ }
118
+
119
+ const self = module.exports = { prefixes: ['/api/insight-moves'], handle, modelOf }; // modelOf is read through `self`, so a test can stand in for it
@@ -9,7 +9,8 @@
9
9
  * briefing-premium-reports adds the board's saved dashboards (lib/premium-dashboards.js list) and the workspace's GET /api/report-setups answer
10
10
  * (setups, findings, asks). That GET is the console's own read: like the console, it may move old dashboard schedules into recurring reports once
11
11
  * per repository. insights-one-list adds the pinned dashboard (lib/premium-dashboards.js pinned) and the opening sentence of each report file, read here
12
- * from the workspace's repository. This route itself writes nothing. The page's presses post to /api/report-setups/* and /api/premium-dashboards/save. */
12
+ * from the workspace's repository. Feedback batch 16 item 1 gives each ✦ strip finding its drafted move (lib/insight-moves.js draftAll; the ✓ is
13
+ * lib/routes-insight-moves.js). This route itself writes nothing. The page's presses post to /api/report-setups/* and /api/premium-dashboards/save. */
13
14
  const Insights = require('./insights-premium.js');
14
15
  const boards = require('./routes-boards.js');
15
16
  const strategy = require('./routes-c3-strategy.js');
@@ -96,6 +97,14 @@ module.exports = {
96
97
  outcomes, reports: reportsOk ? rp.body.reports || [] : [], reportsOk, missing, saved, mine,
97
98
  setups: setupsOk ? su.body : null, pinned, leads, archived, initiatives, goalMeta, ins, budgets,
98
99
  });
100
+ // batch 16 item 1: each ✦ strip finding about a goal that is behind carries one drafted move (lib/insight-moves.js), done ones marked
101
+ if (pick) {
102
+ try {
103
+ const root = require('path').resolve(ctx.getWs(pick.ws).root), A = require('./initiative-rows.js').anchorsOf(root);
104
+ const dir = ctx.stateDirFor ? ctx.stateDirFor(ctx.getWs(pick.ws)) : null;
105
+ require('./insight-moves.js').draftAll(model, { initiatives: initiatives || [], today: model.today, anchorOk: (t) => A.resolve(t).status === 'resolved', ledger: dir ? require('./insight-moves.js').read(dir) : new Map() });
106
+ } catch { /* no move is drafted: the strip says the finding without a ✓ */ }
107
+ }
99
108
  ctx.json(res, { ok: true, state: 'ready', model, as_of: Date.now() });
100
109
  return true;
101
110
  } catch (e) { return fail((e && e.message) || e); }
@@ -8,6 +8,7 @@
8
8
  * POST /api/metric-drafts/keep { ws, scope, id, row } → { ok, rid } ✓ one row: the record and, when now is known, one reading
9
9
  * POST /api/metric-drafts/keep-all { ws, scope, id } → { ok, kept: n, failed } ✓ every open row
10
10
  * POST /api/metric-drafts/drop { ws, scope, id, row } → { ok } ✕
11
+ * POST /api/metric-drafts/edit { ws, scope, id, row, name?, target?, source? } → { ok, row } the inline edit of an open row (batch 16 item 1)
11
12
  * POST /api/metric-drafts/undo { ws, scope, id, row } → { ok } kept → open (its record edited { retired: true }); dropped → open
12
13
  * POST /api/metric-drafts/start { ws, scope, id } → { ok, run } Draft again
13
14
  * POST /api/metric-drafts/stop { ws, scope, id } → { ok } ■ Stop: the run ends; what it filed stays a draft
@@ -63,7 +64,7 @@ async function handle(req, res, url, ctx) {
63
64
  if (!sid) return send(bad(400, 'id names the program or the initiative'));
64
65
  return send({ status: 200, body: { ok: true, ...viewFor(ctx, w, scope, sid) } });
65
66
  }
66
- if (!['keep', 'keep-all', 'drop', 'undo', 'start', 'stop'].includes(what)) return send(bad(404, 'no such metric-drafts route'));
67
+ if (!['keep', 'keep-all', 'drop', 'undo', 'start', 'stop', 'edit'].includes(what)) return send(bad(404, 'no such metric-drafts route'));
67
68
  if (req.method !== 'POST') return send(bad(405, 'POST only'));
68
69
  if (req.headers && req.headers['x-pmos-session']) return send(bad(403, 'Only the PM keeps, drops or starts a draft, from the page. A run files drafts with pmos metrics draft.'));
69
70
  const read = await ctx.readJson(req);
@@ -122,6 +123,14 @@ async function handle(req, res, url, ctx) {
122
123
  const r = keepOne(row);
123
124
  return send(r.rid ? { status: 200, body: { ok: true, rid: r.rid } } : bad(400, r.error));
124
125
  }
126
+ if (what === 'edit') {
127
+ if (row.state !== 'open') return send(bad(409, row.state === 'kept' ? 'You kept it. Undo it first, then edit.' : 'You dropped it. Undo first.'));
128
+ const pick = {}; for (const k of ['name', 'target', 'source']) if (body[k] !== undefined) pick[k] = body[k];
129
+ const e = MD.editOf(row, pick);
130
+ if (e.error) return send(bad(400, e.error));
131
+ if (Object.keys(e.set).length) MD.append(dir, g.actor, { kind: 'edit', scope, id, row: row.id, set: e.set }, at());
132
+ return send({ status: 200, body: { ok: true, row: { ...row, ...e.set }, changed: Object.keys(e.set).length > 0 } });
133
+ }
125
134
  if (what === 'drop') {
126
135
  if (row.state !== 'open') return send(bad(409, row.state === 'kept' ? 'You kept it. Undo it first.' : 'You dropped it already.'));
127
136
  MD.append(dir, g.actor, { kind: 'drop', scope, id, row: row.id }, at());
@@ -0,0 +1,26 @@
1
+ 'use strict';
2
+ /* routes-page-opens.js — POST /api/page-opens { ws, page, view } → { ok, wrote } (feedback batch 16 item 1). Intelligence posts it once per page
3
+ * load, with the view on screen; lib/page-opens.js keeps one line per page, view and day in the runtime folder (local only, never the repository)
4
+ * and lib/intel-report.js proposalsOf reads it for "You open this every week". A call from an agent session is not an open by the PM: 403.
5
+ * The page's own Origin and launch nonce are checked as for any page write (pm-guard requirePagePress). */
6
+ const guard = require('./pm-guard.js');
7
+ const PO = require('./page-opens.js');
8
+
9
+ async function handle(req, res, url, ctx) {
10
+ const send = (status, body) => { ctx.json(res, body, status); return true; };
11
+ if (url.pathname !== '/api/page-opens') return false;
12
+ if (req.method !== 'POST') return send(405, { ok: false, error: 'POST only' });
13
+ if (req.headers && req.headers['x-pmos-session']) return send(403, { ok: false, error: 'An agent session does not open pages. Only the PM\'s own opens are recorded.' });
14
+ const read = await ctx.readJson(req);
15
+ if (!read.ok) return send(400, { ok: false, error: 'the body is not JSON' });
16
+ const body = read.body || {};
17
+ const g = guard.requirePagePress(req, body);
18
+ if (!g.ok) return send(g.status, { ok: false, error: g.error });
19
+ let w = null;
20
+ try { w = ctx.getWs(typeof body.ws === 'string' ? body.ws : null); } catch { w = null; }
21
+ if (!w || w.id !== body.ws) return send(404, { ok: false, error: 'no such workspace' });
22
+ const r = PO.record(ctx.runtimeDir || null, { ws: w.id, page: body.page, view: body.view }, new Date().toISOString());
23
+ return r.ok ? send(200, { ok: true, wrote: r.wrote }) : send(r.error.startsWith('This workspace') ? 409 : 400, { ok: false, error: r.error });
24
+ }
25
+
26
+ module.exports = { prefixes: ['/api/page-opens'], handle };
@@ -290,6 +290,11 @@ function exportAnswer(ctx, res, w, url) {
290
290
  return { status: 200, file: out };
291
291
  }
292
292
 
293
+ /** The view the PM opens every week on Intelligence (feedback batch 16 item 1; lib/page-opens.js, local only), or null. */
294
+ function weeklyOpen(ctx, ws) {
295
+ try { const PO = require('./page-opens.js'); return PO.weeklyOf(PO.readLines(ctx.runtimeDir || null), { ws, page: 'intelligence', now: Date.now() }); } catch { return null; }
296
+ }
297
+
293
298
  async function handle(req, res, url, ctx) {
294
299
  const p = url.pathname;
295
300
  const send = (r) => { ctx.json(res, r.body, r.status); return true; };
@@ -315,7 +320,7 @@ async function handle(req, res, url, ctx) {
315
320
  if (story.answer) S.answer = story.answer;
316
321
  const defaults = IR.defaultsOf(findings, scope, S.name);
317
322
  const preview = IR.documentOf(m, { id: 'preview', name: S.name, audience: defaults.audience, output: defaults.output, source: IR.sourceOf(scope), storyline: story }, { slot: m.today, issue: 1 });
318
- return send({ status: 200, body: { ok: true, storyline: S, defaults, checks: IR.storyChecks(preview), proposals: IR.proposalsOf(m, { findings, dismissed: [...st.stripDismissed] }), as_of: m.today } });
323
+ return send({ status: 200, body: { ok: true, storyline: S, defaults, checks: IR.storyChecks(preview), proposals: IR.proposalsOf(m, { findings, dismissed: [...st.stripDismissed], weekly: weeklyOpen(ctx, w.id), covered: [...st.setups.values()].map((x) => IR.scopeOf(x.source)).filter(Boolean) }), as_of: m.today } });
319
324
  }
320
325
  if (!docPost && (isDocs || isExport || (sub === '' && req.method === 'GET'))) {
321
326
  if (req.method !== 'GET') return send(bad(405, 'GET only'));
@@ -70,6 +70,12 @@ const DEFS = Object.freeze({
70
70
  'upd.apply': one('updates', 'computer', ['ask', 'idle'], 'ask'),
71
71
  'upd.kits': one('updates', 'computer', ['all', 'each'], 'all'),
72
72
  'upd.channel': one('updates', 'computer', ['stable', 'early'], 'stable'),
73
+ // Settings > Adler (feedback batch 16 item 2, canvas AdM5): how much of Claude's face shows, whether he moves, whether he celebrates, and
74
+ // whether PMOS opens on him asleep after 22:00. pm/cozy-adler.js reads them.
75
+ 'adler.amount': one('adler', 'computer', ['full', 'face', 'off'], 'full'),
76
+ 'adler.motion': one('adler', 'computer', ['system', 'still'], 'system'),
77
+ 'adler.celebrate': one('adler', 'computer', ['real', 'never'], 'real'),
78
+ 'adler.quiet': one('adler', 'computer', ['22', 'never'], '22'),
73
79
  });
74
80
 
75
81
  /* The environment variables that win over a setting, here or in a setting's own store. `key` names the setting the page