create-pmos 0.476.0 → 0.477.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 (82) hide show
  1. package/package.json +20 -14
  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-publish-ui-test.js +11 -16
  7. package/workspace/board-shared-ui-test.js +34 -33
  8. package/workspace/changelog.json +19 -0
  9. package/workspace/guide/briefing-premium.md +2 -2
  10. package/workspace/guide/claude-proposes.md +3 -1
  11. package/workspace/guide/forecast.md +16 -3
  12. package/workspace/guide/home.md +2 -2
  13. package/workspace/guide/workflows.md +13 -2
  14. package/workspace/home-railcard-test.js +4 -4
  15. package/workspace/home-rows-test.js +15 -4
  16. package/workspace/ini-workflow-test.js +1 -1
  17. package/workspace/lib/board-pack.js +20 -1
  18. package/workspace/lib/board-trail.js +17 -1
  19. package/workspace/lib/boards-host.js +22 -2
  20. package/workspace/lib/briefing-premium-agent.js +2 -2
  21. package/workspace/lib/engine/boards.js +15 -3
  22. package/workspace/lib/engine/workflows.js +79 -10
  23. package/workspace/lib/forecast-offer.js +57 -0
  24. package/workspace/lib/grill-runs.js +1 -0
  25. package/workspace/lib/grill.js +1 -1
  26. package/workspace/lib/insight-moves.js +8 -6
  27. package/workspace/lib/news-for-you.js +6 -4
  28. package/workspace/lib/report-chat.js +2 -0
  29. package/workspace/lib/routes-board-publish.js +7 -2
  30. package/workspace/lib/routes-boards.js +18 -5
  31. package/workspace/lib/routes-briefing-premium.js +16 -2
  32. package/workspace/lib/routes-forecast.js +8 -1
  33. package/workspace/lib/routes-insight-moves.js +7 -5
  34. package/workspace/lib/routes-news.js +3 -1
  35. package/workspace/lib/routes-workflows.js +13 -0
  36. package/workspace/lib/wf-bridge.js +165 -0
  37. package/workspace/package-lock.json +2 -2
  38. package/workspace/package.json +1 -1
  39. package/workspace/panels-test.js +1 -2
  40. package/workspace/public/pm/bd-fc-card.js +45 -0
  41. package/workspace/public/pm/bd-next.js +1 -1
  42. package/workspace/public/pm/bd-publish.css +22 -18
  43. package/workspace/public/pm/bd-publish.js +57 -48
  44. package/workspace/public/pm/bd-shared.css +92 -30
  45. package/workspace/public/pm/bd-shared.js +143 -55
  46. package/workspace/public/pm/bd-span.js +27 -7
  47. package/workspace/public/pm/cozy-board.css +15 -0
  48. package/workspace/public/pm/cozy-ev.css +46 -0
  49. package/workspace/public/pm/cozy-home.css +4 -4
  50. package/workspace/public/pm/cozy-insights.css +21 -0
  51. package/workspace/public/pm/cozy-jl.js +158 -0
  52. package/workspace/public/pm/cozy-news.js +56 -2
  53. package/workspace/public/pm/cozy-panels.js +3 -2
  54. package/workspace/public/pm/cozy-settings.js +11 -7
  55. package/workspace/public/pm/cozy-today.css +3 -0
  56. package/workspace/public/pm/cozy-viewer.js +19 -3
  57. package/workspace/public/pm/goal-forecast.js +101 -0
  58. package/workspace/public/pm/hi-pop.css +16 -0
  59. package/workspace/public/pm/home-app.js +11 -4
  60. package/workspace/public/pm/home-day.js +5 -3
  61. package/workspace/public/pm/home-list.js +14 -4
  62. package/workspace/public/pm/home-mentions.js +5 -0
  63. package/workspace/public/pm/home-task.js +1 -1
  64. package/workspace/public/pm/home-today.js +11 -4
  65. package/workspace/public/pm/ini-view-model.js +27 -14
  66. package/workspace/public/pm/ini-view.js +1 -1
  67. package/workspace/public/pm/ini-wf-model.js +76 -19
  68. package/workspace/public/pm/ini-wf.js +69 -18
  69. package/workspace/public/pm/metric-drafts.css +9 -0
  70. package/workspace/public/pm/metric-drafts.js +2 -2
  71. package/workspace/public/pm/premium-board.js +13 -3
  72. package/workspace/public/pm/premium-insights.js +43 -6
  73. package/workspace/public/pm/premium-report-tab.js +13 -3
  74. package/workspace/public/pm/premium-vw-item.js +1 -1
  75. package/workspace/public/pm/readonly.js +1 -0
  76. package/workspace/public/pm/report-chat.js +2 -1
  77. package/workspace/public/pm/task-card.js +4 -3
  78. package/workspace/public/pm/wf-page.css +9 -0
  79. package/workspace/public/pm/wf-page.js +30 -1
  80. package/workspace/run-tests.js +10 -2
  81. package/workspace/server.js +5 -2
  82. package/workspace/test-lists/forecast-board.json +5 -0
@@ -25,6 +25,23 @@ const VIEWS = ['track', 'stages', 'time', 'list']; // the Board's views a pack
25
25
  const MODEL_KEYS = ['pending', 'workflows', 'today', 'header', 'board', 'initiatives', 'steps', 'rows'];
26
26
  // a key that is the publisher's own, wherever it sits: what only they can do, and what is theirs to answer
27
27
  const OWN_KEYS = new Set(['acts', 'dialog', 'you']);
28
+ // what Claude proposes to the publisher, wherever it sits on a row: a split or a merge, the ✦ proposals and Grill findings, an unsaved draft plan
29
+ // (batch 20 item 1). A teammate sees what is decided, not what waits on the publisher's ✓.
30
+ const PROPOSAL_KEYS = new Set(['suggest', 'props', 'draft']);
31
+
32
+ /** A row as a teammate may see it: no proposal, the links without Claude's link proposals, quiet moves and asks, a ticket without a move in flight. */
33
+ function settled(v) {
34
+ if (Array.isArray(v)) return v.map(settled);
35
+ if (!v || typeof v !== 'object') return v;
36
+ const o = {};
37
+ for (const k of Object.keys(v)) {
38
+ if (PROPOSAL_KEYS.has(k)) continue;
39
+ if (k === 'move' && v.key) continue; // a Jira ticket's move the publisher asked for: the reading stands
40
+ o[k] = settled(v[k]);
41
+ }
42
+ if (o.links && typeof o.links === 'object' && Array.isArray(o.links.links)) o.links = Object.assign({}, o.links, { proposals: [], moved: { n: 0, batches: [], tasks: [] }, asks: [] });
43
+ return o;
44
+ }
28
45
 
29
46
  const pathOf = (k) => String(k).split('?')[0];
30
47
  const queryOf = (k) => { const i = String(k).indexOf('?'); return new URLSearchParams(i < 0 ? '' : String(k).slice(i + 1)); };
