create-pmos 0.422.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 (79) hide show
  1. package/package.json +13 -13
  2. package/payload/KIT-VERSION +1 -1
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/state/discoveries.md +1 -1
  6. package/workspace/board-programs-test.js +28 -0
  7. package/workspace/briefing-premium-adddoc-test.js +1 -1
  8. package/workspace/briefing-premium-board-test.js +12 -10
  9. package/workspace/briefing-premium-initiative-test.js +30 -38
  10. package/workspace/changelog.json +12 -0
  11. package/workspace/guide/briefing-premium.md +1 -1
  12. package/workspace/guide/home.md +9 -2
  13. package/workspace/guide/programs.md +1 -0
  14. package/workspace/guide/workflows.md +5 -1
  15. package/workspace/ini-workflow-test.js +4 -4
  16. package/workspace/lib/board-premium.js +3 -2
  17. package/workspace/lib/custom-docs.js +65 -3
  18. package/workspace/lib/engine/boards.js +25 -2
  19. package/workspace/lib/initiative-writer.js +63 -1
  20. package/workspace/lib/plan-items.js +36 -5
  21. package/workspace/lib/programs.js +11 -3
  22. package/workspace/lib/route-modules.js +1 -0
  23. package/workspace/lib/routes-board-premium.js +22 -0
  24. package/workspace/lib/routes-boards.js +50 -10
  25. package/workspace/lib/routes-initiatives.js +12 -0
  26. package/workspace/lib/routes-task-links.js +329 -0
  27. package/workspace/lib/split-merge-suggest.js +162 -0
  28. package/workspace/lib/split-merge.js +379 -0
  29. package/workspace/lib/task-cli.js +58 -5
  30. package/workspace/lib/task-items.js +14 -2
  31. package/workspace/lib/task-links.js +422 -0
  32. package/workspace/package-lock.json +2 -2
  33. package/workspace/package.json +1 -1
  34. package/workspace/premium-board-actions-test.js +2 -2
  35. package/workspace/premium-core-doc-issue-test.js +2 -2
  36. package/workspace/premium-vw-backlog-test.js +3 -3
  37. package/workspace/premium-vw-item-test.js +3 -3
  38. package/workspace/premium-vw-jira-test.js +6 -6
  39. package/workspace/product-lane-test.js +165 -0
  40. package/workspace/program-panel-test.js +1 -1
  41. package/workspace/public/pm/bd-ini-panel.js +16 -6
  42. package/workspace/public/pm/bd-prog.js +6 -1
  43. package/workspace/public/pm/bd-span.js +69 -15
  44. package/workspace/public/pm/bd-views.js +3 -2
  45. package/workspace/public/pm/cozy-board.css +10 -0
  46. package/workspace/public/pm/home-app.js +25 -8
  47. package/workspace/public/pm/home-ini-model.js +0 -34
  48. package/workspace/public/pm/home-ini.js +72 -204
  49. package/workspace/public/pm/ini-groups.js +228 -0
  50. package/workspace/public/pm/ini-links.js +561 -0
  51. package/workspace/public/pm/ini-tasks.js +58 -22
  52. package/workspace/public/pm/ini-versions.js +14 -9
  53. package/workspace/public/pm/ini-view-model.js +88 -4
  54. package/workspace/public/pm/ini-view.css +259 -18
  55. package/workspace/public/pm/ini-view.js +140 -32
  56. package/workspace/public/pm/premium-board.js +54 -6
  57. package/workspace/public/pm/split-merge.css +77 -0
  58. package/workspace/public/pm/split-merge.js +265 -0
  59. package/workspace/public/pm/stage-line.js +414 -0
  60. package/workspace/public/pm/task-card.js +5 -3
  61. package/workspace/public/pm/wf-page.css +2 -0
  62. package/workspace/public/pm/wf-page.js +2 -0
  63. package/workspace/public/pm/wf-stage.js +2 -1
  64. package/workspace/server.js +15 -1
  65. package/workspace/split-merge-ui-test.js +175 -0
  66. package/workspace/stage-card-test.js +12 -11
  67. package/workspace/task-card-test.js +3 -2
  68. package/workspace/task-delete-test.js +126 -0
  69. package/workspace/task-links-test.js +227 -0
  70. package/workspace/task-milestones-test.js +1 -1
  71. package/workspace/task-plans-test.js +6 -0
  72. package/workspace/task-views-test.js +1 -1
  73. package/workspace/test-lists/bd-ini-panel.json +8 -2
  74. package/workspace/test-lists/product-lane.json +6 -0
  75. package/workspace/test-lists/split-merge.json +15 -0
  76. package/workspace/test-lists/task-delete.json +5 -0
  77. package/workspace/test-lists/task-links.json +6 -0
  78. package/workspace/tk-tasks-test.js +173 -57
  79. package/workspace/workflows-setup-test.js +4 -3
@@ -7,11 +7,17 @@
7
7
  * check(input) → { ok: true, value } | { ok: false, status, error } PURE
8
8
  * list(root, scope) → [{ id, scope, title, writer, phase, link, at }] in the order they were added
9
9
  * add(root, input, actor, { now }) → { ok: true, doc } | { ok: false, status, error }
10
+ * move(root, ids, scope, actor) → { ok: true, moved: [{ id, from }] } documents taken to another initiative (a split or a merge,
11
+ * feedback batch 11 item 14); Undo is the same call back to `from`
12
+ * drop(root, id, actor) → { ok: true, dropped } the Undo of addFile
13
+ * addFile(root, { scope, title, file, phase? }, actor) → { ok: true, doc } a PMOS file joins an initiative's documents: the PRD of an
14
+ * initiative merged into another (the one that stays keeps its own PRD)
10
15
  *
