create-pmos 0.301.0 → 0.303.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-pmos",
3
- "version": "0.301.0",
3
+ "version": "0.303.0",
4
4
  "description": "Scaffold the PMOS portable kit — run the PMOS product-management workflow (initiative → lane-fit spec → contract → build → three gates, with work-type lanes for features, research, maintenance, incidents, and content) entirely inside your own repo, with all state as git-versioned files. Includes `workflow-sweep`, which audits the state every board derives from and separates real defects from work you simply have not done. `create-pmos workspace` also installs + launches the local Terminal Workspace GUI. No database, no network, no telemetry.",
5
5
  "license": "MIT",
6
6
  "bin": {
@@ -1,3 +1,3 @@
1
- kernel-source: pmos@2c19189
1
+ kernel-source: pmos@2c3014c
2
2
  assembled: 2026-10-19
3
3
  mode: vendor
@@ -2,7 +2,7 @@
2
2
  type: Reference
3
3
  title: "Eval calibration log"
4
4
  description: "Append-only record of every PM override of an evaluator verdict."
5
- generated: {by: process:create-pmos, at: "2026-10-19T07:05:22Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-19T07:23:01Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -2,7 +2,7 @@
2
2
  type: Reference
3
3
  title: "Health budgets"
4
4
  description: "Closed registry of health-budget anchors (D59), edited only by the PM."
5
- generated: {by: process:create-pmos, at: "2026-10-19T07:05:22Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-19T07:23:01Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -2,7 +2,7 @@
2
2
  type: Reference
3
3
  title: "Discoveries and friction log"
4
4
  description: "Append-only record of what runs discovered and where the process rubbed."
5
- generated: {by: process:create-pmos, at: "2026-10-19T07:05:22Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-19T07:23:01Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -71,12 +71,12 @@ function probe(port, ms = PROBE_MS) {
71
71
  req.on('timeout', () => { req.destroy(); res(null); });
72
72
  });
73
73
  }
74
- function api(port, method, pathname, body) {
74
+ function api(port, method, pathname, body, extraHeaders) {
75
75
  return new Promise((res) => {
76
76
  const data = body ? JSON.stringify(body) : null;
77
77
  const req = http.request(`${urlOf(port)}${pathname}`, {
78
78
  method, timeout: 5000,
79
- headers: data ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data) } : {},
79
+ headers: { ...(data ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data) } : {}), ...(extraHeaders || {}) },
80
80
  }, (r) => { let b = ''; r.on('data', (c) => (b += c)); r.on('end', () => { try { res(JSON.parse(b)); } catch { res(null); } }); });
81
81
  req.on('error', () => res(null));
82
82
  req.on('timeout', () => { req.destroy(); res(null); });
@@ -85,6 +85,25 @@ function api(port, method, pathname, body) {
85
85
  });
86
86
  }
87
87
 
88
+ /**
89
+ * A write the server takes from the page only (lib/pm-guard.js) carries this launch's Origin and nonce. The nonce is the
90
+ * `pmos-nonce` meta of GET /, the way the page and test-run.js read it. A server that mints none gets the Origin alone.
91
+ */
92
+ function pressApi(port, method, pathname, body) {
93
+ if (method === 'GET') return api(port, method, pathname, body);
94
+ return new Promise((res) => {
95
+ const req = http.get(`${urlOf(port)}/`, { timeout: 5000 }, (r) => {
96
+ let h = ''; r.on('data', (c) => (h += c));
97
+ r.on('end', () => {
98
+ const m = /<meta name="pmos-nonce" content="([^"]*)"/.exec(h);
99
+ res(api(port, method, pathname, body, { Origin: urlOf(port), ...(m && m[1] ? { 'x-pmos-nonce': m[1] } : {}) }));
100
+ });
101
+ });
102
+ req.on('error', () => res(null));
103
+ req.on('timeout', () => { req.destroy(); res(null); });
104
+ });
105
+ }
106
+
88
107
  /** Every workspace server that answers, in candidate order (the default port first). */
