create-pmos 0.831.0 → 0.833.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 (59) hide show
  1. package/package.json +140 -41
  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/changelog.json +139 -21
  7. package/workspace/guide/backlog.md +2 -1
  8. package/workspace/guide/cli.md +19 -0
  9. package/workspace/guide/initiatives-and-next-steps.md +2 -0
  10. package/workspace/guide/layout.md +4 -1
  11. package/workspace/guide/positioning.md +1 -1
  12. package/workspace/guide/programs.md +2 -1
  13. package/workspace/lib/events-place.js +11 -4
  14. package/workspace/lib/features.json +3 -1
  15. package/workspace/lib/layouts-cli.js +6 -0
  16. package/workspace/lib/line.js +7 -1
  17. package/workspace/lib/list-balance.js +18 -3
  18. package/workspace/lib/pmos-verbs.js +6 -0
  19. package/workspace/lib/route-modules.js +2 -0
  20. package/workspace/lib/routes-events-place.js +19 -1
  21. package/workspace/lib/routes-screen-layouts.js +56 -0
  22. package/workspace/lib/routes-strategy-card.js +6 -2
  23. package/workspace/lib/routes-switches.js +35 -0
  24. package/workspace/lib/switch-owners.js +152 -0
  25. package/workspace/lib/switches-cli.js +85 -0
  26. package/workspace/lib/three-layouts.js +214 -0
  27. package/workspace/lib/work-kr.js +77 -0
  28. package/workspace/package-lock.json +2 -2
  29. package/workspace/package.json +1 -1
  30. package/workspace/public/pm/bd-backlog.css +11 -0
  31. package/workspace/public/pm/bd-goal.js +33 -0
  32. package/workspace/public/pm/bd-ini-panel.js +15 -5
  33. package/workspace/public/pm/bd-pop-ds.css +16 -0
  34. package/workspace/public/pm/bd-positioning.js +6 -4
  35. package/workspace/public/pm/bd-prog-panel.js +16 -5
  36. package/workspace/public/pm/bd-strategy.js +15 -3
  37. package/workspace/public/pm/bd-work-ds.css +6 -0
  38. package/workspace/public/pm/bd-work.js +34 -8
  39. package/workspace/public/pm/cozy-events-view.js +8 -4
  40. package/workspace/public/pm/cozy-pop-work.js +8 -3
  41. package/workspace/public/pm/cozy-today-app.js +28 -1
  42. package/workspace/public/pm/cozy-today-model.js +13 -5
  43. package/workspace/public/pm/cozy-today-view.js +10 -1
  44. package/workspace/public/pm/line-view.js +13 -1
  45. package/workspace/public/pm/list-balance.js +16 -2
  46. package/workspace/public/pm/ms-strip.js +137 -0
  47. package/workspace/public/pm/page-chat.css +19 -0
  48. package/workspace/public/pm/page-chat.js +2 -0
  49. package/workspace/public/pm/premium-board.js +7 -1
  50. package/workspace/public/pm/side-fold.js +94 -0
  51. package/workspace/public/pm/switch-owners.js +70 -0
  52. package/workspace/public/pm/three-layouts.js +66 -0
  53. package/workspace/public/premium-board.html +2 -0
  54. package/workspace/stage-card-tasks-test.js +1 -0
  55. package/workspace/test-lists/ms-strip.json +9 -0
  56. package/workspace/test-lists/side-fold.json +9 -0
  57. package/workspace/test-lists/switch-owners.json +9 -0
  58. package/workspace/test-lists/three-layouts.json +9 -0
  59. package/workspace/test-lists/work-kr.json +9 -0
@@ -28,7 +28,8 @@
28
28
  * scope the filter tokens the item is under: 'p:<ws>' (its product, as the saved product pick names it), 'g:<program id>' (each program that holds its work),
29
29
  * 'j:<ws>|<initiative>' (its project). A meeting with no work is under the product its title names, else under none: it then
30
30
  * shows only when no product, program or project is picked.
31
- * group late (before today, not done) · today · coming (the next WINDOW_DAYS days; a meeting the next MEET_DAYS) · later
31
+ * group late (before today, not done) · today · coming (the next WINDOW_DAYS days; a meeting the next MEET_DAYS) · later ·
32
+ * past (a meeting before today: never late, shown when the PM picks its day, and a mark on the calendar)
32
33
  * tone late · risk (a milestone of an initiative at risk, or whose Jira forecast says it will miss) · ''
33
34
  * suggest { op: done | move | drop | met | gone | ask, to?, with?, ask?, text, why, sig } or null. What PMOS suggests; the PM says yes (✓)
34
35
  * or no (✕). met and gone are kept by Events (the date is met, or dropped: Events stops listing it); ask adds a task for the PM.
@@ -130,7 +131,7 @@ function build(input = {}) {
130
131
  x.date = day10(x.date);
131
132
  x.days = daysBetween(today, x.date);
132
133
  x.group = groupOf(x.kind, x.date, today);
133
- if (x.kind === 'meeting' && x.group === 'late') return; // a meeting that has passed is not late
134
+ if (x.kind === 'meeting' && x.group === 'late') x.group = 'past'; // a meeting that has passed is not late: it is kept for its day
134
135
  if (x.kind === 'report' && x.group === 'late' && !x.draft) return;
135
136
  x.type = x.type || x.kind;
136
137
  x.fixed = !!(x.canFix && fixedSet.has(x.key));
@@ -264,8 +265,14 @@ function build(input = {}) {
264
265
  const time = /T(\d{2}:\d{2})/.exec(e.at);
265
266
  const until = typeof e.end === 'string' && e.end.slice(0, 10) === e.at.slice(0, 10) ? /T(\d{2}:\d{2})/.exec(e.end) : null;
266
267
  const work = e.initiative ? { id: String(e.initiative), title: '', ws: '', board: '' } : null;
268
+ // a meeting that has passed opens its card in the Viewer, which holds its notes (the note linked to it, else Take notes)
269
+ const day = day10(e.at), past = daysBetween(today, day) < 0;
270
+ const note = e.note && e.note.id ? e.note : null;
271
+ const href = !past ? null : note ? '/premium-viewer.html?open=meeting&note=' + encodeURIComponent(note.id)
272
+ : e.id ? '/premium-viewer.html?open=meeting&event=' + encodeURIComponent(e.id) + '&date=' + day : null;
267
273
  put({ key: 'mtg:' + (e.id || e.at + '|' + e.title), kind: 'meeting', type: FOCUS.test(e.title) ? 'focus' : 'meeting', date: e.at, time: time ? time[1] : null, until: until ? until[1] : null, title: clip(e.title, 140),
268
- line: time ? '' : 'All day', product: '', work, task: null, own: null, jira: false, canFix: false, editable: false, scope: [], act: null });
274
+ line: past && note && note.line ? clip(note.line, 120) : time ? '' : 'All day', product: '', work, task: null, own: null, jira: false, canFix: false, editable: false, scope: [],
275
+ act: href ? { label: note ? 'Open notes' : 'Open the meeting', href } : null });
269
276
  }
270
277
 
271
278
  // the dates people state in the sources: proven only (lib/events-stated.js), each names its source
@@ -386,7 +393,7 @@ function build(input = {}) {
386
393
  delete x.oldDrafts;
387
394
  }
