create-pmos 0.598.0 → 0.600.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 (48) 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/layout.md +10 -3
  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/initiative-premium.js +2 -2
  19. package/workspace/lib/job-graph.js +4 -0
  20. package/workspace/lib/owner-cli.js +30 -0
  21. package/workspace/lib/pmos-verbs.js +5 -0
  22. package/workspace/lib/route-modules.js +1 -0
  23. package/workspace/lib/routes-briefing-premium.js +3 -1
  24. package/workspace/lib/routes-home-desk.js +13 -1
  25. package/workspace/lib/routes-initiative-premium.js +11 -1
  26. package/workspace/lib/routes-proposals.js +1 -1
  27. package/workspace/lib/routes-units.js +52 -0
  28. package/workspace/lib/team-cli.js +16 -1
  29. package/workspace/lib/team-runs.js +5 -2
  30. package/workspace/lib/unit-memory.js +65 -0
  31. package/workspace/lib/unit-owner.js +185 -0
  32. package/workspace/lib/units-cli.js +45 -0
  33. package/workspace/lib/units-host.js +151 -0
  34. package/workspace/lib/units.js +88 -0
  35. package/workspace/package-lock.json +2 -2
  36. package/workspace/package.json +1 -1
  37. package/workspace/public/pm/cozy-home.css +76 -0
  38. package/workspace/public/pm/cozy-live-pill.js +4 -0
  39. package/workspace/public/pm/cozy-nav.js +26 -6
  40. package/workspace/public/pm/cozy-today.css +3 -0
  41. package/workspace/public/pm/home-app.js +60 -2
  42. package/workspace/public/pm/home-chat.js +17 -2
  43. package/workspace/public/pm/home-list.js +14 -2
  44. package/workspace/public/pm/home-today.js +7 -4
  45. package/workspace/public/pm/phone-chat-head.js +147 -0
  46. package/workspace/server.js +26 -1
  47. package/workspace/test-files.json +1 -0
  48. package/workspace/test-lists/roomier-phone-chat.json +9 -0
@@ -2,7 +2,7 @@
2
2
  'use strict';
