create-pmos 0.302.0 → 0.304.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.302.0",
3
+ "version": "0.304.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@fa83e50
1
+ kernel-source: pmos@136df86
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:11:19Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-19T07:53:58Z"}
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:11:19Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-19T07:53:58Z"}
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:11:19Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-19T07:53:58Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -269,6 +269,7 @@ Insights is the fourth place on the rail, at `/premium-insights.html`. It reads
269
269
  - **Shape a report's sections.** On a report drawn from your work, **Shape it in the Studio** opens Report mode on it. Tell PMOS how to shape the sections in your own words; PMOS proposes the next version and says what it changed. **Leave out** on a section makes the next version without it; the headline, Needs your call and Sources are always in. **Undo** goes back one version. **Use this structure** saves the version shown, and the next cycle follows it.
270
270
  - **Design how a report looks.** A set-up report in the Studio has two tabs: **1 Structure** (what it says) and **2 Design** (how it looks). The Design tab shows the versions D1 to Dn, the slides of the one shown (a large preview, previous and next, and thumbnails), and the samples the look follows. **Add a file** (PDF, PowerPoint, Word or an image) or **Add the link** (Google or Confluence) adds a sample, and PMOS says what it took from it. Say how it should look, for example "use the theme of my picture", and PMOS makes the next version. Pick a version to look at it. **Undo** goes back one version. **This is it** saves the version shown as the design, and each new cycle is drawn to it. When you open a report again, both tabs show what was said before.
271
271
  - **Choose a deck or a document, and read the design brief.** On the Design tab, the **Format** chip offers **Deck** and **Document** for the next version. Versions you already made keep their form. Once a design is saved, a **Design brief** chip shows what PMOS reads each cycle: your description, your samples, the reference version, and what stays the same, what changes and what PMOS learned. The cycles drafted to match it are checked on the report itself.
272
+ - **Point, make the next version, compare.** On the Design tab, click any part of a slide to attach a request to that spot: a numbered pin appears, and you type the request under the preview (**Point and say**; the switch turns pointing off). **Make the next version** sends the typed line and every pinned request to PMOS, which makes the next version; the pins are cleared once it starts. **Compare two** shows the same slide of two versions side by side; pick the version on each side.
272
273
  - **What stands out.** Up to three plain sentences taken from the series: behind its line for three readings in a row, behind and still moving away from the target, closing in, slipped, reached its target, or a large one-step move. There is no forecast and no cause.
273
274
  - **No series recorded.** A KR metric with one reading or none is listed with the reason and is not drawn.
274
275
  - **Ask PMOS to set up a report.** Type what the report is for and press **Ask**. A background run proposes a report and does nothing else. The request is listed as Working, then Ready to review. A ready request opens with its proposal: **Set it up**, **Change it** (say what to change; the run revises it), or **Cancel**.
@@ -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,29 @@
1
+ 'use strict';
2
+ /* orchestrator-spawn.js — puts the scheduled background jobs under the orchestrator gate (initiative agent-orchestrator, PRD "Capacity
3
+ * governor" and "Gates that stay yours").
4
+ *
5
+ * wrap({ gate, spawn, driverRunning }) → { spawn(spec), running() }
6
+ *
7
+ * `spawn(spec)` is used ONLY by the schedule ticks (the core documents, the weekly report finder). A run the PM starts by a press uses the
8
+ * plain spawn and is never counted or held. Before it starts a run the wrapper asks gate.mayStart. A held start returns an exited session
9
+ * row with a note, which the callers already read as "could not start"; they try again on their next tick, so nothing is lost or refused.
10
+ * A run that started is counted toward the day's cap (gate.granted). The count of running runs adds the Driver's runs to the runs
11
+ * started here that have not ended, so the cap covers all orchestrator work together. */
12
+ function wrap({ gate, spawn, driverRunning = () => 0 }) {
13
+ const live = new Set();
14
+ const prune = () => { for (const s of [...live]) if (!s || s.state === 'exited') live.delete(s); };
15
+ const running = () => { prune(); return live.size + (Number(driverRunning()) || 0); };
16
+ function held(reason) { return { id: null, state: 'exited', headless: null, note: `held by the capacity governor: ${reason}` }; }
17
+ return {
18
+ running,
19
+ spawn(spec) {
20
+ let g = { allowed: true };
21
+ try { g = gate.mayStart({ running: running() }) || g; } catch { /* a broken gate must not stop the PM's schedules */ }
22
+ if (!g.allowed) return held(g.reason || 'it is not time to start more runs');
23
+ const s = spawn(spec);
24
+ if (s && s.state !== 'exited') { live.add(s); try { gate.granted(); } catch { /* a counter */ } }
25
+ return s;
26
+ },
27
+ };
28
+ }
29
+ module.exports = { wrap };
@@ -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.302.0",
3
+ "version": "0.304.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.302.0",
9
+ "version": "0.304.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.302.0",
3
+ "version": "0.304.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",
@@ -84,7 +84,8 @@ const model = async () => (await (await fetch(BASE + '/api/insights-premium')).j
84
84
 
85
85
  const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } }), p = await ctx.newPage(), errs = [], posts = [];
