create-pmos 0.434.0 → 0.436.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +25 -25
- package/payload/KIT-VERSION +1 -1
- package/payload/planning/evals/eval-calibration.md +1 -1
- package/payload/planning/okrs/health-budgets.md +1 -1
- package/payload/state/discoveries.md +1 -1
- package/workspace/changelog.json +24 -0
- package/workspace/fixtures/ready-reports.js +145 -0
- package/workspace/guide/home.md +1 -1
- package/workspace/guide/index.md +1 -0
- package/workspace/guide/initiative-boards.md +1 -1
- package/workspace/guide/ready-made-dashboards.md +62 -0
- package/workspace/lib/board-premium.js +1 -1
- package/workspace/lib/engine/boards.js +1 -1
- package/workspace/lib/intel-report.js +36 -5
- package/workspace/lib/ready-reports.js +616 -0
- package/workspace/lib/report-dashboards.js +5 -0
- package/workspace/lib/report-setups.js +16 -7
- package/workspace/lib/route-modules.js +1 -0
- package/workspace/lib/routes-board-premium.js +5 -0
- package/workspace/lib/routes-boards.js +3 -2
- package/workspace/lib/routes-ready-reports.js +455 -0
- package/workspace/lib/routes-report-setups.js +4 -3
- package/workspace/package-lock.json +2 -2
- package/workspace/package.json +1 -1
- package/workspace/program-charter-test.js +11 -7
- package/workspace/program-panel-test.js +1 -1
- package/workspace/public/pm/bd-ini-panel.js +23 -6
- package/workspace/public/pm/bd-prog-panel.js +58 -10
- package/workspace/public/pm/cozy-viewer.js +2 -2
- package/workspace/public/pm/cozy-vw-rp.css +13 -0
- package/workspace/public/pm/dash-view.css +111 -0
- package/workspace/public/pm/dash-view.js +261 -0
- package/workspace/public/pm/home-app.js +26 -0
- package/workspace/public/pm/home-data.js +3 -2
- package/workspace/public/pm/home-ini.js +19 -1
- package/workspace/public/pm/home-task.js +4 -2
- package/workspace/public/pm/ini-tasks.js +34 -6
- package/workspace/public/pm/ini-view.css +4 -0
- package/workspace/public/pm/premium-insights.js +10 -2
- package/workspace/public/pm/premium-report-read.js +36 -5
- package/workspace/public/pm/premium-vw-item.js +2 -0
- package/workspace/public/pm/ready-lib.css +29 -0
- package/workspace/public/pm/ready-lib.js +62 -0
- package/workspace/public/pm/task-card.css +1 -0
- package/workspace/public/pm/task-card.js +8 -3
- package/workspace/ready-dash-ui-test.js +227 -0
- package/workspace/server.js +2 -0
- package/workspace/task-delete-test.js +31 -0
- package/workspace/task-views-test.js +16 -0
- package/workspace/test-lists/batch17-ready-reports.json +9 -0
- package/workspace/test-lists/ready-reports-ui.json +6 -0
|
@@ -8,6 +8,11 @@
|
|
|
8
8
|
* scopeFilter(body, facts, scope, id, today, opts) the /api/c3-strategy body narrowed to a scope, plus delivery and range
|
|
9
9
|
* validKey · readLayouts · writeLayout the layout store: <runtimeDir>/report-dashboards/layouts.json
|
|
10
10
|
*
|
|
11
|
+
* RETIRED FOR THE PREMIUM PAGES (batch 17 item 1, lib/ready-reports.js): the ready-made dashboard of every program, product and initiative maps
|
|
12
|
+
* this library onto its blocks. North star and Quarter outcomes are the Goals block, Early signals is the ✦ line, Delivery against promise is
|
|
13
|
+
* Ships (a program's Milestones). Maturity by pillar, Bets and checkpoints and Synergy coverage are left out: not every scope has them, so they
|
|
14
|
+
* are not generic. This file stays for the console3 page that still reads it.
|
|
15
|
+
*
|
|
11
16
|
* The layout store is the only I/O. It writes under the runtime directory the caller names, with a temp file and a rename, and never
|
|
12
17
|
* touches the repository. Everything else reads values it is handed. */
|
|
13
18
|
const fs = require('fs');
|
|
@@ -24,14 +24,16 @@
|
|
|
24
24
|
*
|
|
25
25
|
* THE LINES. Every line is { v: 1, ev, …, at, by? }. Who wrote a line is the call path (lib/actor.js), never an argument:
|
|
26
26
|
* setup { id, name, purpose, audience, source: 'work'|'dashboard:<key>'|'intelligence:<scope>', output, schedule, sources[], sections[], learned_from, fixes[],
|
|
27
|
-
* product, ws, last_run, def_sha, from?, storyline? } the PM pressed Set up. `from` is { ask } or { finding }.
|
|
27
|
+
* product, ws, last_run, def_sha, from?, storyline?, ready? } the PM pressed Set up. `from` is { ask } or { finding }.
|
|
28
|
+
* `ready` is { scope, kind }: a ready-made report of a program, product or initiative (batch 17 item 1, lib/ready-reports.js). Its
|
|
29
|
+
* drafting is lib/routes-ready-reports.js tick's, not this file's schedule
|
|
28
30
|
* An Intelligence-sourced setup (batch 15 item 4, lib/intel-report.js) keeps the PM's storyline edits: { answer?, ask?: { text, who, by }, items?: [{ id, on }] }.
|
|
29
31
|
* It is drafted like a dashboard-sourced one, by the tick in lib/routes-report-setups.js, from the live Intelligence model
|
|
30
32
|
* change { id, …the fields that changed } the PM edited a recurring report
|
|
31
33
|
* pause · resume · remove { id } a removed setup is a deleted TEMPLATE: its schedule stops, its documents stay
|
|
32
34
|
* doc-discard { doc, path } the PM discarded an unissued draft (the file is deleted; this line keeps the record)
|
|
33
35
|
* doc-archive { doc, archived } the PM archived (true) or brought back (false) an issued report. The file is never touched
|
|
34
|
-
* drafted { id, slot, path }
|
|
36
|
+
* drafted { id, slot, path, sha? } a dashboard-sourced setup made its document (this is its last run); sha: the git blob sha as drafted
|
|
35
37
|
* ask-start { ask, text, ws } the PM typed a request in the Ask box
|
|
36
38
|
* proposal { ask, proposal } the report-setup run filed ONE proposal (a second one revises it)
|
|
37
39
|
* proposal-change { ask, text } the PM asked for a correction; a second run revises the same proposal
|
|
@@ -199,11 +201,17 @@ function checkProposal(input) {
|
|
|
199
201
|
}
|
|
200
202
|
}
|
|
201
203
|
if (x.product != null && x.product !== '' && !oneLine(x.product, 80)) return { ok: false, error: 'product is one line of at most 80 characters' };
|
|
204
|
+
let ready = null;
|
|
205
|
+
if (x.ready != null) {
|
|
206
|
+
const RR = require('./ready-reports.js');
|
|
207
|
+
if (!isObj(x.ready) || !RR.parseScope(x.ready.scope) || !RR.KINDS.concat(['heads-up']).includes(x.ready.kind)) return { ok: false, error: 'ready is { scope: product | program:<id> | initiative:<id>, kind: weekly | checkpoint | did-it-work | heads-up }' };
|
|
208
|
+
ready = { scope: x.ready.scope, kind: x.ready.kind };
|
|
209
|
+
}
|
|
202
210
|
const clean = (s) => String(s).replace(/["\\]/g, "'").trim();
|
|
203
211
|
return { ok: true, proposal: {
|
|
204
212
|
name: x.name.trim(), purpose: x.purpose.trim(), audience: clean(x.audience), source, output: x.output, schedule: sch.schedule,
|
|
205
213
|
sources: sources.list, sections: sections.list.length ? sections.list : FRAME.slice(), learned_from: x.learned_from ? x.learned_from.trim() : null,
|
|
206
|
-
fixes: fixes.list, found, ...(x.product ? { product: clean(x.product) } : {}), ...(storyline ? { storyline } : {}),
|
|
214
|
+
fixes: fixes.list, found, ...(x.product ? { product: clean(x.product) } : {}), ...(storyline ? { storyline } : {}), ...(ready ? { ready } : {}),
|
|
207
215
|
} };
|
|
208
216
|
}
|
|
209
217
|
|
|
@@ -231,7 +239,7 @@ function fold(lines) {
|
|
|
231
239
|
st.setups.set(l.id, { id: l.id, name: l.name, purpose: l.purpose, audience: l.audience, source: l.source || 'work', output: l.output, schedule: l.schedule,
|
|
232
240
|
sources: l.sources || [], sections: l.sections || FRAME.slice(), learned_from: l.learned_from || null, fixes: l.fixes || [], product: l.product || null,
|
|
233
241
|
ws: l.ws || null, status: 'active', created_at: l.at, last_run: l.last_run || l.at, def_sha: l.def_sha || null, from: l.from || null, migrated: !!l.migrated, drafted: [],
|
|
234
|
-
...(isObj(l.storyline) ? { storyline: l.storyline } : {}) });
|
|
242
|
+
...(isObj(l.storyline) ? { storyline: l.storyline } : {}), ...(isObj(l.ready) ? { ready: l.ready } : {}) });
|
|
235
243
|
if (l.from && l.from.ask) st.asks.delete(l.from.ask);
|
|
236
244
|
if (l.from && l.from.finding && st.findings.has(l.from.finding)) st.findings.get(l.from.finding).state = 'set-up';
|
|
237
245
|
break;
|
|
@@ -247,7 +255,7 @@ function fold(lines) {
|
|
|
247
255
|
case 'remove': { const s = st.setups.get(l.id); if (s) { st.removed.set(l.id, { ...s, status: 'removed', removed_at: l.at }); st.setups.delete(l.id); } break; }
|
|
248
256
|
case 'doc-discard': if (typeof l.doc === 'string') { st.discarded.push({ doc: l.doc, path: l.path || null, at: l.at }); st.archived.delete(l.doc); } break;
|
|
249
257
|
case 'doc-archive': if (typeof l.doc === 'string') { if (l.archived === false) st.archived.delete(l.doc); else st.archived.add(l.doc); } break;
|
|
250
|
-
case 'drafted': { const s = st.setups.get(l.id); if (s) { s.last_run = l.at; s.drafted.push({ slot: l.slot, at: l.at, path: l.path || null }); } break; }
|
|
258
|
+
case 'drafted': { const s = st.setups.get(l.id); if (s) { s.last_run = l.at; s.drafted.push({ slot: l.slot, at: l.at, path: l.path || null, ...(typeof l.sha === 'string' ? { sha: l.sha } : {}) }); } break; }
|
|
251
259
|
case 'ask-start':
|
|
252
260
|
if (ASK_RE.test(String(l.ask || ''))) st.asks.set(l.ask, { id: l.ask, text: l.text, ws: l.ws || null, state: 'running', changed: false, proposal: null, error: null, started: l.at, changes: [] });
|
|
253
261
|
break;
|
|
@@ -518,7 +526,7 @@ function setUp(root, input, opts = {}) {
|
|
|
518
526
|
}
|
|
519
527
|
append(file, { ev: 'setup', id, name: p.name, purpose: p.purpose, audience: p.audience, source: p.source, output: p.output, schedule: p.schedule, sources: p.sources,
|
|
520
528
|
sections: p.sections, learned_from: p.learned_from, fixes: p.fixes, product: setup.product, ws: opts.wsId || null, last_run: lastRun, def_sha: def.sha,
|
|
521
|
-
...(from ? { from } : {}), ...(opts.migrated ? { migrated: true } : {}), ...(p.storyline ? { storyline: p.storyline } : {}) }, { now, by: opts.by });
|
|
529
|
+
...(from ? { from } : {}), ...(opts.migrated ? { migrated: true } : {}), ...(p.storyline ? { storyline: p.storyline } : {}), ...(p.ready ? { ready: p.ready } : {}) }, { now, by: opts.by });
|
|
522
530
|
const next = nextDraftAt(p.schedule, lastRun, now);
|
|
523
531
|
const folded = fold(readLines(file)).setups.get(id);
|
|
524
532
|
return { ok: true, setup: folded, definition: def.path, first_draft: next ? { slot: localDay(next), at: next.toISOString(), day: next.getDay() } : null };
|
|
@@ -744,7 +752,8 @@ function writeDocument(root, setup, slot, markdown, { now, record = true } = {})
|
|
|
744
752
|
const tmp = `${file}.tmp-${crypto.randomBytes(6).toString('hex')}`;
|
|
745
753
|
try { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(tmp, markdown, { flag: 'wx' }); fs.renameSync(tmp, file); }
|
|
746
754
|
catch (e) { try { fs.unlinkSync(tmp); } catch { /* not made */ } return refuse(500, 'could not write the document: ' + String((e && e.message) || e).slice(0, 160)); }
|
|
747
|
-
|
|
755
|
+
// the blob sha of the file as drafted: an issue whose sha is the same was sent unchanged (lib/ready-reports.js trustOf)
|
|
756
|
+
if (record) append(ledgerFile(abs), { ev: 'drafted', id: setup.id, slot, path: rel, sha: issues.blobSha(Buffer.from(markdown)) }, { now });
|
|
748
757
|
return { ok: true, path: rel };
|
|
749
758
|
}
|
|
750
759
|
|
|
@@ -102,6 +102,7 @@ const MODULES = Object.freeze([
|
|
|
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
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
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
|
|
105
|
+
'routes-ready-reports', // batch 17 item 1: the ready-made dashboard and reports of every program, product and initiative (ready-reports.jsonl; page-press POST)
|
|
105
106
|
'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)
|
|
106
107
|
'routes-impact', // batch 16 item 7: Your impact, private to the PM: the week, the log, the weekly check and its ✓/✕ (runtime impact/impact.jsonl; page-press POST)
|
|
107
108
|
'routes-goal-status', // batch 16 item 6: the goals' one status from readings (product page), notify choice, recipe, Read now, test read, CSV readings
|
|
@@ -93,6 +93,11 @@ module.exports = {
|
|
|
93
93
|
rows: listOf(rk, nw), columns: c ? c.columns : [], sprints: s || { source: 'none', sprints: [] }, docs: d, custom,
|
|
94
94
|
items: its && its.body && its.body.ok !== false && Array.isArray(its.body.items) ? its.body.items : [], held: hd ? hd.rows : [], cancelled: cn ? cn.rows : [], archived: ar ? ar.rows : [], asks: ak ? ak.asks || [] : null,
|
|
95
95
|
});
|
|
96
|
+
// every open initiative's anchor, not only the 100 rows listed (batch 17 item 1): Home's product card counts the goals as the ready-made
|
|
97
|
+
// dashboard counts them (lib/ready-reports.js anchorGoalsOf reads the same /api/boards/items rows)
|
|
98
|
+
const iniRows = its && its.body && Array.isArray(its.body.initiatives) ? its.body.initiatives : null;
|
|
99
|
+
if (iniRows) model.anchorRows = iniRows.filter((r) => r && r.anchor && !['done', 'cancelled'].includes(String(r.status || '').toLowerCase()) && !r.archived)
|
|
100
|
+
.map((r) => ({ id: r.id, title: r.title, status: r.status || null, late: r.status === 'late', anchor: r.anchor, kr: BoardPremium.krShort(r.anchor) }));
|
|
96
101
|
// planned versus actual (batch 11 item 8): each row's drafts and saved plans, from task-plans.jsonl
|
|
97
102
|
try {
|
|
98
103
|
const w = ctx.getWs ? ctx.getWs(pick.ws) : null, dir = w && ctx.stateDirFor ? ctx.stateDirFor(w) : null;
|
|
@@ -434,7 +434,8 @@ function stageTasks(file, folded, board, row, by) {
|
|
|
434
434
|
const list = st && Array.isArray(st.finish) ? st.finish.filter((f) => typeof f === 'string' && f.trim()) : [];
|
|
435
435
|
if (!list.length) return 0;
|
|
436
436
|
const have = new Set();
|
|
437
|
-
|
|
437
|
+
// a To finish task the PM deleted stays deleted: the next read must not make it again (batch 17 item 2: "Deleting task, but keep appearing")
|
|
438
|
+
for (const t of [...folded.tasks.values(), ...(folded.removed ? folded.removed.values() : [])]) if (t.initiative === row.id && t.from && t.from.stage === st.key) have.add(t.from.finish);
|
|
438
439
|
let n = 0;
|
|
439
440
|
for (const f of list) {
|
|
440
441
|
if (have.has(f)) continue;
|
|
@@ -715,7 +716,7 @@ const READS = {
|
|
|
715
716
|
const live = r.rows.filter((x) => !x.archived); // an archived initiative leaves every list and timeline (c3-initiative-lifecycle)
|
|
716
717
|
seedRows(ctx, r.w, r.fr, r.board, live);
|
|
717
718
|
ctx.json(res, { ok: true, ws: r.w.id, board: r.board.id, build: r.board.build, jira: r.board.jira, jiraProjects: r.board.jiraProjects, items: itemsOf(r.w, r.fr, r.board, live),
|
|
718
|
-
initiatives: live.map((x) => ({ id: x.id, title: x.title, stage: x.stage, cat: x.cat, status: x.status, owner: x.owner, horizon: x.horizon, start: x.start, end: x.end, progress: x.progress, template: x.template, epics: x.epics,
|
|
719
|
+
initiatives: live.map((x) => ({ id: x.id, title: x.title, stage: x.stage, cat: x.cat, status: x.status, owner: x.owner, anchor: x.anchor || '', horizon: x.horizon, start: x.start, end: x.end, progress: x.progress, template: x.template, epics: x.epics,
|
|
719
720
|
stages: (x.wfStages || []).map((st) => ({ key: st.key, name: st.name, milestone: !!st.milestone })) })) }); // the sections a task can sit in (the task Viewer's move icon)
|
|
720
721
|
},
|
|
721
722
|
'/api/boards/sprints': (ctx, res, url) => {
|
|
@@ -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 };
|