create-pmos 0.420.0 → 0.422.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 (88) hide show
  1. package/package.json +25 -25
  2. package/payload/KIT-VERSION +1 -1
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/scripts/anchor-resolve.js +93 -15
  6. package/payload/state/discoveries.md +1 -1
  7. package/workspace/board-programs-test.js +59 -3
  8. package/workspace/briefing-premium-board-test.js +1 -1
  9. package/workspace/changelog.json +24 -0
  10. package/workspace/fixtures/report-api/draft.json +2 -1
  11. package/workspace/guide/briefing-premium.md +2 -1
  12. package/workspace/guide/home.md +6 -2
  13. package/workspace/guide/programs.md +4 -3
  14. package/workspace/home-other-product-test.js +55 -0
  15. package/workspace/lib/board-premium.js +18 -4
  16. package/workspace/lib/briefing-premium-agent.js +8 -0
  17. package/workspace/lib/doc-live-root.js +37 -0
  18. package/workspace/lib/engine/anchor-resolve.js +93 -15
  19. package/workspace/lib/engine/boards.js +7 -2
  20. package/workspace/lib/engine/intake.js +1 -1
  21. package/workspace/lib/first-input.js +13 -6
  22. package/workspace/lib/hold-spans.js +24 -10
  23. package/workspace/lib/kg.js +1 -1
  24. package/workspace/lib/report-draft.js +3 -0
  25. package/workspace/lib/route-modules.js +1 -0
  26. package/workspace/lib/routes-board-premium.js +6 -0
  27. package/workspace/lib/routes-boards.js +48 -9
  28. package/workspace/lib/routes-doc-sheet.js +29 -1
  29. package/workspace/lib/routes-programs.js +44 -5
  30. package/workspace/lib/routes-task-plans.js +333 -0
  31. package/workspace/lib/task-cli.js +16 -9
  32. package/workspace/lib/task-items.js +1 -1
  33. package/workspace/lib/task-plans.js +232 -0
  34. package/workspace/lib/transcript-read.js +29 -1
  35. package/workspace/lib/vendor/scripts/anchor-resolve.js +93 -15
  36. package/workspace/lib/vendor/scripts/intake.js +1 -1
  37. package/workspace/package-lock.json +2 -2
  38. package/workspace/package.json +1 -1
  39. package/workspace/premium-viewer-test.js +1 -1
  40. package/workspace/premium-vw-doc-test.js +26 -3
  41. package/workspace/program-leave-test.js +203 -0
  42. package/workspace/public/pm/bd-acts.js +5 -2
  43. package/workspace/public/pm/bd-ini-panel.js +20 -7
  44. package/workspace/public/pm/bd-prog-panel.js +22 -7
  45. package/workspace/public/pm/bd-span.js +177 -24
  46. package/workspace/public/pm/cozy-board.css +80 -0
  47. package/workspace/public/pm/cozy-home.css +3 -0
  48. package/workspace/public/pm/cozy-live-pill.js +1 -1
  49. package/workspace/public/pm/cozy-nav.js +1 -1
  50. package/workspace/public/pm/cozy-steps.js +1 -1
  51. package/workspace/public/pm/cozy-xv.js +1 -1
  52. package/workspace/public/pm/doc-follow.js +36 -0
  53. package/workspace/public/pm/home-app.js +38 -7
  54. package/workspace/public/pm/home-ask.js +7 -0
  55. package/workspace/public/pm/home-ini.js +13 -4
  56. package/workspace/public/pm/home-line.js +1 -1
  57. package/workspace/public/pm/home-list.js +2 -2
  58. package/workspace/public/pm/home-today.js +3 -1
  59. package/workspace/public/pm/ini-tasks.js +81 -16
  60. package/workspace/public/pm/ini-versions.js +343 -0
  61. package/workspace/public/pm/ini-view-model.js +27 -41
  62. package/workspace/public/pm/ini-view.css +82 -0
  63. package/workspace/public/pm/ini-view.js +18 -11
  64. package/workspace/public/pm/premium-board.js +109 -18
  65. package/workspace/public/pm/premium-insights.js +1 -1
  66. package/workspace/public/pm/premium-mtg-present.js +2 -2
  67. package/workspace/public/pm/premium-report-read.js +21 -2
  68. package/workspace/public/pm/premium-report-tab.js +1 -1
  69. package/workspace/public/pm/premium-shell.js +29 -4
  70. package/workspace/public/pm/premium-viewer.js +3 -3
  71. package/workspace/public/pm/premium-vw-doc.js +46 -11
  72. package/workspace/public/pm/premium-vw-mtg.js +1 -1
  73. package/workspace/public/pm/premium-vw-open.js +1 -1
  74. package/workspace/public/pm/premium-vw-slides.js +1 -1
  75. package/workspace/public/pm/prog-move.js +69 -0
  76. package/workspace/public/pm/prog-order.js +1 -1
  77. package/workspace/public/pm/task-card.css +3 -0
  78. package/workspace/public/pm/task-card.js +10 -3
  79. package/workspace/public/pm/tk-send.js +1 -1
  80. package/workspace/server.js +26 -2
  81. package/workspace/task-milestones-test.js +176 -0
  82. package/workspace/task-plans-test.js +175 -0
  83. package/workspace/task-views-test.js +2 -2
  84. package/workspace/test-lists/program-leave.json +6 -0
  85. package/workspace/test-lists/task-milestones.json +6 -0
  86. package/workspace/test-lists/task-plans.json +6 -0
  87. package/workspace/test-lists/viewer-live-file.json +9 -0
  88. package/workspace/timeline-holds-test.js +70 -5
@@ -29,7 +29,8 @@
29
29
  * POST /api/boards/tasks/reschedule { ws, board, task, days } → { ok, item }
30
30
  * POST /api/boards/tasks/undo-add { ws, board, task } → { ok } takes back a task added in the last 2 minutes, still To do
31
31
  * POST /api/boards/tasks/rename { ws, board, task, title } → { ok, from, item } only the title changes
32
- * POST /api/boards/tasks/edit { ws, board, task, owner?, notes?, start?, due?, initiative?, section? } → { ok, from, item } the Viewer's edits in place
32
+ * POST /api/boards/tasks/edit { ws, board, task, owner?, notes?, start?, due?, initiative?, section?, milestone? } → { ok, from, item } the Viewer's edits in place
33
+ * (milestone: true | false, the ◇ flag of batch 11 item 3; a Jira key takes the flag only)
33
34
  * (section: the task's place in the breakdown, a stage key of its initiative's workflow or '' — a task-section line)
34
35
  * (canvas XetX1Rest); `from` holds the fields as they were, so Undo is the same call with `from`
