create-pmos 0.687.0 → 0.689.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 (42) hide show
  1. package/package.json +39 -33
  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/briefing-premium-insights-test.js +23 -1
  7. package/workspace/briefing-premium-test.js +3 -0
  8. package/workspace/changelog.json +38 -19
  9. package/workspace/guide/breakdown.md +24 -1
  10. package/workspace/guide/cli.md +3 -0
  11. package/workspace/guide/intelligence-okr-goals.md +1 -1
  12. package/workspace/lib/board-premium.js +13 -3
  13. package/workspace/lib/engine/boards.js +18 -3
  14. package/workspace/lib/jira-cli.js +21 -2
  15. package/workspace/lib/jira-epics.js +125 -0
  16. package/workspace/lib/jira-status.js +18 -3
  17. package/workspace/lib/pmos-verbs.js +1 -1
  18. package/workspace/lib/route-modules.js +1 -0
  19. package/workspace/lib/routes-boards.js +109 -6
  20. package/workspace/lib/routes-jira-epics.js +65 -0
  21. package/workspace/lib/task-cli.js +25 -7
  22. package/workspace/lib/task-jira.js +107 -23
  23. package/workspace/lib/task-store.js +2 -2
  24. package/workspace/lib/tracker-cli.js +21 -2
  25. package/workspace/package-lock.json +2 -2
  26. package/workspace/package.json +1 -1
  27. package/workspace/public/pm/bd-backlog.js +25 -4
  28. package/workspace/public/pm/bd-pop-ds.css +22 -0
  29. package/workspace/public/pm/bd-pop-ds.js +48 -11
  30. package/workspace/public/pm/bd-sprint-ds.js +5 -4
  31. package/workspace/public/pm/bd-sprint.js +10 -3
  32. package/workspace/public/pm/bd-work-ds.css +4 -0
  33. package/workspace/public/pm/cozy-pop-work.css +12 -0
  34. package/workspace/public/pm/cozy-pop-work.js +172 -9
  35. package/workspace/public/pm/ini-view-model.js +12 -1
  36. package/workspace/public/pm/pop-work-model.js +40 -7
  37. package/workspace/public/pm/premium-insights.js +1 -1
  38. package/workspace/public/pm/work-select.js +73 -0
  39. package/workspace/public/pm/work-tree.js +111 -0
  40. package/workspace/skills/jira-epic.skill +35 -0
  41. package/workspace/test-files.json +2 -1
  42. package/workspace/test-lists/work-subtasks.json +11 -0
