create-pmos 0.433.0 → 0.435.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 (89) hide show
  1. package/package.json +25 -25
  2. package/payload/KIT-VERSION +1 -1
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/state/discoveries.md +1 -1
  6. package/workspace/briefing-premium-insights-test.js +63 -58
  7. package/workspace/changelog.json +24 -0
  8. package/workspace/fixtures/ready-reports.js +145 -0
  9. package/workspace/guide/index.md +2 -0
  10. package/workspace/guide/metric-drafts.md +21 -1
  11. package/workspace/guide/ready-made-dashboards.md +62 -0
  12. package/workspace/guide/your-impact.md +58 -0
  13. package/workspace/impact-screens-test.js +149 -0
  14. package/workspace/intel-report-ui-test.js +1 -1
  15. package/workspace/intelligence-gaps-ui-test.js +13 -9
  16. package/workspace/lib/board-premium.js +1 -1
  17. package/workspace/lib/engine/outbox.js +1 -1
  18. package/workspace/lib/engine/records/index.js +11 -3
  19. package/workspace/lib/goal-status.js +199 -0
  20. package/workspace/lib/goal-watch.js +71 -0
  21. package/workspace/lib/headless.js +24 -2
  22. package/workspace/lib/impact-cli.js +72 -0
  23. package/workspace/lib/impact-runs.js +114 -0
  24. package/workspace/lib/impact.js +195 -0
  25. package/workspace/lib/insights-premium.js +43 -4
  26. package/workspace/lib/intel-report.js +36 -5
  27. package/workspace/lib/metric-draft-runs.js +33 -10
  28. package/workspace/lib/metric-drafts.js +118 -15
  29. package/workspace/lib/metric-read-runs.js +132 -0
  30. package/workspace/lib/metric-reads.js +129 -0
  31. package/workspace/lib/metrics-cli.js +100 -5
  32. package/workspace/lib/pmos-verbs.js +4 -1
  33. package/workspace/lib/ready-reports.js +616 -0
  34. package/workspace/lib/report-dashboards.js +5 -0
  35. package/workspace/lib/report-setups.js +16 -7
  36. package/workspace/lib/route-modules.js +4 -0
  37. package/workspace/lib/routes-board-premium.js +5 -0
  38. package/workspace/lib/routes-boards.js +1 -1
  39. package/workspace/lib/routes-goal-status.js +111 -0
  40. package/workspace/lib/routes-impact-views.js +58 -0
  41. package/workspace/lib/routes-impact.js +91 -0
  42. package/workspace/lib/routes-insights-premium.js +20 -0
  43. package/workspace/lib/routes-metric-drafts.js +55 -4
  44. package/workspace/lib/routes-ready-reports.js +455 -0
  45. package/workspace/lib/routes-records.js +2 -0
  46. package/workspace/lib/routes-report-setups.js +4 -3
  47. package/workspace/lib/settings-store.js +3 -0
  48. package/workspace/okr-goals-ui-test.js +175 -0
  49. package/workspace/package-lock.json +2 -2
  50. package/workspace/package.json +1 -1
  51. package/workspace/program-charter-test.js +11 -7
  52. package/workspace/program-panel-test.js +1 -1
  53. package/workspace/public/pm/bd-ini-panel.js +33 -8
  54. package/workspace/public/pm/bd-prog-panel.js +58 -10
  55. package/workspace/public/pm/cozy-adler.css +5 -0
  56. package/workspace/public/pm/cozy-adler.js +17 -9
  57. package/workspace/public/pm/cozy-insights.css +84 -0
  58. package/workspace/public/pm/cozy-settings.js +11 -1
  59. package/workspace/public/pm/cozy-viewer.js +2 -2
  60. package/workspace/public/pm/cozy-vw-rp.css +13 -0
  61. package/workspace/public/pm/dash-view.css +111 -0
  62. package/workspace/public/pm/dash-view.js +261 -0
  63. package/workspace/public/pm/home-app.js +87 -8
  64. package/workspace/public/pm/home-data.js +3 -2
  65. package/workspace/public/pm/home-impact.css +16 -0
  66. package/workspace/public/pm/home-impact.js +72 -0
  67. package/workspace/public/pm/home-ini.js +19 -1
  68. package/workspace/public/pm/home-today.js +4 -2
  69. package/workspace/public/pm/impact.css +37 -0
  70. package/workspace/public/pm/impact.js +201 -0
  71. package/workspace/public/pm/okr-list.js +249 -0
  72. package/workspace/public/pm/premium-insights.js +232 -240
  73. package/workspace/public/pm/premium-report-read.js +36 -5
  74. package/workspace/public/pm/premium-vw-mtg.js +4 -1
  75. package/workspace/public/pm/ready-lib.css +29 -0
  76. package/workspace/public/pm/ready-lib.js +62 -0
  77. package/workspace/public/premium-intelligence.html +3 -2
  78. package/workspace/public/premium.html +1 -0
  79. package/workspace/ready-dash-ui-test.js +227 -0
  80. package/workspace/server.js +58 -2
  81. package/workspace/skills/impact-detect.skill +46 -0
  82. package/workspace/skills/metric-read.skill +32 -0
  83. package/workspace/test-lists/batch17-ready-reports.json +9 -0
  84. package/workspace/test-lists/goal-watch.json +9 -0
  85. package/workspace/test-lists/impact-screens.json +5 -0
  86. package/workspace/test-lists/impact-ui.json +9 -0
  87. package/workspace/test-lists/impact.json +9 -0
  88. package/workspace/test-lists/okr-goals-ui.json +5 -0
  89. package/workspace/test-lists/ready-reports-ui.json +6 -0