35
36
  * POST /api/boards/tickets/note { ws, board, ref, notes } → { ok, from, notes } the PM's notes on a Jira ticket
@@ -281,7 +282,7 @@ function baseRows(w) {
281
282
  stopped: rec.stopped ? { reason: rec.stopped.reason || '', at: rec.stopped.at || null, back: rec.stopped.back || null } : null,
282
283
  hasSpec, record: relRec || null, domainFolder: dm ? dm[1] : null,
283
284
  recordEpic: jiraTickets.anchorOf(fm),
284
- holds: holds.get(id) || [], workSpans: work.map((x) => ({ start: x.start, due: x.due })),
285
+ holds: holds.get(id) || [], workSpans: work.map((x) => ({ start: x.start, due: x.due, stage: x.stage || null })),
285
286
  });
286
287
  }
287
288
  rowCache.set(w.root, { key: cacheKey, rows });
@@ -349,16 +350,19 @@ function taskSpanOf(folded, id) {
349
350
  }
350
351
  return start ? { start, end } : null;
351
352
  }
352
- /** Each dated task of an initiative as { start, due } (Won't do and Archived left out). */
353
+ /** Each dated task of an initiative as { start, due, stage } (Won't do and Archived left out). stage: the PM's placement (a task-section line),
354
+ * else the stage whose To finish entry made it, else null. */
353
355
  function taskSpansOf(folded, id) {
354
- const out = [];
356
+ const out = [], SEC = (folded && folded.sections) || new Map();
355
357
  for (const t of (folded && folded.tasks ? folded.tasks.values() : [])) {
356
358
  if (!t || t.initiative !== id || t.state === "Won't do" || t.state === 'Archived') continue;
357
359
  const a = t.start || t.due, z = t.due || t.start;
358
- if (a) out.push({ start: String(a).slice(0, 10), due: String(z).slice(0, 10) });
360
+ const stage = SEC.has(t.id) ? SEC.get(t.id) || null : (t.from && t.from.stage) || null;
361
+ if (a) out.push({ start: String(a).slice(0, 10), due: String(z).slice(0, 10), stage });
359
362
  }
360
363
  return out;
361
364
  }
365
+ const gapFields = (spans) => ({ gaps: holdSpans.planGaps(spans, 14), stageSpans: holdSpans.stageSpans(spans) });
362
366
  const minDay = (a, b) => (!a ? b || null : !b ? a : a < b ? a : b);
363
367
  const maxDay = (a, b) => (!a ? b || null : !b ? a : a > b ? a : b);
364
368
 
@@ -372,8 +376,9 @@ function boardRow(board, base, folded, lib) {
372
376
  horizon: base.horizon, status: base.status, start: ts ? minDay(base.start, ts.start) : base.start, end: ts ? maxDay(base.end, ts.end) : base.end, progress: base.progress, warnings: [],
373
377
  rank: base.rank, health: B.isActive(base) ? base.health : null, updated: base.updated, reading: base.reading, stageSource: s.source, lifecycle: base.lifecycle,
374
378
  stopped: base.stopped || null, archived: archivedOf(folded, base.id),
375
- // feedback batch 9 item 8: every hold of the initiative, and the stretches of 4 weeks or more that no dated work-item or task covers
376
- holds: base.holds || [], gaps: holdSpans.planGaps((base.workSpans || []).concat(taskSpansOf(folded, base.id)), 28),
379
+ // feedback batch 9 item 8: every hold of the initiative, and the stretches of 2 weeks or more that no dated work-item or task covers (batch 11
380
+ // item 13); stageSpans: where the dated work of each stage runs, so a skipped stage between two of them is marked » (XgapAGrill)
381
+ holds: base.holds || [], ...gapFields((base.workSpans || []).concat(taskSpansOf(folded, base.id))),
377
382
  template: B.templateOf(board, base.id, folded), workflow: wf.map((x) => ({ name: x.name, cat: x.cat })),
378
383
  ...epicsOf(base, folded),
379
384
  };
@@ -533,6 +538,9 @@ function itemsOf(w, fr, board, rows) {
533
538
  // a task's place in the breakdown (one view): the PM's own choice, else the stage whose To finish entry made it
534
539
  const SEC = fr.folded.sections || new Map();
535
540
  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; }
541
+ // a task flagged as a milestone (feedback batch 11 item 3): the PM's flag on the board ledger, else a breakdown item's own plan-items flag
542
+ const MS = fr.folded.milestones || new Map();
543
+ for (const x of out) if (x.kind !== 'Epic') { const on = MS.has(x.uid) ? MS.get(x.uid) : !!x.milestone; if (on) x.milestone = true; else delete x.milestone; }
536
544
  return B.rollupItems(out);
537
545
  }
538
546
 
@@ -1194,6 +1202,15 @@ const WRITES = {
1194
1202
  // the task Viewer edits in place (canvas XetX1Rest, XetX1Dates): each change saves at once; Undo sends `from` back
1195
1203
  const p = postFrame(ctx, res, body);
1196
1204
  if (!p) return;
1205
+ 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)
1207
+ 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');
1209
+ 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 });
1213
+ }
1197
1214
  const t0 = B.taskOf(p.fr.folded, body.task);
1198
1215
  let t = t0;
