create-pmos 0.427.0 → 0.429.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 (147) 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/board-programs-test.js +16 -2
  7. package/workspace/briefing-premium-board-test.js +27 -22
  8. package/workspace/briefing-premium-insights-test.js +81 -60
  9. package/workspace/briefing-premium-metrics-test.js +5 -3
  10. package/workspace/briefing-premium-sources-test.js +5 -5
  11. package/workspace/briefing-premium-test.js +7 -5
  12. package/workspace/changelog.json +24 -0
  13. package/workspace/ev-everywhere-test.js +2 -2
  14. package/workspace/guide/briefing-premium.md +4 -2
  15. package/workspace/guide/home.md +34 -7
  16. package/workspace/guide/index.md +1 -0
  17. package/workspace/guide/metric-drafts.md +48 -0
  18. package/workspace/guide/programs.md +1 -0
  19. package/workspace/home-other-product-test.js +12 -2
  20. package/workspace/intel-report-ui-test.js +189 -0
  21. package/workspace/lib/board-metrics-premium.js +1 -1
  22. package/workspace/lib/headless.js +15 -2
  23. package/workspace/lib/insights-premium.js +5 -1
  24. package/workspace/lib/insights-records.js +14 -5
  25. package/workspace/lib/intel-report.js +419 -0
  26. package/workspace/lib/metric-draft-runs.js +193 -0
  27. package/workspace/lib/metric-drafts.js +231 -0
  28. package/workspace/lib/metrics-cli.js +104 -0
  29. package/workspace/lib/pmos-verbs.js +3 -0
  30. package/workspace/lib/report-setups.js +29 -13
  31. package/workspace/lib/route-modules.js +1 -0
  32. package/workspace/lib/routes-insights-premium.js +2 -2
  33. package/workspace/lib/routes-insights-records.js +13 -5
  34. package/workspace/lib/routes-meeting-material.js +22 -1
  35. package/workspace/lib/routes-metric-drafts.js +141 -0
  36. package/workspace/lib/routes-phone-day.js +13 -2
  37. package/workspace/lib/routes-report-setups.js +92 -3
  38. package/workspace/lib/routes-viewer.js +5 -2
  39. package/workspace/lib/settings-store.js +14 -0
  40. package/workspace/metric-drafts-ui-test.js +209 -0
  41. package/workspace/milestone-pins-test.js +13 -0
  42. package/workspace/milestone-suggest-test.js +10 -4
  43. package/workspace/package-lock.json +2 -2
  44. package/workspace/package.json +1 -1
  45. package/workspace/premium-board-actions-test.js +40 -13
  46. package/workspace/premium-phone-card-test.js +8 -5
  47. package/workspace/premium-rec-tab-test.js +8 -0
  48. package/workspace/premium-vw-item-test.js +7 -3
  49. package/workspace/premium-vw-jira-test.js +2 -1
  50. package/workspace/program-charter-test.js +1 -1
  51. package/workspace/program-leave-test.js +2 -2
  52. package/workspace/program-order-test.js +3 -2
  53. package/workspace/program-panel-test.js +2 -1
  54. package/workspace/public/pm/bd-acts.js +23 -29
  55. package/workspace/public/pm/bd-ini-panel.js +90 -32
  56. package/workspace/public/pm/bd-pin-card.css +4 -4
  57. package/workspace/public/pm/bd-pin-card.js +4 -1
  58. package/workspace/public/pm/bd-prog-panel.js +9 -4
  59. package/workspace/public/pm/bd-span.js +22 -12
  60. package/workspace/public/pm/cozy-aud.css +1 -1
  61. package/workspace/public/pm/cozy-board.css +256 -256
  62. package/workspace/public/pm/cozy-ev.css +45 -45
  63. package/workspace/public/pm/cozy-evmodel.js +1 -1
  64. package/workspace/public/pm/cozy-home-rows.css +23 -23
  65. package/workspace/public/pm/cozy-home.css +207 -207
  66. package/workspace/public/pm/cozy-insights.css +207 -108
  67. package/workspace/public/pm/cozy-live-pill.css +5 -5
  68. package/workspace/public/pm/cozy-mtg-present.css +23 -23
  69. package/workspace/public/pm/cozy-nav.js +1 -1
  70. package/workspace/public/pm/cozy-news.js +2 -2
  71. package/workspace/public/pm/cozy-panel.css +29 -29
  72. package/workspace/public/pm/cozy-pick.css +5 -5
  73. package/workspace/public/pm/cozy-rec-now.css +20 -20
  74. package/workspace/public/pm/cozy-rec-present.css +11 -11
  75. package/workspace/public/pm/cozy-rec-tab.css +13 -13
  76. package/workspace/public/pm/cozy-rec-tab.js +12 -3
  77. package/workspace/public/pm/cozy-settings.js +1 -1
  78. package/workspace/public/pm/cozy-steps.css +9 -9
  79. package/workspace/public/pm/cozy-today.css +107 -71
  80. package/workspace/public/pm/cozy-viewer.css +7 -7
  81. package/workspace/public/pm/cozy-viewer.js +157 -23
  82. package/workspace/public/pm/cozy-vw-mtg.css +81 -81
  83. package/workspace/public/pm/cozy-vw-rp.css +53 -53
  84. package/workspace/public/pm/cozy-vw-shell.css +34 -21
  85. package/workspace/public/pm/cozy-vw.css +117 -117
  86. package/workspace/public/pm/cozy-xv.css +11 -11
  87. package/workspace/public/pm/cozy.css +18 -15
  88. package/workspace/public/pm/hi-pop.css +82 -0
  89. package/workspace/public/pm/hi-pop.js +65 -0
  90. package/workspace/public/pm/home-app.js +83 -28
  91. package/workspace/public/pm/home-day.js +131 -26
  92. package/workspace/public/pm/home-ini.css +38 -108
  93. package/workspace/public/pm/home-ini.js +50 -68
  94. package/workspace/public/pm/home-line.css +7 -7
  95. package/workspace/public/pm/home-list.js +41 -4
  96. package/workspace/public/pm/home-phone-card.js +18 -15
  97. package/workspace/public/pm/home-today.js +18 -7
  98. package/workspace/public/pm/ini-more.js +67 -0
  99. package/workspace/public/pm/ini-view-model.js +3 -2
  100. package/workspace/public/pm/ini-view.css +104 -102
  101. package/workspace/public/pm/ini-view.js +16 -8
  102. package/workspace/public/pm/loose-props.css +13 -13
  103. package/workspace/public/pm/metric-drafts.css +82 -0
  104. package/workspace/public/pm/metric-drafts.js +165 -0
  105. package/workspace/public/pm/ms-suggest.css +8 -8
  106. package/workspace/public/pm/order-model.js +85 -0
  107. package/workspace/public/pm/ov-view.css +12 -12
  108. package/workspace/public/pm/premium-board.js +57 -11
  109. package/workspace/public/pm/premium-chart-tab.js +6 -6
  110. package/workspace/public/pm/premium-insights.js +306 -105
  111. package/workspace/public/pm/premium-report-intel.css +56 -0
  112. package/workspace/public/pm/premium-report-intel.js +232 -0
  113. package/workspace/public/pm/premium-shell.js +2 -2
  114. package/workspace/public/pm/premium-vw-file.js +2 -2
  115. package/workspace/public/pm/premium-vw-item.js +3 -1
  116. package/workspace/public/pm/premium-vw-jira.js +2 -0
  117. package/workspace/public/pm/premium.css +127 -128
  118. package/workspace/public/pm/prog-order.css +6 -6
  119. package/workspace/public/pm/prog-order.js +15 -2
  120. package/workspace/public/pm/program-charter.css +23 -23
  121. package/workspace/public/pm/rp-parts.js +2 -2
  122. package/workspace/public/pm/sort-order.css +17 -0
  123. package/workspace/public/pm/sort-order.js +108 -0
  124. package/workspace/public/pm/split-merge.css +15 -15
  125. package/workspace/public/pm/task-card.css +21 -21
  126. package/workspace/public/pm/tk-tasks.css +37 -37
  127. package/workspace/public/pm/tk-view.css +6 -6
  128. package/workspace/public/pm/tk-view.js +3 -2
  129. package/workspace/public/pm/wf-page.css +28 -28
  130. package/workspace/public/pm/wf-page.js +1 -1
  131. package/workspace/public/premium-board.html +1 -0
  132. package/workspace/public/premium-intelligence.html +82 -0
  133. package/workspace/server.js +38 -3
  134. package/workspace/skills/metric-draft.skill +47 -0
  135. package/workspace/sort-order-test.js +201 -0
  136. package/workspace/stage-card-test.js +1 -0
  137. package/workspace/task-card-test.js +1 -1
  138. package/workspace/test-lists/intel-report-ui.json +5 -0
  139. package/workspace/test-lists/intel-report.json +9 -0
  140. package/workspace/test-lists/metric-drafts-ui.json +5 -0
  141. package/workspace/test-lists/metric-drafts.json +9 -0
  142. package/workspace/test-lists/sort-order.json +6 -0
  143. package/workspace/test-lists/viewer-trail.json +5 -0
  144. package/workspace/test-run.js +3 -0
  145. package/workspace/tk-tasks-test.js +5 -3
  146. package/workspace/viewer-trail-test.js +145 -0
  147. package/workspace/public/premium-insights.html +0 -81