@@ -107,7 +124,9 @@ function buildPack({ ws, board, selection, answers, meta }) {
107
124
  // the model: only the keys that are drawn, only the selection's records, then the sweep
108
125
  const model = {};
109
126
  for (const k of MODEL_KEYS) if (k in model0) model[k] = model0[k];
110
- const swept = sweep(pruneRecords(model, outside), needles);
127
+ const swept = sweep(settled(pruneRecords(model, outside)), needles);
128
+ // the header names what this computer could not read: the publisher's own business, and the line above the copy says when it was made
129
+ if (swept.header && typeof swept.header.text === 'string') swept.header = { text: swept.header.text.replace(/ · not read: .*$/, ''), missing: [] };
111
130
 
112
131
  // programs: a program selection keeps that program, a product keeps the programs that hold something of it, an initiative keeps none
113
132
  const kept = R.wholeBoard ? R.progs.filter((p) => ((p && p.members) || []).some((m) => m && m.ws === ws)) : R.keptPrograms;
@@ -189,6 +189,22 @@ function trail({ root, ids, rows = [], moves = [], now = Date.now(), io } = {})
189
189
  const mv = (byIni.get(id) || []).filter((m) => (wk ? m.to === wk : stageKey(m.to) === stage)).pop();
190
190
  if (mv) { since = Date.parse(mv.at); sinceFrom = 'move'; }
191
191
  else if (!wk) { const L = ladderDates(id, fm, seen, evals); if (L.length) { since = L[L.length - 1][1]; sinceFrom = 'git'; } }
192
+ // batch 20 item 3 (canvas WmD): a switch that merged old stages into this one counts from the day the first of them began, so "20 days in
193
+ // Discovery" is true; the old stages' own days stay in `before`
194
+ let before = null;
195
+ if (wk && mv && mv.via === 'ini-wf' && mv.map) {
196
+ const L = (byIni.get(id) || []).slice().sort((a, b) => String(a.at).localeCompare(String(b.at)));
197
+ const ok = (t) => !!t && (mv.map[t] === wk || mv.map[stageKey(t)] === wk);
198
+ let first = null;
199
+ for (let j = L.indexOf(mv) - 1; j >= 0 && ok(L[j].to); j--) first = L[j];
200
+ if (first) { since = Date.parse(first.at); sinceFrom = 'merged'; }
201
+ else if (ok(mv.from)) { const LD = ladderDates(id, fm, seen, evals); let t0 = null; for (let q = LD.length - 1; q >= 0 && ok(LD[q][0]); q--) t0 = LD[q][1]; if (t0) { since = t0; sinceFrom = 'merged'; } }
202
+ const at = L.indexOf(mv);
203
+ let s0 = 0; for (let j = 0; j < at; j++) if (L[j].via === 'ini-wf') s0 = j;
204
+ const seg = [];
205
+ for (let j = s0; j < at; j++) { const k = String(L[j].to || ''); if (!k) continue; seg.push({ key: k, name: LABEL[stageKey(k)] || (k.charAt(0).toUpperCase() + k.slice(1)).replace(/-/g, ' '), days: Math.max(0, Math.round((Date.parse(L[j + 1].at) - Date.parse(L[j].at)) / DAY)) }); }
206
+ before = seg.length ? seg.slice(-8) : null;
207
+ }
192
208
 
193
209
  // skipped: the lane's own ladder, then a move past a stage (with the move's reason)
194
210
  const k = STAGES.indexOf(stage), laneSet = new Set(LANE_STAGES[lane] || STAGES);
@@ -229,7 +245,7 @@ function trail({ root, ids, rows = [], moves = [], now = Date.now(), io } = {})
229
245
  let mvFrom = 0; if (wk) for (let i = 0; i < mvAll.length; i++) if (mvAll[i].via === 'ini-wf') mvFrom = i;
230
246
  const ran = mvAll.slice(mvFrom).filter((m) => m.to && m.at).slice(-40).map((m) => ({ to: String(m.to), at: dayIso(Date.parse(m.at)) }));
231
247
  items[id] = {
232
- since: since ? dayIso(since) : null, sinceFrom, days: since ? Math.max(0, Math.floor((now - since) / DAY)) : null, moves: ran,
248
+ since: since ? dayIso(since) : null, sinceFrom, days: since ? Math.max(0, Math.floor((now - since) / DAY)) : null, moves: ran, ...(before ? { before } : {}),
233
249
  skipped, parts, next: parts ? (parts.find((p) => !p.done) || {}).name || null : null, you,
234
250
  links: { prd: prdRel, prdVersion: prdRel && (typeof prdFm.version === 'string' || typeof prdFm.version === 'number') && String(prdFm.version).trim() ? String(prdFm.version).trim().slice(0, 12) : null,
235
251
  rubric: rubRel, evaluation: evals[0] || null, epic: jv && jv.ok && jv.epic && jv.epic.key ? jv.epic.key : null },
@@ -5,6 +5,7 @@
5
5
  * POST <host>/api/publish Authorization: Bearer <publish key> { team, name, kind, by, days, password, pack } -> { ok, id, url, ends }
6
6
  * POST <host>/api/republish Authorization: Bearer <publish key> { id, pack } -> { ok, ends }
7
7
  * DELETE <host>/api/links/<id> Authorization: Bearer <publish key> -> { ok }
8
+ * POST <host>/api/links/<id>/password Authorization: Bearer <publish key> -> { ok, password }
8
9
  * The host answers a refusal as { ok: false, error } with a plain sentence. It makes the link id; the workspace never does.
9
10
  *
10
11
  * THE PUBLISH KEY. Made here, once, on the first publish: 32 random bytes. It is kept in <runtime state>/board-publish/state.json (mode 0600)
@@ -25,6 +26,7 @@
25
26
  * publish(dir, o, { fetch, env, now }) o = { pack, team, name, kind, by, days, password, selection, ws, board } -> { ok, id, url, ends } | { ok: false, error, status }
26
27
  * republish(dir, id, pack, { fetch, env, now }) -> { ok, ends } | { ok: false, error }
27
28
  * turnOff(dir, id, { fetch, env }) -> { ok } | { ok: false, error }
29
+ * newPassword(dir, id, { fetch, env }) -> { ok, password } | { ok: false, error } the host makes it; it is passed on once and never kept here
28
30
  */
29
31
  const fs = require('fs');
30
32
  const path = require('path');
@@ -53,7 +55,12 @@ function readState(dir) {
53
55
  catch { return { key: null, host: '', teams: [], links: [] }; }
54
56
  }
55
57
  /** The address the PM saved on the Publish popover ('' when none). The environment variable PMOS_BOARDS_HOST wins over it (see addressOf). */
56
- function savedHost(dir) { return readState(dir).host || ''; }
58
+ function savedHost(dir) {
59
+ const st = readState(dir); if (st.host) return st.host;
60
+ // no saved address, but a link is open (it was published while PMOS_BOARDS_HOST was set): that link's host is the address (batch 20 item 2)
61
+ for (const l of st.links.slice().reverse()) { try { const o = hostOrigin({ PMOS_BOARDS_HOST: new URL(l.url).origin }); if (o) return o; } catch { /* not an address */ } }
62
+ return '';
63
+ }
57
64
  /** Save the host address: '' clears it. Returns { ok, host } or { ok: false, error } with a sentence for the PM. */
58
65
  function setHost(dir, value) {
59
66
  const v = String(value == null ? '' : value).trim();
@@ -150,4 +157,17 @@ async function turnOff(dir, id, opts = {}) {
150
157
  return { ok: true };
151
158
  }
152
159
 
153
- module.exports = { DAYS, TEAM_RX, MAX_PACK, hostOrigin, savedHost, setHost, addressOf, readState, writeState, links, publish, republish, turnOff };
160
+ async function newPassword(dir, id, opts = {}) {
161
+ const origin = hostOrigin(opts.env);
162
+ if (!origin) return noHost;
163
+ const st = readState(dir);
164
+ const l = st.links.find((x) => x.id === id);
165
+ if (!st.key || !l) return { ok: false, status: 404, error: 'This link is not one of yours.' };
166
+ const r = await call(origin, 'POST', '/api/links/' + encodeURIComponent(id) + '/password', st.key, {}, opts.fetch);
167
+ if (!r.ok) return r;
168
+ const pw = r.body.password;
169
+ if (typeof pw !== 'string' || pw.length < 6 || pw.length > 100) return { ok: false, status: 502, error: 'The host sent an answer this workspace does not accept.' };
170
+ return { ok: true, password: pw };
171
+ }
172
+
173
+ module.exports = { DAYS, TEAM_RX, MAX_PACK, hostOrigin, savedHost, setHost, addressOf, readState, writeState, links, publish, republish, turnOff, newPassword };
@@ -239,8 +239,8 @@ function chat({ runtimeDir, key, text, model, context, sessions, wsId, iniInfo,
239
239
  let s;
240
240
  // an initiative chat's opening (or its resumed first message) states the initiative's workflow and stage (lib/initiative-chat.js)
241
241
  const iniRule = /^init:/.test(key) && !goal ? IniChat.rule(info(), iniId(key)) : [];
242
- if (resume && iniRule.length && msg === q) msg = IniChat.wrap(q, info(), iniId(key));
243
- try { s = sessions.spawn({ name, agent: 'claude', ws: wsId, origin: 'chat:' + key, chatClaude: { id: claude, resume }, initialInput: (resume ? msg : openingFor(row, msg, iniRule)) + '\r' }); } catch (e) { s = { state: 'exited', note: String((e && e.message) || e).slice(0, 120) }; }
242
+ if (resume && iniRule.length && msg === q && !/^\/[A-Za-z0-9]/.test(q)) msg = IniChat.wrap(q, info(), iniId(key)); // a / command goes as typed (batch 20 item 7)
243
+ try { s = sessions.spawn({ name, agent: 'claude', ws: wsId, origin: 'chat:' + key, chatClaude: { id: claude, resume }, initialInput: (resume ? msg : openingFor(row, msg, iniRule)) + '\r', ...(resume && /^\/[A-Za-z0-9]/.test(msg) ? { typedByPm: true } : {}) }); } catch (e) { s = { state: 'exited', note: String((e && e.message) || e).slice(0, 120) }; }
244
244
  if (!s || s.state === 'exited' || !s.id) return fail(409, 'Claude could not start: ' + ((s && s.note) || 'no session'));
245
245
  fs.mkdirSync(runtimeDir, { recursive: true });
246
246
  fs.appendFileSync(path.join(runtimeDir, CHATS), JSON.stringify({ key, session: s.id, claude, name, at: now.toISOString() }) + '\n');
@@ -219,7 +219,7 @@ function fold(events) {
219
219
  const deleted = new Map(); // initiative id → { at, by, board, title, tasks, items } while deleted (an ini-restore line brings it back)
220
220
  const notDup = new Map(); // initiative id → Set of initiative ids the PM said it is not a duplicate of
221
221
  // D99 workflows per initiative: the workflow each initiative runs, Won't do, the agent's readings of Only-when stages, Moves on by itself
222
- const iniWf = new Map(); // key(board, id) → { wf, at, by, why, from } (the last ini-wf line)
222
+ const iniWf = new Map(); // key(board, id) → { wf, at, by, why, from, map, before, batch, undo } (the last ini-wf line; map: old stage key → stage now)
223
223
  const ends = new Map(); // key(board, id) → { as: 'wontdo', reason, note, at, by } while it is out (a `back` line brings it back to Triage)
224
224
  const judged = new Map(); // key(board, id) → { [stageKey]: { runs, why, cite, at, by } } (an `undo` line drops the reading)
225
225
  const autoOver = new Map(); // key(board, id) → { [stageKey]: true|false } the PM's own Moves on by itself for one initiative
@@ -338,10 +338,22 @@ function fold(events) {
338
338
  notDup.get(e.id).add(e.of);
339
339
  } else if (e.kind === 'ini-wf' && b && typeof e.id === 'string' && typeof e.wf === 'string' && e.wf) {
340
340
  const k = key(b, e.id);
341
- iniWf.set(k, { wf: e.wf, at: e.at || null, by: e.by || null, why: typeof e.why === 'string' ? e.why : '', from: typeof e.from === 'string' ? e.from : null, pmos: e.pmos === true });
341
+ // the stage map (batch 20 item 3): every stage key the initiative's tasks may name → the stage of this workflow it sits in now, composed
342
+ // over each switch; an undo line puts back the map from before the switch it undoes
343
+ const prev = iniWf.get(k) || null;
344
+ let map = null, before = prev;
345
+ if (e.undo === true) { map = prev && prev.before ? prev.before.map : null; before = prev && prev.before ? prev.before.before : null; }
346
+ else if (isObj(e.map)) {
347
+ map = {};
348
+ if (prev && prev.map) for (const [o, v] of Object.entries(prev.map)) if (typeof e.map[v] === 'string') map[o] = e.map[v];
349
+ for (const [o, v] of Object.entries(e.map)) if (typeof v === 'string') map[o] = v;
350
+ }
351
+ iniWf.set(k, { wf: e.wf, at: e.at || null, by: e.by || null, why: typeof e.why === 'string' ? e.why : '', from: typeof e.from === 'string' ? e.from : null, pmos: e.pmos === true,
352
+ map, before: before ? { map: before.map || null, before: before.before || null } : null, batch: typeof e.batch === 'string' ? e.batch : null, undo: e.undo === true,
353
+ left: isObj(e.moved) ? e.moved.from || null : null, landed: isObj(e.moved) ? e.moved.to || null : null });
342
354
  if (isObj(e.moved) && typeof e.moved.to === 'string') {
343
355
  stages.set(k, e.moved.to);
344
- moves.push({ at: e.at || null, by: e.by || null, board: b, id: e.id, from: e.moved.from || null, to: e.moved.to, why: 'workflow changed', warnings: [], via: 'ini-wf' });
356
+ moves.push({ at: e.at || null, by: e.by || null, board: b, id: e.id, from: e.moved.from || null, to: e.moved.to, why: 'workflow changed', warnings: [], via: 'ini-wf', ...(isObj(e.map) && e.undo !== true ? { map: e.map } : {}) });
345
357
  }
346
358
  } else if (e.kind === 'ini-end' && b && typeof e.id === 'string') {
347
359
  const k = key(b, e.id);
@@ -8,12 +8,16 @@
8
8
  * list(folded, counts?) → [workflow + { count }] Product feature first, archived last
9
9
  * resolve(folded, id) → the workflow (Product feature when the id is unknown or missing)
10
10
  * stageByRef(wf, ref) → the stage a key or a name names, or null
11
- * switchTarget(from, to, stageKey) → the key an initiative lands on when it switches workflow
11
+ * switchTarget(from, to, stageKey) → the key an initiative lands on when it switches workflow (the bridge's stage, see mapOf)
12
+ * proposeBridge(from, to) → { [fromKey]: toKey } Claude's proposal of where each old stage goes (batch 20 item 3)
13
+ * mapOf(from, to, override?) → { [fromKey]: toKey } every old stage's new stage: the PM's override, the saved bridge, the proposal
12
14
  * removedInUse(before, after, standing)→ [{ id, stage }] initiatives that stand in a stage the edit removes
13
15
  * stagesOf(wf, { judged, current }) → the initiative's own stages, each with its reading and status (the ONE function every surface reads)
14
16
  * copyOf(wf, name, taken) → a new editable copy
15
17
  *
16
- * A WORKFLOW is { id, name, icon, builtin?, decide, archived?, stages: [STAGE] }.
18
+ * A WORKFLOW is { id, name, icon, builtin?, decide, archived?, stages: [STAGE], bridge? }.
19
+ * bridge { from, map: { [fromStageKey]: stageKey } }: where each stage of the workflow it replaces lands (batch 20 item 3, canvas WmB).
20
+ * It is saved with the new workflow, so every later switch from `from` uses it. Many old stages may land in one new stage.
17
21
  * A STAGE is { key, name, cat, output: { name, kind, template? }, finish: [text], milestone, auto, when: { mode, text? }, then, unless: [{ text, to }] }.
18
22
  * cat ∈ CATS (To do, In progress, Done). Won't do and Archived (ENDS) are in every workflow and are not stages.
19
23
  * The first stage is always `triage`, in To do. `then` null means the next stage in the list. `unless` sends the initiative elsewhere
@@ -110,7 +114,21 @@ function check(wf) {
110
114
  if (s.then) { const k = ref(s.then); if (!k || k === s.key) return bad(`stage "${s.name}": Then must name another stage of this workflow`); s.then = k; }
111
115
  for (const u of s.unless) { const k = ref(u.to); if (!k || k === s.key) return bad(`stage "${s.name}": Unless must go to another stage of this workflow`); u.to = k; }
112
116
  }
113
- return { ok: true, workflow: { id, name, icon, decide, stages } };
117
+ let bridge = null;
118
+ if (wf.bridge != null) {
119
+ const br = wf.bridge;
120
+ if (!isObj(br) || typeof br.from !== 'string' || !br.from || !isObj(br.map)) return bad('a bridge is { from: the workflow id it replaces, map: { old stage key: stage of this workflow } }');
121
+ const ent = Object.entries(br.map);
122
+ if (ent.length > STAGES_MAX) return bad(`a bridge maps at most ${STAGES_MAX} stages`);
123
+ const map = {};
124
+ for (const [k, v] of ent) {
125
+ // a stage the bridge sends to that an edit removed drops out: that old stage falls back to Claude's proposal (mapOf), the save goes on
126
+ const nk = typeof v === 'string' ? ref(v) : null;
127
+ if (slug(k) && nk) map[slug(k)] = nk;
128
+ }
129
+ if (Object.keys(map).length && slug(br.from) !== id) bridge = { from: slug(br.from), map };
130
+ }
131
+ return { ok: true, workflow: { id, name, icon, decide, stages, ...(bridge ? { bridge } : {}) } };
114
132
  }
115
133
 
116
134
  /** Fold workflows.jsonl (objects or JSON strings), oldest first. */
@@ -125,7 +143,10 @@ function fold(lines) {
125
143
  const c = check(e.wf);
126
144
  if (!c.ok) continue;
127
145
  const was = byId.get(c.workflow.id);
128
- byId.set(c.workflow.id, { ...c.workflow, ...(was && was.archived ? { archived: true } : {}), at: e.at || null });
146
+ // copiedFrom: the workflow it began as a copy of (Product feature cannot be edited, so a simpler one starts as its copy): the ✦ that moves
147
+ // the initiatives over reads it (batch 20 item 3)
148
+ const cf = typeof e.copiedFrom === 'string' ? e.copiedFrom : was && was.copiedFrom ? was.copiedFrom : null;
149
+ byId.set(c.workflow.id, { ...c.workflow, ...(was && was.archived ? { archived: true } : {}), ...(cf ? { copiedFrom: cf } : {}), at: e.at || null });
129
150
  } else if (e.kind === 'wf-archive' && typeof e.id === 'string' && byId.has(e.id) && e.id !== PRODUCT_FEATURE_ID) {
130
151
  const w = { ...byId.get(e.id) };
131
152
  if (e.archived) w.archived = true; else delete w.archived;
@@ -154,14 +175,62 @@ function stageByRef(wf, ref) {
154
175
  return wf.stages.find((s) => s.key === r || s.key === old) || wf.stages.find((s) => s.name.toLowerCase() === low) || null;
155
176
  }
156
177
 
157
- /** Switching workflow (WfAChange): a stage of the same name carries over, else the first stage of the same category, else the first stage. */
178
+ /** Claude's proposal of where each stage of `from` lands in `to` (batch 20 item 3, canvas WmB). Order is kept, so no stage is guessed out of
179
+ * sequence. Anchors first: the same key or name, the same stem in the same category ("Discover" → "Discovery"), the stage whose output is Jira tickets, the first
180
+ * stage to the first and the last to the last. Between two anchors an old stage stays with the earlier one until a ◆ milestone closes it
181
+ * (Build, ◆ Deliver → Implementation; Monitor → Evaluation); a wider gap spreads in order. → { [fromKey]: toKey } for every stage of from. */
182
+ function proposeBridge(from, to) {
183
+ const F = (from && from.stages) || [], T = (to && to.stages) || [];
184
+ const out = {};
185
+ if (!T.length) return out;
186
+ const low = (x) => String(x || '').toLowerCase().trim();
187
+ const stem = (x) => { const v = low(x).replace(/[^a-z0-9]/g, ''); return v.length >= 6 ? v.slice(0, 6) : null; };
188
+ const anchor = F.map((s) => {
189
+ let j = T.findIndex((t) => t.key === s.key || low(t.name) === low(s.name));
190
+ if (j < 0 && stem(s.name)) j = T.findIndex((t) => t.cat === s.cat && stem(t.name) === stem(s.name));
191
+ return j;
192
+ });
193
+ const tj = T.findIndex((t) => t.output && t.output.kind === 'jira');
194
+ if (tj >= 0 && !anchor.includes(tj)) { const i = F.findIndex((s, n) => anchor[n] < 0 && s.output && s.output.kind === 'jira'); if (i >= 0) anchor[i] = tj; }
195
+ if (F.length && anchor[0] < 0) anchor[0] = 0;
196
+ if (F.length > 1 && anchor[F.length - 1] < 0) anchor[F.length - 1] = T.length - 1;
197
+ // keep the order: an anchor that would go back is dropped
198
+ let hi = -1;
199
+ for (let i = 0; i < F.length; i++) { if (anchor[i] < 0) continue; if (anchor[i] < hi) anchor[i] = -1; else hi = anchor[i]; }
200
+ for (let i = 0; i < F.length;) {
201
+ if (anchor[i] >= 0) { out[F[i].key] = T[anchor[i]].key; i++; continue; }
202
+ let j = i; while (j < F.length && anchor[j] < 0) j++;
203
+ const a = i > 0 ? anchor[i - 1] : 0, b = j < F.length ? anchor[j] : a, n = j - i;
204
+ let closed = false;
205
+ for (let k = 0; k < n; k++) {
206
+ let t = a;
207
+ if (b - a === 1) { t = closed ? b : a; if (F[i + k].milestone) closed = true; }
208
+ else if (b - a > 1) t = Math.min(b, a + Math.round(((k + 1) * (b - a)) / (n + 1)));
209
+ out[F[i + k].key] = T[t].key;
210
+ }
211
+ i = j;
212
+ }
213
+ return out;
214
+ }
215
+
216
+ /** Every stage of `from` and where it lands in `to`: the PM's own pick (override), the bridge saved with `to`, else Claude's proposal. */
217
+ function mapOf(from, to, override) {
218
+ const p = proposeBridge(from, to);
219
+ const br = to && to.bridge && from && to.bridge.from === from.id ? to.bridge.map : {};
220
+ const ok = (k) => !!k && !!(to.stages || []).find((s) => s.key === k);
221
+ const out = {};
222
+ for (const s of (from && from.stages) || []) {
223
+ const o = override && override[s.key];
224
+ out[s.key] = ok(o) ? o : ok(br[s.key]) ? br[s.key] : p[s.key];
225
+ }
226
+ return out;
227
+ }
228
+
229
+ /** Switching workflow (WfAChange): the stage the bridge (or Claude's proposal) sends the current stage to; no current stage, the first stage. */
158
230
  function switchTarget(from, to, stageRef) {
159
231
  const cur = stageByRef(from, stageRef);
160
232
  if (!cur) return to.stages[0].key;
161
- const same = to.stages.find((s) => s.name.toLowerCase() === cur.name.toLowerCase());
162
- if (same) return same.key;
163
- const cat = to.stages.find((s) => s.cat === cur.cat);
164
- return (cat || to.stages[0]).key;
233
+ return mapOf(from, to)[cur.key] || to.stages[0].key;
165
234
  }
166
235
 
167
236
  /** standing: [{ id, stage }] (stage = key). The ones whose stage the edit removes (WfARemove). */
@@ -200,5 +269,5 @@ const milestonesOf = (wf) => (wf || PRODUCT_FEATURE).stages.filter((s) => s.mile
200
269
 
201
270
  module.exports = {
202
271
  CATS, CAT_LABEL, ENDS, OUTPUT_KINDS, WHEN_MODES, DECIDE, ICONS, PRODUCT_FEATURE_ID, PRODUCT_FEATURE,
203
- slug, check, fold, list, resolve, stageByRef, switchTarget, removedInUse, stagesOf, copyOf, milestonesOf,
272
+ slug, check, fold, list, resolve, stageByRef, switchTarget, proposeBridge, mapOf, removedInUse, stagesOf, copyOf, milestonesOf,
204
273
  };
@@ -0,0 +1,57 @@
1
+ 'use strict';
2
+ /* lib/forecast-offer.js — a baseline worth offering in the goal Viewer (canvas FcViewer's ✓ "Without the promo weeks"; build brief Grill and
3
+ * Forecast). It finds the readings, and lib/forecast.js goalForecast says the range without them: the one straight-line method, nothing new.
4
+ * The goal Viewer asks for it when a goal opens (POST /api/forecast/offer, lib/routes-forecast.js); the ✓ keeps it through
5
+ * POST /api/forecast/baseline. Nothing is written until that ✓.
6
+ *
7
+ * offerOf(g, f, o) PURE → { label, exclude: [{ from, to }], likely, low, high, state } | null
8
+ * g: a goal of the Insights model (series, target, byAt, unit, direction, base, type). f: its forecast. o: { today }
9
+ * forGoal(g, today) PURE → the offer for a goal as the page sends it: its forecast worked out again here, then offerOf */
10
+ const FC = require('./forecast.js');
11
+
12
+ const DAY = 864e5, WEEK = 7 * DAY;
13
+ const fin = (v) => typeof v === 'number' && Number.isFinite(v);
14
+ const dayMs = (v) => { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(v || '')); return m ? Date.UTC(+m[1], +m[2] - 1, +m[3]) : null; };
15
+ const dayOf = (v) => (dayMs(v) !== null ? String(v).slice(0, 10) : null);
16
+
17
+ /** A baseline worth offering ("without the promo weeks", FcViewer's ✓): a run of 1 to 3 recent readings that sit off the goal's own line, and
18
+ * the range without them. The line is the median-slope line through the last 8 readings (so the odd ones do not bend it); a reading is off
19
+ * when it sits more than 3 times the usual distance from that line. The last reading is never left out. null when nothing sits off, a
20
+ * baseline is kept already, the forecast is not a range, or leaving the run out changes nothing a person would read (zero is silence).
21
+ * PURE → { label, exclude: [{ from, to }], likely, low, high, state } | null. f: the goal's forecast (goalForecast). */
22
+ function offerOf(g, f, o = {}) {
23
+ if (!f || f.baseline || !['on-track', 'at-risk', 'will-miss'].includes(f.state)) return null;
24
+ const S = (g.series || []).filter((r) => r && fin(r.v) && dayMs(r.at) !== null).slice(-8);
25
+ if (S.length < 5) return null;
26
+ const t = S.map((r) => dayMs(r.at) / WEEK), med = (a) => { const b = a.slice().sort((x, y) => x - y), m = b.length >> 1; return b.length % 2 ? b[m] : (b[m - 1] + b[m]) / 2; };
27
+ const sl = []; for (let i = 0; i < S.length; i++) for (let j = i + 1; j < S.length; j++) if (t[j] > t[i]) sl.push((S[j].v - S[i].v) / (t[j] - t[i]));
28
+ if (!sl.length) return null;
29
+ const k = med(sl), c = med(S.map((r, i) => r.v - k * t[i])), res = S.map((r, i) => r.v - (c + k * t[i]));
30
+ const spread = Math.max(...S.map((r) => r.v)) - Math.min(...S.map((r) => r.v)), cut = Math.max(3 * med(res.map(Math.abs)), 0.1 * spread);
31
+ if (!(cut > 0)) return null;
32
+ let best = null, run = null;
33
+ for (let i = 0; i < S.length - 1; i++) {
34
+ const off = Math.abs(res[i]) > cut, sign = Math.sign(res[i]);
35
+ if (off && run && run.sign === sign && run.to === i - 1 && run.to - run.from < 2) { run.to = i; run.w += Math.abs(res[i]); }
36
+ else run = off ? { from: i, to: i, sign, w: Math.abs(res[i]) } : null;
37
+ if (run && (!best || run.w > best.w)) best = { ...run };
38
+ }
39
+ if (!best) return null;
40
+ const a = dayOf(S[best.from].at), z = dayOf(S[best.to].at), exclude = [{ from: a, to: z }];
41
+ const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], dm = (d) => MON[+d.slice(5, 7) - 1] + ' ' + +d.slice(8, 10);
42
+ const label = 'without the reading' + (a === z ? ' of ' + dm(a) : 's of ' + dm(a) + ' to ' + dm(z));
43
+ const w = FC.goalForecast(g, { today: o.today, baseline: { label, exclude } });
44
+ if (!w || !['on-track', 'at-risk', 'will-miss'].includes(w.state)) return null;
45
+ const r1 = (v) => Math.round(v * 10) / 10;
46
+ if (r1(w.low) === r1(f.low) && r1(w.high) === r1(f.high)) return null;
47
+ return { label, exclude, likely: w.likely, low: w.low, high: w.high, state: w.state };
48
+ }
49
+
50
+ function forGoal(g, today) {
51
+ if (!g || typeof g !== 'object') return null;
52
+ const G = { id: String(g.id || ''), type: g.type, target: g.target, byAt: g.byAt, unit: g.unit, direction: g.direction, base: g.base,
53
+ series: Array.isArray(g.series) ? g.series.slice(-40).filter((r) => r && fin(r.v) && dayMs(r.at) !== null).map((r) => ({ at: dayOf(r.at), v: r.v })) : [] };
54
+ return offerOf(G, FC.goalForecast(G, { today }), { today });
55
+ }
56
+
57
+ module.exports = { offerOf, forGoal };
@@ -28,6 +28,7 @@ const WHY = {
28
28
  forecast: 'Its forecast just turned. Grill it: why, and what would bring it back?',
29
29
  move: 'Its scope or dates moved a lot. Grill it: is the plan still the right plan?',
30
30
  monthly: 'The monthly look at running work that feels off (it has late work). Grill it.',
31
+ ask: 'The PM asked for it in the initiative\'s chat. Grill it now: what would make it fail, and what is the next step?',
31
32
  };
32
33
 
33
34
  function promptOf(skill, o) {
@@ -48,7 +48,7 @@ const KINDS = new Set(['start', 'voices', 'end', 'snap', 'paused']);
48
48
  const ANGLES = Object.freeze(['premortem', 'redteam', 'voices', 'reframe', 'scope', 'whatif']);
49
49
  const LABEL = Object.freeze({ premortem: 'Premortem', redteam: 'Red team', voices: 'Voices', reframe: 'Reframe', scope: 'Scope', whatif: 'What-if' });
50
50
  const SIMULATED = Object.freeze({ voices: 'Simulated, not evidence', whatif: 'Simulated, not the plan' });
51
- const WHYS = Object.freeze(['exit', 'forecast', 'move', 'monthly']);
51
+ const WHYS = Object.freeze(['exit', 'forecast', 'move', 'monthly', 'ask']);
52
52
  const MODES = Object.freeze(['full', 'exits', 'off']);
53
53
  const VOICES_MIN = 3;
54
54
  const RUN_MAX_USD = 2; // one run never spends more than this
@@ -5,8 +5,9 @@
5
5
  * of <state>/insight-moves.jsonl. Pure apart from the ledger file, with no clock of its own: every time comes in.
6
6
  *
7
7
  * THE MOVES, tried in this order; the first that fits is the one drafted, and a finding with none draws no ✓ (zero is silence):
8
- * chase an active initiative that moves the goal is past its end date, has an owner and a Jira epic: a comment asking the owner for a new
9
- * date goes to the outbox (channel jira-write). Nothing is sent: it waits in the outbox for the PM's own Send.
8
+ * chase an active initiative that moves the goal is past its end date and has an owner: a note asking the owner for a new date goes to the
9
+ * outbox. With a Jira epic it is a comment on the epic (channel jira-write); with none it is a note to the owner (channel team-note,
10
+ * the channel the goal-watch thank-you uses), written from the PMOS records alone. Nothing is sent: it waits for the PM's own Send.
10
11
  * anchor nothing active moves the goal, and one active initiative of the board has no anchor that resolves while its title shares a word with
11
12
  * the goal: its parent_kr is set to the goal (an anchor the OKR files declare, the same check as any anchor change).
12
13
  * date the goal will miss its target at this pace and the straight line reaches the target on a later day: the KR metric record's `by`
@@ -56,16 +57,17 @@ function draftFor(f, model, o = {}) {
56
57
  if (!goal || !goal.id) return null;
57
58
  const today = DAY_RE.test(str(o.today)) ? o.today : null, t0 = ms(today);
58
59
  const active = (goal.moves || []).filter(ACTIVE);
59
- // chase: the initiative most days past its end, with someone to ask and a ticket to ask on
60
+ // chase: the initiative most days past its end, with someone to ask; on its Jira epic when it has one, else a note to the owner
60
61
  if (t0 !== null) {
61
- const late = active.filter((r) => r.owner && r.epic && ms(r.endAt) !== null && ms(r.endAt) < t0).sort((a, b) => ms(a.endAt) - ms(b.endAt))[0];
62
+ const late = active.filter((r) => r.owner && ms(r.endAt) !== null && ms(r.endAt) < t0).sort((a, b) => ms(a.endAt) - ms(b.endAt))[0];
62
63
  if (late) {
63
64
  const days = Math.round((t0 - ms(late.endAt)) / DAY), who = clip(late.owner, 40);
64
65
  const body = 'Hi ' + first(who) + ', ' + clip(late.title, 80) + ' was due on ' + full(late.endAt) + ' and is ' + days + (days === 1 ? ' day' : ' days') + ' over. '
65
66
  + clip(goal.title, 80) + ' is behind its line' + (goal.nowTxt ? ' at ' + goal.nowTxt : '') + (goal.targetTxt ? ' against a target of ' + goal.targetTxt : '') + '. What is the new date?';
66
- const m = { kind: 'chase', goal: goal.id, ini: late.id, owner: who, epic: late.epic, days, body,
67
+ const epic = str(late.epic).trim() || null, what = epic ? 'comment' : 'note';
68
+ const m = { kind: 'chase', goal: goal.id, ini: late.id, owner: who, epic, channel: epic ? 'jira-write' : 'team-note', days, body,
67
69
  text: 'Ask ' + who + ' for a new date on ' + clip(late.title, 60) + ', ' + days + (days === 1 ? ' day' : ' days') + ' over.',
68
- label: 'Put the comment to ' + who + ' in the outbox', said: 'The comment to ' + who + ' is in the outbox. Nothing is sent until you send it.' };
70
+ label: 'Put the ' + what + ' to ' + who + ' in the outbox', said: 'The ' + what + ' to ' + who + ' is in the outbox. Nothing is sent until you send it.' };
69
71
  return Object.assign(m, { sig: sigOf(m) });
70
72
  }
71
73
  }
@@ -1,11 +1,12 @@
1
1
  'use strict';
2
2
  /* news-for-you.js — New for you, which replaces the Inbox (initiative premium-uncovered-features, E2; canvas EvInbox, HmAround).
3
3
  *
4
- * build({ inbox, work, seen, name }) → { count, groups: [{ key, label, items }] } PURE
4
+ * build({ inbox, work, seen, name, bridges }) → { count, groups: [{ key, label, items }] } PURE
5
5
  * readSeen(runtimeDir) → Set of ids · appendSeen(runtimeDir, ids, now) · badSeen(body) → null | the reason
6
6
  *
7
7
  * New for you holds items for the PM's information only, in three groups (EvInbox):
8
- * propose Claude proposes: an agent's possible-overlap note between two open initiatives (batch 18 item 2b, OvA5), with its pick
8
+ * propose Claude proposes: an agent's possible-overlap note between two open initiatives (batch 18 item 2b, OvA5), with its pick; and
9
+ * moving the initiatives of a replaced workflow to the new one (batch 20 item 3, WmB; GET /api/workflows/proposals), raised once
9
10
  * given a task given to the PM: an open Work item that came from a source (Jira, the work breakdown), not one the PM typed
10
11
  * finished what the agents finished while the PM was away: the new items of the agent inbox (GET /api/inbox items)
11
12
  * An item leaves once it is seen: its id is in <runtime>/news-seen.jsonl. A passed review or a proposal is its initiative's next step, so it
@@ -58,11 +59,12 @@ function finishedItems(inbox, seen) {
58
59
 
59
60
  /** The groups, newest first in each; an empty group is left out. inbox: GET /api/inbox; work: GET /api/pm-items; name(id, ws?) → an initiative's
60
61
  * title, or '' (an id is never shown). */
61
- function build({ inbox = null, work = null, seen = new Set(), name = () => '' } = {}) {
62
+ function build({ inbox = null, work = null, seen = new Set(), name = () => '', bridges = [] } = {}) {
62
63
  const by = (a, b) => (b.at || 0) - (a.at || 0);
63
64
  const ib = inbox && inbox.ok !== false && Array.isArray(inbox.items) ? inbox.items : [];
64
65
  const groups = [
65
- { key: 'propose', label: 'Claude proposes', items: ib.filter((x) => x && x.id && x.overlap && x.overlap.with && !seen.has(x.id)).map((x) => overlapItem(x, name)).sort(by) },
66
+ { key: 'propose', label: 'Claude proposes', items: ib.filter((x) => x && x.id && x.overlap && x.overlap.with && !seen.has(x.id)).map((x) => overlapItem(x, name))
67
+ .concat((bridges || []).filter((x) => x && x.id && x.kind === 'wf-bridge' && !seen.has(x.id))).sort(by) },
66
68
  { key: 'given', label: 'Given to you', items: givenItems(work, seen, name).sort(by) },
67
69
  { key: 'finished', label: 'Finished while you were away', items: finishedItems(inbox, seen).sort(by) },
68
70
  ].filter((g) => g.items.length);
@@ -20,6 +20,8 @@ const RULE = [
20
20
  'You never set up, schedule, change or delete a report yourself, and you never write report-setups.jsonl: the PM presses in the tab.',
21
21
  '- A new report: {"kind":"report","proposal":{"name":"short name","purpose":"what it answers, one line","audience":"who reads it","output":"google-doc|google-slides|google-sheets|confluence|pdf","schedule":null,"sources":["what it draws from"]}}',
22
22
  ' schedule stays null unless the PM named one; then it is {"cadence":"daily|weekly|bi-weekly|monthly","day":"Mon","dayOfMonth":1,"time":"09:00"}. A report with no schedule runs once.',
23
+ ' A new report always starts with the standard sections: Headline, Timeline, Initiatives, New since last report, Decided this cycle, Needs your call, Sources. When the PM wants other contents (or you propose them), add "structure": "the sections it should have instead, in plain words" next to "proposal". Once the PM sets it up, the tab starts that change at once and the PM keeps it with one press.',
24
+ ' In your words, say what the tab will show: the standard sections, and the change in "structure" if there is one. Never describe contents the block does not carry.',
23
25
  '- A report that is set up already: {"kind":"report","id":"<its id>"} and, only when the PM asked for it, "schedule": {…} or "off", "structure": "the change to its sections, in the PM\'s words", "design": "the change to its look, in the PM\'s words".',
24
26
  ' The set-up reports are the setup lines of report-setups.jsonl (planning/ or pmos/state/); a later change line wins, a remove line deletes one.',
25
27
  '- A chart of one measure: {"kind":"chart","proposal":{"measure":"<KR metric id>","title":"short title","question":"what it answers","form":"line|bars|number|meter","range":null,"target":null,"better":"higher|lower","note":""}}',
@@ -5,6 +5,7 @@
5
5
  * POST /api/board-publish { ws, board, select, team, password, days, shared_by } -> { ok, id, url, ends }
6
6
  * POST /api/board-publish/republish { id } -> { ok, ends } the same selection, as the board is now; same link, same password
7
7
  * POST /api/board-publish/off { id } -> { ok } the host deletes the copy at once
8
+ * POST /api/board-publish/password { id } -> { ok, password } a new link password from the host, shown once; the old one stops
8
9
  * POST /api/board-publish/host { host } -> { ok, host } save the host address ('' clears it); PMOS_BOARDS_HOST wins over it
9
10
  * GET /api/board-publish/shared -> { ok, readAt, yours, teams } the Shared view: your links, and each joined team read now (lib/boards-teams.js)
10
11
  * POST /api/board-publish/join { invite } or { host, team, password } -> { ok, team } verified with the host first; the password stays on this computer
@@ -73,7 +74,7 @@ module.exports = {
73
74
  prefixes: ['/api/board-publish'],
74
75
  handle: async (req, res, url, ctx) => {
75
76
  const p = url.pathname;
76
- if (!/^\/api\/board-publish(\/(republish|off|host|shared|join|leave|open))?$/.test(p)) return false;
77
+ if (!/^\/api\/board-publish(\/(republish|off|password|host|shared|join|leave|open))?$/.test(p)) return false;
77
78
  const send = (obj, code) => { ctx.json(res, obj, code); return true; };
78
79
  const dir = stateDir(ctx);
79
80
  if (!dir) return send({ ok: false, error: 'No state folder.' }, 500);
@@ -97,7 +98,7 @@ module.exports = {
97
98
  const g = guard.requirePagePress(req, body);
98
99
  if (!g.ok) return send({ ok: false, error: g.error }, g.status);
99
100
  // D103 point 6 and PRD P2: a copy leaves this computer only on a press by the person. D98 lets an agent session take PM-only acts; this one it does not.
100
- if (g.actor && /^agent/.test(String(g.actor.by || ''))) return send({ ok: false, error: 'Publishing is a press on the page. An agent session cannot publish, republish or turn off a board.' }, 403);
101
+ if (g.actor && /^agent/.test(String(g.actor.by || ''))) return send({ ok: false, error: 'Publishing is a press on the page. An agent session cannot publish, republish, turn off or change the password of a board.' }, 403);
101
102
 
102
103
  if (p === '/api/board-publish/join') { // a team is joined by a pasted invite link, or by host, team and password typed
103
104
  const r = await Teams.join(dir, { invite: body.invite, host: body.host, team: body.team, password: body.password });
@@ -112,6 +113,10 @@ module.exports = {
112
113
  const r = Host.setHost(dir, body.host);
113
114
  return send(r.ok ? { ok: true, host: r.host } : { ok: false, error: r.error }, r.ok ? 200 : 400);
114
115
  }
116
+ if (p === '/api/board-publish/password') { // the answer carries the password once; nothing here keeps or logs it (D08)
117
+ const r = await Host.newPassword(dir, String(body.id || ''), { env });
118
+ return send(r.ok ? { ok: true, password: r.password } : { ok: false, error: r.error }, r.ok ? 200 : (r.status || 502));
119
+ }
115
120
  if (p === '/api/board-publish/off') {
116
121
  const r = await Host.turnOff(dir, String(body.id || ''), { env });
117
122
  return send(r.ok ? { ok: true } : { ok: false, error: r.error }, r.ok ? 200 : (r.status || 502));
@@ -366,8 +366,12 @@ const wfRowFields = (x) => {
366
366
  wfStages: x.stages.map((s) => ({ key: s.key, name: s.name, cat: s.cat, milestone: !!s.milestone, auto: !!s.auto, when: s.when, status: s.status, reading: s.reading,
367
367
  output: s.output, finish: s.finish })), // output and finish: what finishes the stage (the stage card's exit steps on a library workflow)
368
368
  ended: x.ended ? { as: x.ended.as, reason: x.ended.reason, note: x.ended.note, at: x.ended.at } : null,
369
+ // batch 20 item 3: where the tasks of an earlier workflow's stages sit now (old key → stage key), and the switch Undo can still put back (7 days)
370
+ wfMap: x.own && x.own.map ? x.own.map : null,
371
+ wfSwitch: x.own && x.own.batch && !x.own.undo && x.own.at && Date.now() - Date.parse(x.own.at) < UNDO_DAYS * 864e5 ? { batch: x.own.batch, at: x.own.at, from: x.own.from } : null,
369
372
  };
370
373
  };
374
+ const UNDO_DAYS = 7;
371
375
 
372
376
  /** The span of an initiative's own tasks: the earliest start (or due) to the latest due (or start). Won't do and Archived
373
377
  * tasks leave it out. null when no task has a date. Feedback batch 8 item 1: a bar drew only from breakdown items, so an initiative
@@ -490,7 +494,9 @@ function stageTasks(file, folded, board, row, by) {
490
494
  if (!list.length) return 0;
491
495
  const have = new Set();
492
496
  // a To finish task the PM deleted stays deleted: the next read must not make it again (batch 17 item 2: "Deleting task, but keep appearing")
493
- for (const t of [...tasksOfIni(folded, row.id), ...(folded.removed ? folded.removed.values() : [])]) if (t.initiative === row.id && t.from && t.from.stage === st.key) have.add(t.from.finish);
497
+ // a To finish task of an old stage that the switch merged into this one counts as this stage's (batch 20 item 3): a ticked item carries over
498
+ const mine = (k) => k === st.key || !!(row.wfMap && row.wfMap[k] === st.key);
499
+ for (const t of [...tasksOfIni(folded, row.id), ...(folded.removed ? folded.removed.values() : [])]) if (t.initiative === row.id && t.from && mine(t.from.stage)) have.add(t.from.finish);
494
500
  let n = 0;
495
501
  for (const f of list) {
496
502
  if (have.has(f)) continue;
@@ -787,7 +793,7 @@ const READS = {
787
793
  seedRows(ctx, r.w, r.fr, r.board, live);
788
794
  ctx.json(res, { ok: true, ws: r.w.id, board: r.board.id, build: r.board.build, jira: r.board.jira, jiraProjects: r.board.jiraProjects, items: itemsOf(r.w, r.fr, r.board, live),
789
795
  initiatives: live.map((x) => ({ id: x.id, title: x.title, stage: x.stage, cat: x.cat, status: x.status, owner: x.owner, anchor: x.anchor || '', horizon: x.horizon, start: x.start, end: x.end, progress: x.progress, template: x.template, epics: x.epics,
790
- stages: (x.wfStages || []).map((st) => ({ key: st.key, name: st.name, milestone: !!st.milestone })) })) }); // the sections a task can sit in (the task Viewer's move icon)
796
+ stages: (x.wfStages || []).map((st) => ({ key: st.key, name: st.name, milestone: !!st.milestone })), ...(x.wfMap ? { map: x.wfMap } : {}) })) }); // the sections a task can sit in (the task Viewer's move icon)
791
797
  },
792
798
  '/api/boards/sprints': (ctx, res, url) => {
793
799
  const r = boardRead(ctx, res, url);
@@ -1109,13 +1115,20 @@ const WRITES = {
1109
1115
  if (!b0 || boardIdOf(b0, p.fr.boards, p.fr.folded, p.w) !== p.board.id) return fail(ctx, res, 404, 'That initiative is not on this board any more.');
1110
1116
  const before = boardRow(p.board, b0, p.fr.folded);
1111
1117
  const from = WF.resolve(lib, before.wf.id);
1112
- let target = WF.switchTarget(from, to, before.wfStage.key);
1118
+ if (body.map != null && !isObj(body.map)) return fail(ctx, res, 400, 'map is { old stage key: stage of the new workflow }');
1119
+ if (body.batch != null && !(typeof body.batch === 'string' && /^[a-z0-9-]{4,60}$/.test(body.batch))) return fail(ctx, res, 400, 'batch is a short id');
1120
+ // every stage of the old workflow and where it lands (batch 20 item 3): the PM's picks, the bridge saved with the new workflow, Claude's
1121
+ // proposal. The map goes on the line, so the initiative's tasks move with their stage and none fall into "Not in a stage".
1122
+ const map = WF.mapOf(from, to, body.map || null);
1123
+ const curSt = WF.stageByRef(from, before.wfStage.key);
1124
+ let target = (curSt && map[curSt.key]) || to.stages[0].key;
1113
1125
  if (body.to != null) { const t = WF.stageByRef(to, body.to); if (!t) return fail(ctx, res, 400, `That stage is not part of ${to.name}.`); target = t.key; }
1114
1126
  const moved = { from: before.wfStage.key, to: target };
1115
1127
  // A workflow the PM saved in another workspace's library (Settings opens on the home workspace) is written into this one's first, so
1116
1128
  // this workspace's own record still reads the initiative's workflow when the other workspace is not open.
1117
1129
  if (found.ws) { const a = WS.adopt(ctx.stateDirFor(p.w), to, g.actor, found.ws.id); if (!a.ok) return fail(ctx, res, a.status || 400, a.error); }
1118
- append(p.file, g.actor, { kind: 'ini-wf', board: p.board.id, id: body.id, wf: to.id, from: from.id, moved, why: body.why ? body.why.trim() : '', ...(body.pmos === true ? { pmos: true } : {}) });
1130
+ append(p.file, g.actor, { kind: 'ini-wf', board: p.board.id, id: body.id, wf: to.id, from: from.id, moved, map, why: body.why ? body.why.trim() : '', ...(body.pmos === true ? { pmos: true } : {}),
1131
+ ...(body.batch ? { batch: body.batch } : {}), ...(body.undo === true ? { undo: true } : {}) });
1119
1132
  const f1 = foldOf(ctx, p.w), row = boardRow(p.board, b0, f1);
1120
1133
  const made = stageTasks(p.file, f1, p.board, row, g.actor.by);
1121
1134
  ctx.json(res, { ok: true, row, moved, ...(made ? { tasksMade: made } : {}) });
@@ -1741,4 +1754,4 @@ function meetingBoards(ctx) {
1741
1754
  return { list, detail };
1742
1755
  }
1743
1756
 
1744
- module.exports = { prefixes: ['/api/boards'], handle, postFrame, needRows, itemsOf, readLedger, foldOf, epicsOf, rowsOfBoard, invalidateRows: (w) => { rowsLib.invalidate(w.root); rowCache.delete(w.root); }, move, switchWorkflow, taskState, taskAdd, taskEdit, writeAs, taskDelete, taskRestore, initiativeWorkflow, seedInitiative, stageTasks, boardIndex, appendScanAsk, scanDeclineSignal, createAndPlace, ledgerFile, append, frameFor, boardIdOf, meetingBoards, boardsOf, baseRows, boardRow, taskSpanOf, workflowRowOf, foldOf, portfolio, SELF_REFUSAL, NO_STATE };
1757
+ module.exports = { prefixes: ['/api/boards'], handle, tasksOfIni, postFrame, needRows, itemsOf, readLedger, foldOf, epicsOf, rowsOfBoard, invalidateRows: (w) => { rowsLib.invalidate(w.root); rowCache.delete(w.root); }, move, switchWorkflow, taskState, taskAdd, taskEdit, writeAs, taskDelete, taskRestore, initiativeWorkflow, seedInitiative, stageTasks, boardIndex, appendScanAsk, scanDeclineSignal, createAndPlace, ledgerFile, append, frameFor, boardIdOf, meetingBoards, boardsOf, baseRows, boardRow, taskSpanOf, workflowRowOf, foldOf, portfolio, SELF_REFUSAL, NO_STATE };
@@ -57,6 +57,18 @@ const rootOf = (url, ctx) => {
57
57
  /** The PM's own calls (initiative briefing-premium-writes). Each appends one record and answers with the rebuilt model. */
58
58
  /** An initiative chat's workflow and stage (lib/initiative-chat.js infoOf), from the Board's own row (lib/routes-boards.js initiativeWorkflow):
59
59
  * the chat's workspace first, then the others (Home opens initiatives of other products too). null while the rows are being read. */
60
+ /** "grill this" (or "grill it", "grill <name>") in an initiative's chat: start Claude's grill run now and tell the chat's Claude, in one line, what
61
+ * happened, so it answers in a line and does not grill a second time in the chat. → { text, started } | null when the message is not that ask. */
62
+ const GRILL_RE = /^\s*(please\s+)?(grill|re-?grill)\b/i;
63
+ function grillAsk(ctx, key, text, wsId) {
64
+ const k = String(key || ''), q = String(text == null ? '' : text);
65
+ if (!/^init:/.test(k) || !GRILL_RE.test(q) || typeof ctx.grillStart !== 'function') return null;
66
+ const ini = k.replace(/^init:/, '').replace(/:\d+$/, '');
67
+ let r; try { r = ctx.grillStart({ ws: wsId, ini, why: 'ask', key: 'ask:' + Date.now(), detail: q.slice(0, 200) }); } catch (e) { r = { ok: false, error: String((e && e.message) || e).slice(0, 160) }; }
68
+ const note = r && r.ok ? '[PMOS] A grill run on this initiative started in the background just now. Its findings will wait under the initiative\'s ✦. Say so in one line. Do not grill it again here.'
69
+ : '[PMOS] The grill run did not start: ' + ((r && r.error) || 'no answer') + '. Say so in one line, and what would let it run.';
70
+ return { text: note + '\n\nThe PM says: ' + q, started: !!(r && r.ok) };
71
+ }
60
72
  function iniInfoOf(ctx, key, wsId) {
61
73
  const id = String(key || '').replace(/^init:/, '').replace(/:\d+$/, '');
62
74
  if (!/^init:/.test(String(key || '')) || !id) return null;
@@ -111,7 +123,9 @@ async function post(req, res, url, ctx) {
111
123
  // premium-chat-attach A5: the files a message names must be saved files of its conversation; one closing line names each for Claude
112
124
  const att = Files.pathsOf({ runtimeDir, key: b.key, names: b.files });
113
125
  if (!att.ok) { ctx.json(res, { ok: false, error: att.error }, att.status); return true; }
114
- const a = (ctx.chatSessions ? Ag.chat : Ag.ask)({ runtimeDir, key: b.key, text: Files.withFiles(b.text, att.paths), context: b.context, sessions: ctx.chatSessions, model: /^work:/.test(String(b.key || '')) ? WP.peekModel() : /^board:/.test(String(b.key || '')) ? BoardP.peekModel() : /^ins:/.test(String(b.key || '')) ? InsP.peekModel() : /^(init|doc):/.test(String(b.key || '')) ? InitP.peekModel() : sk || (/^src:/.test(String(b.key || '')) && !(b.key === 'src:this-page' && url.searchParams.get('ws'))) ? Prod.peekModel() : BP.peekModel(root), spawnSession: ctx.spawnSession, wsId, iniInfo: () => iniInfoOf(ctx, b.key, wsId) });
126
+ // batch 20 item 13: the PM can start a grill any time by asking for it in an initiative's chat; it also runs by itself
127
+ const g2 = grillAsk(ctx, b.key, b.text, wsId);
128
+ const a = (ctx.chatSessions ? Ag.chat : Ag.ask)({ runtimeDir, key: b.key, text: Files.withFiles(g2 ? g2.text : b.text, att.paths), context: b.context, sessions: ctx.chatSessions, model: /^work:/.test(String(b.key || '')) ? WP.peekModel() : /^board:/.test(String(b.key || '')) ? BoardP.peekModel() : /^ins:/.test(String(b.key || '')) ? InsP.peekModel() : /^(init|doc):/.test(String(b.key || '')) ? InitP.peekModel() : sk || (/^src:/.test(String(b.key || '')) && !(b.key === 'src:this-page' && url.searchParams.get('ws'))) ? Prod.peekModel() : BP.peekModel(root), spawnSession: ctx.spawnSession, wsId, iniInfo: () => iniInfoOf(ctx, b.key, wsId) });
115
129
  ctx.json(res, a.body, a.status);
116
130
  return true;
117
131
  }
@@ -190,7 +204,7 @@ async function chatFile(req, res, url, ctx) {
190
204
  return true;
191
205
  }
192
206
 
193
- module.exports = {
207
+ module.exports = { grillAsk,
194
208
  products,
195
209
  prefixes: ['/api/briefing-premium', '/api/chat-file'],
196
210
  handle: async (req, res, url, ctx) => {