11
16
  * THE LEDGER. Lines { v: 1, ev: 'add', id, scope, title, writer, phase, link, actor, at }. `scope` is board:<id> or initiative:<id>. `writer` is
12
17
  * drafts | you. `phase` is a phase name for an initiative and null for a board. `link` is { kind, url } or null. `actor` is the actor of the call
13
18
  * path (lib/actor.js), never an argument. Nothing here reads or syncs a linked page: the record holds the address and the date it was added.
14
- * The file is never rewritten. A line that does not parse, or has no title, is skipped.
19
+ * The file is never rewritten. A line that does not parse, or has no title, is skipped. A `move` line { v: 1, ev: 'move', id, scope, actor, at } puts
20
+ * a document in another scope (the last one wins); an add with `file` (a repository path) names a document PMOS holds, not a link.
15
21
  */
16
22
  const fs = require('fs');
17
23
  const path = require('path');
@@ -40,7 +46,21 @@ function readLines(file) {
40
46
  if (!raw.trim()) continue;
41
47
  try { const l = JSON.parse(raw); if (isObj(l) && l.ev === 'add' && typeof l.scope === 'string' && typeof l.title === 'string' && l.title && typeof l.id === 'string') out.push(l); } catch { /* a torn line is skipped */ }
42
48
  }
43
- return out;
49
+ return withMoves(out, text);
50
+ }
51
+ /** The adds with each one's scope after the move lines (a split or a merge took it to another initiative). */
52
+ function withMoves(adds, text) {
53
+ if (!text.includes('"move"') && !text.includes('"drop"')) return adds;
54
+ const to = new Map(), gone = new Set();
55
+ for (const raw of text.split('\n')) {
56
+ if (!raw.includes('"move"') && !raw.includes('"drop"')) continue;
57
+ try {
58
+ const l = JSON.parse(raw);
59
+ if (isObj(l) && l.ev === 'move' && typeof l.id === 'string' && SCOPE_RE.test(String(l.scope || ''))) to.set(l.id, l.scope);
60
+ if (isObj(l) && l.ev === 'drop' && typeof l.id === 'string') gone.add(l.id);
61
+ } catch { /* skipped */ }
62
+ }
63
+ return adds.filter((l) => !gone.has(l.id)).map((l) => (to.has(l.id) ? { ...l, scope: to.get(l.id) } : l));
44
64
  }
45
65
 
46
66
  /** Check the fields of an add. The scope's existence is the route's check; this one is about the shape. */
@@ -78,9 +98,49 @@ function list(root, scope) {
78
98
  return readLines(ledgerFile(root)).filter((l) => l.scope === scope).map((l) => ({
79
99
  id: l.id, scope: l.scope, title: l.title, writer: WRITERS.includes(l.writer) ? l.writer : null, phase: PHASES.includes(l.phase) ? l.phase : null,
80
100
  link: isObj(l.link) && KINDS.includes(l.link.kind) && typeof l.link.url === 'string' ? { kind: l.link.kind, url: l.link.url } : null, at: l.at || null,
101
+ ...(typeof l.file === 'string' && l.file ? { file: l.file } : {}),
81
102
  }));
82
103
  }
83
104
 
105
+ /** Documents to another scope: one move line each. `ids` not in the ledger are skipped. */
106
+ function move(root, ids, scope, actor) {
107
+ if (!SCOPE_RE.test(String(scope || ''))) return refuse(400, 'scope must be board:<id> or initiative:<id>');
108
+ const file = ledgerFile(root);
109
+ const have = new Map(readLines(file).map((l) => [l.id, l]));
110
+ const moved = [];
111
+ const t = Date.now();
112
+ for (const id of [...new Set(ids || [])]) {
113
+ const l = have.get(id);
114
+ if (!l || l.scope === scope) continue;
115
+ fs.mkdirSync(path.dirname(file), { recursive: true });
116
+ fs.appendFileSync(file, JSON.stringify({ v: 1, ev: 'move', id, scope, actor: actor || null, at: new Date(t).toISOString() }) + '\n');
117
+ moved.push({ id, from: l.scope });
118
+ }
119
+ return { ok: true, moved };
120
+ }
121
+ /** Take back a document a merge added (its Undo): one drop line. */
122
+ function drop(root, id, actor) {
123
+ const file = ledgerFile(root);
124
+ if (!readLines(file).some((l) => l.id === id)) return { ok: true, dropped: false };
125
+ fs.appendFileSync(file, JSON.stringify({ v: 1, ev: 'drop', id, actor: actor || null, at: new Date().toISOString() }) + '\n');
126
+ return { ok: true, dropped: true };
127
+ }
128
+ /** A PMOS file as one of an initiative's documents (the closing initiative's PRD on a merge). */
129
+ function addFile(root, input, actor) {
130
+ const i = isObj(input) ? input : {};
131
+ if (!SCOPE_RE.test(String(i.scope || ''))) return refuse(400, 'scope must be board:<id> or initiative:<id>');
132
+ const file = typeof i.file === 'string' ? i.file.trim() : '';
133
+ if (!file || file.length > URL_MAX || path.isAbsolute(file) || file.split(/[\\/]/).includes('..')) return refuse(400, 'file is a path inside the repository');
134
+ const title = String(i.title || '').trim().replace(/\s+/g, ' ').slice(0, TITLE_MAX);
135
+ if (!title) return refuse(400, 'Give the document a title.');
136
+ const f = ledgerFile(root), have = readLines(f).filter((l) => l.scope === i.scope);
137
+ const t = Date.now();
138
+ const line = { v: 1, ev: 'add', id: 'cd-' + t.toString(36) + '-' + (have.length + 1), scope: i.scope, title, writer: 'you', phase: PHASES.includes(i.phase) ? i.phase : null, link: null, file, actor: actor || null, at: new Date(t).toISOString() };
139
+ fs.mkdirSync(path.dirname(f), { recursive: true });
140
+ fs.appendFileSync(f, JSON.stringify(line) + '\n');
141
+ return { ok: true, doc: { id: line.id, scope: line.scope, title, file, at: line.at } };
142
+ }
143
+
84
144
  /** THE SINGLE WRITER of custom-docs.jsonl. `v`, `id` and `at` are set here. */