@@ -17,13 +17,16 @@
17
17
  * scheduleFor(setup) · registerSchedule(store, setup, opts) · unregisterSchedule(store, setup) the draft-only schedule
18
18
  * askStart / askChange / askCancel / askEnd / fileProposal(file, …) the Ask box
19
19
  * fileFinding / dismissFinding / setFinder / findStart / findEnd the weekly finder
20
+ * stripDismiss(file, { id }) Not now on a report the Intelligence ✦ strip proposed
20
21
  * migrate(root, { runtimeDir, wsId, isHome, titleOf, now }) the dashboard schedules, once
21
22
  * dashboardKeys(root) the dashboard keys the old schedule tick leaves alone (migrated, or held by a setup)
22
23
  * writeDocument(root, setup, slot, markdown, { now }) <state>/reports/<id>/<slot>.md for a dashboard-sourced setup
23
24
  *
24
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:
25
- * setup { id, name, purpose, audience, source: 'work'|'dashboard:<key>', output, schedule, sources[], sections[], learned_from, fixes[],
26
- * product, ws, last_run, def_sha, from? } the PM pressed Set up. `from` is { ask } or { finding }
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 }.
28
+ * 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
+ * It is drafted like a dashboard-sourced one, by the tick in lib/routes-report-setups.js, from the live Intelligence model
27
30
  * change { id, …the fields that changed } the PM edited a recurring report
28
31
  * pause · resume · remove { id } a removed setup is a deleted TEMPLATE: its schedule stops, its documents stay
29
32
  * doc-discard { doc, path } the PM discarded an unissued draft (the file is deleted; this line keeps the record)
@@ -39,8 +42,9 @@
39
42
  * finding-dismiss { id?, pattern } "Not a report": the pattern is not proposed again
40
43
  * finder { cadence?, sources? } the finder settings: weekly | off, and the four sources
41
44
  * migrated { keys[], count } the one-time move of the dashboard schedules
45
+ * strip-dismiss { id } Not now on a report the Intelligence ✦ strip proposed (lib/intel-report.js proposalsOf)
42
46
  *
43
- * FOLD. { setups: Map id → setup, removed: Map id → setup (deleted templates), archived: Set of doc ids, discarded: [{ doc, path, at }], asks: Map, findings: Map, dismissed: { patterns, names }, finder: { cadence, sources }, finds: [], migrated }.
47
+ * FOLD. { setups: Map id → setup, removed: Map id → setup (deleted templates), archived: Set of doc ids, discarded: [{ doc, path, at }], asks: Map, findings: Map, dismissed: { patterns, names }, finder: { cadence, sources }, finds: [], migrated, stripDismissed: Set of strip proposal ids }.
44
48
  * A later line wins field by field; a `remove` moves the setup to `removed` (its name stays on its documents); a line that does not parse, or names an unknown event, is skipped.
45
49
  *
46
50
  * THE BI-WEEKLY PARITY. lib/schedule-logic.js fires a bi-weekly schedule on the first matching weekday slot that is at least 12.5 days after
@@ -57,10 +61,11 @@ const crypto = require('crypto');
57
61
  const logic = require('./schedule-logic.js');
58
62
  const reportDraft = require('./report-draft.js');
59
63
  const docSync = require('./doc-sync.js');
64
+ const IR = require('./intel-report.js');
60
65
 
61
66
  const LEDGER = 'report-setups.jsonl';
62
67
  const EVENTS = Object.freeze(['setup', 'change', 'pause', 'resume', 'remove', 'drafted', 'ask-start', 'proposal', 'proposal-change', 'proposal-cancel', 'ask-end',
63
- 'find-start', 'find-end', 'finding', 'finding-dismiss', 'finder', 'migrated', 'doc-discard', 'doc-archive']);
68
+ 'find-start', 'find-end', 'finding', 'finding-dismiss', 'finder', 'migrated', 'doc-discard', 'doc-archive', 'strip-dismiss']);
64
69
  const OUTPUTS = Object.freeze(['google-slides', 'google-doc', 'google-sheets', 'confluence', 'pdf']);
65
70
  const CADENCES = Object.freeze(['daily', 'weekly', 'bi-weekly', 'monthly']);
66
71
  const DAYS = Object.freeze(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']);
@@ -175,7 +180,9 @@ function checkProposal(input) {
175
180
  if (!oneLine(x.purpose, LIMITS.purpose)) return { ok: false, error: `purpose is one line of 1 to ${LIMITS.purpose} characters` };
176
181
  if (!oneLine(x.audience, LIMITS.audience)) return { ok: false, error: `audience is one line of 1 to ${LIMITS.audience} characters` };
177
182
  const source = x.source == null || x.source === '' ? 'work' : x.source;
178
- if (source !== 'work' && !DASH_RE.test(String(source))) return { ok: false, error: 'source is work, or dashboard:portfolio, dashboard:board:<id> or dashboard:initiative:<id>' };
183
+ if (source !== 'work' && !DASH_RE.test(String(source)) && !IR.isIntelligence(source)) return { ok: false, error: 'source is work, dashboard:portfolio, dashboard:board:<id>, dashboard:initiative:<id> or intelligence:<scope>' };
184
+ let storyline = null;
185
+ if (x.storyline != null) { const c = IR.checkStoryline(x.storyline); if (!c.ok) return c; storyline = c.storyline; }
179
186
  if (!OUTPUTS.includes(x.output)) return { ok: false, error: `output is one of ${OUTPUTS.join(', ')}` };
180
187
  const sch = checkSchedule(x.schedule);
181
188
  if (!sch.ok) return sch;
@@ -196,7 +203,7 @@ function checkProposal(input) {
196
203
  return { ok: true, proposal: {
197
204
  name: x.name.trim(), purpose: x.purpose.trim(), audience: clean(x.audience), source, output: x.output, schedule: sch.schedule,
198
205
  sources: sources.list, sections: sections.list.length ? sections.list : FRAME.slice(), learned_from: x.learned_from ? x.learned_from.trim() : null,
199
- fixes: fixes.list, found, ...(x.product ? { product: clean(x.product) } : {}),
206
+ fixes: fixes.list, found, ...(x.product ? { product: clean(x.product) } : {}), ...(storyline ? { storyline } : {}),
200
207
  } };
201
208
  }
202
209
 
@@ -211,11 +218,11 @@ function checkEvidence(list) {
211
218
  }
212
219
 
213
220
  // ── the fold ─────────────────────────────────────────────────────────────────────────────────────────
214
- const SETUP_FIELDS = ['name', 'purpose', 'audience', 'output', 'schedule', 'sources', 'sections', 'learned_from', 'fixes', 'product', 'def_sha'];
221
+ const SETUP_FIELDS = ['name', 'purpose', 'audience', 'output', 'schedule', 'sources', 'sections', 'learned_from', 'fixes', 'product', 'def_sha', 'storyline'];
215
222
 
216
223
  function fold(lines) {
217
224
  const st = { setups: new Map(), removed: new Map(), archived: new Set(), discarded: [], asks: new Map(), findings: new Map(), dismissed: { patterns: new Set(), names: new Set() },
218
- finder: { cadence: 'weekly', sources: { ...FINDER_DEFAULTS } }, finds: [], migrated: null };
225
+ finder: { cadence: 'weekly', sources: { ...FINDER_DEFAULTS } }, finds: [], migrated: null, stripDismissed: new Set() };
219
226
  for (const l of lines || []) {
220
227
  if (!isObj(l)) continue;
221
228
  switch (l.ev) {
@@ -223,7 +230,8 @@ function fold(lines) {
223
230
  if (!ID_RE.test(String(l.id || '')) || st.setups.has(l.id)) break;
224
231
  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,
225
232
  sources: l.sources || [], sections: l.sections || FRAME.slice(), learned_from: l.learned_from || null, fixes: l.fixes || [], product: l.product || null,
226
- 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: [] });
233
+ 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 } : {}) });
227
235
  if (l.from && l.from.ask) st.asks.delete(l.from.ask);
