create-pmos 0.301.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 +1 -1
- package/payload/KIT-VERSION +1 -1
- package/payload/planning/evals/eval-calibration.md +1 -1
- package/payload/planning/okrs/health-budgets.md +1 -1
- package/payload/state/discoveries.md +1 -1
- package/workspace/bin/pmos.js +23 -4
- package/workspace/briefing-premium-products-test.js +2 -2
- package/workspace/briefing-premium-sources-test.js +1 -1
- package/workspace/lib/capacity-governor.js +134 -0
- package/workspace/lib/orchestrator-ledger.js +100 -0
- package/workspace/package-lock.json +2 -2
- package/workspace/package.json +1 -1
- package/workspace/server.js +4 -0
- package/workspace/test-lists/agent-orchestrator-a.json +11 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "create-pmos",
|
|
3
|
-
"version": "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": {
|
package/payload/KIT-VERSION
CHANGED
|
@@ -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:
|
|
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:
|
|
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:
|
|
5
|
+
generated: {by: process:create-pmos, at: "2026-10-19T07:11:19Z"}
|
|
6
6
|
status: stable
|
|
7
7
|
---
|
|
8
8
|
|
package/workspace/bin/pmos.js
CHANGED
|
@@ -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
|
|
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 ?
|
|
574
|
+
say, call: async (m, p, b) => (port ? pressApi(port, m, p, b) : null) });
|
|
556
575
|
}
|
|
557
576
|
else if (cmd === 'kg') {
|
|
558
577
|
// Reads tracked .md files straight from disk (lib/kg-cli.js); needs no running server.
|
|
@@ -59,8 +59,8 @@ const product = (name, cond) => {
|
|
|
59
59
|
srv = spawn(process.execPath, [path.join(__dirname, 'server.js')], { cwd: __dirname, stdio: 'ignore', env: T.env({ PMOS_WS_PORT: String(T.PORT), PATH: fakeBin + path.delimiter + process.env.PATH }) });
|
|
60
60
|
await T.waitForServer(BASE);
|
|
61
61
|
const json = async (m, p, b, h) => { const res = await fetch(BASE + p, { method: m, headers: { 'content-type': 'application/json', ...(h || {}) }, body: b ? JSON.stringify(b) : undefined }); let j = null; try { j = await res.json(); } catch { /* not json */ } return { status: res.status, body: j }; };
|
|
62
|
-
const wA = (await json('POST', '/api/workspaces', { root: rootA, name: 'IDPF', focus: false })).body.workspace;
|
|
63
|
-
const wB = (await json('POST', '/api/workspaces', { root: rootB, name: 'microsites', focus: false })).body.workspace;
|
|
62
|
+
const wA = (await json('POST', '/api/workspaces', { root: rootA, name: 'IDPF', focus: false }, await T.pressHeaders(BASE))).body.workspace;
|
|
63
|
+
const wB = (await json('POST', '/api/workspaces', { root: rootB, name: 'microsites', focus: false }, await T.pressHeaders(BASE))).body.workspace;
|
|
64
64
|
const all = (await json('GET', '/api/workspaces')).body.workspaces;
|
|
65
65
|
const home = all.find((w) => w.home);
|
|
66
66
|
ok('P0 the server has a home workspace and the two products', !!home && !!wA && !!wB, JSON.stringify(all.map((w) => [w.name, w.home])));
|
|
@@ -61,7 +61,7 @@ const sh = (cwd, args) => spawnSync('git', args, { cwd, encoding: 'utf8' });
|
|
|
61
61
|
srv = spawn(process.execPath, [path.join(__dirname, 'server.js')], { cwd: __dirname, stdio: 'ignore', env: T.env({ PMOS_WS_PORT: String(T.PORT), PATH: fakeBin + path.delimiter + process.env.PATH }) });
|
|
62
62
|
await T.waitForServer(BASE);
|
|
63
63
|
const json = async (m, p, b, h) => { const res = await fetch(BASE + p, { method: m, headers: { 'content-type': 'application/json', ...(h || {}) }, body: b ? JSON.stringify(b) : undefined }); let j = null; try { j = await res.json(); } catch { j = null; } return { status: res.status, body: j }; };
|
|
64
|
-
const added = await json('POST', '/api/workspaces', { root, name: 'IDPF', focus: false });
|
|
64
|
+
const added = await json('POST', '/api/workspaces', { root, name: 'IDPF', focus: false }, await T.pressHeaders(BASE));
|
|
65
65
|
ok('S0 the product is registered', !!(added.body && added.body.workspace));
|
|
66
66
|
const model = async () => { const r = await json('GET', '/api/briefing-premium'); return r.status === 200 && r.body.model && !r.body.model.pending ? r.body : null; };
|
|
67
67
|
const m0 = await until(model, 90000);
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/* capacity-governor.js — may the orchestrator start another background run now (initiative agent-orchestrator, PRD "Capacity governor").
|
|
3
|
+
*
|
|
4
|
+
* DEFAULTS · normalize(raw) → { ok, settings } | { ok:false, error } the limits, from the PM's file or the defaults
|
|
5
|
+
* modeOf({ now, lastActivityAt, settings }) → 'away' | 'working'
|
|
6
|
+
* decide({ now, lastActivityAt, settings, running, startedToday, load, quota, stopped })
|
|
7
|
+
* → { allowed, mode, cap, reason }
|
|
8
|
+
* memFreeFrac(deps) · cpuPerCore(deps) → the machine's load, read the way each system reports it
|
|
9
|
+
* parseVmStat(text) · parseMeminfo(text) → the pure parts of memFreeFrac
|
|
10
|
+
*
|
|
11
|
+
* There are no quiet hours. When the PM is away, agents may use most of the machine; when the PM is working, the PM's
|
|
12
|
+
* terminals and the workspace keep a reserved share and agents get the rest, with a lower cap on parallel runs. The mode
|
|
13
|
+
* switches by itself: working = inside the work hours AND active within `idleMin` minutes; anything else = away.
|
|
14
|
+
*
|
|
15
|
+
* It only decides whether a NEW run may start. It never ends a run: a run in progress drains by itself when the PM comes back.
|
|
16
|
+
* A run the PM starts by hand is not its business (see session-budget.js).
|
|
17
|
+
* Quota: when the CLI's remaining usage is known and below the reserve, nothing starts. When it is not known, the daily cap
|
|
18
|
+
* is the backstop, so an unreadable quota never means unlimited.
|
|
19
|
+
* Pure but for memFreeFrac and cpuPerCore, which take their readers as arguments. */
|
|
20
|
+
const fs = require('fs');
|
|
21
|
+
const os = require('os');
|
|
22
|
+
const { execFileSync } = require('child_process');
|
|
23
|
+
|
|
24
|
+
const DEFAULTS = Object.freeze({
|
|
25
|
+
workDays: [1, 2, 3, 4, 5], // Date#getDay(): Monday to Friday
|
|
26
|
+
workStart: '09:00', workEnd: '18:00', // host-local time
|
|
27
|
+
idleMin: 20,
|
|
28
|
+
awayParallel: 8, workingParallel: 3,
|
|
29
|
+
reservePct: 50, // share of memory and CPU the PM keeps while working
|
|
30
|
+
quotaReservePct: 30, // remaining usage below which nothing starts
|
|
31
|
+
dailyCap: 40, // the backstop on runs started per local day
|
|
32
|
+
});
|
|
33
|
+
const FLOOR_AWAY = Object.freeze({ memFree: 0.10, cpuPerCore: 1.5 }); // even away, never starve the machine
|
|
34
|
+
|
|
35
|
+
const HHMM = /^([01]?\d|2[0-3]):([0-5]\d)$/;
|
|
36
|
+
const minutes = (t) => { const m = HHMM.exec(t); return m ? (+m[1]) * 60 + (+m[2]) : null; };
|
|
37
|
+
|
|
38
|
+
function normalize(raw) {
|
|
39
|
+
const r = raw && typeof raw === 'object' ? raw : {};
|
|
40
|
+
const s = { ...DEFAULTS, workDays: [...DEFAULTS.workDays] };
|
|
41
|
+
const int = (k, lo, hi) => {
|
|
42
|
+
if (r[k] === undefined) return null;
|
|
43
|
+
const n = Number(r[k]);
|
|
44
|
+
if (!Number.isInteger(n) || n < lo || n > hi) return `${k} must be a whole number from ${lo} to ${hi}`;
|
|
45
|
+
s[k] = n; return null;
|
|
46
|
+
};
|
|
47
|
+
const problems = [
|
|
48
|
+
int('idleMin', 1, 240), int('awayParallel', 1, 32), int('workingParallel', 1, 32),
|
|
49
|
+
int('reservePct', 0, 90), int('quotaReservePct', 0, 100), int('dailyCap', 1, 500),
|
|
50
|
+
].filter(Boolean);
|
|
51
|
+
for (const k of ['workStart', 'workEnd']) {
|
|
52
|
+
if (r[k] === undefined) continue;
|
|
53
|
+
if (minutes(String(r[k])) === null) problems.push(`${k} is a time like 09:00`); else s[k] = String(r[k]);
|
|
54
|
+
}
|
|
55
|
+
if (r.workDays !== undefined) {
|
|
56
|
+
if (!Array.isArray(r.workDays) || !r.workDays.every((d) => Number.isInteger(d) && d >= 0 && d <= 6)) problems.push('workDays is a list of weekday numbers, 0 (Sunday) to 6');
|
|
57
|
+
else s.workDays = [...new Set(r.workDays)].sort();
|
|
58
|
+
}
|
|
59
|
+
if (minutes(s.workEnd) <= minutes(s.workStart)) problems.push('workEnd is after workStart');
|
|
60
|
+
if (s.workingParallel > s.awayParallel) problems.push('workingParallel is not more than awayParallel');
|
|
61
|
+
return problems.length ? { ok: false, error: problems.join('; ') } : { ok: true, settings: s };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function modeOf({ now, lastActivityAt, settings } = {}) {
|
|
65
|
+
const s = settings || DEFAULTS;
|
|
66
|
+
const t = new Date(Number.isFinite(now) ? now : Date.now());
|
|
67
|
+
const mins = t.getHours() * 60 + t.getMinutes();
|
|
68
|
+
const inHours = s.workDays.includes(t.getDay()) && mins >= minutes(s.workStart) && mins < minutes(s.workEnd);
|
|
69
|
+
const idleMs = Number.isFinite(lastActivityAt) ? t.getTime() - lastActivityAt : Infinity;
|
|
70
|
+
const active = idleMs <= s.idleMin * 60000;
|
|
71
|
+
return inHours && active ? 'working' : 'away';
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** load: { memFreeFrac: 0..1 | null, cpuPerCore: number | null }; quota: { remainingPct: 0..100 } | null. */
|
|
75
|
+
function decide({ now, lastActivityAt, settings, running = 0, startedToday = 0, load, quota, stopped = false } = {}) {
|
|
76
|
+
const s = settings || DEFAULTS;
|
|
77
|
+
const mode = modeOf({ now, lastActivityAt, settings: s });
|
|
78
|
+
const cap = mode === 'away' ? s.awayParallel : s.workingParallel;
|
|
79
|
+
const no = (reason) => ({ allowed: false, mode, cap, reason });
|
|
80
|
+
if (stopped) return no('The orchestrator is stopped.');
|
|
81
|
+
if (running >= cap) return no(`${running} orchestrator runs are live (limit ${cap} while ${mode}).`);
|
|
82
|
+
if (startedToday >= s.dailyCap) return no(`${startedToday} runs started today (daily limit ${s.dailyCap}).`);
|
|
83
|
+
if (quota && Number.isFinite(quota.remainingPct) && quota.remainingPct < s.quotaReservePct) {
|
|
84
|
+
return no(`Claude usage left is ${Math.round(quota.remainingPct)}%, below the ${s.quotaReservePct}% reserve.`);
|
|
85
|
+
}
|
|
86
|
+
const mem = load && Number.isFinite(load.memFreeFrac) ? load.memFreeFrac : null;
|
|
87
|
+
const cpu = load && Number.isFinite(load.cpuPerCore) ? load.cpuPerCore : null;
|
|
88
|
+
if (mode === 'working') {
|
|
89
|
+
const keep = s.reservePct / 100;
|
|
90
|
+
if (mem !== null && mem < keep) return no(`The PM is working: free memory ${pct(mem)} is below the ${s.reservePct}% kept for the PM.`);
|
|
91
|
+
if (cpu !== null && cpu > 1 - keep) return no(`The PM is working: CPU load ${cpu.toFixed(2)} per core is above ${(1 - keep).toFixed(2)}.`);
|
|
92
|
+
} else {
|
|
93
|
+
if (mem !== null && mem < FLOOR_AWAY.memFree) return no(`Free memory ${pct(mem)} is below the ${pct(FLOOR_AWAY.memFree)} floor.`);
|
|
94
|
+
if (cpu !== null && cpu >= FLOOR_AWAY.cpuPerCore) return no(`CPU load ${cpu.toFixed(2)} per core is at the ${FLOOR_AWAY.cpuPerCore} floor.`);
|
|
95
|
+
}
|
|
96
|
+
return { allowed: true, mode, cap, reason: null };
|
|
97
|
+
}
|
|
98
|
+
const pct = (f) => `${Math.round(f * 100)}%`;
|
|
99
|
+
|
|
100
|
+
/** macOS: os.freemem() counts cache as used and always looks nearly full, so read vm_stat: free + inactive + speculative + purgeable pages. */
|
|
101
|
+
function parseVmStat(text) {
|
|
102
|
+
const t = String(text || '');
|
|
103
|
+
const size = /page size of (\d+) bytes/.exec(t);
|
|
104
|
+
const pages = (name) => { const m = new RegExp(`^${name}:\\s+(\\d+)\\.`, 'm').exec(t); return m ? +m[1] : 0; };
|
|
105
|
+
const free = pages('Pages free') + pages('Pages inactive') + pages('Pages speculative') + pages('Pages purgeable');
|
|
106
|
+
return { freeBytes: free * (size ? +size[1] : 4096) };
|
|
107
|
+
}
|
|
108
|
+
/** Linux: MemAvailable is the figure the kernel offers for new work. */
|
|
109
|
+
function parseMeminfo(text) {
|
|
110
|
+
const t = String(text || '');
|
|
111
|
+
const a = /^MemAvailable:\s+(\d+) kB/m.exec(t), tot = /^MemTotal:\s+(\d+) kB/m.exec(t);
|
|
112
|
+
return a && tot ? { freeBytes: +a[1] * 1024, totalBytes: +tot[1] * 1024 } : null;
|
|
113
|
+
}
|
|
114
|
+
function memFreeFrac(deps = {}) {
|
|
115
|
+
const platform = deps.platform || process.platform;
|
|
116
|
+
const total = (deps.totalmem || os.totalmem)();
|
|
117
|
+
try {
|
|
118
|
+
if (platform === 'darwin') {
|
|
119
|
+
const out = (deps.vmStat || (() => execFileSync('vm_stat', { encoding: 'utf8', timeout: 2000 })))();
|
|
120
|
+
return Math.min(1, parseVmStat(out).freeBytes / total);
|
|
121
|
+
}
|
|
122
|
+
if (platform === 'linux') {
|
|
123
|
+
const m = parseMeminfo((deps.meminfo || (() => fs.readFileSync('/proc/meminfo', 'utf8')))());
|
|
124
|
+
if (m) return Math.min(1, m.freeBytes / m.totalBytes);
|
|
125
|
+
}
|
|
126
|
+
} catch { /* fall through to the portable figure */ }
|
|
127
|
+
return Math.min(1, (deps.freemem || os.freemem)() / total);
|
|
128
|
+
}
|
|
129
|
+
function cpuPerCore(deps = {}) {
|
|
130
|
+
const cores = Math.max(1, (deps.cpus || (() => os.cpus()))().length);
|
|
131
|
+
return (deps.loadavg || os.loadavg)()[0] / cores;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
module.exports = { DEFAULTS, FLOOR_AWAY, normalize, modeOf, decide, parseVmStat, parseMeminfo, memFreeFrac, cpuPerCore };
|
|
@@ -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.
|
|
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.
|
|
9
|
+
"version": "0.302.0",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@xterm/addon-fit": "^0.11.0",
|
package/workspace/package.json
CHANGED
package/workspace/server.js
CHANGED
|
@@ -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
|
+
}
|