3
3
  /* pmos-memory — curated repository memory (D72).
4
4
  *
5
- * node pmos-memory.js add --text "…" [--target memory|user] [--confidence unconfirmed] [--source kind:ref] [--stale-after YYYY-MM-DD]
5
+ * node pmos-memory.js add --text "…" [--target memory|user] [--confidence unconfirmed] [--source kind:ref] [--stale-after YYYY-MM-DD] [--scope …]
6
6
  * node pmos-memory.js replace --old "unique substring" --text "…" [--target …]
7
7
  * node pmos-memory.js remove --old "unique substring" [--target …]
8
8
  * node pmos-memory.js confirm --old "unique substring"
@@ -15,6 +15,13 @@
15
15
  * USER.md are generated, git-ignored, and rebuilt at session start: a session reads them once (a frozen
16
16
  * snapshot) and sees its own writes only in the next one.
17
17
  *
18
+ * THREE SCOPES (chief-unit-owners ✦4, Wawan 2026-11-18): every entry has a scope. `workspace` (the default, and every line written before
19
+ * scopes) holds the standing rules and the PM's preferences, read by every session and run. `unit:<kind>:<id>` (lib/units.js keyOf, e.g.
20
+ * unit:program:ascent) holds a lesson that repeated across that unit's initiatives. `initiative:<id>` holds what one initiative's runs learned.
21
+ * A run reads workspace, then its unit, then its initiative, never another unit's (workspace/lib/headless.js memoryNote). The capacity
22
+ * limit is per target AND scope, so a busy initiative never crowds out the standing rules. The snapshot views (MEMORY.md, USER.md) show
23
+ * the workspace scope only. AGE OUT: an unconfirmed entry not touched for AGE_DAYS (30) is `aged` and no run reads it.
24
+ *
18
25
  * This is the harness pattern Hermes uses (bounded curated files, add/replace/remove by unique
19
26
  * substring, a capacity error that lists the entries, a frozen snapshot, optional write approval, a
20
27
  * scan for injection and credentials) with three changes: the store lives in the repository so it
@@ -29,6 +36,9 @@ const TARGETS = ['memory', 'user'];
29
36
  const DEFAULTS = { memory_chars: 2200, user_chars: 1375, write_approval: false };
30
37
  const CONFIDENCE = ['confirmed', 'unconfirmed'];
31
38
  const HUMAN = /^human:/;
39
+ const SCOPE_RE = /^(workspace|unit:(program|product|project):[A-Za-z0-9][A-Za-z0-9._-]{0,80}|initiative:[A-Za-z0-9][A-Za-z0-9._-]{0,80})$/;
40
+ const AGE_DAYS = 30;
41
+ const scopeOf = (v) => (v && SCOPE_RE.test(String(v)) ? String(v) : 'workspace');
32
42
 
33
43
  // ── paths ────────────────────────────────────────────────────────────────────────────────────
34
44
  function stateDir(root, create) {
@@ -113,7 +123,7 @@ function fold(events, now) {
113
123
  }
114
124
  if (e.op === 'add') {
115
125
  if (!TARGETS.includes(e.target)) continue;
116
- entries.set(e.eid, { id: e.eid, target: e.target, text: String(e.text), confidence: e.confidence === 'confirmed' ? 'confirmed' : 'unconfirmed',
126
+ entries.set(e.eid, { id: e.eid, target: e.target, scope: scopeOf(e.scope), text: String(e.text), confidence: e.confidence === 'confirmed' ? 'confirmed' : 'unconfirmed',
117
127
  source: e.source || null, by: e.by || 'unknown', at: e.at, updated_at: e.at, stale_after: e.stale_after || null, verified: [] });
118
128
  } else if (e.op === 'replace') {
119
129
  const cur = entries.get(e.id); if (!cur) continue;
@@ -129,11 +139,12 @@ function fold(events, now) {
129
139
  cur.confidence = 'confirmed'; cur.verified.push({ by: e.by, at: e.at });
130
140
  }
131
141
  }
132
- const list = [...entries.values()].map((x) => ({ ...x, stale: !!(x.stale_after && Date.parse(x.stale_after) <= nowMs) }));
142
+ const list = [...entries.values()].map((x) => ({ ...x, stale: !!(x.stale_after && Date.parse(x.stale_after) <= nowMs),
143
+ aged: x.confidence === 'unconfirmed' && nowMs - Date.parse(x.updated_at || x.at) > AGE_DAYS * 86400000 }));
133
144
  return { entries: list, pending, blocked };
134
145
  }
135
146
 
136
- const used = (entries, target) => entries.filter((e) => e.target === target).reduce((n, e) => n + e.text.length + 1, 0);
147
+ const used = (entries, target, scope = 'workspace') => entries.filter((e) => e.target === target && (e.scope || 'workspace') === scope && !e.aged).reduce((n, e) => n + e.text.length + 1, 0);
137
148
  function usage(state, cfg) {
138
149
  const out = {};
139
150
  for (const t of TARGETS) {
@@ -175,11 +186,11 @@ function load(root) {
175
186
  return { dir, cfg, state, torn, usage: usage(state, cfg) };
176
187
  }
177
188
 
178
- function listFor(state, target) { return state.entries.filter((e) => e.target === target); }
179
- function matchOne(state, target, sub) {
189
+ function listFor(state, target, scope) { return state.entries.filter((e) => e.target === target && (!scope || (e.scope || 'workspace') === scope)); }
190
+ function matchOne(state, target, sub, scope) {
180
191
  const s = String(sub || '').trim();
181
192
  if (!s) return { ok: false, error: 'a substring that identifies one entry is required (--old)' };
182
- const pool = listFor(state, target);
193
+ const pool = listFor(state, target, scope);
183
194
  const exact = pool.filter((e) => e.text === s);
184
195
  const hits = exact.length === 1 ? exact : pool.filter((e) => e.text.includes(s));
185
196
  if (hits.length === 1) return { ok: true, entry: hits[0] };
@@ -192,6 +203,8 @@ function write(root, req) {
192
203
  const op = req.op;
193
204
  const target = req.target || 'memory';
194
205
  if (!TARGETS.includes(target)) return { ok: false, error: `target must be one of ${TARGETS.join(', ')}` };
206
+ if (req.scope && !SCOPE_RE.test(String(req.scope))) return { ok: false, error: 'scope must be workspace, unit:<program|product|project>:<id> or initiative:<id>' };
207
+ const scope = req.scope ? String(req.scope) : null;
195
208
  const cur = load(root);
196
209
  const dir = memDir(root, true);
197
210
  const cfg = cur.dir ? cur.cfg : readConfig(dir);
@@ -209,18 +222,19 @@ function write(root, req) {
209
222
  if (!CONFIDENCE.includes(conf)) return { ok: false, error: `confidence must be ${CONFIDENCE.join(' or ')}` };
210
223
  let id = null; let delta = text.length + 1;
211
224
  if (op === 'replace') {
212
- const m = matchOne(cur.state, target, req.old);
225
+ const m = matchOne(cur.state, target, req.old, scope);
213
226
  if (!m.ok) return m;
214
227
  id = m.entry.id; delta = text.length - m.entry.text.length;
215
228
  }
216
- const limit = cfg[`${target}_chars`]; const u = used(cur.state.entries, target);
229
+ const inScope = id ? (cur.state.entries.find((e) => e.id === id) || {}).scope || 'workspace' : scope || 'workspace';
230
+ const limit = cfg[`${target}_chars`]; const u = used(cur.state.entries, target, inScope);
217
231
  if (u + delta > limit) {
218
- return { ok: false, error: `${target} is full (${u}/${limit} chars) and this write needs ${delta} more — merge or remove entries first`, entries: listFor(cur.state, target), usage: cur.usage };
232
+ return { ok: false, error: `${target}${inScope === 'workspace' ? '' : ' at ' + inScope} is full (${u}/${limit} chars) and this write needs ${delta} more — merge or remove entries first`, entries: listFor(cur.state, target, inScope), usage: cur.usage };
219
233
  }
220
- ev = { eid: newEid(), at, by: actor, op, target, ...(id ? { id } : {}), text, confidence: conf,
234
+ ev = { eid: newEid(), at, by: actor, op, target, ...(id ? { id } : {}), ...(op === 'add' && scope && scope !== 'workspace' ? { scope } : {}), text, confidence: conf,
221
235
  ...(req.source ? { source: req.source } : {}), ...(req.stale_after ? { stale_after: req.stale_after } : {}), ...(staged ? { staged: true } : {}) };
222
236
  } else if (op === 'remove' || op === 'confirm') {
223
- const m = matchOne(cur.state, target, req.old || req.text);
237
+ const m = matchOne(cur.state, target, req.old || req.text, scope);
224
238
  if (!m.ok) return m;
225
239
  ev = { eid: newEid(), at, by: actor, op, target, id: m.entry.id, ...(staged ? { staged: true } : {}) };
226
240
  if (op === 'confirm' && !HUMAN.test(actor)) return { ok: false, error: 'only the PM confirms an entry' };
@@ -244,7 +258,7 @@ function viewFor(target, state, usageT, cfg, at) {
244
258
  `# ${title} [${usageT.percent}% — ${usageT.used}/${usageT.limit} chars]`, '',
245
259
  ];
246
260
  if (usageT.percent >= 80) lines.push('> Above 80% full: merge or remove entries before adding.', '');
247
- const es = listFor(state, target).sort(byTime);
261
+ const es = listFor(state, target, 'workspace').filter((e) => !e.aged).sort(byTime);
248
262
  if (!es.length) lines.push('_Nothing recorded yet._');
249
263
  for (const e of es) {
250
264
  const tags = [e.confidence === 'unconfirmed' ? 'UNCONFIRMED' : null, e.stale ? 'STALE' : null].filter(Boolean);
@@ -356,13 +370,13 @@ function main(argv) {
356
370
  if (cmd === 'pending') { for (const p of cur.state.pending) process.stdout.write(`${p.eid} ${p.op} ${p.target} ${p.text || p.id} (${p.by})\n`); return 0; }
357
371
  for (const t of TARGETS) {
358
372
  process.stdout.write(`${t} [${cur.usage[t].percent}% — ${cur.usage[t].used}/${cur.usage[t].limit}]\n`);
359
- for (const e of listFor(cur.state, t)) process.stdout.write(` ${e.confidence === 'unconfirmed' ? '(unconfirmed) ' : ''}${e.stale ? '(stale) ' : ''}${e.text}\n`);
373
+ for (const e of listFor(cur.state, t)) process.stdout.write(` ${e.scope && e.scope !== 'workspace' ? `[${e.scope}] ` : ''}${e.confidence === 'unconfirmed' ? '(unconfirmed) ' : ''}${e.stale ? '(stale) ' : ''}${e.aged ? '(aged) ' : ''}${e.text}\n`);
360
374
  }
361
375
  for (const b of cur.state.blocked) process.stdout.write(`BLOCKED ${b.eid}: ${b.reason}\n`);
362
376
  return 0;
363
377
  }
364
378
  const req = { op: cmd, target: opt.target, text: opt.text, old: opt.old, confidence: opt.confidence, source: opt.source,
365
- stale_after: opt['stale-after'], by: opt.by, ref: rest[0] };
379
+ stale_after: opt['stale-after'], by: opt.by, ref: rest[0], scope: opt.scope };
366
380
  const r = write(root, req);
367
381
  if (opt.json) { say(r); return r.ok ? 0 : 2; }
368
382
  if (r.ok) { process.stdout.write(`${r.staged ? 'held for the PM to approve' : 'saved'} — ${req.target || 'memory'} ${r.usage[req.target || 'memory'].percent}% full. It appears in the next session's snapshot.\n`); return 0; }
@@ -371,5 +385,17 @@ function main(argv) {
371
385
  return 2;
372
386
  }
373
387
 
374
- module.exports = { fold, scan, load, write, render, search, memDir, stateDir, readEvents, readConfig, usage, appendEvent, TARGETS, DEFAULTS, SCAN };
388
+ /** The entries a session or run reads, in order: workspace, then its unit, then its initiative. Never another unit's or initiative's,
389
+ * never a stale, aged or staged one. `cap` bounds the unit and initiative entries (the workspace scope is bounded by its capacity). */
390
+ function scoped(state, { unit = null, ini = null, cap = 12 } = {}) {
391
+ const live = (state.entries || []).filter((e) => e && typeof e.text === 'string' && e.text.trim() && !e.stale && !e.aged && !e.staged);
392
+ const newest = (xs) => xs.sort(byTime).slice(-cap);
393
+ return [
394
+ ...live.filter((e) => (e.scope || 'workspace') === 'workspace'),
395
+ ...(unit ? newest(live.filter((e) => e.scope === 'unit:' + unit)) : []),
396
+ ...(ini ? newest(live.filter((e) => e.scope === 'initiative:' + ini)) : []),
397
+ ];
398
+ }
399
+
400
+ module.exports = { fold, scan, load, write, render, search, memDir, stateDir, readEvents, readConfig, usage, appendEvent, scoped, scopeOf, TARGETS, DEFAULTS, SCAN, SCOPE_RE, AGE_DAYS };
375
401
  if (require.main === module) process.exit(main(process.argv));
