create-pmos 0.386.0 → 0.388.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 (39) hide show
  1. package/package.json +30 -30
  2. package/payload/KIT-VERSION +1 -1
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/state/discoveries.md +1 -1
  6. package/workspace/briefing-premium-calendar-test.js +2 -1
  7. package/workspace/briefing-premium-initiative-test.js +4 -0
  8. package/workspace/briefing-premium-insights-test.js +1 -1
  9. package/workspace/briefing-premium-test.js +1 -1
  10. package/workspace/c3-settings-test.js +1 -1
  11. package/workspace/changelog.json +29 -0
  12. package/workspace/fixtures/initiative-premium-facts.js +1 -1
  13. package/workspace/guide/briefing-premium.md +5 -1
  14. package/workspace/guide/report-design.md +1 -1
  15. package/workspace/lib/core-docs.js +33 -4
  16. package/workspace/lib/initiative-premium.js +1 -0
  17. package/workspace/lib/lead-cli.js +27 -3
  18. package/workspace/lib/pmos-verbs.js +1 -1
  19. package/workspace/lib/popup-leads.js +46 -1
  20. package/workspace/lib/refresh-run.js +22 -5
  21. package/workspace/lib/refresh.js +6 -1
  22. package/workspace/lib/report-design.js +16 -2
  23. package/workspace/lib/report-setups.js +49 -7
  24. package/workspace/lib/routes-briefing-premium.js +13 -0
  25. package/workspace/lib/routes-report-design.js +8 -1
  26. package/workspace/lib/routes-report-setups.js +38 -7
  27. package/workspace/package-lock.json +2 -2
  28. package/workspace/package.json +1 -1
  29. package/workspace/premium-board-actions-test.js +1 -1
  30. package/workspace/premium-briefing-depth-test.js +1 -1
  31. package/workspace/premium-report-read-test.js +11 -4
  32. package/workspace/premium-studio-report-test.js +11 -2
  33. package/workspace/public/pm/premium-initiative.js +7 -4
  34. package/workspace/public/pm/premium-report-read.js +17 -2
  35. package/workspace/public/pm/premium-shell.js +10 -0
  36. package/workspace/public/pm/premium-studio-design.js +15 -3
  37. package/workspace/public/pm/premium.css +8 -0
  38. package/workspace/server.js +2 -0
  39. package/workspace/skills/popup-leads.skill +31 -0
@@ -6,6 +6,7 @@
6
6
  * readEvents(root, cadence) · fold(events) → the current state (see FOLD)
7
7
  * designAnswer(root, cadence, { running }) → the `design` object GET /api/report-design answers
8
8
  * addSample(root, cadence, input, { actor }) → { ok, sample } | { ok: false, status, error } a file (20 MB, pdf/pptx/docx/png/jpg), a link or a report doc
9
+ * removeSample(root, cadence, id, { actor }) → { ok, sample: { id, name } } | refusal the design stops following the sample
9
10
  * writeVersion(root, cadence, html, meta) → { ok, n, outline } sanitizes, writes versions/D<n>.html + D<n>.json
10
11
  * writeBrief(root, cadence, setup, st) → brief.md (type Reference)
11
12
  * sanitize(html) → the render with no script, no on* attribute, no javascript: and no external URL (data: images kept, one style block)
@@ -19,6 +20,8 @@
19
20
  * THE LINES of design.jsonl. Every line is { ev, …, at, actor }. `actor` is the guard's actor for a press, or { by: 'pmos', via: 'job' } for a job:
20
21
  * describe { text, format } the PM's plain words, and Deck or Document
21
22
  * sample { id, name, kind, source, ext, readable } a sample was added (the file is samples/<id>.<ext>, its record samples/<id>.json)
23
+ * unsample { id, name } the PM removed a sample: the next version, the brief and each cycle stop following it.
24
+ * Its files stay in samples/ (the log is append-only); nothing reads them again.
22
25
  * fetched { id, ok, via?, title?, reason? } a link sample was read through the PM's connectors (ok), or could not be (reason); the words are samples/<id>.txt
23
26
  * took { id, took, readable } what a job took from a sample (or that it could not read it)
24
27
  * turn { text, points, base, job } a refine turn started a job; `base` is the version it builds on
@@ -45,7 +48,7 @@ const zlib = require('zlib');
45
48
  const RD = require('./report-draft.js');
46
49
  const issues = require('./issues.js');
47
50
 
48
- const EVENTS = Object.freeze(['describe', 'sample', 'fetched', 'took', 'turn', 'version', 'accept', 'revert', 'error', 'cycle-decision']);
51
+ const EVENTS = Object.freeze(['describe', 'sample', 'unsample', 'fetched', 'took', 'turn', 'version', 'accept', 'revert', 'error', 'cycle-decision']);
49
52
  const FORMATS = Object.freeze(['deck', 'doc']);
50
53
  const SAMPLE_KINDS = Object.freeze(['pdf', 'pptx', 'docx', 'image', 'pictures', 'link', 'pmos-doc']);
51
54
  const MAX_PICTURES = 12;
@@ -122,6 +125,9 @@ function fold(events) {
122
125
  st.samples.set(l.id, { id: l.id, name: str(l.name), kind: l.kind, source: str(l.source), ext: str(l.ext), took: null, readable: l.readable !== false, at: l.at,
123
126
  ...(l.via === 'chrome' ? { via: 'chrome' } : {}), ...(Number.isInteger(l.count) ? { count: l.count } : {}), ...(Number.isInteger(l.pages) ? { pages: l.pages } : {}) });
124
127
  st.log.push({ at: l.at, who: 'you', kind: 'sample', text: str(l.name), sample: l.id });
128
+ } else if (l.ev === 'unsample') {
129
+ const s = st.samples.get(l.id);
130
+ if (s) { st.samples.delete(l.id); st.log.push({ at: l.at, who: 'you', kind: 'unsample', text: `Removed the sample "${s.name}".`, sample: l.id }); }
125
131
  } else if (l.ev === 'fetched') {
126
132
  const s = st.samples.get(l.id);
127
133
  if (s) { s.readable = l.ok === true; s.fetched = l.ok === true; s.fetch_reason = l.ok === true ? null : str(l.reason) || 'no reason'; }
@@ -287,6 +293,14 @@ function addSample(root, cadence, input, { actor, now } = {}) {
287
293
  ...(rec.via ? { via: rec.via } : {}), ...(rec.count ? { count: rec.count } : {}), ...(rec.pages ? { pages: rec.pages } : {}) }, { actor, now });
288
294
  return { ok: true, sample: sampleOut(rec) };
289
295
  }
