create-pmos 0.597.0 → 0.599.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 +27 -27
  2. package/payload/KIT-VERSION +1 -1
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/scripts/pmos-memory.js +42 -16
  6. package/payload/state/discoveries.md +1 -1
  7. package/workspace/changelog.json +26 -0
  8. package/workspace/guide/cli.md +9 -0
  9. package/workspace/guide/settings-and-switches.md +1 -1
  10. package/workspace/lib/bg-queue.js +1 -0
  11. package/workspace/lib/briefing-premium-agent.js +12 -5
  12. package/workspace/lib/corrections-memory.js +9 -5
  13. package/workspace/lib/cos-chat.js +15 -1
  14. package/workspace/lib/driver.js +4 -1
  15. package/workspace/lib/engine/pmos-memory.js +42 -16
  16. package/workspace/lib/goal-loop.js +2 -1
  17. package/workspace/lib/headless.js +7 -3
  18. package/workspace/lib/job-graph.js +4 -0
  19. package/workspace/lib/owner-cli.js +30 -0
  20. package/workspace/lib/pmos-verbs.js +5 -0
  21. package/workspace/lib/route-modules.js +1 -0
  22. package/workspace/lib/routes-briefing-premium.js +3 -1
  23. package/workspace/lib/routes-home-desk.js +13 -1
  24. package/workspace/lib/routes-proposals.js +1 -1
  25. package/workspace/lib/routes-units.js +52 -0
  26. package/workspace/lib/team-cli.js +16 -1
  27. package/workspace/lib/team-runs.js +5 -2
  28. package/workspace/lib/unit-memory.js +65 -0
  29. package/workspace/lib/unit-owner.js +185 -0
  30. package/workspace/lib/units-cli.js +45 -0
  31. package/workspace/lib/units-host.js +151 -0
  32. package/workspace/lib/units.js +88 -0
  33. package/workspace/package-lock.json +2 -2
  34. package/workspace/package.json +1 -1
  35. package/workspace/public/pm/cozy-schedwork.js +4 -2
  36. package/workspace/public/pm/cozy-settings.js +2 -2
  37. package/workspace/public/pm/cozy-today.css +3 -0
  38. package/workspace/public/pm/home-app.js +13 -1
  39. package/workspace/public/pm/home-list.js +14 -2
  40. package/workspace/public/pm/home-today.js +7 -4
  41. package/workspace/server.js +26 -1
  42. package/workspace/test-files.json +1 -0
@@ -86,7 +86,8 @@ function read(dir) {
86
86
  }
