create-pmos 0.421.0 → 0.423.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 (112) 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 +87 -3
  8. package/workspace/briefing-premium-adddoc-test.js +1 -1
  9. package/workspace/briefing-premium-board-test.js +13 -11
  10. package/workspace/briefing-premium-initiative-test.js +30 -38
  11. package/workspace/changelog.json +24 -0
  12. package/workspace/fixtures/report-api/draft.json +2 -1
  13. package/workspace/guide/briefing-premium.md +2 -1
  14. package/workspace/guide/home.md +14 -4
  15. package/workspace/guide/programs.md +5 -3
  16. package/workspace/guide/workflows.md +5 -1
  17. package/workspace/home-other-product-test.js +55 -0
  18. package/workspace/ini-workflow-test.js +4 -4
  19. package/workspace/lib/board-premium.js +21 -6
  20. package/workspace/lib/custom-docs.js +65 -3
  21. package/workspace/lib/doc-live-root.js +37 -0
  22. package/workspace/lib/engine/anchor-resolve.js +93 -15
  23. package/workspace/lib/engine/boards.js +30 -2
  24. package/workspace/lib/engine/intake.js +1 -1
  25. package/workspace/lib/hold-spans.js +24 -10
  26. package/workspace/lib/initiative-writer.js +63 -1
  27. package/workspace/lib/kg.js +1 -1
  28. package/workspace/lib/plan-items.js +36 -5
  29. package/workspace/lib/programs.js +11 -3
  30. package/workspace/lib/report-draft.js +3 -0
  31. package/workspace/lib/route-modules.js +2 -0
  32. package/workspace/lib/routes-board-premium.js +28 -0
  33. package/workspace/lib/routes-boards.js +92 -13
  34. package/workspace/lib/routes-doc-sheet.js +29 -1
  35. package/workspace/lib/routes-initiatives.js +12 -0
  36. package/workspace/lib/routes-programs.js +44 -5
  37. package/workspace/lib/routes-task-links.js +329 -0
  38. package/workspace/lib/routes-task-plans.js +333 -0
  39. package/workspace/lib/split-merge-suggest.js +162 -0
  40. package/workspace/lib/split-merge.js +379 -0
  41. package/workspace/lib/task-cli.js +73 -13
  42. package/workspace/lib/task-items.js +15 -3
  43. package/workspace/lib/task-links.js +422 -0
  44. package/workspace/lib/task-plans.js +232 -0
  45. package/workspace/lib/vendor/scripts/anchor-resolve.js +93 -15
  46. package/workspace/lib/vendor/scripts/intake.js +1 -1
  47. package/workspace/package-lock.json +2 -2
  48. package/workspace/package.json +1 -1
  49. package/workspace/premium-board-actions-test.js +2 -2
  50. package/workspace/premium-core-doc-issue-test.js +2 -2
  51. package/workspace/premium-vw-backlog-test.js +3 -3
  52. package/workspace/premium-vw-doc-test.js +26 -3
  53. package/workspace/premium-vw-item-test.js +3 -3
  54. package/workspace/premium-vw-jira-test.js +6 -6
  55. package/workspace/product-lane-test.js +165 -0
  56. package/workspace/program-leave-test.js +203 -0
  57. package/workspace/program-panel-test.js +1 -1
  58. package/workspace/public/pm/bd-acts.js +5 -2
  59. package/workspace/public/pm/bd-ini-panel.js +32 -9
  60. package/workspace/public/pm/bd-prog-panel.js +22 -7
  61. package/workspace/public/pm/bd-prog.js +6 -1
  62. package/workspace/public/pm/bd-span.js +234 -30
  63. package/workspace/public/pm/bd-views.js +3 -2
  64. package/workspace/public/pm/cozy-board.css +90 -0
  65. package/workspace/public/pm/cozy-home.css +3 -0
  66. package/workspace/public/pm/doc-follow.js +36 -0
  67. package/workspace/public/pm/home-app.js +62 -14
  68. package/workspace/public/pm/home-ini-model.js +0 -34
  69. package/workspace/public/pm/home-ini.js +81 -204
  70. package/workspace/public/pm/home-list.js +2 -2
  71. package/workspace/public/pm/home-today.js +3 -1
  72. package/workspace/public/pm/ini-groups.js +228 -0
  73. package/workspace/public/pm/ini-links.js +561 -0
  74. package/workspace/public/pm/ini-tasks.js +131 -30
  75. package/workspace/public/pm/ini-versions.js +348 -0
  76. package/workspace/public/pm/ini-view-model.js +113 -43
  77. package/workspace/public/pm/ini-view.css +341 -18
  78. package/workspace/public/pm/ini-view.js +153 -38
  79. package/workspace/public/pm/premium-board.js +160 -21
  80. package/workspace/public/pm/premium-report-read.js +20 -1
  81. package/workspace/public/pm/premium-shell.js +29 -4
  82. package/workspace/public/pm/premium-vw-doc.js +46 -11
  83. package/workspace/public/pm/prog-move.js +69 -0
  84. package/workspace/public/pm/split-merge.css +77 -0
  85. package/workspace/public/pm/split-merge.js +265 -0
  86. package/workspace/public/pm/stage-line.js +414 -0
  87. package/workspace/public/pm/task-card.css +3 -0
  88. package/workspace/public/pm/task-card.js +15 -6
  89. package/workspace/public/pm/wf-page.css +2 -0
  90. package/workspace/public/pm/wf-page.js +2 -0
  91. package/workspace/public/pm/wf-stage.js +2 -1
  92. package/workspace/server.js +15 -1
  93. package/workspace/split-merge-ui-test.js +175 -0
  94. package/workspace/stage-card-test.js +12 -11
  95. package/workspace/task-card-test.js +3 -2
  96. package/workspace/task-delete-test.js +126 -0
  97. package/workspace/task-links-test.js +227 -0
  98. package/workspace/task-milestones-test.js +176 -0
  99. package/workspace/task-plans-test.js +181 -0
  100. package/workspace/task-views-test.js +3 -3
  101. package/workspace/test-lists/bd-ini-panel.json +8 -2
  102. package/workspace/test-lists/product-lane.json +6 -0
  103. package/workspace/test-lists/program-leave.json +6 -0
  104. package/workspace/test-lists/split-merge.json +15 -0
  105. package/workspace/test-lists/task-delete.json +5 -0
  106. package/workspace/test-lists/task-links.json +6 -0
  107. package/workspace/test-lists/task-milestones.json +6 -0
  108. package/workspace/test-lists/task-plans.json +6 -0
  109. package/workspace/test-lists/viewer-live-file.json +9 -0
  110. package/workspace/timeline-holds-test.js +61 -4
  111. package/workspace/tk-tasks-test.js +173 -57
  112. package/workspace/workflows-setup-test.js +4 -3