@@ -0,0 +1,125 @@
1
+ 'use strict';
2
+ /* jira-epics.js — the epic check's fix (initiative work-subtasks; board WorkJiraDS on Exploring 3, page Work). THE ONE WRITER and THE ONE FOLD of
3
+ * <state>/tracker/jira/epics.jsonl.
4
+ *
5
+ * The Work breakdown flags a Jira ticket that has no epic, or whose epic is not one of the initiative's (pm/work-tree.js epicFlag), and PMOS
6
+ * proposes to put it under the initiative's epic. On the PM's yes, each ticket becomes an ASK here. The workspace server makes no request to
7
+ * Jira (D53, D88):
8
+ * · a ticket assigned to the PM is DIRECT: an agent session with the PM's own Atlassian connection (skill jira-epic) sets its parent to the
9
+ * epic and answers with `pmos jira epic-done`. Direct Jira writes only on tickets assigned to the PM (Wawan 2026-11-22).
10
+ * · every other ticket goes to the day's DRAFT for its owner: `pmos jira epic-asks --draft` lists them by owner, for the PM to read and
11
+ * send. Nothing is sent by PMOS.
12
+ *
13
+ * THE LEDGER. One line per change, append-only:
14
+ * ask { v, kind: 'ask', id, key, ini, epic, from, who, direct, at, by } from: the epic it had ('' none); who: its assignee as read
15
+ * set { v, kind: 'set', id, at, by } the agent set the epic in Jira
16
+ * refused { v, kind: 'refused', id, why, at, by } Jira refused, or could not be reached
17
+ * withdrawn { v, kind: 'withdrawn', id, at, by } the PM's Undo, before an answer
18
+ *
19
+ * epicsFile(root) · readEpicAsks(root) → Map key → ask (the latest ask of each ticket, with state 'asked' | 'set' | 'refused' | 'withdrawn')
20
+ * isPmName(who, me) · askEpics(root, o, by) · answerEpicAsk(root, id, r, by) · withdrawEpicAsks(root, ids, by) · pendingEpicAsks(F, { direct }) · epicDraftText(F)
21
+ */
22
+ const fs = require('fs');
23
+ const path = require('path');
24
+ const crypto = require('crypto');
25
+ const jiraTickets = require('./jira-tickets.js');
26
+
27
+ const FILE = 'epics.jsonl';
28
+ const KEY_RE = /^[A-Z][A-Z0-9_]{0,30}-\d{1,9}$/;
29
+ const ID_RE = /^ep-[0-9a-f]{10}$/;
30
+ const oneLine = (s, n) => { const t = String(s == null ? '' : s).replace(/[\r\n\t]+/g, ' ').replace(/\s{2,}/g, ' ').trim(); return t.length > n ? t.slice(0, n - 1).trimEnd() + '…' : t; };
31
+
32
+ function epicsFile(root) { return path.join(jiraTickets.jiraDir(root), FILE); }
33
+ function epicLines(root) {
34
+ let txt = '';
35
+ try { txt = fs.readFileSync(epicsFile(root), 'utf8'); } catch { return []; }
36
+ const out = [];
37
+ for (const l of txt.split('\n')) { if (!l.trim()) continue; try { out.push(JSON.parse(l)); } catch { /* a torn line is skipped */ } }
38
+ return out;
39
+ }
40
+ function appendEpicLines(root, ls) {
41
+ fs.mkdirSync(path.dirname(epicsFile(root)), { recursive: true });
42
+ fs.appendFileSync(epicsFile(root), ls.map((l) => JSON.stringify(l)).join('\n') + '\n');
43
+ }
44
+
45
+ /** PURE: the latest ask of each ticket. An answer counts only for the ask it names, and only while that ask is still asked. */
46
+ function foldEpicAsks(ls) {
47
+ const by = new Map(), ids = new Map();
48
+ for (const l of ls || []) {
49
+ if (!l || typeof l !== 'object') continue;
50
+ if (l.kind === 'ask' && ID_RE.test(String(l.id || '')) && KEY_RE.test(String(l.key || '')) && KEY_RE.test(String(l.epic || ''))) {
51
+ const a = { id: l.id, key: l.key, ini: String(l.ini || ''), epic: l.epic, from: String(l.from || ''), who: oneLine(l.who, 80), direct: l.direct === true, state: 'asked', why: '', at: l.at || '', askedAt: l.at || '' };
52
+ by.set(l.key, a); ids.set(l.id, a);
53
+ } else if (['set', 'refused', 'withdrawn'].includes(l.kind) && ids.has(l.id)) {
54
+ const a = ids.get(l.id);
55
+ if (by.get(a.key) !== a || a.state !== 'asked') continue;
56
+ a.state = l.kind; a.at = l.at || a.at;
57
+ if (l.kind === 'refused') a.why = oneLine(l.why, 200) || 'Jira did not say why';
58
+ }
59
+ }
60
+ return by;
61
+ }
62
+ function readEpicAsks(root) { return foldEpicAsks(epicLines(root)); }
63
+
64
+ /** The PM's own name against a Jira assignee: the same name, or the same first name (Jira shows "Wawan Setiawan", the PM is "Wawan"). */
65
+ function isPmName(who, me) {
66
+ const w = String(who || '').trim().toLowerCase(), m = String(me || '').trim().toLowerCase();
67
+ if (!w || !m) return false;
68
+ return w === m || w.split(/\s+/)[0] === m.split(/\s+/)[0];
69
+ }
70
+
71
+ /** Ask the fix of several tickets. o: { ini, epic, tickets: [{ key, from, who }], me }. → { ok, direct: [ask], draft: [ask] } */
72
+ function askEpics(root, o, by, now = Date.now()) {
73
+ const epic = String((o && o.epic) || '').toUpperCase();
74
+ if (!KEY_RE.test(epic)) return { ok: false, status: 400, error: 'epic is a Jira key, for example IDPF-2600' };
75
+ const T = Array.isArray(o.tickets) ? o.tickets : [];
76
+ if (!T.length || T.length > 100) return { ok: false, status: 400, error: 'tickets is a list of 1 to 100 Jira tickets' };
77
+ const at = new Date(now).toISOString(), out = [], seen = new Set();
78
+ for (const t of T) {
79
+ const key = String((t && t.key) || '').toUpperCase();
80
+ if (!KEY_RE.test(key)) return { ok: false, status: 400, error: `${oneLine(t && t.key, 40) || 'a ticket'} is not a Jira key` };
81
+ if (key === epic || seen.has(key)) continue;
82
+ seen.add(key);
83
+ out.push({ v: 1, kind: 'ask', id: 'ep-' + crypto.randomBytes(5).toString('hex'), key, ini: oneLine(o.ini, 120), epic, from: oneLine(t.from, 40).toUpperCase(), who: oneLine(t.who, 80), direct: isPmName(t.who, o.me), at, by: by || 'pm' });
84
+ }
85
+ if (!out.length) return { ok: false, status: 400, error: 'no ticket to put under the epic' };
86
+ appendEpicLines(root, out);
87
+ const F = foldEpicAsks(epicLines(root));
88
+ const A = out.map((l) => F.get(l.key));
89
+ return { ok: true, direct: A.filter((a) => a.direct), draft: A.filter((a) => !a.direct), ids: out.map((l) => l.id) };
90
+ }
91
+ /** The agent's answer for one direct ask: r { set: true } or { why }. */
92
+ function answerEpicAsk(root, id, r, by, now = Date.now()) {
93
+ if (!ID_RE.test(String(id || ''))) return { ok: false, status: 400, error: 'name an epic ask id, for example ep-0a1b2c3d4e' };
94
+ const a = [...readEpicAsks(root).values()].find((x) => x.id === id);
95
+ if (!a) return { ok: false, status: 404, error: `${id} is not the latest epic ask of any ticket` };
96
+ if (a.state !== 'asked') return { ok: false, status: 409, error: `${a.key} already has an answer (${a.state})` };
97
+ const refused = r && r.why != null;
98
+ appendEpicLines(root, [refused ? { v: 1, kind: 'refused', id, why: oneLine(r.why, 200), at: new Date(now).toISOString(), by: by || 'agent' } : { v: 1, kind: 'set', id, at: new Date(now).toISOString(), by: by || 'agent' }]);
99
+ return { ok: true, ask: readEpicAsks(root).get(a.key) };
100
+ }
101
+ /** The PM's Undo: the asks not answered yet are withdrawn. → { ok, withdrawn: [key], kept: [key] (already set in Jira) } */
102
+ function withdrawEpicAsks(root, ids, by, now = Date.now()) {
103
+ const F = readEpicAsks(root), want = new Set((ids || []).filter((x) => ID_RE.test(String(x))));
104
+ const A = [...F.values()].filter((a) => want.has(a.id));
105
+ const go = A.filter((a) => a.state === 'asked');
106
+ if (go.length) appendEpicLines(root, go.map((a) => ({ v: 1, kind: 'withdrawn', id: a.id, at: new Date(now).toISOString(), by: by || 'pm' })));
107
+ return { ok: true, withdrawn: go.map((a) => a.key), kept: A.filter((a) => a.state === 'set').map((a) => a.key) };
108
+ }
109
+ /** The asks not answered yet, oldest first. o.direct: true only the direct ones, false only the draft ones. */
110
+ const pendingEpicAsks = (F, o = {}) => [...F.values()].filter((a) => a.state === 'asked' && (o.direct == null || a.direct === o.direct)).sort((a, b) => String(a.askedAt).localeCompare(String(b.askedAt)));
111
+ /** The day's draft, by owner: plain text the PM can read and send. Nothing is sent by PMOS. */
112
+ function epicDraftText(F) {
113
+ const P = pendingEpicAsks(F, { direct: false }), by = new Map();
114
+ for (const a of P) { const k = a.who || 'No assignee'; if (!by.has(k)) by.set(k, []); by.get(k).push(a); }
115
+ const out = [];
116
+ for (const [who, A] of by) {
117
+ out.push(`To ${who}:`);
118
+ out.push(`Please put ${A.length === 1 ? 'this ticket' : 'these tickets'} under the epic ${A[0].epic === A[A.length - 1].epic ? A[0].epic : 'named'}, so the epic's progress in Jira counts ${A.length === 1 ? 'it' : 'them'}:`);
119
+ for (const a of A) out.push(`- ${a.key}: ${a.from ? 'now under ' + a.from : 'no epic now'} → ${a.epic}`);
120
+ out.push('');
121
+ }
122
+ return out.join('\n').trim();
123
+ }
124
+
125
+ module.exports = { FILE, KEY_RE, ID_RE, epicsFile, readEpicAsks, foldEpicAsks, isPmName, askEpics, answerEpicAsk, withdrawEpicAsks, pendingEpicAsks, epicDraftText };
@@ -24,7 +24,7 @@
24
24
  * readSprintNotes(root) → { writtenAt, notes: [note] } | null (sprint-goal-summary)
25
25
  *
26
26
  * A READING is { key, summary, status, category: todo|doing|done, sprint: { name, state: active|future|closed, id?, start?, end?,
27
- * completed?, goal? } | null, subtasks: { done, total }, fixVersion: [names], points: number | null, resolved: YYYY-MM-DD | null,
27
+ * completed?, goal? } | null, subtasks: { done, total }, subs?: [{ key, summary, status, category }] (the sub-task list, when the search returned it), fixVersion: [names], points: number | null, resolved: YYYY-MM-DD | null,
28
28
  * flagged, reason, url }. The sprint's dates, `points` and `resolved` feed the sprint burndown (lib/stage-tools.js); a
29
29
  * reading saved before they were carried has none of them, and the burndown says it cannot be drawn. A ticket the search did not return keeps its last reading, marked
30
30
  * stale. Titles and statuses only: never a description or a comment. The one person a reading carries is the assignee's display name, with
@@ -198,6 +198,21 @@ function subtasksOf(v) {
198
198
  }
199
199
  return { done: 0, total: 0 };
200
200
  }