296
+ /** Remove a sample: an 'unsample' line. The fold drops it, so the job lines, brief.md and the GET answer no longer name it. */
297
+ function removeSample(root, cadence, id, { actor, now } = {}) {
298
+ if (!SAMPLE_ID_RE.test(String(id))) return refuse(400, 'sample must be a sample id');
299
+ const s = stateOf(root, cadence).samples.get(id);
300
+ if (!s) return refuse(404, 'no such sample');
301
+ append(root, cadence, { ev: 'unsample', id, name: s.name }, { actor, now });
302
+ return { ok: true, sample: { id, name: s.name } };
303
+ }
290
304
  function sampleOut(s, { fetching } = {}) {
291
305
  const out = { id: s.id, name: s.name, kind: s.kind, source: s.source, took: s.took || null, thumb: typeof s.thumb === 'string' && s.thumb.startsWith('data:image/') ? s.thumb : null, readable: s.readable !== false };
292
306
  if (s.via === 'chrome') {
@@ -839,7 +853,7 @@ function currentCycle(root, cadence) {
839
853
  module.exports = {
840
854
  EVENTS, FORMATS, SAMPLE_KINDS, MAX_SAMPLE_BYTES, CHOICES, PIN_OPS, CADENCE_RE, SLOT_RE, SLIDE_ID_RE, PMOS_ACTOR,
841
855
  paths, append, readEvents, fold, stateOf, designAnswer, versionMeta, versionHtml, writeVersion, rulesFor, cleanRules,
842
- addSample, sampleOut, sampleRecord, recordTook, recordFetched, fetchableLink, googleKind, sampleReadPath, writeBrief,
856
+ addSample, removeSample, sampleOut, sampleRecord, recordTook, recordFetched, fetchableLink, googleKind, sampleReadPath, writeBrief,
843
857
  tokenize, sanitize, cleanCss, outlineOf, formatOf, diffOutline,
844
858
  cyclePaths, readCycle, writeCycle, decideCycle, isIssuedSlot, docSha, currentCycle, previousCycle,
845
859
  notesOf, setSpeaker, pinOp, ooxmlText, ooxmlThumb, unzipSome,
@@ -12,6 +12,8 @@
12
12
  * firstSlot(schedule, now) · initialLastRun(schedule, now) · nextDraftAt(schedule, lastRun, now) the bi-weekly parity (below)
13
13
  * definitionText(setup, { product, now }) · writeDefinition(root, setup, { now }) the definition a setup writes
14
14
  * setUp(root, input, opts) · change(root, id, patch, opts) · pause / resume / remove(root, id, opts) the PM's presses
15
+ * reschedule(root, id, schedule, opts) a template's new schedule; { cadence: 'off' } pauses it, any other resumes a paused one
16
+ * discardDraft(root, rel, opts) · archiveDoc(root, rel, archived, opts) a document's presses. AN ISSUED REPORT IS NEVER DELETED: discard refuses it
15
17
  * scheduleFor(setup) · registerSchedule(store, setup, opts) · unregisterSchedule(store, setup) the draft-only schedule
16
18
  * askStart / askChange / askCancel / askEnd / fileProposal(file, …) the Ask box
17
19
  * fileFinding / dismissFinding / setFinder / findStart / findEnd the weekly finder
@@ -23,7 +25,9 @@
23
25
  * setup { id, name, purpose, audience, source: 'work'|'dashboard:<key>', output, schedule, sources[], sections[], learned_from, fixes[],
24
26
  * product, ws, last_run, def_sha, from? } the PM pressed Set up. `from` is { ask } or { finding }
25
27
  * change { id, …the fields that changed } the PM edited a recurring report
26
- * pause · resume · remove { id }
28
+ * pause · resume · remove { id } a removed setup is a deleted TEMPLATE: its schedule stops, its documents stay
29
+ * doc-discard { doc, path } the PM discarded an unissued draft (the file is deleted; this line keeps the record)
30
+ * doc-archive { doc, archived } the PM archived (true) or brought back (false) an issued report. The file is never touched
27
31
  * drafted { id, slot, path } a dashboard-sourced setup made its document (this is its last run)
28
32
  * ask-start { ask, text, ws } the PM typed a request in the Ask box
29
33
  * proposal { ask, proposal } the report-setup run filed ONE proposal (a second one revises it)
@@ -36,8 +40,8 @@
36
40
  * finder { cadence?, sources? } the finder settings: weekly | off, and the four sources
37
41
  * migrated { keys[], count } the one-time move of the dashboard schedules
38
42
  *
39
- * FOLD. { setups: Map id → setup, asks: Map, findings: Map, dismissed: { patterns, names }, finder: { cadence, sources }, finds: [], migrated }.
40
- * A later line wins field by field; a `remove` drops the setup; a line that does not parse, or names an unknown event, is skipped.
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 }.
44
+ * 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.
41
45
  *
42
46
  * 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
43
47
  * lastRun. A schedule added on a Monday would therefore draft on the Wednesday two weeks out, whatever week the session is in. With an
@@ -56,7 +60,7 @@ const docSync = require('./doc-sync.js');
56
60
 
57
61
  const LEDGER = 'report-setups.jsonl';
58
62
  const EVENTS = Object.freeze(['setup', 'change', 'pause', 'resume', 'remove', 'drafted', 'ask-start', 'proposal', 'proposal-change', 'proposal-cancel', 'ask-end',
59
- 'find-start', 'find-end', 'finding', 'finding-dismiss', 'finder', 'migrated']);
63
+ 'find-start', 'find-end', 'finding', 'finding-dismiss', 'finder', 'migrated', 'doc-discard', 'doc-archive']);
60
64
  const OUTPUTS = Object.freeze(['google-slides', 'google-doc', 'google-sheets', 'confluence', 'pdf']);
61
65
  const CADENCES = Object.freeze(['daily', 'weekly', 'bi-weekly', 'monthly']);
62
66
  const DAYS = Object.freeze(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']);
@@ -210,7 +214,7 @@ function checkEvidence(list) {
210
214
  const SETUP_FIELDS = ['name', 'purpose', 'audience', 'output', 'schedule', 'sources', 'sections', 'learned_from', 'fixes', 'product', 'def_sha'];
211
215
 
212
216
  function fold(lines) {
213
- const st = { setups: new Map(), asks: new Map(), findings: new Map(), dismissed: { patterns: new Set(), names: new Set() },
217
+ 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() },
214
218
  finder: { cadence: 'weekly', sources: { ...FINDER_DEFAULTS } }, finds: [], migrated: null };
215
219
  for (const l of lines || []) {
216
220
  if (!isObj(l)) continue;
@@ -232,7 +236,9 @@ function fold(lines) {
232
236
  }
233
237
  case 'pause': { const s = st.setups.get(l.id); if (s) s.status = 'paused'; break; }
234
238
  case 'resume': { const s = st.setups.get(l.id); if (s) { s.status = 'active'; if (l.last_run) s.last_run = l.last_run; } break; }
235
- case 'remove': st.setups.delete(l.id); break;
239
+ 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; }
240
+ 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;
241
+ case 'doc-archive': if (typeof l.doc === 'string') { if (l.archived === false) st.archived.delete(l.doc); else st.archived.add(l.doc); } break;
236
242
  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; }
237
243
  case 'ask-start':
238
244
  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: [] });