@@ -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
+ };
@@ -0,0 +1,162 @@
1
+ 'use strict';
2
+ /* split-merge-suggest.js — Claude's suggestion to split an initiative or merge two (feedback batch 11 item 14, option A grilled; canvas
3
+ * XsmA1Suggest, XsmA4MergeSuggest, rules sticky xsplitR). PURE: it reads the Board's own rows and work items and writes nothing.
4
+ *
5
+ * suggest(rows, items, { dismissed, today }) → Map<initiative id, suggestion>
6
+ * rows the Board model's open rows (lib/board-premium.js rowOf: id, title, anchor, kr, epics, end, wfStage, status)
7
+ * items the board's work items (routes-boards itemsOf): PMOS tasks and Jira tickets, each with ini, status, owner, start, end, epic
8
+ * dismissed Map<id, { kind, fp }> the PM's ✕ Not now (the boards ledger's ini-suggest lines); the same fingerprint stays hidden
9
+ * fingerprint(list) → the 16 hex characters a suggestion is known by: it changes when the tasks or tickets it was made from change
10
+ *
11
+ * It runs on every read of the Board, so it follows the tasks and tickets as they change, never a timer. It only suggests: the card's ✓ is
12
+ * the PM's approval (lib/split-merge.js writes nothing without a page press). One card per initiative; a merge wins over a split.
13
+ *
14
+ * SPLIT when the open work falls into two groups that share no dates (two weeks or more between them), no owner and no Jira epic, and the
15
+ * later group is its own job: its own Jira ticket or its own owner. The later group moves; it is named from its one ticket, else the word
16
+ * its titles share, else its first task.
17
+ * → { kind: 'split', fp, title, why, name, tasks: [uid], tickets: [key], docs: [], counts, stays }
18
+ * MERGE when two open initiatives of one board (one product) link the same Jira epic, or most of their open tasks are alike (3 or more, and
19
+ * at least half of the smaller one's). The one further along stays, then the one with more open work; the card is on the one that closes.
20
+ * → { kind: 'merge', fp, title, why, into, intoTitle, reason, end, anchor }
21
+ * Honest limit: tasks have no dependencies yet, so "waits on nothing in the other" is not checked; and a program's initiatives on another
22
+ * product's board are not compared (a merge stays on one board). */
23
+ const crypto = require('crypto');
24
+
25
+ const OPEN = new Set(['To do', 'In progress', 'In review']);
26
+ const STOP = new Set(['the', 'and', 'for', 'with', 'from', 'into', 'onto', 'old', 'new', 'all', 'our', 'its', 'this', 'that', 'write', 'make', 'plan', 'add', 'set', 'get', 'list', 'run', 'draft', 'review', 'check', 'update', 'task', 'tasks', 'ticket']);
27
+ const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
28
+ const DAY = 86400000;
29
+ const GAP_DAYS = 14;
30
+
31
+ const dayOf = (v) => { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(v || '')); return m ? Date.UTC(+m[1], +m[2] - 1, +m[3]) : null; };
32
+ const mon = (ms) => MON[new Date(ms).getUTCMonth()];
33
+ const monY = (ms) => mon(ms) + ' ' + new Date(ms).getUTCFullYear();
34
+ const clip = (s, n) => { s = String(s == null ? '' : s).replace(/\s+/g, ' ').trim(); return s.length > n ? s.slice(0, n - 1).trimEnd() + '…' : s; };
35
+ const words = (t) => String(t || '').toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length >= 3 && !STOP.has(w));
36
+ const plural = (n, one, many) => n + ' ' + (n === 1 ? one : many);
37
+
38
+ function fingerprint(list) {
39
+ return crypto.createHash('sha1').update(JSON.stringify(list)).digest('hex').slice(0, 16);
40
+ }
41
+ /** The open work of one initiative: its open PMOS tasks and open Jira tickets, each { id, kind, title, owner, epic, a, z }. */
42
+ function openWork(items, id) {
43
+ const out = [];
44
+ for (const x of items) {
45
+ if (!x || x.ini !== id || x.kind === 'Epic' || !OPEN.has(x.status)) continue;
46
+ const a = dayOf(x.start) || dayOf(x.end), z = dayOf(x.end) || dayOf(x.start);
47
+ out.push({ id: x.src === 'jira' ? x.key : x.uid, jira: x.src === 'jira', title: x.title || x.key || x.uid, owner: x.src === 'jira' ? '' : String(x.owner || '').trim(), epic: x.epic || null, a, z });
48
+ }
49
+ return out;
50
+ }
51
+ const fpOf = (work) => fingerprint(work.map((w) => [w.id, w.a, w.z, w.owner, w.epic]).sort((x, y) => String(x[0]).localeCompare(String(y[0]))));
52
+ const disjoint = (a, b) => { for (const x of a) if (b.has(x)) return false; return true; };
53
+
54
+ /** The name of the group that moves: its one Jira ticket, else a word two of its titles share and the other group's do not, else its first task. */
55
+ function nameOf(group, rest) {
56
+ const tk = group.filter((w) => w.jira);
57
+ if (tk.length === 1) return clip(tk[0].title.replace(/^[A-Z][A-Z0-9_]+-\d+\s*/, ''), 80);
58
+ const count = new Map(), other = new Set(rest.flatMap((w) => words(w.title)));
59
+ for (const w of group) for (const x of new Set(words(w.title))) if (!other.has(x)) count.set(x, (count.get(x) || 0) + 1);
60
+ const top = [...count.entries()].filter(([, n]) => n >= 2).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0];
61
+ const first = group.find((w) => !w.jira) || group[0];
62
+ if (top) {
63
+ const head = top[0].charAt(0).toUpperCase() + top[0].slice(1);
64
+ const tail = clip(first.title, 50);
65
+ return tail.toLowerCase().includes(top[0]) ? clip(tail.charAt(0).toUpperCase() + tail.slice(1), 80) : clip(head + ' — ' + tail.charAt(0).toLowerCase() + tail.slice(1), 80);
66
+ }
67
+ return clip(first.title, 80);
68
+ }
69
+
70
+ function splitOf(row, work) {
71
+ const dated = work.filter((w) => w.a != null).sort((x, y) => x.a - y.a || x.z - y.z);
72
+ if (dated.length < 4) return null;
73
+ let best = null;
74
+ for (let c = 2; c <= dated.length - 2; c++) {
75
+ const L = dated.slice(0, c), Rr = dated.slice(c);
76
+ const lz = Math.max(...L.map((w) => w.z)), ra = Math.min(...Rr.map((w) => w.a));
77
+ const gap = (ra - lz) / DAY;
78
+ if (gap < GAP_DAYS) continue;
79
+ const lo = new Set(L.map((w) => w.owner).filter(Boolean)), ro = new Set(Rr.map((w) => w.owner).filter(Boolean));
80
+ const le = new Set(L.map((w) => w.epic).filter(Boolean)), re = new Set(Rr.map((w) => w.epic).filter(Boolean));
81
+ if (!disjoint(lo, ro) || !disjoint(le, re)) continue;
82
+ const ownTicket = Rr.some((w) => w.jira), ownOwner = ro.size > 0;
83
+ if (!ownTicket && !ownOwner) continue;
84
+ if (!best || gap > best.gap) best = { L, R: Rr, gap, ownTicket, ownOwner };
85
+ }
86
+ if (!best) return null;
87
+ const undated = work.filter((w) => w.a == null);
88
+ const rest = best.L.concat(undated);
89
+ const name = nameOf(best.R, rest);
90
+ const a = Math.min(...best.R.map((w) => w.a)), z = Math.max(...best.R.map((w) => w.z));
91
+ const span = mon(a) === mon(z) && new Date(a).getUTCFullYear() === new Date(z).getUTCFullYear() ? mon(a) : mon(a) + '–' + mon(z);
92
+ const own = ['their own dates (' + span + ')'];
93
+ if (best.ownTicket) own.push(best.R.filter((w) => w.jira).length === 1 ? 'their own Jira ticket' : 'their own Jira tickets');
94
+ if (best.ownOwner) own.push('their own owner');
95
+ const n = best.R.length, all = work.length;
96
+ const share = n * 2 === all ? 'Half of the open tasks are' : n === 1 ? 'One open task is' : n + ' of the ' + all + ' open tasks are';
97
+ const tasks = best.R.filter((w) => !w.jira).map((w) => w.id), tickets = best.R.filter((w) => w.jira).map((w) => w.id);
98
+ const stays = rest.slice(0, 3).map((w) => clip(w.title, 28)).join(', ');
99
+ return {
100
+ kind: 'split', fp: fpOf(work), title: 'Split off ' + name + '?', why: share + ' on their own: ' + own.join(', ').replace(/, ([^,]*)$/, ' and $1') + '.',
101
+ name, tasks, tickets, docs: [], counts: { tasks: tasks.length, tickets: tickets.length, docs: 0 }, stays,
102
+ };
103
+ }
104
+
105
+ /** How far along a row is: its stage's place in its workflow. */
106
+ const along = (r) => (r.wfStage && Number.isFinite(r.wfStage.n) ? r.wfStage.n : 0);
107
+ const norm = (t) => words(t).join(' ');
108
+ function alike(a, b) {
109
+ if (!a || !b) return false;
110
+ if (a === b) return true;
111
+ const A = new Set(a.split(' ')), Bs = new Set(b.split(' '));
112
+ let n = 0; for (const x of A) if (Bs.has(x)) n++;
113
+ return n / Math.max(A.size, Bs.size) >= 0.6;
114
+ }
115
+ function mergeOf(rows, workBy, items) {
116
+ const out = new Map();
117
+ const epicsOf = (r) => new Set([...(r.epics || []), ...items.filter((x) => x && x.ini === r.id && x.epic).map((x) => x.epic), ...items.filter((x) => x && x.ini === r.id && x.kind === 'Epic' && x.key).map((x) => x.key)]);
118
+ const open = rows.filter((r) => r && r.id && r.status !== 'done');
119
+ for (let i = 0; i < open.length; i++) {
120
+ for (let j = i + 1; j < open.length; j++) {
121
+ const A = open[i], B = open[j];
122
+ const ea = epicsOf(A), eb = epicsOf(B), shared = [...ea].filter((k) => eb.has(k));
123
+ const wa = workBy.get(A.id) || [], wb = workBy.get(B.id) || [];
124
+ const ta = wa.filter((w) => !w.jira).map((w) => norm(w.title)).filter(Boolean), tb = wb.filter((w) => !w.jira).map((w) => norm(w.title)).filter(Boolean);
125
+ const small = ta.length <= tb.length ? ta : tb, big = small === ta ? tb : ta;
126
+ const match = small.filter((t) => big.some((u) => alike(t, u))).length;
127
+ const many = match >= 3 && match * 2 >= small.length;
128
+ if (!shared.length && !many) continue;
129
+ // the one further along stays, then the one with more open work
130
+ const stay = along(A) !== along(B) ? (along(A) > along(B) ? A : B) : (wa.length !== wb.length ? (wa.length > wb.length ? A : B) : A);
131
+ const go = stay === A ? B : A;
132
+ if (out.has(go.id)) continue;
133
+ const reason = along(A) !== along(B) ? 'it is further along' : wa.length !== wb.length ? 'it has more open work' : 'it was listed first';
134
+ const goWork = workBy.get(go.id) || [], goTasks = goWork.filter((w) => !w.jira).length;
135
+ const why = [];
136
+ if (many) why.push(match + ' of its ' + plural(goTasks || small.length, 'task', 'tasks') + ' match ' + stay.title + '’s');
137
+ if (shared.length) why.push((many ? 'both' : 'Both') + ' link Jira epic ' + shared[0]);
138
+ const ends = [go.end, stay.end].map(dayOf).filter((x) => x != null);
139
+ const end = ends.length ? Math.max(...ends) : null;
140
+ out.set(go.id, {
141
+ kind: 'merge', fp: fingerprint([go.id, stay.id, fpOf(goWork), fpOf(workBy.get(stay.id) || []), shared]), title: 'Same work as ' + clip(stay.title.split(' — ')[0], 40) + '?',
142
+ why: why.join(', and ') + '.', into: stay.id, intoTitle: stay.title, reason, end: end ? monY(end) : null, anchor: stay.kr || stay.anchor || null,
143
+ });
144
+ }
145
+ }
146
+ return out;
147
+ }
148
+
149
+ function suggest(rows, items, { dismissed } = {}) {
150
+ const L = (rows || []).filter((r) => r && r.id), I = (items || []).filter(Boolean);
151
+ const workBy = new Map(L.map((r) => [r.id, openWork(I, r.id)]));
152
+ const out = mergeOf(L, workBy, I);
153
+ for (const r of L) {
154
+ if (out.has(r.id) || r.status === 'done') continue;
155
+ const s = splitOf(r, workBy.get(r.id) || []);
156
+ if (s) out.set(r.id, s);
157
+ }
158
+ if (dismissed && dismissed.size) for (const [id, s] of [...out]) { const d = dismissed.get(id); if (d && d.fp === s.fp) out.delete(id); }
159
+ return out;
160
+ }
161
+
162
+ module.exports = { suggest, fingerprint, openWork };