201
+ /** The sub-task list itself (initiative work-subtasks: Jira sub-tasks show under their ticket): { subs: [{ key, summary, status, category }] }
202
+ * when the search returned the sub-tasks with keys, {} otherwise (a count alone keeps only `subtasks`). At most 30. */
203
+ function subsOf(v) {
204
+ if (!Array.isArray(v)) return {};
205
+ const out = [];
206
+ for (const s of v) {
207
+ const key = oneLine(s && s.key).toUpperCase();
208
+ if (!KEY_RE.test(key)) continue;
209
+ const f = (s.fields && typeof s.fields === 'object') ? s.fields : s, st = f.status;
210
+ const status = nameOf(st) || 'Unknown';
211
+ out.push({ key, summary: clip(oneLine(f.summary || f.title || key), 160), status, category: categoryOf(status, st && typeof st === 'object' ? st.statusCategory : f.category) });
212
+ if (out.length >= 30) break;
213
+ }
214
+ return out.length ? { subs: out } : {};
215
+ }
201
216
  /** https://site.atlassian.net/rest/api/3/issue/10001 → https://site.atlassian.net/browse/KEY */
202
217
  function urlOf(x, key) {
203
218
  const raw = isStr(x.url) ? x.url : isStr(x.self) ? x.self : '';
@@ -237,7 +252,7 @@ function normalizeIssue(x) {
237
252
  const st = f.status || {};
238
253
  const status = nameOf(st) || 'Unknown';
239
254
  const flagged = flaggedIn(f) || /block|impediment|on hold/i.test(status);
240
- return { key, summary, status, category: categoryOf(status, st.statusCategory), sprint: sprintIn(f), ...sprintsAll(sprintField(f)), subtasks: subtasksOf(f.subtasks), fixVersion: fixVersionsOf(f.fixVersions),
255
+ return { key, summary, status, category: categoryOf(status, st.statusCategory), sprint: sprintIn(f), ...sprintsAll(sprintField(f)), subtasks: subtasksOf(f.subtasks), ...subsOf(f.subtasks), fixVersion: fixVersionsOf(f.fixVersions),
241
256
  points: pointsIn(f), resolved: dayOf(f.resolutiondate || f.resolved),
242
257
  flagged, reason: flagged ? (flaggedIn(f) ? 'Flagged in Jira' : `Status: ${status}`) : null, url: urlOf(x, key),
243
258
  ...typeParent(f.issuetype, f.parent), ...whoWhen(f.assignee, f.updated) };
@@ -247,7 +262,7 @@ function normalizeIssue(x) {
247
262
  if (!summary) return null;
248
263
  const status = oneLine(x.status) || 'Unknown';
249
264
  const flagged = x.flagged === true || /block|impediment|on hold/i.test(status);
250
- return { key, summary, status, category: categoryOf(status, x.category), sprint: sprintOf(x.sprint), ...sprintsAll(x.sprints != null ? x.sprints : x.sprint), subtasks: subtasksOf(x.subtasks), fixVersion: fixVersionsOf(x.fixVersions != null ? x.fixVersions : x.fixVersion),
265
+ return { key, summary, status, category: categoryOf(status, x.category), sprint: sprintOf(x.sprint), ...sprintsAll(x.sprints != null ? x.sprints : x.sprint), subtasks: subtasksOf(x.subtasks), ...subsOf(x.subtasks), fixVersion: fixVersionsOf(x.fixVersions != null ? x.fixVersions : x.fixVersion),
251
266
  points: pointsIn(x), resolved: dayOf(x.resolved || x.resolutiondate),
252
267
  flagged, reason: flagged ? clip(oneLine(x.reason || x.flag_reason || (x.flagged === true ? 'Flagged in Jira' : `Status: ${status}`)), 160) : null,
253
268
  url: urlOf(x, key), ...typeParent(x.type != null ? x.type : x.issuetype, x.parent), ...whoWhen(x.assignee, x.updated) };
@@ -62,7 +62,7 @@ const VERBS = Object.freeze({
62
62
  help: 'pmos launch check|list — what is not ready before a launch date: tasks, tracker tickets, sign-offs, open questions (pmos launch help)' }),
63
63
  // Not a pm-os-absorb verb (run: null): tracker-read-freshness added it through the same table.
64
64
  tracker: Object.freeze({ module: 'tracker-cli.js', run: null, guide: 'cli.md',
65
- help: 'pmos tracker done|status — record when the tracker-refresh skill finished a read of this repository (pmos tracker help)' }),
65
+ help: 'pmos tracker done|status|sync — when tracker items were last read, and how much of this repository matches the last Jira read (pmos tracker help)' }),
66
66
  // Not a pm-os-absorb verb (run: null): briefing-source-flow added it through the same table.
67
67
  source: Object.freeze({ module: 'source-cli.js', run: null, guide: 'cli.md',
68
68
  help: 'pmos source save|status|show — the stored read of each tool the Briefing uses: Mail, Slack, Confluence and the rest (pmos source help)' }),
@@ -135,6 +135,7 @@ const MODULES = Object.freeze([
135
135
  'routes-drift', // weekly-drift-check: What would I have missed, Home's weekly ✦ and its ⋯ drop and Undo (runtime drift/drift.jsonl; page-press POST)
136
136
  'routes-moments', // onboarding B3 gradual exposure: the day's ✦ in Home's chat, the menu dots, a quiet place's one line (onboarding-progress record; page-press POST)
137
137
  'routes-spec-critic', // spec-critic: the sceptical reviewer's hardest questions on a document before it is shared (runtime spec-critic.jsonl)
138
+ 'routes-jira-epics', // work-subtasks: the epic check's fix, direct on tickets assigned to the PM, the day's draft for the rest (tracker/jira/epics.jsonl; page-press POST)
138
139
  ]);
139
140
  const PM_DIR = path.join(__dirname, '..', 'public', 'pm');
140
141
  const MODULE_NAME = /^[a-z0-9][a-z0-9-]*\.js$/;
@@ -26,7 +26,7 @@
26
26
  * POST /api/boards/settings { ws, board, buildDeliver?, jira?, offer?, defTpl? } → { ok, board } jira: one key or a list
27
27
  * POST /api/boards/ini-workflow { ws, board, id, template?, stages, moveTo? } → { ok, row, moved }
28
28
  * POST /api/boards/ini-epics { ws, board, id, epics: [Jira key] } → { ok, row } the Jira epics of an initiative ([] unlinks)
29
- * POST /api/boards/tasks/add { ws, board, initiative, title, type?, epic?, start?, due?, owner?, notes?, section?, milestone? } → { ok, item } also `pmos task add`
29
+ * POST /api/boards/tasks/add { ws, board, initiative, title, type?, epic?, start?, due?, owner?, notes?, section?, milestone?, parent? } → { ok, item } also `pmos task add`
30
30
  * (milestone: true adds it as a milestone, ◇ with one date: the due day, no start; batch 25 item 5)
31
31
  * (section: the stage it goes under, as tasks/edit's section: the + on a stage of the Tasks list, batch 18 item 16)
32
32
  * POST /api/boards/tasks/order { ws, board, initiative, section, tasks: [id] } → { ok, from } the PM's order inside one stage (a drag in the
@@ -36,8 +36,12 @@
36
36
  * the popup's direct ✓ presses (bet 1f): see "direct ✓ presses" below; { ask: true } sends the words to Ask PMOS
37
37
  * POST /api/boards/tasks/reschedule { ws, board, task, days } → { ok, item }
38
38
  * POST /api/boards/tasks/undo-add { ws, board, task } → { ok } takes back a task added in the last 2 minutes, still To do
39
+ * POST /api/boards/tasks/bulk { ws, board, tasks: [id], op: parent|section|owner|shift|done, value } → { ok, moved, skipped, undo } several tasks
40
+ * at once (initiative work-subtasks, WorkBulkDS), each through the single route; a Jira ticket keeps its stage, assignee and status
41
+ * POST /api/boards/tasks/bulk-undo { ws, board, undo } → { ok, back, failed } the one Undo of a bulk move
39
42
  * POST /api/boards/tasks/rename { ws, board, task, title } → { ok, from, item } only the title changes
40
- * POST /api/boards/tasks/edit { ws, board, task, owner?, notes?, start?, due?, initiative?, section?, milestone?, pinned? } → { ok, from, item } the Viewer's edits in place
43
+ * POST /api/boards/tasks/edit { ws, board, task, owner?, notes?, start?, due?, initiative?, section?, milestone?, pinned?, parent? } → { ok, from, item } the Viewer's edits in place
44
+ * (parent: the task it sits under, '' for the top level; a task-parent line, any kind of task, a loop refused)
41
45
  * (milestone: true | false, the ◇ flag of batch 11 item 3; a Jira key takes the flag only)
42
46
  * (pinned: true | false | null, a milestone's pin on the Board timeline, batch 13 item 4; null = the rule, the last one only)
43
47
  * (section: the task's place in the breakdown, a stage key of its initiative's workflow or '' — a task-section line)
@@ -855,6 +859,9 @@ function itemsOf(w, fr, board, rows) {
855
859
  if (hit) x.rank = hit.ids.indexOf(x.uid);
856
860
  }
857
861
  }
862
+ // a subtask's parent (initiative work-subtasks): any kind of task, the last task-parent line wins
863
+ const PA = fr.folded.parents || new Map();
864
+ if (PA.size) for (const x of out) if (x.kind !== 'Epic' && PA.has(x.uid)) x.parent = PA.get(x.uid);
858
865
  // a task flagged as a milestone (feedback batch 11 item 3): the PM's flag on the board ledger, else a breakdown item's own plan-items flag
859
866
  const MS = fr.folded.milestones || new Map();
860
867
  for (const x of out) if (x.kind !== 'Epic') { const on = MS.has(x.uid) ? MS.get(x.uid) : !!x.milestone; if (on) x.milestone = true; else delete x.milestone; }
@@ -875,7 +882,10 @@ function trackerMarks(w, items) {
875
882
  if (!key) continue;
876
883
  if (!snaps.has(x.ini)) { let sn = null; try { sn = jiraStatus.readSnapshot(w.root, x.ini); } catch { sn = null; } snaps.set(x.ini, sn); }
877
884
  const sn = snaps.get(x.ini), rd = sn && sn.tickets ? sn.tickets.get(key) : null;
878
- x.tracker = { key, status: (rd && rd.status) || null, readAt: (sn && sn.fetchedAt) || null, stale: TJ.staleOf([key], sn, now).stale };
885
+ x.tracker = { key, status: (rd && rd.status) || null, readAt: (sn && sn.fetchedAt) || null, stale: TJ.staleOf([key], sn, now).stale,
886
+ // the epic check and the sub-tasks (initiative work-subtasks): the read's parent (its epic, or its ticket for a sub-task), assignee, link
887
+ ...(rd ? { read: true, url: rd.url || '', type: rd.type || '', assignee: rd.assignee || '', ...(/sub-?task/i.test(String(rd.type || '')) ? { parentTicket: rd.parent || '' } : { epic: rd.parent || '', parentName: rd.parentName || '' }),
888
+ ...(Array.isArray(rd.subs) && rd.subs.length ? { subs: rd.subs } : {}) } : {}) };
879
889
  }
880
890
  }
881
891
  /** The Jira items of an initiative PMOS pushed nothing for: its linked epics and the issues under them, from the last
@@ -1188,6 +1198,20 @@ function itemOnBoard(ctx, res, p, id) {
1188
1198
  if (!b0 || boardIdOf(b0, p.fr.boards, p.fr.folded, p.w) !== p.board.id) { fail(ctx, res, 404, `no PMOS task ${id} on this board`); return null; }
1189
1199
  return it;
1190
1200
  }
1201
+ /** A subtask's parent (initiative work-subtasks): '' for the top level, else a PMOS task, a breakdown item or a Jira key of the same
1202
+ * initiative (a Jira key is taken as it is: PMOS reads its initiative from Jira). → the error to answer, or null when it may be written. */
1203
+ function parentError(p, taskId, parent, iniId) {
1204
+ if (typeof parent !== 'string' || parent.length > 80) return 'parent is the id of a task of the same initiative, or \'\' for the top level';
1205
+ if (!parent) return null;
1206
+ if (parent === taskId) return 'a task cannot be its own parent';
1207
+ if (B.wouldCycle(p.fr.folded.parents || new Map(), taskId, parent)) return 'that parent sits under this task: it would make a loop';
1208
+ if (B.JIRA_KEY_RE.test(parent) && !B.taskOf(p.fr.folded, parent)) return null;
1209
+ const pt = B.taskOf(p.fr.folded, parent) || (TI.isItemId(parent) ? TI.itemOf(p.w.root, parent) : null);
1210
+ if (!pt) return `no task ${parent} to put it under`;
1211
+ if (iniId && pt.initiative && pt.initiative !== iniId) return 'the parent is a task of another initiative';
1212
+ return null;
1213
+ }
1214
+ const parentLine = (p, task, parent) => ({ kind: 'task-parent', board: p.board.id, task, parent, why: parent ? 'put under ' + parent : 'moved to the top level' });
1191
1215
  /** Writes an item's lines (r: TI.stateEvents or TI.editEvents) as the task routes do and answers the item as a task. */
1192
1216
  function itemWrite(ctx, res, p, it, r, g, extra = {}) {
1193
1217
  if (r.error) return fail(ctx, res, 400, r.error);
@@ -1200,6 +1224,8 @@ function itemWrite(ctx, res, p, it, r, g, extra = {}) {
1200
1224
  ctx.json(res, { ok: true, item: B.rollupItems([row])[0], ...extra });
1201
1225
  }
1202
1226
 
1227
+ /** What a bulk move does (POST /api/boards/tasks/bulk): under a parent, to a stage, to a person, by N days, to Done. */
1228
+ const BULK_OPS = ['parent', 'section', 'owner', 'shift', 'done'];
1203
1229
  const WRITES = {
1204
1230
  '/api/boards/create': (ctx, res, body, g) => {
1205
1231
  const p = postFrame(ctx, res, body, { needBoard: false });
@@ -1498,12 +1524,14 @@ const WRITES = {
1498
1524
  if (body.section && !st.some((x) => x.key === body.section)) return fail(ctx, res, 400, `"${body.section}" is not a stage of this initiative's workflow: one of ${st.map((x) => x.key).join(', ')}, or ''`);
1499
1525
  }
1500
1526
  const id = `task-${crypto.randomBytes(5).toString('hex')}`;
1527
+ // "under Batch 2: …" in the add box (initiative work-subtasks): the new task is a subtask from its first line
1528
+ if (body.parent != null && body.parent !== '') { const pe = parentError(p, id, body.parent, body.initiative); if (pe) return fail(ctx, res, 400, pe); }
1501
1529
  // a milestone has one date, the due day, and no start (the ◇ of the Viewer's add field, batch 25 item 5)
1502
1530
  const ms = body.milestone === true;
1503
1531
  const start = ms ? '' : body.start || (body.due && body.due < B.shiftDay(today(), 1) ? body.due : B.shiftDay(today(), 1));
1504
1532
  const due = body.due || (ms ? body.start || B.shiftDay(today(), 8) : B.shiftDay(start, 7));
1505
1533
  append(p.file, g.actor, { kind: 'task', board: p.board.id, task: id, type: body.type || 'Task', initiative: body.initiative, title: body.title.trim(), epic: body.epic ? String(body.epic).trim() : null,
1506
- owner: body.owner ? String(body.owner).trim() : actorLib.pageName(g.actor.by), state: 'To do', start, due, ...(body.notes && body.notes.trim() ? { notes: body.notes.replace(/\s+$/, '') } : {}) });
1534
+ owner: body.owner ? String(body.owner).trim() : actorLib.pageName(g.actor.by), state: 'To do', start, due, ...(body.notes && body.notes.trim() ? { notes: body.notes.replace(/\s+$/, '') } : {}), ...(body.parent ? { parent: body.parent } : {}) });
1507
1535
  if (typeof body.section === 'string') append(p.file, g.actor, { kind: 'task-section', board: p.board.id, task: id, section: body.section, why: body.section ? 'placed under ' + body.section : 'placed under no stage' });
1508
1536
  if (ms) append(p.file, g.actor, { kind: 'task-milestone', board: p.board.id, task: id, milestone: true, why: 'added as a milestone' });
1509
1537
  const t = B.taskOf(B.fold(readLedger(ctx, p.w)), id);
@@ -1629,7 +1657,8 @@ const WRITES = {
1629
1657
  // Jira keeps its title, status and assignee, and nothing is written to Jira
1630
1658
  if (typeof body.task === 'string' && B.JIRA_KEY_RE.test(body.task) && !B.taskOf(p.fr.folded, body.task)) {
1631
1659
  if (['owner', 'notes', 'initiative', 'section'].some((k) => body[k] != null)) return fail(ctx, res, 409, 'Jira owns this ticket: only its dates, its milestone flag and its pin change here');
1632
- if (body.milestone == null && body.start == null && body.due == null && body.pinned === undefined) return fail(ctx, res, 400, 'nothing to change: send start, due, milestone or pinned');
1660
+ if (body.milestone == null && body.start == null && body.due == null && body.pinned === undefined && body.parent == null) return fail(ctx, res, 400, 'nothing to change: send start, due, milestone, pinned or parent');
1661
+ if (body.parent != null) { const pe = parentError(p, body.task, body.parent, null); if (pe) return fail(ctx, res, 400, pe); }
1633
1662
  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`);
1634
1663
  if (!p.file) return fail(ctx, res, 409, NO_STATE);
1635
1664
  const from = {}, ref = body.task.toUpperCase();
@@ -1647,6 +1676,7 @@ const WRITES = {
1647
1676
  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' });
1648
1677
  }
1649
1678
  if (body.pinned !== undefined) { from.pinned = pinWas(body.task); append(p.file, g.actor, pinLine(body.task)); }
1679
+ if (body.parent != null) { from.parent = (p.fr.folded.parents || new Map()).get(body.task) || ''; append(p.file, g.actor, parentLine(p, body.task, body.parent)); }
1650
1680
  return ctx.json(res, { ok: true, from, item: null });
1651
1681
  }
1652
1682
  const t0 = B.taskOf(p.fr.folded, body.task);
@@ -1699,10 +1729,19 @@ const WRITES = {
1699
1729
  // the pin (batch 13 item 4): a board-ledger line like the milestone flag
1700
1730
  const pin = body.pinned !== undefined;
1701
1731
  if (pin) { if (!p.file) return fail(ctx, res, 409, NO_STATE); from.pinned = pinWas(t.id); }
1702
- if (!Object.keys(ev).length && sec == null && ms == null && !pin) return fail(ctx, res, 400, 'nothing to change: send owner, notes, start, due, initiative, section, milestone or pinned');
1732
+ // a subtask's parent (initiative work-subtasks): a board-ledger line for every kind of task, like the section
1733
+ let par = null;
1734
+ if (body.parent != null) {
1735
+ const pe = parentError(p, t.id, body.parent, ev.initiative || t.initiative);
1736
+ if (pe) return fail(ctx, res, 400, pe);
1737
+ if (!p.file) return fail(ctx, res, 409, NO_STATE);
1738
+ par = body.parent; from.parent = (p.fr.folded.parents || new Map()).get(t.id) || '';
1739
+ }
1740
+ if (!Object.keys(ev).length && sec == null && ms == null && !pin && par == null) return fail(ctx, res, 400, 'nothing to change: send owner, notes, start, due, initiative, section, milestone, pinned or parent');
1703
1741
  if (sec != null) append(p.file, g.actor, { kind: 'task-section', board: p.board.id, task: t.id, section: sec, why: sec ? 'placed under ' + sec : 'placed under no stage' });
1704
1742
  if (ms != null) append(p.file, g.actor, { kind: 'task-milestone', board: p.board.id, task: t.id, milestone: ms, why: ms ? 'made a milestone' : 'no longer a milestone' });
1705
1743
  if (pin) append(p.file, g.actor, pinLine(t.id));
1744
+ if (par != null) append(p.file, g.actor, parentLine(p, t.id, par));
1706
1745
  if (!Object.keys(ev).length) {
1707
1746
  const items = itemsOf(p.w, { ...p.fr, folded: B.fold(readLedger(ctx, p.w)) }, p.board, (needRows(ctx, res, p.w) || []).filter((r) => r.id === t.initiative));
1708
1747
  return ctx.json(res, { ok: true, from, item: items.find((x) => x.uid === t.id) || null });
@@ -1713,6 +1752,70 @@ const WRITES = {
1713
1752
  const t2 = B.taskOf(B.fold(readLedger(ctx, p.w)), t.id);
1714
1753
  ctx.json(res, { ok: true, from, item: B.rollupItems([B.taskItem(t2)])[0] });
1715
1754
  },
1755
+ '/api/boards/tasks/bulk': (ctx, res, body, g) => {
1756
+ // bulk move (initiative work-subtasks, board WorkBulkDS): several tasks under a parent, to a stage, to a person, by N days, or to Done.
1757
+ // Each task goes through the same route a single press uses; the answer's `undo` puts every one back in one press (tasks/bulk-undo)
1758
+ const p = postFrame(ctx, res, body);
1759
+ if (!p) return;
1760
+ const ids = Array.isArray(body.tasks) ? [...new Set(body.tasks.filter((x) => typeof x === 'string' && x && x.length <= 80))] : [];
1761
+ if (!ids.length || ids.length > 200) return fail(ctx, res, 400, 'tasks is a list of 1 to 200 task ids');
1762
+ const op = body.op, v = body.value;
1763
+ if (!BULK_OPS.includes(op)) return fail(ctx, res, 400, `op is one of ${BULK_OPS.join(', ')}`);
1764
+ if (op === 'shift' && (!Number.isInteger(Number(v)) || Number(v) === 0 || Math.abs(Number(v)) > 730)) return fail(ctx, res, 400, 'value is a whole number of days, not 0, at most 730 either way');
1765
+ if ((op === 'parent' || op === 'section' || op === 'owner') && typeof v !== 'string') return fail(ctx, res, 400, `value is the ${op === 'parent' ? 'parent task id' : op === 'section' ? 'stage key' : 'owner'}, or '' for none`);
1766
+ if (op === 'parent' && v && ids.includes(v)) return fail(ctx, res, 400, 'the parent is one of the selected tasks');
1767
+ const base = { ws: body.ws, board: body.board };
1768
+ const moved = [], skipped = [];
1769
+ for (const id of ids) {
1770
+ const jira = B.JIRA_KEY_RE.test(id) && !B.taskOf(p.fr.folded, id);
1771
+ if (jira && (op === 'section' || op === 'owner' || op === 'done')) { skipped.push({ task: id, why: 'Jira owns its ' + (op === 'section' ? 'stage' : op === 'owner' ? 'assignee' : 'status') }); continue; }
1772
+ let r, undo;
1773
+ if (op === 'done') {
1774
+ const t = B.taskOf(p.fr.folded, id) || (TI.isItemId(id) ? (() => { const it = TI.itemOf(p.w.root, id); return it ? { state: TI.STATE_OF[it.state] || 'To do' } : null; })() : null);
1775
+ if (t && t.state === 'Done') { skipped.push({ task: id, why: 'already done' }); continue; }
1776
+ r = writeAs(ctx, '/api/boards/tasks/state', { ...base, task: id, state: 'Done', why: 'marked done with ' + (ids.length - 1) + ' more' }, g);
1777
+ undo = { task: id, op, from: { state: (t && t.state) || 'To do' } };
1778
+ } else if (op === 'shift') {
1779
+ if (jira) {
1780
+ const TD = p.fr.folded.ticketDates || new Map(), was = TD.get(p.board.id + '\u0000' + id.toUpperCase());
1781
+ if (!was || (!was.start && !was.due)) { skipped.push({ task: id, why: 'Jira keeps its dates: give it dates in PMOS first' }); continue; }
1782
+ r = writeAs(ctx, '/api/boards/tasks/edit', { ...base, task: id, ...(was.start ? { start: B.shiftDay(was.start, Number(v)) } : {}), ...(was.due ? { due: B.shiftDay(was.due, Number(v)) } : {}) }, g);
1783
+ undo = { task: id, op: 'edit', from: r.body && r.body.from };
1784
+ } else {
1785
+ r = writeAs(ctx, '/api/boards/tasks/reschedule', { ...base, task: id, days: Number(v) }, g);
1786
+ undo = { task: id, op, from: { days: Number(v) } };
1787
+ }
1788
+ } else {
1789
+ r = writeAs(ctx, '/api/boards/tasks/edit', { ...base, task: id, [op]: v }, g);
1790
+ undo = { task: id, op: 'edit', from: r.body && r.body.from };
1791
+ }
1792
+ if (r.body && r.body.ok !== false) moved.push(undo); else skipped.push({ task: id, why: (r.body && r.body.error) || 'not changed' });
1793
+ }
1794
+ if (!moved.length) return fail(ctx, res, 400, 'no task was moved: ' + skipped.map((x) => x.task + ' (' + x.why + ')').join(', '), { skipped });
1795
+ ctx.json(res, { ok: true, moved: moved.map((x) => x.task), skipped, undo: moved, said: moved.length + (moved.length === 1 ? ' task' : ' tasks') + ' moved.' + (skipped.length ? ' Not moved: ' + skipped.length + '.' : '') });
1796
+ },
1797
+ '/api/boards/tasks/bulk-undo': (ctx, res, body, g) => {
1798
+ // the one Undo of a bulk move: each task back as it was, the last one first
1799
+ const p = postFrame(ctx, res, body);
1800
+ if (!p) return;
1801
+ const list = Array.isArray(body.undo) ? body.undo.filter((x) => x && typeof x.task === 'string' && x.from && typeof x.from === 'object') : [];
1802
+ if (!list.length || list.length > 200) return fail(ctx, res, 400, 'undo is the list a bulk move answered');
1803
+ const base = { ws: body.ws, board: body.board }, back = [], failed = [];
1804
+ for (const x of list.slice().reverse()) {
1805
+ let r;
1806
+ if (x.op === 'done') r = writeAs(ctx, '/api/boards/tasks/state', { ...base, task: x.task, state: String(x.from.state || 'To do'), why: 'undo of a bulk move' }, g);
1807
+ else if (x.op === 'shift') r = writeAs(ctx, '/api/boards/tasks/reschedule', { ...base, task: x.task, days: -Number(x.from.days) }, g);
1808
+ else {
1809
+ const from = {};
1810
+ for (const k of ['owner', 'notes', 'start', 'due', 'initiative', 'section', 'parent']) if (typeof x.from[k] === 'string') from[k] = x.from[k];
1811
+ if (typeof x.from.milestone === 'boolean') from.milestone = x.from.milestone;
1812
+ if (!Object.keys(from).length) continue;
1813
+ r = writeAs(ctx, '/api/boards/tasks/edit', { ...base, task: x.task, ...from }, g);
1814
+ }
1815
+ if (r.body && r.body.ok !== false) back.push(x.task); else failed.push(x.task);
1816
+ }
1817
+ ctx.json(res, { ok: !failed.length || back.length > 0, back, failed, said: back.length + (back.length === 1 ? ' task' : ' tasks') + ' back as they were.' });
1818
+ },
1716
1819
  '/api/boards/tickets/note': (ctx, res, body, g) => {
1717
1820
  // the PM's own notes on a Jira ticket (canvas XetX1Jira): Jira keeps the title, status, dates and assignee
1718
1821
  const p = postFrame(ctx, res, body);
@@ -0,0 +1,65 @@
1
+ 'use strict';
2
+ /* routes-jira-epics.js — the epic check's fix (initiative work-subtasks; board WorkJiraDS). lib/jira-epics.js is the store.
3
+ *
4
+ * GET /api/jira-epics?ws → { ok, asks, draft } the asks not answered yet, and the day's draft text by owner
5
+ * POST /api/jira-epics/fix { ws, ini, epic, tickets: [{ key, from, who }] } → { ok, direct: [key], draft: [{ key, who }], ids, session? }
6
+ * POST /api/jira-epics/undo { ws, ids } → { ok, withdrawn, kept } the ✦'s Undo: asks not answered yet are withdrawn
7
+ *
8
+ * A ticket assigned to the PM is direct: a jira-epic session with the PM's own Atlassian connection sets its epic and answers with
9
+ * `pmos jira epic-done`. Every other ticket waits in the day's draft for its owner, which the PM reads first. This route makes no request to
10
+ * Jira (D53). Every POST passes pm-guard requirePagePress: the page only. */
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+ const guard = require('./pm-guard.js');
14
+ const JE = require('./jira-epics.js');
15
+
16
+ const pmNameOf = () => { try { return require('./routes-board-publish.js').sharedBy() || process.env.PMOS_PM_NAME || ''; } catch { return process.env.PMOS_PM_NAME || ''; } };
17
+ const SKILL = path.join(__dirname, '..', 'skills', 'jira-epic.skill');
18
+ /** The skill's body: the prompt the session starts with. */
19
+ function promptOf() {
20
+ let t = '';
21
+ try { t = fs.readFileSync(SKILL, 'utf8'); } catch { return null; }
22
+ const m = /^---\n[\s\S]*?\n---\n([\s\S]*)$/.exec(t);
23
+ return (m ? m[1] : t).trim() || null;
24
+ }
25
+ const running = new Map(); // ws id → session id
26
+
27
+ module.exports = {
28
+ prefixes: ['/api/jira-epics'],
29
+ handle: async (req, res, url, ctx) => {
30
+ const p = url.pathname;
31
+ if (p === '/api/jira-epics' && req.method === 'GET') {
32
+ const w = ctx.getWs(url.searchParams.get('ws'));
33
+ if (!w) { ctx.json(res, { ok: false, error: 'no such workspace' }, 404); return true; }
34
+ const F = JE.readEpicAsks(w.root);
35
+ ctx.json(res, { ok: true, asks: JE.pendingEpicAsks(F), draft: JE.epicDraftText(F) });
36
+ return true;
37
+ }
38
+ if (req.method !== 'POST' || (p !== '/api/jira-epics/fix' && p !== '/api/jira-epics/undo')) return false;
39
+ const got = await ctx.readJson(req);
40
+ if (!got.ok) { ctx.json(res, { ok: false, error: 'invalid JSON body' }, 400); return true; }
41
+ const body = got.body || {};
42
+ const g = guard.requirePagePress(req, body);
43
+ if (!g.ok) { ctx.json(res, { ok: false, error: g.error }, g.status); return true; }
44
+ const w = ctx.getWs(typeof body.ws === 'string' && body.ws ? body.ws : null);
45
+ if (!w || (body.ws && w.id !== body.ws)) { ctx.json(res, { ok: false, error: 'no such workspace' }, 404); return true; }
46
+ const by = (g.actor && g.actor.by) || 'pm';
47
+ if (p === '/api/jira-epics/undo') { ctx.json(res, JE.withdrawEpicAsks(w.root, Array.isArray(body.ids) ? body.ids : [], by)); return true; }
48
+ const r = JE.askEpics(w.root, { ini: body.ini, epic: body.epic, tickets: body.tickets, me: pmNameOf() }, by);
49
+ if (!r.ok) { ctx.json(res, r, r.status || 400); return true; }
50
+ const out = { ok: true, direct: r.direct.map((a) => a.key), draft: r.draft.map((a) => ({ key: a.key, who: a.who })), ids: r.ids };
51
+ // the direct ones: one jira-epic session per workspace sets them in Jira with the PM's own connection
52
+ if (r.direct.length && typeof ctx.spawnSession === 'function') {
53
+ const prompt = promptOf(), was = running.get(w.id), live = was && typeof ctx.sessionList === 'function' && (ctx.sessionList() || []).some((s) => s && s.id === was && s.state !== 'exited');
54
+ if (prompt && !live) {
55
+ try {
56
+ const s = ctx.spawnSession({ name: 'Set epics in Jira', agent: 'claude', ws: w.id, origin: 'jira:epic', initialInput: prompt + `\n\nThis run: the asks \`pmos jira epic-asks --direct\` lists (the first: ${r.direct[0].key} under ${r.direct[0].epic}).\r` });
57
+ if (s && s.state !== 'exited') { running.set(w.id, s.id); out.session = s.id; }
58
+ else for (const a of r.direct) JE.answerEpicAsk(w.root, a.id, { why: (s && s.note) || 'the agent could not start' }, 'pmos');
59
+ } catch (e) { for (const a of r.direct) JE.answerEpicAsk(w.root, a.id, { why: 'the agent could not start' }, 'pmos'); }
60
+ } else if (live) out.session = was;
61
+ }
62
+ ctx.json(res, out);
63
+ return true;
64
+ },
65
+ };
@@ -39,12 +39,14 @@ const USAGE = [
39
39
  ' pmos task add <initiative> "<title>" [--stage <stage>] [--due YYYY-MM-DD] [--start YYYY-MM-DD] [--owner <who>] [--notes <text>]',
40
40
  ' Add a task. Every new task goes here; pmos item add is the older breakdown record.',
41
41
  ' pmos task set <task> [<task> …] [--stage <stage>|none] [--due YYYY-MM-DD|none] [--start YYYY-MM-DD|none] [--owner <who>] [--notes <text>]',
42
- ' [--milestone|--no-milestone] [--pin|--no-pin|--pin-default]',
42
+ ' [--milestone|--no-milestone] [--pin|--no-pin|--pin-default] [--parent <task>|none]',
43
+ ' --parent puts the task under another task of the same initiative as a subtask; none takes it back to the top level. Set it only when the PM asks.',
43
44
  ' Group tasks under a stage of the initiative\'s workflow (key or name; none takes it out), or change dates, owner or notes.',
44
45
  ' --milestone makes a task a milestone: its due date shows as ◇ on the Board and the timeline. Set it only when the PM asks.',
45
46
  ' --pin shows a milestone on the Board timeline, --no-pin hides it, --pin-default goes back to the rule (the last milestone',
46
47
  ' shows). Set it only when the PM asks.',
47
- ' pmos task list <initiative> [--all] its open tasks, with the start and due day the Board shows; --all adds Done, Won\'t do and Archived',
48
+ ' pmos task list <initiative> [--all] its open tasks, with the start and due day the Board shows; --all adds Done, Won\'t do and Archived.',
49
+ ' A subtask prints under its parent, indented.',
48
50
  ' pmos task remove <task> [<task> …] [--why <text>]',
49
51
  ' Delete a task added by mistake (a placeholder, a duplicate) when the PM asks. It goes from every list; the page\'s Undo brings',
50
52
  ' it back. Work that stopped is Archived or Won\'t do instead. A breakdown item is not deleted: set it to Won\'t do.',
@@ -63,7 +65,7 @@ const USAGE = [
63
65
  ];
64
66
  const BOOL = new Set(['json', 'help', 'all', 'milestone', 'no-milestone', 'pin', 'no-pin', 'pin-default', 'propose']);
65
67
  const PIN_FLAGS = ['pin', 'no-pin', 'pin-default'];
66
- const VALUE = new Set(['to', 'why', 'root', 'due', 'start', 'owner', 'notes', 'stage', 'type', 'lag']);
68
+ const VALUE = new Set(['to', 'why', 'root', 'due', 'start', 'owner', 'notes', 'stage', 'type', 'lag', 'parent']);
67
69
  const ONLY = { add: ['due', 'start', 'owner', 'notes', 'stage'], list: ['all'], state: ['to', 'why'], remove: ['why'], set: ['due', 'start', 'owner', 'notes', 'stage'], link: ['type', 'lag', 'why'], unlink: [] };
68
70
  const OPEN = new Set(['To do', 'In progress']);
69
71
  /** The PM's words for a state: any case, with or without the apostrophe or the space. */
@@ -107,6 +109,16 @@ function boardsCtx(root, stateDir) {
107
109
  return { w, ctx: { getWs: () => w, workspaceList: () => [w], stateDirFor: () => stateDir, selfRoot: path.resolve(__dirname, '..', '..') } };
108
110
  }
109
111
  const line = (t) => `${t.id} · ${t.state} · ${t.title}${t.kind === 'Epic' ? ' (epic)' : ''}${t.milestone ? ' · ◇ milestone' : ''}${t.pinned === true ? ' · pinned' : t.pinned === false ? ' · not pinned' : ''}${t.stage ? ' · under ' + t.stage : ''}${t.start ? ' · starts ' + String(t.start).slice(0, 10) : ''}${t.due ? ' · due ' + String(t.due).slice(0, 10) : ''}`;
112
+ /** The tasks in tree order: each one, then the ones under it (a parent not in the list leaves its subtask at the top level). */
113
+ function nested(T) {
114
+ const ids = new Set(T.map((t) => t.id)), kids = new Map(), out = [];
115
+ for (const t of T) if (t.parent && ids.has(t.parent) && t.parent !== t.id) { if (!kids.has(t.parent)) kids.set(t.parent, []); kids.get(t.parent).push(t); }
116
+ const seen = new Set();
117
+ const walk = (t, d) => { if (seen.has(t.id)) return; seen.add(t.id); out.push({ t, depth: d }); for (const k of kids.get(t.id) || []) walk(k, d + 1); };
118
+ for (const t of T) if (!(t.parent && ids.has(t.parent) && t.parent !== t.id)) walk(t, 0);
119
+ for (const t of T) if (!seen.has(t.id)) walk(t, 0); // a loop: still listed
120
+ return out;
121
+ }
110
122
  /** The workflow row of an initiative, deriving the rows when they are still being read. */
111
123
  function rowOf(boards, ctx, w, id) {
112
124
  let r = boards.initiativeWorkflow(ctx, w, id);
@@ -144,7 +156,11 @@ async function run(argv, { say = (s) => console.log(s), cwd = process.cwd(), isT
144
156
  const cli = { isTTY: isTTY === undefined ? !!(process.stdin.isTTY && process.stdout.isTTY) : isTTY, env: env === undefined ? process.env : env };
145
157
  const g = { ok: true, actor: actorLib.fromCli(cli), cli };
146
158
  /** Every task of an initiative: its Board tasks and its breakdown items (lib/stage-read.js, which `pmos board` reads too). */
147
- const tasksOf = (id) => require('./stage-read.js').tasksOf(ctx, w, id);
159
+ const tasksOf = (id) => {
160
+ // each with its parent (subtasks, initiative work-subtasks), from the same fold the Board reads
161
+ const PA = boards.foldOf(ctx, w).parents || new Map();
162
+ return require('./stage-read.js').tasksOf(ctx, w, id).map((t) => (PA.has(t.id) ? { ...t, parent: PA.get(t.id) } : t));
163
+ };
148
164
 
149
165
  if (verb === 'add') {
150
166
  const [id, title] = pos;
@@ -173,9 +189,10 @@ async function run(argv, { say = (s) => console.log(s), cwd = process.cwd(), isT
173
189
  try { boards.seedInitiative(ctx, w, id); } catch { /* the To finish tasks are made on the next read */ }
174
190
  const all = tasksOf(id);
175
191
  const shown = flags.all ? all : all.filter((t) => OPEN.has(t.state));
176
- if (json) { say(JSON.stringify({ ok: true, tasks: shown.map((t) => ({ id: t.id, board: t.board, kind: t.kind, title: t.title, state: t.state, owner: t.owner, start: t.start || null, due: t.due, stage: t.stage || '', ...(t.milestone ? { milestone: true } : {}), ...(typeof t.pinned === 'boolean' ? { pinned: t.pinned } : {}), ...(t.from ? { from: t.from } : {}) })) })); return 0; }
192
+ if (json) { say(JSON.stringify({ ok: true, tasks: shown.map((t) => ({ id: t.id, board: t.board, kind: t.kind, title: t.title, state: t.state, owner: t.owner, start: t.start || null, due: t.due, stage: t.stage || '', ...(t.milestone ? { milestone: true } : {}), ...(typeof t.pinned === 'boolean' ? { pinned: t.pinned } : {}), ...(t.from ? { from: t.from } : {}), ...(t.parent ? { parent: t.parent } : {}) })) })); return 0; }
177
193
  if (!shown.length) { say(all.length ? `No open task on ${id}. --all lists the ${all.length} closed.` : `No task on ${id}.`); return 0; }
178
- for (const t of shown) say(line(t));
194
+ // subtasks (initiative work-subtasks): a task with a parent prints under it, indented one step per level, up to three
195
+ for (const x of nested(shown)) say(' '.repeat(Math.min(x.depth, 3)) + line(x.t));
179
196
  return 0;
180
197
  }
181
198
  /** A task by its id: a Board task, or a breakdown item with the board its initiative is on. */
@@ -191,7 +208,7 @@ async function run(argv, { say = (s) => console.log(s), cwd = process.cwd(), isT
191
208
  };
192
209
 
193
210
  if (verb === 'set') {
194
- const keys = ['stage', 'due', 'start', 'owner', 'notes'].filter((k) => flags[k] !== undefined).concat(flags.milestone || flags['no-milestone'] ? ['milestone'] : []).concat(PIN_FLAGS.some((k) => flags[k]) ? ['pinned'] : []);
211
+ const keys = ['stage', 'due', 'start', 'owner', 'notes', 'parent'].filter((k) => flags[k] !== undefined).concat(flags.milestone || flags['no-milestone'] ? ['milestone'] : []).concat(PIN_FLAGS.some((k) => flags[k]) ? ['pinned'] : []);
195
212
  if (!pos.length || !keys.length) { say('usage: pmos task set <task> [<task> …] [--stage <stage>|none] [--due YYYY-MM-DD|none] [--start YYYY-MM-DD|none] [--owner <who>] [--notes <text>] [--milestone|--no-milestone] [--pin|--no-pin|--pin-default]'); return 2; }
196
213
  const folded = boards.foldOf(ctx, w);
197
214
  const done = [], refused = [];
@@ -208,6 +225,7 @@ async function run(argv, { say = (s) => console.log(s), cwd = process.cwd(), isT
208
225
  }
209
226
  for (const k of ['due', 'start']) if (flags[k] !== undefined) body[k] = String(flags[k]).toLowerCase() === 'none' ? '' : flags[k];
210
227
  for (const k of ['owner', 'notes']) if (flags[k] !== undefined) body[k] = flags[k];
228
+ if (flags.parent !== undefined) body.parent = String(flags.parent).toLowerCase() === 'none' ? '' : String(flags.parent); // a subtask (initiative work-subtasks)
211
229
  if (flags.milestone || flags['no-milestone']) body.milestone = !!flags.milestone;
212
230
  if (PIN_FLAGS.some((k) => flags[k])) body.pinned = flags.pin ? true : flags['no-pin'] ? false : null;
213
231
  const e = boards.taskEdit(ctx, body, g);