86
86
  p.on('pageerror', (e) => errs.push(String(e)));
87
- p.on('request', (r) => { if (r.method() === 'POST') posts.push(new URL(r.url()).pathname); });
87
+ const turnBodies = [];
88
+ p.on('request', (r) => { if (r.method() === 'POST') { posts.push(new URL(r.url()).pathname); if (/report-design\/turn$/.test(r.url())) turnBodies.push(r.postData() || ''); } });
88
89
  await p.goto(BASE + '/premium-insights.html');
89
90
  await until(() => p.evaluate(() => !!document.querySelector('#repNew')));
90
91
  const M0 = await model(), bname = M0.board.name;
@@ -214,6 +215,7 @@ const model = async () => (await (await fetch(BASE + '/api/insights-premium')).j
214
215
  await tap('#oMain [data-st="save"]');
215
216
  await until(() => chipv('dsv').then((v) => v === 'D1, saved'));
216
217
  ok('D5 This is it saves D1 as the design, and is then not offered', await chipv('dsv') === 'D1, saved' && await cta() === 'This is it:off' && posts.includes('/api/report-design/accept'), await chipv('dsv'));
218
+ await until(() => p.evaluate(() => { const b = document.querySelector('#stPv [data-st="dznext"]'); return !!b && !b.disabled; }), 30000); // the cycle redraw after This is it has finished
217
219
  ok('B3 the Design brief chip appears once a design is saved, and not before', await chipv('dbr') === 'D1');
218
220
  await tap('#oMain [data-st="chip|dbr"]'); await sleep(150);
219
221
  const brTxt = await p.evaluate(() => (document.querySelector('#stTr') || {}).textContent || '');
@@ -221,6 +223,20 @@ const model = async () => (await (await fetch(BASE + '/api/insights-premium')).j
221
223
  const nDesc = posts.filter((x) => x === '/api/report-design/describe').length;
222
224
  await tap('#oMain [data-st="chip|dfmt"]'); await sleep(100); await tap('#stTr [data-st="dzfmt|doc"]'); await sleep(600);
223
225
  ok('F7 with a description saved, choosing Document posts it with the format', posts.filter((x) => x === '/api/report-design/describe').length === nDesc + 1 && await chipv('dfmt') === 'Document', posts.join());
226
+ /* D7 to D9: point and say, make the next version, compare two */
227
+ await until(() => p.evaluate(() => { const b = document.querySelector('#stPv [data-st="dznext"]'); return !!b && !b.disabled; }), 30000);
228
+ await p.click('#dzSlide', { position: { x: 200, y: 100 } });
229
+ await until(() => p.evaluate(() => document.querySelectorAll('#stPv .dzpin').length === 1));
230
+ await p.fill('#stPv [data-dzp="1"]', 'Make this bigger');
231
+ ok('D7 a click on the slide attaches a request, typed under the preview', await p.evaluate(() => document.querySelectorAll('#stPv .dzsay li').length === 1 && document.querySelector('#stPv [data-dzp="1"]').value === 'Make this bigger'));
232
+ await tap('#stPv [data-st="dznext"]');
233
+ await until(() => dver().then((v) => /D2\*/.test(v)), 60000);
234
+ const tb = turnBodies[turnBodies.length - 1] || '';
235
+ ok('D8 Make the next version makes D2 and sends the pointed request with its slide, x and y', /D2\*/.test(await dver()) && /"points":\[\{"n":1,"slide":"[a-z]+","x":[0-9.]+,"y":[0-9.]+,"text":"Make this bigger"\}\]/.test(tb), (await dver()) + ' ' + tb);
236
+ await tap('#stPv [data-st="dzcmp"]'); await sleep(500);
237
+ ok('D9 Compare two shows the same slide of two versions side by side', await p.evaluate(() => document.querySelectorAll('#stPv .dzcc').length === 2 && document.querySelectorAll('#stPv .dzcc .rdbig').length === 2));
238
+ await tap('#stPv [data-st="dzcmp"]'); await sleep(200);
239
+ await tap('#oMain [data-st="save"]'); await until(() => chipv('dsv').then((v) => v === 'D2, saved'));
224
240
  await shot('report-design-1280');
225
241
  await p.click('#oMain [data-st="rtab|structure"]');
226
242
  await until(() => chipv('ver').then((v) => /^S/.test(v)));
@@ -22,12 +22,13 @@ export function useStudio(x) { X = x; }
22
22
  const hand = () => X.P.design;
23
23
 
24
24
  /* ── the state of one report's design, kept on its draft: d.D = { design, err, loading, shown, ver: Map, i } ── */
25
- export function fresh() { return { fmt: null, design: null, err: '', loading: false, shown: null, ver: new Map(), i: 0, working: false, link: '' }; }
25
+ export function fresh() { return { fmt: null, design: null, err: '', loading: false, shown: null, ver: new Map(), i: 0, working: false, link: '', points: [], point: true, cmp: false, cmpB: null }; }
26
26
  const FMTN = { deck: 'Deck', doc: 'Document' };
27
27
  const fmtOf = (z) => z.fmt || (z.design && z.design.format) || 'deck';
28
28
  const saved = (z) => (z.design && z.design.saved ? z.design.saved.version : null);
29
29
  const versions = (z) => (z.design && z.design.versions) || [];
30
- const slidesOf = (z) => { const r = z.ver.get(z.shown); return r ? r.slides.map((s) => ({ k: 'frame', h: s.h, html: s.html, css: r.style })) : []; };
30
+ const slidesAt = (z, n) => { const r = z.ver.get(n); return r ? r.slides.map((s) => ({ k: 'frame', h: s.h, id: ((/data-slide-id="([^"]*)"/.exec(s.html) || [])[1]) || '', html: s.html, css: r.style })) : []; };
31
+ const slidesOf = (z) => slidesAt(z, z.shown);
31
32
 
32
33
  export async function load(d) {
33
34
  const z = d.Z; z.loading = true;
@@ -112,13 +113,29 @@ export function preview(d) {
112
113
  if (!v.length) return `<div class="stpvw"><p class="note">${z.working ? 'PMOS is making the first version.' : 'No version yet. Add a sample, or say how the report should look. PMOS makes D1.'}</p></div>`;
113
114
  const L = slidesOf(z), i = z.i = Math.max(0, Math.min(z.i, L.length - 1));
114
115
  const strip = `<span class="rdv" role="group" aria-label="Design versions">${v.map((x) => `<button type="button" data-st="dzver|${x.n}" aria-pressed="${x.n === z.shown}"${z.working ? ' disabled' : ''} title="${esc((x.n === n ? 'Saved. ' : '') + (x.turn || ''))}" aria-label="D${x.n}${x.n === n ? ', saved' : ''}">D${x.n}${x.n === n ? CHK : ''}</button>`).join('')}</span>`;
115
- const big = L.length ? `<div class="rdk"><div class="rdbig" id="dzSlide" tabindex="0" role="group" aria-roledescription="slide" aria-label="Slide ${i + 1} of ${L.length}: ${esc(L[i].h)}">${slideCard(L[i])}</div>`
116
- + `<div class="rdnv"><button type="button" data-st="dzgo|${i - 1}" aria-label="Previous slide"${i === 0 ? ' disabled' : ''}>${PREV}</button><span>${i + 1} / ${L.length}</span><button type="button" data-st="dzgo|${i + 1}" aria-label="Next slide"${i === L.length - 1 ? ' disabled' : ''}>${NEXT}</button></div>`
116
+ const tools = `<span class="dzact"><button type="button" class="dmcta alt" data-st="dzcmp" aria-pressed="${z.cmp}"${v.length < 2 ? ' disabled' : ''}>Compare two</button><button type="button" class="dmcta" data-st="dznext"${z.working ? ' disabled' : ''}>Make the next version</button></span>`;
117
+ const note = `<span class="note">${z.working ? 'PMOS is working on the next version.' : z.shown === n ? 'The saved design.' : 'Not saved. Press This is it to keep it.'}</span>`;
118
+ const nav = (len) => `<div class="rdnv"><button type="button" data-st="dzgo|${i - 1}" aria-label="Previous slide"${i === 0 ? ' disabled' : ''}>${PREV}</button><span>${i + 1} / ${len}</span><button type="button" data-st="dzgo|${i + 1}" aria-label="Next slide"${i >= len - 1 ? ' disabled' : ''}>${NEXT}</button></div>`;
119
+ if (z.cmp) return `<div class="stpvw dzpv"><div class="dzbar">${strip}${tools}${note}</div>${compare(z, i, nav)}</div>`;
120
+ const pins = z.points.filter((q) => L[i] && q.slide === L[i].id).map((q) => `<span class="dzpin" data-x="${q.x}" data-y="${q.y}" aria-hidden="true">${q.n}</span>`).join('');
121
+ const big = L.length ? `<div class="rdk"><div class="rdbig dzbig" id="dzSlide" tabindex="0" role="group" aria-roledescription="slide" aria-label="Slide ${i + 1} of ${L.length}: ${esc(L[i].h)}.${z.point ? ' Click a part of it to attach a request.' : ''}">${slideCard(L[i])}${pins}</div>${nav(L.length)}`
117
122
  + `<div class="rdt dzth" role="group" aria-label="Slides">${L.map((x, j) => `<button type="button" data-st="dzgo|${j}"${j === i ? ' aria-current="true"' : ''} aria-label="Slide ${j + 1}: ${esc(x.h)}">${slideCard(x, true)}<i>${j + 1}</i></button>`).join('')}</div></div>`
118
123
  : '<p class="note">This version is not drawn as slides. It is a page.</p>';
119
- return `<div class="stpvw dzpv"><div class="dzbar">${strip}<span class="note">${z.working ? 'PMOS is working on the next version.' : z.shown === n ? 'The saved design.' : 'Not saved. Press This is it to keep it.'}</span></div>${big}</div>`;
124
+ const say = `<div class="dzsay"><div class="dzsh"><span class="label">Point and say <b>${z.points.length}</b></span><label class="dzon"><input type="checkbox" id="dzPoint"${z.point ? ' checked' : ''}> On</label></div>`
125
+ + (z.points.length ? `<ul class="sul">${z.points.map((q) => `<li><span class="dzpn">${q.n}</span><input class="sti" data-dzp="${q.n}" value="${esc(q.text)}" placeholder="What should change here? Slide ${esc(q.slide)}" maxlength="1000" aria-label="Request ${q.n}, on slide ${esc(q.slide)}" autocomplete="off"><button type="button" class="lk" data-st="dzpx|${q.n}" aria-label="Remove request ${q.n}">Remove</button></li>`).join('')}</ul><p class="note">The next version carries these. Make the next version, or say it in the chat.</p>` : `<p class="note">${z.point ? 'Click any part of the preview to attach a request to it.' : 'Pointing is off.'}</p>`) + '</div>';
126
+ return `<div class="stpvw dzpv"><div class="dzbar">${strip}${tools}${note}</div>${big}${L.length ? say : ''}</div>`;
120
127
  }
121
- export function afterDraw() { const m = $('#stPv'); if (m) fit(m); }
128
+ /* Compare two: the same slide of two versions side by side */
129
+ function compare(z, i, nav) {
130
+ const v = versions(z);
131
+ const B = z.cmpB != null && v.some((x) => x.n === z.cmpB) ? z.cmpB : ((v.filter((x) => x.n !== z.shown).pop() || {}).n);
132
+ z.cmpB = B;
133
+ const A = slidesOf(z), Bs = slidesAt(z, B), len = Math.max(A.length, Bs.length);
134
+ const pick = (k, cur) => `<span class="rdv" role="group" aria-label="${k === 'dzcl' ? 'Left' : 'Right'} version">${v.map((x) => `<button type="button" data-st="${k}|${x.n}" aria-pressed="${x.n === cur}">D${x.n}</button>`).join('')}</span>`;
135
+ const cell = (L, n, k) => `<div class="dzcc"><div class="dzch">${pick(k, n)}</div>${L[i] ? `<div class="rdbig" role="group" aria-label="D${n}, slide ${i + 1}: ${esc(L[i].h)}">${slideCard(L[i])}</div>` : `<p class="note">D${n} has no slide ${i + 1}.</p>`}</div>`;
136
+ return `<div class="dzcmp"><div class="dzcg">${cell(A, z.shown, 'dzcl')}${cell(Bs, B, 'dzcr')}</div>${nav(len)}<p class="note">Left is the version shown. Press Compare two again to go back to one.</p></div>`;
137
+ }
138
+ export function afterDraw() { const m = $('#stPv'); if (!m) return; fit(m); m.querySelectorAll('.dzpin').forEach((p) => { p.style.setProperty('--rp-pinx', p.dataset.x + '%'); p.style.setProperty('--rp-piny', p.dataset.y + '%'); }); }
122
139
  export function checks(d) {
123
140
  const z = d.Z, S = (z.design || {}).samples || [], n = saved(z), v = versions(z);
124
141
  return [
@@ -139,6 +156,11 @@ export async function press(d, a) {
139
156
  const [k, v] = a, z = d.Z;
140
157
  if (k === 'dzgo') { z.i = +v; X.draw(['pv']); afterDraw(); const s = $('#dzSlide'); if (s) s.focus(); return; }
141
158
  if (k === 'dzver') { await show(d, +v, true); return; }
159
+ if (k === 'dzcmp') { z.cmp = !z.cmp; if (z.cmp) { const V = versions(z).filter((x) => x.n !== z.shown); z.cmpB = (V.pop() || {}).n; await read(z, z.cmpB); } X.draw(['pv']); afterDraw(); return; }
160
+ if (k === 'dzcl') { z.shown = +v; await read(z, z.shown); X.draw(); afterDraw(); return; }
161
+ if (k === 'dzcr') { z.cmpB = +v; await read(z, z.cmpB); X.draw(['pv']); afterDraw(); return; }
162
+ if (k === 'dzpx') { z.points = z.points.filter((q) => q.n !== +v); X.draw(['pv']); afterDraw(); return; }
163
+ if (k === 'dznext') { const i = $('#stIn'), t = i ? i.value.trim() : ''; X.converse(t || (z.points.length ? 'Make the next version with the requests I pointed at.' : 'Make the next version.')); return; }
142
164
  if (k === 'dzfmt') { await setFmt(d, v); return; }
143
165
  if (k === 'dzkeep') { await keep(d); return; }
144
166
  if (k === 'dzpick') { const f = $('#dzFile'); if (f) f.click(); return; }
@@ -178,6 +200,18 @@ export async function keep(d) {
178
200
  if (!r || r.ok !== true) { s.msg = (r && r.error) || 'The design could not be saved.'; X.draw(); return; }
179
201
  z.design = r.design; s.msg = 'D' + n + ' is saved as the design. ' + (r.redraw && r.redraw.started ? 'PMOS is drawing the current cycle to match it.' : 'Each new cycle is drawn to match it.');
180
202
  X.draw(); afterDraw(); X.P.reportsChanged();
203
+ // the cycle is redrawn to the saved design by the one design job of this report; a turn waits for it
204
+ if (r.redraw && r.redraw.started) {
205
+ z.working = true; X.draw();
206
+ const t0 = Date.now();
207
+ for (;;) {
208
+ await new Promise((ok) => setTimeout(ok, POLL_MS));
209
+ if (X.r() !== d) return;
210
+ const g = await refresh(d);
211
+ if (!g || !g.running || Date.now() - t0 > POLL_MAX) break;
212
+ }
213
+ z.working = false; X.draw(); afterDraw();
214
+ }
181
215
  }
182
216
  async function sample(d, body) {
183
217
  const z = d.Z, s = X.st; s.msg = 'Adding the sample.'; X.draw(['ft']);
@@ -208,8 +242,10 @@ export async function turn(d, t, low) {
208
242
  if (!r0 || r0.ok !== true) { z.working = false; X.draw(); return 'The description was not saved: ' + ((r0 && r0.error) || 'the press did not go through.'); }
209
243
  }
210
244
  const before = ((z.design && z.design.log) || []).length;
211
- const r = await hand().post('turn', d.id, { text: t });
245
+ const pts = z.points.filter((q) => q.text.trim() && q.slide).map((q) => ({ n: q.n, slide: q.slide, x: q.x, y: q.y, text: q.text.trim() }));
246
+ const r = await hand().post('turn', d.id, pts.length ? { text: t, points: pts } : { text: t });
212
247
  if (!r || r.ok !== true) { z.working = false; X.draw(); return 'Nothing changed: ' + ((r && r.error) || 'the change could not start.'); }
248
+ z.points = []; X.draw(['pv']); afterDraw();
213
249
  return wait(d, before);
214
250
  }
215
251
  async function wait(d, before) {
@@ -228,3 +264,23 @@ async function wait(d, before) {
228
264
  if (Date.now() - t0 > POLL_MAX) { z.working = false; X.draw(); return 'PMOS has not answered yet. The version shows when you open this report again.'; }
229
265
  }
230
266
  }
267
+
268
+ /* Point and say: a click on the slide attaches a request to that spot; each request is typed under the preview. */
269
+ const inDesign = (e) => { const r = X && X.r && X.r(); return r && r.kind === 'setup' && r.tab === 'design' && $('#dlg').classList.contains('stud') && $('#dlg').classList.contains('on') && e.target.closest && e.target.closest('#oMain'); };
270
+ document.addEventListener('click', (e) => {
271
+ if (!inDesign(e)) return;
272
+ const big = e.target.closest('#dzSlide'); if (!big) return;
273
+ const d = X.r(), z = d.Z; if (!z.point || z.working || z.cmp) return;
274
+ const L = slidesOf(z), sl = L[Math.max(0, Math.min(z.i, L.length - 1))]; if (!sl || !sl.id) return;
275
+ const b = big.getBoundingClientRect(); if (!b.width) return;
276
+ if (z.points.length >= 20) return;
277
+ const n = z.points.reduce((m, q) => Math.max(m, q.n), 0) + 1;
278
+ z.points.push({ n, slide: sl.id, x: Math.round(((e.clientX - b.left) / b.width) * 1000) / 10, y: Math.round(((e.clientY - b.top) / b.height) * 1000) / 10, text: '' });
279
+ X.draw(['pv']); afterDraw();
280
+ const i = document.querySelector(`#stPv [data-dzp="${n}"]`); if (i) i.focus();
281
+ });
282
+ document.addEventListener('input', (e) => {
283
+ if (!inDesign(e) || !e.target.dataset || !e.target.dataset.dzp) return;
284
+ const q = X.r().Z.points.find((x) => x.n === +e.target.dataset.dzp); if (q) q.text = e.target.value;
285
+ });
286
+ document.addEventListener('change', (e) => { if (inDesign(e) && e.target.id === 'dzPoint') { X.r().Z.point = e.target.checked; X.draw(['pv']); afterDraw(); } });
@@ -26,7 +26,7 @@ const HELP = 'I understand: call it something, it answers something (or a questi
26
26
  const HELPS = 'Tell me how to shape the sections in your own words, for example: leave out the timeline, or put the decisions first. PMOS proposes the next version; nothing is saved until you press Use this structure. Undo goes back one version.';
27
27
 
28
28
  let X = null; // the Studio's hand: { st, P, chip, opt, field, draw, plural }
29
- export function useStudio(x) { X = x; DES.useStudio({ get st() { return x.st; }, get P() { return x.P; }, chip: x.chip, draw: x.draw, say: x.say, restream: x.restream, r: () => x.st.r }); }
29
+ export function useStudio(x) { X = x; DES.useStudio({ get st() { return x.st; }, get P() { return x.P; }, chip: x.chip, draw: x.draw, say: x.say, restream: x.restream, converse: x.converse, r: () => (x.st ? x.st.r : null) }); }
30
30
  const design = (d) => d.kind === 'setup' && d.tab === 'design';
31
31
  const st = () => X.st;
32
32
  const r = () => X.st.r;
@@ -439,6 +439,7 @@ export function openStudio(p) {
439
439
  REP.useStudio({ get st() { return st; }, get P() { return P; }, chip: (k, l, v) => chip(k, l, v), opt: (...a) => opt(...a), field: (...a) => field(...a), draw: (x) => draw(x), snap: () => snap(),
440
440
  replay: (L) => { const el = $('#dBody .stream'); if (!el || !L.length) return; el.insertAdjacentHTML('beforeend', L.map((x) => (x.who === 'u' ? turnU(x.text) : turnA(ptx(x.text)))).join('')); el.scrollTop = el.scrollHeight; },
441
441
  say: (text) => { const el = $('#dBody .stream'); if (!el) return; el.insertAdjacentHTML('beforeend', turnA(ptx(text))); el.scrollTop = el.scrollHeight; draw(); },
442
+ converse: (t) => { const i = $('#stIn'), f = $('#stF'); if (!i || !f) return; i.value = t; if (f.requestSubmit) f.requestSubmit(); else f.dispatchEvent(new Event('submit', { cancelable: true, bubbles: true })); },
442
443
  restream: (L) => { const el = $('#dBody .stream'); if (!el) return; el.innerHTML = L.map((x) => (x.who === 'u' ? turnU(x.text) : turnA(ptx(x.text)))).join(''); el.scrollTop = el.scrollHeight; },
443
444
  done: (msg) => { closeDlg(); toast(msg); P.reportsChanged(); } });
444
445
  /* The Studio's presses. The dialog is shared, so each listener first asks whether the Studio is what it holds. */
@@ -1961,3 +1961,16 @@ button.wl-row[aria-pressed="true"] .wl-tog{background:var(--solid);color:var(--o
1961
1961
  .dlg.stud.sz-half[data-mode="split"] .dgrid{grid-template-columns:minmax(0,1fr)}
1962
1962
  .dlg.stud.sz-half[data-mode="split"] .dgrid[data-tab="chat"] .p-out,.dlg.stud.sz-half[data-mode="split"] .dgrid[data-tab="out"] .p-work{display:none}
1963
1963
  }
1964
+ .dzact{display:inline-flex;gap:8px;flex-wrap:wrap;margin-left:auto}
1965
+ .dzact .dmcta[aria-pressed="true"]{background:var(--solid);color:var(--on-solid)}
1966
+ .dzbig{position:relative;cursor:crosshair}
1967
+ .dzpin{position:absolute;left:var(--rp-pinx,0);top:var(--rp-piny,0);transform:translate(-50%,-50%);min-width:24px;height:24px;padding:0 6px;border-radius:999px;background:var(--ember);color:var(--on-solid);font:700 12px var(--mono);display:grid;place-items:center;box-shadow:0 1px 4px color-mix(in oklab,var(--ink) 30%,transparent);pointer-events:none}
1968
+ .dzsay{margin-top:12px;padding:12px;border-radius:14px;background:var(--well)}
1969
+ .dzsh{display:flex;align-items:center;justify-content:space-between;gap:8px}
1970
+ .dzon{display:inline-flex;align-items:center;gap:6px;min-height:44px;font-size:13px}
1971
+ .dzsay .sul li{display:flex;align-items:center;gap:8px}
1972
+ .dzsay .sul .sti{flex:1 1 auto;min-width:0}
1973
+ .dzpn{flex:0 0 auto;min-width:24px;height:24px;border-radius:999px;background:var(--ember);color:var(--on-solid);font:700 12px var(--mono);display:grid;place-items:center}
1974
+ .dzcg{display:grid;grid-template-columns:1fr 1fr;gap:12px}
1975
+ @media (max-width:700px){.dzcg{grid-template-columns:1fr}}
1976
+ .dzch{margin-bottom:6px}
@@ -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,30 @@ 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
+ // agent-orchestrator: the scheduled background jobs (core documents, the weekly finder) start through the gate, so the stop switch, the
2609
+ // away/working caps and the daily cap govern them with the Driver. A press by the PM uses the plain spawnSession and is never held.
2610
+ const orchSpawn = require('./lib/orchestrator-spawn.js').wrap({ gate: orchGate, spawn: (spec) => spawnSession(spec), driverRunning: () => driver.active().length });
2611
+ const orchHealth = () => {
2612
+ const backupLib = require('./lib/state-backup.js'), log = backupLib.readLog(STATE);
2613
+ return require('./lib/orchestrator-health.js').rows({ now: Date.now(), stopped: orchGate.status({}).stopped, lastTickAt: orchLastTickAt, tickMs: TICK_MS,
2614
+ diskFreeFrac: require('./lib/orchestrator-health.js').diskFreeFrac(STATE), loginHeld: driver.loginHeld(),
2615
+ backup: { configured: !!orchGate.backupDir(), lastOkAt: log.lastOkAt, lastError: log.lastError } });
2616
+ };
2617
+ const orchTick = () => {
2618
+ orchLastTickAt = Date.now();
2619
+ try {
2620
+ const dest = orchGate.backupDir();
2621
+ if (!dest || orchBackupRunning) return;
2622
+ const backupLib = require('./lib/state-backup.js');
2623
+ if (orchGate.status({}).mode !== 'away' || !backupLib.due({ now: Date.now(), lastOkAt: backupLib.readLog(STATE).lastOkAt })) return;
2624
+ orchBackupRunning = true;
2625
+ const r = backupLib.run({ src: STATE, dest, now: Date.now() });
2626
+ 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 });
2627
+ orchBackupRunning = false;
2628
+ } catch (e) { orchBackupRunning = false; warnWriteFail('orchestrator tick', e); }
2629
+ };
2601
2630
  // 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
2631
  // 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
2632
  const scanRoutesCtx = () => ({ getWs, stateDirFor, workspaceList: () => [...workspaces.values()], runtimeDir: STATE, selfRoot: EMBEDDED_SELF ? SELF_ROOT : null });
@@ -2637,7 +2666,7 @@ const reportFinder = reportFinderLib.create({
2637
2666
  headlessOff: () => headlessLib.switchedOff(process.env),
2638
2667
  env: process.env,
2639
2668
  promptFor: (skillId) => { const h = homeWorkspace(); const t = taskById(skillId, h ? h.root : SELF_ROOT); return t && t.prompt ? t.prompt : null; },
2640
- spawn: (spec) => spawnSession({ name: spec.name, agent: 'claude', ws: spec.ws, origin: spec.origin, initialInput: spec.initialInput, extraEnv: spec.env, autoDelete: undefined, onDone: spec.onDone }),
2669
+ spawn: (spec) => orchSpawn.spawn({ name: spec.name, agent: 'claude', ws: spec.ws, origin: spec.origin, initialInput: spec.initialInput, extraEnv: spec.env, autoDelete: undefined, onDone: spec.onDone }),
2641
2670
  stop: (s) => { if (s && s.child) stopHeadless(s); },
2642
2671
  warn: (what, e) => warnWriteFail(what, e),
2643
2672
  });
@@ -2678,7 +2707,7 @@ const coreDocsTick = () => {
2678
2707
  const t = process.env.PMOS_CORE_DOCS_NOW ? Date.parse(process.env.PMOS_CORE_DOCS_NOW) : NaN;
2679
2708
  try {
2680
2709
  m.tick({ getWs, stateDirFor, workspaceList: () => [...workspaces.values()], runtimeDir: STATE, selfRoot: EMBEDDED_SELF ? SELF_ROOT : null, initiativeIndex,
2681
- spawnSession, stopSession: (id) => { const x = sessions.get(String(id || '')); if (x && x.child) stopHeadless(x); }, invalidateNeedsAgg,
2710
+ spawnSession: orchSpawn.spawn, stopSession: (id) => { const x = sessions.get(String(id || '')); if (x && x.child) stopHeadless(x); }, invalidateNeedsAgg,
2682
2711
  proSettings, inQuiet: (now, quiet) => proactiveLib.inQuietHours(now, quiet), isLead: (w) => isPlanNeedsTree(w) }, Number.isFinite(t) ? { now: t } : {});
2683
2712
  } catch (e) { warnWriteFail('core documents tick', e); }
2684
2713
  };
@@ -2741,7 +2770,7 @@ const gated = (id, fn) => () => { let g = { ok: true }; try { g = refreshRun.job
2741
2770
  // data-refresh-settings: the seed schedules move to Settings › Data refresh (refreshRun.settings(), once) BEFORE checkDueSchedules reads
2742
2771
  // schedules.json, so a schedule that is moving never fires once more from the old list on the first tick after an upgrade.
2743
2772
  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 {}
2773
+ 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
2774
 
2746
2775
  // ── Sessions: real PTYs, owned by the server, with disk-backed scrollback + metadata. ──
2747
2776
  /** @type {Map<string, {id,ws,name,agent,cwd,state,note,created,pty,buf,cols,rows,clients:Set}>} */
@@ -9375,7 +9404,8 @@ async function handleRequest(req, res) {
9375
9404
  }
9376
9405
  // 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.
9377
9406
  // meeting-notes Run 1: the Notes routes keep notes in the per-user runtime directory and start the agent-summary session.
9378
- if (await routeModules.dispatch(req, res, url, { json, readBody, getWs, invalidateNeedsAgg, boardCache, consoleState, stateDirFor, sessionList, initiativeIndex,
9407
+ if (req.method === 'POST' && !(req.headers && req.headers['x-pmos-session'])) orchGate.touch(); // agent-orchestrator: a page press by the PM
9408
+ 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,
9379
9409
  runtimeDir: STATE, homeRoot: HOME_ENABLED ? SELF_ROOT : null, spawnSession, jevModelOpts, sendToSession, endSupersededRuns, proSettings,
9380
9410
  // 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
9381
9411
  scheduleStore: { read: readSchedules, write: writeSchedules },
@@ -9624,6 +9654,7 @@ wss.on('connection', (ws) => {
9624
9654
  return;
9625
9655
  }
9626
9656
  if (m.t === 'input' && !rateLimit.take(ws._rlInput)) return; // drop excess input quietly
9657
+ if (m.t === 'input' || m.t === 'attach') orchGate.touch(); // agent-orchestrator: the PM is at a terminal, so the work-hours mode applies
9627
9658
  if (m.t === 'attach') {
9628
9659
  const s = sessions.get(m.id); if (!s) return;
9629
9660
  s.clients.add(ws); ws.attached.add(s.id);
@@ -0,0 +1,17 @@
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, and the wrapper that puts the scheduled jobs under the gate (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
+ "orchestrator-spawn.test.js"
9
+ ],
10
+ "seconds": {
11
+ "orchestrator-gate.test.js": 1,
12
+ "orchestrator-health.test.js": 1,
13
+ "state-backup.test.js": 1,
14
+ "routes-orchestrator.test.js": 1,
15
+ "orchestrator-spawn.test.js": 1
16
+ }
17
+ }