@@ -560,6 +566,42 @@ function remove(root, id, opts = {}) {
560
566
  return { ok: true };
561
567
  }
562
568
 
569
+ /** A template's schedule, as the PM changes it. { cadence: 'off' } is Schedule Off: the template pauses and keeps its schedule for later.
570
+ * Any other schedule is checked, changed through change(), and resumes a paused template. → { ok, setup } | { ok: false, status, error } */
571
+ function reschedule(root, id, schedule, opts = {}) {
572
+ if (isObj(schedule) && schedule.cadence === 'off') return setStatus(root, id, 'pause', opts);
573
+ const c = checkSchedule(schedule);
574
+ if (!c.ok) return refuse(400, c.error);
575
+ const r = change(root, id, { schedule: c.schedule }, opts);
576
+ if (!r.ok) return r;
577
+ return r.setup && r.setup.status === 'paused' ? setStatus(root, id, 'resume', opts) : r;
578
+ }
579
+
580
+ /** The report document at `rel` (repository-relative), as report-needs lists it, else null. */
581
+ function documentAt(root, rel) {
582
+ const list = require('./report-needs.js').reportsOf(root).reports || [];
583
+ return list.find((x) => x.path === String(rel || '')) || null;
584
+ }
585
+
586
+ /** Discard an unissued draft: the file is deleted and a doc-discard line keeps the record. An issued report is refused (409) and not touched. */
587
+ function discardDraft(root, rel, opts = {}) {
588
+ const d = documentAt(root, rel);
589
+ if (!d) return refuse(404, 'no such report document');
590
+ if (d.issued) return refuse(409, 'this report was issued, so it is kept for good. You can archive it instead');
591
+ try { fs.rmSync(path.join(path.resolve(String(root)), d.path)); } catch (e) { return refuse(500, 'the draft was not deleted: ' + String((e && e.message) || e).slice(0, 160)); }
592
+ append(ledgerFile(root), { ev: 'doc-discard', doc: `${d.cadence}/${d.slot}`, path: d.path }, { now: opts.now, by: opts.by });
593
+ return { ok: true, doc: `${d.cadence}/${d.slot}` };
594
+ }
595
+
596
+ /** Archive (archived true) or bring back (false) an issued report. Only a line is written; the file is never touched. A draft is refused (409). */
597
+ function archiveDoc(root, rel, archived, opts = {}) {
598
+ const d = documentAt(root, rel);
599
+ if (!d) return refuse(404, 'no such report document');
600
+ if (!d.issued) return refuse(409, 'only an issued report is archived. Discard a draft instead');
601
+ append(ledgerFile(root), { ev: 'doc-archive', doc: `${d.cadence}/${d.slot}`, archived: archived !== false }, { now: opts.now, by: opts.by });
602
+ return { ok: true, doc: `${d.cadence}/${d.slot}`, archived: archived !== false };
603
+ }
604
+
563
605
  // ── the Ask box ──────────────────────────────────────────────────────────────────────────────────────
