create-pmos 0.300.0 → 0.302.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.300.0",
3
+ "version": "0.302.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@5fa27d4
1
+ kernel-source: pmos@fa83e50
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:00:37Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-19T07:11:19Z"}
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:00:37Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-19T07:11:19Z"}
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:00:37Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-19T07:11:19Z"}
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);
@@ -193,11 +193,13 @@ My work is the second place on the rail, at `/premium-work.html`. It reads the l
193
193
 
194
194
  **Weekly review.** A card lists five steps: sort the inbox, place your tray, check who owes you, review agent drafts, and look at what sat untouched. Each step shows a count from your list and opens its first item. **Start the review** opens the first step that has something. On a Friday the card reads Friday review. PMOS keeps no review schedule and no timing, so the card shows none. The tray's tabs are drawn from your own items (see below). Answers, ideas and reports an agent files by itself are not shown, because PMOS holds no records for them.
195
195
 
196
+ **Decide.** An inbox row shows a **Decide** button that opens the item, where you give it a day, put it in Someday or drop it.
197
+
196
198
  **Tray tabs.** The tray has six tabs, each built from your item records: **To place**, **Ready** (an agent draft is ready), **Working** (an agent is running), **Kept** (you pressed Keep), **Used** (done in the last 7 days) and **Compost** (untouched for the review days). A row shows a button that fits its tab: Today, Review, Use it, or Let go.
197
199
 
198
200
  **The item dialog.** The dialog shows **Done**, **Not yet** (Later today, Tomorrow, Next week, Do today) and **Drop it**. **More** opens the rest: Edit, Who does each step, Not before, Someday and Waiting on someone. Every action stays reachable.
199
201
 
200
- **The agent's draft.** The draft shows as formatted text in the detail panel on the right, labelled as the agent's and not checked, with **Open** and **Copy**. It appears there as soon as the agent finishes, even while the dialog is open. The left column keeps the conversation (with **View round**) and the decision cards, in the console's words: **Post it to Jira** (marked outward, with exactly the text that goes), **Edit the draft**, **Keep it as a draft** and **Mark it done**. Post asks you to confirm the exact text first, and nothing is posted before that.
202
+ **The agent's draft.** The draft shows as formatted text in the detail panel on the right, labelled as the agent's and not checked, with **Open** and **Copy**. Its heading names the item ("Draft for IDPF-2989", or "Draft for you"), the round and the time of the latest round, and an approved step shows as "Step when you approve". A long draft is cut short, with **Show all**. It appears there as soon as the agent finishes, even while the dialog is open. The left column keeps the conversation (with **View round**) and the decision cards, in the console's words: **Post it to Jira** (marked outward, with exactly the text that goes), **Edit the draft**, **Keep it as a draft** and **Mark it done**. Post asks you to confirm the exact text first, and nothing is posted before that.
201
203
 
202
204
  **An agent's offer.** When an agent has offered to draft an item, the dialog shows three choices: let the agent draft it (suggested), do it today, or not before next Monday. You pick one and press its button. A row with steps says how many it has and how many an agent can do. PMOS does not record that a step is done, so it shows no "done" count.
203
205
 