@@ -0,0 +1,455 @@
1
+ 'use strict';
2
+ /* routes-ready-reports.js — the ready-made dashboard and reports of every program, product and initiative (feedback batch 17 item 1, design A+;
3
+ * the engines are lib/ready-reports.js, the documents lib/intel-report.js documentOf through lib/routes-report-setups.js draftIntelligence).
4
+ *
5
+ * GET /api/ready-reports/dashboard?ws&scope&from=read|act → { ok, dashboard } the Dashboard view (PbA1, PbA2, PbA3, PbA7, PbS1, PbS2, PbG1–G10).
6
+ * scope: product | program:<id> | initiative:<id>. `from` says why the PM came: read (Intelligence, a report, a
7
+ * notification) opens on the Dashboard, act (a Board row, a Home task) on Work. The page keeps the PM's last choice
8
+ * GET /api/ready-reports/library?ws → { ok, lead, groups, yours, overlap } ⋯ › Reports and dashboards (PbA6, PbG4)
9
+ * GET /api/ready-reports/cut?ws&path&cut=sponsors|team → { ok, cut, markdown } the two cuts of one draft (PbG5), the same numbers
10
+ * POST /api/ready-reports/switch { ws, scope, kind, on } one switch per report; scope 'initiative:*' is every initiative's
11
+ * POST /api/ready-reports/picks { ws } ✓ on the lead card: keep Claude's picks (schedules the weekly reports it picked)
12
+ * POST /api/ready-reports/trust { ws, scope, kind, on } Send by itself (PbG6); on: false from the offer card is ✕ and it is not offered again
13
+ * POST /api/ready-reports/hold { ws, scope, kind, act } a held report (PbG2): send-note writes the stale source's note on the draft; wait; skip
14
+ * POST /api/ready-reports/overlap { ws } ✓ on "Lee would get 3 updates": the wider report carries the narrower (PbG4)
15
+ * POST /api/ready-reports/promise { ws, scope, act, date } keep or drop the drafted promise date (PbA5)
16
+ * tick(ctx, now) drafts each weekly that is due (skipped in a week where nothing moved), each checkpoint and Did it work? at its
17
+ * moment, and a heads-up for a broken health budget or a critical slip. server.js runs it after the setups tick.
18
+ *
19
+ * SEND IS ISSUE. PMOS sends nothing outward: Send on a report row is the existing PM-only Issue press, POST /api/report/issue { ws, cadence, slot, sha },
20
+ * so every row with a document carries cadence, slot, sha and path. "Send by itself" is the PM's standing switch; it marks a calm week's draft ready to
21
+ * go with `auto: true` on its row, and the Issue press stays the PM's (issues are PM-only, R25).
22
+ * Every POST passes pm-guard requirePagePress. With no state folder the reads answer and the writes answer 409. */
23
+ const fs = require('fs');
24
+ const path = require('path');
25
+ const guard = require('./pm-guard.js');
26
+ const RR = require('./ready-reports.js');
27
+ const RS = require('./report-setups.js');
28
+ const RN = require('./report-needs.js');
29
+ const IR = require('./intel-report.js');
30
+ const issues = require('./issues.js');
31
+ const logic = require('./schedule-logic.js');
32
+
33
+ const text = (v) => (typeof v === 'string' ? v : '');
34
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
35
+ const pad = (n) => String(n).padStart(2, '0');
36
+ const localIso = (d) => d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate());
37
+ const POSTS = ['switch', 'picks', 'trust', 'hold', 'overlap', 'promise'];
38
+
39
+ /** GET `pathAndQuery` from a route module's own handler (as lib/routes-insights-premium.js does). → { status, body } */
40
+ async function via(mod, pathAndQuery, req, ctx) {
41
+ let out = { status: 500, body: null };
42
+ const c = Object.assign({}, ctx, { json: (res, obj, code) => { out = { status: code || 200, body: obj }; } });
43
+ const handled = await mod.handle({ method: 'GET', headers: (req && req.headers) || {} }, {}, new URL('http://local' + pathAndQuery), c);
44
+ return handled === false ? { status: 404, body: null } : out;
45
+ }
46
+ const qs = (o) => '?' + Object.entries(o).filter(([, v]) => v != null && v !== '').map(([k, v]) => k + '=' + encodeURIComponent(v)).join('&');
47
+ function wsOf(ctx, id) { let w = null; try { w = ctx.getWs(id || null); } catch { w = null; } return w && (!id || w.id === id) ? w : null; }
48
+ const stateDir = (w) => RS.stateDir(w.root);
49
+ const hasState = (w) => { try { return fs.statSync(stateDir(w)).isDirectory(); } catch { return false; } };
50
+
51
+ // ── reading one workspace ────────────────────────────────────────────────────────────────────────────────────────────────────
52
+ /** The board of a workspace, its initiatives (with stage, status and dates) and its tasks. → { board, rows, items } | null */
53
+ async function boardOf(req, ctx, ws) {
54
+ const B = require('./routes-boards.js');
55
+ const list = await via(B, '/api/boards', req, ctx).catch(() => ({ body: null }));
56
+ const board = ((list.body && list.body.boards) || []).find((b) => b.ws === ws) || null;
57
+ if (!board) return null;
58
+ const it = await via(B, '/api/boards/items' + qs({ ws, board: board.id }), req, ctx).catch(() => ({ body: null }));
59
+ const ok = it.body && it.body.ok !== false;
60
+ return { board, rows: ok ? (it.body.initiatives || []).map((r) => ({ ...r, ws, product: { tag: tagOf(board.name), name: board.name } })) : [], items: ok ? it.body.items || [] : [], ok };
61
+ }
62
+ const tagOf = (name) => String(name || '?').split(/[\s-]+/).filter(Boolean).slice(0, 2).map((s) => s[0].toUpperCase()).join('') || '?';
63
+ function jiraOf(w, ids) {
64
+ const out = {};
65
+ let JS; try { JS = require('./jira-status.js'); } catch { return out; }
66
+ for (const id of ids) { try { const s = JS.readSnapshot(w.root, id); if (s) out[id] = { at: s.fetchedAt, tickets: [...s.tickets.values()].map((t) => ({ category: t.category, resolved: t.resolved || null })) }; } catch { /* no snapshot */ } }
67
+ return out;
68
+ }
69
+ /** The open proposals of the initiatives, as the Needs you block takes them: the slips (dates) first, one decision each. */
70
+ /** The initiatives with an open filed proposal, from one read of proposals.jsonl (no board frame per initiative: the Library lists hundreds). */
71
+ function openInis(ctx, w) {
72
+ try {
73
+ const PR = require('./proposals.js');
74
+ const dir = ctx.stateDirFor ? ctx.stateDirFor(w) : RS.stateDir(w.root);
75
+ const F = PR.read(dir), kept = PR.keptIds(F), out = new Set();
76
+ for (const p of F.props.values()) if (p && !kept.has(p.id) && !F.drops.has(PR.sigOf(p))) out.add(p.ini);
77
+ return out;
78
+ } catch { return new Set(); }
79
+ }
80
+ const MAX_VIEWS = 5; // the Needs you block shows one decision: at most 5 initiatives' proposal views are built for it
81
+ function needsOf(ctx, w, boardId, ids) {
82
+ const out = [];
83
+ let RP; try { RP = require('./routes-proposals.js'); } catch { return out; }
84
+ const open = ids.length > 1 ? openInis(ctx, w) : null;
85
+ for (const ini of ids.filter((x) => !open || open.has(x)).slice(0, MAX_VIEWS)) {
86
+ let v = null; try { v = RP.viewFor(ctx, w, boardId, ini); } catch { v = null; }
87
+ if (!v || !Array.isArray(v.groups)) continue;
88
+ const ps = v.groups.flatMap((g) => g.props || []).sort((a, b) => (a.group === 'dates' ? -1 : 0) - (b.group === 'dates' ? -1 : 0));
89
+ const p = ps[0]; if (!p) continue;
90
+ const first = (p.items || [])[0] || null;
91
+ out.push({ id: p.id, q: String(p.title || (first && first.title) || 'A change Claude proposes').slice(0, 160), sub: String(p.why || '').slice(0, 200), pick: first && first.to ? '✦ My pick: ' + String(first.to).slice(0, 120) : '', from: ini, ini, board: boardId, group: p.group,
92
+ keep: { ids: [p.id] }, drop: { sig: p.sig } });
93
+ }
94
+ return out.sort((a, b) => (a.group === 'dates' ? -1 : 0) - (b.group === 'dates' ? -1 : 0));
95
+ }
96
+ /** The product's weekly update that Home already keeps (lib/routes-home-desk.js): who it goes to and the weeks it was sent. One weekly, not two. */
97
+ async function deskOf(req, ctx, w) {
98
+ let H; try { H = require('./routes-home-desk.js'); } catch { return null; }
99
+ const r = await via(H, '/api/home-desk' + qs({ ws: w.id }), req, ctx).catch(() => ({ body: null }));
100
+ const P = r.body && r.body.product;
101
+ return P ? { recipients: Array.isArray(P.recipients) ? P.recipients : [], sent: Array.isArray(P.sent) ? P.sent : [] } : null;
102
+ }
103
+ async function programsOf(req, ctx) {
104
+ let P; try { P = require('./routes-programs.js'); } catch { return []; }
105
+ const r = await via(P, '/api/programs', req, ctx).catch(() => ({ body: null }));
106
+ return (r.body && r.body.programs) || [];
107
+ }
108
+
109
+ /** Everything the dashboard of one scope reads. → { f, w, model, setups, st } | { error, status } */
110
+ /** A memo for one tick or one request: the board, the Intelligence model and the programs are read once per workspace, not once per scope. */
111
+ const memo = (cache, key, fn) => { if (!cache) return fn(); if (!cache.has(key)) cache.set(key, fn()); return cache.get(key); };
112
+ async function factsFor(req, ctx, w, scope, { from, now = Date.now(), cache = null, lite = false } = {}) {
113
+ const P = RR.parseScope(scope);
114
+ if (!P) return { status: 400, error: 'scope is product, program:<id> or initiative:<id>' };
115
+ const today = localIso(new Date(now));
116
+ const B = await memo(cache, 'board:' + w.id, () => boardOf(req, ctx, w.id));
117
+ const SR = require('./routes-report-setups.js');
118
+ let rows = B ? B.rows : [], items = B ? B.items : [], program = null, products = [];
119
+ let model = await memo(cache, 'intel:' + w.id, () => SR.intelModel(req, ctx, w.id, B ? B.board.id : null));
120
+ const jira = {};
121
+ if (P.level === 'program') {
122
+ program = (await memo(cache, 'programs', () => programsOf(req, ctx))).find((p) => p.id === P.id) || null;
123
+ if (!program) return { status: 404, error: 'no such program' };
124
+ const wss = [...new Set((program.members || []).map((m) => m.ws).concat(program.home ? [program.home] : []))];
125
+ rows = []; items = [];
126
+ const goals = [];
127
+ for (const ws of wss) {
128
+ const ow = wsOf(ctx, ws);
129
+ const OB = ow ? await memo(cache, 'board:' + ws, () => boardOf(req, ctx, ws)) : null;
130
+ const mine = (program.members || []).filter((m) => m.ws === ws).map((m) => m.initiative);
131
+ const om = ow ? (ws === w.id ? model : await memo(cache, 'intel:' + ws, () => SR.intelModel(req, ctx, ws, OB ? OB.board.id : null))) : null;
132
+ const name = OB ? OB.board.name : ws;
133
+ const read = !!(ow && OB && OB.ok && om);
134
+ products.push({ ws, name, read, why: read ? '' : !ow ? 'It is not connected to this workspace' : !OB ? 'It has no board yet' : 'Its goals could not be read', asked: '' });
135
+ if (OB) { rows.push(...OB.rows.filter((r) => mine.includes(r.id))); items.push(...OB.items.filter((x) => mine.includes(x.ini))); Object.assign(jira, jiraOf(ow, mine)); }
136
+ if (om) for (const g of om.goals || []) if (!goals.some((x) => x.id === g.id)) goals.push({ ...g, product: { tag: tagOf(name), name } });
137
+ }
138
+ model = Object.assign({}, model || {}, { goals: goals.length ? goals : (model && model.goals) || [] });
139
+ } else if (B) {
140
+ const ids = P.level === 'initiative' ? [P.id] : rows.map((r) => r.id);
141
+ Object.assign(jira, jiraOf(w, ids));
142
+ }
143
+ if (P.level === 'initiative' && !rows.some((r) => r.id === P.id)) return { status: 404, error: 'no such initiative on this board' };
144
+ if (model) {
145
+ const progs = P.level === 'program' ? [program] : [];
146
+ model = Object.assign({}, model, { members: Object.fromEntries(progs.map((p) => [p.id, (p.members || []).map((m) => m.initiative)])),
147
+ names: Object.assign({}, ...rows.map((r) => ({ ['initiative:' + r.id]: r.title || r.id })), ...progs.map((p) => ({ ['program:' + p.id]: p.title || p.id }))) });
148
+ }
149
+ const row = P.level === 'initiative' ? rows.find((r) => r.id === P.id) : null;
150
+ const name = P.level === 'initiative' ? (row.title || row.id) : P.level === 'program' ? program.title || program.id : (B ? B.board.name : w.id);
151
+ const st = hasState(w) ? RR.stateOf(stateDir(w)) : RR.fold([]);
152
+ const rst = RS.stateOf(w.root);
153
+ const setups = [...rst.setups.values()];
154
+ const inScope = P.level === 'initiative' ? [row] : rows;
155
+ const needs = B && !lite ? needsOf(ctx, w, B.board.id, inScope.map((r) => r.id)) : []; // lite: the tick reads the decisions only for a weekly that is due
156
+ // a source is stale when Jira has not been read for two days for work in Build or Deliver (PbG2)
157
+ let stale = null;
158
+ for (const r of inScope) {
159
+ const J = jira[r.id], i = require('./board-premium.js').stepIndex(r.stage, r.cat);
160
+ if (!J || !J.at || (i !== 4 && i !== 5)) continue;
161
+ const age = now - Date.parse(J.at);
162
+ if (Number.isFinite(age) && age > RR.STALE_MS && (!stale || Date.parse(J.at) < Date.parse(stale.since))) stale = { source: 'Jira', since: J.at, why: 'Jira has not been read since then' };
163
+ }
164
+ const checklist = row ? items.filter((x) => x && x.ini === row.id && x.kind !== 'jira').map((x) => ({ text: x.title, done: String(x.status || '').toLowerCase() === 'done', who: x.owner || '', when: x.end || '' })) : [];
165
+ const desk = P.level === 'product' ? await deskOf(req, ctx, w) : null;
166
+ const f = { desk, scope, from, now, today, name, sub: P.level === 'initiative' ? [B && B.board.name, row.stage].filter(Boolean).join(' · ') : P.level === 'program' ? 'Program' : 'Product',
167
+ intel: model, rows, program, jiraOf: jira, checklist, needs, products, stale, kept: st.promises.get(scope) || null };
168
+ return { f, w, model, setups, st, rst, B, P, row, rows, program };
169
+ }
170
+
171
+ /** The Reports block's rows of one scope, with their documents. */
172
+ function reportRows(w, X) {
173
+ const docsBy = new Map();
174
+ const R = RN.reportsOf(w.root).reports || [];
175
+ const abs = path.resolve(w.root);
176
+ const docsOf = (id) => {
177
+ if (docsBy.has(id)) return docsBy.get(id);
178
+ const setup = X.setups.find((s) => s.id === id);
179
+ const list = R.filter((x) => x.cadence === id).sort((a, b) => (a.slot < b.slot ? -1 : 1)).map((x) => {
180
+ let sha = null; try { sha = issues.blobSha(fs.readFileSync(path.join(abs, x.path))); } catch { sha = null; }
181
+ const d = setup ? setup.drafted.find((y) => y.slot === x.slot) : null;
182
+ let md = ''; try { md = fs.readFileSync(path.join(abs, x.path), 'utf8'); } catch { md = ''; }
183
+ return { slot: x.slot, path: x.path, issued: x.issued, sha, draftSha: d ? d.sha || null : null, auto: X.st.trust.get(RR.keyOf(setup.ready.scope, setup.ready.kind)) === true && !x.issued && RR.autoOk(md) };
184
+ });
185
+ docsBy.set(id, list);
186
+ return list;
187
+ };
188
+ const headsUps = [...X.st.headsUps.entries()].filter(([, h]) => h.key === RR.keyOf(X.f.scope, 'heads-up') && h.path).map(([id, h]) => {
189
+ const setup = X.setups.find((s) => s.ready && s.ready.scope === X.f.scope && s.ready.kind === 'heads-up');
190
+ const doc = setup ? docsOf(setup.id).find((d) => d.slot === h.slot) : null;
191
+ return doc ? { id, title: h.why ? h.why : 'Heads-up', sub: 'Drafted ' + h.slot + ' for the sponsors', audience: setup.audience, channel: 'mail', path: doc.path, cadence: setup.id, slot: doc.slot, sha: doc.sha, issued: !!doc.issued } : null;
192
+ }).filter(Boolean).filter((h) => !h.issued);
193
+ const row = X.row;
194
+ const paused = !!(row && ['on hold', 'cancelled', "won't do"].includes(String(row.status || '').toLowerCase()));
195
+ const picked = !!X.st.picks && X.st.picks.keys.includes(RR.keyOf(X.f.scope, 'weekly'));
196
+ const rows = RR.rowsFor({ scope: X.f.scope, level: X.P.level, st: X.st, setups: X.setups, docsOf, now: X.f.now, stale: X.f.stale, paused, closed: !!(X.program && (X.program.archived || X.program.closed)), picked, headsUps });
197
+ return RR.withDesk(rows, X.f.desk, { now: X.f.now, hasSetup: X.setups.some((s) => s.ready && s.ready.scope === 'product' && s.ready.kind === 'weekly' && s.status === 'active'), off: RR.switchOf(X.st, 'product', 'weekly') === false });
198
+ }
199
+ /** A report the PM already sends by hand, from the report finder's findings: one whose name names the scope. */
200
+ function handOf(rst, name) {
201
+ const n = String(name || '').toLowerCase();
202
+ if (!n) return null;
203
+ const f = [...rst.findings.values()].find((x) => x && x.state === 'open' && x.proposal && x.proposal.audience && (String(x.name || '').toLowerCase().includes(n) || String(x.proposal.name || '').toLowerCase().includes(n)));
204
+ return f ? { name: f.proposal.name || f.name, audience: f.proposal.audience, schedule: f.proposal.schedule || null, n: (f.evidence || []).length } : null;
205
+ }
206
+
207
+ async function dashboardAnswer(req, ctx, w, scope, from) {
208
+ const X = await factsFor(req, ctx, w, scope, { from });
209
+ if (X.error) return { status: X.status, body: { ok: false, error: X.error } };
210
+ X.f.reports = reportRows(w, X);
211
+ const wk = X.setups.find((s) => s.ready && s.ready.scope === scope && s.ready.kind === 'weekly');
212
+ if (wk) {
213
+ const hist = RN.reportsOf(w.root).reports.filter((x) => x.cadence === wk.id && x.issued).sort((a, b) => (a.slot < b.slot ? -1 : 1)).map((x) => ({ sha: x.issued.sha, draftSha: (wk.drafted.find((d) => d.slot === x.slot) || {}).sha || null }));
214
+ const T = RR.trustOf(hist, X.st, RR.keyOf(scope, 'weekly'));
215
+ if (T.offer) X.f.trust = { reportId: wk.id, scope, kind: 'weekly', text: 'You sent the last ' + RR.TRUST_N + ' weekly updates exactly as I drafted them.' };
216
+ }
217
+ if (!X.model) X.f.goalDraft = null;
218
+ else if (!RR.goalsOf(X.f.intel, scope, Date.parse(X.f.today + 'T00:00:00Z'), false).goals.length) X.f.goalDraft = { title: '', sub: '', anchor: scope };
219
+ return { status: 200, body: { ok: true, dashboard: RR.dashboardOf(X.f) } };
220
+ }
221
+
222
+ /** The scopes of a workspace: its product, its programs (the ones whose charter is here) and its live initiatives. */
223
+ async function scopesOf(req, ctx, w, cache = null) {
224
+ const B = await memo(cache, 'board:' + w.id, () => boardOf(req, ctx, w.id));
225
+ const progs = (await memo(cache, 'programs', () => programsOf(req, ctx))).filter((p) => p.home === w.id);
226
+ const live = B ? B.rows.filter((r) => !['done', 'cancelled'].includes(String(r.status || '').toLowerCase())) : [];
227
+ return { B, progs, list: [{ scope: 'product', level: 'product', name: B ? B.board.name : w.id }].concat(progs.map((p) => ({ scope: 'program:' + p.id, level: 'program', name: p.title || p.id })), live.map((r) => ({ scope: 'initiative:' + r.id, level: 'initiative', name: r.title || r.id }))) };
228
+ }
229
+ async function libraryAnswer(req, ctx, w) {
230
+ const S = await scopesOf(req, ctx, w);
231
+ const st = hasState(w) ? RR.stateOf(stateDir(w)) : RR.fold([]);
232
+ const rst = RS.stateOf(w.root);
233
+ const setups = [...rst.setups.values()];
234
+ const live = new Set(S.list.filter((s) => s.level === 'initiative').map((s) => s.scope.slice(11)));
235
+ const jira = S.B ? jiraOf(w, S.B.rows.filter((r) => live.has(r.id)).map((r) => r.id)) : {};
236
+ const open = openInis(ctx, w);
237
+ const desk = await deskOf(req, ctx, w);
238
+ const scopes = S.list.map((s) => {
239
+ const hand = s.level === 'product' && desk && (desk.recipients.length || desk.sent.length) ? { name: 'Weekly update', audience: desk.recipients.join(', '), n: desk.sent.length, desk: true } : handOf(rst, s.name);
240
+ const news = [];
241
+ if (s.level === 'initiative' && S.B) {
242
+ const id = s.scope.slice(11), r = S.B.rows.find((x) => x.id === id);
243
+ if (open.has(id)) news.push('a decision');
244
+ const F = RR.forecastOf(jira[id], localIso(new Date()), r && r.end);
245
+ if (F && (F.dot === 'behind' || F.dot === 'risk')) news.push('a slip');
246
+ }
247
+ return { ...s, hand, news, ...(s.level === 'product' ? { quarterEnd: RR.quarterEndOf(localIso(new Date())) } : {}) };
248
+ });
249
+ const L = RR.libraryOf({ scopes, st, setups, yours: setups.filter((s) => !s.ready).map((s) => ({ id: s.id, name: s.name, sub: IR.isIntelligence(s.source) ? 'Made from Intelligence · ' + RS.scheduleLabel(s.schedule) : RS.scheduleLabel(s.schedule) })) });
250
+ const on = setups.filter((s) => s.ready && s.ready.kind === 'weekly' && s.status === 'active').map((s) => { const P = RR.parseScope(s.ready.scope); return { key: RR.keyOf(s.ready.scope, 'weekly'), scope: s.ready.scope, level: P ? P.level : 'product', name: s.name, audience: s.audience, day: s.schedule && s.schedule.day }; });
251
+ const O = st.overlap === true ? null : RR.overlapOf(on);
252
+ return { status: 200, body: { ok: true, ...L, overlap: O ? { lead: O.lead, people: O.people } : null } };
253
+ }
254
+
255
+ // ── setting a ready report up ────────────────────────────────────────────────────────────────────────────────────────────────
256
+ const AUDIENCE = { program: 'the sponsors', product: 'the product team', initiative: 'the initiative team' };
257
+ /** The setup of one ready report, made when the PM turns it on (or keeps Claude's picks), or when its moment comes. Paused when switched off. */
258
+ function ensureSetup(w, scope, kind, name, { by, hand, now } = {}) {
259
+ const st = RS.stateOf(w.root);
260
+ const id = RR.setupIdOf(scope, kind);
261
+ const have = st.setups.get(id);
262
+ if (have) { if (have.status === 'paused') RS.resume(w.root, id, { by }); return { ok: true, setup: RS.stateOf(w.root).setups.get(id) }; }
263
+ const P = RR.parseScope(scope);
264
+ const title = RR.kindName(P.level, kind);
265
+ const audience = (hand && hand.audience) || (kind === 'heads-up' ? 'the sponsors' : AUDIENCE[P.level]);
266
+ const proposal = { name: String(name).slice(0, 50) + ' · ' + title, purpose: `${title} of ${String(name).slice(0, 80)}: the answer first, the scorecard, the milestones and what needs a decision. A ready-made report.`, audience,
267
+ source: IR.sourceOf(scope), output: 'pdf', schedule: kind === 'weekly' && hand && hand.schedule && hand.schedule.cadence === 'weekly' ? hand.schedule : { cadence: 'weekly', day: 'Mon', time: '09:00' },
268
+ sources: ['Ready-made · ' + String(name).slice(0, 80)], sections: RS.FRAME.slice(), learned_from: 'A ready-made report (batch 17 item 1).', fixes: [], storyline: {}, ready: { scope, kind } };
269
+ const r = RS.setUp(w.root, proposal, { id, by, wsId: w.id, now });
270
+ if (r.ok && kind !== 'weekly') RS.pause(w.root, id, { by }); // a moment report has no timer: the tick drafts it at its moment
271
+ return r.ok ? { ok: true, setup: RS.stateOf(w.root).setups.get(id) } : r;
272
+ }
273
+
274
+ // ── the handler ──────────────────────────────────────────────────────────────────────────────────────────────────────────────
275
+ async function handle(req, res, url, ctx) {
276
+ const p = url.pathname;
277
+ if (p !== '/api/ready-reports' && !p.startsWith('/api/ready-reports/')) return false;
278
+ const send = (status, body) => { ctx.json(res, body, status); return true; };
279
+ const sub = p.slice('/api/ready-reports/'.length);
280
+ if (req.method === 'GET') {
281
+ const w = wsOf(ctx, url.searchParams.get('ws'));
282
+ if (!w) return send(404, { ok: false, error: 'no such workspace' });
283
+ try {
284
+ if (sub === 'dashboard') { const r = await dashboardAnswer(req, ctx, w, text(url.searchParams.get('scope')), url.searchParams.get('from') === 'act' ? 'act' : 'read'); return send(r.status, r.body); }
285
+ if (sub === 'library') { const r = await libraryAnswer(req, ctx, w); return send(r.status, r.body); }
286
+ if (sub === 'cut') {
287
+ const rel = text(url.searchParams.get('path')), cut = url.searchParams.get('cut') === 'sponsors' ? 'sponsors' : 'team';
288
+ const abs = path.resolve(w.root), file = path.resolve(abs, rel);
289
+ if (!rel || !file.startsWith(abs + path.sep) || !/\/reports\/[^/]+\/\d{4}-\d{2}-\d{2}\.md$/.test(rel.replace(/\\/g, '/'))) return send(400, { ok: false, error: 'path is a report document: <state>/reports/<id>/<slot>.md' });
290
+ let md; try { md = fs.readFileSync(file, 'utf8'); } catch { return send(404, { ok: false, error: 'no such document' }); }
291
+ return send(200, { ok: true, cut, markdown: cut === 'sponsors' ? RR.sponsorsCut(md) : md });
292
+ }
293
+ } catch (e) { return send(500, { ok: false, error: String((e && e.message) || e).slice(0, 240) }); }
294
+ return send(404, { ok: false, error: 'no such ready-report route' });
295
+ }
296
+ if (!POSTS.includes(sub)) return send(404, { ok: false, error: 'no such ready-report route' });
297
+ if (req.method !== 'POST') return send(405, { ok: false, error: 'POST only' });
298
+ const read = await ctx.readJson(req);
299
+ if (!read.ok) return send(400, { ok: false, error: 'the body is not JSON' });
300
+ const body = read.body || {};
301
+ const g = guard.requirePagePress(req, body);
302
+ if (!g.ok) return send(g.status, { ok: false, error: g.error });
303
+ const w = wsOf(ctx, text(body.ws));
304
+ if (!w) return send(404, { ok: false, error: 'no such workspace' });
305
+ if (!hasState(w)) return send(409, { ok: false, error: 'This repository has no PMOS state folder, so nothing is saved.' });
306
+ const file = RR.ledgerFile(stateDir(w));
307
+ const scope = text(body.scope), kind = text(body.kind);
308
+ const key = RR.keyOf(scope, kind);
309
+ const write = (line) => RR.append(file, line, { actor: g.actor });
310
+ const fail = (r) => send(r.status || 400, { ok: false, error: r.error });
311
+ const nameOf = async (sc) => { const S = await scopesOf(req, ctx, w); const s = S.list.find((x) => x.scope === sc); return s ? s.name : sc; };
312
+
313
+ if (sub === 'switch') {
314
+ if (!RR.KEY_RE.test(key) || kind === 'heads-up' || typeof body.on !== 'boolean') return send(400, { ok: false, error: 'switch is { ws, scope, kind: weekly | checkpoint | did-it-work, on }' });
315
+ const r = write({ ev: 'switch', key, on: body.on }); if (!r.ok) return fail(r);
316
+ if (!scope.endsWith(':*') && kind === 'weekly') {
317
+ if (body.on) { const e = ensureSetup(w, scope, kind, await nameOf(scope), { by: g.actor, hand: handOf(RS.stateOf(w.root), await nameOf(scope)) }); if (!e.ok) return fail(e); }
318
+ else { const id = RR.setupIdOf(scope, kind); const s = RS.stateOf(w.root).setups.get(id); if (s && s.status === 'active') RS.pause(w.root, id, { by: g.actor }); }
319
+ }
320
+ return send(200, { ok: true, key, on: body.on });
321
+ }
322
+ if (sub === 'picks') {
323
+ const L = await libraryAnswer(req, ctx, w);
324
+ const keys = (L.body.lead && L.body.lead.keys) || [];
325
+ const r = write({ ev: 'picks', keys }); if (!r.ok) return fail(r);
326
+ const rst = RS.stateOf(w.root), made = [];
327
+ for (const k of keys) { const sc = k.split('|')[0]; const nm = await nameOf(sc); const e = ensureSetup(w, sc, 'weekly', nm, { by: g.actor, hand: handOf(rst, nm) }); if (e.ok) made.push(e.setup.id); }
328
+ return send(200, { ok: true, keys, setups: made });
329
+ }
330
+ if (sub === 'trust') {
331
+ if (!RR.KEY_RE.test(key) || typeof body.on !== 'boolean') return send(400, { ok: false, error: 'trust is { ws, scope, kind, on }' });
332
+ const st = RR.stateOf(stateDir(w));
333
+ const r = write(body.on || st.trust.get(key) === true ? { ev: 'trust', key, on: body.on } : { ev: 'trust-no', key }); if (!r.ok) return fail(r);
334
+ return send(200, { ok: true, key, on: body.on });
335
+ }
336
+ if (sub === 'hold') {
337
+ const act = text(body.act);
338
+ if (!RR.KEY_RE.test(key) || !RR.HOLD_ACTS.includes(act)) return send(400, { ok: false, error: `hold is { ws, scope, kind, act: ${RR.HOLD_ACTS.join(' | ')} }` });
339
+ const s = RS.stateOf(w.root).setups.get(RR.setupIdOf(scope, kind));
340
+ const last = s && s.drafted.length ? s.drafted[s.drafted.length - 1] : null;
341
+ if (!last) return send(409, { ok: false, error: 'nothing is drafted to hold' });
342
+ const r = write({ ev: 'hold', key, slot: last.slot, act }); if (!r.ok) return fail(r);
343
+ let noted = false;
344
+ if (act === 'send-note' && last.path) {
345
+ const X = await factsFor(req, ctx, w, scope, {});
346
+ if (X.f && X.f.stale) noted = noteOn(w, s.id, last.slot, last.path, X.f.stale.source + ' as of ' + X.f.stale.since.slice(0, 16).replace('T', ' ') + ': its numbers may be out of date.');
347
+ }
348
+ return send(200, { ok: true, key, slot: last.slot, act, noted });
349
+ }
350
+ if (sub === 'overlap') { const r = write({ ev: 'overlap', on: true }); if (!r.ok) return fail(r); return send(200, { ok: true }); }
351
+ if (sub === 'promise') {
352
+ const r = write({ ev: 'promise', scope, act: text(body.act), date: text(body.date) }); if (!r.ok) return fail(r);
353
+ return send(200, { ok: true, scope, act: body.act, date: body.date });
354
+ }
355
+ return send(404, { ok: false, error: 'no such ready-report route' });
356
+ }
357
+
358
+ /** Write the held source's note on an unissued draft, under its title. An issued report is frozen and never touched. → true when written */
359
+ function noteOn(w, cadence, slot, rel, note) {
360
+ if (issues.isIssued(issues.readIssues(path.resolve(w.root)), cadence, slot)) return false;
361
+ const file = path.join(path.resolve(w.root), rel);
362
+ let md; try { md = fs.readFileSync(file, 'utf8'); } catch { return false; }
363
+ if (md.includes('> ' + note)) return true;
364
+ const out = md.replace(/^(# .*\n\n[^\n]*\n)/m, (m) => m + '\n> ' + note + '\n');
365
+ if (out === md) return false;
366
+ try { fs.writeFileSync(file, out); } catch { return false; }
367
+ return true;
368
+ }
369
+
370
+ // ── the tick ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────
371
+ let ticking = false;
372
+ const lastRun = new Map();
373
+ const EVERY_MS = 15 * 60e3; // the scopes' facts are read at most every 15 minutes per workspace: a weekly slot, a moment and a heads-up are not minute-sharp
374
+ /** Draft what is due in every workspace. → [{ scope, kind, slot, ok, error?, why? }] */
375
+ async function tick(ctx, now = new Date(), { force = false } = {}) {
376
+ if (ticking || !ctx) return [];
377
+ ticking = true;
378
+ const done = [];
379
+ try {
380
+ const list = typeof ctx.workspaceList === 'function' ? ctx.workspaceList() : [ctx.getWs(null)].filter(Boolean);
381
+ for (const w of list) {
382
+ if (!w || !w.root || !hasState(w)) continue;
383
+ if (!force && now.getTime() - (lastRun.get(w.id) || 0) < EVERY_MS) continue;
384
+ lastRun.set(w.id, now.getTime());
385
+ const c = { ...ctx, getWs: (id) => (id === w.id || id == null ? w : ctx.getWs(id)) };
386
+ const cache = new Map();
387
+ let S; try { S = await scopesOf(null, c, w, cache); } catch { continue; }
388
+ for (const s of S.list) { try { done.push(...await tickScope(c, w, s, now, cache)); } catch (e) { done.push({ scope: s.scope, ok: false, error: String((e && e.message) || e).slice(0, 160) }); } }
389
+ }
390
+ } finally { ticking = false; }
391
+ return done;
392
+ }
393
+ async function tickScope(ctx, w, s, now, cache = null) {
394
+ const out = [];
395
+ const st = RR.stateOf(stateDir(w));
396
+ const rst = RS.stateOf(w.root);
397
+ const today = localIso(now);
398
+ const wkId = RR.setupIdOf(s.scope, 'weekly'), wk = rst.setups.get(wkId);
399
+ const P = RR.parseScope(s.scope);
400
+ const weeklyDue = wk && wk.status === 'active' && logic.isDue(RS.scheduleOf(wk), now) && (() => { const at = logic.lastSlot(RS.scheduleOf(wk), now); return at && !wk.drafted.some((d) => d.slot === RS.localDay(at)) && !(st.quiet.get(RR.keyOf(s.scope, 'weekly')) || []).includes(RS.localDay(at)); })();
401
+ // the moments need the scope's facts; read them only when something could be due
402
+ const X = await factsFor(null, ctx, w, s.scope, { now: now.getTime(), cache, lite: !weeklyDue });
403
+ if (X.error) return out;
404
+ const extras = (X2) => readyExtras(X2);
405
+ const SR = require('./routes-report-setups.js');
406
+ if (weeklyDue) {
407
+ const slot = RS.localDay(logic.lastSlot(RS.scheduleOf(wk), now));
408
+ const tickets = Object.values(X.f.jiraOf).flatMap((j) => j.tickets || []);
409
+ const moved = RR.movedOf({ today, tickets, goals: IR.goalsIn(X.model || {}, s.scope), needs: X.f.needs });
410
+ if (!moved) { RR.append(RR.ledgerFile(stateDir(w)), { ev: 'quiet', key: RR.keyOf(s.scope, 'weekly'), slot }, { now }); out.push({ scope: s.scope, kind: 'weekly', slot, ok: true, why: 'quiet' }); }
411
+ else { const r = await SR.draftIntelligence(ctx, w, wk, slot, { model: X.model, now, ready: extras(X) }); out.push({ scope: s.scope, kind: 'weekly', slot, ...r }); }
412
+ }
413
+ const items = X.row ? (X.f.checklist || []) : [];
414
+ for (const m of RR.momentsOf(P.level, { today, row: X.row, rows: X.rows, program: X.program, checklist: items, quarterEnd: RR.quarterEndOf(today) })) {
415
+ const key = RR.keyOf(s.scope, m.kind);
416
+ if (st.moments.has(key + '|' + m.why)) continue;
417
+ const sw = RR.switchOf(st, s.scope, m.kind);
418
+ if (sw === false) continue;
419
+ const e = ensureSetup(w, s.scope, m.kind, s.name, { now });
420
+ if (!e.ok) { out.push({ scope: s.scope, kind: m.kind, ok: false, error: e.error }); continue; }
421
+ const r = await SR.draftIntelligence(ctx, w, e.setup, m.slot, { model: X.model, now, ready: extras(X) });
422
+ if (r.ok || r.existing) RR.append(RR.ledgerFile(stateDir(w)), { ev: 'moment', key, slot: m.slot, why: m.why }, { now });
423
+ out.push({ scope: s.scope, kind: m.kind, slot: m.slot, why: m.why, ...r });
424
+ }
425
+ // a heads-up: a broken health budget or a critical slip, at once and outside the schedule (PbG3)
426
+ const ships = RR.stageOf(P.level, { today, row: X.row, rows: X.rows, jira: X.row ? X.f.jiraOf[X.row.id] : null, jiraOf: X.f.jiraOf, program: X.program, intel: X.model, kept: X.f.kept });
427
+ const H = RR.headsUpOf({ budgets: P.level === 'product' ? (X.model && X.model.budgets) || [] : [], ships, name: s.name });
428
+ for (const h of H) {
429
+ if (st.headsUps.has(h.id)) continue;
430
+ const e = ensureSetup(w, s.scope, 'heads-up', s.name, { now });
431
+ if (!e.ok) continue;
432
+ const md = headsUpMd(e.setup, h, today);
433
+ const r = RS.writeDocument(w.root, e.setup, today, md, { now });
434
+ if (r.ok) RR.append(RR.ledgerFile(stateDir(w)), { ev: 'heads-up', key: RR.keyOf(s.scope, 'heads-up'), id: h.id, slot: today, path: r.path, why: h.title }, { now });
435
+ out.push({ scope: s.scope, kind: 'heads-up', slot: today, ok: r.ok, ...(r.ok ? { path: r.path } : { error: r.error }) });
436
+ }
437
+ return out;
438
+ }
439
+ /** The sections a ready report adds: milestones (a program), the tickets closed this week, the products not read, the held source's note. */
440
+ function readyExtras(X) {
441
+ const S = RR.stageOf(X.P.level, { today: X.f.today, row: X.row, rows: X.rows, jira: X.row ? X.f.jiraOf[X.row.id] : null, jiraOf: X.f.jiraOf, program: X.program, intel: X.model, kept: X.f.kept, multi: X.f.products.length > 1 });
442
+ const ms = S && S.kind === 'milestones' ? S.items.map((m) => ({ name: m.name, promised: m.date, forecast: m.when, status: m.dot === 'behind' ? 'Behind' : m.dot === 'risk' ? 'At risk' : m.when === 'done' ? 'Done' : 'On plan' }))
443
+ : S && S.kind === 'ships' ? [{ name: 'Ships', promised: S.promised, forecast: S.lo ? S.lo + (S.hi && S.hi !== S.lo ? ' to ' + S.hi : '') : S.why, status: S.dot === 'behind' ? 'Behind' : S.dot === 'risk' ? 'At risk' : S.dot === 'on' ? 'On plan' : '—' }] : [];
444
+ const t = Date.parse(X.f.today + 'T00:00:00Z');
445
+ const n = Object.values(X.f.jiraOf).flatMap((j) => j.tickets || []).filter((x) => x.category === 'done' && x.resolved && t - Date.parse(x.resolved + 'T00:00:00Z') < 7 * 864e5 && t >= Date.parse(x.resolved + 'T00:00:00Z')).length;
446
+ return { milestones: ms, done: n ? [n + (n === 1 ? ' Jira ticket was' : ' Jira tickets were') + ' closed in the last 7 days.'] : [], unknown: X.f.products.filter((p) => !p.read).map((p) => p.name + ': ' + p.why + '.'), note: X.f.stale ? X.f.stale.source + ' has not read since ' + X.f.stale.since.slice(0, 10) + '. This draft is held until it reads again.' : '' };
447
+ }
448
+ function headsUpMd(setup, h, today) {
449
+ const q = (v) => `"${String(v == null ? '' : v).replace(/["\\]/g, "'")}"`;
450
+ return ['---', 'type: Reference', `title: ${q(setup.name + ' ' + today)}`, `description: ${q('A heads-up drafted outside the schedule. Nothing was sent.')}`, `timestamp: ${today}`, `cadence: ${setup.id}`, `slot: ${today}`,
451
+ 'status: draft', `output: ${setup.output}`, `source: ${setup.source}`, 'made_by: schedule', '---', '', `# ${h.title}`, '', `Heads-up · ${today} · for ${setup.audience}`, '', `1. ${h.sub}.`, '2. The next scheduled update closes the story.', '',
452
+ `Source: ${h.why === 'budget' ? 'the health budget readings' : 'the Jira tickets and the promise date'}, read ${today}.`, ''].join('\n');
453
+ }
454
+
455
+ module.exports = { prefixes: ['/api/ready-reports'], handle, tick, factsFor, readyExtras, ensureSetup };
@@ -58,6 +58,8 @@ module.exports = {
58
58
  const r = verb === 'add' ? addRecord(writeRootOf(ctx, body), kind, body)
59
59
  : verb === 'edit' ? editRecord(writeRootOf(ctx, body), kind, body)
60
60
  : kind === 'kr-metrics' ? readingRecord(writeRootOf(ctx, body), body) : bad(404, 'readings belong to kr-metrics');
61
+ // batch 16 item 6: a typed reading is a reading too: the limit alert and the standing read fixes follow it (lib/goal-watch.js)
62
+ if (verb === 'reading' && r.status === 200 && body.rid) { try { const w = ctx.getWs(body.ws || null); if (w) require('./routes-goal-status.js').afterRead(ctx, w, [String(body.rid)]); } catch { /* the reading stands */ } }
61
63
  ctx.json(res, r.body, r.status);
62
64
  return true;
63
65
  },
@@ -151,7 +151,7 @@ function setupOut(s, now, docsOf, idx, root, draft) {
151
151
  if (s.status === 'active') { try { const n = RS.nextDraftAt(s.schedule, s.last_run, now); next = n ? n.toISOString() : null; } catch { next = null; } }
152
152
  return {
153
153
  id: s.id, name: s.name, purpose: s.purpose, audience: s.audience, source: s.source, output: s.output, schedule: s.schedule, label: RS.scheduleLabel(s.schedule),
154
- ...(IR.isIntelligence(s.source) ? { scope: IR.scopeOf(s.source), storyline: s.storyline || {} } : {}),
154
+ ...(IR.isIntelligence(s.source) ? { scope: IR.scopeOf(s.source), storyline: s.storyline || {} } : {}), ...(s.ready ? { ready: s.ready } : {}),
155
155
  next_draft: next, last_issued: issued, status: s.status, cycles: mine.length,
156
156
  copy: copyOf(latest ? linkFor(idx, latest.path, s.output) : null, docSync.copyKindOf(s.output)),
157
157
  structure: structureOf(root, s.id),
@@ -240,6 +240,7 @@ async function tick(ctx, now = new Date()) {
240
240
  try { st = RS.stateOf(w.root); } catch { continue; }
241
241
  for (const s of st.setups.values()) {
242
242
  if (s.status !== 'active' || !(String(s.source).startsWith('dashboard:') || IR.isIntelligence(s.source))) continue;
243
+ if (s.ready) continue; // a ready-made report is drafted by lib/routes-ready-reports.js tick (its moments, quiet weeks and holds)
243
244
  const sched = RS.scheduleOf(s);
244
245
  if (!logic.isDue(sched, now)) continue;
245
246
  const slotAt = logic.lastSlot(sched, now);
@@ -515,7 +516,7 @@ async function intelModel(req, ctx, ws, board) {
515
516
  /** Draft one issue of a report from Intelligence at `slot` (lib/intel-report.js documentOf). The issue number counts the documents before it; the issue
516
517
  * before it (the latest issued one) gives Actions from issue N and Since issue N. A document already at the slot is the answer and is not overwritten.
517
518
  * → { ok, slot, path } | { ok: false, existing?, error } */
518
- async function draftIntelligence(ctx, w, s, slot, { model, now = new Date() } = {}) {
519
+ async function draftIntelligence(ctx, w, s, slot, { model, now = new Date(), ready = null } = {}) {
519
520
  const rel = RD.draftPath(path.resolve(w.root), s.id, slot);
520
521
  try { if (fs.statSync(path.join(path.resolve(w.root), rel)).isFile()) return { ok: false, existing: true, slot, path: rel, error: 'drafted already' }; } catch { /* not there yet */ }
521
522
  const m = model || await intelModel(null, ctx, w.id, null);
@@ -524,7 +525,7 @@ async function draftIntelligence(ctx, w, s, slot, { model, now = new Date() } =
524
525
  const before = mine.filter((x) => x.issued).pop() || null;
525
526
  let prior = null;
526
527
  if (before) { try { prior = fs.readFileSync(path.join(path.resolve(w.root), before.path), 'utf8'); } catch { prior = null; } }
527
- const md = IR.documentOf(m, s, { slot, now, issue: mine.length + 1, prior });
528
+ const md = IR.documentOf(m, s, { slot, now, issue: mine.length + 1, prior, ...(ready ? { ready } : {}) });
528
529
  const r = RS.writeDocument(w.root, s, slot, md, { now });
529
530
  return r.ok ? { ok: true, slot, path: r.path } : { ok: false, status: r.status, error: r.error };
530
531
  }
@@ -76,6 +76,9 @@ const DEFS = Object.freeze({
76
76
  'adler.motion': one('adler', 'computer', ['system', 'still'], 'system'),
77
77
  'adler.celebrate': one('adler', 'computer', ['real', 'never'], 'real'),
78
78
  'adler.quiet': one('adler', 'computer', ['22', 'never'], '22'),
79
+ // Settings > General > Your impact (feedback batch 16 item 7, canvas GmP1Switch): the one switch. Off hides every impact surface, Adler's
80
+ // leaf included, and stops the daily impact run (lib/routes-impact.js, lib/impact-runs.js).
81
+ 'impact.on': bool('general', 'computer', true),
79
82
  });
80
83
 
81
84
  /* The environment variables that win over a setting, here or in a setting's own store. `key` names the setting the page