564
606
  function askStart(file, { text, ws, by, now }) {
565
607
  if (!oneLine(String(text || '').replace(/\s+/g, ' '), LIMITS.text)) return refuse(400, `say what report you want, in up to ${LIMITS.text} characters`);
@@ -760,6 +802,6 @@ module.exports = {
760
802
  ledgerFile, stateDir, append, readLines, fold, stateOf, openFindings, isDismissed, slugOf, patternOf, checkProposal, checkEvidence, checkSchedule,
761
803
  scheduleLabel, scheduleOf, firstSlot, initialLastRun, nextDraftAt, definitionText, writeDefinition, definitionsOf, definitionFile, shaOf,
762
804
  fileScheduleStore, scheduleFor, registerSchedule, updateSchedule, unregisterSchedule,
763
- setUp, change, pause, resume, remove, askStart, askChange, askCancel, askEnd, fileProposal, findStart, findEnd, fileFinding, dismissFinding, lookupFinding, setFinder,
805
+ setUp, change, pause, resume, remove, reschedule, discardDraft, archiveDoc, documentAt, askStart, askChange, askCancel, askEnd, fileProposal, findStart, findEnd, fileFinding, dismissFinding, lookupFinding, setFinder,
764
806
  writeDocument, frameMarkdown, migrate, migratedKeys, dashboardKeys, dashTitle, keyOfSource, longDate, localDay,
765
807
  };
@@ -191,6 +191,19 @@ module.exports = {
191
191
  ctx.json(res, key ? Goal.onStop({ runtimeDir: ctx.runtimeDir, key, message: body.last_assistant_message }) : {});
192
192
  return true;
193
193
  }
194
+ if (url.pathname === '/api/briefing-premium/seen') {
195
+ // popup context slice 3b: a popup the PM opened, with what it showed, so the leads session after a refresh writes its lead. Starts nothing.
196
+ if (req.method !== 'POST') { ctx.json(res, { ok: false, error: 'POST only' }, 405); return true; }
197
+ if (req.headers && req.headers['x-pmos-session']) { ctx.json(res, { ok: false, error: 'an agent session cannot record what the PM opened' }, 403); return true; }
198
+ const got = await ctx.readJson(req);
199
+ if (!got.ok || !got.body || typeof got.body !== 'object') { ctx.json(res, { ok: false, error: 'body must be JSON' }, 400); return true; }
200
+ const g = guard.requirePagePress(req, got.body);
201
+ if (!g.ok) { ctx.json(res, { ok: false, error: g.error }, g.status); return true; }
202
+ const t = ctx.runtimeDir ? Leads.seen(ctx.runtimeDir, got.body) : null;
203
+ if (!t) { ctx.json(res, { ok: false, error: 'key must be a popup key, pop:<kind>:<id>, of a popup that is not a form, with a title' }, 400); return true; }
204
+ ctx.json(res, { ok: true, key: t.key, at: t.at });
205
+ return true;
206
+ }
194
207
  if (url.pathname.startsWith('/api/briefing-premium/') && POSTS.includes(url.pathname.slice('/api/briefing-premium/'.length))) {
195
208
  if (req.method !== 'POST') { ctx.json(res, { ok: false, error: 'POST only' }, 405); return true; }
196
209
  return post(req, res, url, ctx);
@@ -5,6 +5,7 @@
5
5
  * GET /api/report-design/version?ws&id&n → text/html, the sanitized render of D<n>
6
6
  * POST /api/report-design/describe { ws, id, text, format? }
7
7
  * POST /api/report-design/sample { ws, id, name, kind, data } | { ws, id, link, name? } | { ws, id, doc, name? } → { ok, sample }
8
+ * POST /api/report-design/unsample { ws, id, sample } → { ok, design } the design stops following that sample; a saved design's brief.md is written again
8
9
  * from Chrome: { kind: 'pdf', data, from: 'chrome', source_url?, pages? } | { kind: 'pictures', pictures: [base64 JPEG or PNG, …], source_url?, name, from: 'chrome' } (the field is `from`: pm-guard reserves `via` for the writer; the record keeps via: 'chrome')
9
10
  * GET /api/report-design/last?ws → { ok, id, name, at } the report whose design studio was opened last (the Chrome popup's default report); id null when none
10
11
  * POST /api/report-design/turn { ws, id, text, points: [{ n, slide, x, y, text }] } → { ok, running } ONE job per report; 409 while one runs
@@ -50,7 +51,7 @@ const headless = require('./headless.js');
50
51
  const text = (v) => (typeof v === 'string' ? v : '');
51
52
  const bad = (status, error) => ({ status, body: { ok: false, error } });
52
53
  const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
53
- const DESIGN_POSTS = ['describe', 'sample', 'turn', 'accept', 'revert', 'cycle-decision'];
54
+ const DESIGN_POSTS = ['describe', 'sample', 'unsample', 'turn', 'accept', 'revert', 'cycle-decision'];
54
55
  const NOTES_POSTS = ['speaker', 'pin'];
55
56
  const HTML_CSP = "default-src 'none'; img-src data:; style-src 'unsafe-inline'; font-src data:";
56
57
 
@@ -560,6 +561,12 @@ async function handle(req, res, url, ctx) {
560
561
  }
561
562
  return send({ status: 200, body: { ok: true, sample: r.sample } });
562
563
  }
564
+ if (sub === 'unsample') {
565
+ const r = D.removeSample(root, id, text(body.sample), { actor: g.actor });
566
+ if (!r.ok) return fail(r);
567
+ if (D.stateOf(root, id).saved) { const b = D.writeBrief(root, id, setup); if (!b.ok) return fail(b); }
568
+ return answer();
569
+ }
563
570
  if (sub === 'turn') {
564
571
  if (jobs.has(keyOf(root, id))) return send(bad(409, 'PMOS is already working on this report. Wait for the answer, then try again.'));
565
572
  const t = text(body.text).trim();
@@ -14,9 +14,14 @@
14
14
  * POST /api/report-setups/draft { ws, id } → { ok, drafted: { slot, path }, id } Draft it now (the next cycle)
15
15
  * POST /api/report-setups/dismiss { ws, finding } → { ok } "Not a report"
16
16
  * POST /api/report-setups/pause | resume { ws, id } → { ok, setup }
17
+ * POST /api/report-setups/edit { ws, id, schedule?, name?, audience?, output? } → { ok, setup } change a TEMPLATE (premium-reports-from-chat L1).
18
+ * schedule { cadence: 'off' } pauses it; any other schedule changes it and resumes it
19
+ * POST /api/report-setups/remove { ws, id } → { ok } delete a TEMPLATE: its schedule stops; its drafts and issued reports stay (L2)
17
20
  * POST /api/report-setups/from-dashboard { ws, key, name, output, schedule, audience } → { ok, setup }
18
21
  * POST /api/report-setups/finder { ws, cadence?, sources? } → { ok, finder }
19
22
  * GET /api/report-documents?ws → { docs: [{ path, id, setup, name, slot, state: draft|issued, source, output, made_by: schedule|you|agent, v, copy }] }
23
+ * POST /api/report-documents/discard { ws, path } → { ok, doc } delete an UNISSUED draft; an issued report is 409 and untouched (L3)
24
+ * POST /api/report-documents/archive { ws, path, archived } → { ok, doc, archived } hide (or bring back) an ISSUED report; a draft is 409 (L4)
20
25
  * GET /api/report-export?ws&path&fmt=pptx|xlsx|docx|csv → the file, Content-Disposition: attachment. PDF is printed by the browser: there is no route.
21
26
  *
22
27
  * WHO SETS A REPORT UP. Only a PM press does. Every POST passes pm-guard requirePagePress, and a request that carries an agent session header is
@@ -25,7 +30,8 @@
25
30
  * those runs do, sends anything outward (D65: the factory is propose-only).
26
31
  *
27
32
  * A DOCUMENT is any <state>/reports/<cadence>/<slot>.md, one-offs included, joined to issues.jsonl. Its `id` is "<cadence>/<slot>"; `setup` is the
28
- * recurring report that made it (the cadence folder is the setup id), or null for a one-off. `made_by` reads the file's own `made_by` line; with
33
+ * recurring report that made it (the cadence folder is the setup id), or null for a one-off or a deleted template (then `template_deleted` is true and
34
+ * `name` is still the template's). `archived` is true for an issued report the PM archived. AN ISSUED REPORT IS NEVER DELETED: no route removes one. `made_by` reads the file's own `made_by` line; with
29
35
  * none, a setup's folder says "schedule" and a one-off says "you". `v` is 1 plus the saves the document sheet kept for the file. `copy` is the linked
30
36
  * copy's state from lib/doc-sync-store.js (kind: the output's copy kind; state: none | in-step | pmos-ahead | copy-changed | not-checked).
31
37
  *
@@ -48,7 +54,7 @@ const headless = require('./headless.js');
48
54
 
49
55
  const text = (v) => (typeof v === 'string' ? v : '');
50
56
  const bad = (status, error) => ({ status, body: { ok: false, error } });
51
- const POSTS = ['ask', 'change', 'cancel', 'setup', 'draft', 'dismiss', 'pause', 'resume', 'from-dashboard', 'finder'];
57
+ const POSTS = ['ask', 'change', 'cancel', 'setup', 'draft', 'dismiss', 'pause', 'resume', 'from-dashboard', 'finder', 'edit', 'remove', 'documents/discard', 'documents/archive'];
52
58
  const MADE_BY = ['schedule', 'you', 'agent'];
53
59
 
54
60
  const runs = new Map(); // ask id → session id, for the report-setup runs this server started
@@ -108,10 +114,11 @@ function documentsOf(ctx, w) {
108
114
  for (const x of r.reports) {
109
115
  const fm = RN.frontmatter(path.join(abs, x.path));
110
116
  const setup = st.setups.get(x.cadence) || null;
111
- const output = fm.output || (setup && setup.output) || null;
117
+ const gone = setup ? null : (st.removed.get(x.cadence) || null);
118
+ const output = fm.output || ((setup || gone) && (setup || gone).output) || null;
112
119
  docs.push({
113
- path: x.path, id: `${x.cadence}/${x.slot}`, setup: setup ? setup.id : null,
114
- name: setup ? setup.name : (fm.title || x.cadence), slot: x.slot, state: x.issued ? 'issued' : 'draft',
120
+ path: x.path, id: `${x.cadence}/${x.slot}`, setup: setup ? setup.id : null, template_deleted: !!gone,
121
+ name: setup ? setup.name : gone ? gone.name : (fm.title || x.cadence), slot: x.slot, state: x.issued ? 'issued' : 'draft', archived: !!x.issued && st.archived.has(`${x.cadence}/${x.slot}`),
115
122
  source: fm.source || (setup ? setup.source : 'work'), output,
116
123
  made_by: MADE_BY.includes(fm.made_by) ? fm.made_by : (setup ? 'schedule' : 'you'),
117
124
  v: 1 + (saves.get(x.path) || 0), copy: copyOf(linkFor(idx, x.path, output), docSync.copyKindOf(output)),
@@ -275,9 +282,10 @@ async function handle(req, res, url, ctx) {
275
282
  const send = (r) => { ctx.json(res, r.body, r.status); return true; };
276
283
  const isDocs = p === '/api/report-documents' || p.startsWith('/api/report-documents/');
277
284
  const isExport = p === '/api/report-export' || p.startsWith('/api/report-export/');
278
- const sub = isDocs ? 'documents' : isExport ? 'export' : p.replace(/^\/api\/report-setups\/?/, '');
285
+ const docPost = p === '/api/report-documents/discard' || p === '/api/report-documents/archive';
286
+ const sub = docPost ? p.replace(/^\/api\/report-/, '') : isDocs ? 'documents' : isExport ? 'export' : p.replace(/^\/api\/report-setups\/?/, '');
279
287
 
280
- if (isDocs || isExport || (sub === '' && req.method === 'GET')) {
288
+ if (!docPost && (isDocs || isExport || (sub === '' && req.method === 'GET'))) {
281
289
  if (req.method !== 'GET') return send(bad(405, 'GET only'));
282
290
  if ((isDocs && p !== '/api/report-documents') || (isExport && p !== '/api/report-export')) return send(bad(404, 'no such report route'));
283
291
  const w = wsOf(ctx, url.searchParams.get('ws'));
@@ -397,6 +405,29 @@ async function handle(req, res, url, ctx) {
397
405
  if (!r.ok) return fail(r);
398
406
  return send({ status: 200, body: { ok: true, setup: setupOut(r.setup, new Date(), { reports: [] }, new Map(), root) } });
399
407
  }
408
+ if (sub === 'edit') {
409
+ const id = text(body.id);
410
+ if (!RS.fold(RS.readLines(file)).setups.has(id)) return send(bad(404, 'no such report'));
411
+ let r = null;
412
+ const patch = {};
413
+ for (const k of ['name', 'audience', 'output']) if (typeof body[k] === 'string' && body[k].trim()) patch[k] = body[k].trim();
414
+ if (Object.keys(patch).length) { r = RS.change(root, id, patch, opts); if (!r.ok) return fail(r); }
415
+ if (body.schedule !== undefined) { r = RS.reschedule(root, id, body.schedule, opts); if (!r.ok) return fail(r); }
416
+ if (!r) return send(bad(400, 'say what to change: schedule, name, audience or output'));
417
+ const now = new Date();
418
+ return send({ status: 200, body: { ok: true, setup: setupOut(RS.fold(RS.readLines(file)).setups.get(id), now, documentsOf(ctx, w), copyIndex(root), root) } });
419
+ }
420
+ if (sub === 'remove') {
421
+ const r = RS.remove(root, text(body.id), opts);
422
+ if (!r.ok) return fail(r);
423
+ return send({ status: 200, body: { ok: true } });
424
+ }
425
+ if (sub === 'documents/discard' || sub === 'documents/archive') {
426
+ const r = sub === 'documents/discard' ? RS.discardDraft(root, text(body.path), opts) : RS.archiveDoc(root, text(body.path), body.archived !== false, opts);
427
+ if (!r.ok) return fail(r);
428
+ if (ctx.invalidateNeedsAgg) ctx.invalidateNeedsAgg();
429
+ return send({ status: 200, body: r });
430
+ }
400
431
  if (sub === 'finder') {
401
432
  const r = RS.setFinder(file, { cadence: body.cadence, sources: body.sources, by: g.actor });
402
433
  if (!r.ok) return fail(r);
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.386.0",
3
+ "version": "0.388.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.386.0",
9
+ "version": "0.388.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.386.0",
3
+ "version": "0.388.0",
4
4
  "private": true,
5
5
  "description": "PMOS Terminal Workspace — local companion hosting real PTYs beside the library and gates (D62)",
6
6
  "license": "MIT",
@@ -186,7 +186,7 @@ const ALLOWED = /^\/api\/(?:boards\/(?:asks\/(?:add|accept|decline)|move|archive
186
186
 
187
187
  /* P the POST allow-list and the refusals */
188
188
  const all = P.posts.concat(I.posts);
189
- const other = all.filter((x) => !ALLOWED.test(x.path));
189
+ const other = all.filter((x) => !ALLOWED.test(x.path) && x.path !== '/api/briefing-premium/seen'); // an opened popup's record (popup context slice 11, R1) is not a press
190
190
  ok('P1 the pages post only to the asks, move, lifecycle and archive routes', all.length > 10 && !other.length, JSON.stringify(other));
191
191
  const noNonce = await post('/api/boards/move', { id: 'fx-bare', to: ready.model.board.stages[1] }, { 'Content-Type': 'application/json', Origin: BASE });
192
192
  const lifeNo = await post('/api/lifecycle', { initiative_id: 'fx-bare', state: 'on-hold' }, { 'Content-Type': 'application/json', Origin: BASE });
@@ -314,7 +314,7 @@ const GANTT = [
314
314
  repReply = null;
315
315
 
316
316
  /* W: the POST allow-list */
317
- const allowed = new Set(['/api/mentions/read', '/api/pm-items/add', '/api/driver/keep', '/api/driver/return', '/api/driver/drop', '/api/scan/proposal', '/api/scan/now', '/api/scan/stop', '/api/sources/refresh', '/api/sources/refresh-all', '/api/report-setups/setup', '/api/report-setups/dismiss']);
317
+ const allowed = new Set(['/api/mentions/read', '/api/pm-items/add', '/api/driver/keep', '/api/driver/return', '/api/driver/drop', '/api/scan/proposal', '/api/scan/now', '/api/scan/stop', '/api/sources/refresh', '/api/sources/refresh-all', '/api/report-setups/setup', '/api/report-setups/dismiss', '/api/briefing-premium/seen']); // seen: an opened popup's record (popup context slice 11, R1)
318
318
  const strays = posts.filter((x) => !allowed.has(x.path));
319
319
  ok('W1 every POST is one of the existing routes in the PRD', posts.length > 0 && strays.length === 0, JSON.stringify(strays));
320
320
  const fields = { '/api/driver/keep': ['ws', 'proposal'], '/api/driver/return': ['ws', 'proposal', 'note'], '/api/driver/drop': ['ws', 'proposal'], '/api/mentions/read': ['id', 'read'], '/api/pm-items/add': ['line'], '/api/scan/proposal': ['ws', 'id', 'action', 'why'], '/api/scan/now': ['ws'], '/api/sources/refresh': ['ws', 'source'], '/api/sources/refresh-all': ['ws'], '/api/report-setups/setup': ['ws', 'finding'], '/api/report-setups/dismiss': ['ws', 'finding', 'name'] };
@@ -74,6 +74,7 @@ let input = ''; process.stdin.on('data', (d) => { input += d; }); process.stdin.
74
74
  `, { mode: 0o755 });
75
75
  const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==', 'base64');
76
76
  fs.writeFileSync(path.join(base, 'q3-deck.png'), PNG);
77
+ fs.writeFileSync(path.join(base, 'brand.png'), PNG);
77
78
 
78
79
  (async () => {
79
80
  ok('setup: the older cycle is issued', iss && iss.ok === true, JSON.stringify(iss));
@@ -88,7 +89,7 @@ fs.writeFileSync(path.join(base, 'q3-deck.png'), PNG);
88
89
 
89
90
  const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 }, acceptDownloads: true }), p = await ctx.newPage(), errs = [], posts = [];
90
91
  p.on('pageerror', (e) => errs.push(String(e)));
91
- p.on('request', (r) => { const u = new URL(r.url()).pathname; if (r.method() === 'POST' && u !== '/api/doc-health/check') posts.push(u); }); // the document page's health check is a read sent as a POST; it writes nothing
92
+ p.on('request', (r) => { const u = new URL(r.url()).pathname; if (r.method() === 'POST' && u !== '/api/doc-health/check' && u !== '/api/briefing-premium/seen') posts.push(u); }); // the document page's health check is a read sent as a POST; it writes nothing. An opened popup's seen record (popup context slice 11) is not a press either.
92
93
  const shot = async (n) => { if (process.env.READ_SHOTS) await p.screenshot({ path: path.join(process.env.READ_SHOTS, n + '.png') }); };
93
94
  const tap = (sel) => p.$eval(sel, (b) => b.click());
94
95
  const lastA = () => p.evaluate(() => { const a = [...document.querySelectorAll('#dBody .stream .turn.a .tt')]; return a.length ? a[a.length - 1].textContent : ''; });
@@ -194,6 +195,12 @@ fs.writeFileSync(path.join(base, 'q3-deck.png'), PNG);
194
195
  await until(() => p.evaluate(() => /drawn to the saved design/.test(document.querySelector('#rdSrc').textContent)), 10000);
195
196
  ok('L10 this cycle, redrawn, shows in the saved design in sandboxed frames', /This cycle, drawn to the saved design D1/.test(await p.textContent('#rdSrc')) && await bigTitle() === 'frame' && await p.evaluate(() => [...document.querySelectorAll('#oMain iframe')].every((f) => f.getAttribute('sandbox') === '')), await p.textContent('#rdSrc'));
196
197
  await shot('reader-look-1280');
198
+ await p.setInputFiles('#rdFile', path.join(base, 'brand.png'));
199
+ await until(() => p.evaluate(() => /brand\.png/.test(document.querySelector('.rdz').textContent)));
200
+ ok('L11 each sample has its own remove button, named for the sample', await p.evaluate(() => [...document.querySelectorAll('.rdz [data-rr^="unsample|"]')].map((b) => b.getAttribute('aria-label')).join()) === 'Remove the sample q3-deck.png,Remove the sample brand.png');
201
+ await tap('#oMain [aria-label="Remove the sample q3-deck.png"]');
202
+ await until(() => p.evaluate(() => !/q3-deck\.png/.test(document.querySelector('.rdz').textContent)));
203
+ ok('L12 removing a sample drops it from the row, keeps the other, and says the next version stops following it', /Follows brand\.png/.test(await p.textContent('.rdz')) && !/q3-deck/.test(await p.textContent('.rdz')) && /Removed "q3-deck.png"\. The next version and each new cycle no longer follow it/.test(await lastA()), await lastA());
197
204
  await p.click('#dClose'); await sleep(200);
198
205
 
199
206
  /* I: an issued cycle is frozen */
@@ -204,9 +211,9 @@ fs.writeFileSync(path.join(base, 'q3-deck.png'), PNG);
204
211
  await p.click('#dClose'); await sleep(200);
205
212
 
206
213
  /* P: the writes */
207
- const allowed = new Set(['/api/report-design/describe', '/api/report-design/sample', '/api/report-design/turn', '/api/report-design/accept', '/api/report-design/revert']);
208
- ok('P1 before Issue, the only POSTs are the report-design describe, sample, turn, accept and revert routes', posts.length > 0 && posts.every((x) => allowed.has(x)), posts.join());
209
- ok('P2 the first turn described the look first, and each later press posted once', posts.join() === ['sample', 'describe', 'turn', 'turn', 'revert', 'accept'].map((x) => '/api/report-design/' + x).join(), posts.join());
214
+ const allowed = new Set(['/api/report-design/describe', '/api/report-design/sample', '/api/report-design/turn', '/api/report-design/accept', '/api/report-design/revert', '/api/report-design/unsample']);
215
+ ok('P1 before Issue, the only POSTs are the report-design describe, sample, unsample, turn, accept and revert routes', posts.length > 0 && posts.every((x) => allowed.has(x)), posts.join());
216
+ ok('P2 the first turn described the look first, and each later press posted once', posts.join() === ['sample', 'describe', 'turn', 'turn', 'revert', 'accept', 'sample', 'unsample'].map((x) => '/api/report-design/' + x).join(), posts.join());
210
217
  ok('P3 the document file is unchanged', fs.readFileSync(path.join(dir, pNew), 'utf8') === DOC);
211
218
 
212
219
  /* F: floors */
@@ -223,6 +223,16 @@ const model = async () => (await (await fetch(BASE + '/api/insights-premium')).j
223
223
  const nDesc = posts.filter((x) => x === '/api/report-design/describe').length;
224
224
  await tap('#oMain [data-st="chip|dfmt"]'); await sleep(100); await tap('#stTr [data-st="dzfmt|doc"]'); await sleep(600);
225
225
  ok('F7 with a description saved, choosing Document posts it with the format', posts.filter((x) => x === '/api/report-design/describe').length === nDesc + 1 && await chipv('dfmt') === 'Document', posts.join());
226
+ await tap('#oMain [data-st="chip|dsmp"]'); await sleep(100);
227
+ await p.setInputFiles('#dzFile', { name: 'other.png', mimeType: 'image/png', buffer: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64') });
228
+ await until(() => chipv('dsmp').then((v) => v === '2'), 8000);
229
+ ok('D10 each listed sample has its own remove button, named for the sample', await p.evaluate(() => [...document.querySelectorAll('#stTr [data-st^="dzrm|"]')].map((b) => b.getAttribute('aria-label') + ':' + b.offsetHeight).join()) === 'Remove the sample sample.png:44,Remove the sample other.png:44');
230
+ await shot('report-samples-1280');
231
+ await tap('#stTr [aria-label="Remove the sample sample.png"]');
232
+ await until(() => chipv('dsmp').then((v) => v === '1'), 8000);
233
+ ok('D11 removing a sample drops it from the list and the count, and says the next version stops following it', await chipv('dsmp') === '1' && !/sample\.png/.test(await p.evaluate(() => document.querySelector('#stTr').textContent)) && /other\.png/.test(await p.evaluate(() => document.querySelector('#stTr').textContent))
234
+ && posts.includes('/api/report-design/unsample') && /Removed "sample\.png"/.test(await lastA()), await lastA());
235
+
226
236
  /* D7 to D9: point and say, make the next version, compare two */
227
237
  await until(() => p.evaluate(() => { const b = document.querySelector('#stPv [data-st="dznext"]'); return !!b && !b.disabled; }), 30000);
228
238
  await p.click('#dzSlide', { position: { x: 200, y: 100 } });
@@ -247,9 +257,8 @@ const model = async () => (await (await fetch(BASE + '/api/insights-premium')).j
247
257
  const lib = await p.evaluate(() => [...document.querySelectorAll('#stLb .stli')].map((b) => b.querySelector('b').textContent + ':' + b.querySelector('em').textContent));
248
258
  ok('L1 the library lists the set-up reports', lib.join() === 'Partner review:Open', lib.join());
249
259
  await tap('#oMain [data-st="lib"]');
250
-
251
260
  /* P: the writes */
252
- const allowed = new Set(['/api/report-setups/setup', '/api/report-setups/from-dashboard', '/api/report-structure/turn', '/api/report-structure/remove', '/api/report-structure/revert', '/api/report-structure/accept', '/api/report-design/describe', '/api/report-design/sample', '/api/report-design/turn', '/api/report-design/accept', '/api/report-design/revert']);
261
+ const allowed = new Set(['/api/briefing-premium/seen', '/api/report-design/unsample', '/api/report-setups/setup', '/api/report-setups/from-dashboard', '/api/report-structure/turn', '/api/report-structure/remove', '/api/report-structure/revert', '/api/report-structure/accept', '/api/report-design/describe', '/api/report-design/sample', '/api/report-design/turn', '/api/report-design/accept', '/api/report-design/revert']);
253
262
  ok('P1 every POST is one of the existing report routes', posts.length > 0 && posts.every((x) => allowed.has(x)), posts.join());
254
263
 
255
264
  /* F: floors */
@@ -239,12 +239,15 @@ function openAsk(q) {
239
239
  function openAbout(d) {
240
240
  if (!d) return;
241
241
  const draftable = d.act && d.act.kind === 'draft' && !d.running;
242
- const say = d.title + ' is ' + (d.state || 'not started').toLowerCase() + '. ' + (d.path ? '' : d.st === 'missing' ? 'There is no file to read yet.' : 'It has no file of its own to read.') + (d.what ? ' ' + d.what : '');
243
- const rows = [['State', d.state], ['Who writes it', d.by], ['Read by', d.reader], ['How often', d.cadence], ['Updated', d.when], ['Added', d.added]];
242
+ // popup context slice 4b: a derived document with no file shows the PRD section it comes from, and the first line says so
243
+ const fr = d.from && d.from.text ? d.from : null;
244
+ const say = d.title + ' is ' + (d.state || 'not started').toLowerCase() + '. ' + (fr ? 'It has no file of its own. The PRD\u2019s \u201c' + fr.heading + '\u201d section covers it, shown on the right.' : d.path ? '' : d.st === 'missing' ? 'There is no file to read yet.' : 'It has no file of its own to read.') + (d.what && !fr ? ' ' + d.what : '');
245
+ const rows = [['State', d.state], ['Who writes it', d.by], ['Read by', d.reader], ['How often', d.cadence], ['Updated', d.when], ['Added', d.added], ['From the PRD', fr ? fr.path + ' \u00a7 ' + fr.heading : '']];
246
+ const prd = fr ? `<p class="label" style="margin:0 0 8px">From the PRD: ${esc(fr.heading)}</p><div class="dprd">${fr.text.split(/\n{2,}/).map((x) => `<p>${esc(x.replace(/^[-*]\s+/gm, '\u2022 '))}</p>`).join('')}</div><p class="note" style="margin:8px 0 14px">${esc(fr.path)}${fr.cut ? ' \u00b7 cut short; the PRD has the rest' : ''}</p>` : '';
244
247
  const holds = d.sections && d.sections.length ? `<p class="label" style="margin:16px 0 8px">What a draft will contain</p><ul class="dabt">${d.sections.map((x) => `<li>${esc(x)}</li>`).join('')}</ul>` : '';
245
- const why = d.st === 'missing' ? (draftable ? 'Draft it starts a read-only agent run that writes a draft for you to read. Nothing is sent.' : d.act ? '' : /pmos/i.test(d.by || '') ? 'PMOS drafts this one, but a draft cannot be started from this page yet.' : 'PMOS does not draft this one. ' + (d.by ? d.by + '.' : 'You write it.')) : d.path ? '' : 'There is no file to open yet, so there is nothing to read here.';
248
+ const why = d.st === 'missing' ? (draftable ? 'Draft it starts a read-only agent run that writes a draft for you to read. Nothing is sent.' : d.act ? '' : /pmos/i.test(d.by || '') ? 'PMOS drafts this one, but a draft cannot be started from this page yet.' : 'PMOS does not draft this one. ' + (d.by ? d.by + '.' : 'You write it.')) : d.path || fr ? '' : 'There is no file to open yet, so there is nothing to read here.';
246
249
  const act = draftable ? `<div class="cact"><button class="cta" id="abDraft">${ICO(SPARK)}${esc(d.act.label)}</button></div>` : d.running ? '<p class="note" role="status" style="margin-top:12px">The agent is drafting this now. It runs in the background and sends nothing.</p>' : '';
247
- openDlg({ eye: 'Document · real data', title: d.title, sub: M.title, say, stream: turnA(ptx(say)), noteKey: popKey('doc', M.id, d.key || d.title), facts: rows, pane: `<article class="paper doc">${d.what ? `<p class="lede" style="margin:0 0 12px">${esc(d.what)}</p>` : ''}${kv(rows)}${holds}${why ? `<p class="note" style="margin-top:12px">${esc(why)}</p>` : ''}${act}</article>`, label: 'Document' });
250
+ openDlg({ eye: 'Document · real data', title: d.title, sub: M.title, say, stream: turnA(ptx(say)), noteKey: popKey('doc', M.id, d.key || d.title), facts: rows, pane: `<article class="paper doc">${d.what ? `<p class="lede" style="margin:0 0 12px">${esc(d.what)}</p>` : ''}${prd}${kv(rows)}${holds}${why ? `<p class="note" style="margin-top:12px">${esc(why)}</p>` : ''}${act}</article>`, label: 'Document' });
248
251
  const b = $('#abDraft'); if (b) b.onclick = async () => { b.disabled = true; closeDlg(); await draftKey(d.key); };
249
252
  }
250
253
  $('#dBody').addEventListener('click', (e) => { const lt = e.target.closest('#logT'); if (lt) { const c = $('#alog').classList.toggle('col'); lt.setAttribute('aria-expanded', !c); } });
@@ -9,7 +9,7 @@
9
9
  * READS: GET /api/doc (the words), GET /api/report-design/cycle and cycle-html (a cycle drawn to the saved design), GET /api/report-design and
10
10
  * version (the design and its versions), GET /api/report-export (the files). PDF is the browser's print. Every render is HTML the server sanitized,
11
11
  * shown in a frame with an empty sandbox: nothing in it runs.
12
- * WRITES: only the report-design describe, sample, turn, accept and revert routes, each a press on the page (pmPost, behind the launch nonce). An
12
+ * WRITES: only the report-design describe, sample, unsample, turn, accept and revert routes, each a press on the page (pmPost, behind the launch nonce). An
13
13
  * issued cycle is frozen: no design row and no turn. Issue (POST /api/report/issue, after a confirm) freezes a draft cycle; the copies in other tools stay in the console.
14
14
  * Edit opens the report's file as a page in the viewer (premium-vw-doc.js, initiative premium-viewer S2): the one document page every markdown file uses,
15
15
  * with Present, Print and Download on its bar. Its words are saved there through the /api/doc-sheet routes. */
@@ -136,7 +136,8 @@ function designHtml() {
136
136
  const d = R.design;
137
137
  if (!d) return `<div class="rdz"><span class="label">Design</span><span class="rds2">${R.dErr ? esc(R.dErr) : 'Reading the design.'}</span></div>`;
138
138
  const vs = d.versions || [], shown = R.show, saved = d.saved ? d.saved.version : null;
139
- const smp = (d.samples || []).length ? 'Follows ' + d.samples.map((x) => `<em>${esc(x.name)}</em>`).join(', ') : 'No sample yet.';
139
+ // each sample with its own remove (x): a press, never hover-only, so it works on a phone
140
+ const smp = (d.samples || []).length ? 'Follows ' + d.samples.map((x) => `<span class="rdsm"><em title="${esc(x.name)}">${esc(x.name)}</em><button type="button" class="rdsx" data-rr="unsample|${esc(x.id)}" aria-label="Remove the sample ${esc(x.name)}" title="Remove this sample"${R.busy ? ' disabled' : ''}>${XI}</button></span>`).join('') : 'No sample yet.';
140
141
  const keep = shown === 'cycle' ? '' : saved === shown ? `<span class="s issued">${CHK}Saved as the design</span>` : `<button class="dmcta alt" data-rr="keep"${R.busy ? ' disabled' : ''}>This is it</button>`;
141
142
  return `<div class="rdz"><span class="label">Design</span><span class="rdv" role="group" aria-label="Design versions"><button data-rr="ver|cycle" aria-pressed="${shown === 'cycle'}">This cycle</button>${vs.map((v) => `<button data-rr="ver|${v.n}" aria-pressed="${shown === v.n}"${R.busy ? ' disabled' : ''} title="${esc(v.turn || '')}">D${v.n}</button>`).join('')}</span>`
142
143
  + `<span class="rds2">${smp}${d.running || R.busy ? ' <b>PMOS is working on it.</b>' : ''}</span><button class="dlink" data-rr="pick">${PLUS}Add a sample</button><input type="file" id="rdFile" hidden accept=".pdf,.pptx,.docx,.png,.jpg,.jpeg">${keep}</div>`;
@@ -272,6 +273,7 @@ async function act(a) {
272
273
  if (k === 'issueno') { R.conf = false; R.issueErr = ''; draw(); return; }
273
274
  if (k === 'issueok') { if (!R.busy) await issueIt(); return; }
274
275
  if (k === 'pick') { const f = $('#rdFile'); if (f) f.click(); return; }
276
+ if (k === 'unsample') { if (!R.busy) await removeSample(v); return; }
275
277
  if (k === 'ver') {
276
278
  if (v === 'cycle') { R.show = 'cycle'; R.i = 0; draw(); return; }
277
279
  const n = +v;
@@ -324,6 +326,19 @@ async function addSample(file) {
324
326
  sayA('Added "' + file.name + '". Tell me what to take from it, and I make the next version follow it.');
325
327
  }
326
328
 
329
+ /** Remove a sample: the next version, the brief and each cycle stop following it. Add the file again to follow it again. */
330
+ async function removeSample(id) {
331
+ const s = ((R.design && R.design.samples) || []).find((x) => x.id === id);
332
+ if (!s) return;
333
+ R.busy = true; draw();
334
+ const r = await pmPost('/api/report-design/unsample', { ws: R.ws, id: R.id, sample: id }).catch((x) => ({ ok: false, error: String(x && x.message || x) }));
335
+ R.busy = false;
336
+ if (!r || r.ok !== true) { draw(); toast('The sample was not removed: ' + ((r && r.error) || 'the press did not go through.')); return; }
337
+ R.design = r.design; draw();
338
+ const b = $('#oMain [data-rr="pick"]'); if (b) b.focus();
339
+ sayA('Removed "' + s.name + '". The next version and each new cycle no longer follow it.');
340
+ }
341
+
327
342
  /* ── Present: the current slide on the whole screen ── */
328
343
  function presHtml() {
329
344
  const L = slides(), i = R.i;
@@ -289,9 +289,19 @@ export function popKey(...parts) {
289
289
  const k = parts.map((p) => String(p == null ? '' : p).replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '')).filter(Boolean).join(':').replace(/^[^A-Za-z0-9]+/, '').slice(0, 100);
290
290
  return 'pop:' + (k || 'x');
291
291
  }
292
+ // popup context slice 3b: an opened popup is recorded once per page load, with what it showed, so the leads session after the next
293
+ // source refresh writes its lead. Recording starts nothing; a failed record is dropped.
294
+ const seenKeys = new Set();
295
+ const FORM_KINDS = ['new-task', 'new-doc', 'settings', 'sources', 'act']; // as lib/popup-leads.js: a form gets no lead
296
+ function markSeen(key, c) {
297
+ if (seenKeys.has(key) || FORM_KINDS.includes(key.split(':')[1])) return;
298
+ seenKeys.add(key);
299
+ pmPost('/api/briefing-premium/seen', { key, title: c.title, subject: c.subject, say: c.say, facts: c.facts.slice(0, 12).map((f) => [String(f[0]), String(f[1])]) }).catch(() => {});
300
+ }
292
301
  export function openDlg(o) {
293
302
  S.key = o.noteKey || null;
294
303
  S.ctx = S.key && S.key.startsWith('pop:') ? { title: o.title, subject: o.sub || '', say: o.say || '', facts: (o.facts || []).filter((f) => f && f[1]) } : null;
304
+ if (S.ctx) markSeen(S.key, S.ctx);
295
305
  park(); // a page's own control lent to the dialog (the Briefing's product picker) goes home before the pane is replaced
296
306
  const ae = document.activeElement; if (ae && ae !== document.body) lastFocus = ae;
297
307
  $$('.rail,main.stage,#dock').forEach((x) => { x.inert = true; });