228
236
  if (l.from && l.from.finding && st.findings.has(l.from.finding)) st.findings.get(l.from.finding).state = 'set-up';
229
237
  break;
@@ -258,6 +266,7 @@ function fold(lines) {
258
266
  case 'finding':
259
267
  if (FINDING_RE.test(String(l.id || '')) && !st.findings.has(l.id)) st.findings.set(l.id, { id: l.id, run: l.run || null, pattern: l.pattern, name: l.name, why: l.why, evidence: l.evidence || [], confidence: l.confidence, proposal: l.proposal, at: l.at, state: 'open' });
260
268
  break;
269
+ case 'strip-dismiss': if (typeof l.id === 'string') st.stripDismissed.add(l.id); break;
261
270
  case 'finding-dismiss': {
262
271
  const f = l.id ? st.findings.get(l.id) : null;
263
272
  if (f) f.state = 'dismissed';
@@ -371,7 +380,7 @@ function definitionText(setup, { product, now = new Date() } = {}) {
371
380
  '## Audience', '', `${setup.audience}. Needs your call holds asks to them only, each with who and by when.`, '',
372
381
  '## Output', '', `The finished report is ${OUTPUT_WORDS[setup.output] || setup.output}. PMOS keeps the report as a document in this repository; a copy is made only when the PM presses Create the copy.`, '',
373
382
  '## Schedule', '', scheduleSentence(setup.schedule, now), '',
374
- '## Sources', '', list(setup.sources, dash ? `- The dashboard ${setup.source.slice('dashboard:'.length)}, as its report frame reads it.` : '- The local ledgers that `pmos report draft` reads.'), '',
383
+ '## Sources', '', list(setup.sources, IR.isIntelligence(setup.source) ? `- Intelligence (${IR.scopeOf(setup.source)}): the KR metric records, health budgets and verdicts it reads.` : dash ? `- The dashboard ${setup.source.slice('dashboard:'.length)}, as its report frame reads it.` : '- The local ledgers that `pmos report draft` reads.'), '',
375
384
  '## Sections', '', 'The script writes the frame and every number. The agent writes only the notes.', '',
376
385
  ...FRAME.map((id, i) => `${i + 1}. ${SECTION_NOTES[id]}`), '',
377
386
  '## Learned from earlier copies', '', setup.learned_from || 'None yet. Add what the earlier copies show after the first cycle.', '',
@@ -509,7 +518,7 @@ function setUp(root, input, opts = {}) {
509
518
  }
510
519
  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,
511
520
  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,
512
- ...(from ? { from } : {}), ...(opts.migrated ? { migrated: true } : {}) }, { now, by: opts.by });
521
+ ...(from ? { from } : {}), ...(opts.migrated ? { migrated: true } : {}), ...(p.storyline ? { storyline: p.storyline } : {}) }, { now, by: opts.by });
513
522
  const next = nextDraftAt(p.schedule, lastRun, now);
514
523
  const folded = fold(readLines(file)).setups.get(id);
515
524
  return { ok: true, setup: folded, definition: def.path, first_draft: next ? { slot: localDay(next), at: next.toISOString(), day: next.getDay() } : null };