@@ -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
  }
@@ -127,11 +127,11 @@ function build(f) {
127
127
  const phases = dd && Array.isArray(dd.phases) && dd.phases.length ? dd.phases.slice() : null;
128
128
  const all = dd ? (dd.docs || []).map((d) => ({
129
129
  key: d.key, title: d.title, what: d.for || '', st: d.st, state: d.kind === 'live' ? 'Live' : DOC_STATE[d.st] || d.st || '', by: BY[d.by] || d.by || '', byKey: d.by || '',
130
- when: d.when ? shortDate(d.when) : '', cat: phases ? (d.other ? null : d.cat || null) : d.cat === 'Do' ? 'Build' : d.cat === 'Learn' ? 'Evaluate' : d.cat || 'Board', ...(d.other ? { other: true } : {}), path: d.open && d.open.path ? d.open.path : null, slot: d.st === 'draft' && d.draft && d.draft.slot ? d.draft.slot : '', running: !!d.running, tech: TECH.has(d.key), kind: d.kind || '', reader: d.reader || '', cadence: d.cadence || '', sections: ((GUIDE[d.key] || {}).sections || []).slice(),
130
+ when: d.when ? shortDate(d.when) : '', at: d.when || '', cat: phases ? (d.other ? null : d.cat || null) : d.cat === 'Do' ? 'Build' : d.cat === 'Learn' ? 'Evaluate' : d.cat || 'Board', ...(d.other ? { other: true } : {}), path: d.open && d.open.path ? d.open.path : null, slot: d.st === 'draft' && d.draft && d.draft.slot ? d.draft.slot : '', running: !!d.running, tech: TECH.has(d.key), kind: d.kind || '', reader: d.reader || '', cadence: d.cadence || '', sections: ((GUIDE[d.key] || {}).sections || []).slice(),
131
131
  act: d.act && d.act.do === 'draft' ? { kind: 'draft', label: d.running ? 'Drafting' : d.act.label || 'Draft it' } : null,
132
132
  from: d.from && d.from.text ? { path: d.from.path, heading: d.from.heading, text: d.from.text, cut: !!d.from.cut } : null,
133
133
  })) : [];
134
- const custom = (f.custom || []).map((d) => Object.assign(Custom.rowOf(d), { added: shortDate(d.at), cat: d.phase || 'Board' }));
134
+ const custom = (f.custom || []).map((d) => Object.assign(Custom.rowOf(d), { added: shortDate(d.at), at: d.at || '', cat: d.phase || 'Board' }));
135
135
  const rows = all.concat(custom);
136
136
  const core = rows.filter((d) => !d.tech);
137
137
  const cnt = { all: core.length, none: core.filter((d) => d.st === 'missing').length, draft: core.filter((d) => d.st === 'draft').length, ok: core.filter((d) => d.st === 'ok' || d.st === 'live').length };
@@ -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
  }
