create-pmos 0.422.0 → 0.424.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 (102) hide show
  1. package/package.json +25 -25
  2. package/payload/KIT-VERSION +2 -2
  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/payload/state/log.md +1 -1
  7. package/workspace/board-programs-test.js +28 -0
  8. package/workspace/briefing-premium-adddoc-test.js +1 -1
  9. package/workspace/briefing-premium-board-test.js +12 -10
  10. package/workspace/briefing-premium-initiative-test.js +30 -38
  11. package/workspace/briefing-premium-products-test.js +16 -3
  12. package/workspace/changelog.json +24 -0
  13. package/workspace/guide/briefing-premium.md +1 -1
  14. package/workspace/guide/claude-proposes.md +37 -0
  15. package/workspace/guide/home.md +9 -2
  16. package/workspace/guide/index.md +1 -0
  17. package/workspace/guide/programs.md +1 -0
  18. package/workspace/guide/workflows.md +5 -1
  19. package/workspace/home-pill-test.js +138 -0
  20. package/workspace/ini-workflow-test.js +4 -4
  21. package/workspace/lib/board-premium.js +3 -2
  22. package/workspace/lib/custom-docs.js +65 -3
  23. package/workspace/lib/engine/boards.js +25 -2
  24. package/workspace/lib/headless.js +14 -1
  25. package/workspace/lib/initiative-writer.js +63 -1
  26. package/workspace/lib/plan-items.js +36 -5
  27. package/workspace/lib/pmos-verbs.js +3 -0
  28. package/workspace/lib/programs.js +11 -3
  29. package/workspace/lib/proposal-runs.js +148 -0
  30. package/workspace/lib/proposals.js +370 -0
  31. package/workspace/lib/propose-cli.js +96 -0
  32. package/workspace/lib/route-modules.js +2 -0
  33. package/workspace/lib/routes-board-premium.js +33 -0
  34. package/workspace/lib/routes-boards.js +50 -10
  35. package/workspace/lib/routes-initiatives.js +12 -0
  36. package/workspace/lib/routes-proposals.js +325 -0
  37. package/workspace/lib/routes-task-links.js +336 -0
  38. package/workspace/lib/split-merge-suggest.js +162 -0
  39. package/workspace/lib/split-merge.js +379 -0
  40. package/workspace/lib/task-cli.js +58 -5
  41. package/workspace/lib/task-items.js +14 -2
  42. package/workspace/lib/task-links.js +422 -0
  43. package/workspace/package-lock.json +2 -2
  44. package/workspace/package.json +1 -1
  45. package/workspace/premium-board-actions-test.js +4 -4
  46. package/workspace/premium-core-doc-issue-test.js +2 -2
  47. package/workspace/premium-vw-backlog-test.js +3 -3
  48. package/workspace/premium-vw-item-test.js +3 -3
  49. package/workspace/premium-vw-jira-test.js +6 -6
  50. package/workspace/product-lane-test.js +165 -0
  51. package/workspace/program-panel-test.js +1 -1
  52. package/workspace/public/pm/bd-asks.js +3 -0
  53. package/workspace/public/pm/bd-ini-panel.js +16 -6
  54. package/workspace/public/pm/bd-prog.js +6 -1
  55. package/workspace/public/pm/bd-span.js +69 -15
  56. package/workspace/public/pm/bd-views.js +3 -2
  57. package/workspace/public/pm/cozy-board.css +10 -0
  58. package/workspace/public/pm/cozy-today.css +23 -0
  59. package/workspace/public/pm/cozy-viewer.js +14 -3
  60. package/workspace/public/pm/cozy-vw-shell.css +8 -0
  61. package/workspace/public/pm/home-app.js +45 -14
  62. package/workspace/public/pm/home-ini-model.js +0 -34
  63. package/workspace/public/pm/home-ini.js +72 -204
  64. package/workspace/public/pm/home-task.js +2 -1
  65. package/workspace/public/pm/home-today.js +66 -16
  66. package/workspace/public/pm/ini-groups.js +253 -0
  67. package/workspace/public/pm/ini-links.js +519 -0
  68. package/workspace/public/pm/ini-props.js +218 -0
  69. package/workspace/public/pm/ini-tasks.js +58 -22
  70. package/workspace/public/pm/ini-versions.js +14 -9
  71. package/workspace/public/pm/ini-view-model.js +93 -4
  72. package/workspace/public/pm/ini-view.css +306 -18
  73. package/workspace/public/pm/ini-view.js +161 -36
  74. package/workspace/public/pm/premium-board.js +54 -6
  75. package/workspace/public/pm/premium-vw-item.js +2 -1
  76. package/workspace/public/pm/split-merge.css +77 -0
  77. package/workspace/public/pm/split-merge.js +265 -0
  78. package/workspace/public/pm/stage-line.js +414 -0
  79. package/workspace/public/pm/task-card.css +13 -0
  80. package/workspace/public/pm/task-card.js +42 -5
  81. package/workspace/public/pm/wf-page.css +2 -0
  82. package/workspace/public/pm/wf-page.js +2 -0
  83. package/workspace/public/pm/wf-stage.js +2 -1
  84. package/workspace/server.js +52 -3
  85. package/workspace/skills/initiative-propose.skill +45 -0
  86. package/workspace/split-merge-ui-test.js +175 -0
  87. package/workspace/stage-card-test.js +13 -12
  88. package/workspace/task-card-test.js +3 -2
  89. package/workspace/task-delete-test.js +126 -0
  90. package/workspace/task-links-test.js +239 -0
  91. package/workspace/task-milestones-test.js +1 -1
  92. package/workspace/task-plans-test.js +6 -0
  93. package/workspace/task-views-test.js +1 -1
  94. package/workspace/test-lists/bd-ini-panel.json +8 -2
  95. package/workspace/test-lists/claude-proposes.json +5 -0
  96. package/workspace/test-lists/home-sessions-pill.json +6 -0
  97. package/workspace/test-lists/product-lane.json +6 -0
  98. package/workspace/test-lists/split-merge.json +15 -0
  99. package/workspace/test-lists/task-delete.json +5 -0
  100. package/workspace/test-lists/task-links.json +6 -0
  101. package/workspace/tk-tasks-test.js +186 -57
  102. package/workspace/workflows-setup-test.js +4 -3