388
395
 
389
- const ORDER = { late: 0, today: 1, coming: 2, later: 3 };
396
+ const ORDER = { past: 0, late: 1, today: 2, coming: 3, later: 4 };
390
397
  // Late: the newest first, so the dates you can still save come before the old ones. A day: the dates with no time first, then by time
391
398
  items.sort((a, b) => ORDER[a.group] - ORDER[b.group] || (a.group === 'late' ? b.date.localeCompare(a.date) : a.date.localeCompare(b.date)) || String(a.time || '').localeCompare(String(b.time || '')) || a.title.localeCompare(b.title));
392
399
  for (const x of items) { delete x.row; delete x.jiraKey; }
@@ -4,7 +4,7 @@
4
4
  "features": [
5
5
  {"id": "goal", "audience": "user", "status": "ga", "group": "Plan and decide", "name": "Give PMOS a goal", "say": "PMOS asks a few questions, then works on the goal after you press Start.", "cmd": "/goal", "phrases": ["work on this until", "keep going until", "make it happen"], "since": "0.560.0"},
6
6
  {"id": "why", "audience": "user", "status": "ga", "group": "Plan and decide", "name": "Why this work exists", "say": "Three lines on an initiative or a task: its goal, its problem and the evidence.", "cmd": "/why", "verb": "why", "hint": "<initiative or task>", "phrases": ["why does this exist", "why are we doing", "why are we building", "what is the point of", "reason for this work", "why this initiative"], "phone": true, "since": "0.700.0", "ask": ["initiative", "task"]},
7
- {"id": "rehearse", "audience": "user", "status": "ga", "group": "Plan and decide", "name": "Rehearse a change", "say": "Move a task by some days and see what else slips, before anything changes.", "cmd": "/rehearse", "verb": "rehearse", "sub": "move", "hint": "<task> <days>", "place": "board", "phrases": ["what if slips", "what happens if slips", "what if move", "push back", "delay by", "slips a week", "what breaks if", "move the date", "what if we cut"], "since": "0.600.0"},
7
+ {"id": "rehearse", "audience": "user", "status": "ga", "group": "Plan and decide", "name": "Rehearse a change", "say": "Move a task by some days and see what else slips, before anything changes.", "cmd": "/rehearse", "verb": "rehearse", "sub": "move", "hint": "<task> <days>", "ask": ["task"], "place": "board", "phrases": ["what if slips", "what happens if slips", "what if move", "push back", "delay by", "slips a week", "what breaks if", "move the date", "what if we cut"], "since": "0.600.0"},
8
8
  {"id": "decisions", "audience": "user", "status": "ga", "group": "Plan and decide", "name": "Decision journal", "say": "Write one line per decision, with what you expect and the date to check it.", "cmd": "/decide", "verb": "decisions", "sub": "add", "hint": "<the decision>", "phrases": ["we decided", "log a decision", "record a decision", "note the decision", "decision journal", "list decisions"], "since": "0.640.0"},
9
9
  {"id": "questions", "audience": "user", "status": "ga", "group": "Plan and decide", "name": "Open questions", "say": "Every question nobody has answered yet, oldest first, in one list.", "cmd": "/questions", "verb": "questions", "phrases": ["open questions", "unanswered questions", "what is still open", "questions nobody answered", "what do we not know"], "phone": true, "since": "0.660.0"},
10
10
  {"id": "press-release", "audience": "user", "status": "ga", "group": "Plan and decide", "name": "Press release and FAQ", "say": "A one-page press release and FAQ for a bet, drafted from its record, for you to edit.", "cmd": "/press-release", "verb": "press-release", "hint": "<initiative>", "phrases": ["press release", "working backwards", "write the faq", "announce this"], "since": "0.690.0", "ask": ["initiative"]},
@@ -20,6 +20,7 @@
20
20
  {"id": "connectors", "audience": "user", "status": "ga", "group": "Your product", "name": "What connectors read and write", "say": "What PMOS reads and writes through each connector, and what leaves this computer.", "cmd": "/connectors", "verb": "connectors", "sub": "data", "since": "0.825.0"},
21
21
  {"id": "positioning", "audience": "user", "status": "ga", "group": "Your product", "name": "Positioning and key messages", "say": "A positioning statement and key messages, each citing a strategy line.", "cmd": "/positioning", "verb": "positioning", "sub": "list", "phrases": ["positioning statement", "key messages", "messaging for"], "since": "0.740.0"},
22
22
  {"id": "principles", "audience": "user", "status": "ga", "group": "Your product", "name": "Product principles", "say": "Four to six principles drafted from your past decisions, each citing them.", "cmd": "/principles", "verb": "principles", "sub": "list", "phrases": ["product principles", "our principles", "design principles for"], "since": "0.720.0"},
23
+ {"id": "switches", "audience": "user", "status": "ga", "group": "Your product", "name": "Who has which switch", "say": "Each customer's switches, why each is on and who agreed; turning one waits for you.", "cmd": "/switches", "verb": "switches", "sub": "list", "since": "0.830.0"},
23
24
  {"id": "glossary", "audience": "user", "status": "ga", "group": "Your product", "name": "Glossary", "say": "The product's own words; every page shows a word's meaning on hover.", "cmd": "/glossary", "verb": "glossary", "sub": "list", "hint": "<word>", "phrases": ["define the word", "glossary", "add to glossary", "meaning of the word"], "since": "0.690.0"},
24
25
  {"id": "health", "audience": "user", "status": "ga", "group": "Your product", "name": "Health score", "say": "This product's health from 0 to 100, and the three parts that make it.", "cmd": "/health", "verb": "health", "sub": "score", "phrases": ["health score", "how healthy is", "product health"], "phone": true, "since": "0.737.0", "ask": ["product"]},
25
26
  {"id": "outcomes", "audience": "user", "status": "ga", "group": "Your product", "name": "Did it work?", "say": "Each initiative's expected outcome and the date to check it.", "cmd": "/outcomes", "verb": "outcomes", "sub": "list", "phrases": ["did it work", "expected outcome", "outcomes due", "check the outcome"], "since": "0.640.0"},
@@ -63,6 +64,7 @@
63
64
  {"id": "goals", "audience": "user", "status": "ga", "group": "Your product", "name": "Starter goals", "say": "Up to three goals drafted from your own product, each with its source; keep one and it becomes a goal.", "cmd": "/goals", "verb": "goals"},
64
65
  {"id": "approver", "audience": "user", "status": "ga", "group": "Before you ship", "name": "What an approver asks", "say": "What each approver asked or objected to before, ahead of the next sign-off.", "cmd": "/approver", "verb": "approver", "hint": "<name>"},
65
66
  {"id": "balance", "audience": "user", "status": "ga", "group": "Plan and decide", "name": "The mix of a list", "say": "Feature, fix, debt or discovery in one line, with a note when one kind is over your line.", "cmd": "/balance", "verb": "balance"},
67
+ {"id": "layouts", "audience": "user", "status": "ga", "group": "Before you ship", "name": "Three layouts for a new screen", "say": "Three layouts of a new screen side by side, the one that fits your picks, and the one you keep to build.", "cmd": "/layouts", "verb": "layouts"},
66
68
  {"id": "declined", "audience": "user", "status": "ga", "group": "Plan and decide", "name": "Asks you declined", "say": "Asks closed without being done, each with a kind reply draft PMOS never sends.", "cmd": "/declined", "verb": "declined"},
67
69
  {"id": "sprint", "audience": "user", "status": "ga", "group": "Catch up", "name": "Sprint retro", "say": "A closed sprint's retro from its close numbers, and its one tracked change.", "cmd": "/sprint", "verb": "sprint"},
68
70
  {"id": "deps", "audience": "user", "status": "beta", "group": "Catch up", "name": "Waiting on other teams", "say": "Each piece of your work that waits on another team, since when, with a Chase draft.", "cmd": "/deps", "verb": "deps"},
@@ -0,0 +1,6 @@
1
+ 'use strict';
2
+ /* layouts-cli.js — `pmos layouts` (initiative three-layouts, job #1904, idea A317). The verb's module; lib/three-layouts.js holds the store,
3
+ * the rules and the commands, so the Work popup's route and the terminal read and write the same layouts.jsonl.
4
+ * run(argv, { say, root?, cwd?, stateDir?, runtimeDir? }) → exit code · COMMANDS · USAGE */
5
+ const T = require('./three-layouts.js');
6
+ module.exports = { run: (argv, o) => T.run(argv, o), COMMANDS: T.COMMANDS, USAGE: T.USAGE };
@@ -14,6 +14,7 @@
14
14
  * waiting when it waits on live initiatives its record names as depends_on or predecessor (depsOf)
15
15
  * lineOf(root, { only?, now?, derive? }) → { ok, product, rows: [place answer], live, placed, ended } | { ok: false, error, pending? }
16
16
  * derive false: read only the rows already derived (the server's sweep); pending while they are not
17
+ * a row whose parent_kr names a key result of the OKR file carries kr: { token, title, objective } (lib/work-kr.js)
17
18
  * summary(line) → { live, placed, percent }
18
19
  *
19
20
  * THE STATION IS THE INITIATIVE'S OWN WORKFLOW STAGE (D99), the one the Board and `pmos workflow of` show. Its exit items are the stage's
@@ -288,14 +289,19 @@ function lineOf(root, { only = null, now = Date.now(), derive = true } = {}) {
288
289
  // factory-signoffs-reach-you: this initiative's sign-offs, and the sign-off lines the PM kept from PMOS's suggestion for its stage
289
290
  const signoffs = SO ? SO.list(soFile, { ini: id }) : [];
290
291
  const byKept = SS && r.row.wf && r.row.wfStage ? SS.keptFor(kept, r.row.wf.id, r.row.wfStage.key) : null;
291
- rows.push({ deps, doubt: doubtOf(r.row, derived.get(id)), p: place({ row: r.row, tasks, moves, jira, activity, signoffs, byKept }, now) });
292
+ rows.push({ deps, anchor: b0.anchor || null, doubt: doubtOf(r.row, derived.get(id)), p: place({ row: r.row, tasks, moves, jira, activity, signoffs, byKept }, now) });
292
293
  }
293
294
  // a dependency counts while it is itself live on the line (not ended): waiting on it is never stuck
294
295
  const first = new Map(rows.map((x) => [x.p.id, x.p]));
296
+ const WK = require('./work-kr.js');
297
+ let OKR = null; try { const o = WK.forRoot(root, now); OKR = o.objectives.length ? o.objectives : null; } catch { OKR = null; }
295
298
  for (let i = 0; i < rows.length; i++) {
296
299
  const x = rows[i];
297
300
  const waitsOn = x.deps.map((d) => first.get(d) || { id: d, live: true, station: null }).filter((p) => p && p.live).map((p) => ({ id: p.id, station: p.station ? p.station.name : null }));
298
301
  rows[i] = settle(x.p, { doubt: x.doubt, waitsOn });
302
+ // tb-work-kr: the key result its parent_kr names in the OKR file (lib/work-kr.js), else none; nothing is guessed
303
+ const kr = OKR && x.anchor ? WK.krOf(x.anchor, OKR) : null;
304
+ if (kr) rows[i] = { ...rows[i], kr };
299
305
  }
300
306
  const live = rows.filter((x) => x.live);
301
307
  return { ok: true, product: path.basename(root), rows, live: live.length, placed: live.filter((x) => x.station && x.next).length, ended: rows.length - live.length };
@@ -6,6 +6,7 @@
6
6
  * item already has and says the mix in one line, with a quiet note only when one kind passes the PM's line (default 60 percent).
7
7
  *
8
8
  * kindOf(item) → 'feature' | 'fix' | 'debt' | 'discovery' | 'other'
9
+ * an initiative on a workflow (`wf`): the kind the workflow's name says ("Simple feature" → feature), else its lane; never `type`.
9
10
  * the item's own words, first that names one: kind, lane, type (a Jira issue type). feature · story · epic → feature;
10
11
  * incident · bug · defect · fix → fix; chore · debt · tech-debt · refactor → debt (a plain Jira Task is other); discovery · spike · prototype ·
11
12
  * research → discovery. Anything else, or nothing, is other. Never guessed from the title.
@@ -46,10 +47,24 @@ function wordKind(w) {
46
47
  return '';
47
48
  }
48
49
 
49
- /** The item's kind from its own fields, never from its title. */
50
+ /** The kind a workflow's name (or id) names: "Simple feature" → feature, "Bug triage" → fix; '' when it names none. */
51
+ function workflowKind(wf) {
52
+ if (!wf || typeof wf !== 'object') return '';
53
+ for (const src of [wf.name, wf.id]) {
54
+ const w = norm(String(src == null ? '' : src).replace(/[-]+/g, ' ')).split(' ').filter(Boolean);
55
+ for (let i = 0; i < w.length; i++) { const k = wordKind(w[i] + ' ' + (w[i + 1] || '')) || wordKind(w[i]); if (k) return k; }
56
+ }
57
+ return '';
58
+ }
59
+
60
+ /** The item's kind from its own fields, never from its title. An initiative on a workflow (a row with `wf`): the kind its workflow
61
+ * names, else its lane; a legacy `type:` decides nothing there, since the workflow sets the kind (kind-follows-workflow, #1731).
62
+ * Any other item: kind, lane, type (a Jira issue type). */
50
63
  function kindOf(item) {
51
64
  if (!item || typeof item !== 'object') return 'other';
52
- for (const f of ['kind', 'lane', 'type', 'issuetype']) {
65
+ const onWf = item.wf && typeof item.wf === 'object';
66
+ if (onWf) { const k = workflowKind(item.wf); if (k) return k; }
67
+ for (const f of onWf ? ['lane'] : ['kind', 'lane', 'type', 'issuetype']) {
53
68
  const v = valOf(item[f]);
54
69
  const k = wordKind(v && typeof v === 'object' ? v.name : v);
55
70
  if (k) return k;
@@ -98,7 +113,7 @@ function roadmapItems(root, { today } = {}) {
98
113
  return S.subjects.filter((it) => !it.accepted).map((it) => ({ id: it.id, title: it.title, lane: it.lane, outcome_metric: it.metric }));
99
114
  }
100
115
 
101
- module.exports = { KINDS, KIND_LABEL, OUTCOMES, OUTCOME_LABEL, DEFAULT_MAX, MIN_ITEMS, TAG, kindOf, outcomeOf, balanceOf, line, roadmapItems };
116
+ module.exports = { KINDS, KIND_LABEL, OUTCOMES, OUTCOME_LABEL, DEFAULT_MAX, MIN_ITEMS, TAG, workflowKind, kindOf, outcomeOf, balanceOf, line, roadmapItems };
102
117
 
103
118
  if (require.main === module) {
104
119
  const a = process.argv.slice(2);
@@ -191,6 +191,9 @@ const VERBS = Object.freeze({
191
191
  // Not a pm-os-absorb verb (run: null): initiative product-principles-draft (bet A352) added it through the same table.
192
192
  principles: Object.freeze({ module: 'principles-cli.js', run: null, guide: 'cli.md',
193
193
  help: 'pmos principles list|sources|draft|keep|drop|undo|add — the product\'s principles, drafted from its decisions, each citing them; keep or drop each (pmos principles help)' }),
194
+ // Not a pm-os-absorb verb (run: null): initiative switch-owners (job #1908, idea A263) added it through the same table.
195
+ switches: Object.freeze({ module: 'switches-cli.js', run: null, guide: 'cli.md',
196
+ help: 'pmos switches list|add|set|undo|turn|cancel|count — who has which switch: each customer\'s switch, why, and who agreed; turning one waits for you (pmos switches help)' }),
194
197
  // Not a pm-os-absorb verb (run: null): initiative positioning-draft (idea A328) added it through the same table.
195
198
  positioning: Object.freeze({ module: 'positioning-cli.js', run: null, guide: 'cli.md',
196
199
  help: 'pmos positioning strategy|list|keep|drop — the product\'s positioning and key messages, each citing its strategy lines (pmos positioning help)' }),
@@ -264,6 +267,9 @@ const VERBS = Object.freeze({
264
267
  help: 'pmos signal add|remove|list|count — the customer signals behind each roadmap item; Work shows the count (pmos signal help)' }),
265
268
  launcher: Object.freeze({ module: 'launcher-cli.js', run: null, guide: 'cli.md',
266
269
  help: 'pmos launcher on|off|status — a PMOS app and a login item, so the workspace starts without a terminal' }),
270
+ // Not a pm-os-absorb verb (run: null): initiative three-layouts (job #1904, A317) added it through the same table.
271
+ layouts: Object.freeze({ module: 'layouts-cli.js', run: null, guide: 'cli.md',
272
+ help: 'pmos layouts show|pick|undo|taste — a new screen\'s three layouts, the one PMOS recommends from your picks, and your pick (pmos layouts help)' }),
267
273
  // bet A459a (job #1751): a new public API, held out of auto-merge until Wawan's final yes
268
274
  mcp: Object.freeze({ module: 'mcp-cli.js', run: null, guide: 'cli.md',
269
275
  help: 'pmos mcp [--root <repo>] — PMOS cards for another agent, as A2UI v1.0 over MCP (stdio)' }),
@@ -152,12 +152,14 @@ const MODULES = Object.freeze([
152
152
  'routes-use-log', // bet A466: the local use log, page opens and controls pressed, on this computer only (runtime use-log.jsonl; page-press POST)
153
153
  'routes-strategy-card', // bet A458: a product's five-line strategy above its Board, and the gentle "doesn't fit" note on new work (records strategy-card.jsonl; page-press POST)
154
154
  'routes-principles', // bet A352: a product's principles drafted from its decisions, kept or dropped on the Board (records principles.jsonl; page-press POST)
155
+ 'routes-switches', // idea A263: who has which switch, per customer, on Work; turning one waits for the PM's own press (records switches.jsonl; page-press POST)
155
156
  'routes-prefs', // bet A461: view preferences that follow the person to the phone and other browsers (runtime view-prefs.json; page-press POST)
156
157
  'routes-skill-map', // bet A208: the team skill map on Work, for the person and their lead only (records skill-map.jsonl; page-press POST)
157
158
  'routes-stakeholders', // bet A371: an initiative's stakeholder map, decides / must agree / needs to know, in the Work popup (records stakeholders.jsonl; page-press POST)
158
159
  'routes-code-map', // idea A176: the product's code map on Work, redrawn when the default branch moves (records code-map.json; read-only)
159
160
  'routes-arch-warns', // idea A54: one warning when an initiative names a risky part of the code (reads code-map.json; read-only)
160
161
  'routes-live-rows', // bet A458: chat-made task changes streamed to open pages (runtime live-events.jsonl; read-only event stream)
162
+ 'routes-screen-layouts', // three-layouts (A317): a new screen's three layouts, the ✦ pick and its Undo (product state layouts.jsonl; page-press POST)
161
163
  'routes-team-waits', // team-waits (A364): Work › Dependencies' waits on other teams (GET, read-only; team-waits.jsonl written by pmos deps)
162
164
  'routes-connector-data', // connector-data (A150): what each connector reads and writes, from lib/connector-data.js (read only)
163
165
  'routes-review-pack', // job #1910 (A343): the monthly review packs for Library › Reports, drafted when due (<state>/reports/review-pack/; page-press POST)
@@ -123,6 +123,24 @@ function readMeetings(runtimeDir, now) {
123
123
  const events = require('./calendar-events.js').readAll(runtimeDir, { now: now.getTime() });
124
124
  let links = null;
125
125
  try { const CL = require('./calendar-links.js'); links = CL.read(runtimeDir); for (const e of events) { const l = links.get(CL.keyOf(e)); if (l && l.kind === 'initiative' && l.initiative) e.initiative = l.initiative; } } catch { /* the brief's own link stays */ }
126
+ attachNotes(events, runtimeDir, now);
127
+ return events;
128
+ }
129
+ /** The note of each meeting that has passed: { id, line } (its first summary line; a private note gives its id only), so a past day on
130
+ * Events shows the meeting with its notes. The same match as lib/notes.js sameEvent: the event id, else the start minute and title.
131
+ * Meetings from today on are left alone. A notes folder that cannot be read gives no notes. */
132
+ function attachNotes(events, runtimeDir, now) {
133
+ const today = localDay(now);
134
+ const past = events.filter((e) => e && typeof e.at === 'string' && e.at.slice(0, 10) < today);
135
+ if (!past.length) return events;
136
+ let rows = [];
137
+ try { const N = require('./notes.js'); const l = N.list(runtimeDir, { now: now.getTime() }); rows = l && l.ok ? l.notes.filter((n) => n && n.meeting && n.meeting.kind === 'event') : []; } catch { return events; }
138
+ if (!rows.length) return events;
139
+ const same = require('./notes.js').sameEvent;
140
+ for (const e of past) {
141
+ const n = rows.find((r) => same(r.meeting, { event_id: e.id, start: e.at, title: e.title }));
142
+ if (n) e.note = { id: n.id, line: n.private ? '' : String((n.summary_lines || [])[0] || '') };
143
+ }
126
144
  return events;
127
145
  }
128
146
  /** Does PMOS read a calendar at all: an import ledger, the remembered calendar, or a meeting in hand? */
@@ -161,7 +179,7 @@ async function handle(deps) {
161
179
  }
162
180
 
163
181
  module.exports = {
164
- foldMarks, markLine, handlePure: handle, readers: { readSchedules, readDrafts, readOwn, readMarks, readJira, readMeetings, calendarRead },
182
+ foldMarks, markLine, handlePure: handle, readers: { readSchedules, readDrafts, readOwn, readMarks, readJira, readMeetings, calendarRead, attachNotes },
165
183
  prefixes: ['/api/events-place'],
166
184
  handle: async (req, res, url, ctx) => {
167
185
  if (url.pathname === '/api/events-place/mark') {
@@ -0,0 +1,56 @@
1
+ 'use strict';
2
+ /* routes-screen-layouts.js — three layouts for a new screen, pick one (initiative three-layouts, job #1904, idea A317). lib/three-layouts.js
3
+ * is the store and the rules; this is the HTTP the Work popup's Layouts block reads and writes (pm/three-layouts.js).
4
+ *
5
+ * GET /api/screen-layouts?ws&ini → { ok, none: true } the initiative adds no screen (zero is silence), or has no record
6
+ * → { ok, ini, title, layouts: [A, B, C], rec: { key, letter, name, why }, picked, kept, taste }
7
+ * POST /api/screen-layouts/pick { ws, ini, key } → { ok, picked, kept } key: A|B|C or list|summary|action. A page press only.
8
+ * POST /api/screen-layouts/undo { ws, ini } → { ok } the pick taken back. A page press only.
9
+ * STATE: the product's own state folder (stateDirFor), layouts.jsonl, append-only. GET writes nothing. Nothing is sent; no model is called.
10
+ * (`/api/layouts` is the workspace's pane layouts in server.js, hence the longer name.) */
11
+ const T = require('./three-layouts.js');
12
+
13
+ function wsOf(ctx, id) {
14
+ const w = ctx.getWs ? ctx.getWs(id || '') : null;
15
+ return w && (!id || w.id === id) && w.root ? w : null;
16
+ }
17
+ const dirOf = (ctx, w, create) => (ctx.stateDirFor ? ctx.stateDirFor(w) : null) || T.stateDirOf(w.root, create);
18
+
19
+ module.exports = {
20
+ prefixes: ['/api/screen-layouts'],
21
+ handle: async (req, res, url, ctx) => {
22
+ const send = (status, body) => { ctx.json(res, body, status); return true; };
23
+ const p = url.pathname;
24
+ if (p === '/api/screen-layouts' && req.method === 'GET') {
25
+ const w = wsOf(ctx, url.searchParams.get('ws') || '');
26
+ if (!w) return send(404, { ok: false, error: 'no such workspace' });
27
+ const ini = String(url.searchParams.get('ini') || '');
28
+ return send(200, T.viewOf(w.root, ini, { stateDir: dirOf(ctx, w, false) }));
29
+ }
30
+ if (req.method !== 'POST' || (p !== '/api/screen-layouts/pick' && p !== '/api/screen-layouts/undo')) return false;
31
+ const got = await ctx.readJson(req);
32
+ if (!got.ok) return send(400, { ok: false, error: 'invalid JSON body' });
33
+ const b = got.body || {};
34
+ const g = require('./pm-guard.js').requirePagePress(req, b);
35
+ if (!g.ok) return send(g.status, { ok: false, error: g.error });
36
+ const w = wsOf(ctx, typeof b.ws === 'string' ? b.ws : '');
37
+ if (!w) return send(404, { ok: false, error: 'no such workspace' });
38
+ const r = T.recordOf(w.root, String(b.ini || ''));
39
+ if (!r) return send(404, { ok: false, error: 'no initiative ' + String(b.ini || '') + ' here' });
40
+ const dir = dirOf(ctx, w, true);
41
+ if (!dir) return send(503, { ok: false, error: 'this product has no state folder, so the pick cannot be kept' });
42
+ const by = (g.actor && g.actor.by) || 'pm';
43
+ if (p === '/api/screen-layouts/undo') {
44
+ if (!T.pickedOf(T.readLines(dir), r.id)) return send(200, { ok: true, picked: null });
45
+ T.append(dir, T.undoLine({ ini: r.id, by }).line);
46
+ console.info(`${T.TAG} undo ini=${r.id}`);
47
+ return send(200, { ok: true, picked: null });
48
+ }
49
+ const L = T.pickLine({ ini: r.id, key: b.key, title: r.title, by });
50
+ if (L.error) return send(400, { ok: false, error: L.error });
51
+ T.append(dir, L.line);
52
+ console.info(`${T.TAG} pick ini=${r.id} key=${L.line.key}`);
53
+ try { if (ctx.runtimeDir) require('./use-log.js').record(ctx.runtimeDir, [{ kind: 'use', page: 'premium-board', control: 'layoutPick', device: 'desk' }]); } catch { /* a count, never a reason to fail */ }
54
+ return send(200, { ok: true, picked: L.line.key, kept: L.line.kept });
55
+ },
56
+ };
@@ -2,8 +2,9 @@
2
2
  /* routes-strategy-card.js — a product's five-line strategy over HTTP (bet A458, initiative strategy-five-lines). The card and its fit rule are
3
3
  * lib/strategy-card.js; the file is strategy-card.jsonl in the product's records folder (lib/records-dir.js).
4
4
  *
5
- * GET /api/strategy-card?ws=<id>[&board=<id>] → { ok, card, labels, complete, notes, sources, drafting } notes: null while the Board is
5
+ * GET /api/strategy-card?ws=<id>[&board=<id>] → { ok, card, labels, complete, notes, sources, drafting, period, serves } notes: null while the Board is
6
6
  * still being read; sources: { <line>: [{ ref, title }] } for each line PMOS drafted
7
+ * period: the OKR period head, serves: its objectives and key results (lib/work-kr.js; tb-work-kr)
7
8
  * POST /api/strategy-card { ws, fields } → { ok, card, complete } | 400 when no known line is named
8
9
  * POST /api/strategy-card { ws, undo: true, line? } → { ok, card, complete } | 400 take PMOS's draft back (all drafted lines, or one)
9
10
  * POST /api/strategy-card/draft { ws } → { ok, drafting, why? } the PM's ✦: start the drafting run now
@@ -164,7 +165,10 @@ async function handle(req, res, url, ctx) {
164
165
  const drafting = !!(seeder && w && seeder.running && seeder.running(w.id));
165
166
  let notes = [];
166
167
  if (complete) { const rows = ctx.strategyRows ? ctx.strategyRows : await rowsOf(req, ctx, ws, url.searchParams.get('board') || null); notes = rows ? SC.notes(card, rows) : null; }
167
- return send(200, { ok: true, card, labels: SC.LABELS, complete, notes, sources: sourcesOf(rootFor(ctx, w), card), drafting });
168
+ // tb-work-kr: the OKR period the strategy is for and the objectives it serves (lib/work-kr.js); none when no OKR file names them
169
+ let okr = { period: null, serves: [] };
170
+ try { okr = require('./work-kr.js').forRoot(rootFor(ctx, w)); } catch { okr = { period: null, serves: [] }; }
171
+ return send(200, { ok: true, card, labels: SC.LABELS, complete, notes, sources: sourcesOf(rootFor(ctx, w), card), drafting, period: okr.period, serves: okr.serves });
168
172
  }
169
173
  if (req.method !== 'POST') return send(405, { ok: false, error: 'GET or POST' });
170
174
  const rd = await ctx.readJson(req);
@@ -0,0 +1,35 @@
1
+ 'use strict';
2
+ /* routes-switches.js — who has which switch over HTTP (idea A263, initiative switch-owners). The store is lib/switch-owners.js (switches.jsonl
3
+ * in the product's records folder, lib/records-dir.js); the verb is `pmos switches`; the block is public/pm/switch-owners.js on Work.
4
+ *
5
+ * GET /api/switches?ws=<id> → { ok, switches: [row], marked }
6
+ * POST /api/switches { ws, act, id } → { ok, row } | 400 act ∈ confirm (the PM's ✓ "I turned it") · cancel (✕ "keep it as it is") · undo
7
+ *
8
+ * WHO WRITES. A page press only: pm-guard requirePagePress checks the page's Origin and launch nonce, and only then is the press the PM's own
9
+ * (by: 'pm'), the one way a switch's recorded state changes. Nothing here sends anything. */
10
+ const guard = require('./pm-guard.js');
11
+ const SW = require('./switch-owners.js');
12
+ const { recordsDirFor } = require('./records-dir.js');
13
+
14
+ const ACTS = ['confirm', 'cancel', 'undo'];
15
+
16
+ async function handle(req, res, url, ctx) {
17
+ if (url.pathname !== '/api/switches') return false;
18
+ const send = (status, body) => { ctx.json(res, body, status); return true; };
19
+ if (req.method === 'GET') {
20
+ const rows = SW.read(recordsDirFor(ctx, url.searchParams.get('ws') || null));
21
+ return send(200, { ok: true, switches: rows, marked: rows.filter((r) => r.marks.length).length });
22
+ }
23
+ if (req.method !== 'POST') return send(405, { ok: false, error: 'GET or POST' });
24
+ const rd = await ctx.readJson(req);
25
+ if (!rd.ok) return send(400, { ok: false, error: 'the body is not JSON' });
26
+ const body = rd.body || {};
27
+ const g = guard.requirePagePress(req, body);
28
+ if (!g.ok) return send(g.status, { ok: false, error: g.error });
29
+ const act = String(body.act || '');
30
+ if (!ACTS.includes(act)) return send(400, { ok: false, error: 'act is confirm, cancel or undo' });
31
+ const r = SW[act](recordsDirFor(ctx, body.ws || null), String(body.id || ''), { by: 'pm' });
32
+ return r.ok ? send(200, { ok: true, row: r.row }) : send(400, { ok: false, error: r.error });
33
+ }
34
+
35
+ module.exports = { prefixes: ['/api/switches'], handle };
@@ -0,0 +1,152 @@
1
+ 'use strict';
2
+ /* switch-owners.js — who has which switch: every per-customer switch of a product, why it is set and who agreed (idea A263, initiative
3
+ * switch-owners, board BatchReleaseDS panel 23). THE ONE WRITER and THE ONE FOLD of switches.jsonl.
4
+ * lib/switches-cli.js is the verb `pmos switches`; lib/routes-switches.js is the HTTP side; public/pm/switch-owners.js is the Switches block on Work.
5
+ *
6
+ * readLines(dir) · fold(lines) → [row] row: { id, customer, name, on, why, agreedBy, agreedOn, waiting: { to, at, by } | null, marks, at }
7
+ * read(dir) → fold(readLines(dir)), sorted by customer, then switch
8
+ * marks(row) → [] | ['why'] | ['approver'] | ['why', 'approver'] what the switch is missing
9
+ * add(dir, input, { by, now }) → { ok, row } | { ok: false, error } input: { customer, name, why?, agreedBy?, agreedOn?, on? }
10
+ * set(dir, id, input, { by, now }) → { ok, row } | { ok: false, error } fills or changes why / agreedBy / agreedOn
11
+ * undo(dir, id, { by, now }) → { ok, row } | { ok: false, error } takes the last `set` on this switch back
12
+ * turn(dir, id, to, { by, now }) → { ok, row } | { ok: false, error } asks to turn it on or off: the ask WAITS; `on` does not change
13
+ * confirm(dir, id, { by, now }) → { ok, row } | { ok: false, error } the PM's own page press "I turned it": only `by: 'pm'` is taken
14
+ * cancel(dir, id, { by, now }) → { ok, row } | { ok: false, error } drops a waiting ask
15
+ * count(dir, { marked }) → how many switches (or how many are marked)
16
+ * idOf(customer, name) → 's-<8 hex>' the same customer and switch give the same id
17
+ *
18
+ * WHERE. `dir` is the product's records folder (lib/records-dir.js): planning/records in the PMOS repo, pmos/state/records in a kit product.
19
+ * Append-only: one line per event { at, by, ev, id, ... }; nothing rewrites it.
20
+ *
21
+ * TURNING A SWITCH IS AN OUTWARD CHANGE. The switch lives in the user's product, not here, so PMOS never turns one: the chat or the CLI may
22
+ * only write a `turn` ask, which waits for the PM. The recorded state changes on `confirm`, which takes only the PM's own page press
23
+ * (lib/routes-switches.js passes by: 'pm' after pm-guard requirePagePress), and means "I turned it in the product". Nothing here sends anything. */
24
+ const fs = require('fs');
25
+ const path = require('path');
26
+ const crypto = require('crypto');
27
+
28
+ const FILE = 'switches.jsonl';
29
+ const TAG = '[switch-owners]';
30
+ const MAX = 120;
31
+ const EVENTS = ['add', 'set', 'undo', 'turn', 'confirm', 'cancel'];
32
+ const one = (v, max = MAX) => { const s = String(v == null ? '' : v).replace(/\s+/g, ' ').trim(); return s.length > max ? s.slice(0, max - 1).trimEnd() + '…' : s; };
33
+ const idOf = (customer, name) => 's-' + crypto.createHash('sha256').update(one(customer).toLowerCase() + '\u0000' + one(name).toLowerCase()).digest('hex').slice(0, 8);
34
+ const fileOf = (dir) => path.join(dir, FILE);
35
+ const DAY = /^\d{4}-\d{2}-\d{2}$/;
36
+ const log = (s) => { try { console.log(TAG + ' ' + s); } catch { /* no console */ } };
37
+
38
+ function readLines(dir) {
39
+ let raw = '';
40
+ try { raw = fs.readFileSync(fileOf(dir), 'utf8'); } catch { return []; }
41
+ const out = [];
42
+ for (const l of raw.split('\n')) { if (!l.trim()) continue; try { const x = JSON.parse(l); if (x && EVENTS.includes(x.ev) && x.id) out.push(x); } catch { /* a torn line is skipped */ } }
43
+ return out;
44
+ }
45
+ function append(dir, ev) {
46
+ fs.mkdirSync(dir, { recursive: true });
47
+ fs.appendFileSync(fileOf(dir), JSON.stringify(ev) + '\n');
48
+ }
49
+
50
+ /** What a switch is missing: a reason, an approver, or both. */
51
+ function marks(row) {
52
+ const m = [];
53
+ if (!one(row && row.why)) m.push('why');
54
+ if (!one(row && row.agreedBy)) m.push('approver');
55
+ return m;
56
+ }
57
+
58
+ const FIELDS = { why: 'why', agreedBy: 'agreedBy', agreedOn: 'agreedOn' };
59
+ function fold(lines) {
60
+ const by = new Map();
61
+ for (const e of lines) {
62
+ const r = by.get(e.id);
63
+ if (e.ev === 'add') {
64
+ if (r) continue;
65
+ by.set(e.id, { id: e.id, customer: e.customer, name: e.name, on: e.on !== false, why: e.why || '', agreedBy: e.agreedBy || '', agreedOn: e.agreedOn || '',
66
+ waiting: null, at: e.at, sets: [] });
67
+ continue;
68
+ }
69
+ if (!r) continue;
70
+ if (e.ev === 'set') {
71
+ const before = {}; for (const k of Object.keys(FIELDS)) if (k in (e.fields || {})) { before[k] = r[k]; r[k] = e.fields[k] || ''; }
72
+ r.sets.push(before);
73
+ } else if (e.ev === 'undo') {
74
+ const before = r.sets.pop(); if (before) Object.assign(r, before);
75
+ } else if (e.ev === 'turn') {
76
+ r.waiting = { to: e.to, at: e.at, by: e.by || '' }; // an ask only: `on` stays as it was
77
+ } else if (e.ev === 'confirm') {
78
+ if (e.by === 'pm' && r.waiting) { r.on = r.waiting.to === 'on'; r.waiting = null; }
79
+ } else if (e.ev === 'cancel') {
80
+ r.waiting = null;
81
+ }
82
+ r.at = e.at;
83
+ }
84
+ return [...by.values()].map((r) => { const { sets, ...rest } = r; return { ...rest, canUndo: sets.length > 0, marks: marks(r) }; });
85
+ }
86
+ function read(dir) {
87
+ return fold(readLines(dir)).sort((a, b) => a.customer.localeCompare(b.customer) || a.name.localeCompare(b.name));
88
+ }
89
+ const find = (dir, id) => read(dir).find((r) => r.id === id) || null;
90
+
91
+ function add(dir, input = {}, { by = 'unknown', now = Date.now() } = {}) {
92
+ const customer = one(input.customer), name = one(input.name);
93
+ if (!customer || !name) return { ok: false, error: 'a switch needs a customer and a name' };
94
+ const agreedOn = one(input.agreedOn, 10);
95
+ if (agreedOn && !DAY.test(agreedOn)) return { ok: false, error: 'the day it was agreed is YYYY-MM-DD' };
96
+ const id = idOf(customer, name);
97
+ if (find(dir, id)) return { ok: false, error: `${customer} already has ${name} (${id}); pmos switches set ${id} changes it` };
98
+ append(dir, { at: new Date(now).toISOString(), by, ev: 'add', id, customer, name, on: input.on !== false, why: one(input.why), agreedBy: one(input.agreedBy, 80), agreedOn });
99
+ log(`add ${id} ${customer} · ${name}`);
100
+ return { ok: true, row: find(dir, id) };
101
+ }
102
+ function set(dir, id, input = {}, { by = 'unknown', now = Date.now() } = {}) {
103
+ if (!find(dir, id)) return { ok: false, error: `no switch ${id}` };
104
+ const fields = {};
105
+ if (input.why !== undefined) fields.why = one(input.why);
106
+ if (input.agreedBy !== undefined) fields.agreedBy = one(input.agreedBy, 80);
107
+ if (input.agreedOn !== undefined) { const d = one(input.agreedOn, 10); if (d && !DAY.test(d)) return { ok: false, error: 'the day it was agreed is YYYY-MM-DD' }; fields.agreedOn = d; }
108
+ if (!Object.keys(fields).length) return { ok: false, error: 'name --why, --agreed-by or --agreed-on' };
109
+ append(dir, { at: new Date(now).toISOString(), by, ev: 'set', id, fields });
110
+ log(`set ${id} ${Object.keys(fields).join(',')}`);
111
+ return { ok: true, row: find(dir, id) };
112
+ }
113
+ function undo(dir, id, { by = 'unknown', now = Date.now() } = {}) {
114
+ const r = find(dir, id);
115
+ if (!r) return { ok: false, error: `no switch ${id}` };
116
+ if (!r.canUndo) return { ok: false, error: 'nothing to undo on this switch' };
117
+ append(dir, { at: new Date(now).toISOString(), by, ev: 'undo', id });
118
+ log(`undo ${id}`);
119
+ return { ok: true, row: find(dir, id) };
120
+ }
121
+ function turn(dir, id, to, { by = 'unknown', now = Date.now() } = {}) {
122
+ const r = find(dir, id);
123
+ if (!r) return { ok: false, error: `no switch ${id}` };
124
+ if (to !== 'on' && to !== 'off') return { ok: false, error: 'turn it on or off' };
125
+ if ((to === 'on') === r.on) return { ok: false, error: `${r.name} is already ${to} for ${r.customer}` };
126
+ append(dir, { at: new Date(now).toISOString(), by, ev: 'turn', id, to });
127
+ log(`turn ${id} ${to} waits for the PM`);
128
+ return { ok: true, row: find(dir, id) };
129
+ }
130
+ function confirm(dir, id, { by = 'unknown', now = Date.now() } = {}) {
131
+ if (by !== 'pm') return { ok: false, error: 'only your own press on Work turns a switch; PMOS never does' };
132
+ const r = find(dir, id);
133
+ if (!r) return { ok: false, error: `no switch ${id}` };
134
+ if (!r.waiting) return { ok: false, error: 'nothing waits on this switch' };
135
+ append(dir, { at: new Date(now).toISOString(), by, ev: 'confirm', id });
136
+ log(`confirm ${id} ${r.waiting.to}`);
137
+ return { ok: true, row: find(dir, id) };
138
+ }
139
+ function cancel(dir, id, { by = 'unknown', now = Date.now() } = {}) {
140
+ const r = find(dir, id);
141
+ if (!r) return { ok: false, error: `no switch ${id}` };
142
+ if (!r.waiting) return { ok: false, error: 'nothing waits on this switch' };
143
+ append(dir, { at: new Date(now).toISOString(), by, ev: 'cancel', id });
144
+ log(`cancel ${id}`);
145
+ return { ok: true, row: find(dir, id) };
146
+ }
147
+ function count(dir, { marked = false } = {}) {
148
+ const rows = read(dir);
149
+ return marked ? rows.filter((r) => r.marks.length).length : rows.length;
150
+ }
151
+
152
+ module.exports = { FILE, TAG, idOf, readLines, fold, read, marks, add, set, undo, turn, confirm, cancel, count };
@@ -0,0 +1,85 @@
1
+ 'use strict';
2
+ /* switches-cli.js — `pmos switches`: who has which switch, per customer, why, and who agreed (idea A263, initiative switch-owners; the store is
3
+ * lib/switch-owners.js, switches.jsonl in the product's records folder, so what the chat writes shows in the Switches block on Work).
4
+ * `turn` only writes an ask that waits for the PM: PMOS turns nothing. Exit codes: 0 done, 1 refused, 2 usage. Nothing is sent. */
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const { TAG, read, add, set, undo, turn, cancel, count } = require('./switch-owners.js');
8
+
9
+ /* ─ pmos switches ─────────────────────────────────────────────────────────────────────────────────────── */
10
+ const COMMANDS = { switches: ['list', 'add', 'set', 'undo', 'turn', 'cancel', 'count'] };
11
+ const USAGE = [
12
+ 'usage: pmos switches list|add|set|undo|turn|cancel|count — who has which switch: each customer\'s switch, why, and who agreed',
13
+ ' pmos switches list [--json] every switch; a switch with no reason or no approver is marked',
14
+ ' pmos switches add --customer <name> --switch <name> [--why <text>] [--agreed-by <person>] [--agreed-on <YYYY-MM-DD>] [--off]',
15
+ ' pmos switches set <id> [--why <text>] [--agreed-by <person>] [--agreed-on <YYYY-MM-DD>] fill in a reason or an approver',
16
+ ' pmos switches undo <id> take the last set back',
17
+ ' pmos switches turn <id> on|off ask to turn it: the ask waits for you on Work; PMOS turns nothing',
18
+ ' pmos switches cancel <id> drop an ask that waits',
19
+ ' pmos switches count [--marked] how many switches (or how many are marked); the number is the last line',
20
+ 'Run it in the product\'s repository, or pass --root <dir>. Nothing is sent.',
21
+ ];
22
+ const FLAGS = { customer: 'customer', switch: 'name', why: 'why', 'agreed-by': 'agreedBy', 'agreed-on': 'agreedOn', root: 'root' };
23
+ function parse(args) {
24
+ const pos = [], f = {};
25
+ for (let i = 0; i < args.length; i++) {
26
+ const a = args[i];
27
+ if (a === '--json' || a === '--marked' || a === '--off') { f[a.slice(2)] = true; continue; }
28
+ if (a.startsWith('--')) { const k = a.slice(2); if (!(k in FLAGS)) return { bad: a }; f[FLAGS[k]] = args[i + 1] !== undefined ? args[++i] : ''; continue; }
29
+ pos.push(a);
30
+ }
31
+ return { pos, f };
32
+ }
33
+ function repoOf(cwd) {
34
+ let d = path.resolve(cwd);
35
+ for (;;) { try { if (fs.existsSync(path.join(d, '.git'))) return d; } catch { /* look further up */ } const up = path.dirname(d); if (up === d) return path.resolve(cwd); d = up; }
36
+ }
37
+ function recordsDirOf(root) {
38
+ try { const { repoScript } = require('./repo-script.js'); return require(repoScript('signals/layout-paths.js')).pathsFor(root).recordsDir; } catch { return path.join(root, 'planning', 'records'); }
39
+ }
40
+ const missingWords = (r) => (r.marks.length === 2 ? 'no reason, nobody agreed' : r.marks[0] === 'why' ? 'no reason' : 'nobody agreed');
41
+ const lineOf = (r) => ` ${r.id} ${r.customer} · ${r.name} · ${r.on ? 'on' : 'off'} · ${r.why || '—'} · ${r.agreedBy ? r.agreedBy + (r.agreedOn ? ', ' + r.agreedOn : '') : 'nobody'}`
42
+ + (r.marks.length ? ` ! ${missingWords(r)}` : '') + (r.waiting ? ` waits for you: turn ${r.waiting.to}` : '');
43
+
44
+ function run(argv, o = {}) {
45
+ const say = o.say || ((s) => console.log(s)), now = o.now || Date.now();
46
+ const args = argv[0] === 'switches' ? argv.slice(1) : argv.slice();
47
+ const cmd = args[0] || 'list';
48
+ if (cmd === 'help' || cmd === '--help' || cmd === '-h') { USAGE.forEach((l) => say(l)); return 0; }
49
+ if (!COMMANDS.switches.includes(cmd)) { say(`✗ ${cmd} is not a command of pmos switches`); USAGE.forEach((l) => say(l)); return 2; }
50
+ const p = parse(args.slice(1));
51
+ if (p.bad) { say(`✗ ${p.bad} is not an option of pmos switches`); return 2; }
52
+ const { pos, f } = p;
53
+ const root = path.resolve(f.root || o.root || repoOf(o.cwd || process.cwd()));
54
+ const dir = o.dir || recordsDirOf(root);
55
+ const by = o.by || 'cli'; // never 'pm': only the page press is the PM's own turn
56
+ const out = (r, ok) => { if (f.json) say(JSON.stringify(r.ok ? { ok: true, row: r.row } : { ok: false, error: r.error })); else say(r.ok ? ok(r.row) : '✗ ' + r.error); return r.ok ? 0 : 1; };
57
+
58
+ if (cmd === 'list') {
59
+ const rows = read(dir);
60
+ if (f.json) { say(JSON.stringify({ ok: true, switches: rows, marked: rows.filter((r) => r.marks.length).length })); return 0; }
61
+ if (!rows.length) { say('No switch is recorded yet. pmos switches add --customer <name> --switch <name> records one.'); return 0; }
62
+ const m = rows.filter((r) => r.marks.length).length;
63
+ say(`${rows.length} switch${rows.length === 1 ? '' : 'es'}${m ? ` · ${m} without a reason or an approver` : ''}`);
64
+ rows.forEach((r) => say(lineOf(r)));
65
+ return 0;
66
+ }
67
+ if (cmd === 'count') {
68
+ const n = count(dir, { marked: !!f.marked });
69
+ say(`${TAG} ${n} switch${n === 1 ? '' : 'es'}${f.marked ? ' without a reason or an approver' : ' recorded'}.`);
70
+ say(String(n));
71
+ return 0;
72
+ }
73
+ if (cmd === 'add') {
74
+ if (pos.length) { say('✗ usage: pmos switches add --customer <name> --switch <name> [--why <text>] [--agreed-by <person>]'); return 2; }
75
+ return out(add(dir, { ...f, on: !f.off }, { by, now }), (r) => `✓ Recorded ${r.customer} · ${r.name} (${r.id})${r.marks.length ? ` — ${missingWords(r)}, so Work marks it` : ''}.`);
76
+ }
77
+ const id = pos[0];
78
+ if (!id) { say(`✗ usage: pmos switches ${cmd} <id>`); return 2; }
79
+ if (cmd === 'set') return out(set(dir, id, f, { by, now }), (r) => `✓ ${r.customer} · ${r.name}: ${r.why || '—'} · ${r.agreedBy || 'nobody'}. Undo: pmos switches undo ${r.id}`);
80
+ if (cmd === 'undo') return out(undo(dir, id, { by, now }), (r) => `✓ Put back: ${r.customer} · ${r.name}: ${r.why || '—'} · ${r.agreedBy || 'nobody'}.`);
81
+ if (cmd === 'turn') return out(turn(dir, id, pos[1], { by, now }), (r) => `Turning ${r.name} ${r.waiting.to} for ${r.customer} is an outward change, so it waits for you on Work. PMOS turned nothing. Drop the ask: pmos switches cancel ${r.id}`);
82
+ return out(cancel(dir, id, { by, now }), (r) => `✓ The ask on ${r.customer} · ${r.name} is dropped. It stays ${r.on ? 'on' : 'off'}.`);
83
+ }
84
+
85
+ module.exports = { run, COMMANDS, USAGE };