create-pmos 0.574.0 → 0.576.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 +27 -27
- package/payload/AGENTS.md +35 -2
- package/payload/KIT-VERSION +1 -1
- package/payload/okf/core/templates/agent-eval-set-template.md +65 -0
- package/payload/okf/core/templates/index.md +1 -0
- package/payload/planning/evals/eval-calibration.md +1 -1
- package/payload/planning/okrs/health-budgets.md +1 -1
- package/payload/scripts/agent-eval-set.js +85 -0
- package/payload/scripts/factory-guardrail.js +50 -8
- package/payload/scripts/work-item.js +49 -3
- package/payload/scripts/workflow-state.js +28 -3
- package/payload/state/discoveries.md +1 -1
- package/payload/templates/pmos-guardrail.yml +38 -10
- package/payload/templates/pmos-review-check.yml +59 -0
- package/workspace/briefing-premium-calendar-3-test.js +3 -10
- package/workspace/changelog.json +26 -0
- package/workspace/fixtures/agenda/invites.json +73 -0
- package/workspace/fixtures/builder-bench.json +121 -0
- package/workspace/guide/cli.md +71 -4
- package/workspace/guide/notes.md +1 -1
- package/workspace/guide/settings-and-switches.md +6 -0
- package/workspace/lib/agenda-topics.js +401 -0
- package/workspace/lib/agent-team.js +5 -2
- package/workspace/lib/build-cli.js +119 -7
- package/workspace/lib/build-engine.js +106 -25
- package/workspace/lib/builder-bench.js +267 -0
- package/workspace/lib/engine/agent-eval-set.js +85 -0
- package/workspace/lib/engine/workflow-state.js +28 -3
- package/workspace/lib/factory-checks.js +117 -0
- package/workspace/lib/factory-ci.js +151 -0
- package/workspace/lib/factory-fleet.js +263 -0
- package/workspace/lib/factory-identity.js +182 -0
- package/workspace/lib/factory-lessons.js +183 -0
- package/workspace/lib/factory-needs.js +48 -0
- package/workspace/lib/factory-review.js +241 -0
- package/workspace/lib/factory-rollout.js +56 -10
- package/workspace/lib/factory-traces.js +229 -0
- package/workspace/lib/headless.js +11 -2
- package/workspace/lib/meeting-focus.js +26 -13
- package/workspace/lib/needs-providers.js +1 -0
- package/workspace/lib/pmos-verbs.js +1 -1
- package/workspace/lib/project-onboard.js +1 -1
- package/workspace/lib/proposals.js +3 -1
- package/workspace/lib/route-modules.js +1 -0
- package/workspace/lib/routes-factory-metrics.js +41 -0
- package/workspace/lib/routes-meeting-focus.js +79 -10
- package/workspace/lib/routes-proposals.js +9 -1
- package/workspace/lib/team-cli.js +2 -2
- package/workspace/lib/team-runs.js +13 -3
- package/workspace/lib/vendor/scripts/agent-eval-set.js +85 -0
- package/workspace/lib/vendor/scripts/workflow-state.js +28 -3
- package/workspace/lib/verify-runs.js +62 -1
- package/workspace/package-lock.json +2 -2
- package/workspace/package.json +1 -1
- package/workspace/public/pm/agenda-live.css +44 -0
- package/workspace/public/pm/agenda-live.js +100 -0
- package/workspace/public/pm/cozy-rec-now.js +20 -2
- package/workspace/public/pm/ini-props.js +1 -1
- package/workspace/public/pm/premium-vw-mtg.js +20 -21
- package/workspace/server.js +4 -0
- package/workspace/test-lists/adlc-identity.json +9 -0
- package/workspace/test-lists/build-engine.json +5 -3
- package/workspace/test-lists/builder-bench.json +9 -0
- package/workspace/test-lists/factory-checks.json +9 -0
- package/workspace/test-lists/factory-fleet.json +9 -0
- package/workspace/test-lists/factory-lessons.json +9 -0
- package/workspace/test-lists/factory-real-run.json +9 -0
- package/workspace/test-lists/factory-run-traces.json +9 -0
- package/workspace/test-lists/live-agenda-topics.json +7 -0
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/* builder-bench.js — the golden benchmark of the Builder (initiative factory-builder-benchmark, ADLC gap P2). `pmos build bench`
|
|
3
|
+
* (lib/build-cli.js) is its terminal face.
|
|
4
|
+
*
|
|
5
|
+
* loadSet(file?) → { file, version, product: { path: text }, items: [{ n, id, type, file, criterion, check, solution: { path: text } }] }
|
|
6
|
+
* writeFiles(dir, files) write a { path: text } map under dir (the product, a solution)
|
|
7
|
+
* setup(set, { base? }) → { sandbox, prod, buildDir, items: [{ ...item, ini, item_id }] } the product, the kit and the declared items
|
|
8
|
+
* checkItem(set, item, dir) → { pass, why } the item's held-out check against one folder (a child process, no model)
|
|
9
|
+
* harnessParts() · versionOf(parts) · harnessVersion() what "harness" means here, and its short hash
|
|
10
|
+
* run({ root, model, only, runner, env, now, keep }) → { ok, row, file } | { ok: false, error }
|
|
11
|
+
* defaultRunner(spec) → { costUsd, durationMs, turns, isError, text, model } one headless Builder run (`claude -p`)
|
|
12
|
+
* benchFile(root) · readRows(file) → { rows, torn } · rollup(rows) → [{ model, harness, set, runs, items, passed, pass_rate, … }]
|
|
13
|
+
*
|
|
14
|
+
* WHAT IT MEASURES. The golden set (fixtures/builder-bench.json, one file, so the set has one version) is a small product and 10 work items. Each item has a held-out check and a
|
|
15
|
+
* known-good solution: the check fails on the untouched product and passes with the solution (builder-bench.test.js B1). A bench run
|
|
16
|
+
* copies the product to a temporary folder, installs the kit and declares each item under an initiative of its own (bench-01 … bench-10),
|
|
17
|
+
* so each Builder run sees one declared item and builds it in a worktree of its own. The Builder works exactly as in a product: the role
|
|
18
|
+
* prompt of lib/team-runs.js, the tool list of lib/agent-team.js toolsOf('build'), and `pmos build claim` and `propose` (lib/build-engine.js).
|
|
19
|
+
*
|
|
20
|
+
* HOW IT SCORES. An item passes only when the Builder PROPOSED it (the ledger reads verified, so build-engine committed it) AND the item's
|
|
21
|
+
* held-out check passes on that commit, checked out into a folder of its own. The Builder's own evidence never counts, and it never sees
|
|
22
|
+
* the check: the checks and solutions never enter the sandbox. No model call is part of the score.
|
|
23
|
+
*
|
|
24
|
+
* WHAT IT RECORDS. One row per bench run, appended to planning/runs/builder-bench.jsonl (a kit repository: pmos/planning/runs/): the model,
|
|
25
|
+
* the harness version, the set version, pass rate, cost and duration, total and per item. A cost the run did not report stays null, never 0.
|
|
26
|
+
* rollup() groups rows by model, harness and set, the way D40 keeps evaluator calibration per evaluator model: a model or harness change
|
|
27
|
+
* starts a new group and never inherits the old pass rate.
|
|
28
|
+
*
|
|
29
|
+
* THE TRIFECTA. The Builder run holds the tools of a real Builder run: no git push, no gh, no network tool. The sandbox has no remote, and
|
|
30
|
+
* the bench never runs `pmos build open`. The record is written by this process after the runs end, never by a Builder run, and
|
|
31
|
+
* build-cli refuses `bench` in a role run (PMOS_TEAM_RUN set). The held-out check runs the Builder's code in a child process with a bare
|
|
32
|
+
* environment (PATH only, HOME in the sandbox) and a time limit.
|
|
33
|
+
*/
|
|
34
|
+
const fs = require('fs');
|
|
35
|
+
const os = require('os');
|
|
36
|
+
const path = require('path');
|
|
37
|
+
const crypto = require('crypto');
|
|
38
|
+
const cp = require('child_process');
|
|
39
|
+
|
|
40
|
+
const FIXTURE = path.join(__dirname, '..', 'fixtures', 'builder-bench.json');
|
|
41
|
+
const CHECK_TIMEOUT_MS = 20000;
|
|
42
|
+
const IDENTITY = { name: 'PMOS bench', email: 'bench@pmos.invalid' };
|
|
43
|
+
const sha = (s) => crypto.createHash('sha1').update(s).digest('hex').slice(0, 12);
|
|
44
|
+
const one = (s, n) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim().slice(0, n);
|
|
45
|
+
|
|
46
|
+
function git(cwd, args) {
|
|
47
|
+
const r = cp.spawnSync('git', args, { cwd, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, env: { ...process.env, GIT_TERMINAL_PROMPT: '0' } });
|
|
48
|
+
return { ok: !r.error && r.status === 0, out: String(r.stdout || '').trim(), err: String(r.stderr || (r.error && r.error.message) || '').trim() };
|
|
49
|
+
}
|
|
50
|
+
function mustGit(cwd, args) {
|
|
51
|
+
const r = git(cwd, args);
|
|
52
|
+
if (!r.ok) throw new Error(`git ${args.join(' ')} failed: ${one(r.err, 300)}`);
|
|
53
|
+
return r.out;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The golden set. Its version is a hash of the whole file, so a changed item, check or product file makes a new set. */
|
|
57
|
+
function loadSet(file = FIXTURE) {
|
|
58
|
+
const raw = fs.readFileSync(file, 'utf8');
|
|
59
|
+
const o = JSON.parse(raw);
|
|
60
|
+
if (!o || !Array.isArray(o.items) || !o.items.length || !o.product) throw new Error('the golden set has no items');
|
|
61
|
+
return { file, version: sha(raw), product: o.product, items: o.items };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Write a { path: text } map under dir. A path that leaves dir is refused. */
|
|
65
|
+
function writeFiles(dir, files) {
|
|
66
|
+
for (const [rel, text] of Object.entries(files || {})) {
|
|
67
|
+
const p = path.resolve(dir, rel);
|
|
68
|
+
if (path.relative(dir, p).startsWith('..') || path.isAbsolute(path.relative(dir, p))) throw new Error('a golden-set path leaves its folder: ' + rel);
|
|
69
|
+
fs.mkdirSync(path.dirname(p), { recursive: true });
|
|
70
|
+
fs.writeFileSync(p, String(text));
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const iniOf = (it) => 'bench-' + it.id;
|
|
75
|
+
const itemIdOf = (it) => iniOf(it) + '.1';
|
|
76
|
+
|
|
77
|
+
/** A sandbox product with the kit and every item declared, waiting for a Builder. Throws with the reason when a step fails. */
|
|
78
|
+
function setup(set, { base = os.tmpdir(), only = null } = {}) {
|
|
79
|
+
const sandbox = fs.mkdtempSync(path.join(base, 'pmos-bench-'));
|
|
80
|
+
const prod = path.join(sandbox, 'prod');
|
|
81
|
+
writeFiles(prod, set.product);
|
|
82
|
+
mustGit(prod, ['init', '-q']);
|
|
83
|
+
mustGit(prod, ['symbolic-ref', 'HEAD', 'refs/heads/main']);
|
|
84
|
+
// the sandbox is the bench's own repository, so it names its own committer (PMOS never guesses one in a real product)
|
|
85
|
+
mustGit(prod, ['config', 'user.name', IDENTITY.name]);
|
|
86
|
+
mustGit(prod, ['config', 'user.email', IDENTITY.email]);
|
|
87
|
+
mustGit(prod, ['config', 'commit.gpgsign', 'false']);
|
|
88
|
+
const PO = require('./project-onboard.js');
|
|
89
|
+
PO.installKit(prod, PO.kitSource());
|
|
90
|
+
const items = set.items.filter((it) => !only || only.includes(it.n));
|
|
91
|
+
const inis = path.join(prod, 'pmos', 'state', 'initiatives');
|
|
92
|
+
fs.mkdirSync(inis, { recursive: true });
|
|
93
|
+
for (const it of items) {
|
|
94
|
+
fs.writeFileSync(path.join(inis, iniOf(it) + '.md'), `---\ntype: Initiative\ntitle: "Bench item ${it.id}"\nid: ${iniOf(it)}\nlane: chore\nkind: sdlc\nparent_kr: health:tech\ntimestamp: 2026-11-16\n---\n\n# Bench item ${it.id}\n\n## Done test\n\n${it.criterion}\n`);
|
|
95
|
+
}
|
|
96
|
+
mustGit(prod, ['add', '-A']);
|
|
97
|
+
mustGit(prod, ['commit', '-qm', 'the benchmark product']);
|
|
98
|
+
const kit = path.join(prod, 'pmos');
|
|
99
|
+
for (const it of items) {
|
|
100
|
+
const r = cp.spawnSync(process.execPath, [path.join(kit, 'scripts', 'work-item.js'), 'declare', iniOf(it), '--type', it.type, '--blast', 'low',
|
|
101
|
+
'--criterion', it.criterion, '--check', 'test', '--ref', 'the held-out check of the PMOS Builder benchmark', '--no-claim'], { cwd: kit, encoding: 'utf8' });
|
|
102
|
+
if (r.status !== 0) throw new Error(`could not declare ${iniOf(it)}: ${one((r.stdout || '') + (r.stderr || ''), 300)}`);
|
|
103
|
+
}
|
|
104
|
+
return { sandbox, prod, buildDir: path.join(sandbox, 'worktrees'), items: items.map((it) => ({ ...it, ini: iniOf(it), item_id: itemIdOf(it) })) };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** The item's held-out check against one folder. The Builder's code runs in a child process with PATH only, HOME in a scratch folder. */
|
|
108
|
+
function checkItem(set, it, dir) {
|
|
109
|
+
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'pmos-bench-check-'));
|
|
110
|
+
try {
|
|
111
|
+
const check = path.join(home, 'check.js');
|
|
112
|
+
fs.writeFileSync(check, String(it.check));
|
|
113
|
+
const r = cp.spawnSync(process.execPath, [check, dir], { cwd: home, encoding: 'utf8', timeout: CHECK_TIMEOUT_MS,
|
|
114
|
+
env: { PATH: process.env.PATH || '', HOME: home } });
|
|
115
|
+
if (r.error && r.error.code === 'ETIMEDOUT') return { pass: false, why: 'the held-out check timed out' };
|
|
116
|
+
if (r.status === 0) return { pass: true, why: 'the held-out check passed' };
|
|
117
|
+
const msg = String(r.stderr || '').split('\n').find((l) => /Error|assert/i.test(l)) || 'it exited ' + r.status;
|
|
118
|
+
return { pass: false, why: 'the held-out check failed: ' + one(msg, 200) };
|
|
119
|
+
} finally { fs.rmSync(home, { recursive: true, force: true }); }
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/* THE HARNESS. Everything around the model that decides how the Builder works: its prompt, its tool list and the engine that claims
|
|
123
|
+
* and proposes. A change to any of them is a new harness version, and its rows are a new group. The build folder is a placeholder,
|
|
124
|
+
* so the version does not depend on where a run happened. */
|
|
125
|
+
function harnessParts() {
|
|
126
|
+
const H = require('./headless.js');
|
|
127
|
+
const TR = require('./team-runs.js');
|
|
128
|
+
const prev = process.env.PMOS_BUILD_DIR;
|
|
129
|
+
process.env.PMOS_BUILD_DIR = '/pmos-build';
|
|
130
|
+
let argv;
|
|
131
|
+
try { argv = H.argsFor('team', { team: { role: 'build', mode: 'propose' } }); }
|
|
132
|
+
finally { if (prev === undefined) delete process.env.PMOS_BUILD_DIR; else process.env.PMOS_BUILD_DIR = prev; }
|
|
133
|
+
const at = argv.indexOf('--allowedTools');
|
|
134
|
+
return {
|
|
135
|
+
prompt: TR.promptOf('build', { id: 'bench', ini: 'bench-00' }, { now: Date.UTC(2026, 0, 1) }),
|
|
136
|
+
tools: at >= 0 ? argv[at + 1] : '',
|
|
137
|
+
engine: fs.readFileSync(path.join(__dirname, 'build-engine.js'), 'utf8'),
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
const versionOf = (parts) => sha(JSON.stringify([parts.prompt, parts.tools, parts.engine]));
|
|
141
|
+
const harnessVersion = () => versionOf(harnessParts());
|
|
142
|
+
|
|
143
|
+
/** One headless Builder run: the role's own tool list (no git push, no gh, no merge) and the role prompt, in the sandbox. */
|
|
144
|
+
function defaultRunner({ prompt, model, cwd, env, addDirs }) {
|
|
145
|
+
const H = require('./headless.js');
|
|
146
|
+
const argv = H.argsFor('team', { team: { role: 'build', mode: 'propose' }, modelArgs: model ? ['--model', model] : [], addDirs });
|
|
147
|
+
const t0 = Date.now();
|
|
148
|
+
const r = cp.spawnSync('claude', argv, { cwd, env, input: prompt, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, timeout: H.timeoutMs(env) });
|
|
149
|
+
if (r.error) return { isError: true, text: r.error.code === 'ENOENT' ? 'the agent CLI (claude) is not installed on this computer' : one(r.error.message, 200), durationMs: Date.now() - t0, costUsd: null };
|
|
150
|
+
const p = H.parseResult(r.stdout);
|
|
151
|
+
const u = H.usageOf(r.stdout);
|
|
152
|
+
return { isError: !p.ok || p.isError, text: one(p.text || r.stderr, 300), durationMs: p.durationMs != null ? p.durationMs : Date.now() - t0,
|
|
153
|
+
costUsd: p.costUsd, turns: p.turns, model: u && u.model ? u.model : null };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Where the rows go: planning/runs/ in PMOS-self, pmos/planning/runs/ in a kit repository. */
|
|
157
|
+
function benchFile(root) {
|
|
158
|
+
const self = path.join(root, 'planning', 'runs');
|
|
159
|
+
const kit = path.join(root, 'pmos', 'planning');
|
|
160
|
+
const dir = fs.existsSync(self) || !fs.existsSync(kit) ? self : path.join(kit, 'runs');
|
|
161
|
+
return path.join(dir, 'builder-bench.jsonl');
|
|
162
|
+
}
|
|
163
|
+
function readRows(file) {
|
|
164
|
+
let text = '';
|
|
165
|
+
try { text = fs.readFileSync(file, 'utf8'); } catch { return { rows: [], torn: 0 }; }
|
|
166
|
+
const rows = []; let torn = 0;
|
|
167
|
+
for (const l of text.split('\n')) {
|
|
168
|
+
if (!l.trim()) continue;
|
|
169
|
+
try { const o = JSON.parse(l); if (o && o.type === 'builder-bench') rows.push(o); else torn++; } catch { torn++; }
|
|
170
|
+
}
|
|
171
|
+
return { rows, torn };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Rows grouped by model, harness and set version, newest group first. Cost per item counts only items whose cost is known. */
|
|
175
|
+
function rollup(rows) {
|
|
176
|
+
const g = new Map();
|
|
177
|
+
for (const r of rows) {
|
|
178
|
+
const k = [r.model, r.harness, r.set].join('\u0000');
|
|
179
|
+
const a = g.get(k) || { model: r.model, harness: r.harness, set: r.set, runs: 0, items: 0, passed: 0, cost: 0, cost_items: 0, ms: 0, ms_items: 0, last_ts: '' };
|
|
180
|
+
a.runs++;
|
|
181
|
+
for (const it of r.items || []) {
|
|
182
|
+
a.items++; if (it.pass) a.passed++;
|
|
183
|
+
if (Number.isFinite(it.cost_usd)) { a.cost += it.cost_usd; a.cost_items++; }
|
|
184
|
+
if (Number.isFinite(it.duration_ms)) { a.ms += it.duration_ms; a.ms_items++; }
|
|
185
|
+
}
|
|
186
|
+
if (String(r.ts) > a.last_ts) a.last_ts = String(r.ts);
|
|
187
|
+
g.set(k, a);
|
|
188
|
+
}
|
|
189
|
+
return [...g.values()].map((a) => ({ model: a.model, harness: a.harness, set: a.set, runs: a.runs, items: a.items, passed: a.passed,
|
|
190
|
+
pass_rate: a.items ? a.passed / a.items : null,
|
|
191
|
+
cost_per_item_usd: a.cost_items ? a.cost / a.cost_items : null, cost_items: a.cost_items,
|
|
192
|
+
duration_per_item_ms: a.ms_items ? Math.round(a.ms / a.ms_items) : null, last_ts: a.last_ts }))
|
|
193
|
+
.sort((x, y) => (x.last_ts < y.last_ts ? 1 : x.last_ts > y.last_ts ? -1 : 0));
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Score one item after its run: proposed (verified in the ledger) and the held-out check passes on the proposed commit. */
|
|
197
|
+
function scoreItem(set, sb, it) {
|
|
198
|
+
const BE = require('./build-engine.js');
|
|
199
|
+
const st = (BE.itemsOf(sb.prod).find((x) => x.item_id === it.item_id) || {}).state || 'missing';
|
|
200
|
+
if (st !== 'verified') return { pass: false, why: `not proposed: the item is ${st}` };
|
|
201
|
+
const branch = 'refs/heads/' + BE.branchOf(it.item_id);
|
|
202
|
+
if (!git(sb.prod, ['rev-parse', '--verify', '--quiet', branch]).ok) return { pass: false, why: 'not proposed: no branch' };
|
|
203
|
+
const dir = path.join(sb.sandbox, 'score', it.id);
|
|
204
|
+
const w = git(sb.prod, ['worktree', 'add', '--detach', '-q', dir, branch]);
|
|
205
|
+
if (!w.ok) return { pass: false, why: 'the proposed commit could not be checked out: ' + one(w.err, 200) };
|
|
206
|
+
return checkItem(set, it, dir);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** A shim folder with `pmos` on it, so the Builder's `pmos build …` runs this workspace's CLI. */
|
|
210
|
+
function shimDir(sandbox) {
|
|
211
|
+
const d = path.join(sandbox, 'bin');
|
|
212
|
+
fs.mkdirSync(d, { recursive: true });
|
|
213
|
+
const f = path.join(d, 'pmos');
|
|
214
|
+
fs.writeFileSync(f, `#!/bin/sh\nexec "${process.execPath}" "${path.join(__dirname, '..', 'bin', 'pmos.js')}" "$@"\n`);
|
|
215
|
+
fs.chmodSync(f, 0o755);
|
|
216
|
+
return d;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async function run({ root, model = null, only = null, runner = defaultRunner, env = process.env, now = () => new Date(), keep = false, set = null } = {}) {
|
|
220
|
+
if (env.PMOS_TEAM_RUN) return { ok: false, error: 'a role run cannot run the benchmark. The PM runs pmos build bench' };
|
|
221
|
+
if (process.platform === 'win32') return { ok: false, error: 'the benchmark runs on macOS and Linux only' };
|
|
222
|
+
if (!root) return { ok: false, error: 'no repository to record the result in' };
|
|
223
|
+
const S = set || loadSet();
|
|
224
|
+
if (only && only.some((n) => !S.items.some((it) => it.n === n))) return { ok: false, error: `the golden set has items 1 to ${S.items.length}` };
|
|
225
|
+
let sb;
|
|
226
|
+
try { sb = setup(S, { only }); } catch (e) { return { ok: false, error: 'the benchmark product could not be made: ' + one(e.message, 300) }; }
|
|
227
|
+
const harness = harnessVersion();
|
|
228
|
+
const runId = 'bench-' + crypto.randomBytes(4).toString('hex');
|
|
229
|
+
const bin = shimDir(sb.sandbox);
|
|
230
|
+
const started = now();
|
|
231
|
+
const items = [];
|
|
232
|
+
let reported = null;
|
|
233
|
+
try {
|
|
234
|
+
for (const it of sb.items) {
|
|
235
|
+
const runEnv = { ...env, PMOS_TEAM_RUN: `${runId}-${it.id}`, PMOS_TEAM_ROLE: 'build', PMOS_TEAM_ROOT: sb.prod, PMOS_BUILD_DIR: sb.buildDir,
|
|
236
|
+
PATH: bin + path.delimiter + (env.PATH || process.env.PATH || '') };
|
|
237
|
+
const TR = require('./team-runs.js');
|
|
238
|
+
const prompt = TR.promptOf('build', { id: runEnv.PMOS_TEAM_RUN, ini: it.ini }, { now: now().getTime() });
|
|
239
|
+
const t0 = Date.now();
|
|
240
|
+
let r;
|
|
241
|
+
try { r = (await runner({ item: it, prompt, model, cwd: sb.prod, env: runEnv, addDirs: [sb.buildDir] })) || {}; }
|
|
242
|
+
catch (e) { r = { isError: true, text: one(e.message, 200) }; }
|
|
243
|
+
if (r.model && !reported) reported = r.model;
|
|
244
|
+
const s = scoreItem(S, sb, it);
|
|
245
|
+
items.push({ n: it.n, item: it.item_id, type: it.type, pass: s.pass, why: s.why,
|
|
246
|
+
cost_usd: Number.isFinite(r.costUsd) ? r.costUsd : null,
|
|
247
|
+
duration_ms: Number.isFinite(r.durationMs) ? r.durationMs : Date.now() - t0,
|
|
248
|
+
turns: Number.isFinite(r.turns) ? r.turns : null, run_error: r.isError ? one(r.text, 200) || 'the run failed' : null });
|
|
249
|
+
}
|
|
250
|
+
} finally {
|
|
251
|
+
if (!keep) fs.rmSync(sb.sandbox, { recursive: true, force: true });
|
|
252
|
+
}
|
|
253
|
+
const passed = items.filter((x) => x.pass).length;
|
|
254
|
+
const costs = items.map((x) => x.cost_usd);
|
|
255
|
+
const row = {
|
|
256
|
+
type: 'builder-bench', ts: started.toISOString(), model: model || reported || 'default', model_reported: reported,
|
|
257
|
+
harness, set: S.version, n: items.length, passed, pass_rate: items.length ? passed / items.length : null,
|
|
258
|
+
cost_usd: costs.every(Number.isFinite) ? costs.reduce((a, b) => a + b, 0) : null, cost_known: costs.filter(Number.isFinite).length,
|
|
259
|
+
duration_ms: items.reduce((a, x) => a + x.duration_ms, 0), items,
|
|
260
|
+
};
|
|
261
|
+
const file = benchFile(root);
|
|
262
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
263
|
+
fs.appendFileSync(file, JSON.stringify(row) + '\n');
|
|
264
|
+
return { ok: true, row, file, sandbox: keep ? sb.sandbox : null };
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
module.exports = { FIXTURE, IDENTITY, loadSet, writeFiles, setup, checkItem, harnessParts, versionOf, harnessVersion, defaultRunner, benchFile, readRows, rollup, scoreItem, run };
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
/* agent-eval-set.js — the simulation eval set of a product that is an AI agent (initiative agent-product-lane, ADLC gap P1).
|
|
4
|
+
*
|
|
5
|
+
* A Full SDLC initiative may say `agent: true`: the product it builds is itself an agent. Its done test is then a simulation eval set,
|
|
6
|
+
* not a check table: scenarios that each give an input conversation, the expected behaviour and a scoring rubric, and one pass threshold.
|
|
7
|
+
* scripts/workflow-state.js requires it before the build. The template is okf/core/templates/agent-eval-set-template.md.
|
|
8
|
+
*
|
|
9
|
+
* isAgent(fm) → bool a record's `agent:` reads true (true, yes)
|
|
10
|
+
* parse(text) → { ok, threshold, scenarios: [{ id, title, input, expected, scoring }], missing: [string] }
|
|
11
|
+
*
|
|
12
|
+
* THE SHAPE (plain markdown, so a person reads it and this file checks it):
|
|
13
|
+
* front matter `pass_threshold: 0.8` a number above 0 and at most 1 (a share of the scenarios' scores)
|
|
14
|
+
* `## Scenario <id>: <title>` at least MIN_SCENARIOS of them
|
|
15
|
+
* under each, three labelled parts: `Input:` (the conversation: at least one `user:` turn), `Expected:`, `Scoring:`
|
|
16
|
+
*
|
|
17
|
+
* Deterministic. No model call, no network, no dependency: it is vendored into the kit with workflow-state.js.
|
|
18
|
+
*
|
|
19
|
+
* CLI: node scripts/agent-eval-set.js <file> [--json] exit 0 when the file is a valid eval set, 1 otherwise.
|
|
20
|
+
*/
|
|
21
|
+
const fs = require('fs');
|
|
22
|
+
|
|
23
|
+
const MIN_SCENARIOS = 3;
|
|
24
|
+
const PARTS = ['input', 'expected', 'scoring'];
|
|
25
|
+
const HEAD = /^##\s+scenario\b\s*([^:]*?)\s*(?::\s*(.*))?$/i;
|
|
26
|
+
const LABEL = /^\s*(?:[-*]\s*)?(?:\*\*|__)?(input|expected|scoring)(?:\s+behaviou?r|\s+rubric|\s+conversation)?\s*(?::\s*(?:\*\*|__)?|(?:\*\*|__)\s*:)\s*(.*)$/i;
|
|
27
|
+
|
|
28
|
+
const truthy = (v) => v === true || /^\s*["']?(true|yes)["']?\s*$/i.test(String(v == null ? '' : v));
|
|
29
|
+
/** The record's `agent:` value reads true. */
|
|
30
|
+
const isAgent = (fm) => !!fm && truthy(fm.agent);
|
|
31
|
+
|
|
32
|
+
function frontmatter(text) {
|
|
33
|
+
const m = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);
|
|
34
|
+
const out = {};
|
|
35
|
+
if (!m) return { fm: out, body: text };
|
|
36
|
+
for (const l of m[1].split(/\r?\n/)) {
|
|
37
|
+
const kv = /^([A-Za-z_][\w-]*):\s*(.*)$/.exec(l);
|
|
38
|
+
if (kv) out[kv[1]] = kv[2].trim().replace(/^["']|["']$/g, '');
|
|
39
|
+
}
|
|
40
|
+
return { fm: out, body: text.slice(m[0].length) };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Read an eval set. Never throws. */
|
|
44
|
+
function parse(text) {
|
|
45
|
+
const missing = [];
|
|
46
|
+
const { fm, body } = frontmatter(String(text == null ? '' : text));
|
|
47
|
+
const raw = String(fm.pass_threshold == null ? '' : fm.pass_threshold).trim();
|
|
48
|
+
const t = /%$/.test(raw) ? Number(raw.slice(0, -1)) / 100 : Number(raw);
|
|
49
|
+
const threshold = raw !== '' && Number.isFinite(t) && t > 0 && t <= 1 ? t : null;
|
|
50
|
+
if (threshold === null) missing.push(raw ? `pass_threshold "${raw}" is not a number above 0 and at most 1` : 'no pass_threshold in the front matter');
|
|
51
|
+
|
|
52
|
+
const scenarios = [];
|
|
53
|
+
let cur = null, part = null;
|
|
54
|
+
for (const line of body.split(/\r?\n/)) {
|
|
55
|
+
const h = HEAD.exec(line);
|
|
56
|
+
if (h) { cur = { id: h[1] || String(scenarios.length + 1), title: (h[2] || '').trim(), input: '', expected: '', scoring: '' }; scenarios.push(cur); part = null; continue; }
|
|
57
|
+
if (/^#{1,2}\s/.test(line)) { cur = null; part = null; continue; }
|
|
58
|
+
if (!cur) continue;
|
|
59
|
+
const l = LABEL.exec(line);
|
|
60
|
+
if (l) { part = l[1].toLowerCase(); cur[part] = l[2].trim(); continue; }
|
|
61
|
+
if (part) cur[part] = (cur[part] + '\n' + line).trim();
|
|
62
|
+
}
|
|
63
|
+
if (scenarios.length < MIN_SCENARIOS) missing.push(`${scenarios.length} scenario${scenarios.length === 1 ? '' : 's'} (## Scenario …); an eval set needs at least ${MIN_SCENARIOS}`);
|
|
64
|
+
for (const s of scenarios) {
|
|
65
|
+
// a template placeholder (<…>, …, ...) and the turn labels are not content
|
|
66
|
+
const lack = PARTS.filter((p) => !s[p].replace(/<[^>\n]*>|…|\.\.\.|\b(user|agent|assistant)\s*:/gi, '').replace(/[>*_`\s.;:,-]/g, ''));
|
|
67
|
+
if (lack.length) missing.push(`scenario ${s.id} has no ${lack.join(', ')}`);
|
|
68
|
+
else if (!/(^|\n)\s*(?:>\s*)?(?:[-*]\s*)?(?:\*\*)?user(?:\*\*)?\s*:/i.test(s.input)) missing.push(`scenario ${s.id}'s input is not a conversation (no "user:" turn)`);
|
|
69
|
+
}
|
|
70
|
+
return { ok: missing.length === 0, threshold, scenarios, missing };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
module.exports = { MIN_SCENARIOS, isAgent, parse };
|
|
74
|
+
|
|
75
|
+
if (require.main === module) {
|
|
76
|
+
const f = process.argv[2];
|
|
77
|
+
if (!f) { console.log('usage: node scripts/agent-eval-set.js <file> [--json]'); process.exit(2); }
|
|
78
|
+
let text;
|
|
79
|
+
try { text = fs.readFileSync(f, 'utf8'); } catch { console.log(`agent-eval-set: cannot read ${f}`); process.exit(1); }
|
|
80
|
+
const r = parse(text);
|
|
81
|
+
if (process.argv.includes('--json')) console.log(JSON.stringify(r));
|
|
82
|
+
else console.log(r.ok ? `agent-eval-set: ${f} is a simulation eval set: ${r.scenarios.length} scenarios, pass threshold ${r.threshold}.`
|
|
83
|
+
: `agent-eval-set: ${f} is not a simulation eval set:\n${r.missing.map((m) => '- ' + m).join('\n')}`);
|
|
84
|
+
process.exit(r.ok ? 0 : 1);
|
|
85
|
+
}
|
|
@@ -598,6 +598,17 @@ function surfaceRoute(v) {
|
|
|
598
598
|
// D77 — the lane lists, tracks and rung sets are DATA in scripts/lane-defs.js. This file reads them;
|
|
599
599
|
// it holds no lane list of its own, so editing a definition changes the ladder with no edit here.
|
|
600
600
|
const laneDefs = require('./lane-defs');
|
|
601
|
+
// agent-product-lane (ADLC gap P1): a record with `agent: true` builds a product that is itself an AI agent; its done test is a
|
|
602
|
+
// simulation eval set (scripts/agent-eval-set.js), required before the build on both ladders.
|
|
603
|
+
const agentEvalSet = require('./agent-eval-set');
|
|
604
|
+
/** '' when the done test at `rel` is a valid simulation eval set, else what is missing (one line). */
|
|
605
|
+
function evalSetGap(root, rel) {
|
|
606
|
+
let text;
|
|
607
|
+
try { text = fs.readFileSync(path.resolve(root, rel), 'utf8'); } catch { return `${rel} cannot be read`; }
|
|
608
|
+
const r = agentEvalSet.parse(text);
|
|
609
|
+
return r.ok ? '' : r.missing.join('; ');
|
|
610
|
+
}
|
|
611
|
+
const AGENT_FIX = 'write the simulation eval set (okf/core/templates/agent-eval-set-template.md): pass_threshold, and at least 3 scenarios, each with Input (a user: turn), Expected and Scoring';
|
|
601
612
|
function profileOf(root) {
|
|
602
613
|
try {
|
|
603
614
|
const line = fs.readFileSync(path.join(root, '.pmos-profile'), 'utf8')
|
|
@@ -1010,7 +1021,11 @@ function computeWorkflowDerived(id, opts) {
|
|
|
1010
1021
|
// PRD already on the record still satisfies the spec rung after a kind change: a gate already passed stays passed.
|
|
1011
1022
|
const workKind = (() => { const k = String(fm.kind || '').trim().replace(/^["']|["']$/g, ''); return k === 'sdlc' || k === 'project' ? k : 'product'; })();
|
|
1012
1023
|
const planPath = String(fm.plan_path || '').trim();
|
|
1013
|
-
|
|
1024
|
+
const agentMode = agentEvalSet.isAgent(fm);
|
|
1025
|
+
if (agentMode && !doneTest) {
|
|
1026
|
+
steps.push(step('spec', 'spec', 'blocked', 'an agent product (agent: true) needs a simulation eval set as its done test before the build — never a PRD',
|
|
1027
|
+
`${AGENT_FIX}; set done_test_path and kill: in ${recRel}`, { blocking: true, rule: 'R2' }));
|
|
1028
|
+
} else if (!doneTest && workKind === 'sdlc' && !prd) {
|
|
1014
1029
|
steps.push(step('spec', 'spec', 'blocked', 'Full SDLC needs a done test and a kill condition before the first pull request — never a PRD',
|
|
1015
1030
|
`write the done test (okf/core/templates/done-test-template.md), set done_test_path and kill: in ${recRel}`, { blocking: true, rule: 'R2' }));
|
|
1016
1031
|
} else if (!doneTest && workKind === 'project' && (planPath || !prd)) {
|
|
@@ -1035,8 +1050,11 @@ function computeWorkflowDerived(id, opts) {
|
|
|
1035
1050
|
} else if (!killCond) {
|
|
1036
1051
|
steps.push(step('spec', 'spec', 'blocked', 'no kill condition — an experiment states what would stop it (D107)',
|
|
1037
1052
|
`write kill: "<the result that would make us stop>" in ${recRel}`, { blocking: true, rule: 'R2' }));
|
|
1053
|
+
} else if (agentMode && evalSetGap(root, doneTest)) {
|
|
1054
|
+
steps.push(step('spec', 'spec', 'blocked', `an agent product's done test is a simulation eval set: ${evalSetGap(root, doneTest)}`,
|
|
1055
|
+
`${AGENT_FIX} in ${doneTest}`, { blocking: true, rule: 'R2' }));
|
|
1038
1056
|
} else {
|
|
1039
|
-
steps.push(orderOf(`done test ${doneTest}`, dtIdx, 'O1'));
|
|
1057
|
+
steps.push(orderOf(agentMode ? `eval set ${doneTest}` : `done test ${doneTest}`, dtIdx, 'O1'));
|
|
1040
1058
|
}
|
|
1041
1059
|
} else {
|
|
1042
1060
|
const wants = {
|
|
@@ -1651,7 +1669,14 @@ function pmLadder({ id, fm, lane, effLane, knownLane, legacy, steps, root, L, re
|
|
|
1651
1669
|
const planPath = String(fm.plan_path || '').trim();
|
|
1652
1670
|
const kindSpec = !doneTest && !exists(briefPath) && !foundBrief && (workKind === 'sdlc' || (workKind === 'project'));
|
|
1653
1671
|
const tasksPlan = kindSpec && workKind === 'project' && !planPath ? taskPlanOf(root, id) : null;
|
|
1654
|
-
|
|
1672
|
+
const agentMode = agentEvalSet.isAgent(fm);
|
|
1673
|
+
const agentGap = agentMode && dtPresent ? evalSetGap(root, doneTest) : '';
|
|
1674
|
+
if (agentMode && !doneTest) steps.push(step('brief', 'eval set', legacy ? 'pending' : 'blocked',
|
|
1675
|
+
'an agent product (agent: true) needs a simulation eval set as its done test before the build — never a brief or a PRD',
|
|
1676
|
+
`${AGENT_FIX}; set done_test_path and kill: in ${recRel}`, { blocking: !legacy, rule: 'R2' }));
|
|
1677
|
+
else if (agentGap && killCond) steps.push(step('brief', 'eval set', legacy ? 'pending' : 'blocked', `an agent product's done test is a simulation eval set: ${agentGap}`,
|
|
1678
|
+
`${AGENT_FIX} in ${doneTest}`, { blocking: !legacy, rule: 'R2' }));
|
|
1679
|
+
else if (doneTest && dtPresent && killCond) steps.push(step('brief', def.brief_label, 'done', agentMode ? `eval set ${doneTest} + kill condition (agent product)` : `done test ${doneTest} + kill condition (D107)`));
|
|
1655
1680
|
else if (kindSpec && workKind === 'sdlc') steps.push(step('brief', 'done test', legacy ? 'pending' : 'blocked',
|
|
1656
1681
|
'Full SDLC needs a done test and a kill condition before the first pull request — never a brief or a PRD',
|
|
1657
1682
|
`write the done test, set done_test_path and kill: in ${recRel} (pmos artefacts set experiment:${id} done-test check --text "…" writes both)`, { blocking: !legacy, rule: 'R2' }));
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/* factory-checks.js — the product's own checks, run by PMOS in the Builder's worktree (initiative factory-builder-inner-loop, done test L1–L3).
|
|
3
|
+
* No model.
|
|
4
|
+
*
|
|
5
|
+
* checksOf(root) → { checks: [{ name, cmd }], dropped: [name], timeout_ms } what the product declares in <kit>/factory.json
|
|
6
|
+
* isolation() → { argv(cmd) → [bin, ...args], how } | null how this machine runs a command with no network
|
|
7
|
+
* runChecks(root, item, { env }) → { ok, declared, results: [{ name, cmd, code, ms, tail }], evidence, error? }
|
|
8
|
+
* record(root, item, out, { now }) → the line written to <state>/factory-checks.jsonl
|
|
9
|
+
* evidenceOf(results) → 'test: exit 0 · lint: exit 0'
|
|
10
|
+
*
|
|
11
|
+
* THE DECLARATION is the PM's: `<kit>/factory.json` (pmos/factory.json in a product repository), next to the flag provider:
|
|
12
|
+
* { "checks": { "test": "npm test", "lint": "npm run lint", "secrets": "gitleaks detect --no-git" }, "checks_timeout_minutes": 15 }
|
|
13
|
+
* PMOS reads it from the PM's checkout (WK.factoryDir(root)), never from the Builder's worktree, and a factory commit may not touch
|
|
14
|
+
* pmos/ (lib/build-engine.js FORBIDDEN). So the Builder runs exactly the commands the PM wrote, and cannot change them.
|
|
15
|
+
*
|
|
16
|
+
* THE TRIFECTA. A check runs code the Builder wrote, so it must not be an outward channel. Each command runs:
|
|
17
|
+
* - in the item's worktree only (lib/build-engine.js worktreeOf), never the PM's checkout;
|
|
18
|
+
* - in a new network namespace with only loopback (Linux `unshare -rn`), or under `sandbox-exec` with outbound IP denied (macOS);
|
|
19
|
+
* - with every token and proxy variable taken out of the environment (GH_TOKEN, GITHUB_TOKEN, *_PROXY, …).
|
|
20
|
+
* Where neither isolation works, the checks do not run and the caller says why. There is no setting that runs them with the network on.
|
|
21
|
+
*/
|
|
22
|
+
const fs = require('fs');
|
|
23
|
+
const path = require('path');
|
|
24
|
+
const cp = require('child_process');
|
|
25
|
+
const WK = require('./work-kind.js');
|
|
26
|
+
|
|
27
|
+
const NAME_RE = /^[a-z0-9][a-z0-9_-]{0,39}$/;
|
|
28
|
+
const MAX = 8;
|
|
29
|
+
const TAIL = 1200;
|
|
30
|
+
const LEDGER = 'factory-checks.jsonl';
|
|
31
|
+
const DEFAULT_TIMEOUT_MS = 15 * 60 * 1000;
|
|
32
|
+
const STRIP = /^(GH_TOKEN|GITHUB_TOKEN|GH_ENTERPRISE_TOKEN|GITHUB_ENTERPRISE_TOKEN|NPM_TOKEN|NODE_AUTH_TOKEN|ANTHROPIC_API_KEY|OPENAI_API_KEY|AWS_[A-Z_]+|SSH_AUTH_SOCK|https?_proxy|all_proxy|no_proxy|HTTPS?_PROXY|ALL_PROXY|NO_PROXY|PMOS_TEAM_FILE)$/;
|
|
33
|
+
const one = (s, n) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim().slice(0, n);
|
|
34
|
+
|
|
35
|
+
/** → { checks, dropped, timeout_ms }. No file or no "checks": no checks. */
|
|
36
|
+
function checksOf(root) {
|
|
37
|
+
const dir = WK.factoryDir(root);
|
|
38
|
+
const none = { checks: [], dropped: [], timeout_ms: DEFAULT_TIMEOUT_MS };
|
|
39
|
+
if (!dir) return none;
|
|
40
|
+
let j;
|
|
41
|
+
try { j = JSON.parse(fs.readFileSync(path.join(dir, 'factory.json'), 'utf8')); } catch { return none; }
|
|
42
|
+
const c = j && j.checks && typeof j.checks === 'object' && !Array.isArray(j.checks) ? j.checks : {};
|
|
43
|
+
const checks = [], dropped = [];
|
|
44
|
+
for (const [name, cmd] of Object.entries(c)) {
|
|
45
|
+
if (NAME_RE.test(name) && typeof cmd === 'string' && cmd.trim() && cmd.length <= 500 && !cmd.includes('\0') && checks.length < MAX) checks.push({ name, cmd: cmd.trim() });
|
|
46
|
+
else dropped.push(one(name, 40));
|
|
47
|
+
}
|
|
48
|
+
const m = Number(j && j.checks_timeout_minutes);
|
|
49
|
+
return { checks, dropped, timeout_ms: Number.isFinite(m) && m > 0 && m <= 120 ? m * 60000 : DEFAULT_TIMEOUT_MS };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// loopback up inside the new namespace, so a test server on 127.0.0.1 still works; best effort (ip, else python3)
|
|
53
|
+
const LO_UP = 'ip link set lo up 2>/dev/null || python3 -c "import socket,fcntl,struct;s=socket.socket(2,2);f=struct.unpack(\'16sh\',fcntl.ioctl(s,0x8913,struct.pack(\'16sh\',b\'lo\',0)))[1];fcntl.ioctl(s,0x8914,struct.pack(\'16sh\',b\'lo\',f|1))" 2>/dev/null; ';
|
|
54
|
+
// later rules win in a sandbox profile: every outbound IP is denied, then loopback is allowed again. A profile this macOS does not
|
|
55
|
+
// parse fails the probe below, so it fails closed (no isolation, no checks), never open.
|
|
56
|
+
const MAC_PROFILE = '(version 1)(allow default)(deny network-outbound (remote ip "*:*"))(allow network-outbound (remote ip "localhost:*"))';
|
|
57
|
+
|
|
58
|
+
let probed;
|
|
59
|
+
let override = null;
|
|
60
|
+
/** How this machine runs a command with no network, or null. Probed once: a namespace that cannot be made is no isolation. */
|
|
61
|
+
function isolation() {
|
|
62
|
+
if (override !== null) return override || null;
|
|
63
|
+
if (probed !== undefined) return probed;
|
|
64
|
+
probed = null;
|
|
65
|
+
if (process.platform === 'linux') {
|
|
66
|
+
const r = cp.spawnSync('unshare', ['-rn', 'true'], { encoding: 'utf8', timeout: 10000 });
|
|
67
|
+
if (!r.error && r.status === 0) probed = { how: 'unshare -rn (no network namespace)', argv: (cmd) => ['unshare', '-rn', 'sh', '-c', LO_UP + cmd] };
|
|
68
|
+
} else if (process.platform === 'darwin') {
|
|
69
|
+
const r = cp.spawnSync('sandbox-exec', ['-p', MAC_PROFILE, 'true'], { encoding: 'utf8', timeout: 10000 });
|
|
70
|
+
if (!r.error && r.status === 0) probed = { how: 'sandbox-exec (outbound IP denied)', argv: (cmd) => ['sandbox-exec', '-p', MAC_PROFILE, 'sh', '-c', cmd] };
|
|
71
|
+
}
|
|
72
|
+
return probed;
|
|
73
|
+
}
|
|
74
|
+
/** Tests only, in-process: replace the isolation ({ how, argv }, false for "none on this machine", null to probe again).
|
|
75
|
+
* No environment variable reaches it. */
|
|
76
|
+
function __setIsolationForTests(x) { override = x === false ? false : (x || null); if (x == null) probed = undefined; }
|
|
77
|
+
|
|
78
|
+
function cleanEnv(env) {
|
|
79
|
+
const out = {};
|
|
80
|
+
for (const [k, v] of Object.entries(env || {})) if (!STRIP.test(k)) out[k] = v;
|
|
81
|
+
return { ...out, GIT_TERMINAL_PROMPT: '0', CI: '1', PMOS_CHECK: '1' };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const evidenceOf = (results) => results.map((r) => `${r.name}: ${r.code === 0 ? 'exit 0' : r.code == null ? 'timed out' : 'exit ' + r.code}`).join(' · ');
|
|
85
|
+
|
|
86
|
+
/** Run every declared check in the item's worktree. ok only when every check exits 0. */
|
|
87
|
+
function runChecks(root, item, { env = process.env } = {}) {
|
|
88
|
+
const { checks, dropped, timeout_ms } = checksOf(root);
|
|
89
|
+
if (!checks.length) return { ok: true, declared: false, results: [], evidence: '', dropped };
|
|
90
|
+
const wt = require('./build-engine.js').worktreeOf(root, item);
|
|
91
|
+
if (!fs.existsSync(wt)) return { ok: false, declared: true, results: [], evidence: '', error: `${item} has no worktree at ${wt}` };
|
|
92
|
+
const iso = isolation();
|
|
93
|
+
if (!iso) return { ok: false, declared: true, results: [], evidence: '', error: 'this machine cannot run a command without network (no unshare on Linux, no sandbox-exec on macOS), so PMOS does not run the product\'s checks here' };
|
|
94
|
+
const e = cleanEnv(env);
|
|
95
|
+
const results = [];
|
|
96
|
+
for (const c of checks) {
|
|
97
|
+
const t0 = Date.now();
|
|
98
|
+
const [bin, ...args] = iso.argv(c.cmd);
|
|
99
|
+
const r = cp.spawnSync(bin, args, { cwd: wt, env: e, encoding: 'utf8', timeout: timeout_ms, maxBuffer: 32 * 1024 * 1024 });
|
|
100
|
+
const all = String(r.stdout || '') + String(r.stderr || '') + (r.error && r.error.code !== 'ETIMEDOUT' ? String(r.error.message) : '');
|
|
101
|
+
const code = r.error && r.error.code === 'ETIMEDOUT' ? null : (r.status == null ? 1 : r.status);
|
|
102
|
+
results.push({ name: c.name, cmd: c.cmd, code, ms: Date.now() - t0, tail: all.slice(-TAIL) });
|
|
103
|
+
}
|
|
104
|
+
return { ok: results.every((r) => r.code === 0), declared: true, results, evidence: evidenceOf(results), isolation: iso.how, dropped };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** One line per run in <state>/factory-checks.jsonl: the exit codes and the tails, which the ledger's one-line evidence cannot hold. */
|
|
108
|
+
function record(root, item, out, { now = Date.now(), commit = null } = {}) {
|
|
109
|
+
const top = (() => { const r = cp.spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd: root, encoding: 'utf8' }); return r.status === 0 ? String(r.stdout).trim() : root; })();
|
|
110
|
+
const dir = require('./driver.js').stateDirOf(top, { create: true });
|
|
111
|
+
const line = { at: new Date(now).toISOString(), item, ok: !!out.ok, ...(commit ? { commit } : {}), isolation: out.isolation || null,
|
|
112
|
+
results: (out.results || []).map((r) => ({ name: r.name, code: r.code, ms: r.ms, tail: r.tail })) };
|
|
113
|
+
if (dir) { try { fs.mkdirSync(dir, { recursive: true }); fs.appendFileSync(path.join(dir, LEDGER), JSON.stringify(line) + '\n'); } catch { /* the evidence line still says what ran */ } }
|
|
114
|
+
return line;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
module.exports = { NAME_RE, MAX, LEDGER, checksOf, isolation, runChecks, record, evidenceOf, cleanEnv, __setIsolationForTests };
|