@@ -2,7 +2,7 @@
2
2
  /* routes-initiative-premium.js — GET /api/initiative-premium?id=<id>[&ws=<id>&board=<id>] (initiative briefing-premium-initiative).
3
3
  *
4
4
  * 200 { ok, state: 'ready', model, as_of } | 202 { ok, state: 'reading' } | 404 { ok: false, state: 'error', error } | 500 { ok: false, state: 'error', error }
5
- * model is lib/initiative-premium.js build(), made from the answers of the routes the production Initiatives sheet reads: /api/boards/initiative,
5
+ * model is lib/initiative-premium.js build() plus model.prs (prsOf below), made from the answers of the routes the production Initiatives sheet reads: /api/boards/initiative,
6
6
  * /api/initiatives/<id>, /api/boards/items and /api/core-docs?level=initiative. Those routes derive the initiatives in the background and answer 202
7
7
  * while they do, so this route answers 202 too and the page asks again: no request waits for the read. Read-only: the one press of the page (Draft it)
8
8
  * goes to POST /api/core-docs/draft from the page. */
@@ -11,6 +11,7 @@ const boards = require('./routes-boards.js');
11
11
  const initiatives = require('./routes-initiatives.js');
12
12
  const coreDocs = require('./routes-core-docs.js');
13
13
  const Custom = require('./custom-docs.js');