1199
1216
  if (!t0 && TI.isItemId(body.task)) {
@@ -1234,8 +1251,16 @@ const WRITES = {
1234
1251
  sec = body.section; from.section = S0.has(t.id) ? S0.get(t.id) : (t.from && t.from.stage) || '';
1235
1252
  if (!p.file) return fail(ctx, res, 409, NO_STATE);
1236
1253
  }
1237
- if (!Object.keys(ev).length && sec == null) return fail(ctx, res, 400, 'nothing to change: send owner, notes, start, due, initiative or section');
1254
+ // the milestone flag (feedback batch 11 item 3): a board-ledger line for every kind of task, like the section
1255
+ let ms = null;
1256
+ if (body.milestone != null) {
1257
+ if (!p.file) return fail(ctx, res, 409, NO_STATE);
1258
+ const MS0 = p.fr.folded.milestones || new Map();
1259
+ ms = body.milestone; from.milestone = MS0.has(t.id) ? MS0.get(t.id) : !!t.milestone;
1260
+ }
1261
+ if (!Object.keys(ev).length && sec == null && ms == null) return fail(ctx, res, 400, 'nothing to change: send owner, notes, start, due, initiative, section or milestone');
1238
1262
  if (sec != null) append(p.file, g.actor, { kind: 'task-section', board: p.board.id, task: t.id, section: sec, why: sec ? 'placed under ' + sec : 'placed under no stage' });
1263
+ if (ms != null) append(p.file, g.actor, { kind: 'task-milestone', board: p.board.id, task: t.id, milestone: ms, why: ms ? 'made a milestone' : 'no longer a milestone' });
1239
1264
  if (!Object.keys(ev).length) {
1240
1265
  const items = itemsOf(p.w, { ...p.fr, folded: B.fold(readLedger(ctx, p.w)) }, p.board, (needRows(ctx, res, p.w) || []).filter((r) => r.id === t.initiative));
1241
1266
  return ctx.json(res, { ok: true, from, item: items.find((x) => x.uid === t.id) || null });
@@ -1393,6 +1418,20 @@ async function handle(req, res, url, ctx) {
1393
1418
  return true;
1394
1419
  }
1395
1420
 
1421
+ /** Planned versus actual (batch 11 item 8): a move into Build saves the plan "Build start" once, when the initiative has none
1422
+ * (lib/routes-task-plans.js buildStart). It runs after the move's answer is ready, and never changes it. */
1423
+ for (const route of ['/api/boards/move', '/api/boards/ini-wf']) {
1424
+ const plain = WRITES[route];
1425
+ if (!plain) continue;
1426
+ WRITES[route] = (ctx, res, body, g) => plain({ ...ctx, json: (r, obj, code) => {
1427
+ if (obj && obj.ok && obj.row && obj.row.id) {
1428
+ const w = wsOf(ctx, typeof body.ws === 'string' ? body.ws : null), b = w && frameFor(ctx, w).boards.find((x) => x.id === body.board);
1429
+ if (w && b) require('./routes-task-plans.js').buildStart(ctx, w, b, obj.row, g.actor);
1430
+ }
1431
+ ctx.json(r, obj, code);
1432
+ } }, res, body, g);
1433
+ }
1434
+
1396
1435
  /** One write route run outside HTTP, by the same function the page's press runs, so its validation, warnings and ledger line are the
1397
1436
  * route's own. `g` is { ok, actor }: who writes comes from the call path, never from the body. Answers { status, body } with the body the
1398
1437
  * route would send. */
@@ -1503,4 +1542,4 @@ function meetingBoards(ctx) {
1503
1542
  return { list, detail };
1504
1543
  }
1505
1544
 
1506
- module.exports = { prefixes: ['/api/boards'], handle, move, switchWorkflow, taskState, taskAdd, taskEdit, taskDelete, taskRestore, initiativeWorkflow, seedInitiative, stageTasks, itemsOf, boardIndex, appendScanAsk, scanDeclineSignal, createAndPlace, ledgerFile, append, frameFor, boardIdOf, meetingBoards, boardsOf, baseRows, boardRow, taskSpanOf, workflowRowOf, foldOf, portfolio, SELF_REFUSAL, NO_STATE };
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 };
@@ -19,6 +19,9 @@
19
19
  * POST /api/doc-sheet/why { path, rev, why } page press; a reason for a revision that has none (an outside change);
20
20
  * appended to annotations.jsonl, the revision itself is not rewritten
21
21
  * POST /api/doc-sheet/mark-current { path, why } page press; "still current" with a reason; it counts as the last change
22
+ * GET /api/doc-sheet/stamp?path=&ini= → { ok, ws, hash } which workspace holds the live copy and its text's hash. With an initiative id,
23
+ * the initiative's own worktree when it holds the file (lib/doc-live-root.js): a chat edits there and
24
+ * does not commit. The page checks this every few seconds and reads again when it changed.
22
25
  *
23
26
  * Every revision says who wrote the text and how it came in: via 'sheet' (an edit here), 'proposal' (accepted; text_by 'agent',
24
27
  * by 'pm', the proposal id and the sections taken) or 'outside' (the file changed outside the sheet; git's last commit of
@@ -372,11 +375,35 @@ function changeNote(root, body, runtimeDir) {
372
375
  return { status: 200, body: { ok: true, note } };
373
376
  }
374
377
 
378
+ // the live copy (GET /api/doc-sheet/stamp). git is asked at most every few seconds per repository: an open page asks every 2.5 s.
379
+ const GIT_TTL_MS = 3000;
380
+ const gitCache = new Map();
381
+ function cached(key, fn) {
382
+ const hit = gitCache.get(key);
383
+ if (hit && Date.now() - hit.at < GIT_TTL_MS) return hit.v;
384
+ const v = fn(); gitCache.set(key, { at: Date.now(), v });
385
+ if (gitCache.size > 200) gitCache.delete(gitCache.keys().next().value);
386
+ return v;
387
+ }
388
+ function stampRoute(q, w, ctx) {
389
+ const gitInfo = require('./git-info.js');
390
+ const base = w || { id: null, root: ctx.root || ROOT };
391
+ const live = require('./doc-live-root.js').liveWs({
392
+ base, ini: q.ini, rel: q.path,
393
+ workspaces: ctx.workspaceList ? ctx.workspaceList() : [],
394
+ topOf: (root) => cached('top|' + root, () => gitInfo.repoRoot(root)),
395
+ worktreesOf: (top) => cached('wt|' + top, () => gitInfo.worktrees(top)),
396
+ has: (root, rel) => !resolveDoc(root, rel).error,
397
+ });
398
+ const r = resolveDoc(live.root, q.path); if (r.error) return r.error;
399
+ return { status: 200, body: { ok: true, path: r.rel, ws: live.id || null, hash: S.hashText(r.text) } };
400
+ }
401
+
375
402
  const respond = (ctx, res, r) => { ctx.json(res, r.body, r.status); return true; };
376
403
 
377
404
  module.exports = {
378
405
  prefixes: ['/api/doc-sheet'],
379
- resolveDoc, revisionsRoute, atRoute, edit, propose, accept, changeNote, proposalsRoute, logRoute, reject, addWhy, markCurrent, lastSheetChange, ask, askState, askPrompt, parseAsk, settleAsk,
406
+ resolveDoc, stampRoute, revisionsRoute, atRoute, edit, propose, accept, changeNote, proposalsRoute, logRoute, reject, addWhy, markCurrent, lastSheetChange, ask, askState, askPrompt, parseAsk, settleAsk,
380
407
  handle: async (req, res, url, ctx) => {
381
408
  const p = url.pathname;
382
409
  const w = (url.searchParams.get('ws') && ctx.getWs) ? ctx.getWs(url.searchParams.get('ws')) : null;
@@ -385,6 +412,7 @@ module.exports = {
385
412
  if (req.method === 'GET' && p === '/api/doc-sheet/ask') return respond(ctx, res, askState(Object.fromEntries(url.searchParams), base));
386
413
  if (req.method === 'GET' && p === '/api/doc-sheet/at') return respond(ctx, res, atRoute(base.root, Object.fromEntries(url.searchParams), base.runtimeDir));
387
414
  if (req.method === 'GET' && p === '/api/doc-sheet/proposals') return respond(ctx, res, proposalsRoute(base.root, Object.fromEntries(url.searchParams), base.runtimeDir));
415
+ if (req.method === 'GET' && p === '/api/doc-sheet/stamp') return respond(ctx, res, stampRoute(Object.fromEntries(url.searchParams), w, ctx));
388
416
  if (req.method === 'GET' && p === '/api/doc-sheet/log') return respond(ctx, res, logRoute(base.root, Object.fromEntries(url.searchParams), base.runtimeDir));
389
417
  const fn = req.method === 'POST' && { '/api/doc-sheet/edit': edit, '/api/doc-sheet/propose': propose, '/api/doc-sheet/accept': accept,
390
418
  '/api/doc-sheet/reject': reject, '/api/doc-sheet/why': addWhy, '/api/doc-sheet/mark-current': markCurrent, '/api/doc-sheet/ask': ask,
@@ -3,7 +3,10 @@
3
3
  *
4
4
  * GET /api/programs → { ok, programs: [program] } merged from every registered workspace (lib/programs.js merge)
5
5
  * POST /api/programs/save { ws, program } the charter: title, owner, goal, why, start, target, jira, milestones (the last save wins)
6
- * POST /api/programs/member { ws, program, initiative, leave? } an initiative of workspace `ws` joins (or leaves) the program
6
+ * POST /api/programs/member { ws, program, initiative, leave?, back? } an initiative of workspace `ws` joins (or leaves) the program. A leave
7
+ * takes it off the charter's milestones that wait on it and answers `off`: [{ id, name, stage? }];
8
+ * a join that leaves another program answers `left`: { program, title, off }. Undo rejoins with
9
+ * `back` (an `off` list), which puts it back on those milestones (canvas LpA3Done)
7
10
  * POST /api/programs/turn { ws, initiative, title? } "Turn into a program": a charter named after the initiative, which joins it; the
8
11
  * charter keeps `from` (the initiative), so the panel can count its tasks with no level
9
12
  * POST /api/programs/task { ws, program, title, owner?, due?, key? } a task on the program itself
@@ -116,11 +119,47 @@ module.exports = {
116
119
  if (!P.ID_RE.test(pid)) return bad('program must name a program');
117
120
  if (!known(pid)) return bad('no such program', 404);
118
121
  if (p === '/api/programs/member') {
119
- if (!P.INI_RE.test(String(b.initiative || ''))) return bad('initiative must name an initiative');
122
+ const ini = String(b.initiative || '');
123
+ if (!P.INI_RE.test(ini)) return bad('initiative must name an initiative');
124
+ const charter = (prog, milestones) => { // one charter line in the charter's workspace, as a Save writes it (the last line wins)
125
+ const v = P.validProgram({ ...prog, milestones }), cw = ctx.getWs ? ctx.getWs(prog.home || null) : null, cf = cw ? fileOf(ctx, cw) : null;
126
+ if (!v.error && cf) pmItems.appendEvent(cf, v, now);
127
+ };
128
+ // a milestone that waits on an initiative that left could never be done (program-model.js counts it unread): the leave takes it off
129
+ // the charter's milestones, and answers which, with the ◆ stage each picked, so Undo puts them back (canvas LpA3Done, "off 1 milestone")
130
+ const takeOff = (prog) => {
131
+ const off = [];
132
+ const ms = (prog.milestones || []).map((m) => {
133
+ if (!(m.waits || []).includes(ini)) return m;
134
+ const st = { ...(m.stages || {}) }, one = { id: m.id, name: m.name };
135
+ if (st[ini]) { one.stage = st[ini]; delete st[ini]; }
136
+ off.push(one);
137
+ return { ...m, waits: m.waits.filter((x) => x !== ini), stages: st };
138
+ });
139
+ if (off.length) charter(prog, ms);
140
+ return off;
141
+ };
142
+ let left = null, off = [];
120
143
  // an initiative is in one program at most: joining one leaves any other it is in, in this workspace
121
- if (!b.leave) for (const o of all(ctx)) if (o.id !== pid && o.members.some((m) => m.ws === w.id && m.initiative === b.initiative)) add({ kind: 'leave', program: o.id, initiative: String(b.initiative) });
122
- add({ kind: b.leave ? 'leave' : 'member', program: pid, initiative: String(b.initiative) });
123
- ctx.json(res, { ok: true, program: known(pid) });
144
+ if (!b.leave) for (const o of all(ctx)) if (o.id !== pid && o.members.some((m) => m.ws === w.id && m.initiative === ini)) { add({ kind: 'leave', program: o.id, initiative: ini }); left = { program: o.id, title: o.title, off: takeOff(o) }; }
145
+ if (b.leave) off = takeOff(known(pid));
146
+ add({ kind: b.leave ? 'leave' : 'member', program: pid, initiative: ini });
147
+ // Undo of a leave rejoins with `back`: the milestones it was taken off, [{ id, stage? }]; a milestone the charter no longer has is skipped
148
+ const back = !b.leave && Array.isArray(b.back) ? b.back.filter((x) => x && P.ID_RE.test(String(x.id || ''))).slice(0, 12) : [];
149
+ if (back.length) {
150
+ const prog = known(pid);
151
+ let n = 0;
152
+ const ms = (prog.milestones || []).map((m) => {
153
+ const x = back.find((y) => y.id === m.id);
154
+ if (!x || (m.waits || []).includes(ini)) return m;
155
+ n++;
156
+ const st = { ...(m.stages || {}) };
157
+ if (x.stage && /^[a-z0-9][a-z0-9-]{0,39}$/.test(String(x.stage))) st[ini] = String(x.stage);
158
+ return { ...m, waits: [...(m.waits || []), ini], stages: st };
159
+ });
160
+ if (n) charter(prog, ms);
161
+ }
162
+ ctx.json(res, { ok: true, program: known(pid), off, left });
124
163
  return true;
125
164
  }
126
165
  if (p === '/api/programs/task') {
@@ -0,0 +1,333 @@
1
+ 'use strict';
2
+ /* routes-task-plans.js — drafts and saved plans of an initiative's tasks: planned versus actual (feedback batch 11 item 8; canvas In
3
+ * development, row "Planned vs actual"). The fold and the writer are lib/task-plans.js; a Live task changes only through the lines the
4
+ * board's own task routes write (boards.jsonl, and the plan-items ledger for a breakdown item).
5
+ *
6
+ * GET /api/task-plans?ws&board&initiative → { ok, versions } versions: lib/task-plans.js versionsOf (null: none)
7
+ * GET /api/task-plans/preview?ws&board&draft → { ok, summary } what Make live would do: added, moved, dropped, conflicts
8
+ * POST /api/task-plans/draft { ws, board, initiative, from: 'live' | <draft id>, name? } → { ok, draft, versions } a new draft
9
+ * POST /api/task-plans/propose { ws, board, initiative, title, start?, due?, owner?, section? } → { ok, draft, task, versions }
10
+ * a task of an initiative with no Live task and no saved plan: it goes to the automatic draft "Proposal"
11
+ * (409 when the initiative has Live tasks or a plan: the page adds it to Live)
12
+ * POST /api/task-plans/task { ws, board, draft, task?, add? | set? | drop? | undrop? } → { ok, task, from?, versions }
13
+ * task: the draft task's key (or its uid dt:<draft>:<key>); add: { title, start?, due?, owner?, section? };
14
+ * set: { title?, start?, due?, owner?, section?, status?, milestone? }; `from` holds the fields as they were (Undo)
15
+ * POST /api/task-plans/name { ws, board, draft, name } · /delete { draft } · /restore { draft } (Delete's Undo)
16
+ * POST /api/task-plans/live { ws, board, draft } → { ok, plan, summary, versions } Make live
17
+ * POST /api/task-plans/unlive { ws, board, draft } → { ok, kept } its Undo; `kept`: breakdown items it withdrew, which stay withdrawn
18
+ * POST /api/task-plans/plan { ws, board, initiative, name? } → { ok, plan, versions } Save Live as a plan
19
+ * POST /api/task-plans/plan/remove { ws, board, plan } → { ok } its Undo
20
+ *
21
+ * buildStart(ctx, w, board, row, actor) PMOS saves the plan "Build start" once, when an initiative enters Build with no plan yet
22
+ * (routes-boards.js calls it after a move).
23
+ *
24
+ * Every POST passes pm-guard requirePagePress. With no state folder the reads answer no versions and every write answers 409. */
25
+ const guard = require('./pm-guard.js');
26
+ const actorLib = require('./actor.js');
27
+ const TP = require('./task-plans.js');
28
+ const TI = require('./task-items.js');
29
+ const RB = require('./routes-boards.js');
30
+ const { repoScript } = require('./repo-script.js');
31
+ const B = require(repoScript('boards.js'));
32
+
33
+ const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
34
+ const today = () => new Date().toISOString().slice(0, 10);
35
+ const md = (iso) => { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(iso || '')); return m ? MON[+m[2] - 1] + ' ' + +m[3] : ''; };
36
+ const ONE_LINE = (v, max) => typeof v === 'string' && v.trim().length >= 1 && v.trim().length <= max && !/[\r\n\x00-\x08\x0b-\x1f]/.test(v);
37
+ const DAY = /^\d{4}-\d{2}-\d{2}$/;
38
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
39
+ const fail = (ctx, res, status, error, extra = {}) => { ctx.json(res, { ok: false, error, ...extra }, status); return true; };
40
+ const NO_STATE = 'This repository has no PMOS state folder (pmos/state, state or .pmos). Nothing is saved until the folder exists.';
41
+ const STATES = ['To do', 'In progress', 'Done', "Won't do", 'Archived'];
42
+
43
+ const dirOf = (ctx, w) => (ctx.stateDirFor ? ctx.stateDirFor(w) : null);
44
+ /** The Live PMOS tasks of one initiative: its Board tasks and its breakdown items (the same work items the Board reads). */
45
+ function liveOf(p, row) {
46
+ return RB.itemsOf(p.w, p.fr, p.board, [row]).filter((x) => x.src === 'pmos' && x.kind !== 'Epic' && x.ini === row.id);
47
+ }
48
+ /** The initiative on this board, or an answer already sent (null). */
49
+ function rowOn(ctx, res, p, id) {
50
+ if (typeof id !== 'string' || !id) { fail(ctx, res, 400, 'initiative is required'); return null; }
51
+ const base = RB.needRows(ctx, res, p.w);
52
+ if (!base) return null;
53
+ const b0 = base.find((r) => r.id === id);
54
+ if (!b0 || RB.boardIdOf(b0, p.fr.boards, p.fr.folded, p.w) !== p.board.id) { fail(ctx, res, 404, `no initiative ${id} on this board`); return null; }
55
+ return b0;
56
+ }
57
+ function versions(ctx, p, row) { return TP.versionsOf(TP.read(dirOf(ctx, p.w)), row.id, liveOf({ ...p, fr: RB.frameFor(ctx, p.w) }, row)); }
58
+ /** The draft named in the body, open (or any state with `any`), on this board. */
59
+ function draftOf(ctx, res, p, body, any) {
60
+ const raw = typeof body.draft === 'string' ? body.draft : '';
61
+ const F = TP.read(dirOf(ctx, p.w)), d = F.drafts.get(raw);
62
+ if (!d || d.board !== p.board.id || (!any && d.state !== 'open')) { fail(ctx, res, 404, `no open draft ${raw || '(none named)'} on this board`); return null; }
63
+ return { F, d };
64
+ }
65
+ /** A draft task's fields from a body's add or set: { value } | { error }. */
66
+ function fieldsOf(o, adding) {
67
+ if (!isObj(o)) return { error: 'send the fields as an object' };
68
+ const v = {};
69
+ if (o.title != null) { if (!ONE_LINE(o.title, 200)) return { error: 'title is one line of 1 to 200 characters' }; v.title = o.title.trim(); }
70
+ else if (adding) return { error: 'title is required' };
71
+ for (const k of ['start', 'due']) if (o[k] != null) { if (o[k] !== '' && !DAY.test(String(o[k]))) return { error: `${k} is a day, YYYY-MM-DD, or ''` }; v[k] = String(o[k]); }
72
+ if (o.owner != null) { if (o.owner !== '' && !ONE_LINE(o.owner, 80)) return { error: 'owner is one line of at most 80 characters' }; v.owner = String(o.owner).trim(); }
73
+ if (o.section != null) { if (typeof o.section !== 'string' || o.section.length > 80) return { error: 'section is a stage key, or ""' }; v.section = o.section; }
74
+ if (o.status != null) { if (!STATES.includes(o.status)) return { error: `status is one of ${STATES.join(', ')}` }; v.status = o.status; }
75
+ if (o.milestone != null) { if (typeof o.milestone !== 'boolean') return { error: 'milestone is true or false' }; v.milestone = o.milestone; }
76
+ if (!Object.keys(v).length) return { error: 'nothing to change' };
77
+ return { value: v };
78
+ }
79
+ /** "Proposal A", "Proposal B"; "Change 1", "Change 2" for a draft from Live after a plan exists. */
80
+ function nameFor(F, ini, fromLive) {
81
+ const mine = [...F.drafts.values()].filter((d) => d.ini === ini).map((d) => d.name);
82
+ const plans = [...F.plans.values()].some((x) => x.ini === ini);
83
+ if (fromLive && plans) { let n = 1; while (mine.includes('Change ' + n)) n++; return 'Change ' + n; }
84
+ for (const c of 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') if (!mine.includes('Proposal ' + c)) return 'Proposal ' + c;
85
+ return 'Proposal ' + (mine.length + 1);
86
+ }
87
+
88
+ /* ── Make live: the lines in boards.jsonl and the plan-items ledger, then the plan ── */
89
+ function applyLive(ctx, p, row, d, g) {
90
+ const live = liveOf(p, row), S = TP.stepsOf(d, live), undo = { added: [], changed: [], dropped: [], unchosen: [] };
91
+ const file = p.file, by = g.actor;
92
+ for (const x of S.add) {
93
+ const id = `task-${require('crypto').randomBytes(5).toString('hex')}`;
94
+ RB.append(file, by, { kind: 'task', board: p.board.id, task: id, type: 'Task', initiative: row.id, title: x.title || 'Task', epic: null, owner: x.owner || actorLib.pageName(by.by),
95
+ state: 'To do', start: x.start || null, due: x.due || null, ...(x.milestone ? { milestone: true } : {}), why: 'made live from ' + d.name });
96
+ const sec = x.section || (x.from && x.from.stage) || '';
97
+ if (sec) RB.append(file, by, { kind: 'task-section', board: p.board.id, task: id, section: sec, why: 'placed under ' + sec });
98
+ undo.added.push(id);
99
+ }
100
+ for (const c of S.change) {
101
+ const ev = {}; for (const k of ['title', 'start', 'due', 'owner']) if (k in c.set) ev[k] = c.set[k];
102
+ if (Object.keys(ev).length) {
103
+ if (c.item) { const it = TI.itemOf(p.w.root, c.uid); const r = it ? TI.editEvents(it, ev) : null; if (r && r.events) TI.write(p.w.root, r.events, by, null); }
104
+ else RB.append(file, by, { kind: 'task-update', board: p.board.id, task: c.uid, ...ev, why: 'made live from ' + d.name });
105
+ }
106
+ if ('section' in c.set) RB.append(file, by, { kind: 'task-section', board: p.board.id, task: c.uid, section: c.set.section, why: 'placed under ' + (c.set.section || 'no stage') });
107
+ undo.changed.push({ uid: c.uid, item: c.item, from: c.from });
108
+ }
109
+ for (const x of S.drop) {
110
+ if (x.item) { const it = TI.itemOf(p.w.root, x.uid); const r = it ? TI.stateEvents(it, "Won't do") : null; if (r && r.events) TI.write(p.w.root, r.events, by, null); }
111
+ else RB.append(file, by, { kind: 'task-update', board: p.board.id, task: x.uid, state: "Won't do", why: 'dropped by ' + d.name });
112
+ undo.dropped.push({ uid: x.uid, item: x.item, from: x.from });
113
+ }
114
+ // the plan: the Live dates as they are now, named after the draft
115
+ const after = liveOf({ ...p, fr: RB.frameFor(ctx, p.w) }, row);
116
+ const plan = TP.newId('plan'), dir = dirOf(ctx, p.w);
117
+ TP.append(dir, by, { kind: 'plan', plan, board: p.board.id, initiative: row.id, name: d.name + ' · ' + md(today()), source: 'draft', tasks: TP.planTasksOf(after) });
118
+ const F = TP.read(dir);
119
+ undo.unchosen = [...F.drafts.values()].filter((o) => o.ini === row.id && o.id !== d.id && o.state === 'open').map((o) => o.id);
120
+ TP.append(dir, by, { kind: 'draft-live', draft: d.id, plan, undo });
121
+ return { plan, summary: TP.summaryOf(S), notChosen: undo.unchosen.length };
122
+ }
123
+ function undoLive(ctx, p, d, g) {
124
+ const u = d.undo || {}, file = p.file, by = g.actor, F0 = RB.frameFor(ctx, p.w).folded;
125
+ let kept = 0;
126
+ for (const id of u.added || []) if (B.taskOf(F0, id)) RB.append(file, by, { kind: 'task-remove', board: p.board.id, task: id, why: 'undo of make live' });
127
+ for (const c of u.changed || []) {
128
+ const ev = {}; for (const k of ['title', 'start', 'due', 'owner']) if (c.from && k in c.from) ev[k] = c.from[k];
129
+ if (Object.keys(ev).length) {
130
+ if (c.item) { const it = TI.itemOf(p.w.root, c.uid); const r = it ? TI.editEvents(it, ev) : null; if (r && r.events) TI.write(p.w.root, r.events, by, null); }
131
+ else if (B.taskOf(F0, c.uid)) RB.append(file, by, { kind: 'task-update', board: p.board.id, task: c.uid, ...ev, why: 'undo of make live' });
132
+ }
133
+ if (c.from && 'section' in c.from) RB.append(file, by, { kind: 'task-section', board: p.board.id, task: c.uid, section: c.from.section, why: 'undo of make live' });
134
+ }
135
+ for (const x of u.dropped || []) {
136
+ if (x.item) { kept++; continue; } // a withdrawn breakdown item cannot come back (lib/task-items.js)
137
+ if (B.taskOf(F0, x.uid)) RB.append(file, by, { kind: 'task-update', board: p.board.id, task: x.uid, state: x.from || 'To do', why: 'undo of make live' });
138
+ }
139
+ const dir = dirOf(ctx, p.w);
140
+ if (d.plan) TP.append(dir, by, { kind: 'plan-remove', plan: d.plan });
141
+ TP.append(dir, by, { kind: 'draft-unlive', draft: d.id });
142
+ return { kept };
143
+ }
144
+
145
+ /** PMOS saves the plan "Build start" once: when the initiative enters Build and has no plan yet. A failure here never fails the move. */
146
+ function buildStart(ctx, w, board, row, actor) {
147
+ try {
148
+ const name = String((row.wfStage && row.wfStage.name) || row.stage || '');
149
+ if (!/^build\b/i.test(name)) return null;
150
+ const dir = dirOf(ctx, w);
151
+ if (!dir) return null;
152
+ const F = TP.read(dir);
153
+ if ([...F.plans.values()].some((x) => x.ini === row.id)) return null;
154
+ const fr = RB.frameFor(ctx, w), live = RB.itemsOf(w, fr, board, [row]).filter((x) => x.src === 'pmos' && x.kind !== 'Epic' && x.ini === row.id);
155
+ const tasks = TP.planTasksOf(live);
156
+ if (!tasks.length) return null;
157
+ const plan = TP.newId('plan');
158
+ TP.append(dir, actor || { by: 'pmos' }, { kind: 'plan', plan, board: board.id, initiative: row.id, name: 'Build start · ' + md(today()), source: 'build', tasks });
159
+ return plan;
160
+ } catch { return null; }
161
+ }
162
+
163
+ const READS = {
164
+ '/api/task-plans': (ctx, res, url) => {
165
+ const p = RB.postFrame(ctx, res, { ws: url.searchParams.get('ws') || null, board: url.searchParams.get('board') || '' });
166
+ if (!p) return;
167
+ const row = rowOn(ctx, res, p, url.searchParams.get('initiative'));
168
+ if (!row) return;
169
+ ctx.json(res, { ok: true, versions: dirOf(ctx, p.w) ? versions(ctx, p, row) : null });
170
+ },
171
+ '/api/task-plans/preview': (ctx, res, url) => {
172
+ const p = RB.postFrame(ctx, res, { ws: url.searchParams.get('ws') || null, board: url.searchParams.get('board') || '' });
173
+ if (!p) return;
174
+ const got = draftOf(ctx, res, p, { draft: url.searchParams.get('draft') || '' });
175
+ if (!got) return;
176
+ const row = rowOn(ctx, res, p, got.d.ini);
177
+ if (!row) return;
178
+ const S = TP.stepsOf(got.d, liveOf(p, row));
179
+ const others = [...got.F.drafts.values()].filter((o) => o.ini === row.id && o.id !== got.d.id && o.state === 'open').map((o) => o.name);
180
+ ctx.json(res, { ok: true, summary: { ...TP.summaryOf(S), planName: got.d.name + ' · ' + md(today()), notChosen: others } });
181
+ },
182
+ };
183
+
184
+ const WRITES = {
185
+ '/api/task-plans/draft': (ctx, res, body, g, p) => {
186
+ const row = rowOn(ctx, res, p, body.initiative);
187
+ if (!row) return;
188
+ const dir = dirOf(ctx, p.w), F = TP.read(dir), from = body.from == null ? 'live' : body.from;
189
+ if (body.name != null && !ONE_LINE(body.name, 60)) return fail(ctx, res, 400, 'name is one line of 1 to 60 characters');
190
+ let tasks;
191
+ if (from === 'live') tasks = liveOf(p, row).filter((x) => x.status !== 'Archived').map(TP.taskOfLive);
192
+ else {
193
+ const src = F.drafts.get(from);
194
+ if (!src || src.ini !== row.id || src.state === 'deleted') return fail(ctx, res, 404, `no draft ${from} of this initiative to copy`);
195
+ tasks = [...src.tasks.values()].map((x) => ({ ...TP.taskLine(x), k: TP.newKey(), ...(x.base ? { base: x.base } : {}), ...(x.drop ? { drop: true } : {}) })); // a copy of a draft keeps where each task came from, and what Live had
196
+ }
197
+ const id = TP.newId('draft'), name = body.name ? body.name.trim() : nameFor(F, row.id, from === 'live');
198
+ TP.append(dir, g.actor, { kind: 'draft-new', draft: id, board: p.board.id, initiative: row.id, name, from, tasks });
199
+ ctx.json(res, { ok: true, draft: { id, name }, versions: versions(ctx, p, row) });
200
+ },
201
+ '/api/task-plans/propose': (ctx, res, body, g, p) => {
202
+ const row = rowOn(ctx, res, p, body.initiative);
203
+ if (!row) return;
204
+ const f = fieldsOf({ title: body.title, start: body.start, due: body.due, owner: body.owner, section: body.section }, true);
205
+ if (f.error) return fail(ctx, res, 400, f.error);
206
+ const dir = dirOf(ctx, p.w), F = TP.read(dir);
207
+ if ([...F.plans.values()].some((x) => x.ini === row.id) || liveOf(p, row).some((x) => x.status !== 'Archived')) return fail(ctx, res, 409, 'this initiative has Live tasks or a saved plan: add the task to Live');
208
+ let d = [...F.drafts.values()].find((x) => x.ini === row.id && x.auto && x.state === 'open');
209
+ let draftId = d ? d.id : null;
210
+ if (!draftId) {
211
+ // a proposal that another draft already holds keeps going there: the newest open draft
212
+ const open = [...F.drafts.values()].filter((x) => x.ini === row.id && x.state === 'open');
213
+ if (open.length) draftId = open[open.length - 1].id;
214
+ else { draftId = TP.newId('draft'); TP.append(dir, g.actor, { kind: 'draft-new', draft: draftId, board: p.board.id, initiative: row.id, name: 'Proposal', auto: true, from: 'empty', tasks: [] }); }
215
+ }
216
+ const start = f.value.start || B.shiftDay(today(), 1), due = f.value.due || B.shiftDay(start, 7), k = TP.newKey();
217
+ TP.append(dir, g.actor, { kind: 'draft-task', draft: draftId, k, add: { ...f.value, start, due, owner: f.value.owner || actorLib.pageName(g.actor.by), status: 'To do' } });
218
+ ctx.json(res, { ok: true, draft: { id: draftId, name: TP.read(dir).drafts.get(draftId).name }, task: 'dt:' + draftId + ':' + k, versions: versions(ctx, p, row) });
219
+ },
220
+ '/api/task-plans/task': (ctx, res, body, g, p) => {
221
+ const m = /^dt:([^:]+):(.+)$/.exec(String(body.task || ''));
222
+ if (m && !body.draft) body.draft = m[1];
223
+ const got = draftOf(ctx, res, p, body);
224
+ if (!got) return;
225
+ const { d } = got, dir = dirOf(ctx, p.w), k0 = m ? m[2] : typeof body.task === 'string' ? body.task : '';
226
+ const row = rowOn(ctx, res, p, d.ini);
227
+ if (!row) return;
228
+ if (body.add != null) {
229
+ const f = fieldsOf(body.add, true);
230
+ if (f.error) return fail(ctx, res, 400, f.error);
231
+ const start = f.value.start || B.shiftDay(today(), 1), due = f.value.due || B.shiftDay(start, 7), k = TP.newKey();
232
+ if (start && due && start > due) return fail(ctx, res, 400, 'the start is after the due day');
233
+ TP.append(dir, g.actor, { kind: 'draft-task', draft: d.id, k, add: { ...f.value, start, due, owner: f.value.owner || actorLib.pageName(g.actor.by), status: 'To do' } });
234
+ return ctx.json(res, { ok: true, task: 'dt:' + d.id + ':' + k, versions: versions(ctx, p, row) });
235
+ }
236
+ const x = d.tasks.get(k0);
237
+ if (!x) return fail(ctx, res, 404, `no task ${k0 || '(none named)'} in ${d.name}`);
238
+ if (body.drop === true || body.undrop === true) {
239
+ if (body.undrop === true && !x.drop) return fail(ctx, res, 409, 'that task is not dropped');
240
+ TP.append(dir, g.actor, { kind: 'draft-task', draft: d.id, k: x.k, ...(body.drop === true ? { drop: true } : { undrop: true }) });
241
+ return ctx.json(res, { ok: true, task: 'dt:' + d.id + ':' + x.k, gone: body.drop === true && !x.src, versions: versions(ctx, p, row) });
242
+ }
243
+ const f = fieldsOf(body.set, false);
244
+ if (f.error) return fail(ctx, res, 400, f.error);
245
+ const s = f.value.start != null ? f.value.start : x.start, e = f.value.due != null ? f.value.due : x.due;
246
+ if (s && e && s > e) return fail(ctx, res, 400, 'the start is after the due day');
247
+ const from = {}; for (const key of Object.keys(f.value)) from[key] = x[key] == null ? '' : x[key];
248
+ TP.append(dir, g.actor, { kind: 'draft-task', draft: d.id, k: x.k, set: f.value });
249
+ ctx.json(res, { ok: true, task: 'dt:' + d.id + ':' + x.k, from, versions: versions(ctx, p, row) });
250
+ },
251
+ '/api/task-plans/name': (ctx, res, body, g, p) => {
252
+ const got = draftOf(ctx, res, p, body, true);
253
+ if (!got) return;
254
+ if (!ONE_LINE(body.name, 60)) return fail(ctx, res, 400, 'name is one line of 1 to 60 characters');
255
+ TP.append(dirOf(ctx, p.w), g.actor, { kind: 'draft-name', draft: got.d.id, name: body.name.trim() });
256
+ ctx.json(res, { ok: true, from: got.d.name });
257
+ },
258
+ '/api/task-plans/delete': (ctx, res, body, g, p) => {
259
+ const got = draftOf(ctx, res, p, body, true);
260
+ if (!got) return;
261
+ if (got.d.state === 'live' || got.d.state === 'deleted') return fail(ctx, res, 409, `${got.d.name} is ${got.d.state === 'live' ? 'live: its plan stays' : 'deleted already'}`);
262
+ TP.append(dirOf(ctx, p.w), g.actor, { kind: 'draft-delete', draft: got.d.id });
263
+ ctx.json(res, { ok: true, name: got.d.name });
264
+ },
265
+ '/api/task-plans/restore': (ctx, res, body, g, p) => {
266
+ const got = draftOf(ctx, res, p, body, true);
267
+ if (!got) return;
268
+ if (got.d.state !== 'deleted') return fail(ctx, res, 409, `${got.d.name} is not deleted`);
269
+ TP.append(dirOf(ctx, p.w), g.actor, { kind: 'draft-restore', draft: got.d.id });
270
+ ctx.json(res, { ok: true });
271
+ },
272
+ '/api/task-plans/live': (ctx, res, body, g, p) => {
273
+ const got = draftOf(ctx, res, p, body);
274
+ if (!got) return;
275
+ const row = rowOn(ctx, res, p, got.d.ini);
276
+ if (!row) return;
277
+ const out = applyLive(ctx, p, row, got.d, g);
278
+ ctx.json(res, { ok: true, ...out, name: got.d.name, versions: versions(ctx, p, row) });
279
+ },
280
+ '/api/task-plans/unlive': (ctx, res, body, g, p) => {
281
+ const got = draftOf(ctx, res, p, body, true);
282
+ if (!got) return;
283
+ const { F, d } = got;
284
+ if (d.state !== 'live') return fail(ctx, res, 409, `${d.name} is not live`);
285
+ const later = [...F.drafts.values()].some((o) => o.ini === d.ini && o.state === 'live' && o.liveAt > d.liveAt);
286
+ if (later) return fail(ctx, res, 409, 'a newer draft was made live since: undo that one first');
287
+ const out = undoLive(ctx, p, d, g);
288
+ ctx.json(res, { ok: true, ...out });
289
+ },
290
+ '/api/task-plans/plan': (ctx, res, body, g, p) => {
291
+ const row = rowOn(ctx, res, p, body.initiative);
292
+ if (!row) return;
293
+ if (body.name != null && !ONE_LINE(body.name, 60)) return fail(ctx, res, 400, 'name is one line of 1 to 60 characters');
294
+ const tasks = TP.planTasksOf(liveOf(p, row));
295
+ if (!tasks.length) return fail(ctx, res, 409, 'no Live task has a date yet: nothing to save');
296
+ const plan = TP.newId('plan'), name = body.name ? body.name.trim() : 'Live · ' + md(today());
297
+ TP.append(dirOf(ctx, p.w), g.actor, { kind: 'plan', plan, board: p.board.id, initiative: row.id, name, source: 'live', tasks });
298
+ ctx.json(res, { ok: true, plan: { id: plan, name }, versions: versions(ctx, p, row) });
299
+ },
300
+ '/api/task-plans/plan/remove': (ctx, res, body, g, p) => {
301
+ const F = TP.read(dirOf(ctx, p.w)), x = F.plans.get(String(body.plan || ''));
302
+ if (!x || x.board !== p.board.id) return fail(ctx, res, 404, `no saved plan ${body.plan || '(none named)'} on this board`);
303
+ if ([...F.drafts.values()].some((d) => d.plan === x.id && d.state === 'live')) return fail(ctx, res, 409, 'this plan came from Make live: undo that instead');
304
+ TP.append(dirOf(ctx, p.w), g.actor, { kind: 'plan-remove', plan: x.id });
305
+ ctx.json(res, { ok: true });
306
+ },
307
+ };
308
+
309
+ module.exports = {
310
+ prefixes: ['/api/task-plans'],
311
+ buildStart, liveOf,
312
+ handle: async (req, res, url, ctx) => {
313
+ const path = url.pathname;
314
+ if (req.method === 'GET') {
315
+ const fn = READS[path];
316
+ if (!fn) return fail(ctx, res, 404, 'not found');
317
+ fn(ctx, res, url);
318
+ return true;
319
+ }
320
+ if (req.method !== 'POST') return fail(ctx, res, 405, 'GET or POST only');
321
+ const fn = WRITES[path];
322
+ if (!fn) return fail(ctx, res, 404, 'not found');
323
+ const got = await ctx.readJson(req);
324
+ if (!got.ok || !isObj(got.body)) return fail(ctx, res, 400, 'the body must be a JSON object');
325
+ const body = got.body, g = guard.requirePagePress(req, body);
326
+ if (!g.ok) return fail(ctx, res, g.status, g.error);
327
+ const p = RB.postFrame(ctx, res, body);
328
+ if (!p) return true;
329
+ if (!p.file || !dirOf(ctx, p.w)) return fail(ctx, res, 409, NO_STATE);
330
+ fn(ctx, res, body, g, p);
331
+ return true;
332
+ },
333
+ };