@@ -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 };
@@ -55,7 +55,9 @@ function agentDetail(it) {
55
55
  if (a.state === 'suggest' && !(a.instruction || a.suggest)) return null; // an offer with no words behind it is not drawn
56
56
  const mine = isLocal(it) && !it.origin;
57
57
  const d = a.draft || null;
58
+ const rounds = (Array.isArray(a.log) ? a.log : []).filter((t) => t && t.body), lastRound = rounds[rounds.length - 1] || null;
58
59
  return {
60
+ ref: it.key || null, round: rounds.length || (d ? 1 : 0), round_at: lastRound ? lastRound.at || null : null,
59
61
  state: a.state, ask: clip(a.instruction || a.suggest || '', 500),
60
62
  draft: d ? { summary: clip(d.summary || '', 300), body: String(d.body || '').slice(0, 4000), step: d.step ? clip(d.step, 200) : null } : null,
61
63
  error: a.error ? clip(a.error, 300) : null, asks: !!a.asks, session: a.session || null,
@@ -84,7 +86,8 @@ function suggestOf(it, list, today, overdue) {
84
86
  else if (overdue) sug = { b: 'Overdue.', t: 'It was due ' + shortDate(it.due) + ' and is still open.' };
85
87
  else if (d === 0) sug = { b: 'Due today.', t: 'Its date is today.' };
86
88
  else if (d != null && d > 0 && d <= 6) sug = { b: 'This week.', t: 'Its date is ' + shortDate(it.due) + '.' };
87
- if (!cta && list !== 'waiting' && !isRunning(it) && state !== 'failed') cta = list === 'today' ? { label: 'Tomorrow', act: 'tomorrow' } : { label: 'Today', act: 'today' };
89
+ if (!cta && list === 'inbox') cta = { label: 'Decide', act: 'open' }; // the console's Decide: the item opens, where it gets a day, Someday or a drop
90
+ else if (!cta && list !== 'waiting' && !isRunning(it) && state !== 'failed') cta = list === 'today' ? { label: 'Tomorrow', act: 'tomorrow' } : { label: 'Today', act: 'today' };
88
91
  return { sug, cta };
89
92
  }
90
93
 
@@ -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 };
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.300.0",
3
+ "version": "0.302.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.300.0",
9
+ "version": "0.302.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.300.0",
3
+ "version": "0.302.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",
@@ -195,7 +195,7 @@ const mk = (edit) => { const v = F.view(); if (edit) edit(v); return WP.build({
195
195
  const RD = await open({ model: mk((v) => { v.work.today[0].origin = 'jira'; v.work.today[0].place = null; }) }), q = RD.page;
196
196
  await openKey(q, 'work:wbs:alpha:4.2');
197
197
  const rd = await q.evaluate(() => ({ state: document.querySelector('.agblk').dataset.state, tag: document.querySelector('.agpane .agtag').textContent, body: document.querySelector('.agpane').textContent, btn: [...document.querySelectorAll('.agblk .xco b, .agblk > .cact button')].map((b) => b.textContent.trim()), copy: !!document.querySelector('[data-pp="copy"]'), open: !!document.querySelector('[data-pp="open"]') }));
198
- ok('W7 a ready draft is labelled the agent\'s, unchecked, and shows it in the detail panel with Open and Copy, and offers Post, Edit, Keep, Mark done and Send back', rd.state === 'ready' && /Agent draft · not checked/.test(rd.tag) && /sign off A and B/.test(rd.body) && rd.copy && rd.open && rd.btn.join() === 'Post it to Jira,Edit the draft,Keep it as a draft,Mark it done,Post it to Jira,Send it back with a note', JSON.stringify(rd));
198
+ ok('W7 a ready draft is labelled the agent\'s, unchecked, and shows it in the detail panel with Open and Copy, and offers Post, Edit, Keep, Mark done and Send back', rd.state === 'ready' && /Draft for Jira/.test(rd.tag) && /Agent draft · not checked/.test(rd.body) && /sign off A and B/.test(rd.body) && rd.copy && rd.open && rd.btn.join() === 'Post it to Jira,Edit the draft,Keep it as a draft,Mark it done,Post it to Jira,Send it back with a note', JSON.stringify(rd));
199
199
  const m0 = RD.posts.length; await q.click('[data-p="ag-post"]'); await sleep(300);
200
200
  const cf = await q.evaluate(() => ({ text: document.querySelector('.xcon').textContent, btn: [...document.querySelectorAll('.xcon button')].map((b) => b.textContent.trim()) }));
201
201
  ok('W7 Post it posts nothing: it asks, names Jira and shows exactly the text', RD.posts.length === m0 && /Post this to Jira as you\?/.test(cf.text) && /Two of the three quotes meet the brief\. I would sign off A and B\./.test(cf.text) && cf.btn.join() === 'Post it to Jira now,Not yet', JSON.stringify(cf));
@@ -243,25 +243,28 @@ function paneHtml(r) {
243
243
  const p = r.dialog.pane, ag = r.dialog.agent, dr = ag && ag.draft && (ag.draft.body || ag.draft.summary) ? ag.draft : null;
244
244
  let h = '';
245
245
  if (dr) {
246
- const last = ag.turns && ag.turns.length ? ag.turns[ag.turns.length - 1] : null;
247
- h += `<article class="paper doc agpane"><div class="agpt"><p class="agtag">Agent draft · not checked${last ? ' · ' + esc(KIND[last.kind] || '') : ''}</p><span class="agpa"><button class="xtb" data-pp="open" type="button">Open</button><button class="xtb" data-pp="copy" type="button">Copy</button></span></div><div class="mdr">${mdHtml(dr.body || dr.summary)}</div></article>`;
246
+ const long = String(dr.body || '').length > 900 || String(dr.body || '').split('\n').length > 16, clip = long && !ui.all;
247
+ h += `<article class="paper doc agpane"><div class="agpt"><p class="agtag"><span class="agst">${ag.state === 'sent' ? 'Posted' : 'Draft'}</span> ${ag.mine ? 'Draft for you' : 'Draft for ' + esc(ag.ref || ag.where || 'the item')}</p><span class="agver">${ag.round ? 'Round ' + ag.round : 'Agent draft'}${ag.round_at ? ' · ' + esc(hhmm(ag.round_at)) : ''}</span><span class="agpa"><button class="xtb" data-pp="open" type="button">Open</button><button class="xtb" data-pp="copy" type="button">Copy</button></span></div><p class="note">Agent draft · not checked</p>`
248
+ + (dr.step ? `<p class="agstep">Step when you approve: ${esc(dr.step)}</p>` : '')
249
+ + `<div class="mdr${clip ? ' clipd' : ''}">${mdHtml(dr.body || dr.summary)}</div>${long ? `<button class="xtb" data-pp="all" type="button" aria-expanded="${!clip}">${clip ? 'Show all' : 'Show less'}</button>` : ''}</article>`;
248
250
  }
249
251
  let g = `<p class="dpath">${esc(p.file)}</p>${p.h ? `<h3 class="d1">${esc(p.h)}</h3>` : ''}${p.intro ? `<p>${esc(p.intro)}</p>` : ''}`; // the heading and lead line, as the mockup draws them
250
252
  if (p.rows && p.rows.length) g += `<div class="kv2">${p.rows.map(([a, b]) => `<span>${esc(a)}</span><span>${esc(b)}</span>`).join('')}</div>`;
251
253
  return h + `<article class="paper doc">${g}<p class="xn">The item as your list holds it.</p></article>`;
252
254
  }
253
255
  const paneLabel = (r) => (r.dialog.agent && r.dialog.agent.draft && (r.dialog.agent.draft.body || r.dialog.agent.draft.summary) ? 'Draft and item record' : r.dialog.pane.label);
254
- const paneSig = (r) => JSON.stringify([r.dialog.agent && r.dialog.agent.draft, r.dialog.pane]);
256
+ const paneSig = (r) => JSON.stringify([r.dialog.agent && r.dialog.agent.draft, r.dialog.agent && r.dialog.agent.round, r.dialog.agent && r.dialog.agent.state, r.dialog.pane]);
255
257
  /* the detail panel follows the item: a draft that lands while the dialog is open shows at once */
256
258
  function paintPane() {
257
259
  if (!openR || dlgKind !== 'item') return;
258
- const sg = paneSig(openR); if (sg === ui.pane) return;
260
+ const sg = paneSig(openR) + (ui.all ? 'A' : ''); if (sg === ui.pane) return;
259
261
  ui.pane = sg; const m = $('#oMain'), top = m.scrollTop;
260
262
  m.innerHTML = paneHtml(openR); $('#oLab').textContent = paneLabel(openR); m.scrollTop = top;
261
263
  }
262
264
  $('#oMain').addEventListener('click', async (e) => {
263
265
  const b = e.target.closest('[data-pp]'); if (!b || dlgKind !== 'item' || !openR) return;
264
266
  const ag = openR.dialog.agent, txt = (ag && ag.draft && (ag.draft.body || ag.draft.summary)) || '';
267
+ if (b.dataset.pp === 'all') { ui.all = !ui.all; ui.pane = ''; paintPane(); return; }
265
268
  if (b.dataset.pp === 'copy') { try { await navigator.clipboard.writeText(txt); toast('Draft copied.'); } catch (_) { toast('Copy did not work here. Select the text and copy it.'); } }
266
269
  else { const u = URL.createObjectURL(new Blob([txt], { type: 'text/plain;charset=utf-8' })); window.open(u, '_blank', 'noopener'); setTimeout(() => URL.revokeObjectURL(u), 60000); }
267
270
  });
@@ -1936,6 +1936,10 @@ button.wl-row[aria-pressed="true"] .wl-tog{background:var(--solid);color:var(--o
1936
1936
  .dscr>div:first-child{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
1937
1937
  .dscr small{font:12px var(--mono);color:var(--ink-3);overflow-wrap:anywhere}
1938
1938
  .dscr .lk{justify-self:start;min-height:44px;display:inline-flex;align-items:center}
1939
+ .agst{font:600 11px var(--mono);text-transform:uppercase;letter-spacing:.04em;color:var(--ink-3);margin-right:4px}
1940
+ .agver{font:500 12px var(--mono);color:var(--ink-3);margin-left:auto}
1941
+ .agstep{margin:6px 0;font:500 12.5px var(--mono);color:var(--ember-ink)}
1942
+ .mdr.clipd{max-height:18em;overflow:hidden}
1939
1943
 
1940
1944
  .prep{display:flex;align-items:center;gap:14px;margin:10px 0 2px;padding:10px 14px;border-radius:var(--r-in);background:var(--well)}
1941
1945
  .prep[hidden]{display:none}
@@ -6250,6 +6250,8 @@ async function handleRequest(req, res) {
6250
6250
  let body = {};
6251
6251
  try { body = JSON.parse((await readBody(req)) || '{}'); }
6252
6252
  catch { return json(res, { ok: false, error: 'invalid JSON body' }, 400); }
6253
+ const g = pmGuard.requirePagePress(req, body); // Add workspace is a page press (premium-settings), so an agent session gets 403
6254
+ if (!g.ok) return json(res, { ok: false, error: g.error }, g.status);
6253
6255
  if (!body.root) return json(res, { ok: false, error: 'root is required' }, 400);
6254
6256
  const w = registerWorkspace(body.root, body.name);
6255
6257
  if (!w) return json(res, { ok: false, error: `not a directory: ${body.root}` }, 400);
@@ -8959,6 +8961,8 @@ async function handleRequest(req, res) {
8959
8961
  if (req.method === 'GET') return json(res, { ok: true, settings: proSettings() });
8960
8962
  if (req.method === 'POST') {
8961
8963
  let body = {}; try { body = JSON.parse((await readBody(req)) || '{}'); } catch { return json(res, { ok: false, error: 'invalid JSON body' }, 400); }
8964
+ const g = pmGuard.requirePagePress(req, body); // a settings write is a page press, so an agent session gets 403
8965
+ if (!g.ok) return json(res, { ok: false, error: g.error }, g.status);
8962
8966
  const cur = proSettings();
8963
8967
  // A patch: triggers, sources, the check and each service's levels merge over what is stored (a level of null clears it).
8964
8968
  const bs = body.scopes && typeof body.scopes === 'object' && !Array.isArray(body.scopes) ? body.scopes : null;
@@ -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
+ }