@@ -525,7 +534,7 @@ function change(root, id, patch, opts = {}) {
525
534
  if (!merged.ok) return refuse(400, merged.error);
526
535
  const now = opts.now == null ? new Date() : new Date(opts.now);
527
536
  const fields = {};
528
- for (const k of ['name', 'purpose', 'audience', 'output', 'schedule', 'sources', 'sections', 'learned_from', 'fixes']) {
537
+ for (const k of ['name', 'purpose', 'audience', 'output', 'schedule', 'sources', 'sections', 'learned_from', 'fixes', 'storyline']) {
529
538
  if (Object.prototype.hasOwnProperty.call(patch || {}, k) && JSON.stringify(merged.proposal[k]) !== JSON.stringify(cur[k])) fields[k] = merged.proposal[k];
530
539
  }
531
540
  if (!Object.keys(fields).length) return { ok: true, setup: cur, unchanged: true };
@@ -699,6 +708,13 @@ function dismissFinding(file, { id, name, by, now }) {
699
708
  append(file, { ev: 'finding-dismiss', id: l.finding.id, pattern: l.finding.pattern }, { now, by });
700
709
  return { ok: true };
701
710
  }
711
+ /** Not now on a report the Intelligence ✦ strip proposed: that proposal is not offered again. */
712
+ function stripDismiss(file, { id, by, now }) {
713
+ if (typeof id !== 'string' || !/^(found:rf-[0-9a-f]{10}|period-end:\d{4}-\d{2}-\d{2})$/.test(id)) return refuse(400, 'id is a proposal of the strip: found:<finding> or period-end:<date>');
714
+ if (fold(readLines(file)).stripDismissed.has(id)) return { ok: true, unchanged: true };
715
+ append(file, { ev: 'strip-dismiss', id }, { now, by });
716
+ return { ok: true };
717
+ }
702
718
  function setFinder(file, { cadence, sources, by, now }) {
703
719
  const line = {};
704
720
  if (cadence !== undefined) { if (!FINDER_CADENCES.includes(cadence)) return refuse(400, `cadence is ${FINDER_CADENCES.join(' or ')}`); line.cadence = cadence; }
@@ -802,6 +818,6 @@ module.exports = {
802
818
  ledgerFile, stateDir, append, readLines, fold, stateOf, openFindings, isDismissed, slugOf, patternOf, checkProposal, checkEvidence, checkSchedule,
803
819
  scheduleLabel, scheduleOf, firstSlot, initialLastRun, nextDraftAt, definitionText, writeDefinition, definitionsOf, definitionFile, shaOf,
804
820
  fileScheduleStore, scheduleFor, registerSchedule, updateSchedule, unregisterSchedule,
805
- setUp, change, pause, resume, remove, reschedule, discardDraft, archiveDoc, documentAt, askStart, askChange, askCancel, askEnd, fileProposal, findStart, findEnd, fileFinding, dismissFinding, lookupFinding, setFinder,
821
+ setUp, change, pause, resume, remove, reschedule, discardDraft, archiveDoc, documentAt, askStart, askChange, askCancel, askEnd, fileProposal, findStart, findEnd, fileFinding, dismissFinding, stripDismiss, lookupFinding, setFinder,
806
822
  writeDocument, frameMarkdown, migrate, migratedKeys, dashboardKeys, dashTitle, keyOfSource, longDate, localDay,
807
823
  };
@@ -100,6 +100,7 @@ const MODULES = Object.freeze([
100
100
  'routes-premium-charts', // premium-studio-chart: the charts the PM makes in the Insight Studio (premium-charts.jsonl; page-press POST save)
101
101
  'routes-report-design', // report-design-studio: the design studio (describe, samples, turns, versions, This is it), cycle renders and decisions, speaker notes and pins
102
102
  'routes-report-structure', // report-structure: the structure step (turns, versions, Use this structure, sources and their checks, dry run) and the chart store (GET /api/charts)
103
+ 'routes-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)
103
104
  'routes-refresh', // data-refresh-settings: Settings › Data refresh: what refreshes, when, the refresh log, Refresh now
104
105
  ]);
105
106
  const PM_DIR = path.join(__dirname, '..', 'public', 'pm');
@@ -59,7 +59,7 @@ module.exports = {
59
59
  let outcomes, goalMeta = {};
60
60
  try {
61
61
  const today = new Date(), pad = (n) => String(n).padStart(2, '0'), day = today.getFullYear() + '-' + pad(today.getMonth() + 1) + '-' + pad(today.getDate());
62
- const krs = require(repoScript('records/index.js')).list(recordsDirFor(ctx, ws), 'kr-metrics');
62
+ const krs = require(repoScript('records/index.js')).list(recordsDirFor(ctx, ws), 'kr-metrics').filter((k) => k.retired !== true); // an undone ✓ on a drafted metric retires its record
63
63
  outcomes = krs.map((k) => strategy.outcomeOf(k, day));
64
64
  goalMeta = Object.fromEntries(krs.map((k) => [k.rid, k])); // premium-agreed-design: the fields New goal keeps (type, direction, period, owner, …)
65
65
  } catch (e) { return fail('the KR metric records could not be read: ' + ((e && e.message) || e)); }
@@ -92,7 +92,7 @@ module.exports = {
92
92
  const counts = new Map();
93
93
  const goalsIn = (w) => { if (!counts.has(w)) { let n = null; try { n = w === ws ? outcomes.length : require(repoScript('records/index.js')).list(recordsDirFor(ctx, w), 'kr-metrics').length; } catch { n = null; } counts.set(w, n); } return counts.get(w) === null ? {} : { goals: counts.get(w) }; };
94
94
  const model = Insights.build({
95
- now: Date.now(), board: pick ? { ws: pick.ws, id: pick.id, name: pick.name } : { ws, id: null, name: 'Insights' }, boards: all.map((x) => Object.assign({ ws: x.ws, id: x.id, name: x.name }, goalsIn(x.ws))),
95
+ now: Date.now(), board: pick ? { ws: pick.ws, id: pick.id, name: pick.name } : { ws, id: null, name: 'Intelligence' }, boards: all.map((x) => Object.assign({ ws: x.ws, id: x.id, name: x.name }, goalsIn(x.ws))),
96
96
  outcomes, reports: reportsOk ? rp.body.reports || [] : [], reportsOk, missing, saved, mine,
97
97
  setups: setupsOk ? su.body : null, pinned, leads, archived, initiatives, goalMeta, ins, budgets,
98
98
  });
@@ -9,7 +9,9 @@
9
9
  * POST /api/insights-records/chart { ws, board, dash, goal, form, range, compare, target, forecast, note, add } → { ok }
10
10
  * one chart line (lib/insights-records.js); with add, the goal is first added to the dashboard
11
11
  * POST /api/insights-records/describe { ws, text } → { ok, name, question, goals, range, said } reads the goals; writes nothing
12
- * POST /api/insights-records/verdict { ws, board, ini, verdict, learned, goal } → { ok, verdict } one verdict line; the Board is not changed
12
+ * POST /api/insights-records/verdict { ws, board, ini, verdict, learned, goal, drafted } → { ok, verdict } one verdict line; the Board is not changed.
13
+ * Intelligence's "Did it work?" sends Claude's drafted line as `learned` with drafted: true when the PM presses ✓ Keep
14
+ * POST /api/insights-records/verdict-undo { ws, board, ini } → { ok } takes the initiative's verdict back (Undo after ✓ Keep): one verdict-undo line
13
15
  * POST /api/insights-records/target { ws, key: late | scope, target } → { ok, targets }
14
16
  * POST /api/insights-records/tile { ws, key, dir: at least | at most | none, from, chip } → { ok, tiles } how a Delivery trends target is
15
17
  * read (premium-uncovered-features, IsTarget): its direction, the day it counts from and whether the Board chip shows it
@@ -52,7 +54,7 @@ async function handle(req, res, url, ctx) {
52
54
  res.end(IG.exportCsv(m.goals || []));
53
55
  return true;
54
56
  }
55
- if (!['goal', 'steps', 'dashboard', 'chart', 'describe', 'verdict', 'target', 'tile'].includes(what)) return send(bad(404, 'no such insights-records route'));
57
+ if (!['goal', 'steps', 'dashboard', 'chart', 'describe', 'verdict', 'verdict-undo', 'target', 'tile'].includes(what)) return send(bad(404, 'no such insights-records route'));
56
58
  if (req.method !== 'POST') return send(bad(405, 'POST only'));
57
59
  const read = await ctx.readJson(req);
58
60
  if (!read.ok) return send(bad(400, 'the body is not JSON'));
@@ -72,7 +74,7 @@ async function handle(req, res, url, ctx) {
72
74
  if (what === 'goal') {
73
75
  const f = IG.goalFields(body, { today: today() });
74
76
  if (!f.ok) return send(bad(400, f.error));
75
- const r = records().add(recordsDirFor(ctx, w.id), 'kr-metrics', f.fields, UI(), 'New goal from Insights');
77
+ const r = records().add(recordsDirFor(ctx, w.id), 'kr-metrics', f.fields, UI(), 'New goal from Intelligence');
76
78
  return send(r.ok ? { status: 200, body: { ok: true, rid: r.rid, fields: f.fields } } : bad(400, r.reasons.join('; ')));
77
79
  }
78
80
  if (what === 'steps') {
@@ -81,9 +83,9 @@ async function handle(req, res, url, ctx) {
81
83
  if (!cur || !Array.isArray(cur.steps) || !cur.steps.length) return send(bad(404, 'That goal has no steps.'));
82
84
  if (!Array.isArray(body.done) || body.done.length !== cur.steps.length) return send(bad(400, 'Say which of its steps are done.'));
83
85
  const steps = cur.steps.map((s, i) => ({ text: s.text, done: body.done[i] === true })), n = steps.filter((s) => s.done).length, root = recordsDirFor(ctx, w.id);
84
- const e = records().edit(root, 'kr-metrics', cur.rid, { steps }, UI(), 'Steps ticked on Insights');
86
+ const e = records().edit(root, 'kr-metrics', cur.rid, { steps }, UI(), 'Steps ticked on Intelligence');
85
87
  if (!e.ok) return send(bad(400, e.reasons.join('; ')));
86
- const r = records().addReading(root, cur.rid, { at: today(), value: n }, UI(), 'Steps done, from Insights');
88
+ const r = records().addReading(root, cur.rid, { at: today(), value: n }, UI(), 'Steps done, from Intelligence');
87
89
  return send(r.ok ? { status: 200, body: { ok: true, done: n } } : bad(400, r.reasons.join('; ')));
88
90
  }
89
91
  if (what === 'target' || what === 'tile') {
@@ -99,6 +101,12 @@ async function handle(req, res, url, ctx) {
99
101
  const r = IR.append(w.root, 'verdict', body, g.actor, { now });
100
102
  return send(r.ok ? { status: 200, body: { ok: true, verdict: r.line } } : bad(r.status, r.error));
101
103
  }
104
+ if (what === 'verdict-undo') {
105
+ const had = ((IR.read(w.root).verdicts || {})[text(body.board)] || {})[text(body.ini)];
106
+ if (!had) return send(bad(404, 'That initiative has no verdict to take back.'));
107
+ const r = IR.append(w.root, 'verdict-undo', body, g.actor, { now });
108
+ return send(r.ok ? { status: 200, body: { ok: true } } : bad(r.status, r.error));
109
+ }
102
110
  const ks = dashRoutes.krIds(ctx, w.id);
103
111
  if (!ks) return send(bad(503, 'The KR metric records could not be read, so the charts cannot be checked.'));
104
112
  if (what === 'chart') {
@@ -91,6 +91,21 @@ function candidates(ctx, w) {
91
91
  }
92
92
  }
93
93
  } catch { /* no library */ }
94
+ // a document a chat wrote and nobody has committed yet: the library lists tracked files only, so it is read here
95
+ try {
96
+ const seen = new Set(docs.map((d) => d.ref));
97
+ const out = require('child_process').execFileSync('git', ['ls-files', '--others', '--exclude-standard', '-z', '--', '*.md'], { cwd: root, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] });
98
+ for (const rel of out.split('\0').filter(Boolean).slice(0, 2000)) {
99
+ if (seen.has(rel) || isReportPath(rel) || /(^|\/)(node_modules|\.git)\//.test(rel)) continue;
100
+ let title = '', date = '';
101
+ try {
102
+ const full = require('path').join(root, rel), head = fs.readFileSync(full, 'utf8').slice(0, 4096);
103
+ const m = /^---\n[\s\S]*?^title:\s*"?(.+?)"?\s*$/m.exec(head) || /^#\s+(.+)$/m.exec(head);
104
+ title = m ? m[1].trim() : ''; date = fs.statSync(full).mtime.toISOString().slice(0, 10);
105
+ } catch { /* the name stands for it */ }
106
+ docs.push({ kind: 'pmos-doc', ref: rel, title: title || rel.split('/').pop().replace(/\.md$/, ''), date, ini: null, ws: w.id, meta: 'Not committed yet' + (date ? ' · ' + dayText(date) : '') });
107
+ }
108
+ } catch { /* not a git repository */ }
94
109
  try {
95
110
  const rs = require('./routes-report-setups.js');
96
111
  for (const d of rs.documentsOf({ runtimeDir: ctx.runtimeDir, getWs: ctx.getWs }, w).docs || []) {
@@ -121,8 +136,14 @@ function suggest(q, ctx) {
121
136
  const text = str(q.q, 120).toLowerCase();
122
137
  let found = [];
123
138
  if (text.length >= 2) {
139
+ // a search looks in every workspace, this one first: the meeting's workspace is often not the one that holds the document
124
140
  const hit = (x) => (x.title + ' ' + x.ref).toLowerCase().includes(text);
125
- found = [...c.reports.filter(hit), ...c.docs.filter(hit)].sort(newest).slice(0, 8).map((x) => pick(x));
141
+ const others = typeof ctx.workspaceList === 'function' ? (ctx.workspaceList() || []).filter((o) => o && o.root && o.id !== w.id && o.root !== w.root) : [];
142
+ for (const [i, src] of [c, ...others.map((o) => candidates(ctx, o))].entries()) {
143
+ if (found.length >= 8) break;
144
+ const got = [...src.reports.filter(hit), ...src.docs.filter(hit)].sort(newest).map((x) => pick(x));
145
+ found.push(...(i === 0 ? got : got.map((x) => ({ ...x, meta: x.meta + ' · ' + (others[i - 1].name || others[i - 1].id) }))).slice(0, 8 - found.length));
146
+ }
126
147
  }
127
148
  return { status: 200, body: { ok: true, suggested, found } };
128
149
  }
@@ -0,0 +1,141 @@
1
+ 'use strict';
2
+ /* routes-metric-drafts.js — the metrics Claude drafts without being asked (batch 15 item 1; contract metric-drafts-contract.md). The fold is
3
+ * lib/metric-drafts.js; the runs are lib/metric-draft-runs.js (ctx.metricDraftRuns). Only the PM's ✓ keep writes: one kr-metrics record
4
+ * (planning/records/kr-metrics.jsonl through scripts/records, the workspace's folder from lib/records-dir.js).
5
+ *
6
+ * GET /api/metric-drafts?ws=&scope=&id= → { ok, scope, id, title, when, run: { state: idle|running|ready|failed|off, step, reads },
7
+ * rows, head, sub, src } rows [] and run.state idle when nothing is drafted
8
+ * POST /api/metric-drafts/keep { ws, scope, id, row } → { ok, rid } ✓ one row: the record and, when now is known, one reading
9
+ * POST /api/metric-drafts/keep-all { ws, scope, id } → { ok, kept: n, failed } ✓ every open row
10
+ * POST /api/metric-drafts/drop { ws, scope, id, row } → { ok } ✕
11
+ * POST /api/metric-drafts/undo { ws, scope, id, row } → { ok } kept → open (its record edited { retired: true }); dropped → open
12
+ * POST /api/metric-drafts/start { ws, scope, id } → { ok, run } Draft again
13
+ * POST /api/metric-drafts/stop { ws, scope, id } → { ok } ■ Stop: the run ends; what it filed stays a draft
14
+ *
15
+ * WHICH LEDGER. A product's and an initiative's drafts are in the state folder of `ws`. A program's are in its charter's workspace (its home,
16
+ * lib/routes-programs.js all), whatever `ws` says, so a program reads the same from every product.
17
+ *
18
+ * WHO WRITES. As routes-premium-dashboards.js: a POST that carries an agent session header is refused (403), and pm-guard requirePagePress
19
+ * checks the launch nonce and the page's origin. With no state folder the read answers nothing and every write answers 409.
20
+ *
21
+ * wsFor(ctx, ws, scope, id) → the workspace whose ledger holds the scope, or null */
22
+ const guard = require('./pm-guard.js');
23
+ const MD = require('./metric-drafts.js');
24
+ const Runs = require('./metric-draft-runs.js');
25
+ const { repoScript } = require('./repo-script.js');
26
+ const { recordsDirFor } = require('./records-dir.js');
27
+
28
+ const text = (v) => (typeof v === 'string' ? v : '');
29
+ const bad = (status, error) => ({ status, body: { ok: false, error } });
30
+ const records = () => require(repoScript('records/index.js'));
31
+ const UI = () => require(repoScript('trust/ledger.js')).actorFrom({ ui: true });
32
+ const NO_STATE = 'This repository has no PMOS state folder (pmos/state, state or .pmos). Nothing is saved until the folder exists.';
33
+ const todayIso = () => { const d = new Date(); return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0'); };
34
+ const dirOf = (ctx, w) => { try { return ctx.stateDirFor ? ctx.stateDirFor(w) : null; } catch { return null; } };
35
+
36
+ function wsFor(ctx, ws, scope, id) {
37
+ let w = null;
38
+ try { w = ctx.getWs(ws || null); } catch { w = null; }
39
+ if (ws && w && w.id !== ws) w = null;
40
+ if (scope === 'program') {
41
+ try {
42
+ const p = require('./routes-programs.js').all(ctx).find((x) => x.id === id);
43
+ const list = (ctx.workspaceList ? ctx.workspaceList() : []) || [];
44
+ const home = p && list.find((x) => x.id === p.home);
45
+ if (home) return home;
46
+ } catch { /* the programs could not be read: the ledger of `ws` */ }
47
+ }
48
+ return w;
49
+ }
50
+ const offNow = (ctx) => Runs.off(ctx.env || process.env);
51
+ const viewFor = (ctx, w, scope, id) => { const dir = dirOf(ctx, w); return MD.viewOf(dir ? MD.read(dir) : null, scope, id, { off: offNow(ctx) }); };
52
+
53
+ async function handle(req, res, url, ctx) {
54
+ const send = (r) => { ctx.json(res, r.body, r.status); return true; };
55
+ const what = url.pathname.replace(/^\/api\/metric-drafts\/?/, '');
56
+ if (what === '') {
57
+ if (req.method !== 'GET') return send(bad(405, 'GET only'));
58
+ const scope = url.searchParams.get('scope') || '', id = url.searchParams.get('id') || '', ws = url.searchParams.get('ws') || '';
59
+ if (!MD.SCOPES.includes(scope)) return send(bad(400, 'scope is product, program or initiative'));
60
+ const w = wsFor(ctx, ws, scope, id || ws);
61
+ if (!w) return send(bad(404, 'no such workspace'));
62
+ const sid = scope === 'product' ? (id || w.id) : id;
63
+ if (!sid) return send(bad(400, 'id names the program or the initiative'));
64
+ return send({ status: 200, body: { ok: true, ...viewFor(ctx, w, scope, sid) } });
65
+ }
66
+ if (!['keep', 'keep-all', 'drop', 'undo', 'start', 'stop'].includes(what)) return send(bad(404, 'no such metric-drafts route'));
67
+ if (req.method !== 'POST') return send(bad(405, 'POST only'));
68
+ if (req.headers && req.headers['x-pmos-session']) return send(bad(403, 'Only the PM keeps, drops or starts a draft, from the page. A run files drafts with pmos metrics draft.'));
69
+ const read = await ctx.readJson(req);
70
+ if (!read.ok) return send(bad(400, 'the body is not JSON'));
71
+ const body = read.body || {};
72
+ const g = guard.requirePagePress(req, body);
73
+ if (!g.ok) return send(bad(g.status, g.error));
74
+ const scope = text(body.scope);
75
+ if (!MD.SCOPES.includes(scope)) return send(bad(400, 'scope is product, program or initiative'));
76
+ const w = wsFor(ctx, text(body.ws), scope, text(body.id));
77
+ if (!w) return send(bad(404, 'no such workspace'));
78
+ const id = scope === 'product' ? (text(body.id) || w.id) : text(body.id);
79
+ if (!id) return send(bad(400, 'id names the program or the initiative'));
80
+ if (scope === 'product' && id !== w.id) return send(bad(400, 'A product\'s id is its workspace id.'));
81
+ const dir = dirOf(ctx, w);
82
+ if (!dir) return send(bad(409, NO_STATE));
83
+ const at = () => new Date().toISOString();
84
+ const S = () => MD.read(dir).scopes.get(MD.keyOf(scope, id));
85
+
86
+ if (what === 'start') {
87
+ if (!ctx.metricDraftRuns) return send(bad(503, 'Claude\'s runs are off on this server.'));
88
+ const r = ctx.metricDraftRuns.start({ ws: w.id, scope, id, why: 'press' });
89
+ if (!r || !r.ok) return send(bad(409, (r && r.error) || 'Claude could not start drafting.'));
90
+ return send({ status: 200, body: { ok: true, run: r.run } });
91
+ }
92
+ if (what === 'stop') {
93
+ const s = S();
94
+ if (!s || !s.run || s.run.ended) return send(bad(409, 'Claude is not drafting now.'));
95
+ try { if (ctx.metricDraftRuns) ctx.metricDraftRuns.stop(s.run.run); } catch { /* the end line below says it stopped */ }
96
+ MD.append(dir, g.actor, { kind: 'end', scope, id, run: s.run.run, ok: true, stopped: true }, at());
97
+ return send({ status: 200, body: { ok: true } });
98
+ }
99
+ const s = S();
100
+ const root = recordsDirFor(ctx, w.id), today = todayIso();
101
+ const keepOne = (row) => {
102
+ const k = MD.keepFields(scope, id, row, { today });
103
+ if (k.error) return { error: k.error };
104
+ let r;
105
+ try { r = records().add(root, 'kr-metrics', k.fields, UI(), 'Kept a metric Claude drafted'); } catch (e) { return { error: 'The record could not be written: ' + String((e && e.message) || e).slice(0, 160) }; }
106
+ if (!r.ok) return { error: r.reasons.join('; ') };
107
+ if (k.reading) { try { records().addReading(root, r.rid, k.reading, UI(), 'The reading Claude drafted it from'); } catch { /* the record stands; the next reading fills it */ } }
108
+ MD.append(dir, g.actor, { kind: 'keep', scope, id, row: row.id, rid: r.rid }, at());
109
+ return { rid: r.rid };
110
+ };
111
+ if (what === 'keep-all') {
112
+ const open = s ? [...s.rows.values()].filter((r) => r.state === 'open') : [];
113
+ if (!open.length) return send(bad(409, 'There is nothing open to keep.'));
114
+ let kept = 0; const failed = [];
115
+ for (const row of open) { const r = keepOne(row); if (r.rid) kept++; else failed.push({ row: row.id, error: r.error }); }
116
+ return send(kept ? { status: 200, body: { ok: true, kept, failed } } : bad(400, failed[0].error));
117
+ }
118
+ const row = s && s.rows.get(text(body.row));
119
+ if (!row) return send(bad(404, 'There is no such draft.'));
120
+ if (what === 'keep') {
121
+ if (row.state !== 'open') return send(bad(409, row.state === 'kept' ? 'You kept it already.' : 'You dropped it. Undo first.'));
122
+ const r = keepOne(row);
123
+ return send(r.rid ? { status: 200, body: { ok: true, rid: r.rid } } : bad(400, r.error));
124
+ }
125
+ if (what === 'drop') {
126
+ if (row.state !== 'open') return send(bad(409, row.state === 'kept' ? 'You kept it. Undo it first.' : 'You dropped it already.'));
127
+ MD.append(dir, g.actor, { kind: 'drop', scope, id, row: row.id }, at());
128
+ return send({ status: 200, body: { ok: true } });
129
+ }
130
+ // undo: a kept row's record is retired (readers skip it), a dropped row comes back
131
+ if (row.state === 'open') return send(bad(409, 'There is nothing to undo.'));
132
+ if (row.state === 'kept' && row.rid) {
133
+ let e;
134
+ try { e = records().edit(root, 'kr-metrics', row.rid, { retired: true }, UI(), 'Undo of a kept draft'); } catch (x) { e = { ok: false, reasons: [String((x && x.message) || x).slice(0, 160)] }; }
135
+ if (!e.ok && !(e.reasons || []).some((m) => /no such record/.test(m))) return send(bad(400, 'The record could not be retired: ' + (e.reasons || []).join('; ')));
136
+ }
137
+ MD.append(dir, g.actor, { kind: 'undo', scope, id, row: row.id, ...(row.rid ? { rid: row.rid } : {}) }, at());
138
+ return send({ status: 200, body: { ok: true } });
139
+ }
140
+
141
+ module.exports = { prefixes: ['/api/metric-drafts'], handle, wsFor };
@@ -14,6 +14,9 @@
14
14
  * text, sub }: the confirmed decisions first, then the items done, then the drafts.
15
15
  * tomorrow end of the day: the next working day (Monday to Friday) and its meetings, in the shape of GET /api/brief-page today[] rows
16
16
  * (routes-brief-page.js todayAgenda), so the companion opens their briefs the same way.
17
+ * run today's morning prep run (Prepare my day), or null when there is none: { started_at, working, failed: [{ id, title, error }] }.
18
+ * working counts the tasks still waiting, working or sending; failed are the tasks the agent could not finish (at most 3).
19
+ * Your day (batch 15 item 3) says "My part's done" only when working is 0, and names each failed task as Claude's own miss.
17
20
  * A private note is never read. A file that is missing or unreadable counts as empty. */
18
21
  const fs = require('fs');
19
22
  const path = require('path');
@@ -46,6 +49,14 @@ function finishedOf(run) {
46
49
  .sort((a, b) => String(b.at || '').localeCompare(String(a.at || '')));
47
50
  }
48
51
 
52
+ /** Today's run as Your day reads it: what is still under way and what failed. Null when there is no run. */
53
+ function runOf(run) {
54
+ if (!run || !Array.isArray(run.tasks)) return null;
55
+ const T = run.tasks.filter(Boolean);
56
+ return { started_at: run.started_at || null, working: T.filter((t) => ['waiting', 'working', 'sending'].includes(t.status)).length,
57
+ failed: T.filter((t) => t.status === 'failed').slice(0, 3).map((t) => ({ id: t.id, title: clip(t.title, 200), error: clip(t.error, 200) })) };
58
+ }
59
+
49
60
  /** deps: { events, items, run, notes: [note with final_notes], adapter, points: (noteId) → { [pointId]: 'confirmed' | 'wrong' } }
50
61
  * notes are today's non-private notes, read in full. A decision's point id is the Replay's (lib/meeting-replay.js): d1, d2, … in caughtOf order. */
51
62
  function build(query, deps = {}) {
@@ -71,7 +82,7 @@ function build(query, deps = {}) {
71
82
  ...finished.map((t) => ({ kind: 'agent', text: clip(t.title, 200), sub: t.status === 'review' ? 'Drafted by the agent; it waits for you' : 'Finished by the agent' }))].slice(0, 5);
72
83
  const tm = nextWorkday(now);
73
84
  return { status: 200, body: {
74
- ok: true, date: today, finished,
85
+ ok: true, date: today, finished, run: runOf(deps.run),
75
86
  recap: { meetings: agenda.filter((m) => Date.parse(m.end || m.start) <= now.getTime()).length, decided: decisions.length, to_confirm: toConfirm, done: done.length, finished: finished.length, moved },
76
87
  tomorrow: { date: localDate(tm), label: WD[tm.getDay()] + ' ' + tm.getDate() + ' ' + MO[tm.getMonth()], meetings: todayAgenda(events, items, tm, deps.adapter || {}) },
77
88
  } };
@@ -93,7 +104,7 @@ function readRun(dir, date) {
93
104
 
94
105
  module.exports = {
95
106
  prefixes: ['/api/phone-day'],
96
- build, finishedOf, nextWorkday,
107
+ build, finishedOf, nextWorkday, runOf,
97
108
  handle: async (req, res, url, ctx) => {
98
109
  if (url.pathname !== '/api/phone-day') return false;
99
110
  if (req.method !== 'GET') { ctx.json(res, { ok: false, error: 'GET only' }, 405); return true; }
@@ -19,6 +19,12 @@
19
19
  * POST /api/report-setups/remove { ws, id } → { ok } delete a TEMPLATE: its schedule stops; its drafts and issued reports stay (L2)
20
20
  * POST /api/report-setups/from-dashboard { ws, key, name, output, schedule, audience } → { ok, setup }
21
21
  * POST /api/report-setups/finder { ws, cadence?, sources? } → { ok, finder }
22
+ * GET /api/report-setups/storyline?ws&board&scope&story? → { ok, storyline, defaults, checks, proposals } a report from Intelligence (batch 15 item 4,
23
+ * lib/intel-report.js): the draft the side panel opens on, who reads it / how often / the format from history,
24
+ * the five checks on the draft as `story` (the PM's edits, JSON) leaves it, and the ✦ strip's proposals
25
+ * POST /api/report-setups/setup { ws, source: 'intelligence', scope, board?, name, audience, output, schedule, storyline } → as above: sets up a
26
+ * report from Intelligence and drafts issue 1 from the live model (source intelligence:<scope>)
27
+ * POST /api/report-setups/strip-dismiss { ws, id } → { ok } Not now on a report the ✦ strip proposed
22
28
  * GET /api/report-documents?ws → { docs: [{ path, id, setup, name, slot, state: draft|issued, source, output, made_by: schedule|you|agent, v, copy }] }
23
29
  * POST /api/report-documents/discard { ws, path } → { ok, doc } delete an UNISSUED draft; an issued report is 409 and untouched (L3)
24
30
  * POST /api/report-documents/archive { ws, path, archived } → { ok, doc, archived } hide (or bring back) an ISSUED report; a draft is 409 (L4)
@@ -54,7 +60,8 @@ const headless = require('./headless.js');
54
60
 
55
61
  const text = (v) => (typeof v === 'string' ? v : '');
56
62
  const bad = (status, error) => ({ status, body: { ok: false, error } });
57
- const POSTS = ['ask', 'change', 'cancel', 'setup', 'draft', 'dismiss', 'pause', 'resume', 'from-dashboard', 'finder', 'edit', 'remove', 'documents/discard', 'documents/archive'];
63
+ const POSTS = ['ask', 'change', 'cancel', 'setup', 'draft', 'dismiss', 'pause', 'resume', 'from-dashboard', 'finder', 'edit', 'remove', 'documents/discard', 'documents/archive', 'strip-dismiss'];
64
+ const IR = require('./intel-report.js');
58
65
  const MADE_BY = ['schedule', 'you', 'agent'];
59
66
 
60
67
  const runs = new Map(); // ask id → session id, for the report-setup runs this server started
@@ -144,6 +151,7 @@ function setupOut(s, now, docsOf, idx, root, draft) {
144
151
  if (s.status === 'active') { try { const n = RS.nextDraftAt(s.schedule, s.last_run, now); next = n ? n.toISOString() : null; } catch { next = null; } }
145
152
  return {
146
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 || {} } : {}),
147
155
  next_draft: next, last_issued: issued, status: s.status, cycles: mine.length,
148
156
  copy: copyOf(latest ? linkFor(idx, latest.path, s.output) : null, docSync.copyKindOf(s.output)),
149
157
  structure: structureOf(root, s.id),
@@ -231,7 +239,7 @@ async function tick(ctx, now = new Date()) {
231
239
  let st;
232
240
  try { st = RS.stateOf(w.root); } catch { continue; }
233
241
  for (const s of st.setups.values()) {
234
- if (s.status !== 'active' || !String(s.source).startsWith('dashboard:')) continue;
242
+ if (s.status !== 'active' || !(String(s.source).startsWith('dashboard:') || IR.isIntelligence(s.source))) continue;
235
243
  const sched = RS.scheduleOf(s);
236
244
  if (!logic.isDue(sched, now)) continue;
237
245
  const slotAt = logic.lastSlot(sched, now);
@@ -239,6 +247,11 @@ async function tick(ctx, now = new Date()) {
239
247
  const slot = RS.localDay(slotAt);
240
248
  if (s.drafted.some((d) => d.slot === slot)) continue;
241
249
  let out;
250
+ if (IR.isIntelligence(s.source)) {
251
+ try { out = await draftIntelligence({ ...ctx, getWs: (id) => (id === w.id || id == null ? w : ctx.getWs(id)) }, w, s, slot, { now }); } catch (e) { out = { ok: false, error: String((e && e.message) || e) }; }
252
+ done.push({ id: s.id, slot, ...out });
253
+ continue;
254
+ }
242
255
  try {
243
256
  const c3 = require('./routes-c3-reports.js');
244
257
  const deps = await c3.depsFor({ ...ctx, getWs: (id) => (id === w.id || id == null ? w : ctx.getWs(id)) }, w.id);
@@ -285,6 +298,25 @@ async function handle(req, res, url, ctx) {
285
298
  const docPost = p === '/api/report-documents/discard' || p === '/api/report-documents/archive';
286
299
  const sub = docPost ? p.replace(/^\/api\/report-/, '') : isDocs ? 'documents' : isExport ? 'export' : p.replace(/^\/api\/report-setups\/?/, '');
287
300
 
301
+ if (sub === 'storyline') {
302
+ if (req.method !== 'GET') return send(bad(405, 'GET only'));
303
+ const w = wsOf(ctx, url.searchParams.get('ws'));
304
+ if (!w) return send(bad(404, 'no such workspace'));
305
+ const scope = text(url.searchParams.get('scope')) || 'view';
306
+ if (!IR.SCOPE_RE.test(scope)) return send(bad(400, 'scope is view, dashboard:<id>, goal:<id> or outcome:<id>'));
307
+ const m = await intelModel(req, ctx, w.id, url.searchParams.get('board'));
308
+ if (!m) return send(bad(500, 'Intelligence could not be read, so there is no draft.'));
309
+ const st = RS.fold(RS.readLines(RS.ledgerFile(w.root)));
310
+ const findings = RS.openFindings(st);
311
+ // ?story= the PM's edits so far ({ answer, ask, items }): the draft is redrawn with them and the five checks run on that preview
312
+ let story = {};
313
+ if (url.searchParams.get('story')) { let raw = null; try { raw = JSON.parse(url.searchParams.get('story')); } catch { raw = null; } const c = IR.checkStoryline(raw); if (!c.ok) return send(bad(400, c.error)); story = c.storyline; }
314
+ const S = IR.storylineOf(m, { scope, ask: story.ask, items: story.items });
315
+ if (story.answer) S.answer = story.answer;
316
+ const defaults = IR.defaultsOf(findings, scope, S.name);
317
+ const preview = IR.documentOf(m, { id: 'preview', name: S.name, audience: defaults.audience, output: defaults.output, source: IR.sourceOf(scope), storyline: story }, { slot: m.today, issue: 1 });
318
+ return send({ status: 200, body: { ok: true, storyline: S, defaults, checks: IR.storyChecks(preview), proposals: IR.proposalsOf(m, { findings, dismissed: [...st.stripDismissed] }), as_of: m.today } });
319
+ }
288
320
  if (!docPost && (isDocs || isExport || (sub === '' && req.method === 'GET'))) {
289
321
  if (req.method !== 'GET') return send(bad(405, 'GET only'));
290
322
  if ((isDocs && p !== '/api/report-documents') || (isExport && p !== '/api/report-export')) return send(bad(404, 'no such report route'));
@@ -346,6 +378,30 @@ async function handle(req, res, url, ctx) {
346
378
  if (sid && typeof ctx.stopSession === 'function') { try { ctx.stopSession(sid); } catch { /* the run ends by itself */ } }
347
379
  return send({ status: 200, body: { ok: true } });
348
380
  }
381
+ if (sub === 'setup' && body.source === 'intelligence') {
382
+ const scope = text(body.scope) || 'view';
383
+ if (!IR.SCOPE_RE.test(scope)) return send(bad(400, 'scope is view, dashboard:<id>, goal:<id> or outcome:<id>'));
384
+ const m = await intelModel(req, ctx, w.id, text(body.board) || null);
385
+ if (!m) return send(bad(500, 'Intelligence could not be read, so nothing was set up.'));
386
+ const name = text(body.name).trim() || IR.scopeName(m, scope);
387
+ const audience = text(body.audience).trim();
388
+ if (!audience) return send(bad(400, 'say who reads it'));
389
+ const finding = text(body.finding) ? RS.lookupFinding(RS.fold(RS.readLines(file)), text(body.finding)) : null;
390
+ const proposal = { name, purpose: `${name} from Intelligence for ${audience}: the answer first, the scorecard, and what needs a decision.`, audience, source: IR.sourceOf(scope),
391
+ output: text(body.output) || 'pdf', schedule: body.schedule, sources: [`Intelligence · ${IR.scopeName(m, scope)}`], sections: RS.FRAME.slice(), learned_from: 'Set up from Intelligence.', fixes: [],
392
+ storyline: body.storyline || {}, ...(finding && finding.ok ? { from: { finding: finding.finding.id } } : {}) };
393
+ const r = RS.setUp(root, proposal, opts);
394
+ if (!r.ok) return fail(r);
395
+ let drafted = { error: 'no first draft day' };
396
+ if (r.first_draft) { try { drafted = await draftIntelligence(ctx, w, r.setup, r.first_draft.slot, { model: m, now: new Date() }); } catch (e) { drafted = { error: String((e && e.message) || e) }; } }
397
+ if (drafted.path && ctx.invalidateNeedsAgg) ctx.invalidateNeedsAgg();
398
+ return send({ status: 200, body: { ok: true, setup: setupOut(r.setup, new Date(), documentsOf(ctx, w), copyIndex(root), root), first_draft: r.first_draft, drafted } });
399
+ }
400
+ if (sub === 'strip-dismiss') {
401
+ const r = RS.stripDismiss(file, { id: text(body.id), by: g.actor });
402
+ if (!r.ok) return fail(r);
403
+ return send({ status: 200, body: { ok: true } });
404
+ }
349
405
  if (sub === 'setup') {
350
406
  const st = RS.fold(RS.readLines(file));
351
407
  let from = null; let base = null;
@@ -371,6 +427,14 @@ async function handle(req, res, url, ctx) {
371
427
  // Draft it now: the next cycle of a set-up report, written at the slot of its next scheduled draft. A page write, like Draft now on the report.
372
428
  const s = RS.fold(RS.readLines(file)).setups.get(text(body.id));
373
429
  if (!s || s.status === 'removed') return send(bad(404, 'no such report'));
430
+ if (IR.isIntelligence(s.source)) {
431
+ let next = null; try { next = RS.nextDraftAt(s.schedule, s.last_run, new Date()); } catch { next = null; }
432
+ if (!next) return send(bad(400, 'this report has no next draft day'));
433
+ const d = await draftIntelligence(ctx, w, s, RS.localDay(next), { now: new Date() });
434
+ if (!d.ok && !d.existing) return send(bad(d.status || 500, 'the draft was not written: ' + d.error));
435
+ if (ctx.invalidateNeedsAgg) ctx.invalidateNeedsAgg();
436
+ return send({ status: 200, body: { ok: true, drafted: { slot: d.slot, path: d.path, existing: !!d.existing }, id: s.id + '/' + d.slot } });
437
+ }
374
438
  if (s.source !== 'work') return send(bad(400, 'a dashboard report is drafted from its dashboard on its day'));
375
439
  let next = null; try { next = RS.nextDraftAt(s.schedule, s.last_run, new Date()); } catch { next = null; }
376
440
  const day = next ? `${next.getFullYear()}-${String(next.getMonth() + 1).padStart(2, '0')}-${String(next.getDate()).padStart(2, '0')}` : null; // the local day, as setUp names a slot
@@ -435,6 +499,31 @@ async function handle(req, res, url, ctx) {
435
499
  return send(bad(404, 'no such report route'));
436
500
  }
437
501
 
502
+ /** The Intelligence model, through its page's own read (as lib/routes-insights-records.js does), so a report says what the page shows. null when it cannot be read. */
503
+ async function intelModel(req, ctx, ws, board) {
504
+ let out = null;
505
+ const c = Object.assign({}, ctx, { json: (res, obj) => { out = obj; } });
506
+ const u = new URL('http://local/api/insights-premium?' + new URLSearchParams(Object.entries({ ws, board }).filter(([, v]) => v)).toString());
507
+ try { await require('./routes-insights-premium.js').handle({ method: 'GET', headers: (req && req.headers) || {} }, {}, u, c); } catch { return null; }
508
+ return out && out.ok ? out.model : null;
509
+ }
510
+ /** 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
511
+ * 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.
512
+ * → { ok, slot, path } | { ok: false, existing?, error } */
513
+ async function draftIntelligence(ctx, w, s, slot, { model, now = new Date() } = {}) {
514
+ const rel = RD.draftPath(path.resolve(w.root), s.id, slot);
515
+ 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 */ }
516
+ const m = model || await intelModel(null, ctx, w.id, null);
517
+ if (!m) return { ok: false, error: 'Intelligence could not be read' };
518
+ const mine = (RN.reportsOf(w.root).reports || []).filter((x) => x.cadence === s.id && x.slot < slot).sort((a, b) => (a.slot < b.slot ? -1 : 1));
519
+ const before = mine.filter((x) => x.issued).pop() || null;
520
+ let prior = null;
521
+ if (before) { try { prior = fs.readFileSync(path.join(path.resolve(w.root), before.path), 'utf8'); } catch { prior = null; } }
522
+ const md = IR.documentOf(m, s, { slot, now, issue: mine.length + 1, prior });
523
+ const r = RS.writeDocument(w.root, s, slot, md, { now });
524
+ return r.ok ? { ok: true, slot, path: r.path } : { ok: false, status: r.status, error: r.error };
525
+ }
526
+
438
527
  /** Draft a report's cycle now through the one writer (report-draft.js writeDraft). → { slot, path } | { error } */
439
528
  function draftCycle(root, cadence, slot, actor) {
440
529
  const d = RD.draftOf(root, { cadence, slot: slot || undefined });
@@ -450,4 +539,4 @@ function firstDraft(root, r, actor) {
450
539
  return draftCycle(root, r.setup.id, r.first_draft && r.first_draft.slot, actor);
451
540
  }
452
541
 
453
- module.exports = { prefixes: ['/api/report-setups', '/api/report-documents', '/api/report-export'], handle, tick, ensureMigrated, documentsOf, listAnswer, copyOf };
542
+ module.exports = { prefixes: ['/api/report-setups', '/api/report-documents', '/api/report-export'], handle, tick, ensureMigrated, documentsOf, listAnswer, copyOf, draftIntelligence, intelModel };