14
+ const factoryJoin = require('./factory-join.js');
14
15
 
15
16
  /** GET `pathAndQuery` from a route module's own handler, as the Work page's route does, and return { status, body }. */
16
17
  async function via(mod, pathAndQuery, req, ctx) {
@@ -21,9 +22,17 @@ async function via(mod, pathAndQuery, req, ctx) {
21
22
  return handled === false ? { status: 404, body: null } : out;
22
23
  }
23
24
  const qs = (o) => '?' + Object.entries(o).filter(([, v]) => v != null && v !== '').map(([k, v]) => k + '=' + encodeURIComponent(v)).join('&');
25
+ /** The initiative's pull requests (batch 31 item 5, the phone chat's context line): the factory's work items that name one in their evidence
26
+ * (lib/factory-join.js, the one join). [{ ref, item, state: 'Open' | 'Merged' | 'Closed' }]; no ledger or no PR gives []. */
27
+ const PR_STATE = { integrated: 'Merged', shipped: 'Merged', withdrawn: 'Closed' };
28
+ function prsOf(join, id) {
29
+ const f = factoryJoin.factoryOf(join, id);
30
+ return f && Array.isArray(f.items) ? f.items.filter((x) => x && x.pr).map((x) => ({ ref: String(x.pr), item: x.id, state: PR_STATE[x.state] || 'Open' })) : [];
31
+ }
24
32
  const ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,80}$/;
25
33
 
26
34
  module.exports = {
35
+ prsOf,
27
36
  prefixes: ['/api/initiative-premium'],
28
37
  handle: async (req, res, url, ctx) => {
29
38
  if (url.pathname !== '/api/initiative-premium') return false;
@@ -64,6 +73,7 @@ module.exports = {
64
73
  row: head.body.row, sheet: sh, items: it ? it.items : [], docs: dd, custom, ladder: lad,
65
74
  boards: all.map((x) => ({ ws: x.ws, id: x.id, name: x.name })), siblings: it ? (it.initiatives || []).map((x) => ({ id: x.id, title: x.title })) : [],
66
75
  });
76
+ try { const w = ctx.getWs ? ctx.getWs(pick.ws) : null; model.prs = w ? prsOf(factoryJoin.joinFactory(w.root, { initiative: id }), id) : []; } catch { model.prs = []; }
67
77
  ctx.json(res, { ok: true, state: 'ready', model, as_of: Date.now() });
68
78
  return true;
69
79
  } catch (e) { return fail((e && e.message) || e); }
@@ -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 };