85
145
  function add(root, input, actor, { now } = {}) {
86
146
  const c = check(input);
@@ -99,9 +159,11 @@ function add(root, input, actor, { now } = {}) {
99
159
  /** One added document as a row of the Core documents card. PURE. `st` is `missing` (no link) or `linked`; never `ok`: PMOS cannot read a linked page.
100
160
  * `added` is the day it was added (YYYY-MM-DD) and the only date the row holds. */
101
161
  function rowOf(d) {
162
+ // a PMOS file that joined from a merged initiative opens like a core document
163
+ if (d.file) return { key: 'custom:' + d.id, title: d.title, what: 'Joined on a merge.', st: 'ok', state: 'Saved', by: '', cat: d.phase || null, link: null, path: d.file, added: d.at ? String(d.at).slice(0, 10) : '', custom: true, act: null };
102
164
  const linked = !!d.link;
103
165
  return { key: 'custom:' + d.id, title: d.title, what: linked ? 'Lives in ' + d.link.kind + ': ' + d.link.url : 'Added by you.', st: linked ? 'linked' : 'missing', state: linked ? 'Linked' : 'Not started',
104
166
  by: d.writer === 'you' ? 'You write it' : d.writer === 'drafts' ? 'PMOS drafts it' : '', cat: d.phase || null, link: d.link, added: d.at ? String(d.at).slice(0, 10) : '', custom: true, act: null };
105
167
  }
106
168
 
107
- module.exports = { rowOf, KINDS, PHASES, WRITERS, TITLE_MAX, URL_MAX, ledgerFile, readLines, check, list, add };
169
+ module.exports = { rowOf, KINDS, PHASES, WRITERS, TITLE_MAX, URL_MAX, ledgerFile, readLines, check, list, add, move, addFile, drop };
@@ -43,6 +43,8 @@
43
43
  * never moves the initiative. `task` is a Board task or a breakdown item; the last line wins.
44
44
  * task-milestone { task, milestone } a task flagged as a milestone (feedback batch 11 item 3): its due
45
45
  * date is the milestone's date and Done is its done. `task` is a Board task, a breakdown item or a Jira key; the last line wins.
46
+ * ticket-dates { ref, start, due } the PM's own start and due days for a Jira ticket (feedback batch 11
47
+ * item 23): kept in PMOS only, never written to Jira; '' clears one. They win over Jira's dates on the timeline; the last line wins.
46
48
  * Nothing is deleted. A line that is not an object with a known kind is skipped.
47
49
  *
48
50
  * STAGE OF AN INITIATIVE on a team board: the last move recorded for it on that board (a workflow edit's `moved` and an
@@ -163,7 +165,9 @@ function foundOf(f) {
163
165
  const sources = Array.isArray(f.sources) ? f.sources.filter((x) => x && typeof x.ref === 'string').slice(0, 8).map((x) => ({ label: String(x.label || ''), ref: x.ref })) : [];
164
166
  return { why: typeof f.why === 'string' ? f.why : '', sources, match: typeof f.match === 'string' && f.match ? f.match : null, scan: typeof f.scan === 'string' ? f.scan : null, run: typeof f.run === 'string' ? f.run : null };
165
167
  }
166
- const KINDS = new Set(['board', 'workflow', 'move', 'assign', 'ask', 'ask-accept', 'ask-decline', 'ask-more', 'ini-workflow', 'task', 'task-update', 'task-remove', 'task-restore', 'ticket-note', 'ini-epics', 'ini-archive', 'ini-notdup', 'ini-wf', 'ini-end', 'stage-judge', 'ini-auto', 'task-section', 'task-milestone']);
168
+ const KINDS = new Set(['board', 'workflow', 'move', 'assign', 'ask', 'ask-accept', 'ask-decline', 'ask-more', 'ini-workflow', 'task', 'task-update', 'task-remove', 'task-restore', 'ticket-note', 'ini-epics', 'ini-archive', 'ini-notdup', 'ini-wf', 'ini-end', 'stage-judge', 'ini-auto', 'task-section', 'task-milestone', 'ticket-dates',
169
+ // split or merge initiatives (feedback batch 11 item 14): a Jira ticket moved to another initiative, the split and merge records with their Undo, Claude's suggestion dismissed
170
+ 'ticket-move', 'ini-split', 'ini-merge', 'ini-sm-undo', 'ini-suggest']);
167
171
  // A task's state is its only stage (Wawan, 2026-10-25): the same five every workflow ends in. An old 'In review' reads as In progress (taskState).
168
172
  const TASK_STATES = Object.freeze(['To do', 'In progress', 'Done', "Won't do", 'Archived']);
169
173
  const taskState = (s) => (s === 'In review' ? 'In progress' : TASK_STATES.includes(s) ? s : null);
@@ -196,6 +200,7 @@ function fold(events) {
196
200
  const milestones = new Map(); // task id (or Jira key) → true | false: the PM's milestone flag; the last task-milestone line wins
197
201
  const removed = new Map(); // task id → the task a task-remove took out, so a task-restore (Delete's Undo) puts it back
198
202
  const ticketNotes = new Map(); // key(board, Jira key) → the PM's notes on that ticket (the last ticket-note line wins)
203
+ const ticketDates = new Map(); // key(board, Jira key) → { start, due } the PM keeps in PMOS for that ticket (the last ticket-dates line wins)
199
204
  const epics = new Map(); // initiative id → the Jira epic keys the PM linked to it (the last ini-epics line wins)
200
205
  const archives = new Map(); // initiative id → { at, by, reason, into, moved } while archived (an `archived: false` line restores it)
201
206
  const notDup = new Map(); // initiative id → Set of initiative ids the PM said it is not a duplicate of
@@ -204,6 +209,12 @@ function fold(events) {
204
209
  const ends = new Map(); // key(board, id) → { as: 'wontdo', reason, note, at, by } while it is out (a `back` line brings it back to Triage)
205
210
  const judged = new Map(); // key(board, id) → { [stageKey]: { runs, why, cite, at, by } } (an `undo` line drops the reading)
206
211
  const autoOver = new Map(); // key(board, id) → { [stageKey]: true|false } the PM's own Moves on by itself for one initiative
212
+ // split or merge (batch 11 item 14): Jira key → the initiative it moved to (a split or a merge; `to: null` sends it back to where Jira puts it),
213
+ // op id → the ini-split / ini-merge line (its `undo` says how to put everything back), the ops undone, and the PM's ✕ on Claude's suggestion
214
+ const ticketMoves = new Map();
215
+ const smOps = new Map();
216
+ const smUndone = new Set();
217
+ const suggestNo = new Map(); // initiative id → { kind, fp, at } (the last ✕; a suggestion with another fingerprint shows again)
207
218
  const list = [];
208
219
  for (let e of Array.isArray(events) ? events : []) {
209
220
  if (typeof e === 'string') { try { e = JSON.parse(e); } catch { continue; } }
@@ -280,6 +291,10 @@ function fold(events) {
280
291
  sections.set(e.task, e.section);
281
292
  } else if (e.kind === 'task-milestone' && typeof e.task === 'string' && e.task && typeof e.milestone === 'boolean') {
282
293
  milestones.set(e.task, e.milestone);
294
+ } else if (e.kind === 'ticket-dates' && b && typeof e.ref === 'string' && JIRA_KEY_RE.test(e.ref)) {
295
+ const d = (v) => (typeof v === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(v) ? v : '');
296
+ const v = { start: d(e.start), due: d(e.due) };
297
+ if (v.start || v.due) ticketDates.set(key(b, e.ref.toUpperCase()), v); else ticketDates.delete(key(b, e.ref.toUpperCase()));
283
298
  } else if (e.kind === 'ticket-note' && b && typeof e.ref === 'string' && typeof e.notes === 'string') {
284
299
  if (e.notes) ticketNotes.set(key(b, e.ref), e.notes); else ticketNotes.delete(key(b, e.ref));
285
300
  } else if (e.kind === 'task-remove' && typeof e.task === 'string' && tasks.has(e.task)) {
@@ -324,9 +339,17 @@ function fold(events) {
324
339
  const a = asks.get(e.ask);
325
340
  if (a.state !== 'open') continue;
326
341
  Object.assign(a, { state: 'declined', why: e.why || '', closedAt: e.at || null });
342
+ } else if (e.kind === 'ticket-move' && typeof e.key === 'string' && JIRA_KEY_RE.test(e.key)) {
343
+ if (typeof e.to === 'string' && e.to) ticketMoves.set(e.key.toUpperCase(), e.to); else ticketMoves.delete(e.key.toUpperCase());
344
+ } else if ((e.kind === 'ini-split' || e.kind === 'ini-merge') && typeof e.op === 'string' && e.op && !smOps.has(e.op)) {
345
+ smOps.set(e.op, e);
346
+ } else if (e.kind === 'ini-sm-undo' && typeof e.op === 'string' && smOps.has(e.op)) {
347
+ smUndone.add(e.op);
348
+ } else if (e.kind === 'ini-suggest' && typeof e.id === 'string' && e.answer === 'dismiss' && typeof e.fp === 'string') {
349
+ suggestNo.set(e.id, { kind: e.of === 'merge' ? 'merge' : 'split', fp: e.fp, at: e.at || null });
327
350
  }
328
351
  }
329
- return { boards, moves, assigns, asks, stages, iniWorkflows, tasks, sections, milestones, ticketNotes, epics, archives, notDup, iniWf, ends, judged, autoOver, events: list };
352
+ return { boards, moves, assigns, asks, stages, iniWorkflows, tasks, sections, milestones, ticketNotes, ticketDates, epics, archives, notDup, iniWf, ends, judged, autoOver, ticketMoves, smOps, smUndone, suggestNo, events: list };
330
353
  }
331
354
 
332
355
  /** The stages an initiative runs on a board: its own workflow when one is recorded, else the board's. */
@@ -36,6 +36,14 @@
36
36
  * RENAME (testing feedback 2026-10-24, canvas RnAIni). Only the record's `title:` line changes, and its `# <title>` heading
37
37
  * when that heading is the old title. The id, the file name and every other line stay as they are, so links, the
38
38
  * placements and the gates keep reading the same record. Same refusals for the title as a new record; no record → 404.
39
+ *
40
+ * setAnchor(root, id, anchor, { actor }) → { ok: true, id, from, anchor } | { ok: false, … }
41
+ * withdrawSplit(root, id, sha, { actor }) → { ok: true, removed } | { ok: false, … }
42
+ *
43
+ * SPLIT AND MERGE (feedback batch 11 item 14). A merge can keep the closing initiative's anchor: only the `parent_kr:` line changes, to an
44
+ * anchor the OKR files or the health budgets declare (D59, the same check as a new record), and Undo sets the old one back. The Undo of a
45
+ * split takes back the record the split made, only while the file still holds exactly what the split wrote (its sha256): a record the PM
46
+ * has edited since stays, and the Undo says so.
39
47
  */
40
48
  const fs = require('fs');
41
49
  const path = require('path');
@@ -182,4 +190,58 @@ function renameInitiative(root, id, title, { actor } = {}) {
182
190
  return { ok: true, id, path: path.relative(realRoot, file).split(path.sep).join('/'), from, title: name };
183
191
  }
184
192
 
185
- module.exports = { createInitiative, renameInitiative, slugOf, ID_RE, INPUT_KEYS };
193
+ /** The record file of an initiative inside the resolved initiatives folder, or a refusal. */
194
+ function recordFile(root, id) {
195
+ if (typeof id !== 'string' || !ID_RE.test(id) || id.includes('..') || id.length > MAX_ID) return refuse(400, 'name the initiative by its id', 'id');
196
+ const loaded = consoleState.loadEngine();
197
+ if (!loaded.ok) return refuse(500, loaded.error);
198
+ let realDir, realRoot;
199
+ try { realDir = fs.realpathSync(loaded.engine.layout(root).initiatives); realRoot = fs.realpathSync(path.resolve(root)); }
200
+ catch { return refuse(404, `no initiative ${id}`, 'id'); }
201
+ if (realDir !== realRoot && !realDir.startsWith(realRoot + path.sep)) return refuse(500, 'the initiatives folder resolves outside the repository — nothing was saved');
202
+ const file = path.join(realDir, `${id}.md`);
203
+ let st;
204
+ try { st = fs.lstatSync(file); } catch { return refuse(404, `no initiative ${id}`, 'id'); }
205
+ if (!st.isFile()) return refuse(409, `the record of ${id} is not a plain file — nothing was saved`, 'id');
206
+ return { ok: true, file, realRoot };
207
+ }
208
+ const sha = (text) => require('crypto').createHash('sha256').update(text).digest('hex');
209
+ /** The sha256 of a record as it is on disk now, or null. A split keeps it, so its Undo can tell an untouched record from an edited one. */
210
+ function recordSha(root, id) {
211
+ const f = recordFile(root, id);
212
+ if (!f.ok) return null;
213
+ try { return sha(fs.readFileSync(f.file, 'utf8')); } catch { return null; }
214
+ }
215
+
216
+ function setAnchor(root, id, anchor, { actor } = {}) {
217
+ if (!actorLib.valid(actor)) return refuse(500, 'initiative-writer: the caller must pass the actor from pm-guard.js or actor.js');
218
+ const text0 = typeof anchor === 'string' ? anchor.trim() : '';
219
+ if (!text0 || !ONE_LINE(text0, 120)) return refuse(400, 'an initiative needs an anchor: a KR, or health:<id> from the health budgets (D59)', 'anchor');
220
+ if (rows.anchorsOf(root).resolve(text0).status !== 'resolved') return refuse(400, `the anchor "${text0}" is not declared in the OKR files or the health budgets (D59)`, 'anchor');
221
+ const f = recordFile(root, id);
222
+ if (!f.ok) return f;
223
+ const text = fs.readFileSync(f.file, 'utf8');
224
+ const m = /^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/.exec(text);
225
+ if (!m) return refuse(409, `the record of ${id} has no front matter — nothing was saved`, 'id');
226
+ const lines = m[1].split(/\r?\n/);
227
+ const at = lines.findIndex((l) => /^parent_kr:/.test(l));
228
+ const from = at >= 0 ? unquote(lines[at].slice(10)) : '';
229
+ if (from === text0) return { ok: true, id, from, anchor: text0, same: true };
230
+ const line = `parent_kr: ${PLAIN(text0) ? text0 : q(text0)}`;
231
+ if (at >= 0) lines[at] = line; else lines.push(line);
232
+ try { fs.writeFileSync(f.file, '---\n' + lines.join('\n') + '\n---' + m[2] + text.slice(m[0].length), { flag: 'w' }); } catch { return refuse(500, 'the record could not be written — nothing was saved'); }
233
+ return { ok: true, id, from, anchor: text0 };
234
+ }
235
+
236
+ function withdrawSplit(root, id, want, { actor } = {}) {
237
+ if (!actorLib.valid(actor)) return refuse(500, 'initiative-writer: the caller must pass the actor from pm-guard.js or actor.js');
238
+ const f = recordFile(root, id);
239
+ if (!f.ok) return f.status === 404 ? { ok: true, removed: false } : f;
240
+ let text = '';
241
+ try { text = fs.readFileSync(f.file, 'utf8'); } catch { return refuse(500, 'the record could not be read'); }
242
+ if (!want || sha(text) !== want) return { ok: true, removed: false, edited: true };
243
+ try { fs.unlinkSync(f.file); } catch { return refuse(500, 'the record could not be removed'); }
244
+ return { ok: true, removed: true };
245
+ }
246
+
247
+ module.exports = { createInitiative, renameInitiative, setAnchor, withdrawSplit, recordSha, slugOf, ID_RE, INPUT_KEYS };
@@ -37,7 +37,8 @@ const consoleState = require('./console-state');
37
37
  const actorLib = require('./actor.js');
38
38
 
39
39
  const LEDGER = 'plan-items.jsonl';
40
- const EVENTS = ['planned', 'set', 'moved', 'flagged', 'withdrawn', 'kept'];
40
+ // `restored` (batch 11 item 16) is the Undo of a Delete: it brings back a withdrawn item as it was. A delete is a withdraw with why "deleted".
41
+ const EVENTS = ['planned', 'set', 'moved', 'flagged', 'withdrawn', 'kept', 'restored'];
41
42
  const STATES = ['todo', 'doing', 'review', 'done'];
42
43
  const PM_SLUG = 'wawan';
43
44
  const ID_RE = /^(.+)\.([0-9a-z]{10})$/;
@@ -218,7 +219,8 @@ function lineErr(r) {
218
219
  if (r.blocked === true) return oneLine(r.reason, 200) ? null : 'a block reason is 1 to 200 characters';
219
220
  if (r.blocked === false) return null;
220
221
  return 'blocked is not true or false';
221
- case 'withdrawn': return null;
222
+ case 'withdrawn': return r.why === undefined || oneLine(r.why, 200) ? null : 'a why is 1 to 200 characters on one line';
223
+ case 'restored': return null;
222
224
  case 'kept':
223
225
  if (r.item !== undefined) return 'a kept line names no item';
224
226
  if (!isStr(r.batch) || !/^agent:/.test(r.batch)) return 'batch is not agent:<session>';
@@ -278,13 +280,14 @@ function historyOf(rec) {
278
280
  if (rec.ev === 'set') h.fields = { ...rec.fields };
279
281
  if (rec.ev === 'moved') { h.to = rec.to; if (rec.evidence) h.evidence = { ...rec.evidence }; if (rec.override) h.override = true; }
280
282
  if (rec.ev === 'flagged') { h.blocked = rec.blocked; if (rec.blocked) h.reason = rec.reason; }
283
+ if (rec.ev === 'withdrawn' && rec.why) h.why = rec.why;
281
284
  return h;
282
285
  }
283
286
  const touch = (it, rec) => { it.updatedBy = rec.by; it.updatedVia = rec.via; it.updatedAt = rec.at; it.history.push(historyOf(rec)); };
284
287
 
285
288
  /** A mutable fold state, so the writer can apply the events of one call to a working copy as it checks them. */
286
289
  function createState() {
287
- return { items: new Map(), withdrawn: new Set(), flags: [] };
290
+ return { items: new Map(), withdrawn: new Set(), gone: new Map(), flags: [] }; // gone: each withdrawn item as it was, for a restore
288
291
  }
289
292
  function flag(S, kind, rec, n, message) {
290
293
  S.flags.push({ kind, line: n == null ? null : n, eid: (rec && rec.eid) || null, item: (rec && rec.item) || null,
@@ -315,6 +318,16 @@ function applyLine(S, rec, n) {
315
318
  }
316
319
  return;
317
320
  }
321
+ if (rec.ev === 'restored') {
322
+ const was = S.gone.get(rec.item);
323
+ if (!S.withdrawn.has(rec.item) || !was) { flag(S, 'restore-not-withdrawn', rec, n, `restored names ${rec.item}, which is not withdrawn — it has no effect`); return; }
324
+ S.withdrawn.delete(rec.item); S.gone.delete(rec.item);
325
+ was.state = was.withdrawnFrom || 'todo';
326
+ delete was.withdrawnFrom;
327
+ S.items.set(rec.item, was);
328
+ touch(was, rec);
329
+ return;
330
+ }
318
331
  if (S.withdrawn.has(rec.item)) { flag(S, 'after-terminal', rec, n, `${rec.item} was withdrawn — a later ${rec.ev} line has no effect`); return; }
319
332
  const it = S.items.get(rec.item);
320
333
  if (!it) { flag(S, 'unknown-item', rec, n, `${rec.ev} names ${rec.item}, which was never planned — it has no effect`); return; }
@@ -346,9 +359,11 @@ function applyLine(S, rec, n) {
346
359
  it.blocked = rec.blocked ? { reason: rec.reason.trim(), by: rec.by, at: rec.at } : null;
347
360
  break;
348
361
  case 'withdrawn':
362
+ it.withdrawnFrom = it.state;
349
363
  it.state = 'withdrawn';
350
364
  S.items.delete(rec.item);
351
365
  S.withdrawn.add(rec.item);
366
+ S.gone.set(rec.item, it);
352
367
  touch(it, rec);
353
368
  return;
354
369
  default: return;
@@ -451,6 +466,8 @@ function finish(S, { now = Date.now(), dupes = 0 } = {}) {
451
466
  return {
452
467
  items, order: list.map((x) => x.id), batches, flags: S.flags.slice(), dupes,
453
468
  withdrawnCount: S.withdrawn.size, withdrawnIds: [...S.withdrawn].sort(),
469
+ // each withdrawn item as it was when it went, so a restore (and the writer's working copy) can bring it back
470
+ withdrawnItems: Object.fromEntries([...S.gone].map(([id, it]) => [id, { ...it, after: it.after.slice(), history: it.history.slice() }])),
454
471
  };
455
472
  }
456
473
 
@@ -513,7 +530,8 @@ function buildRecord(ctx, ev, index) {
513
530
  set: ['ev', 'item', 'initiative', 'fields'],
514
531
  moved: ['ev', 'item', 'initiative', 'to', 'evidence'],
515
532
  flagged: ['ev', 'item', 'initiative', 'blocked', 'reason'],
516
- withdrawn: ['ev', 'item', 'initiative'],
533
+ withdrawn: ['ev', 'item', 'initiative', 'why'],
534
+ restored: ['ev', 'item', 'initiative'],
517
535
  kept: ['ev', 'initiative', 'batch', 'items'],
518
536
  }[ev.ev];
519
537
  for (const k of Object.keys(ev)) if (!allowed.includes(k)) return refuse(400, `field ${k} is not part of a ${ev.ev} line`, index);
@@ -663,7 +681,19 @@ function buildRecord(ctx, ev, index) {
663
681
  case 'withdrawn': {
664
682
  const ex = existing(); if (ex.ok === false) return ex;
665
683
  // D98: any actor withdraws any item; the line names who did it.
666
- return { rec: common(ex.init, ex.it.id, ex.it.updatedAt) };
684
+ if (ev.why !== undefined && !oneLine(ev.why, 200)) return refuse(400, 'a why is 1 to 200 characters on one line', index);
685
+ const rec = common(ex.init, ex.it.id, ex.it.updatedAt);
686
+ if (ev.why !== undefined) rec.why = ev.why.trim();
687
+ return { rec };
688
+ }
689
+ case 'restored': {
690
+ // the Undo of a Delete (batch 11 item 16): only a withdrawn item comes back, as it was
691
+ if (!isStr(ev.item) || !ID_RE.test(ev.item)) return refuse(400, 'item must be an item id, <initiative>.<10 characters>', index);
692
+ const init = initiativeOf(ev.item);
693
+ if (ev.initiative !== undefined && ev.initiative !== init) return refuse(400, `item ${ev.item} does not belong to initiative ${ev.initiative}`, index);
694
+ const was = S.gone.get(ev.item);
695
+ if (!S.withdrawn.has(ev.item) || !was) return refuse(409, `${ev.item} is not withdrawn`, index);
696
+ return { rec: common(init, ev.item, was.updatedAt) };
667
697
  }
668
698
  case 'kept': {
669
699
  const init = ev.initiative;
@@ -715,6 +745,7 @@ function append(root, events, actor, { now, allowKept }) {
715
745
  S.items.set(id, { ...it, after: it.after.slice(), history: it.history.slice() });
716
746
  }
717
747
  for (const id of base.withdrawnIds) S.withdrawn.add(id);
748
+ for (const [id, it] of Object.entries(base.withdrawnItems || {})) S.gone.set(id, { ...it, after: it.after.slice(), history: it.history.slice() });
718
749
  /* Strictly increasing `at`. Lines written by one call (a planned then a set in the same millisecond) must
719
750
  * sort in the order they were written, and the fold sorts by (at, eid). A line dated more than a second
720
751
  * ahead of this clock is ignored for the GLOBAL floor, so one forged future date cannot drag every later write
@@ -107,7 +107,7 @@ const withChecks = (milestones, checks) => (milestones || []).map((m) => {
107
107
  /** The programs one workspace's ledger says, members carrying no workspace yet (merge adds it). `checks` holds the check lines, by milestone id. */
108
108
  function fold(lines) {
109
109
  const out = {};
110
- const get = (id) => out[id] || (out[id] = { ...blank(id), charter: false, checks: {} });
110
+ const get = (id) => out[id] || (out[id] = { ...blank(id), charter: false, checks: {}, touched: [] });
111
111
  for (const l of lines || []) {
112
112
  if (!l || typeof l !== 'object') continue;
113
113
  if (l.kind === 'program' && ID_RE.test(String(l.id || ''))) {
@@ -122,6 +122,7 @@ function fold(lines) {
122
122
  if (l.kind === 'member' || l.kind === 'leave') {
123
123
  if (!INI_RE.test(String(l.initiative || ''))) continue;
124
124
  p.members = p.members.filter((x) => x !== l.initiative);
125
+ if (!p.touched.includes(String(l.initiative))) p.touched.push(String(l.initiative));
125
126
  if (l.kind === 'member') p.members.push(String(l.initiative));
126
127
  } else if (l.kind === 'task' && l.key && l.title) {
127
128
  const t = { key: String(l.key), title: String(l.title), owner: l.owner || '', due: l.due || '', done: false };
@@ -144,18 +145,25 @@ function merge(perWs) {
144
145
  for (const { ws, lines } of perWs || []) {
145
146
  const one = fold(lines);
146
147
  for (const p of Object.values(one)) {
147
- const m = all[p.id] || (all[p.id] = { ...blank(p.id), home: '', checks: {} });
148
+ const m = all[p.id] || (all[p.id] = { ...blank(p.id), home: '', checks: {}, touched: [] });
148
149
  if (p.charter) Object.assign(m, { title: p.title, owner: p.owner, goal: p.goal, why: p.why, start: p.start, target: p.target, jira: p.jira, from: p.from, milestones: p.milestones, home: ws, at: p.at });
149
150
  Object.assign(m.checks, p.checks);
150
151
  // the route writes the order line to the charter's workspace; a line elsewhere counts only while the charter's has none
151
152
  if (p.orderSet && (p.charter || !m.orderHome)) { m.order = p.order; if (p.charter) m.orderHome = true; }
152
153
  for (const ini of p.members) if (!m.members.some((x) => x.ws === ws && x.initiative === ini)) m.members.push({ ws, initiative: ini });
153
154
  for (const t of p.tasks) m.tasks.push({ ...t, ws });
155
+ for (const ini of p.touched) m.touched.push({ ws, initiative: ini });
154
156
  if (p.archived) m.archived = true;
155
157
  }
156
158
  }
157
159
  // the check lines of every workspace apply to the charter's milestones (the route writes them to the charter's workspace)
158
- for (const m of Object.values(all)) { m.milestones = withChecks(m.milestones, m.checks); delete m.checks; delete m.orderHome; }
160
+ // a program turned from Home before batch 11 item 18 wrote its initiative's member line to the charter's workspace, not the initiative's own:
161
+ // a member or leave line for that initiative in another workspace says where it really is, so the charter's stale line is dropped (else it
162
+ // shows twice once the PM adds it again, or stays under its product)
163
+ for (const m of Object.values(all)) {
164
+ if (m.from && m.touched.some((x) => x.initiative === m.from && x.ws !== m.home)) m.members = m.members.filter((x) => !(x.ws === m.home && x.initiative === m.from));
165
+ m.milestones = withChecks(m.milestones, m.checks); delete m.checks; delete m.orderHome; delete m.touched;
166
+ }
159
167
  // a program with no charter anywhere is a member line whose program was never made: it is not shown
160
168
  return Object.values(all).filter((p) => p.home && !p.archived).sort((a, b) => String(a.title).localeCompare(String(b.title)));
161
169
  }
@@ -74,6 +74,7 @@ const MODULES = Object.freeze([
74
74
  'routes-onboarding', // onboarding-scan-and-map slice 2: first run (scan read-only, structure, import into the overlay, undo, first Briefing)
75
75
  'routes-boards', // c3-initiative-boards: Portfolio, Board, Backlog, Triage asks, workflows and moves (boards.jsonl)
76
76
  'routes-task-plans', // batch 11 item 8: drafts of an initiative's tasks, saved plans, Make live (task-plans.jsonl; page-press POST)
77
+ 'routes-task-links', // batch 11 item 15: links between tasks, Claude's proposals, the quiet moves (task-links.jsonl; page-press POST)
77
78
  'routes-workflows', // workflows-per-initiative (D99): the workflow library, save, copy, archive and the chat's draft (workflows.jsonl; page-press POST)
78
79
  'routes-settings', // console3 Settings: the settings store for settings with no home of their own (GET; page-press POST)
79
80
  'routes-hooks', // planning-flows run 7: CLI hook endpoints (session token, per-run JSONL)
@@ -17,6 +17,8 @@ const path = require('path');
17
17
  const fs = require('fs');
18
18
  const Metrics = require('./board-metrics-premium.js');
19
19
  const TaskPlans = require('./task-plans.js');
20
+ const TaskLinks = require('./task-links.js');
21
+ const Suggest = require('./split-merge-suggest.js');
20
22
  const { ENGINE_PATHS } = require('./console-state.js');
21
23
 
22
24
  /** GET `pathAndQuery` from a route module's own handler, as the Work page's route does, and return { status, body }. */
@@ -96,6 +98,26 @@ module.exports = {
96
98
  const w = ctx.getWs ? ctx.getWs(pick.ws) : null, dir = w && ctx.stateDirFor ? ctx.stateDirFor(w) : null;
97
99
  if (dir) { const F = TaskPlans.read(dir); for (const L of [model.rows, ...(model.stages || []).map((x) => x.rows), model.cancelled, model.archived]) TaskPlans.decorate(L, F); }
98
100
  } catch { missing.push('saved plans'); }
101
+ // links between tasks (batch 11 item 15): each row's links, Claude's proposals, the quiet moves and what waits on the PM (task-links.jsonl)
102
+ try {
103
+ const w = ctx.getWs ? ctx.getWs(pick.ws) : null, dir = w && ctx.stateDirFor ? ctx.stateDirFor(w) : null;
104
+ if (dir) {
105
+ const F = TaskLinks.read(dir), items = its && its.body && Array.isArray(its.body.items) ? its.body.items : [], TLR = require('./routes-task-links.js');
106
+ const src = (ini) => TLR.sourcesOf(w.root, ini, items);
107
+ for (const L of [model.rows, ...(model.stages || []).map((x) => x.rows)]) TaskLinks.decorate(L, F, items, { today: model.today || new Date().toISOString().slice(0, 10), src });
108
+ }
109
+ } catch { missing.push('task links'); }
110
+ // Claude's suggestion to split an initiative or merge two (batch 11 item 14): made from the tasks and tickets on every read, never a timer;
111
+ // the PM's ✕ Not now hides one until its tasks change. A failure here only leaves the suggestions out.
112
+ try {
113
+ const w = ctx.getWs ? ctx.getWs(pick.ws) : null;
114
+ let dismissed = null;
115
+ try { const f = w ? boards.foldOf(ctx, w) : null; dismissed = f ? f.suggestNo : null; } catch { dismissed = null; }
116
+ const items = its && its.body && Array.isArray(its.body.items) ? its.body.items : [];
117
+ const open = ((model.initiatives && model.initiatives.list && model.initiatives.list.rows) || []).filter((r) => r && r.id && r.status !== 'done' && r.status !== 'on hold');
118
+ const got = Suggest.suggest(open, items, { dismissed });
119
+ for (const L of [model.rows, model.initiatives.list.rows, ...(model.initiatives.stages || []).map((x) => x.rows)]) for (const r of L || []) if (r && r.id && got.has(r.id)) r.suggest = got.get(r.id);
120
+ } catch { /* no suggestions this read */ }
99
121
  // a press re-derives the rows in the background; while the answer is stale the page asks again (initiative premium-board-actions)
100
122
  let stale = false;
101
123
  try { const w = ctx.getWs ? ctx.getWs(pick.ws) : null; const pk = w ? Rows.peek(w.root) : null; stale = !!(pk && (pk.pending || pk.stale)); } catch { stale = false; }
@@ -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, 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;