89
108
  async function discover() {
90
109
  const ports = D.candidatePorts({ stateDir: STATE, pinned: PINNED });
@@ -228,7 +247,7 @@ function ensureInstalled() {
228
247
  let FORCE_WELCOME = false; // `pmos welcome [path]`
229
248
  async function openWorkspace(dir, port, { open = true } = {}) {
230
249
  const root = repoRootOf(dir);
231
- const reg = await api(port, 'POST', '/api/workspaces', { root, name: path.basename(root) });
250
+ const reg = await pressApi(port, 'POST', '/api/workspaces', { root, name: path.basename(root) });
232
251
  if (!reg || !reg.ok) {
233
252
  say(`✗ could not open ${root}${reg && reg.error ? ` — ${reg.error}` : ''}`);
234
253
  if (open) openBrowser(urlOf(port));
@@ -552,7 +571,7 @@ function doctor() {
552
571
  const live = await discover();
553
572
  const port = live.length ? live[0].port : null;
554
573
  code = await require('../lib/proactive-cli').run(process.argv.slice(2), {
555
- say, call: async (m, p, b) => (port ? api(port, m, p, b) : null) });
574
+ say, call: async (m, p, b) => (port ? pressApi(port, m, p, b) : null) });
556
575
  }
557
576
  else if (cmd === 'kg') {
558
577
  // Reads tracked .md files straight from disk (lib/kg-cli.js); needs no running server.
@@ -59,8 +59,8 @@ const product = (name, cond) => {
59
59
  srv = spawn(process.execPath, [path.join(__dirname, 'server.js')], { cwd: __dirname, stdio: 'ignore', env: T.env({ PMOS_WS_PORT: String(T.PORT), PATH: fakeBin + path.delimiter + process.env.PATH }) });
60
60
  await T.waitForServer(BASE);
61
61
  const json = async (m, p, b, h) => { const res = await fetch(BASE + p, { method: m, headers: { 'content-type': 'application/json', ...(h || {}) }, body: b ? JSON.stringify(b) : undefined }); let j = null; try { j = await res.json(); } catch { /* not json */ } return { status: res.status, body: j }; };
62
- const wA = (await json('POST', '/api/workspaces', { root: rootA, name: 'IDPF', focus: false })).body.workspace;
63
- const wB = (await json('POST', '/api/workspaces', { root: rootB, name: 'microsites', focus: false })).body.workspace;
62
+ const wA = (await json('POST', '/api/workspaces', { root: rootA, name: 'IDPF', focus: false }, await T.pressHeaders(BASE))).body.workspace;
63
+ const wB = (await json('POST', '/api/workspaces', { root: rootB, name: 'microsites', focus: false }, await T.pressHeaders(BASE))).body.workspace;
64
64
  const all = (await json('GET', '/api/workspaces')).body.workspaces;
65
65
  const home = all.find((w) => w.home);
66
66
  ok('P0 the server has a home workspace and the two products', !!home && !!wA && !!wB, JSON.stringify(all.map((w) => [w.name, w.home])));
@@ -61,7 +61,7 @@ const sh = (cwd, args) => spawnSync('git', args, { cwd, encoding: 'utf8' });
61
61
  srv = spawn(process.execPath, [path.join(__dirname, 'server.js')], { cwd: __dirname, stdio: 'ignore', env: T.env({ PMOS_WS_PORT: String(T.PORT), PATH: fakeBin + path.delimiter + process.env.PATH }) });
62
62
  await T.waitForServer(BASE);
63
63
  const json = async (m, p, b, h) => { const res = await fetch(BASE + p, { method: m, headers: { 'content-type': 'application/json', ...(h || {}) }, body: b ? JSON.stringify(b) : undefined }); let j = null; try { j = await res.json(); } catch { j = null; } return { status: res.status, body: j }; };
64
- const added = await json('POST', '/api/workspaces', { root, name: 'IDPF', focus: false });
64
+ const added = await json('POST', '/api/workspaces', { root, name: 'IDPF', focus: false }, await T.pressHeaders(BASE));
65
65
  ok('S0 the product is registered', !!(added.body && added.body.workspace));
66
66
  const model = async () => { const r = await json('GET', '/api/briefing-premium'); return r.status === 200 && r.body.model && !r.body.model.pending ? r.body : null; };
67
67
  const m0 = await until(model, 90000);
@@ -0,0 +1,134 @@
1
+ 'use strict';
2
+ /* capacity-governor.js — may the orchestrator start another background run now (initiative agent-orchestrator, PRD "Capacity governor").
3
+ *
4
+ * DEFAULTS · normalize(raw) → { ok, settings } | { ok:false, error } the limits, from the PM's file or the defaults
5
+ * modeOf({ now, lastActivityAt, settings }) → 'away' | 'working'
6
+ * decide({ now, lastActivityAt, settings, running, startedToday, load, quota, stopped })
7
+ * → { allowed, mode, cap, reason }
8
+ * memFreeFrac(deps) · cpuPerCore(deps) → the machine's load, read the way each system reports it
9
+ * parseVmStat(text) · parseMeminfo(text) → the pure parts of memFreeFrac
10
+ *
11
+ * There are no quiet hours. When the PM is away, agents may use most of the machine; when the PM is working, the PM's
12
+ * terminals and the workspace keep a reserved share and agents get the rest, with a lower cap on parallel runs. The mode
13
+ * switches by itself: working = inside the work hours AND active within `idleMin` minutes; anything else = away.
14
+ *
15
+ * It only decides whether a NEW run may start. It never ends a run: a run in progress drains by itself when the PM comes back.
16
+ * A run the PM starts by hand is not its business (see session-budget.js).
17
+ * Quota: when the CLI's remaining usage is known and below the reserve, nothing starts. When it is not known, the daily cap
18
+ * is the backstop, so an unreadable quota never means unlimited.
19
+ * Pure but for memFreeFrac and cpuPerCore, which take their readers as arguments. */
20
+ const fs = require('fs');
21
+ const os = require('os');
22
+ const { execFileSync } = require('child_process');
23
+
24
+ const DEFAULTS = Object.freeze({
25
+ workDays: [1, 2, 3, 4, 5], // Date#getDay(): Monday to Friday
26
+ workStart: '09:00', workEnd: '18:00', // host-local time
27
+ idleMin: 20,
28
+ awayParallel: 8, workingParallel: 3,
29
+ reservePct: 50, // share of memory and CPU the PM keeps while working
30
+ quotaReservePct: 30, // remaining usage below which nothing starts
31
+ dailyCap: 40, // the backstop on runs started per local day
32
+ });
33
+ const FLOOR_AWAY = Object.freeze({ memFree: 0.10, cpuPerCore: 1.5 }); // even away, never starve the machine
34
+
35
+ const HHMM = /^([01]?\d|2[0-3]):([0-5]\d)$/;
36
+ const minutes = (t) => { const m = HHMM.exec(t); return m ? (+m[1]) * 60 + (+m[2]) : null; };
37
+
38
+ function normalize(raw) {
39
+ const r = raw && typeof raw === 'object' ? raw : {};
40
+ const s = { ...DEFAULTS, workDays: [...DEFAULTS.workDays] };
41
+ const int = (k, lo, hi) => {
42
+ if (r[k] === undefined) return null;
43
+ const n = Number(r[k]);
44
+ if (!Number.isInteger(n) || n < lo || n > hi) return `${k} must be a whole number from ${lo} to ${hi}`;
45
+ s[k] = n; return null;
46
+ };
47
+ const problems = [
48
+ int('idleMin', 1, 240), int('awayParallel', 1, 32), int('workingParallel', 1, 32),
49
+ int('reservePct', 0, 90), int('quotaReservePct', 0, 100), int('dailyCap', 1, 500),
50
+ ].filter(Boolean);
51
+ for (const k of ['workStart', 'workEnd']) {
52
+ if (r[k] === undefined) continue;
53
+ if (minutes(String(r[k])) === null) problems.push(`${k} is a time like 09:00`); else s[k] = String(r[k]);
54
+ }
55
+ if (r.workDays !== undefined) {
56
+ if (!Array.isArray(r.workDays) || !r.workDays.every((d) => Number.isInteger(d) && d >= 0 && d <= 6)) problems.push('workDays is a list of weekday numbers, 0 (Sunday) to 6');
57
+ else s.workDays = [...new Set(r.workDays)].sort();
58
+ }
59
+ if (minutes(s.workEnd) <= minutes(s.workStart)) problems.push('workEnd is after workStart');
60
+ if (s.workingParallel > s.awayParallel) problems.push('workingParallel is not more than awayParallel');
61
+ return problems.length ? { ok: false, error: problems.join('; ') } : { ok: true, settings: s };
62
+ }
63
+
64
+ function modeOf({ now, lastActivityAt, settings } = {}) {
65
+ const s = settings || DEFAULTS;
66
+ const t = new Date(Number.isFinite(now) ? now : Date.now());
67
+ const mins = t.getHours() * 60 + t.getMinutes();
68
+ const inHours = s.workDays.includes(t.getDay()) && mins >= minutes(s.workStart) && mins < minutes(s.workEnd);
69
+ const idleMs = Number.isFinite(lastActivityAt) ? t.getTime() - lastActivityAt : Infinity;
70
+ const active = idleMs <= s.idleMin * 60000;
71
+ return inHours && active ? 'working' : 'away';
72
+ }
73
+
74
+ /** load: { memFreeFrac: 0..1 | null, cpuPerCore: number | null }; quota: { remainingPct: 0..100 } | null. */
75
+ function decide({ now, lastActivityAt, settings, running = 0, startedToday = 0, load, quota, stopped = false } = {}) {
76
+ const s = settings || DEFAULTS;
77
+ const mode = modeOf({ now, lastActivityAt, settings: s });
78
+ const cap = mode === 'away' ? s.awayParallel : s.workingParallel;
79
+ const no = (reason) => ({ allowed: false, mode, cap, reason });
80
+ if (stopped) return no('The orchestrator is stopped.');
81
+ if (running >= cap) return no(`${running} orchestrator runs are live (limit ${cap} while ${mode}).`);
82
+ if (startedToday >= s.dailyCap) return no(`${startedToday} runs started today (daily limit ${s.dailyCap}).`);
83
+ if (quota && Number.isFinite(quota.remainingPct) && quota.remainingPct < s.quotaReservePct) {
84
+ return no(`Claude usage left is ${Math.round(quota.remainingPct)}%, below the ${s.quotaReservePct}% reserve.`);
85
+ }
86
+ const mem = load && Number.isFinite(load.memFreeFrac) ? load.memFreeFrac : null;
87
+ const cpu = load && Number.isFinite(load.cpuPerCore) ? load.cpuPerCore : null;
88
+ if (mode === 'working') {
89
+ const keep = s.reservePct / 100;
90
+ if (mem !== null && mem < keep) return no(`The PM is working: free memory ${pct(mem)} is below the ${s.reservePct}% kept for the PM.`);
91
+ if (cpu !== null && cpu > 1 - keep) return no(`The PM is working: CPU load ${cpu.toFixed(2)} per core is above ${(1 - keep).toFixed(2)}.`);
92
+ } else {
93
+ if (mem !== null && mem < FLOOR_AWAY.memFree) return no(`Free memory ${pct(mem)} is below the ${pct(FLOOR_AWAY.memFree)} floor.`);
94
+ if (cpu !== null && cpu >= FLOOR_AWAY.cpuPerCore) return no(`CPU load ${cpu.toFixed(2)} per core is at the ${FLOOR_AWAY.cpuPerCore} floor.`);
95
+ }
96
+ return { allowed: true, mode, cap, reason: null };
97
+ }
98
+ const pct = (f) => `${Math.round(f * 100)}%`;
99
+
100
+ /** macOS: os.freemem() counts cache as used and always looks nearly full, so read vm_stat: free + inactive + speculative + purgeable pages. */
101
+ function parseVmStat(text) {
102
+ const t = String(text || '');
103
+ const size = /page size of (\d+) bytes/.exec(t);
104
+ const pages = (name) => { const m = new RegExp(`^${name}:\\s+(\\d+)\\.`, 'm').exec(t); return m ? +m[1] : 0; };
105
+ const free = pages('Pages free') + pages('Pages inactive') + pages('Pages speculative') + pages('Pages purgeable');
106
+ return { freeBytes: free * (size ? +size[1] : 4096) };
107
+ }
108
+ /** Linux: MemAvailable is the figure the kernel offers for new work. */
109
+ function parseMeminfo(text) {
110
+ const t = String(text || '');
111
+ const a = /^MemAvailable:\s+(\d+) kB/m.exec(t), tot = /^MemTotal:\s+(\d+) kB/m.exec(t);
112
+ return a && tot ? { freeBytes: +a[1] * 1024, totalBytes: +tot[1] * 1024 } : null;
113
+ }
114
+ function memFreeFrac(deps = {}) {
115
+ const platform = deps.platform || process.platform;
116
+ const total = (deps.totalmem || os.totalmem)();
117
+ try {
118
+ if (platform === 'darwin') {
119
+ const out = (deps.vmStat || (() => execFileSync('vm_stat', { encoding: 'utf8', timeout: 2000 })))();
120
+ return Math.min(1, parseVmStat(out).freeBytes / total);
121
+ }
122
+ if (platform === 'linux') {
123
+ const m = parseMeminfo((deps.meminfo || (() => fs.readFileSync('/proc/meminfo', 'utf8')))());
124
+ if (m) return Math.min(1, m.freeBytes / m.totalBytes);
125
+ }
126
+ } catch { /* fall through to the portable figure */ }
127
+ return Math.min(1, (deps.freemem || os.freemem)() / total);
128
+ }
129
+ function cpuPerCore(deps = {}) {
130
+ const cores = Math.max(1, (deps.cpus || (() => os.cpus()))().length);
131
+ return (deps.loadavg || os.loadavg)()[0] / cores;
132
+ }
133
+
134
+ module.exports = { DEFAULTS, FLOOR_AWAY, normalize, modeOf, decide, parseVmStat, parseMeminfo, memFreeFrac, cpuPerCore };
@@ -190,7 +190,14 @@ function create(deps) {
190
190
  let live = active.size;
191
191
  for (const group of p.start) {
192
192
  if (live >= D.BUDGET.concurrent) break;
193
+ // agent-orchestrator: the capacity governor may hold a start (stopped, machine busy, PM working, daily cap). The wakes stay queued, as for the login hold.
194
+ if (deps.mayStart) {
195
+ let g = { allowed: true };
196
+ try { g = deps.mayStart({ running: live }) || g; } catch (e) { warn('driver gate', e); }
197
+ if (!g.allowed) { summary.held = g.reason || 'the capacity governor'; break; }
198
+ }
193
199
  startRun(w, file, group, state, factsNow, now);
200
+ if (deps.started) { try { deps.started(); } catch { /* a counter */ } }
194
201
  live = active.size; summary.started++;
195
202
  }
196
203
  } catch (e) { warn('driver tick', e); }
@@ -198,7 +205,7 @@ function create(deps) {
198
205
  return summary;
199
206
  }
200
207
 
201
- return { tick, active: () => [...active.keys()] };
208
+ return { tick, active: () => [...active.keys()], loginHeld: (now = Date.now()) => !!(loginFailedAt && now - loginFailedAt < LOGIN_HOLD_MS) };
202
209
  }
203
210
 
204
211
  module.exports = { create, off, dayCheckOpen, loginFailure, LOGIN_HOLD_MS };
@@ -0,0 +1,62 @@
1
+ 'use strict';
2
+ /* orchestrator-gate.js — the one question "may the orchestrator start another run now", answered from the machine and the PM's files
3
+ * (initiative agent-orchestrator, PRD "Capacity governor"). It joins lib/capacity-governor.js (the rule), lib/orchestrator-ledger.js (the
4
+ * stop switch) and the PM's settings file; the server hands it to the Initiative Driver and to the status route.
5
+ *
6
+ * create({ dir, now?, load?, quota?, bootAt? }) → gate
7
+ * gate.touch(at?) the PM did something (a key in a terminal, a page press): the work-hours mode needs this
8
+ * gate.mayStart({ running }) → the governor's answer { allowed, mode, cap, reason }, with the day's count and the stop switch read in
9
+ * gate.granted(at?) a start was made: it counts toward today's cap
10
+ * gate.status({ running }) → { stopped, mode, cap, allowed, reason, running, startedToday, settings, lastActivityAt }
11
+ * gate.settings() · gate.backupDir() → the governor's settings (defaults for what the file leaves out) · the nightly backup destination or null
12
+ * gate.setStopped(stopped, actor) the stop switch
13
+ *
14
+ * STATE: <dir>/orchestrator.json the PM's settings, written by the PM only: { v: 1, settings: {…governor keys}, backupDir? }
15
+ * <dir>/orchestrator-day.json { day, count }: runs started today, kept on disk so a restart does not reset the daily cap
16
+ * <dir>/orchestrator-stop.json the stop switch (lib/orchestrator-ledger.js)
17
+ * An unreadable or invalid settings file means the defaults, and the status says so. QUOTA: the Claude CLI shows no usage figure this
18
+ * module can read, so `quota` is null unless the caller supplies one; the daily cap is the backstop then (PRD: never unlimited). */
19
+ const fs = require('fs');
20
+ const path = require('path');
21
+ const G = require('./capacity-governor.js');
22
+ const L = require('./orchestrator-ledger.js');
23
+
24
+ const localDay = (ms) => { const d = new Date(ms); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; };
25
+ const readJson = (f) => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch { return null; } };
26
+
27
+ function create({ dir, now = Date.now, load = () => ({ memFreeFrac: G.memFreeFrac(), cpuPerCore: G.cpuPerCore() }), quota = () => null, bootAt } = {}) {
28
+ let lastActivityAt = Number.isFinite(bootAt) ? bootAt : now(); // a restart counts as the PM being here: the safer mode
29
+ const cfgFile = path.join(dir, 'orchestrator.json'), dayFile = path.join(dir, 'orchestrator-day.json');
30
+
31
+ function config() {
32
+ const raw = readJson(cfgFile);
33
+ if (raw === null) return { settings: { ...G.DEFAULTS }, backupDir: null, problem: null };
34
+ const n = G.normalize(raw && raw.settings);
35
+ return { settings: n.ok ? n.settings : { ...G.DEFAULTS }, backupDir: raw && typeof raw.backupDir === 'string' && raw.backupDir.trim() ? raw.backupDir.trim() : null,
36
+ problem: n.ok ? null : `orchestrator.json is not valid (${n.error}); the defaults apply` };
37
+ }
38
+ function startedToday(t) { const d = readJson(dayFile); return d && d.day === localDay(t) && Number.isInteger(d.count) ? d.count : 0; }
39
+ function safeLoad() { try { return load(); } catch { return null; } }
40
+ function safeQuota() { try { return quota(); } catch { return null; } }
41
+
42
+ function mayStart({ running = 0 } = {}) {
43
+ const t = now();
44
+ return G.decide({ now: t, lastActivityAt, settings: config().settings, running, startedToday: startedToday(t), load: safeLoad(), quota: safeQuota(), stopped: L.isStopped(dir) });
45
+ }
46
+ function granted(at = now()) {
47
+ try { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(dayFile, JSON.stringify({ day: localDay(at), count: startedToday(at) + 1 }) + '\n'); } catch { /* the cap is a backstop; a failed write must not stop a run that already started */ }
48
+ }
49
+ function status({ running = 0 } = {}) {
50
+ const t = now(), c = config(), d = mayStart({ running });
51
+ return { stopped: L.isStopped(dir), mode: d.mode, cap: d.cap, allowed: d.allowed, reason: d.reason, running, startedToday: startedToday(t), settings: c.settings,
52
+ settingsProblem: c.problem, backupDir: c.backupDir, lastActivityAt };
53
+ }
54
+ return {
55
+ touch: (at = now()) => { lastActivityAt = at; },
56
+ mayStart, granted, status,
57
+ settings: () => config().settings, backupDir: () => config().backupDir,
58
+ setStopped: (stopped, actor) => L.setStopped(dir, stopped, actor, now()),
59
+ };
60
+ }
61
+
62
+ module.exports = { create, localDay };
@@ -0,0 +1,36 @@
1
+ 'use strict';
2
+ /* orchestrator-health.js — what is wrong with the machine the orchestrator works on, in words (initiative agent-orchestrator, PRD "Keeping the Mac mini up").
3
+ *
4
+ * rows({ now, stopped, lastTickAt, tickMs, diskFreeFrac, loginHeld, backup }) → [{ id, level: 'warn' | 'bad', text }]
5
+ * diskFreeFrac(dir) → 0..1 | null the free share of the disk that holds `dir`
6
+ *
7
+ * Only a problem is a row: a healthy machine returns []. `backup` = { configured, lastOkAt, lastError } from lib/state-backup.js.
8
+ * Pure but for diskFreeFrac. The Briefing and the status route show these rows; no row starts or stops anything. */
9
+ const fs = require('fs');
10
+
11
+ const HOUR = 3600 * 1000;
12
+
13
+ function rows({ now = Date.now(), stopped = false, lastTickAt = null, tickMs = 60000, diskFreeFrac = null, loginHeld = false, backup = null } = {}) {
14
+ const out = [];
15
+ if (stopped) out.push({ id: 'stopped', level: 'warn', text: 'The orchestrator is stopped. Nothing new starts until you press Resume.' });
16
+ if (!stopped && lastTickAt !== null && now - lastTickAt > Math.max(5 * tickMs, 5 * 60000)) {
17
+ out.push({ id: 'tick', level: 'bad', text: `The workspace has not run its background tick for ${Math.round((now - lastTickAt) / 60000)} minutes.` });
18
+ }
19
+ if (loginHeld) out.push({ id: 'login', level: 'bad', text: 'Claude is signed out on this computer, so background runs are on hold. Sign in again with /login in a workspace terminal.' });
20
+ if (Number.isFinite(diskFreeFrac)) {
21
+ if (diskFreeFrac < 0.05) out.push({ id: 'disk', level: 'bad', text: `The disk is almost full (${Math.round(diskFreeFrac * 100)}% free).` });
22
+ else if (diskFreeFrac < 0.15) out.push({ id: 'disk', level: 'warn', text: `The disk is getting full (${Math.round(diskFreeFrac * 100)}% free).` });
23
+ }
24
+ if (backup) {
25
+ if (!backup.configured) out.push({ id: 'backup', level: 'warn', text: 'The nightly backup has no destination yet. Choose a folder outside this one (an external disk or a synced folder).' });
26
+ else if (backup.lastError) out.push({ id: 'backup', level: 'bad', text: `The last backup failed: ${backup.lastError}` });
27
+ else if (!Number.isFinite(backup.lastOkAt) || now - backup.lastOkAt > 36 * HOUR) out.push({ id: 'backup', level: 'bad', text: 'There has been no good backup in over 36 hours.' });
28
+ }
29
+ return out;
30
+ }
31
+
32
+ function diskFreeFrac(dir) {
33
+ try { const s = fs.statfsSync(dir); return s.blocks > 0 ? s.bavail / s.blocks : null; } catch { return null; }
34
+ }
35
+
36
+ module.exports = { rows, diskFreeFrac };
@@ -0,0 +1,100 @@
1
+ 'use strict';
2
+ /* orchestrator-ledger.js — the orchestrator's stop switch and its task ledger (initiative agent-orchestrator, PRD "Orchestrator and workers").
3
+ *
4
+ * isStopped(dir) · setStopped(dir, stopped, actor, now) the one stop switch; a missing file means running
5
+ * open(dir, task, now) → { ok, duplicate } task = { id, job, trigger, subject, rank }; the same id is never opened twice while it is live or was done in the last `DONE_HOLD_MS`
6
+ * started(dir, id, session, now) → { ok } | { ok:false, error } only an `open` task starts, so a task never has two live runs
7
+ * finished(dir, id, outcome, now) outcome = { ok, summary?, reason? }
8
+ * fold(lines) · read(dir) → Map<id, task> state: open | running | parked | failed
9
+ * recover(dir, alive, now) → { requeued: [id], failed: [id] } after a restart: a running task whose session is gone runs once more, then fails with a reason
10
+ * queue(map, limit) → the open tasks, highest rank first, oldest first
11
+ *
12
+ * One append-only file, tasks.jsonl, in the workspace state folder. Nothing is rewritten; the state of a task is its last line.
13
+ * `parked` means a worker finished and the result waits in the Briefing for the PM; it is the end of the orchestrator's part.
14
+ * The PM's Keep, Return and Drop live in the Driver and the Briefing, not here (D65: this file is not a control-graph record). */
15
+ const fs = require('fs');
16
+ const path = require('path');
17
+
18
+ const FILE = 'tasks.jsonl';
19
+ const STOP_FILE = 'orchestrator-stop.json';
20
+ const MAX_ATTEMPTS = 2; // the first run and one more after an interruption
21
+ const DONE_HOLD_MS = 20 * 60 * 60 * 1000; // a finished task is not opened again for 20 hours
22
+ const ID_RE = /^[a-z0-9][a-z0-9:._-]{0,120}$/i;
23
+ const clip = (s, n) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim().slice(0, n);
24
+
25
+ function isStopped(dir) {
26
+ try { const v = JSON.parse(fs.readFileSync(path.join(dir, STOP_FILE), 'utf8')); return !!(v && v.stopped === true); } catch { return false; }
27
+ }
28
+ function setStopped(dir, stopped, actor, now = Date.now()) {
29
+ fs.mkdirSync(dir, { recursive: true });
30
+ fs.writeFileSync(path.join(dir, STOP_FILE), JSON.stringify({ v: 1, stopped: !!stopped, at: new Date(now).toISOString(), by: clip(actor, 40) }) + '\n');
31
+ return { ok: true, stopped: !!stopped };
32
+ }
33
+
34
+ function append(dir, row) {
35
+ fs.mkdirSync(dir, { recursive: true });
36
+ fs.appendFileSync(path.join(dir, FILE), JSON.stringify(row) + '\n');
37
+ }
38
+ function fold(lines) {
39
+ const m = new Map();
40
+ for (const raw of lines) {
41
+ let r; try { r = JSON.parse(raw); } catch { continue; }
42
+ if (!r || r.v !== 1 || !ID_RE.test(String(r.id || ''))) continue;
43
+ const t = m.get(r.id) || { id: r.id, attempts: 0 };
44
+ if (r.ev === 'open') Object.assign(t, { state: 'open', job: r.job, trigger: r.trigger, subject: r.subject, rank: r.rank, openedAt: r.at, session: null, reason: null });
45
+ else if (!t.state) continue; // a line for a task never opened is ignored
46
+ else if (r.ev === 'start') Object.assign(t, { state: 'running', session: r.session, startedAt: r.at, attempts: t.attempts + 1 });
47
+ else if (r.ev === 'finish') Object.assign(t, { state: r.ok ? 'parked' : 'failed', summary: r.summary || null, reason: r.reason || null, finishedAt: r.at, session: null });
48
+ else if (r.ev === 'requeue') Object.assign(t, { state: 'open', session: null, reason: r.reason || null });
49
+ m.set(r.id, t);
50
+ }
51
+ return m;
52
+ }
53
+ function read(dir) {
54
+ try { return fold(fs.readFileSync(path.join(dir, FILE), 'utf8').split('\n').filter(Boolean)); } catch { return new Map(); }
55
+ }
56
+
57
+ function open(dir, task, now = Date.now()) {
58
+ const t = task || {};
59
+ if (!ID_RE.test(String(t.id || ''))) return { ok: false, error: 'a task id is lowercase letters, digits and : . _ -' };
60
+ const cur = read(dir).get(t.id);
61
+ if (cur && (cur.state === 'open' || cur.state === 'running')) return { ok: true, duplicate: true };
62
+ if (cur && cur.finishedAt && now - Date.parse(cur.finishedAt) < DONE_HOLD_MS) return { ok: true, duplicate: true };
63
+ append(dir, { v: 1, at: new Date(now).toISOString(), ev: 'open', id: t.id, job: clip(t.job, 40), trigger: clip(t.trigger, 40), subject: clip(t.subject, 200), rank: Number.isFinite(t.rank) ? t.rank : 0 });
64
+ return { ok: true, duplicate: false };
65
+ }
66
+ function started(dir, id, session, now = Date.now()) {
67
+ const cur = read(dir).get(id);
68
+ if (!cur) return { ok: false, error: 'no such task' };
69
+ if (cur.state !== 'open') return { ok: false, error: `the task is ${cur.state}, not open` };
70
+ append(dir, { v: 1, at: new Date(now).toISOString(), ev: 'start', id, session: clip(session, 80) });
71
+ return { ok: true };
72
+ }
73
+ function finished(dir, id, outcome, now = Date.now()) {
74
+ const cur = read(dir).get(id);
75
+ if (!cur || cur.state !== 'running') return { ok: false, error: 'the task is not running' };
76
+ const o = outcome || {};
77
+ append(dir, { v: 1, at: new Date(now).toISOString(), ev: 'finish', id, ok: !!o.ok, summary: clip(o.summary, 400) || undefined, reason: o.ok ? undefined : (clip(o.reason, 300) || 'the run ended without a result') });
78
+ return { ok: true };
79
+ }
80
+ function recover(dir, alive, now = Date.now()) {
81
+ const out = { requeued: [], failed: [] };
82
+ const live = alive instanceof Set ? alive : new Set(alive || []);
83
+ for (const t of read(dir).values()) {
84
+ if (t.state !== 'running' || (t.session && live.has(t.session))) continue;
85
+ if (t.attempts < MAX_ATTEMPTS) {
86
+ append(dir, { v: 1, at: new Date(now).toISOString(), ev: 'requeue', id: t.id, reason: 'interrupted by a restart' });
87
+ out.requeued.push(t.id);
88
+ } else {
89
+ append(dir, { v: 1, at: new Date(now).toISOString(), ev: 'finish', id: t.id, ok: false, reason: `interrupted twice (${t.attempts} runs); not started again` });
90
+ out.failed.push(t.id);
91
+ }
92
+ }
93
+ return out;
94
+ }
95
+ function queue(map, limit = 50) {
96
+ return [...map.values()].filter((t) => t.state === 'open')
97
+ .sort((a, b) => (b.rank - a.rank) || String(a.openedAt).localeCompare(String(b.openedAt))).slice(0, limit);
98
+ }
99
+
100
+ module.exports = { FILE, STOP_FILE, MAX_ATTEMPTS, DONE_HOLD_MS, isStopped, setStopped, open, started, finished, fold, read, recover, queue };
@@ -77,6 +77,7 @@ const MODULES = Object.freeze([
77
77
  'routes-meeting-replay', // meeting-material-replay: the note, the Focus state and the shots joined for the Replay page (GET, read-only)
78
78
  'routes-meeting-material', // meeting-material-replay: the material the PM links to a meeting (GET list and suggest; page-press POST add and remove; meeting-material.jsonl)
79
79
  'routes-stage-tools', // stage-tools-records: the records the PM edits per stage, what PMOS holds per stage, the sprint burndown
80
+ 'routes-orchestrator', // agent-orchestrator: the status of the capacity governor and the PM's stop switch (orchestrator-stop.json)
80
81
  'routes-driver', // initiative-driver: the Agent strip's data, Keep, Send back, Drop, Pause and the board mode (driver.jsonl)
81
82
  'routes-scan', // horizon-scan-portfolio: one scan for the workspace: the watch list and setting, Scan now and Stop, report documents and their proposals (approve, change, dismiss, undo), plus the first scan's per-board and Briefing reads (scan.jsonl)
82
83
  'routes-report-setups', // report-workspace: recurring reports, the Ask box, the finder, the report documents and their export (report-setups.jsonl)
@@ -0,0 +1,37 @@
1
+ 'use strict';
2
+ /* routes-orchestrator.js — the orchestrator's status and stop switch (initiative agent-orchestrator, PRD "Gates that stay yours").
3
+ *
4
+ * GET /api/orchestrator → { ok, stopped, mode, cap, allowed, reason, running, startedToday, settings, settingsProblem, backupDir, health: [{ id, level, text }] }
5
+ * POST /api/orchestrator/stop → { ok, stopped: true }
6
+ * POST /api/orchestrator/resume → { ok, stopped: false }
7
+ *
8
+ * The GET changes nothing. Both POSTs pass pm-guard requirePagePress, and a request that carries an agent session header is refused
9
+ * first: an agent cannot start the orchestrator again after the PM stopped it, and cannot stop it either. The stop switch is a file
10
+ * (lib/orchestrator-ledger.js); the tick reads it before every start. `ctx.orchestrator` is { gate, running(), health() } from server.js. */
11
+ const guard = require('./pm-guard.js');
12
+ const actorLib = require('./actor.js');
13
+
14
+ const bad = (status, error) => ({ status, body: { ok: false, error } });
15
+
16
+ async function handle(req, res, url, ctx) {
17
+ const send = (r) => { ctx.json(res, r.body, r.status); return true; };
18
+ const o = ctx.orchestrator;
19
+ if (!o || !o.gate) return send(bad(503, 'the orchestrator is not running in this workspace'));
20
+ const sub = url.pathname.replace(/^\/api\/orchestrator\/?/, '');
21
+
22
+ if (sub === '') {
23
+ if (req.method !== 'GET') return send(bad(405, 'GET only'));
24
+ return send({ status: 200, body: { ok: true, ...o.gate.status({ running: o.running() }), health: o.health() } });
25
+ }
26
+ if (sub !== 'stop' && sub !== 'resume') return send(bad(404, 'no such orchestrator route'));
27
+ if (req.method !== 'POST') return send(bad(405, 'POST only'));
28
+ const read = await ctx.readJson(req);
29
+ if (!read.ok) return send(bad(400, 'the body is not JSON'));
30
+ if (req.headers && req.headers['x-pmos-session']) return send(bad(403, 'an agent session cannot stop or resume the orchestrator'));
31
+ const g = guard.requirePagePress(req, read.body);
32
+ if (!g.ok) return send(bad(g.status, g.error));
33
+ const r = o.gate.setStopped(sub === 'stop', actorLib.pageName ? actorLib.pageName(g.actor) : 'pm');
34
+ return send({ status: 200, body: { ok: true, stopped: r.stopped } });
35
+ }
36
+
37
+ module.exports = { prefixes: ['/api/orchestrator'], handle };
@@ -0,0 +1,102 @@
1
+ 'use strict';
2
+ /* state-backup.js — the nightly copy of the workspace state folder (initiative agent-orchestrator, PRD "Keeping the Mac mini up").
3
+ *
4
+ * run({ src, dest, now?, keep? }) → { ok, day, files, bytes, pruned: [day] } | { ok: false, error }
5
+ * restore({ dest, day, target }) → { ok, files } | { ok: false, error }
6
+ * due({ now, lastOkAt, hour? }) → boolean once per local day, from `hour` (default 02:00)
7
+ * days(dest) → the dated folders there, oldest first
8
+ * readLog(src) · logTo(src, row) → <src>/backup-log.jsonl: { at, ok, day?, files?, bytes?, error? }; the last row feeds the health check
9
+ *
10
+ * WHAT IS COPIED: the small state files (.json .jsonl .md .txt) under `src`, to <dest>/<YYYY-MM-DD>/, with a manifest.json of what was
11
+ * copied. Terminal buffers, sockets, caches and anything whose name looks like a secret (token, secret, key, nonce, credential, password)
12
+ * are left out: a backup that copies the PM's keys to a second place is worse than none. A copy is checked by reading it back (file count and
13
+ * bytes against the manifest) before the run says ok, and only then are days beyond the newest `keep` (default 7) removed.
14
+ * `dest` must be outside `src`. Nothing is sent over a network; the PM chooses the folder. */
15
+ const fs = require('fs');
16
+ const path = require('path');
17
+
18
+ const KEEP_EXT = /\.(jsonl?|md|txt)$/i;
19
+ const SKIP_NAME = /(token|secret|key|nonce|credential|password|\.sock$|buffer|cache|node_modules|\.git$)/i;
20
+ const MAX_FILE = 50 * 1024 * 1024;
21
+ const DAY_RE = /^\d{4}-\d{2}-\d{2}$/;
22
+ const LOG = 'backup-log.jsonl';
23
+ const localDay = (ms) => { const d = new Date(ms); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; };
24
+ const inside = (child, parent) => { const r = path.relative(path.resolve(parent), path.resolve(child)); return r === '' || (!r.startsWith('..') && !path.isAbsolute(r)); };
25
+
26
+ function listFiles(root) {
27
+ const out = [];
28
+ (function walk(d) {
29
+ let ents; try { ents = fs.readdirSync(d, { withFileTypes: true }); } catch { return; }
30
+ for (const e of ents) {
31
+ if (SKIP_NAME.test(e.name)) continue;
32
+ const p = path.join(d, e.name);
33
+ if (e.isDirectory()) walk(p);
34
+ else if (e.isFile() && KEEP_EXT.test(e.name)) { try { if (fs.statSync(p).size <= MAX_FILE) out.push(p); } catch { /* vanished */ } }
35
+ }
36
+ })(root);
37
+ return out;
38
+ }
39
+ function totals(root) { const fl = listFiles(root); return { files: fl.length, bytes: fl.reduce((n, f) => { try { return n + fs.statSync(f).size; } catch { return n; } }, 0) }; }
40
+
41
+ function days(dest) { try { return fs.readdirSync(dest).filter((n) => DAY_RE.test(n)).sort(); } catch { return []; } }
42
+
43
+ function run({ src, dest, now = Date.now(), keep = 7 } = {}) {
44
+ if (!src || !dest) return { ok: false, error: 'a source and a destination are needed' };
45
+ if (inside(dest, src)) return { ok: false, error: 'the destination is inside the state folder; choose a folder outside it' };
46
+ if (!fs.existsSync(src)) return { ok: false, error: 'the state folder is missing' };
47
+ const day = localDay(now), out = path.join(dest, day), tmp = path.join(dest, `.${day}.partial`);
48
+ try {
49
+ fs.rmSync(tmp, { recursive: true, force: true });
50
+ fs.mkdirSync(tmp, { recursive: true });
51
+ const files = listFiles(src);
52
+ for (const f of files) {
53
+ const to = path.join(tmp, path.relative(src, f));
54
+ fs.mkdirSync(path.dirname(to), { recursive: true });
55
+ fs.copyFileSync(f, to);
56
+ }
57
+ const copied = totals(tmp);
58
+ const want = files.reduce((n, f) => { try { return n + fs.statSync(f).size; } catch { return n; } }, 0);
59
+ if (copied.files !== files.length || copied.bytes !== want) throw new Error(`the copy does not match: ${copied.files} of ${files.length} files, ${copied.bytes} of ${want} bytes`);
60
+ fs.writeFileSync(path.join(tmp, 'manifest.json'), JSON.stringify({ v: 1, at: new Date(now).toISOString(), files: files.length, bytes: want }) + '\n');
61
+ fs.rmSync(out, { recursive: true, force: true });
62
+ fs.renameSync(tmp, out);
63
+ const all = days(dest), old = all.slice(0, Math.max(0, all.length - Math.max(1, keep)));
64
+ for (const d of old) fs.rmSync(path.join(dest, d), { recursive: true, force: true });
65
+ return { ok: true, day, files: files.length, bytes: want, pruned: old };
66
+ } catch (e) {
67
+ try { fs.rmSync(tmp, { recursive: true, force: true }); } catch { /* best effort */ }
68
+ return { ok: false, error: String((e && e.message) || e).slice(0, 300) };
69
+ }
70
+ }
71
+
72
+ function restore({ dest, day, target } = {}) {
73
+ if (!dest || !target) return { ok: false, error: 'a backup folder and a target are needed' };
74
+ const d = day || days(dest).pop();
75
+ if (!d || !DAY_RE.test(d) || !fs.existsSync(path.join(dest, d))) return { ok: false, error: 'there is no such backup day' };
76
+ const from = path.join(dest, d);
77
+ let n = 0;
78
+ (function walk(dir) {
79
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
80
+ const p = path.join(dir, e.name);
81
+ if (e.isDirectory()) walk(p);
82
+ else if (e.name !== 'manifest.json') { const to = path.join(target, path.relative(from, p)); fs.mkdirSync(path.dirname(to), { recursive: true }); fs.copyFileSync(p, to); n++; }
83
+ }
84
+ })(from);
85
+ return { ok: true, files: n };
86
+ }
87
+
88
+ function due({ now = Date.now(), lastOkAt = null, hour = 2 } = {}) {
89
+ if (new Date(now).getHours() < hour) return false;
90
+ return !Number.isFinite(lastOkAt) || localDay(lastOkAt) !== localDay(now);
91
+ }
92
+
93
+ function logTo(src, row) { try { fs.appendFileSync(path.join(src, LOG), JSON.stringify(row) + '\n'); } catch { /* the log is informational */ } }
94
+ function readLog(src) {
95
+ try {
96
+ const rows = fs.readFileSync(path.join(src, LOG), 'utf8').split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
97
+ const lastOk = rows.filter((r) => r.ok).pop(), last = rows.pop() || null;
98
+ return { lastOkAt: lastOk ? Date.parse(lastOk.at) : null, lastError: last && !last.ok ? last.error : null };
99
+ } catch { return { lastOkAt: null, lastError: null }; }
100
+ }
101
+
102
+ module.exports = { run, restore, due, days, logTo, readLog, listFiles, localDay, inside };
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.301.0",
3
+ "version": "0.303.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.301.0",
9
+ "version": "0.303.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.301.0",
3
+ "version": "0.303.0",
4
4
  "private": true,
5
5
  "description": "PMOS Terminal Workspace — local companion hosting real PTYs beside the library and gates (D62)",
6
6
  "license": "MIT",
@@ -2581,7 +2581,12 @@ const dashboardScheduleTick = () => {
2581
2581
  };
2582
2582
  // initiative-driver: the driver wakes on a creation, a move or a note, sweeps for blockers every 30 minutes inside the day-check
2583
2583
  // window, and starts its short headless runs. Everything it decides is in lib/driver.js; this only hands it the server's parts.
2584
+ // agent-orchestrator: the capacity governor in front of every run the orchestrator may start. The Driver asks it before each start; the status route reads it.
2585
+ // PMOS_TICK_MS is the suites' fast clock: a suite runs beside forty others, so the machine-load check is skipped there (the rest of the gate applies).
2586
+ const orchGate = require('./lib/orchestrator-gate.js').create({ dir: STATE, ...(process.env.PMOS_TICK_MS ? { load: () => null } : {}) });
2584
2587
  const driver = driverRunLib.create({
2588
+ mayStart: ({ running }) => orchGate.mayStart({ running }),
2589
+ started: () => orchGate.granted(),
2585
2590
  workspaces: () => [...workspaces.values()],
2586
2591
  isLead: (w) => isPlanNeedsTree(w),
2587
2592
  stateDirFor: (w) => stateDirFor(w),
@@ -2598,6 +2603,27 @@ const driver = driverRunLib.create({
2598
2603
  warn: (what, e) => warnWriteFail(what, e),
2599
2604
  });
2600
2605
  const driverTick = () => { try { driver.tick({}); } catch (e) { warnWriteFail('driver tick', e); } };
2606
+ // agent-orchestrator: the health rows (lib/orchestrator-health.js) and the nightly backup of the state folder (lib/state-backup.js, only when the PM has chosen a destination).
2607
+ let orchLastTickAt = null, orchBackupRunning = false;
2608
+ const orchHealth = () => {
2609
+ const backupLib = require('./lib/state-backup.js'), log = backupLib.readLog(STATE);
2610
+ return require('./lib/orchestrator-health.js').rows({ now: Date.now(), stopped: orchGate.status({}).stopped, lastTickAt: orchLastTickAt, tickMs: TICK_MS,
2611
+ diskFreeFrac: require('./lib/orchestrator-health.js').diskFreeFrac(STATE), loginHeld: driver.loginHeld(),
2612
+ backup: { configured: !!orchGate.backupDir(), lastOkAt: log.lastOkAt, lastError: log.lastError } });
2613
+ };
2614
+ const orchTick = () => {
2615
+ orchLastTickAt = Date.now();
2616
+ try {
2617
+ const dest = orchGate.backupDir();
2618
+ if (!dest || orchBackupRunning) return;
2619
+ const backupLib = require('./lib/state-backup.js');
2620
+ if (orchGate.status({}).mode !== 'away' || !backupLib.due({ now: Date.now(), lastOkAt: backupLib.readLog(STATE).lastOkAt })) return;
2621
+ orchBackupRunning = true;
2622
+ const r = backupLib.run({ src: STATE, dest, now: Date.now() });
2623
+ backupLib.logTo(STATE, r.ok ? { at: new Date().toISOString(), ok: true, day: r.day, files: r.files, bytes: r.bytes } : { at: new Date().toISOString(), ok: false, error: r.error });
2624
+ orchBackupRunning = false;
2625
+ } catch (e) { orchBackupRunning = false; warnWriteFail('orchestrator tick', e); }
2626
+ };
2601
2627
  // horizon-scan: a scan is two headless runs for the whole portfolio (web, then repository), at most one scan at a time, on the workspace cadence inside the working hours.
2602
2628
  // Everything it decides is in lib/scan.js and lib/scan-run.js; this only hands it the server's parts. The web run gets an empty scratch folder to run in.
2603
2629
  const scanRoutesCtx = () => ({ getWs, stateDirFor, workspaceList: () => [...workspaces.values()], runtimeDir: STATE, selfRoot: EMBEDDED_SELF ? SELF_ROOT : null });
@@ -2741,7 +2767,7 @@ const gated = (id, fn) => () => { let g = { ok: true }; try { g = refreshRun.job
2741
2767
  // data-refresh-settings: the seed schedules move to Settings › Data refresh (refreshRun.settings(), once) BEFORE checkDueSchedules reads
2742
2768
  // schedules.json, so a schedule that is moving never fires once more from the old list on the first tick after an upgrade.
2743
2769
  const scheduleOwner = require('./lib/schedule-owner.js').create({ port: PORT });
2744
- try { const _tick = setInterval(() => { try { if (!scheduleOwner.mayRun()) return; } catch { /* no lock: run as before */ } try { refreshRun.settings(); } catch { /* the refresh tick tries again */ } checkDueSchedules(); proactiveTick(); try { prepareTick({ manual: false }); } catch { /* the next tick tries again */ } try { dayTick(); } catch (e) { warnWriteFail('day run tick', e); } try { refreshRun.tick(); } catch (e) { warnWriteFail('refresh tick', e); } gated('sync', () => autoSync.tick().catch(() => {}))(); dashboardScheduleTick(); gated('driver', driverTick)(); gated('scan', scanTick)(); gated('finder', reportFinderTick)(); gated('coredocs', coreDocsTick)(); reportDesignTick(); reportStructureTick(); }, TICK_MS); if (_tick.unref) _tick.unref(); } catch {}
2770
+ try { const _tick = setInterval(() => { try { if (!scheduleOwner.mayRun()) return; } catch { /* no lock: run as before */ } try { refreshRun.settings(); } catch { /* the refresh tick tries again */ } checkDueSchedules(); proactiveTick(); try { prepareTick({ manual: false }); } catch { /* the next tick tries again */ } try { dayTick(); } catch (e) { warnWriteFail('day run tick', e); } try { refreshRun.tick(); } catch (e) { warnWriteFail('refresh tick', e); } gated('sync', () => autoSync.tick().catch(() => {}))(); dashboardScheduleTick(); orchTick(); gated('driver', driverTick)(); gated('scan', scanTick)(); gated('finder', reportFinderTick)(); gated('coredocs', coreDocsTick)(); reportDesignTick(); reportStructureTick(); }, TICK_MS); if (_tick.unref) _tick.unref(); } catch {}
2745
2771
 
2746
2772
  // ── Sessions: real PTYs, owned by the server, with disk-backed scrollback + metadata. ──
2747
2773
  /** @type {Map<string, {id,ws,name,agent,cwd,state,note,created,pty,buf,cols,rows,clients:Set}>} */
@@ -6250,6 +6276,8 @@ async function handleRequest(req, res) {
6250
6276
  let body = {};
6251
6277
  try { body = JSON.parse((await readBody(req)) || '{}'); }
6252
6278
  catch { return json(res, { ok: false, error: 'invalid JSON body' }, 400); }
6279
+ const g = pmGuard.requirePagePress(req, body); // Add workspace is a page press (premium-settings), so an agent session gets 403
6280
+ if (!g.ok) return json(res, { ok: false, error: g.error }, g.status);
6253
6281
  if (!body.root) return json(res, { ok: false, error: 'root is required' }, 400);
6254
6282
  const w = registerWorkspace(body.root, body.name);
6255
6283
  if (!w) return json(res, { ok: false, error: `not a directory: ${body.root}` }, 400);
@@ -8959,6 +8987,8 @@ async function handleRequest(req, res) {
8959
8987
  if (req.method === 'GET') return json(res, { ok: true, settings: proSettings() });
8960
8988
  if (req.method === 'POST') {
8961
8989
  let body = {}; try { body = JSON.parse((await readBody(req)) || '{}'); } catch { return json(res, { ok: false, error: 'invalid JSON body' }, 400); }
8990
+ const g = pmGuard.requirePagePress(req, body); // a settings write is a page press, so an agent session gets 403
8991
+ if (!g.ok) return json(res, { ok: false, error: g.error }, g.status);
8962
8992
  const cur = proSettings();
8963
8993
  // A patch: triggers, sources, the check and each service's levels merge over what is stored (a level of null clears it).
8964
8994
  const bs = body.scopes && typeof body.scopes === 'object' && !Array.isArray(body.scopes) ? body.scopes : null;
@@ -9371,7 +9401,8 @@ async function handleRequest(req, res) {
9371
9401
  }
9372
9402
  // pm-os-absorb Runs 2–5 — the planning layer's routes, one file per run (lib/route-modules.js). Last, so none shadows a route above.
9373
9403
  // meeting-notes Run 1: the Notes routes keep notes in the per-user runtime directory and start the agent-summary session.
9374
- if (await routeModules.dispatch(req, res, url, { json, readBody, getWs, invalidateNeedsAgg, boardCache, consoleState, stateDirFor, sessionList, initiativeIndex,
9404
+ if (req.method === 'POST' && !(req.headers && req.headers['x-pmos-session'])) orchGate.touch(); // agent-orchestrator: a page press by the PM
9405
+ if (await routeModules.dispatch(req, res, url, { orchestrator: { gate: orchGate, running: () => driver.active().length, health: orchHealth }, json, readBody, getWs, invalidateNeedsAgg, boardCache, consoleState, stateDirFor, sessionList, initiativeIndex,
9375
9406
  runtimeDir: STATE, homeRoot: HOME_ENABLED ? SELF_ROOT : null, spawnSession, jevModelOpts, sendToSession, endSupersededRuns, proSettings,
9376
9407
  // report-workspace: the schedule store a recurring report registers its draft-only schedule in, a skill's body, and the stop of a headless run
9377
9408
  scheduleStore: { read: readSchedules, write: writeSchedules },
@@ -9620,6 +9651,7 @@ wss.on('connection', (ws) => {
9620
9651
  return;
9621
9652
  }
9622
9653
  if (m.t === 'input' && !rateLimit.take(ws._rlInput)) return; // drop excess input quietly
9654
+ if (m.t === 'input' || m.t === 'attach') orchGate.touch(); // agent-orchestrator: the PM is at a terminal, so the work-hours mode applies
9623
9655
  if (m.t === 'attach') {
9624
9656
  const s = sessions.get(m.id); if (!s) return;
9625
9657
  s.clients.add(ws); ws.attached.add(s.id);
@@ -0,0 +1,11 @@
1
+ {
2
+ "_comment": "agent-orchestrator slice A: the capacity governor, the stop switch and the task ledger (pure, node).",
3
+ "modules": [
4
+ "capacity-governor.test.js",
5
+ "orchestrator-ledger.test.js"
6
+ ],
7
+ "seconds": {
8
+ "capacity-governor.test.js": 1,
9
+ "orchestrator-ledger.test.js": 1
10
+ }
11
+ }
@@ -0,0 +1,15 @@
1
+ {
2
+ "_comment": "agent-orchestrator slice B: the gate that joins the governor and the stop switch, the health rows, the nightly state backup and the status route (node, no server).",
3
+ "modules": [
4
+ "orchestrator-gate.test.js",
5
+ "orchestrator-health.test.js",
6
+ "state-backup.test.js",
7
+ "routes-orchestrator.test.js"
8
+ ],
9
+ "seconds": {
10
+ "orchestrator-gate.test.js": 1,
11
+ "orchestrator-health.test.js": 1,
12
+ "state-backup.test.js": 1,
13
+ "routes-orchestrator.test.js": 1
14
+ }
15
+ }