87
87
  function append(dir, line, { now } = {}) {
88
88
  if (!dir) throw new Error('goal-loop: no runtime folder');
89
- const out = { v: 1, at: new Date(now == null ? Date.now() : now).toISOString(), ...line };
89
+ // chief-unit-owners ✦1: a goal's start line carries the unit of its workspace (lib/units.js), so the product's owner folds its rounds
90
+ const out = { v: 1, at: new Date(now == null ? Date.now() : now).toISOString(), ...(line && line.ev === 'start' && line.ws ? require('./units.js').stamp(line, { ws: line.ws }) : line) };
90
91
  fs.mkdirSync(dir, { recursive: true });
91
92
  fs.appendFileSync(file(dir), JSON.stringify(out) + '\n');
92
93
  return out;
@@ -439,7 +439,7 @@ function userModelOf(env) {
439
439
  * ledger's scan blocks, a staged write and a stale entry are left out. A web kind never gets it: it reads untrusted pages and has web
440
440
  * tools, so it holds nothing it could send out. PMOS_RUN_MEMORY=off: no note. */
441
441
  const MEMORY_HEAD = 'What PMOS remembers (curated memory, D72). Follow it unless this run\'s own instructions say otherwise.';
442
- function memoryNote(roots, env) {
442
+ function memoryNote(roots, env, { unit = null, ini = null } = {}) {
443
443
  if (/^(off|0|false|no)$/i.test(String(((env || {}).PMOS_RUN_MEMORY) || '').trim())) return '';
444
444
  let c = null; try { c = require('./memory.js').core(); } catch { return ''; }
445
445
  if (!c || !c.ok) return '';
@@ -448,11 +448,15 @@ function memoryNote(roots, env) {
448
448
  const root = String(r || ''); if (!root || seen.has(root)) continue; seen.add(root);
449
449
  let cur = null; try { cur = c.core.load(root); } catch { cur = null; }
450
450
  if (!cur || !cur.dir || !cur.state || !Array.isArray(cur.state.entries)) continue;
451
- const es = cur.state.entries.filter((e) => e && typeof e.text === 'string' && e.text.trim() && !e.stale && !e.staged);
451
+ // chief-unit-owners ✦4: workspace, then this run's unit, then its initiative; never another unit's or initiative's (scripts/pmos-memory.js scoped)
452
+ const es = typeof c.core.scoped === 'function' ? c.core.scoped(cur.state, { unit, ini })
453
+ : cur.state.entries.filter((e) => e && typeof e.text === 'string' && e.text.trim() && !e.stale && !e.staged);
452
454
  if (!es.length) continue;
453
455
  const line = (e) => '- ' + (e.confidence === 'unconfirmed' ? '(unconfirmed) ' : '') + oneLine(e.text, 600);
454
456
  const user = es.filter((e) => e.target === 'user'), mem = es.filter((e) => e.target !== 'user');
455
- return [MEMORY_HEAD, ...(user.length ? ['About the PM:', ...user.map(line)] : []), ...(mem.length ? ['About the product:', ...mem.map(line)] : [])].join('\n');
457
+ const ws = mem.filter((e) => !e.scope || e.scope === 'workspace'), un = mem.filter((e) => String(e.scope || '').startsWith('unit:')), own = mem.filter((e) => String(e.scope || '').startsWith('initiative:'));
458
+ return [MEMORY_HEAD, ...(user.length ? ['About the PM:', ...user.map(line)] : []), ...(ws.length ? ['About the product:', ...ws.map(line)] : []),
459
+ ...(un.length ? [`Lessons of ${unit}, the unit that owns this work:`, ...un.map(line)] : []), ...(own.length ? [`Lessons of ${ini}:`, ...own.map(line)] : [])].join('\n');
456
460
  }
457
461
  return '';
458
462
  }
@@ -80,6 +80,9 @@ const LEDGERS = Object.freeze({
80
80
  r('lib/routes-ready-reports.js', null, 'Reports: the ready-made reports')] },
81
81
  '<state>/design.jsonl': { concept: 'report-design', owner: 'lib/report-design.js', readers: [
82
82
  r('lib/routes-report-design.js', null, 'the report design studio')] },
83
+ '<state>/units.jsonl': { concept: 'unit-owners', owner: 'lib/unit-owner.js', readers: [
84
+ r('lib/units-host.js', 'O.latest(F)', 'GET /api/units and Home\'s one line per group, from the newest brief of each unit'),
85
+ r('lib/briefing-premium-agent.js', 'briefsBlock', 'the chief\'s opening (Home\'s chat) carries the latest unit briefs')] },
83
86
  '<state>/team.jsonl': { concept: 'role-team', owner: 'lib/team-runs.js', readers: [
84
87
  r('lib/team-cli.js', 'R.status', '`pmos team status`: who works on what, and the inbox entry of each ended dispatch'),
85
88
  r('lib/team-runs.js', 'function advance', 'the next role of a dispatch, and the Evaluator woken by another role\'s write')] },
@@ -151,6 +154,7 @@ const JOBS = Object.freeze([
151
154
  q('report-design', 'lib/routes-report-design.js', ['<state>/design.jsonl']),
152
155
  q('report-structure', 'lib/routes-report-structure.js', ['<state>/structure.jsonl']),
153
156
  q('team', 'lib/team-runs.js', ['<state>/team.jsonl'], ['<state>/team.jsonl', 'initiative records']),
157
+ q('owner', 'lib/unit-owner.js', ['<state>/units.jsonl'], ['<state>/team.jsonl', '<state>/driver.jsonl', '<runtime>/goal-loops.jsonl', 'memory'], 'chief-unit-owners: one brief a day per unit, a fold of the workers\' ledgers; no model, no session'),
154
158
  q('improve', 'lib/improve-runs.js', ['<state>/improve.jsonl', '<state>/autonomy.jsonl', props], ['<state>/improve-signals.jsonl', '<state>/improve.jsonl', 'repo:planning/improve/loop.jsonl'],
155
159
  'step 5; one headless run at a time; a lesson is a curated-memory entry with Undo, a harness change only a ✦'),
156
160
  q('scan', 'lib/scan-run.js', ['<state>/scan.jsonl'], ['public web']),
@@ -0,0 +1,30 @@
1
+ 'use strict';
2
+ /* owner-cli.js — `pmos owner …`: a unit owner's tick (chief-unit-owners ✦2 and ✦3). The owner is a record, never a session
3
+ * (lib/unit-owner.js); these verbs only ask the running workspace to fold its ledgers now .
4
+ *
5
+ * pmos owner brief [<unit>] [--json] run the owner's tick now: one unit writes a fresh brief; no unit, every unit with none today
6
+ * Upkeep with one right answer: the chief (Home's chat) may run `brief` itself. It writes only units.jsonl. Exit codes: 0, 1 refused, 2 usage.
7
+ */
8
+ const COMMANDS = { owner: ['brief'] };
9
+ const USAGE = [
10
+ 'usage: pmos owner brief — a unit owner\'s daily brief',
11
+ ' pmos owner brief [<unit>] fold the unit\'s workers into a fresh brief now (no unit: every unit with no brief today)',
12
+ 'a unit is program:<id>, product:<id> or project:<id> (pmos units lists them) · every command: [--json]',
13
+ ];
14
+
15
+ async function run(argv, { say = (s) => console.log(s), call = async () => null } = {}) {
16
+ const args = argv[0] === 'owner' ? argv.slice(1) : argv.slice();
17
+ const json = args.includes('--json');
18
+ const pos = args.filter((a) => !a.startsWith('--'));
19
+ const verb = pos[0];
20
+ if (!verb || ['help', '-h'].includes(verb) || args.includes('--help')) { for (const l of USAGE) say(l); return verb ? 0 : 1; }
21
+ if (!COMMANDS.owner.includes(verb)) { say(`unknown owner command "${verb}" — one of ${COMMANDS.owner.join(', ')}`); return 2; }
22
+ const out = (r, text) => {
23
+ if (!r || !r.ok) { say(json ? JSON.stringify({ ok: false, error: (r && r.error) || 'no PMOS workspace is running' }) : `✗ ${(r && r.error) || 'no PMOS workspace is running: start it with `pmos`'}`); return 1; }
24
+ say(json ? JSON.stringify(r) : text(r)); return 0;
25
+ };
26
+ const r = await call('POST', '/api/units/tick', pos[1] ? { unit: pos[1] } : {});
27
+ return out(r, (x) => (x.wrote.length ? `brief written for ${x.wrote.join(', ')}` : 'every unit has today\'s brief already') + '. `pmos units` shows them.');
28
+ }
29
+
30
+ module.exports = { run, COMMANDS, USAGE };
@@ -121,6 +121,11 @@ const VERBS = Object.freeze({
121
121
  // Not a pm-os-absorb verb (run: null): initiative outcome-for-every-initiative added it through the same table.
122
122
  outcomes: Object.freeze({ module: 'outcomes-cli.js', run: null, guide: 'cli.md',
123
123
  help: 'pmos outcomes list|propose|declare|record — every initiative\'s expected outcome and check date: Claude\'s cited drafts, the PM\'s yes, and the verdict when a check is due (pmos outcomes help)' }),
124
+ // Not a pm-os-absorb verb (run: null): chief-unit-owners (Wawan 2026-11-18) added both through the same table.
125
+ units: Object.freeze({ module: 'units-cli.js', run: null, guide: 'cli.md',
126
+ help: 'pmos units [list|show <unit>] — the programs, products and projects, who owns each initiative, and each owner\'s brief (pmos units help)' }),
127
+ owner: Object.freeze({ module: 'owner-cli.js', run: null, guide: 'cli.md',
128
+ help: 'pmos owner brief|budget — a unit owner\'s daily brief now, and its Driver runs a day (pmos owner help)' }),
124
129
  driver: Object.freeze({ module: 'driver-cli.js', run: null, guide: 'cli.md',
125
130
  help: 'pmos driver propose|status|keep|return|drop|undo|pause|resume|mode … — the Initiative Driver: class A and B changes apply with Undo, the rest wait for you (pmos driver help)' }),
126
131
  // D106 (Full autonomy now): what agents do by themselves, and the goals they work on until done
@@ -60,6 +60,7 @@ const MODULES = Object.freeze([
60
60
  'routes-forecast', // build brief Grill and Forecast F-A: a goal forecast's kept baseline, and the forecasts that turned
61
61
  'routes-morning-goals', // build brief Good morning GM1: the quarter strip, the PM's line, the morning snapshot, goal tags, what Yes does
62
62
  'routes-grill', // Grill and Forecast screens: Claude's checks for the pages (mode, cap, spend, each initiative's last run, Home's one line; read-only)
63
+ 'routes-units', // chief-unit-owners: the units, their owners' briefs, a tick on demand and a unit's runs a day
63
64
  'routes-home-desk', // premium-agreed-design (Home): seen marks, queued messages, the weekly update's recipients and sends, stakeholders (page press; file mode)
64
65
  'routes-live', // batch 6 item 2: the Live pill's sessions and the titles of their initiatives (read-only)
65
66
  'routes-home-review', // premium-uncovered-features (Home): the weekly review's four steps and the untouched work looked at (page press; file mode)
@@ -183,7 +183,9 @@ async function post(req, res, url, ctx) {
183
183
  // batch 20 item 13: the PM can start a grill any time by asking for it in an initiative's chat; it also runs by itself
184
184
  // the live round: "show 3 ways" or feedback on a round that waits (lib/live-round.js); a grill ask comes first
185
185
  const g2 = grillAsk(ctx, b.key, b.text, wsId) || liveAsk(ctx, b.key, b.text, wsId, att.paths);
186
- const a = (ctx.chatSessions ? Ag.chat : Ag.ask)({ runtimeDir, key: b.key, text: Files.withFiles(g2 ? g2.text : b.text, att.paths), context: b.context, sessions: ctx.chatSessions, reportInfo: () => reportInfoOf(ctx, wsId, b.report), model: /^work:/.test(String(b.key || '')) ? WP.peekModel() : /^board:/.test(String(b.key || '')) ? BoardP.peekModel() : /^ins:/.test(String(b.key || '')) ? InsP.peekModel() : /^(init|doc):/.test(String(b.key || '')) ? InitP.peekModel() : sk || (/^src:/.test(String(b.key || '')) && !(b.key === 'src:this-page' && url.searchParams.get('ws'))) ? Prod.peekModel() : BP.peekModel(root), spawnSession: ctx.spawnSession, wsId, iniInfo: () => iniInfoOf(ctx, b.key, wsId) });
186
+ const a = (ctx.chatSessions ? Ag.chat : Ag.ask)({ runtimeDir, key: b.key, text: Files.withFiles(g2 ? g2.text : b.text, att.paths), context: b.context, sessions: ctx.chatSessions, reportInfo: () => reportInfoOf(ctx, wsId, b.report), model: /^work:/.test(String(b.key || '')) ? WP.peekModel() : /^board:/.test(String(b.key || '')) ? BoardP.peekModel() : /^ins:/.test(String(b.key || '')) ? InsP.peekModel() : /^(init|doc):/.test(String(b.key || '')) ? InitP.peekModel() : sk || (/^src:/.test(String(b.key || '')) && !(b.key === 'src:this-page' && url.searchParams.get('ws'))) ? Prod.peekModel() : BP.peekModel(root), spawnSession: ctx.spawnSession, wsId, iniInfo: () => iniInfoOf(ctx, b.key, wsId),
187
+ // chief-unit-owners ✦3: the chief's opening carries every unit's newest brief; an initiative chat's, its unit's brief and lessons
188
+ unitsInfo: () => (ctx.unitsHost ? { chief: ctx.unitsHost.chiefLines(), ofIni: (ini) => ctx.unitsHost.iniLines(wsId, ini), ofUnit: (k) => ctx.unitsHost.unitLines(k) } : null) });
187
189
  // a prototype round the sentence started: the page opens it in the Viewer (pm/home-app.js iniTarget onSent)
188
190
  ctx.json(res, g2 && g2.live && a.body && a.body.ok ? { ...a.body, live: g2.live } : a.body, a.status);
189
191
  return true;
@@ -2,7 +2,8 @@
2
2
  /* routes-home-desk.js — the records Home's desk reads and the PM's presses on it (initiative premium-agreed-design, Home).
3
3
  *
4
4
  * GET /api/home-desk?ws=<id>
5
- * → { ok, roles, seen, product: { recipients, sent }, stakeholders: { [initiative]: [person] }, queued: { [session]: [entry] } }
5
+ * → { ok, roles, seen, product: { recipients, sent }, stakeholders: { [initiative]: [person] }, queued: { [session]: [entry] },
6
+ * units: { [unit key]: { line, done, forYou, failed } } } the owners' brief lines Home shows on each group (lib/unit-owner.js)
6
7
  * POST /api/home-desk/seen { key, at? } the PM looked at a conversation: the "New since you left" marker
7
8
  * POST /api/home-desk/recipients { ws, to: [string] } who the product's weekly update goes to
8
9
  * POST /api/home-desk/update-sent { ws, week, to: [string], subject } the PM sent the weekly update from their own mail (a mailto draft)
@@ -36,6 +37,15 @@ function stateDir(ctx, w) {
36
37
  try { d = ctx.stateDirFor ? ctx.stateDirFor(w, { create: true }) : null; } catch { d = null; }
37
38
  return d || (w && w.root ? path.join(w.root, 'pmos', 'state') : null);
38
39
  }
40
+ /** { [unit key]: { line, failed: [{ ini, why }] } } for the units whose newest brief has something to say (lib/unit-owner.js lineOf). */
41
+ function unitLines(ctx) {
42
+ if (!ctx.unitsHost) return {};
43
+ try {
44
+ const st = ctx.unitsHost.state(), out = {};
45
+ for (const [k, b] of Object.entries(st.latest || {})) if (b.line) out[k] = { line: b.line, done: b.done || 0, forYou: b.forYou || 0, failed: b.failed || [] };
46
+ return out;
47
+ } catch { return {}; }
48
+ }
39
49
  const read = (f) => { try { return pmItems.readLines(f).filter(Boolean); } catch { return []; } };
40
50
 
41
51
  /** The last seen mark per conversation key. Pure over the lines. */
@@ -109,6 +119,8 @@ module.exports = {
109
119
  product: sd ? foldProduct(read(path.join(sd, 'product-updates.jsonl')), w.id) : { recipients: [], sent: [] },
110
120
  stakeholders: sd ? foldStakeholders(read(path.join(sd, 'stakeholders.jsonl'))) : {},
111
121
  ws: w ? w.id : null,
122
+ // chief-unit-owners ✦2: one quiet line per program and product group, from each unit's newest brief; zero is silence
123
+ units: unitLines(ctx),
112
124
  });
113
125
  return true;
114
126
  }
@@ -461,7 +461,7 @@ const WRITES = {
461
461
  try { const AF = require('./artefacts.js'); AF.set(AF.file(dirOf(ctx, p.w)), { scope: 'experiment:' + ini, artefact: 'lessons', field: 'line', text: `✕ dropped "${String(of.title || '').slice(0, 140)}"${why ? ': ' + why : ''}`, sources: [{ label: 'live round' }] }, { by: g.actor && /^(pm|agent):/.test(String(g.actor.by)) ? g.actor.by : 'agent:live-round' }); } catch { /* the drop line holds it */ }
462
462
  }
463
463
  // the reason becomes curated memory by itself, so every later run knows it (lib/corrections-memory.js)
464
- if (why) require('./corrections-memory.js').remember(p.w.root, { what: `a ${(of && (of.group || of.type)) || ''} proposal on ${ini}`.replace(/ +/g, ' '), why, source: 'proposal:' + (which.id || sig) });
464
+ if (why) require('./corrections-memory.js').remember(p.w.root, { what: `a ${(of && (of.group || of.type)) || ''} proposal on ${ini}`.replace(/ +/g, ' '), why, source: 'proposal:' + (which.id || sig), ini });
465
465
  ctx.json(res, { ok: true });
466
466
  },
467
467
  '/api/proposals/undo': (ctx, res, body, g, p) => {
@@ -0,0 +1,52 @@
1
+ 'use strict';
2
+ /* routes-units.js — the units (Program, Product, Project) and their owners' briefs (chief-unit-owners ✦2 and ✦3).
3
+ *
4
+ * GET /api/units → { ok, units: [{ key, kind, id, title, initiatives: n, line, day, forYou, done, failed, next }] }
5
+ * POST /api/units/tick { unit? } → { ok, wrote: [key], skipped: [key] } run the owner's tick now: one unit (a new brief even when today
6
+ * has one) or every unit that has none today. `pmos owner brief` calls it; it is upkeep with one right
7
+ * answer, so the chief may run it from chat (lib/cos-chat.js). It writes only units.jsonl.
8
+ * POST /api/units/dispatch { unit, roles? } the role agents for the unit's first open initiative (Roadmap order) with no dispatch running
9
+ * POST /api/units/pause { unit, on } hold (on) or restart (on: false) every role run on the unit's initiatives
10
+ * Both are `pmos team dispatch|pause|resume --unit`, which the chief may run from chat. They write team.jsonl lines only.
11
+ * The host is lib/units-host.js (ctx.unitsHost). File mode only (D64/D66). Nothing here merges, sends, or writes a control-graph record.
12
+ */
13
+ const U = require('./units.js');
14
+
15
+ async function handle(req, res, url, ctx) {
16
+ const H = ctx.unitsHost;
17
+ if (!H) { ctx.json(res, { ok: false, error: 'units are not available in this server' }, 503); return true; }
18
+ const p = url.pathname;
19
+ if (req.method === 'GET' && p === '/api/units') {
20
+ const st = H.state();
21
+ const units = st.units.map((u) => {
22
+ const b = st.latest[u.key] || {};
23
+ return { key: u.key, kind: u.kind, id: u.id, title: u.title, ...(u.ws ? { ws: u.ws } : {}), initiatives: u.initiatives.length,
24
+ line: b.line || '', day: b.day || '', done: b.done || 0, forYou: b.forYou || 0, failed: b.failed || [], next: b.next || '' };
25
+ });
26
+ ctx.json(res, { ok: true, units });
27
+ return true;
28
+ }
29
+ if (req.method === 'POST' && (p === '/api/units/dispatch' || p === '/api/units/pause')) {
30
+ const r = await ctx.readJson(req);
31
+ const body = (r && r.ok && r.body) || {};
32
+ const unit = String(body.unit || '');
33
+ if (!U.parseKey(unit)) { ctx.json(res, { ok: false, error: 'a unit is program:<id>, product:<id> or project:<id> (pmos units lists them)' }, 400); return true; }
34
+ const roles = Array.isArray(body.roles) && body.roles.length ? body.roles.map(String) : null;
35
+ const out = p === '/api/units/dispatch' ? H.dispatch(unit, { roles }) : H.pause(unit, body.on !== false);
36
+ ctx.json(res, out, out.ok ? 200 : 409);
37
+ return true;
38
+ }
39
+ if (req.method === 'POST' && p === '/api/units/tick') {
40
+ const r = await ctx.readJson(req);
41
+ const body = (r && r.ok && r.body) || {};
42
+ const unit = body.unit ? String(body.unit) : null;
43
+ if (unit && !U.parseKey(unit)) { ctx.json(res, { ok: false, error: 'a unit is program:<id>, product:<id> or project:<id> (pmos units lists them)' }, 400); return true; }
44
+ if (unit && !H.units().some((u) => u.key === unit)) { ctx.json(res, { ok: false, error: `no unit ${unit} (pmos units lists them)` }, 404); return true; }
45
+ const out = H.tick({ only: unit, force: !!unit });
46
+ ctx.json(res, { ok: !out.error, ...out }, out.error ? 409 : 200);
47
+ return true;
48
+ }
49
+ return false;
50
+ }
51
+
52
+ module.exports = { prefixes: ['/api/units'], handle };
@@ -6,6 +6,7 @@
6
6
  * pmos team dispatch --goal "<goal in words>" [--roles a,b]
7
7
  * pmos team status [--json] who works on what, what waits, and the inbox entries of ended dispatches
8
8
  * pmos team pause|resume <role|all> stop or restart a role's runs (a running run ends on its own)
9
+ * pmos team dispatch --unit <unit> [--roles a,b] · pmos team pause|resume --unit <unit> the same for a whole unit (chief-unit-owners ✦3)
9
10
  * common: [--root <dir>]
10
11
  *
11
12
  * INSIDE A ROLE RUN only (the server pins PMOS_TEAM_RUN, _ROLE, _FILE, _ROOT, _INI, _MODE; nothing here takes them as arguments):
@@ -28,6 +29,7 @@ const USAGE = [
28
29
  ' pmos team dispatch --goal "<goal>" [--roles …] the same for a goal in words (Strategist, Researcher, Evaluator)',
29
30
  ' pmos team status who works on what, what waits, and the inbox entries of ended dispatches',
30
31
  ' pmos team pause|resume <role|all> stop or restart a role\'s runs',
32
+ ' pmos team dispatch --unit <unit> · pmos team pause|resume --unit <unit> the same for a whole program, product or project (pmos units)',
31
33
  'Inside a role run: pmos team wrote <path> · pmos team done "<summary>" [--propose <path> "<what>"] · pmos team verdict <path> pass|fail "<why>"',
32
34
  'every command: [--json] [--root <dir>]',
33
35
  ];
@@ -50,7 +52,7 @@ function repoRoot(cwd) {
50
52
  catch { return cwd; }
51
53
  }
52
54
 
53
- async function run(argv, { say = (s) => console.log(s), env = process.env, cwd = process.cwd(), now = Date.now() } = {}) {
55
+ async function run(argv, { say = (s) => console.log(s), env = process.env, cwd = process.cwd(), now = Date.now(), call = async () => null } = {}) {
54
56
  const args = argv[0] === 'team' ? argv.slice(1) : argv.slice();
55
57
  const verb = args[0];
56
58
  if (!verb || ['help', '--help', '-h'].includes(verb)) { for (const l of USAGE) say(l); return verb ? 0 : 1; }
@@ -95,6 +97,19 @@ async function run(argv, { say = (s) => console.log(s), env = process.env, cwd =
95
97
  return 0;
96
98
  }
97
99
 
100
+ // chief-unit-owners ✦3: `--unit <unit>` acts on a whole Program, Product or Project through the running workspace (lib/routes-units.js),
101
+ // which knows every workspace the unit's initiatives live in
102
+ if (typeof flags.unit === 'string' && (verb === 'dispatch' || verb === 'pause' || verb === 'resume')) {
103
+ if (!flags.unit) return fail('name the unit: program:<id>, product:<id> or project:<id> (pmos units lists them)', 2);
104
+ const roles = typeof flags.roles === 'string' && flags.roles ? flags.roles.split(',').map((x) => x.trim()).filter(Boolean) : null;
105
+ if (roles) for (const k of roles) if (!T.roleOf(k)) return fail(`"${k}" is not a role (${Object.keys(T.TEAM).join(', ')})`, 2);
106
+ const r = verb === 'dispatch' ? await call('POST', '/api/units/dispatch', { unit: flags.unit, ...(roles ? { roles } : {}) })
107
+ : await call('POST', '/api/units/pause', { unit: flags.unit, on: verb === 'pause' });
108
+ if (!r) return fail('no PMOS workspace is running: start it with `pmos`');
109
+ if (!r.ok) return fail(r.error || 'refused');
110
+ return verb === 'dispatch' ? ok(r, `dispatched ${r.id} on ${r.initiative} for ${r.unit}: ${r.roles.join(' → ')}`)
111
+ : ok(r, `${verb === 'pause' ? '⏸ paused' : '▶ resumed'} the role runs of ${r.unit}`);
112
+ }
98
113
  if (verb === 'pause' || verb === 'resume') {
99
114
  const k = String(pos[0] || '');
100
115
  if (!k || (k !== 'all' && !T.roleOf(k))) return fail(`name a role (${Object.keys(T.TEAM).join(', ')}) or all`, 2);
@@ -20,7 +20,7 @@
20
20
  * result { kind: 'result', run, role, summary, at } `pmos team done`: what the run did, in one line
21
21
  * verdict { kind: 'verdict', run, rel, verdict: 'pass'|'fail', why, of: { run, role }, at } `pmos team verdict` (Evaluator only)
22
22
  * inbox { kind: 'inbox', dispatch, title, items: [{ role, summary, wrote, proposed, verdicts }], at } the one entry a dispatch ends in
23
- * pause { kind: 'pause', role: key|'all', on: bool, at } `pmos team pause|resume`
23
+ * pause { kind: 'pause', role: key|'all'|'unit:<kind>:<id>', on: bool, at } `pmos team pause|resume` (a unit: `--unit`, chief-unit-owners)
24
24
  *
25
25
  * THE RUNNER (the bg-queue job `team`, step 4, once a minute):
26
26
  * 1. a dispatch's steps run in ORDER, one after the other: a step is queued only when the step before it ended. Handoffs go through the
@@ -48,7 +48,8 @@ const newId = (p, now) => p + now.toString(36) + crypto.randomBytes(3).toString(
48
48
  function append(dir, line, now = Date.now()) {
49
49
  if (!dir) throw new Error('team-runs: no state folder');
50
50
  fs.mkdirSync(dir, { recursive: true });
51
- const l = { at: new Date(now).toISOString(), ...line };
51
+ // chief-unit-owners ✦1: a line about an initiative carries the unit that owns it (lib/units.js), so the owner's tick folds it
52
+ const l = { at: new Date(now).toISOString(), ...(line && line.ini && line.ws ? require('./units.js').stamp(line, { ws: line.ws, ini: line.ini }) : line) };
52
53
  fs.appendFileSync(file(dir), JSON.stringify(l) + '\n');
53
54
  return l;
54
55
  }
@@ -275,6 +276,8 @@ function create(deps) {
275
276
  for (const s of F.steps) {
276
277
  if (s.state !== 'queued' && s.state !== 'held') continue;
277
278
  if (F.paused.has('all') || F.paused.has(s.role)) continue;
279
+ // chief-unit-owners ✦3: `pmos team pause --unit <unit>` holds every role run on that unit's initiatives (the step carries its unit)
280
+ if (s.unit && s.unit.kind && F.paused.has(`unit:${s.unit.kind}:${s.unit.id}`)) continue;
278
281
  if (active.has(s.id)) continue;
279
282
  start(w, dir, F, s, now);
280
283
  }
@@ -0,0 +1,65 @@
1
+ 'use strict';
2
+ /* unit-memory.js — a unit's lessons: promote on repetition (chief-unit-owners ✦4; doc GCFCo233wHawPk7Ypjba4J "How memory is kept across
3
+ * the whole workspace", agreed by Wawan 2026-11-18).
4
+ *
5
+ * One ledger (D72, scripts/pmos-memory.js), three scopes: workspace, unit:<kind>:<id>, initiative:<id>. Runs write what they learn at
6
+ * initiative scope (lib/corrections-memory.js). The unit owner's daily tick (lib/unit-owner.js) calls promote(): a lesson that appears on
7
+ * TWO of the unit's initiatives is written once at the unit's scope, unconfirmed, with both sources, so every run on the unit reads it.
8
+ *
9
+ * lessonKey(text) → string what two entries must share to be one lesson: the PM's quoted reason when there is one, else the text,
10
+ * lower case, with no initiative id and no punctuation. Deterministic, no model: equal words, not meaning.
11
+ * repeats(entries, inis) → [{ text, sources: [ini] }] PURE. entries: the ledger's entries; inis: the unit's initiative ids
12
+ * promote(host, unit, { now? }) → [{ text, sources }] writes each new unit lesson to memory; returns them for units.jsonl (its notebook)
13
+ * A unit lesson seen in two units becomes a ✦ for the PM to make it a workspace rule; the chief files it (lib/cos-chat.js RULE).
14
+ */
15
+ const DAY = 86400000;
16
+ const BY = 'agent:unit-owner';
17
+ const STALE_DAYS = 90;
18
+
19
+ const norm = (s) => String(s || '').toLowerCase().replace(/[^a-z0-9 ]+/g, ' ').replace(/\s+/g, ' ').trim();
20
+ function lessonKey(text, inis = []) {
21
+ const t = String(text || '');
22
+ const q = /"([^"]{8,})"/.exec(t);
23
+ let k = norm(q ? q[1] : t);
24
+ for (const id of inis) if (id) k = k.split(norm(id)).join(' ');
25
+ return k.replace(/\s+/g, ' ').trim();
26
+ }
27
+
28
+ function repeats(entries, inis) {
29
+ const mine = new Set(inis || []);
30
+ const by = new Map();
31
+ for (const e of entries || []) {
32
+ const m = /^initiative:(.+)$/.exec(String(e && e.scope || ''));
33
+ if (!m || !mine.has(m[1]) || e.stale || e.aged || e.staged) continue;
34
+ const k = lessonKey(e.text, [...mine]);
35
+ if (k.length < 8) continue;
36
+ const g = by.get(k) || by.set(k, { text: e.text, sources: [] }).get(k);
37
+ if (!g.sources.includes(m[1])) g.sources.push(m[1]);
38
+ }
39
+ return [...by.values()].filter((g) => g.sources.length >= 2);
40
+ }
41
+
42
+ /** Root of the repository whose memory the unit reads: the home workspace's (the ledger travels with Sync). */
43
+ function promote(host, unit, { root = null, now = Date.now() } = {}) {
44
+ let c = null; try { c = require('./memory.js').core(); } catch { return []; }
45
+ if (!c || !c.ok) return [];
46
+ const M = c.core;
47
+ const r = root || (host && host.memoryRoot ? host.memoryRoot() : null);
48
+ if (!r) return [];
49
+ const key = `${unit.kind}:${unit.id}`;
50
+ const inis = (unit.initiatives || []).map((x) => x.ini);
51
+ const st = M.load(r).state;
52
+ const have = new Set(st.entries.filter((e) => e.scope === 'unit:' + key).map((e) => lessonKey(e.text, inis)));
53
+ const out = [];
54
+ for (const g of repeats(st.entries, inis)) {
55
+ const k = lessonKey(g.text, inis);
56
+ if (have.has(k)) continue;
57
+ const text = `Seen on ${g.sources.slice(0, 3).join(' and ')}: ${String(g.text).replace(/\s+/g, ' ').slice(0, 480)}`;
58
+ const w = M.write(r, { op: 'add', target: 'memory', scope: 'unit:' + key, text, by: BY, confidence: 'unconfirmed',
59
+ source: 'initiatives:' + g.sources.slice(0, 4).join(','), stale_after: new Date(now + STALE_DAYS * DAY).toISOString() });
60
+ if (w.ok) { have.add(k); out.push({ text, sources: g.sources }); }
61
+ }
62
+ return out;
63
+ }
64
+
65
+ module.exports = { BY, lessonKey, repeats, promote };
@@ -0,0 +1,185 @@
1
+ 'use strict';
2
+ /* unit-owner.js — the owner of a Program, Product or Project: a RECORD with a daily tick, never a session (chief-unit-owners ✦2;
3
+ * grill doc GCFCo233wHawPk7Ypjba4J "Improved plan", agreed by Wawan 2026-11-18 "Build now").
4
+ *
5
+ * Which unit owns an initiative is lib/units.js. This file is what the owner keeps and how it reports up: one brief a day, which the chief
6
+ * (Home's chat, lib/cos-chat.js) reads in its opening and Home shows as one quiet line on the unit's group. Reporting up is that one thing.
7
+ *
8
+ * LEDGER = 'units.jsonl' in the home workspace's state folder. Append-only; THIS FILE IS ITS ONE WRITER.
9
+ * append(dir, line, now?) · read(dir) → [line]
10
+ * fold(lines) → Map(unit key → { key, plan: [ini], lessons: [{ text, sources, at }], briefs: [brief] }) briefs oldest first
11
+ * eventsFor(unit, { team, driver, loops }, since) → { events: [{ ini, state: 'done'|'failed', what, why, at }], forYou } PURE
12
+ * team: [{ ws, lines }] team.jsonl lines (lib/team-runs.js): a role run's step that ended done or failed
13
+ * driver: [{ ws, state }] lib/driver.js fold(): a Driver run that ended, and the open proposals that wait on the PM (forYou)
14
+ * loops: [{ ws, lines }] goal-loops.jsonl lines (lib/goal-loop.js): a round that ended, counted on the goal's product
15
+ * briefOf({ events, forYou, plan }) → { done, forYou, failed: [{ ini, why }], items: [{ ini, what }], next } PURE
16
+ * tick(dir, { units, gather, rankedOf?, promote?, now?, only?, force? }) → { wrote: [key], skipped: [key] }
17
+ * units: lib/units.js list(). gather(unit, sinceIso) → eventsFor's result. rankedOf(unit) → [ini] in Roadmap order (D105).
18
+ * promote(unit) → [{ text, sources }] lessons to note (✦4, lib/unit-memory.js). Once a day per unit; `only` + `force` is the chief's
19
+ * "run it now" (`pmos owner brief <unit>`). A restart mid-tick resumes: a unit that has today's brief is skipped, so no brief doubles.
20
+ * lineOf(brief) → '3 done · 1 for you' | '' zero is silence (design principles): no brief, or nothing done and nothing for you, says nothing
21
+ * latest(F) → { [key]: { line, day, at, done, forYou, failed, next } } the newest brief of every unit (Home and the chief)
22
+ * openingLines(F, units, { cap }) → [string] the chief's opening: one line per unit with a brief, newest first
23
+ *
24
+ * THE LINES (append-only, { at, kind, unit, … }):
25
+ * plan { unit, ranked: [ini] } the unit's initiatives in Roadmap order (derived at each tick; written only when it changed)
26
+ * lesson { unit, text, sources: [ini] } a lesson seen on two of the unit's initiatives (✦4); its notebook
27
+ * brief { unit, day, since, done, forYou, failed: [{ ini, why }], items: [{ ini, what }], next }
28
+ *
29
+ * A FAILED RUN IS NOT THE PM'S WORK (R4). It counts under done with its reason; `forYou` is only what waits on the PM's ✓ (open proposals).
30
+ * The tick reads ledgers and writes this ledger: no model, no session, nothing that merges, sends or touches a control-graph record (D65).
31
+ */
32
+ const fs = require('fs');
33
+ const path = require('path');
34
+
35
+ const LEDGER = 'units.jsonl';
36
+ const KINDS = Object.freeze(['plan', 'lesson', 'brief']);
37
+ const DAY = 86400000;
38
+ const one = (s, n) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim().slice(0, n);
39
+ const file = (dir) => path.join(dir, LEDGER);
40
+
41
+ function localDay(ms) {
42
+ const d = new Date(ms), p = (n) => String(n).padStart(2, '0');
43
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
44
+ }
45
+
46
+ function append(dir, line, now = Date.now()) {
47
+ if (!dir) throw new Error('unit-owner: no state folder');
48
+ if (!line || !KINDS.includes(line.kind) || !line.unit) throw new Error('unit-owner: a line needs a kind and a unit');
49
+ fs.mkdirSync(dir, { recursive: true });
50
+ const l = { at: new Date(now).toISOString(), ...line };
51
+ fs.appendFileSync(file(dir), JSON.stringify(l) + '\n');
52
+ return l;
53
+ }
54
+ function read(dir) {
55
+ let text = '';
56
+ try { text = fs.readFileSync(file(dir), 'utf8'); } catch { return []; }
57
+ const out = [];
58
+ for (const raw of text.split('\n')) { if (!raw.trim()) continue; try { const l = JSON.parse(raw); if (l && KINDS.includes(l.kind) && l.unit) out.push(l); } catch { /* a torn line */ } }
59
+ return out;
60
+ }
61
+
62
+ function fold(lines) {
63
+ const F = new Map();
64
+ const get = (key) => F.get(key) || F.set(key, { key, plan: [], lessons: [], briefs: [] }).get(key);
65
+ for (const l of lines || []) {
66
+ const u = get(String(l.unit));
67
+ if (l.kind === 'plan' && Array.isArray(l.ranked)) u.plan = l.ranked.map(String);
68
+ else if (l.kind === 'lesson' && l.text) { if (!u.lessons.some((x) => x.text === l.text)) u.lessons.push({ text: String(l.text), sources: Array.isArray(l.sources) ? l.sources : [], at: l.at }); }
69
+ else if (l.kind === 'brief' && l.day) u.briefs.push({ day: l.day, at: l.at, since: l.since || null, done: +l.done || 0, forYou: +l.forYou || 0,
70
+ failed: Array.isArray(l.failed) ? l.failed : [], items: Array.isArray(l.items) ? l.items : [], next: l.next || '' });
71
+ }
72
+ return F;
73
+ }
74
+
75
+ /** The workers' ended runs on the unit's initiatives since `since`, and what waits on the PM there now. */
76
+ function eventsFor(unit, { team = [], driver = [], loops = [] } = {}, since = null) {
77
+ const mine = new Set((unit.initiatives || []).map((x) => `${x.ws}:${x.ini}`));
78
+ const key = `${unit.kind}:${unit.id}`;
79
+ const after = (at) => !since || String(at || '') > String(since);
80
+ const ours = (ws, ini, u) => (u && u.kind ? `${u.kind}:${u.id}` === key : mine.has(`${ws}:${ini}`));
81
+ const events = [];
82
+ for (const { ws, lines } of team) {
83
+ const last = new Map(); // a later step line for the same id replaces the earlier one (lib/team-runs.js fold)
84
+ for (const l of lines || []) if (l && l.kind === 'step' && l.id) last.set(l.id, { ...(last.get(l.id) || {}), ...l });
85
+ const result = new Map();
86
+ for (const l of lines || []) if (l && l.kind === 'result' && l.run) result.set(l.run, l.summary);
87
+ for (const s of last.values()) {
88
+ if ((s.state !== 'done' && s.state !== 'failed') || !after(s.at) || !s.ini || !ours(s.ws || ws, s.ini, s.unit)) continue;
89
+ events.push({ ini: s.ini, state: s.state, what: one(result.get(s.id) || `${s.role || 'a role'} run`, 160), why: s.state === 'failed' ? one(s.why || 'the run failed', 160) : '', at: s.at });
90
+ }
91
+ }
92
+ let forYou = 0;
93
+ for (const { ws, state } of driver) {
94
+ if (!state) continue;
95
+ for (const r of state.runs ? state.runs.values() : []) {
96
+ if (!r.end || !after(r.end) || !r.target || r.target.kind !== 'initiative' || !ours(r.target.ws || ws, r.target.id, null)) continue;
97
+ events.push({ ini: r.target.id, state: r.ok ? 'done' : 'failed', what: 'Driver run', why: r.ok ? '' : one(r.reason || 'the run failed', 160), at: r.end });
98
+ }
99
+ for (const id of state.order || []) {
100
+ const p = state.proposals.get(id);
101
+ if (p && p.state === 'open' && p.target && p.target.kind === 'initiative' && ours(p.target.ws || ws, p.target.id, null)) forYou++;
102
+ }
103
+ }
104
+ if (unit.kind === 'product') {
105
+ for (const { ws, lines } of loops) {
106
+ if (ws && ws !== unit.id) continue;
107
+ const wsOf = new Map(), goalOf = new Map();
108
+ for (const l of lines || []) if (l && l.ev === 'start') { wsOf.set(l.id, l.ws); goalOf.set(l.id, l.goal); }
109
+ for (const l of lines || []) {
110
+ if (!l || l.ev !== 'round-end' || !after(l.at) || wsOf.get(l.id) !== unit.id) continue;
111
+ events.push({ ini: '', state: l.ok === false ? 'failed' : 'done', what: one(`a round of the goal "${goalOf.get(l.id) || l.id}"`, 160), why: l.ok === false ? one(l.reason || 'the round failed', 160) : '', at: l.at });
112
+ }
113
+ }
114
+ }
115
+ events.sort((a, b) => String(a.at).localeCompare(String(b.at)));
116
+ return { events, forYou };
117
+ }
118
+
119
+ function briefOf({ events = [], forYou = 0, plan = [] } = {}) {
120
+ const failed = events.filter((e) => e.state === 'failed').map((e) => ({ ini: e.ini || '', why: e.why || 'the run failed' })).slice(0, 8);
121
+ const items = events.filter((e) => e.state === 'done').map((e) => ({ ini: e.ini || '', what: e.what || '' })).slice(-12);
122
+ const touched = new Set(events.map((e) => e.ini).filter(Boolean));
123
+ const next = (plan || []).find((x) => !touched.has(x)) || (plan || [])[0] || '';
124
+ return { done: events.length, forYou: Math.max(0, forYou | 0), failed, items, next };
125
+ }
126
+
127
+ function tick(dir, { units = [], gather, rankedOf = null, promote = null, now = Date.now(), only = null, force = false } = {}) {
128
+ const out = { wrote: [], skipped: [] };
129
+ if (!dir || typeof gather !== 'function') return out;
130
+ const day = localDay(now);
131
+ let F = fold(read(dir));
132
+ for (const unit of units) {
133
+ const key = `${unit.kind}:${unit.id}`;
134
+ if (only && key !== only) continue;
135
+ const have = F.get(key);
136
+ const last = have && have.briefs.length ? have.briefs[have.briefs.length - 1] : null;
137
+ if (!force && last && last.day === day) { out.skipped.push(key); continue; }
138
+ let plan = (unit.initiatives || []).map((x) => x.ini);
139
+ if (rankedOf) { try { const r = rankedOf(unit); if (Array.isArray(r)) { const set = new Set(plan); plan = r.filter((x) => set.has(x)).concat(plan.filter((x) => !r.includes(x))); } } catch { /* the unit's own order */ } }
140
+ if (!have || JSON.stringify(have.plan) !== JSON.stringify(plan)) append(dir, { kind: 'plan', unit: key, ranked: plan }, now);
141
+ if (promote) {
142
+ let ls = []; try { ls = promote(unit) || []; } catch { ls = []; }
143
+ for (const x of ls) if (x && x.text && !(have && have.lessons.some((y) => y.text === x.text))) append(dir, { kind: 'lesson', unit: key, text: one(x.text, 600), sources: (x.sources || []).slice(0, 8) }, now);
144
+ }
145
+ const since = last ? last.at : new Date(now - DAY).toISOString();
146
+ let g = { events: [], forYou: 0 };
147
+ try { g = gather(unit, since) || g; } catch { /* an unreadable ledger: an empty brief, said once */ }
148
+ append(dir, { kind: 'brief', unit: key, day, since, ...briefOf({ events: g.events, forYou: g.forYou, plan }) }, now);
149
+ out.wrote.push(key);
150
+ F = fold(read(dir));
151
+ }
152
+ return out;
153
+ }
154
+
155
+ function lineOf(b) {
156
+ if (!b) return '';
157
+ const parts = [];
158
+ if (b.done) parts.push(`${b.done} done`);
159
+ if (b.forYou) parts.push(`${b.forYou} for you`);
160
+ return parts.join(' · ');
161
+ }
162
+ function latest(F) {
163
+ const out = {};
164
+ for (const [key, u] of F || []) {
165
+ const b = u.briefs[u.briefs.length - 1];
166
+ if (!b) continue;
167
+ out[key] = { line: lineOf(b), day: b.day, at: b.at, done: b.done, forYou: b.forYou, failed: b.failed, next: b.next };
168
+ }
169
+ return out;
170
+ }
171
+ function openingLines(F, units = [], { cap = 8 } = {}) {
172
+ const title = new Map(units.map((u) => [u.key || `${u.kind}:${u.id}`, u.title]));
173
+ const rows = [];
174
+ for (const [key, u] of F || []) {
175
+ const b = u.briefs[u.briefs.length - 1];
176
+ if (!b || (units.length && !title.has(key))) continue;
177
+ const bits = [lineOf(b) || 'nothing new'];
178
+ if (b.failed.length) bits.push(`failed: ${b.failed.slice(0, 3).map((f) => (f.ini ? f.ini + ' — ' : '') + f.why).join('; ')}`);
179
+ if (b.next) bits.push(`next: ${b.next}`);
180
+ rows.push({ at: b.at, text: `- ${title.get(key) || key} (${key}), ${b.day}: ${bits.join('; ')}` });
181
+ }
182
+ return rows.sort((a, b) => String(b.at).localeCompare(String(a.at))).slice(0, cap).map((r) => r.text);
183
+ }
184
+
185
+ module.exports = { LEDGER, KINDS, localDay, append, read, fold, eventsFor, briefOf, tick, lineOf, latest, openingLines };
@@ -0,0 +1,45 @@
1
+ 'use strict';
2
+ /* units-cli.js — `pmos units`: every Program, Product and Project, who owns which initiative, and each owner's newest brief
3
+ * (chief-unit-owners ✦1 and ✦3). A read: it runs at once, from Home's chat (the chief) or a terminal.
4
+ *
5
+ * pmos units [list] [--json] one row per unit: its key, title, initiatives, the brief line, what failed, what is next, runs a day
6
+ * pmos units show <unit> [--json] one unit with the ids of its initiatives
7
+ * The owner is derived (lib/units.js): an initiative in a program is the program's, else its product's (project work: the project's).
8
+ * It reads GET /api/units on the running workspace. Exit codes: 0 done, 1 refused or no workspace running, 2 usage.
9
+ */
10
+ const COMMANDS = { units: ['list', 'show'] };
11
+ const USAGE = [
12
+ 'usage: pmos units [list|show <unit>] — the programs, products and projects, who owns each initiative, and each owner\'s brief',
13
+ ' pmos units list one row per unit: initiatives, today\'s brief ("3 done · 1 for you"), what failed, what is next',
14
+ ' pmos units show <unit> one unit (program:<id>, product:<id> or project:<id>) and its initiatives',
15
+ 'every command: [--json]',
16
+ ];
17
+
18
+ async function run(argv, { say = (s) => console.log(s), call = async () => null } = {}) {
19
+ const args = argv[0] === 'units' ? argv.slice(1) : argv.slice();
20
+ const json = args.includes('--json');
21
+ const pos = args.filter((a) => !a.startsWith('--'));
22
+ const verb = pos[0] || 'list';
23
+ if (['help', '-h'].includes(verb) || args.includes('--help')) { for (const l of USAGE) say(l); return 0; }
24
+ if (!COMMANDS.units.includes(verb)) { say(`unknown units command "${verb}" — one of ${COMMANDS.units.join(', ')}`); return 2; }
25
+ const r = await call('GET', '/api/units');
26
+ if (!r || !r.ok) { say(json ? JSON.stringify({ ok: false, error: (r && r.error) || 'no PMOS workspace is running' }) : `✗ ${(r && r.error) || 'no PMOS workspace is running: start it with `pmos`'}`); return 1; }
27
+ let units = r.units || [];
28
+ if (verb === 'show') {
29
+ const key = pos[1];
30
+ if (!key) { say('usage: pmos units show <unit>'); return 2; }
31
+ units = units.filter((u) => u.key === key);
32
+ if (!units.length) { say(`✗ no unit ${key} (pmos units lists them)`); return 1; }
33
+ if (json) { say(JSON.stringify({ ok: true, unit: units[0] })); return 0; }
34
+ }
35
+ if (json) { say(JSON.stringify({ ok: true, units })); return 0; }
36
+ if (!units.length) { say('No units yet: no workspace has an open initiative.'); return 0; }
37
+ for (const u of units) {
38
+ say(`${u.key} ${u.title} · ${u.initiatives} ${u.initiatives === 1 ? 'initiative' : 'initiatives'}`);
39
+ if (u.day) say(` brief ${u.day}: ${u.line || 'nothing new'}${u.next ? ` · next: ${u.next}` : ''}`);
40
+ for (const f of u.failed || []) say(` did not finish: ${f.ini ? f.ini + ' — ' : ''}${f.why}`);
41
+ }
42
+ return 0;
43
+ }
44
+
45
+ module.exports = { run, COMMANDS, USAGE };