@@ -535,6 +535,12 @@ function itemsOf(w, fr, board, rows) {
535
535
  for (const t of fr.folded.tasks.values()) if (t.board === board.id && ids.has(t.initiative)) out.push(B.taskItem(t));
536
536
  out.push(...TI.rowsOf(w.root, ids, board.id)); // one kind of task: an initiative's breakdown items show as its tasks (lib/task-items.js)
537
537
  for (const x of out) if (x.src === 'jira') x.notes = (fr.folded.ticketNotes && fr.folded.ticketNotes.get(board.id + '\u0000' + x.key)) || ''; // the PM's notes (canvas XetX1Jira)
538
+ // the PM's own days for a Jira ticket (batch 11 item 23): kept in PMOS, they win over Jira's, and the row says so
539
+ const TD = fr.folded.ticketDates || new Map();
540
+ if (TD.size) for (const x of out) if (x.src === 'jira' && x.key) { const v = TD.get(board.id + '\u0000' + String(x.key).toUpperCase()); if (v) { if (v.start) x.start = v.start; if (v.due) x.end = v.due; x.datesHere = true; } }
541
+ // a split or a merge took a Jira ticket to another initiative (batch 11 item 14): PMOS holds where it belongs; Jira is not written to
542
+ const TM = fr.folded.ticketMoves || new Map();
543
+ if (TM.size) for (const x of out) if (x.src === 'jira' && x.key && TM.has(x.key)) x.ini = TM.get(x.key);
538
544
  // a task's place in the breakdown (one view): the PM's own choice, else the stage whose To finish entry made it
539
545
  const SEC = fr.folded.sections || new Map();
540
546
  for (const x of out) if (x.src === 'pmos' && x.kind !== 'Epic') { if (SEC.has(x.uid)) x.section = SEC.get(x.uid); else if (x.from && x.from.stage) x.section = x.from.stage; }
@@ -671,7 +677,9 @@ const READS = {
671
677
  for (const m of F.moves) if (m.id === id) history.push({ kind: m.via === 'move' ? 'move' : m.via, ...pageMove(m) });
672
678
  for (const e of F.events) {
673
679
  if (e.kind === 'assign' && e.id === id) history.push({ kind: 'assign', at: e.at || null, by: actorLib.pageName(e.by || null), board: e.board || null, to: e.to });
674
- if (e.kind === 'ini-archive' && (e.id === id || e.into === id)) history.push({ kind: e.archived === false ? 'restore' : (e.into ? 'merge' : 'archive'), at: e.at || null, by: actorLib.pageName(e.by || null), board: e.board || null, id: e.id, into: e.into || null, reason: e.reason || '' });
680
+ if (e.kind === 'ini-archive' && !e.op && (e.id === id || e.into === id)) history.push({ kind: e.archived === false ? 'restore' : (e.into ? 'merge' : 'archive'), at: e.at || null, by: actorLib.pageName(e.by || null), board: e.board || null, id: e.id, into: e.into || null, reason: e.reason || '' });
681
+ // split or merge (batch 11 item 14): one line on each side; an undone one says so
682
+ if ((e.kind === 'ini-split' || e.kind === 'ini-merge') && (e.id === id || e.to === id)) history.push({ kind: e.kind === 'ini-split' ? (e.id === id ? 'split-off' : 'split-from') : (e.id === id ? 'merged-into' : 'merged-in'), at: e.at || null, by: actorLib.pageName(e.by || null), board: e.board || null, id: e.id, to: e.to, title: e.id === id ? e.toTitle || e.to : e.fromTitle || e.id, undone: F.smUndone ? F.smUndone.has(e.op) : false });
675
683
  if (e.kind === 'ini-workflow' && e.id === id && Array.isArray(e.stages)) history.push({ kind: 'workflow', at: e.at || null, by: actorLib.pageName(e.by || null), board: e.board || null, template: e.template || null, stages: e.stages.map((x) => x && x.name).filter(Boolean) });
676
684
  }
677
685
  history.sort((a, b) => String(b.at || '').localeCompare(String(a.at || '')));
@@ -1159,13 +1167,19 @@ const WRITES = {
1159
1167
  },
1160
1168
  '/api/boards/tasks/delete': (ctx, res, body, g) => {
1161
1169
  // a task added by mistake (batch 7 item 5): the task-remove line takes it out everywhere; tasks/restore is its Undo. Archived stays for
1162
- // work that stopped. A breakdown item is withdrawn (Won't do), never deleted.
1170
+ // work that stopped. A breakdown item is withdrawn with why "deleted", and a restored line is its Undo (batch 11 item 16).
1163
1171
  const p = postFrame(ctx, res, body);
1164
1172
  if (!p) return;
1165
- if (TI.isItemId(body.task)) return fail(ctx, res, 409, `${body.task} is a breakdown item: set it to Won't do instead`);
1173
+ if (body.why != null && (typeof body.why !== 'string' || body.why.length > 500)) return fail(ctx, res, 400, 'why is text of at most 500 characters');
1174
+ if (!B.taskOf(p.fr.folded, body.task) && TI.isItemId(body.task)) {
1175
+ const it = itemOnBoard(ctx, res, p, body.task);
1176
+ if (!it) return;
1177
+ const w = TI.write(p.w.root, TI.deleteEvents(it, body.why).events, g.actor, g.cli || null);
1178
+ if (!w.ok) return fail(ctx, res, w.status || 400, w.error);
1179
+ return ctx.json(res, { ok: true, task: it.id, title: it.title });
1180
+ }
1166
1181
  const t = B.taskOf(p.fr.folded, body.task);
1167
1182
  if (!t || t.board !== p.board.id) return fail(ctx, res, 404, `no PMOS task ${body.task} on this board`);
1168
- if (body.why != null && (typeof body.why !== 'string' || body.why.length > 500)) return fail(ctx, res, 400, 'why is text of at most 500 characters');
1169
1183
  if (!p.file) return fail(ctx, res, 409, NO_STATE);
1170
1184
  append(p.file, g.actor, { kind: 'task-remove', board: p.board.id, task: t.id, why: body.why ? String(body.why).trim() : 'deleted' });
1171
1185
  ctx.json(res, { ok: true, task: t.id, title: t.title });
@@ -1175,6 +1189,17 @@ const WRITES = {
1175
1189
  if (!p) return;
1176
1190
  if (typeof body.task !== 'string' || !body.task) return fail(ctx, res, 400, 'task is required');
1177
1191
  if (B.taskOf(p.fr.folded, body.task)) return fail(ctx, res, 409, `${body.task} is not deleted`);
1192
+ if (TI.isItemId(body.task)) {
1193
+ if (TI.itemOf(p.w.root, body.task)) return fail(ctx, res, 409, `${body.task} is not deleted`);
1194
+ const was = TI.goneOf(p.w.root, body.task);
1195
+ const base = was && needRows(ctx, res, p.w);
1196
+ if (was && !base) return;
1197
+ const b0 = base && base.find((r) => r.id === was.initiative);
1198
+ if (!was || !b0 || boardIdOf(b0, p.fr.boards, p.fr.folded, p.w) !== p.board.id) return fail(ctx, res, 404, `no deleted task ${body.task} on this board`);
1199
+ const w = TI.write(p.w.root, TI.restoreEvents(body.task).events, g.actor, g.cli || null);
1200
+ if (!w.ok) return fail(ctx, res, w.status || 400, w.error);
1201
+ return ctx.json(res, { ok: true, task: body.task });
1202
+ }
1178
1203
  const ev = [...p.fr.folded.events].reverse().find((e) => e.kind === 'task-remove' && e.task === body.task);
1179
1204
  if (!ev || ev.board !== p.board.id) return fail(ctx, res, 404, `no deleted task ${body.task} on this board`);
1180
1205
  if (!p.file) return fail(ctx, res, 409, NO_STATE);
@@ -1203,13 +1228,28 @@ const WRITES = {
1203
1228
  const p = postFrame(ctx, res, body);
1204
1229
  if (!p) return;
1205
1230
  if (body.milestone != null && typeof body.milestone !== 'boolean') return fail(ctx, res, 400, 'milestone is true or false');
1206
- // a Jira ticket takes the milestone flag only: Jira keeps its title, status and dates (feedback batch 11 item 3)
1231
+ // a Jira ticket takes the milestone flag (feedback batch 11 item 3) and the PM's own start and due days, kept in PMOS only (item 23):
1232
+ // Jira keeps its title, status and assignee, and nothing is written to Jira
1207
1233
  if (typeof body.task === 'string' && B.JIRA_KEY_RE.test(body.task) && !B.taskOf(p.fr.folded, body.task)) {
1208
- if (body.milestone == null || ['owner', 'notes', 'start', 'due', 'initiative', 'section'].some((k) => body[k] != null)) return fail(ctx, res, 409, 'Jira owns this ticket: only its milestone flag changes here');
1234
+ if (['owner', 'notes', 'initiative', 'section'].some((k) => body[k] != null)) return fail(ctx, res, 409, 'Jira owns this ticket: only its dates and its milestone flag change here');
1235
+ if (body.milestone == null && body.start == null && body.due == null) return fail(ctx, res, 400, 'nothing to change: send start, due or milestone');
1236
+ for (const k of ['start', 'due']) if (body[k] != null && body[k] !== '' && !/^\d{4}-\d{2}-\d{2}$/.test(String(body[k]))) return fail(ctx, res, 400, `${k} is a day, YYYY-MM-DD, or '' for none`);
1209
1237
  if (!p.file) return fail(ctx, res, 409, NO_STATE);
1210
- const MS0 = p.fr.folded.milestones || new Map();
1211
- append(p.file, g.actor, { kind: 'task-milestone', board: p.board.id, task: body.task, milestone: body.milestone, why: body.milestone ? 'made a milestone' : 'no longer a milestone' });
1212
- return ctx.json(res, { ok: true, from: { milestone: !!MS0.get(body.task) }, item: null });
1238
+ const from = {}, ref = body.task.toUpperCase();
1239
+ if (body.start != null || body.due != null) {
1240
+ const TD = p.fr.folded.ticketDates || new Map(), was = TD.get(p.board.id + '\u0000' + ref) || { start: '', due: '' };
1241
+ const next = { start: body.start != null ? String(body.start) : was.start, due: body.due != null ? String(body.due) : was.due };
1242
+ if (next.start && next.due && next.start > next.due) return fail(ctx, res, 400, 'the start is after the due day');
1243
+ if (body.start != null) from.start = was.start;
1244
+ if (body.due != null) from.due = was.due;
1245
+ append(p.file, g.actor, { kind: 'ticket-dates', board: p.board.id, ref, ...next, why: 'dates kept in PMOS' });
1246
+ }
1247
+ if (body.milestone != null) {
1248
+ const MS0 = p.fr.folded.milestones || new Map();
1249
+ from.milestone = !!MS0.get(body.task);
1250
+ append(p.file, g.actor, { kind: 'task-milestone', board: p.board.id, task: body.task, milestone: body.milestone, why: body.milestone ? 'made a milestone' : 'no longer a milestone' });
1251
+ }
1252
+ return ctx.json(res, { ok: true, from, item: null });
1213
1253
  }
1214
1254
  const t0 = B.taskOf(p.fr.folded, body.task);
1215
1255
  let t = t0;
@@ -1542,4 +1582,4 @@ function meetingBoards(ctx) {
1542
1582
  return { list, detail };
1543
1583
  }
1544
1584
 
1545
- module.exports = { prefixes: ['/api/boards'], handle, postFrame, needRows, itemsOf, move, switchWorkflow, taskState, taskAdd, taskEdit, 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 };
1585
+ 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 };
@@ -662,6 +662,18 @@ async function handle(req, res, url, ctx) {
662
662
  ctx.json(res, { ok: true, id: r.id, from: r.from, title: r.title, path: r.path, sig: sigOf(w.root) });
663
663
  return true;
664
664
  }
665
+ // split or merge initiatives (feedback batch 11 item 14; lib/split-merge.js): the editor's button or ✓ on Claude's card, Undo, and ✕ Not now
666
+ const SM_ROUTES = { '/api/initiatives/split': 'split', '/api/initiatives/merge': 'merge', '/api/initiatives/sm-undo': 'undo', '/api/initiatives/suggest': 'dismiss' };
667
+ if (SM_ROUTES[p]) {
668
+ const g = guard.requirePagePress(req, body);
669
+ if (!g.ok) return answer(ctx, res, g), true;
670
+ let r;
671
+ try { r = require('./split-merge.js')[SM_ROUTES[p]](ctx, w, body, g.actor); }
672
+ catch (e) { r = { ok: false, status: 500, error: String((e && e.message) || e).slice(0, 200) }; }
673
+ if (!r.ok) { const { ok: _o, status, ...rest } = r; ctx.json(res, { ok: false, ...rest }, status || 400); return true; }
674
+ ctx.json(res, { ...r, ws: w.id, sig: sigOf(w.root) });
675
+ return true;
676
+ }
665
677
  if (p === '/api/initiatives') {
666
678
  const g = guard.requirePagePress(req, body);
667
679
  if (!g.ok) return answer(ctx, res, g), true;
@@ -0,0 +1,325 @@
1
+ 'use strict';
2
+ /* routes-proposals.js — what Claude proposes on an initiative, under its one blue ✦ (feedback batch 12 items 2, 3 and 4; canvas In
3
+ * development, rows "Populate initiative" and "Task proposals"). The fold and the engines are lib/proposals.js; every write to a task or an
4
+ * initiative goes through the board's own writer (routes-boards writeAs), so its checks and its ledger line are the route's own. A Jira
5
+ * ticket is never written: a proposal for one becomes a drafted comment in the outbox (rule 8). A draft plan is never touched (rule 9).
6
+ *
7
+ * GET /api/proposals?ws&board&initiative → { ok, props, found } props: lib/proposals.js viewOf (null: nothing to show)
8
+ * POST /api/proposals/keep { ws, board, initiative, ids?: [id] | all: true, choices?: { <from>><to>: 'keep' | 'ignore' } }
9
+ * → { ok, batch, said, counts, props } ✓ one proposal, or ✓ in the header (all: every one Claude is sure of;
10
+ * Check these and a Jira ticket's comment never ride on it). One batch, one toast, one Undo.
11
+ * POST /api/proposals/drop { ws, board, initiative, sig } → { ok } ✕ on a proposal or on one item of it, for good (rule 7)
12
+ * POST /api/proposals/undo { ws, board, batch } → { ok, back, kept } the whole batch; a task changed since keeps its change
13
+ * POST /api/proposals/stop { ws, board, initiative } → { ok } ■ Stop: the look ends; what was found so far stays proposed
14
+ * POST /api/proposals/look { ws, board, initiative, why?: 'populate' | 'check' } → { ok, started } Claude looks now (the New initiative
15
+ * panel's Create sends it at once; the server's tick starts the same run for every other way an initiative is made)
16
+ * GET /api/proposals/history?ws&board&task → { ok, history } Claude's approved changes to one task (lib/proposals.js historyOf)
17
+ *
18
+ * viewFor(ctx, w, board, ini) the same view outside HTTP (`pmos propose status`)
19
+ *
20
+ * Every POST passes pm-guard requirePagePress. With no state folder the read answers nothing and every write answers 409. */
21
+ const fs = require('fs');
22
+ const path = require('path');
23
+ const crypto = require('crypto');
24
+ const guard = require('./pm-guard.js');
25
+ const PR = require('./proposals.js');
26
+ const TL = require('./task-links.js');
27
+ const RB = require('./routes-boards.js');
28
+ const TLR = require('./routes-task-links.js');
29
+
30
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
31
+ const fail = (ctx, res, status, error, extra = {}) => { ctx.json(res, { ok: false, error, ...extra }, status); return true; };
32
+ const NO_STATE = 'This repository has no PMOS state folder (pmos/state, state or .pmos). Nothing is saved until the folder exists.';
33
+ const dirOf = (ctx, w) => (ctx.stateDirFor ? ctx.stateDirFor(w) : null);
34
+ const todayIso = () => { const d = new Date(); return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0'); };
35
+ const plural = (n, a, b) => n + ' ' + (n === 1 ? a : b);
36
+ const srcText = (p) => (p.sources || []).map((s) => s.label).join(', ');
37
+
38
+ /* ── the view ── */
39
+ function rowOf(f, ini) { return (f.rows || []).find((r) => r.id === ini) || null; }
40
+ function stagesOf(ctx, p, ini) {
41
+ try { const r = RB.initiativeWorkflow(ctx, p.w, ini); if (r.ok) return (r.row.wfStages || []).map((s) => ({ key: s.key, name: s.name })); } catch { /* none */ }
42
+ return [];
43
+ }
44
+ function view(ctx, p, ini, f) {
45
+ const dir = dirOf(ctx, p.w); if (!dir) return null;
46
+ f = f || TLR.frame(ctx, p.w, p.board);
47
+ if (!f) return null;
48
+ const F = PR.read(dir), LF = TL.read(dir);
49
+ const links = TL.linksOf(LF).filter((l) => f.T.has(l.from) && f.T.has(l.to));
50
+ let linkProps = [];
51
+ try { const lv = TL.viewOf(LF, ini, { T: f.T, today: todayIso(), limit: f.limit, src: TLR.sourcesOf(p.w.root, ini, f.items) }); linkProps = lv ? lv.proposals : []; } catch { linkProps = []; }
52
+ const T = new Map(); for (const x of f.items) { if (!x || !(x.uid || x.key)) continue; const t = PR.taskOf(x); T.set(t.uid, t); }
53
+ return PR.viewOf(F, ini, { T, today: todayIso(), stages: stagesOf(ctx, p, ini), links, settle: TL.settle, linkProps });
54
+ }
55
+ function viewFor(ctx, w, boardId, ini) {
56
+ const fr = RB.frameFor(ctx, w), board = fr.boards.find((b) => b.id === boardId);
57
+ return board ? view(ctx, { w, fr, board }, ini) : null;
58
+ }
59
+
60
+ /* ── the writes, each one remembered with what it was before (Undo, the task's History) ── */
61
+ const W = {
62
+ ok: (r) => !!(r && r.body && r.body.ok),
63
+ dates(ctx, p, g, uid, x, to) {
64
+ const body = { ws: p.w.id, board: p.board.id, task: uid };
65
+ if (to.start !== undefined && (x.start || to.start)) body.start = to.start || '';
66
+ if (to.due !== undefined) body.due = to.due || '';
67
+ return RB.taskEdit(ctx, body, g);
68
+ },
69
+ };
70
+ /** The writes of one proposal. → [write] (each { op, ... } that landed). sk: the item ids the PM left out (✕ on one item). */
71
+ function applyOne(ctx, p, g, f, ini, x, choices, outbox) {
72
+ const wrote = [], why = x.why, source = srcText(x);
73
+ const items = x.items || [];
74
+ const add = (w) => { wrote.push({ why, ...(source ? { source } : {}), ...w }); };
75
+ if (x.group === 'found') {
76
+ if (x.type === 'stage') {
77
+ const row = rowOf(f, ini), stage = x.data && x.data.stage;
78
+ if (stage && row && row.stage !== stage) {
79
+ const r = RB.move(ctx, { ws: p.w.id, board: p.board.id, id: ini, to: stage, why: 'Claude found it there: ' + why }, g);
80
+ if (W.ok(r)) add({ op: 'stage', from: row.stage || '', to: stage });
81
+ }
82
+ for (const it of items) add({ op: 'ran', stage: it.stage, from: it.start || null, to: it.due || null, source: it.source || source });
83
+ if (stage && x.data.since) add({ op: 'ran', stage, from: x.data.since, to: null });
84
+ } else if (x.type === 'docs') {
85
+ for (const it of items) add({ op: 'doc', id: 'fd-' + PR.hash(ini + '|' + (it.ref || it.title)), title: it.title, source: it.source || source, at: it.at || '', ref: it.ref || '', kind: it.kind || 'doc' });
86
+ } else if (x.type === 'tasks' || (x.type === 'maybe' && items.some((it) => it.due || it.start || it.owner))) {
87
+ const epics = [];
88
+ for (const it of items) {
89
+ if (it.jira) { epics.push(it.jira.toUpperCase()); continue; }
90
+ const title = (it.wbs && !String(it.title).startsWith(it.wbs) ? it.wbs + ' ' : '') + it.title;
91
+ const r = RB.taskAdd(ctx, { ws: p.w.id, board: p.board.id, initiative: ini, title: title.slice(0, 200), ...(it.start ? { start: it.start } : {}), ...(it.due ? { due: it.due } : {}), ...(it.owner ? { owner: it.owner } : {}),
92
+ notes: ['From ' + (it.source || source || 'your sources') + (it.ref ? ': ' + it.ref : ''), it.notes || ''].filter(Boolean).join('\n').slice(0, 1900) }, g);
93
+ if (!W.ok(r)) continue;
94
+ const uid = r.body.item && (r.body.item.uid || r.body.item.id);
95
+ if (uid && it.stage) {
96
+ const st = stagesOf(ctx, p, ini).find((s) => s.key === it.stage || s.name.toLowerCase() === String(it.stage).toLowerCase());
97
+ if (st) RB.taskEdit(ctx, { ws: p.w.id, board: p.board.id, task: uid, section: st.key }, g);
98
+ }
99
+ add({ op: 'add', task: uid, title, to: { start: it.start || '', due: it.due || '' } });
100
+ }
101
+ if (epics.length) {
102
+ const row = rowOf(f, ini), was = (row && row.epics) || [];
103
+ const next = [...new Set([...was, ...epics])].slice(0, 20);
104
+ const r = RB.writeAs(ctx, '/api/boards/ini-epics', { ws: p.w.id, board: p.board.id, id: ini, epics: next }, g);
105
+ if (W.ok(r)) add({ op: 'epics', from: was, to: next });
106
+ }
107
+ } else {
108
+ // a duplicate is linked, never copied (rule 4); a maybe document is linked too; what could not be placed is kept under Linked
109
+ for (const it of items) add({ op: x.type === 'maybe' && it.kind !== 'link' ? 'doc' : 'linked', id: 'fl-' + PR.hash(ini + '|' + (it.ref || it.title)), title: it.title, ref: it.ref || '', at: it.at || '', source: it.source || source,
110
+ ...(it.other ? { why: 'Also in ' + it.other.title } : {}) });
111
+ }
112
+ } else if (x.group === 'dates') {
113
+ for (const it of items) {
114
+ const t = f.T.get(it.task), xi = f.byUid.get(it.task) || {};
115
+ if (!t) continue;
116
+ if (t.jira) { outbox.push({ task: it.task, text: 'Could ' + it.task + ' move to ' + PR.md(PR.dn(it.to.due)) + '? ' + why }); continue; }
117
+ const r = W.dates(ctx, p, g, it.task, xi, it.to);
118
+ if (W.ok(r)) add({ op: 'dates', task: it.task, title: t.title, from: { start: xi.start || '', due: xi.end || '' }, to: { start: it.to.start || xi.start || '', due: it.to.due || '' } });
119
+ }
120
+ // rule 11: a link the new date reaches: keep it (the waiting task moves too) or ignore it (it stays; the link is taken off so nothing moves it later)
121
+ for (const l of x.links || []) {
122
+ if (l.clash) continue;
123
+ const pick = (choices && choices[l.key]) || l.rec;
124
+ if (pick === 'keep') {
125
+ for (const m of l.moves) {
126
+ const xi = f.byUid.get(m.task) || {}, t = f.T.get(m.task); if (!t || t.jira) continue;
127
+ const r = W.dates(ctx, p, g, m.task, xi, m.to);
128
+ if (W.ok(r)) add({ op: 'dates', task: m.task, title: t.title, from: { start: xi.start || '', due: xi.end || '' }, to: m.to, why: 'it waits on ' + l.title });
129
+ }
130
+ } else {
131
+ const dir = dirOf(ctx, p.w), LF = TL.read(dir), was = LF.links.get(TL.keyOf(l.from, l.to));
132
+ if (was) { TL.append(dir, g.actor, { kind: 'unlink', from: l.from, to: l.to }); add({ op: 'unlink', from: l.from, to: l.to, link: { type: was.type, lag: was.lag, source: was.source } }); }
133
+ }
134
+ }
135
+ } else if (x.group === 'status') {
136
+ for (const it of items) {
137
+ const t = f.T.get(it.task); if (!t || t.closed) continue;
138
+ if (t.jira) { outbox.push({ task: it.task, text: 'It looks done: ' + why + ' Could you close ' + it.task + '?' }); continue; }
139
+ const r = RB.taskState(ctx, { ws: p.w.id, board: p.board.id, task: it.task, state: 'Done', why: 'Claude ✦: ' + why }, g);
140
+ if (W.ok(r)) add({ op: 'state', task: it.task, title: t.title, from: t.status, to: 'Done' });
141
+ }
142
+ } else if (x.group === 'names') {
143
+ for (const it of items) {
144
+ const t = f.T.get(it.task), xi = f.byUid.get(it.task) || {}; if (!t || t.jira || t.title === it.to) continue;
145
+ const r = RB.writeAs(ctx, '/api/boards/tasks/rename', { ws: p.w.id, board: p.board.id, task: it.task, title: it.to }, g);
146
+ if (!W.ok(r)) continue;
147
+ add({ op: 'rename', task: it.task, title: it.to, from: t.title, to: it.to });
148
+ // the detail cut from the name moves to the notes, so nothing is lost (rule 5)
149
+ const was = xi.notes || '', note = it.notes || ('Old name: ' + t.title);
150
+ if (!was.includes(note)) { const r2 = RB.taskEdit(ctx, { ws: p.w.id, board: p.board.id, task: it.task, notes: (was ? was + '\n' : '') + note }, g); if (W.ok(r2)) add({ op: 'notes', task: it.task, from: was, to: (was ? was + '\n' : '') + note }); }
151
+ // rule 12: where the PRD quotes the old name, the same ✓ changes it
152
+ const pr = prdRename(p.w.root, ini, t.title, it.to); if (pr) add({ op: 'prd', file: pr.file, from: t.title, to: it.to, n: pr.n });
153
+ }
154
+ }
155
+ return wrote;
156
+ }
157
+ /** The PRD's own quotes of a task's old name, changed to the new one (rule 12). → { file, n } | null */
158
+ function prdRename(root, ini, from, to) {
159
+ try {
160
+ const JT = require('./jira-tickets.js'), rel = JT.prdOf(JT.recordFm(root, ini));
161
+ if (!rel || !from || from.length < 6) return null;
162
+ const file = path.resolve(root, rel.replace(/^\/+/, ''));
163
+ if (!file.startsWith(path.resolve(root) + path.sep)) return null;
164
+ const text = fs.readFileSync(file, 'utf8'), n = text.split(from).length - 1;
165
+ if (!n) return null;
166
+ fs.writeFileSync(file, text.split(from).join(to));
167
+ return { file: path.relative(root, file), n };
168
+ } catch { return null; }
169
+ }
170
+ /** A drafted Jira comment for a ticket Claude would change: it goes to the outbox, never to Jira (rule 8). */
171
+ function toOutbox(ctx, ask) {
172
+ try {
173
+ const { repoScript } = require('./repo-script.js');
174
+ const outbox = require(repoScript('outbox.js')), store = require('./outbox-store.js');
175
+ const e = outbox.draftOutbox({ channel: 'jira-write', recipient: ask.task, subject: 'About ' + ask.task, body: ask.text, origin: 'pm' });
176
+ const entry = { id: 'out-' + crypto.randomBytes(6).toString('hex'), ...e };
177
+ store.appendEvent(ctx.runtimeDir, { event: 'queued', ...entry }, new Date());
178
+ return entry.id;
179
+ } catch { return null; }
180
+ }
181
+ /** The toast's one line: "Kept the stage, 7 documents and 41 tasks. 2 still ask you." or "Moved 7 tasks and 2 plans, ticked 1 done, renamed 7." */
182
+ function saidOf(wrote, plans, left) {
183
+ const n = (op) => wrote.filter((w) => w.op === op).length;
184
+ const found = [n('stage') ? 'the stage' : '', n('doc') ? plural(n('doc'), 'document', 'documents') : '', n('add') ? plural(n('add'), 'task', 'tasks') : '', n('linked') ? plural(n('linked'), 'link', 'links') : ''].filter(Boolean);
185
+ const bits = [];
186
+ if (found.length) bits.push('Kept ' + (found.length > 1 ? found.slice(0, -1).join(', ') + ' and ' + found[found.length - 1] : found[0]));
187
+ const moved = new Set(wrote.filter((w) => w.op === 'dates').map((w) => w.task)).size;
188
+ if (moved) bits.push((bits.length ? 'moved ' : 'Moved ') + plural(moved, 'task', 'tasks') + (plans ? ' and ' + plural(plans, 'plan', 'plans') : ''));
189
+ if (n('state')) bits.push((bits.length ? 'ticked ' : 'Ticked ') + n('state') + ' done');
190
+ if (n('rename')) bits.push((bits.length ? 'renamed ' : 'Renamed ') + n('rename'));
191
+ if (n('outbox')) bits.push(plural(n('outbox'), 'Jira comment', 'Jira comments') + ' drafted');
192
+ if (!bits.length) bits.push('Nothing changed');
193
+ return bits.join(', ') + '.' + (left ? ' ' + left + ' still ' + (left === 1 ? 'asks' : 'ask') + ' you.' : '');
194
+ }
195
+
196
+ const READS = {
197
+ '/api/proposals': (ctx, res, url) => {
198
+ const p = RB.postFrame(ctx, res, { ws: url.searchParams.get('ws') || null, board: url.searchParams.get('board') || '' });
199
+ if (!p) return;
200
+ const ini = url.searchParams.get('initiative') || '';
201
+ if (!ini) return fail(ctx, res, 400, 'initiative is required');
202
+ const dir = dirOf(ctx, p.w);
203
+ ctx.json(res, { ok: true, props: dir ? view(ctx, p, ini) : null, found: dir ? PR.foundOf(PR.read(dir), ini) : null });
204
+ },
205
+ '/api/proposals/history': (ctx, res, url) => {
206
+ const p = RB.postFrame(ctx, res, { ws: url.searchParams.get('ws') || null, board: url.searchParams.get('board') || '' });
207
+ if (!p) return;
208
+ const uid = url.searchParams.get('task') || '';
209
+ if (!uid) return fail(ctx, res, 400, 'task is required');
210
+ const dir = dirOf(ctx, p.w);
211
+ ctx.json(res, { ok: true, history: dir ? PR.historyOf(PR.read(dir), uid) : [] });
212
+ },
213
+ };
214
+
215
+ const WRITES = {
216
+ '/api/proposals/keep': (ctx, res, body, g, p) => {
217
+ const ini = String(body.initiative || '');
218
+ if (!ini) return fail(ctx, res, 400, 'initiative is required');
219
+ const ids = Array.isArray(body.ids) ? body.ids.filter((x) => typeof x === 'string').slice(0, 60) : [];
220
+ if (!ids.length && body.all !== true) return fail(ctx, res, 400, 'ids names the proposals to keep, or all: true');
221
+ const f = TLR.frame(ctx, p.w, p.board);
222
+ if (!f) return fail(ctx, res, 202, 'The board is still being read. Try again in a moment.');
223
+ const v = view(ctx, p, ini, f), all = v ? v.groups.flatMap((x) => x.props) : [];
224
+ // ✓ in the header keeps all Claude is sure of: Check these, Not placed and Jira-only proposals wait for their own ✓
225
+ const want = body.all === true ? all.filter((x) => x.section === 'sure') : all.filter((x) => ids.includes(x.id));
226
+ if (!want.length) return fail(ctx, res, 409, 'Those proposals are no longer open');
227
+ const dir = dirOf(ctx, p.w), wrote = [], keptIds = [], outbox = [];
228
+ let plans = 0;
229
+ const choices = isObj(body.choices) ? body.choices : {};
230
+ for (const x of want) {
231
+ if (x.group === 'links') {
232
+ const r = TLR.acceptFor ? TLR.acceptFor(ctx, p, g, ini, [x.link.id]) : null;
233
+ if (r && r.linked) for (const l of r.linked) wrote.push({ op: 'link', from: l.from, to: l.to, why: x.why });
234
+ continue;
235
+ }
236
+ const w = applyOne(ctx, p, g, f, ini, x, choices, outbox);
237
+ wrote.push(...w);
238
+ if (x.group === 'dates' && x.plan && w.some((y) => y.op === 'dates')) plans++;
239
+ keptIds.push(x.group === 'dates' ? x.id + ':' + x.sig : x.id);
240
+ }
241
+ for (const a of outbox) { const id = toOutbox(ctx, a); if (id) wrote.push({ op: 'outbox', task: a.task, entry: id, why: a.text }); }
242
+ const batch = PR.newBatch();
243
+ PR.append(dir, g.actor, { kind: 'keep', ini, board: p.board.id, batch, ids: keptIds, wrote });
244
+ const v2 = view(ctx, p, ini);
245
+ const left = v2 ? v2.groups.flatMap((x) => x.props).filter((x) => x.section === 'check').length : 0;
246
+ ctx.json(res, { ok: true, batch, said: saidOf(wrote, plans, body.all === true ? left : 0), counts: { wrote: wrote.length }, props: v2, found: PR.foundOf(PR.read(dir), ini) });
247
+ },
248
+ '/api/proposals/drop': (ctx, res, body, g, p) => {
249
+ const sig = String(body.sig || ''), ini = String(body.initiative || '');
250
+ if (!/^[sdi]:[0-9a-f]{10}$/.test(sig) || !ini) return fail(ctx, res, 400, 'sig names a proposal or one item of it; initiative is required');
251
+ PR.append(dirOf(ctx, p.w), g.actor, { kind: 'drop', ini, sig });
252
+ ctx.json(res, { ok: true });
253
+ },
254
+ '/api/proposals/undo': (ctx, res, body, g, p) => {
255
+ const dir = dirOf(ctx, p.w), F = PR.read(dir), id = String(body.batch || '');
256
+ const k = F.kept.find((x) => x.batch === id);
257
+ if (!k || F.undone.has(id)) return fail(ctx, res, 409, 'Nothing to undo');
258
+ const f = TLR.frame(ctx, p.w, p.board);
259
+ if (!f) return fail(ctx, res, 202, 'The board is still being read. Try again in a moment.');
260
+ let back = 0, kept = 0;
261
+ for (const w of k.wrote.slice().reverse()) {
262
+ const xi = w.task ? f.byUid.get(w.task) : null, t = w.task ? f.T.get(w.task) : null;
263
+ let r = null;
264
+ if (w.op === 'add') { if (xi && (xi.status || 'To do') === 'To do') r = RB.taskDelete(ctx, { ws: p.w.id, board: p.board.id, task: w.task, why: 'Undo: Claude ✦ added it' }, g); }
265
+ // a task changed since keeps its change: Undo never overwrites a later edit
266
+ else if (w.op === 'dates') { if (xi && (xi.end || '') === (w.to.due || xi.end || '')) r = W.dates(ctx, p, g, w.task, xi, { start: w.from.start, due: w.from.due }); }
267
+ else if (w.op === 'state') { if (t && t.status === w.to) r = RB.taskState(ctx, { ws: p.w.id, board: p.board.id, task: w.task, state: w.from || 'To do', why: 'Undo' }, g); }
268
+ else if (w.op === 'rename') { if (t && t.title === w.to) r = RB.writeAs(ctx, '/api/boards/tasks/rename', { ws: p.w.id, board: p.board.id, task: w.task, title: w.from }, g); }
269
+ else if (w.op === 'notes') { if (xi && (xi.notes || '') === w.to) r = RB.taskEdit(ctx, { ws: p.w.id, board: p.board.id, task: w.task, notes: w.from || '' }, g); }
270
+ else if (w.op === 'stage') { const row = rowOf(f, k.ini); if (row && row.stage === w.to && w.from) r = RB.move(ctx, { ws: p.w.id, board: p.board.id, id: k.ini, to: w.from, why: 'Undo: Claude ✦ moved it' }, g); }
271
+ else if (w.op === 'epics') r = RB.writeAs(ctx, '/api/boards/ini-epics', { ws: p.w.id, board: p.board.id, id: k.ini, epics: w.from }, g);
272
+ else if (w.op === 'unlink') { TL.append(dir, g.actor, { kind: 'link', board: p.board.id, ini: k.ini, from: w.from, to: w.to, type: w.link.type, lag: w.link.lag, source: w.link.source }); back++; continue; }
273
+ else if (w.op === 'link') { TL.append(dir, g.actor, { kind: 'unlink', from: w.from, to: w.to }); back++; continue; }
274
+ else if (w.op === 'prd') { try { const file = path.resolve(p.w.root, w.file), text = fs.readFileSync(file, 'utf8'); if (text.includes(w.to)) { fs.writeFileSync(file, text.split(w.to).join(w.from)); back++; } else kept++; } catch { kept++; } continue; }
275
+ else if (w.op === 'doc' || w.op === 'linked' || w.op === 'ran') { back++; continue; } // the fold leaves an undone batch out
276
+ else if (w.op === 'outbox') { kept++; continue; } // a drafted comment waits in the outbox, where the PM drops it
277
+ if (r && r.body && r.body.ok) back++; else kept++;
278
+ }
279
+ PR.append(dir, g.actor, { kind: 'undo', batch: id });
280
+ ctx.json(res, { ok: true, back, kept });
281
+ },
282
+ '/api/proposals/stop': (ctx, res, body, g, p) => {
283
+ const ini = String(body.initiative || '');
284
+ if (!ini) return fail(ctx, res, 400, 'initiative is required');
285
+ const dir = dirOf(ctx, p.w), L = PR.read(dir).looks.get(ini);
286
+ if (!L || L.ended) return fail(ctx, res, 409, 'Claude is not looking now');
287
+ try { if (ctx.proposalRuns) ctx.proposalRuns.stop(L.run); } catch { /* the end line below says it stopped */ }
288
+ PR.append(dir, g.actor, { kind: 'end', ini, run: L.run, ok: true, stopped: true });
289
+ ctx.json(res, { ok: true });
290
+ },
291
+ '/api/proposals/look': (ctx, res, body, g, p) => {
292
+ const ini = String(body.initiative || ''), why = body.why === 'check' ? 'check' : 'populate';
293
+ if (!ini) return fail(ctx, res, 400, 'initiative is required');
294
+ if (!ctx.proposalRuns) return fail(ctx, res, 503, 'Claude\'s runs are off on this server');
295
+ const r = ctx.proposalRuns.start({ ws: p.w.id, board: p.board.id, ini, why });
296
+ if (!r || !r.ok) return fail(ctx, res, 409, (r && r.error) || 'Claude could not start looking');
297
+ ctx.json(res, { ok: true, started: r.run });
298
+ },
299
+ };
300
+
301
+ module.exports = {
302
+ prefixes: ['/api/proposals'],
303
+ viewFor, saidOf, prdRename,
304
+ handle: async (req, res, url, ctx) => {
305
+ const p0 = url.pathname;
306
+ if (req.method === 'GET') {
307
+ const fn = READS[p0];
308
+ if (!fn) return fail(ctx, res, 404, 'not found');
309
+ fn(ctx, res, url);
310
+ return true;
311
+ }
312
+ if (req.method !== 'POST') return fail(ctx, res, 405, 'GET or POST only');
313
+ const fn = WRITES[p0];
314
+ if (!fn) return fail(ctx, res, 404, 'not found');
315
+ const got = await ctx.readJson(req);
316
+ if (!got.ok || !isObj(got.body)) return fail(ctx, res, 400, 'the body must be a JSON object');
317
+ const body = got.body, g = guard.requirePagePress(req, body);
318
+ if (!g.ok) return fail(ctx, res, g.status, g.error);
319
+ const p = RB.postFrame(ctx, res, body);
320
+ if (!p) return true;
321
+ if (!p.file || !dirOf(ctx, p.w)) return fail(ctx, res, 409, NO_STATE);
322
+ fn(ctx, res, body, g, p);
323
+ return true;
324
+ },
325
+ };