create-pmos 0.575.0 → 0.577.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.
Files changed (62) hide show
  1. package/package.json +27 -27
  2. package/payload/AGENTS.md +35 -2
  3. package/payload/KIT-VERSION +2 -2
  4. package/payload/okf/core/templates/agent-eval-set-template.md +65 -0
  5. package/payload/okf/core/templates/index.md +1 -0
  6. package/payload/planning/evals/eval-calibration.md +1 -1
  7. package/payload/planning/okrs/health-budgets.md +1 -1
  8. package/payload/scripts/agent-eval-set.js +85 -0
  9. package/payload/scripts/factory-guardrail.js +50 -8
  10. package/payload/scripts/work-item.js +49 -3
  11. package/payload/scripts/workflow-state.js +28 -3
  12. package/payload/state/discoveries.md +1 -1
  13. package/payload/state/log.md +1 -1
  14. package/payload/templates/pmos-guardrail.yml +38 -10
  15. package/payload/templates/pmos-review-check.yml +59 -0
  16. package/workspace/changelog.json +26 -0
  17. package/workspace/fixtures/builder-bench.json +121 -0
  18. package/workspace/guide/cli.md +71 -4
  19. package/workspace/guide/settings-and-switches.md +7 -0
  20. package/workspace/lib/agent-team.js +5 -2
  21. package/workspace/lib/build-cli.js +119 -7
  22. package/workspace/lib/build-engine.js +106 -25
  23. package/workspace/lib/builder-bench.js +267 -0
  24. package/workspace/lib/engine/agent-eval-set.js +85 -0
  25. package/workspace/lib/engine/workflow-state.js +28 -3
  26. package/workspace/lib/factory-checks.js +117 -0
  27. package/workspace/lib/factory-ci.js +151 -0
  28. package/workspace/lib/factory-fleet.js +263 -0
  29. package/workspace/lib/factory-identity.js +182 -0
  30. package/workspace/lib/factory-lessons.js +183 -0
  31. package/workspace/lib/factory-needs.js +48 -0
  32. package/workspace/lib/factory-review.js +241 -0
  33. package/workspace/lib/factory-rollout.js +56 -10
  34. package/workspace/lib/factory-traces.js +229 -0
  35. package/workspace/lib/headless.js +11 -2
  36. package/workspace/lib/job-graph.js +9 -1
  37. package/workspace/lib/needs-providers.js +1 -0
  38. package/workspace/lib/pmos-verbs.js +1 -1
  39. package/workspace/lib/project-onboard.js +1 -1
  40. package/workspace/lib/proposals.js +3 -1
  41. package/workspace/lib/route-modules.js +1 -0
  42. package/workspace/lib/routes-factory-metrics.js +41 -0
  43. package/workspace/lib/routes-proposals.js +9 -1
  44. package/workspace/lib/signals.js +272 -0
  45. package/workspace/lib/team-cli.js +2 -2
  46. package/workspace/lib/team-runs.js +13 -3
  47. package/workspace/lib/vendor/scripts/agent-eval-set.js +85 -0
  48. package/workspace/lib/vendor/scripts/workflow-state.js +28 -3
  49. package/workspace/lib/verify-runs.js +89 -1
  50. package/workspace/package-lock.json +2 -2
  51. package/workspace/package.json +1 -1
  52. package/workspace/public/pm/ini-props.js +1 -1
  53. package/workspace/server.js +4 -0
  54. package/workspace/test-files.json +2 -1
  55. package/workspace/test-lists/adlc-identity.json +9 -0
  56. package/workspace/test-lists/build-engine.json +5 -3
  57. package/workspace/test-lists/builder-bench.json +9 -0
  58. package/workspace/test-lists/factory-checks.json +9 -0
  59. package/workspace/test-lists/factory-fleet.json +9 -0
  60. package/workspace/test-lists/factory-lessons.json +9 -0
  61. package/workspace/test-lists/factory-real-run.json +9 -0
  62. package/workspace/test-lists/factory-run-traces.json +9 -0
@@ -0,0 +1,151 @@
1
+ 'use strict';
2
+ /* factory-ci.js — the CI-fix loop of the factory (initiative factory-builder-inner-loop, done test L6). No model.
3
+ *
4
+ * prChecks(root, item, { env }) → { state: 'pass'|'fail'|'pending'|'none', open, head, failed: [name], url } | { error }
5
+ * tick(root, { now, env, every }) → { acted: [{ item, step, why }], why? } the server's verify tick runs it for each product with a
6
+ * factory, at most once per `every` ms (5 minutes)
7
+ * statusOf(root) → [{ item, step, head, at, why }] the newest line per item
8
+ *
9
+ * THE LOOP, per verified work item whose pull request is open (state `verified`: the Builder proposed and PMOS opened it):
10
+ * 1. PMOS reads the pull request's checks with `gh pr view` IN ITS OWN PROCESS. The Builder's run never reads CI: it has no gh and no
11
+ * network, and tick() refuses a role run (PMOS_TEAM_RUN).
12
+ * 2. pending, passing, or no checks: nothing. A head on GitHub that is not the local branch's head: wait (a fix is not pushed yet, or
13
+ * someone else pushed).
14
+ * 3. failed at that head, and the item had fewer than FIX_ROUNDS fix rounds (lib/build-engine.js roundsOf): PMOS queues ONE Builder
15
+ * step in the team ledger (lib/team-runs.js, `trigger: ci-fix`), so the team runner starts it like any role run. Once per head.
16
+ * At the Builder's daily budget (lib/agent-team.js TEAM.build.budget, counted over today's Builder steps) it waits and says so once.
17
+ * 4. failed after FIX_ROUNDS rounds: PMOS appends `blocked` with the reason through the ledger's one writer (scripts/work-item.js block).
18
+ * Today shows it (lib/factory-needs.js).
19
+ * `pmos ai off` (PMOS_AUTONOMY=off) stops the loop. Every step is one line in <state>/factory-ci.jsonl.
20
+ * The guardrail's own check (pmos-guardrail) is not a CI failure: HUMAN is a merge decision, not something the Builder fixes.
21
+ */
22
+ const fs = require('fs');
23
+ const path = require('path');
24
+ const crypto = require('crypto');
25
+ const cp = require('child_process');
26
+ const WK = require('./work-kind.js');
27
+
28
+ const LEDGER = 'factory-ci.jsonl';
29
+ const FAIL = new Set(['FAILURE', 'TIMED_OUT', 'CANCELLED', 'ACTION_REQUIRED', 'STARTUP_FAILURE', 'ERROR']);
30
+ const DONE_OK = new Set(['SUCCESS', 'NEUTRAL', 'SKIPPED']);
31
+ const HEX = /^[0-9a-f]{40}$/;
32
+ const one = (s, n) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim().slice(0, n);
33
+
34
+ function topOf(root) {
35
+ const r = cp.spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd: root, encoding: 'utf8' });
36
+ return r.status === 0 ? String(r.stdout).trim() : null;
37
+ }
38
+ const stateDir = (root) => require('./driver.js').stateDirOf(topOf(root) || root, { create: true });
39
+ function lines(root) {
40
+ const d = stateDir(root);
41
+ if (!d) return [];
42
+ let t = '';
43
+ try { t = fs.readFileSync(path.join(d, LEDGER), 'utf8'); } catch { return []; }
44
+ return t.split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
45
+ }
46
+ function log(root, line, now) {
47
+ const d = stateDir(root);
48
+ const full = { at: new Date(now == null ? Date.now() : now).toISOString(), ...line };
49
+ if (d) fs.appendFileSync(path.join(d, LEDGER), JSON.stringify(full) + '\n');
50
+ return full;
51
+ }
52
+
53
+ const isGuardrail = (c) => /pmos-guardrail/i.test(String(c.workflowName || '')) || /pmos-guardrail/i.test(String(c.name || c.context || ''));
54
+
55
+ /** The checks GitHub reports for the item's pull request, read by PMOS's own process with the PM's gh. */
56
+ function prChecks(root, item, { env = process.env } = {}) {
57
+ if (env.PMOS_TEAM_RUN) return { error: 'a role run cannot read CI' };
58
+ const top = topOf(root) || root;
59
+ const BE = require('./build-engine.js');
60
+ const r = cp.spawnSync('gh', ['pr', 'view', BE.branchOf(item), '--json', 'url,state,headRefOid,statusCheckRollup'], { cwd: top, encoding: 'utf8', env, timeout: 60000 });
61
+ if (r.error || r.status !== 0) return { error: one(r.stderr || (r.error && r.error.message) || 'gh pr view failed', 200) };
62
+ let j;
63
+ try { j = JSON.parse(r.stdout || 'null'); } catch { return { error: 'gh printed no JSON' }; }
64
+ if (!j || typeof j !== 'object') return { error: 'gh printed no pull request' };
65
+ const all = (Array.isArray(j.statusCheckRollup) ? j.statusCheckRollup : []).filter((c) => c && typeof c === 'object' && !isGuardrail(c));
66
+ const failed = [], pending = [];
67
+ for (const c of all) {
68
+ const name = one(c.name || c.context || 'a check', 80);
69
+ const concl = String(c.conclusion || '').toUpperCase(), st = String(c.status || c.state || '').toUpperCase();
70
+ if (FAIL.has(concl) || FAIL.has(st)) failed.push(name);
71
+ else if (!(DONE_OK.has(concl) || DONE_OK.has(st))) pending.push(name);
72
+ }
73
+ const state = !all.length ? 'none' : failed.length ? 'fail' : pending.length ? 'pending' : 'pass';
74
+ return { state, open: j.state === 'OPEN', head: HEX.test(String(j.headRefOid || '')) ? j.headRefOid : null, failed, url: one(j.url, 300) };
75
+ }
76
+
77
+ /** Today's Builder steps (started, queued or held) in the team ledger, against the role's daily budget. */
78
+ function budgetOf(dir, now) {
79
+ const T = require('./agent-team.js'), TR = require('./team-runs.js');
80
+ const F = TR.fold(TR.read(dir)); // read again: an earlier item in this tick may have queued a step
81
+ const today = T.localDay(now);
82
+ const used = F.steps.filter((s) => s.role === 'build' && ((s.started && T.localDay(Date.parse(s.started)) === today)
83
+ || ((s.state === 'queued' || s.state === 'held') && T.localDay(Date.parse(s.at)) === today))).length;
84
+ return { used, budget: T.TEAM.build.budget, F };
85
+ }
86
+
87
+ const EVERY_MS = 5 * 60 * 1000; // one gh read per verified item every 5 minutes, not every verify tick
88
+ const lastTick = new Map();
89
+ function tick(root, { now = Date.now(), env = process.env, every = EVERY_MS } = {}) {
90
+ if (env.PMOS_TEAM_RUN) return { acted: [], why: 'a role run cannot run the CI-fix loop' };
91
+ if (!WK.factoryRuns(root)) return { acted: [] };
92
+ const key = path.resolve(root);
93
+ if (every > 0 && lastTick.has(key) && now - lastTick.get(key) < every) return { acted: [] };
94
+ lastTick.set(key, now);
95
+ const k = require('./autonomy.js').killed({ env });
96
+ if (k) return { acted: [], why: k };
97
+ const BE = require('./build-engine.js');
98
+ const items = BE.itemsOf(root).filter((x) => x.state === 'verified');
99
+ if (!items.length) return { acted: [] };
100
+ const top = topOf(root) || root;
101
+ const dir = stateDir(root);
102
+ const seen = new Map(), sent = new Map();
103
+ for (const l of lines(root)) if (l.item) { seen.set(l.item, l); if (l.step === 'dispatched') sent.set(l.item, (sent.get(l.item) || 0) + 1); }
104
+ const TR = require('./team-runs.js');
105
+ const steps = dir ? TR.fold(TR.read(dir)).steps : [];
106
+ const acted = [];
107
+ const say = (line) => { acted.push(log(root, line, now)); };
108
+ for (const it of items) {
109
+ const local = cp.spawnSync('git', ['rev-parse', '--verify', '--quiet', 'refs/heads/' + BE.branchOf(it.item_id)], { cwd: top, encoding: 'utf8' });
110
+ const head = local.status === 0 ? String(local.stdout).trim() : '';
111
+ if (!HEX.test(head)) continue;
112
+ const pr = prChecks(root, it.item_id, { env });
113
+ if (pr.error || !pr.open || pr.state !== 'fail') continue;
114
+ if (pr.head !== head) continue; // the fix is not pushed yet, or the branch moved: read again on the next tick
115
+ const prev = seen.get(it.item_id);
116
+ if (prev && prev.head === head) {
117
+ if (prev.step === 'blocked' || prev.step === 'block-failed') continue;
118
+ // a round dispatched at this head: wait while its run is queued or working. A run that ended with no fix pushed spent its round.
119
+ if (prev.step === 'dispatched') { const s = steps.find((x) => x.id === prev.run); if (!s || !(s.state === 'done' || s.state === 'failed')) continue; }
120
+ }
121
+ const rounds = Math.max(BE.roundsOf(it), sent.get(it.item_id) || 0);
122
+ const names = pr.failed.slice(0, 8);
123
+ if (rounds >= BE.FIX_ROUNDS) {
124
+ const reason = one(`The product's CI still fails after ${rounds} fix rounds (${names.join(', ') || 'a check'}). PMOS stopped; it waits for you.`, 480);
125
+ const r = cp.spawnSync(process.execPath, [path.join(WK.factoryDir(root), 'scripts', 'work-item.js'), 'block', it.item_id, '--reason', reason], { cwd: WK.factoryDir(root), encoding: 'utf8' });
126
+ say({ item: it.item_id, head, step: r.status === 0 ? 'blocked' : 'block-failed', failed: names, url: pr.url,
127
+ why: r.status === 0 ? reason : one(String(r.stdout || '') + String(r.stderr || ''), 300) });
128
+ continue;
129
+ }
130
+ if (!dir) continue;
131
+ const b = budgetOf(dir, now);
132
+ if (b.used >= b.budget) {
133
+ if (!prev || prev.head !== head || prev.step !== 'wait-budget') say({ item: it.item_id, head, step: 'wait-budget', failed: names, why: `The Builder used its ${b.budget} runs for today. The fix round of ${it.item_id} starts when the Builder has a run left, tomorrow at the latest` });
134
+ continue;
135
+ }
136
+ const round = rounds + 1;
137
+ const step = { kind: 'step', id: 'tr' + now.toString(36) + crypto.randomBytes(3).toString('hex'), role: 'build', ini: it.initiative_id, ws: null, board: null,
138
+ trigger: 'ci-fix', key: `ci-fix:${it.item_id}:${head}`, item: it.item_id, round, failed: names, detail: `CI failed on ${it.item_id}: ${names.join(', ') || 'a check'}`, state: 'queued' };
139
+ require('./team-runs.js').append(dir, step, now);
140
+ say({ item: it.item_id, head, step: 'dispatched', round, run: step.id, failed: names, url: pr.url, why: `CI failed (${names.join(', ') || 'a check'}). PMOS started fix round ${round} of ${BE.FIX_ROUNDS}` });
141
+ }
142
+ return { acted };
143
+ }
144
+
145
+ function statusOf(root) {
146
+ const m = new Map();
147
+ for (const l of lines(root)) if (l.item) m.set(l.item, l);
148
+ return [...m.values()].map((l) => ({ item: l.item, step: l.step, head: l.head, at: l.at, why: l.why || '' }));
149
+ }
150
+
151
+ module.exports = { LEDGER, prChecks, tick, statusOf };
@@ -0,0 +1,263 @@
1
+ 'use strict';
2
+ /* factory-fleet.js — more than one Builder, in dependency order, with an integrator (initiative factory-fleet-scale, ADLC gap P2,
3
+ * done test P1–P6). No model. lib/build-engine.js calls it from next(), claim() and open().
4
+ *
5
+ * buildersOf(root) → { max_parallel, per_day, set } the Builder's concurrency, from pmos/factory.json "builders"
6
+ * waitingOn(item, items) → [item id] the dependencies (depends_on) not integrated or shipped yet
7
+ * roleBudget(role, { root }) → n a role's runs a day; the Builder's is builders.per_day (lib/agent-team.js keeps the rest)
8
+ * claimRoom(root, items, { now }) → { ok } | { ok: false, error } refuses a Builder claim past max_parallel or per_day
9
+ * integrate(root, { env, now, every? }) → { ok, acted: [{ item, step, why, files? }] } | { ok: false, error }
10
+ * inFixRound(root, item) · finishFix(root, item, { env }) → { ok, pushed, branch } | { ok: false, error }
11
+ *
12
+ * THE CONCURRENCY is the PM's: `<kit>/factory.json` (pmos/factory.json in a product repository)
13
+ * { "builders": { "max_parallel": 2, "per_day": 6 } } default 1 and 2. max_parallel 1–20, per_day 1–100; anything else is the default.
14
+ * A Builder claim is one whose agent starts with `pmos:builder` (lib/build-cli.js claim). A claim the PM made with `declare` is not counted.
15
+ * max_parallel always holds. per_day caps claims only when "builders" is set; with no setting the Builder's day budget is shown, not enforced.
16
+ *
17
+ * THE INTEGRATOR runs in PMOS's own process (the verify tick and `pmos build integrate`), never in a role run. For each open pull request
18
+ * on pmos/<item> whose item is verified:
19
+ * - the default branch has not changed a file the branch changes: nothing.
20
+ * - it has: PMOS rebases the branch onto the default branch in the item's worktree, with the repository's own git identity.
21
+ * A rebase rewrites the branch, so the push is forced, with a lease on the sha PMOS pushed, by an explicit refspec
22
+ * refs/heads/pmos/<item>, and only while the pull request is a draft: a ready one is turned back to draft first (GitHub drops its
23
+ * auto-merge; the guardrail marks it ready again on AUTO). The push reruns the checks. The default branch is never pushed.
24
+ * - the rebase conflicts: PMOS aborts it and pushes nothing. The first time, the item goes back to the Builder as a FIX ROUND: PMOS
25
+ * claims it again for the Builder and puts the branch's change onto the default branch in the worktree with the conflicts left to
26
+ * resolve. The Builder resolves them and runs `pmos build propose`; open() then finishes the round (finishFix: the same draft-only,
27
+ * leased push, no new pull request). The second time, the item is BLOCKED: the pull request gets `PMOS-Merge: human` and the PM
28
+ * resolves it.
29
+ * It reads the default branch as this checkout last fetched it (the PM's sync fetches); it fetches nothing itself.
30
+ * Every step is one line in <state>/factory-integrate.jsonl.
31
+ */
32
+ const fs = require('fs');
33
+ const path = require('path');
34
+ const WK = require('./work-kind.js');
35
+
36
+ const DEFAULTS = Object.freeze({ max_parallel: 1, per_day: 2 });
37
+ const RANGE = Object.freeze({ max_parallel: [1, 20], per_day: [1, 100] });
38
+ const BUILDER = 'pmos:builder';
39
+ const FIX_AGENT = 'pmos:builder:fix';
40
+ const DONE = Object.freeze(['integrated', 'shipped']);
41
+ const LEDGER = 'factory-integrate.jsonl';
42
+ const MAX_FIX_ROUNDS = 1;
43
+ const ITEM_BRANCH = /^pmos\/([a-z0-9][a-z0-9_-]*\.[0-9]+)$/;
44
+ const one = (s, n) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim().slice(0, n);
45
+ const BE = () => require('./build-engine.js');
46
+
47
+ function buildersOf(root) {
48
+ const dir = root ? WK.factoryDir(root) : null;
49
+ let b = null;
50
+ try { const j = JSON.parse(fs.readFileSync(path.join(dir, 'factory.json'), 'utf8')); b = j && j.builders && typeof j.builders === 'object' ? j.builders : null; } catch { b = null; }
51
+ const out = { ...DEFAULTS, set: !!b };
52
+ for (const k of Object.keys(DEFAULTS)) {
53
+ const n = b ? Number(b[k]) : NaN;
54
+ if (Number.isInteger(n) && n >= RANGE[k][0] && n <= RANGE[k][1]) out[k] = n;
55
+ }
56
+ return out;
57
+ }
58
+
59
+ /** The most runs a role starts in one local day. The Builder's is builders.per_day when a factory repository is named; every other role's is
60
+ * its record's in lib/agent-team.js. `role` is a key or a role record. */
61
+ function roleBudget(r, { root = null } = {}) {
62
+ const ro = typeof r === 'string' ? require('./agent-team.js').roleOf(r) : r;
63
+ if (!ro) return 0;
64
+ return ro.key === 'build' && root && WK.factoryRuns(root) ? buildersOf(root).per_day : ro.budget;
65
+ }
66
+
67
+ /** PURE. The ids in item.depends_on whose item is not integrated or shipped. An id with no item waits too (never assumed done). */
68
+ function waitingOn(it, items) {
69
+ const deps = it && Array.isArray(it.depends_on) ? it.depends_on : [];
70
+ if (!deps.length) return [];
71
+ const byId = new Map((items || []).map((x) => [x.item_id, x]));
72
+ return deps.filter((d) => { const x = byId.get(d); return !x || !DONE.includes(x.state); });
73
+ }
74
+
75
+ const localDay = (ms) => { const d = new Date(ms); return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0'); };
76
+ const isBuilder = (agent) => typeof agent === 'string' && (agent === BUILDER || agent.startsWith(BUILDER + ':')) && agent !== FIX_AGENT;
77
+
78
+ /** The Builder claims made on the local day of `now`, read from the ledger's own lines (the fold keeps no claim times). */
79
+ function claimsToday(root, now) {
80
+ const dir = WK.factoryDir(root);
81
+ let t = '';
82
+ try { t = fs.readFileSync(path.join(dir, 'planning', 'work-items.jsonl'), 'utf8'); } catch { return 0; }
83
+ const day = localDay(now);
84
+ let n = 0;
85
+ for (const l of t.split('\n')) {
86
+ if (!l.trim()) continue;
87
+ let o; try { o = JSON.parse(l); } catch { continue; }
88
+ if (o && o.event === 'claimed' && o.claim && isBuilder(o.claim.agent) && localDay(Date.parse(o.at)) === day) n++;
89
+ }
90
+ return n;
91
+ }
92
+
93
+ function claimRoom(root, items, { now = Date.now() } = {}) {
94
+ const b = buildersOf(root);
95
+ const live = (items || []).filter((x) => x.state === 'claimed' && x.claim && isBuilder(x.claim.agent)).map((x) => x.item_id);
96
+ if (live.length >= b.max_parallel) {
97
+ return { ok: false, error: `${live.length === 1 ? 'a Builder holds' : live.length + ' Builders hold'} ${live.slice(0, 5).join(', ')} already, and pmos/factory.json allows ${b.max_parallel} at a time (builders.max_parallel). Finish one first, or raise the limit` };
98
+ }
99
+ // per_day counts claims only once the PM sets builders: with no setting, the old behaviour (no day cap on claims) stays
100
+ const today = b.set ? claimsToday(root, now) : 0;
101
+ if (b.set && today >= b.per_day) return { ok: false, error: `the Builder made ${today} claims today, and pmos/factory.json allows ${b.per_day} a day (builders.per_day). It waits for tomorrow, or raise the limit` };
102
+ return { ok: true, live: live.length, today, ...b };
103
+ }
104
+
105
+ // ── the integrator ───────────────────────────────────────────────────────────────────────────────────────────────────────────
106
+
107
+ function stateDir(top) { return require('./driver.js').stateDirOf(top, { create: true }); }
108
+ function lines(top) {
109
+ const d = stateDir(top);
110
+ if (!d) return [];
111
+ let t = '';
112
+ try { t = fs.readFileSync(path.join(d, LEDGER), 'utf8'); } catch { return []; }
113
+ return t.split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
114
+ }
115
+ function log(top, line, now) {
116
+ const d = stateDir(top);
117
+ const full = { at: new Date(now == null ? Date.now() : now).toISOString(), ...line };
118
+ if (d) fs.appendFileSync(path.join(d, LEDGER), JSON.stringify(full) + '\n');
119
+ return full;
120
+ }
121
+ const lastOf = (top, item) => { let l = null; for (const x of lines(top)) if (x.item === item) l = x; return l; };
122
+ const roundsOf = (top, item) => lines(top).filter((x) => x.item === item && x.step === 'fix').length;
123
+
124
+ function topOf(root) { const r = BE().git(root, ['rev-parse', '--show-toplevel']); return r.ok ? r.out : null; }
125
+ function inFixRound(root, item) { const top = topOf(root) || root; const l = lastOf(top, item); return !!(l && l.step === 'fix'); }
126
+
127
+ /** The one push the integrator makes: refs/heads/pmos/<item>, forced with a lease on `expect`, never the default branch. */
128
+ function leasePush(top, branch, expect, d) {
129
+ if (!ITEM_BRANCH.test(branch) || branch === d.name || /^pmos\/revert-/.test(branch)) return { ok: false, err: `PMOS never force-pushes ${branch}` };
130
+ return BE().git(top, ['push', `--force-with-lease=refs/heads/${branch}:${expect}`, 'origin', `refs/heads/${branch}:refs/heads/${branch}`]);
131
+ }
132
+
133
+ function gh(top, args, env) {
134
+ const r = require('child_process').spawnSync('gh', args, { cwd: top, encoding: 'utf8', env });
135
+ return { ok: !r.error && r.status === 0, out: String(r.stdout || '').trim(), err: one(r.stderr || (r.error && r.error.message), 200) };
136
+ }
137
+
138
+ /** The pull request of one branch, as gh reports it. → { number, isDraft, body } | null */
139
+ function prOf(top, branch, ghEnv) {
140
+ const r = gh(top, ['pr', 'view', branch, '--json', 'number,isDraft,body,state'], ghEnv);
141
+ if (!r.ok) return null;
142
+ try { const p = JSON.parse(r.out); return p && String(p.state || 'OPEN').toUpperCase() === 'OPEN' ? p : null; } catch { return null; }
143
+ }
144
+
145
+ /** Make the pull request a draft before a forced push. → true when it is a draft now. */
146
+ function toDraft(top, pr, ghEnv) {
147
+ if (pr.isDraft) return true;
148
+ return gh(top, ['pr', 'ready', String(pr.number), '--undo'], ghEnv).ok;
149
+ }
150
+
151
+ /** The item's worktree on its branch, clean. Made from the branch when missing. → { ok, wt } | { ok: false, why } */
152
+ function worktreeFor(root, top, item, branch) {
153
+ const E = BE();
154
+ const wt = E.worktreeOf(root, item);
155
+ if (!fs.existsSync(wt)) {
156
+ fs.mkdirSync(path.dirname(wt), { recursive: true });
157
+ const w = E.git(top, ['worktree', 'add', wt, branch]);
158
+ if (!w.ok) return { ok: false, why: `the worktree could not be made: ${one(w.err, 200)}` };
159
+ }
160
+ if (E.git(wt, ['rev-parse', '--abbrev-ref', 'HEAD']).out !== branch) return { ok: false, why: `${wt} is not on ${branch}` };
161
+ if (E.git(wt, ['status', '--porcelain']).out) return { ok: false, why: `${wt} has changes that are not committed` };
162
+ return { ok: true, wt };
163
+ }
164
+
165
+ const RAN = new Map(); // top → when the tick last ran integrate (`every`), so the verify tick asks gh at most once per interval
166
+ function integrate(root, { env = process.env, now = Date.now(), every = 0 } = {}) {
167
+ if (env.PMOS_TEAM_RUN) return { ok: false, error: 'a role run cannot integrate. PMOS integrates in its own process' };
168
+ const k = require('./autonomy.js').killed({ env });
169
+ if (k) return { ok: true, acted: [], why: k };
170
+ const E = BE();
171
+ if (!WK.factoryRuns(root)) return { ok: true, acted: [], why: 'no factory runs in this repository' };
172
+ const top = topOf(root) || root;
173
+ if (every > 0 && RAN.has(top) && now - RAN.get(top) < every) return { ok: true, acted: [], why: 'PMOS checked a short time ago' };
174
+ RAN.set(top, now);
175
+ const d = E.defaultBranch(root);
176
+ if (!d) return { ok: false, error: 'this repository has no default branch' };
177
+ const ghEnv = E.ghEnvOf(top, env);
178
+ const l = gh(top, ['pr', 'list', '--state', 'open', '--limit', '100', '--json', 'number,headRefName,isDraft,body'], ghEnv);
179
+ if (!l.ok) return { ok: false, error: `gh could not list the open pull requests: ${l.err}` };
180
+ let prs = [];
181
+ try { prs = JSON.parse(l.out || '[]'); } catch { prs = []; }
182
+ const items = E.itemsOf(root);
183
+ const acted = [];
184
+ const say = (x) => { acted.push(log(top, x, now)); };
185
+ const id = require('./git-identity.js').localIdentity(top);
186
+ for (const pr of Array.isArray(prs) ? prs : []) {
187
+ const m = ITEM_BRANCH.exec(String((pr && pr.headRefName) || ''));
188
+ if (!m || !/^[0-9]+$/.test(String(pr.number))) continue;
189
+ const item = m[1], branch = 'pmos/' + item;
190
+ const it = items.find((x) => x.item_id === item);
191
+ if (!it || it.state !== 'verified') continue; // claimed: a Builder works on it; anything else is not waiting for a merge
192
+ const old = E.git(top, ['rev-parse', '--verify', '--quiet', 'refs/heads/' + branch]).out;
193
+ if (!old) continue;
194
+ const last = lastOf(top, item);
195
+ if (last && last.step === 'blocked' && last.head === old) continue; // said once; a new push on the branch reopens it
196
+ const base = E.git(top, ['merge-base', d.ref, 'refs/heads/' + branch]).out;
197
+ const tip = E.git(top, ['rev-parse', d.ref]).out;
198
+ if (!base || base === tip) continue; // up to date with the default branch
199
+ const mine = E.git(top, ['diff', '--name-only', base, 'refs/heads/' + branch]).out.split('\n').filter(Boolean);
200
+ const theirs = new Set(E.git(top, ['diff', '--name-only', base, d.ref]).out.split('\n').filter(Boolean));
201
+ const overlap = mine.filter((f) => theirs.has(f));
202
+ if (!overlap.length) continue;
203
+ if (!id.name || !id.email) { say({ item, step: 'skip', why: 'this repository has no git identity of its own, and PMOS never guesses who commits' }); continue; }
204
+ const w = worktreeFor(root, top, item, branch);
205
+ if (!w.ok) { say({ item, step: 'skip', why: w.why }); continue; }
206
+ const as = ['-c', `user.name=${id.name}`, '-c', `user.email=${id.email}`];
207
+ const rb = E.git(w.wt, [...as, 'rebase', '-q', d.ref]);
208
+ if (rb.ok) {
209
+ const p = { number: pr.number, isDraft: !!pr.isDraft };
210
+ if (!toDraft(top, p, ghEnv)) { E.git(w.wt, ['reset', '-q', '--hard', old]); say({ item, step: 'skip', why: `pull request #${pr.number} could not be turned back to a draft, so PMOS does not force-push it` }); continue; }
211
+ const push = leasePush(top, branch, old, d);
212
+ if (!push.ok) { E.git(w.wt, ['reset', '-q', '--hard', old]); say({ item, step: 'skip', why: `the push of ${branch} failed: ${one(push.err, 200)}` }); continue; }
213
+ say({ item, step: 'rebased', files: overlap, head: E.git(top, ['rev-parse', 'refs/heads/' + branch]).out,
214
+ why: `${d.name} changed ${overlap.slice(0, 5).join(', ')} after ${branch} started. PMOS rebased ${branch} onto ${d.name} and pushed it; its checks run again` });
215
+ continue;
216
+ }
217
+ const conflicts = E.git(w.wt, ['diff', '--name-only', '--diff-filter=U']).out.split('\n').filter(Boolean);
218
+ E.git(w.wt, ['rebase', '--abort']);
219
+ const files = conflicts.length ? conflicts : overlap;
220
+ const p = prOf(top, branch, ghEnv) || { number: pr.number, isDraft: !!pr.isDraft, body: pr.body || '' };
221
+ toDraft(top, p, ghEnv);
222
+ if (roundsOf(top, item) < MAX_FIX_ROUNDS) {
223
+ const c = E.ledger(root, ['claim', item, '--agent', FIX_AGENT]);
224
+ if (c.status !== 0) { say({ item, step: 'skip', why: `the conflict could not go back to the Builder: ${one(c.out, 200)}` }); continue; }
225
+ // the branch's change on top of the default branch, with the conflicts in the files for the Builder to resolve
226
+ E.git(w.wt, ['reset', '-q', '--hard', d.ref]);
227
+ E.git(w.wt, [...as, 'merge', '-q', '--squash', old]);
228
+ gh(top, ['pr', 'comment', String(pr.number), '--body', `PMOS could not rebase ${branch} onto ${d.name}: ${files.join(', ')} conflict. The Builder resolves them in a fix round.`], ghEnv);
229
+ say({ item, step: 'fix', files, head: old, why: `${files.slice(0, 5).join(', ')} conflict with ${d.name}. ${item} goes back to the Builder as a fix round` });
230
+ continue;
231
+ }
232
+ if (!/^PMOS-Merge:\s*human\s*$/mi.test(String(p.body || ''))) {
233
+ gh(top, ['pr', 'edit', String(pr.number), '--body', `${String(p.body || '').replace(/\s+$/, '')}\n\nPMOS-Merge: human\n(PMOS could not rebase ${branch} onto ${d.name}: ${files.join(', ')} conflict)`], ghEnv);
234
+ }
235
+ say({ item, step: 'blocked', files, head: old, why: `${files.slice(0, 5).join(', ')} still conflict with ${d.name} after a fix round. A person resolves pull request #${pr.number}` });
236
+ }
237
+ return { ok: true, acted };
238
+ }
239
+
240
+ /** open() of an item in a fix round: push the Builder's resolved branch with the same draft-only, leased push. No new pull request. */
241
+ function finishFix(root, item, { env = process.env, now = Date.now() } = {}) {
242
+ if (env.PMOS_TEAM_RUN) return { ok: false, pushed: false, error: 'a role run cannot push' };
243
+ const E = BE();
244
+ const top = topOf(root) || root;
245
+ const d = E.defaultBranch(root);
246
+ if (!d) return { ok: false, pushed: false, error: 'this repository has no default branch' };
247
+ const branch = 'pmos/' + item;
248
+ const head = E.git(top, ['rev-parse', '--verify', '--quiet', 'refs/heads/' + branch]).out;
249
+ if (!head) return { ok: false, pushed: false, error: `there is no branch ${branch}` };
250
+ const fix = lastOf(top, item);
251
+ const remote = fix && fix.step === 'fix' ? fix.head : ''; // the sha PMOS pushed before the fix round: the lease
252
+ if (!remote) return { ok: false, pushed: false, error: `${item} is not in a fix round` };
253
+ const ghEnv = E.ghEnvOf(top, env);
254
+ const pr = prOf(top, branch, ghEnv);
255
+ if (!pr) return { ok: false, pushed: false, error: `${branch} has no open pull request` };
256
+ if (!toDraft(top, pr, ghEnv)) return { ok: false, pushed: false, error: `pull request #${pr.number} could not be turned back to a draft, so PMOS does not force-push it` };
257
+ const p = leasePush(top, branch, remote, d);
258
+ if (!p.ok) return { ok: false, pushed: false, error: `the push of ${branch} failed: ${one(p.err, 200)}` };
259
+ log(top, { item, step: 'rebased', head, why: `the Builder resolved the conflicts; PMOS pushed ${branch} and its checks run again` }, now);
260
+ return { ok: true, pushed: true, branch, base: d.name, url: '', fixed: true };
261
+ }
262
+
263
+ module.exports = { DEFAULTS, RANGE, BUILDER, FIX_AGENT, MAX_FIX_ROUNDS, LEDGER, buildersOf, roleBudget, waitingOn, claimRoom, claimsToday, integrate, inFixRound, finishFix };
@@ -0,0 +1,182 @@
1
+ 'use strict';
2
+ /* factory-identity.js — the factory's own git identity and token, and the Builder's sandboxed check (ADLC gap P1, initiative
3
+ * factory-bot-identity-sandbox, done test I1–I7). No model, no network of its own.
4
+ *
5
+ * identityOf(root, { env }) → { set, name?, email?, tokenEnv?, token?, why } the bot that authors factory commits and opens its PRs
6
+ * commitArgs(root, pm, { env }) → { args: ['-c', …], trailer } git -c flags and the Co-authored-by line for one commit
7
+ * ghTokenOf(root, { env }) → string | null the factory token for gh, read from the environment
8
+ * sandboxOf(root, { env }) → { mode: 'docker'|'podman'|'worktree', bin?, image?, why }
9
+ * checkOf(root, item) → { command, install } | null what `pmos build check` runs
10
+ * runCheck(root, item, { env, wt, base }) → { ok, mode, exit, install, out, why } | { ok: false, error }
11
+ * lastChecks(root) → Map<item, line> the newest check line per item (`pmos build status`)
12
+ *
13
+ * THE IDENTITY is opt-in, in `<kit>/factory.json` (pmos/factory.json in a product repository), next to the rollout's flags:
14
+ * { "identity": { "name": "acme-pmos[bot]", "email": "123+acme-pmos[bot]@users.noreply.github.com", "token_env": "PMOS_FACTORY_GH_TOKEN" } }
15
+ * The file names the environment VARIABLE, never the token. A token-like value or a `token`/`secret`/`password` key in the file
16
+ * refuses the whole identity: a token never goes in a tracked file. With an identity, a factory commit has the bot as author and
17
+ * committer and `Co-authored-by:` the repository's own git identity (the PM). token_env must start with PMOS_FACTORY_: lib/headless.js
18
+ * drops every PMOS_FACTORY_* variable from an agent run's environment, so the Builder's run never holds it. With a token variable set, PMOS's own gh calls
19
+ * (open, close, revert, holdOpen in lib/build-engine.js) get it as GH_TOKEN in the child's environment only; process.env is not changed.
20
+ * With no identity the factory behaves as before: the repository's identity and the PM's gh login.
21
+ *
22
+ * THE SANDBOX is opt-in by `PMOS_BUILD_SANDBOX=docker` (or podman) on the machine, plus `check.image` in factory.json:
23
+ * { "check": { "command": "npm test", "image": "node:20", "install": "npm ci --ignore-scripts" } }
24
+ * `pmos build check <item>` runs check.command (else the item's criterion when it is an `assertion`, which names a command) in the
25
+ * item's worktree. Sandbox mode: `<bin> run --rm --network none --cap-drop ALL` with the worktree mounted at /work. A declared install
26
+ * step runs first in the same image WITH the network, and only when the item's diff touches no dependency manifest, lock file or
27
+ * registry config (the guardrail's own lists): the Builder cannot choose what the networked step fetches. Worktree mode: the commands
28
+ * run in the worktree with this machine's network, so a role run (PMOS_TEAM_RUN) is refused there and only the PM runs it. Each run
29
+ * is one line in <state>/build-checks.jsonl.
30
+ */
31
+ const fs = require('fs');
32
+ const path = require('path');
33
+ const cp = require('child_process');
34
+ const WK = require('./work-kind.js');
35
+
36
+ const LEDGER = 'build-checks.jsonl';
37
+ const TOKENISH = /^(gh[pousr]_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{20,}|[0-9a-f]{40})$/;
38
+ const SECRET_KEY = /^(token|secret|password|pat|key|private_key|app_key)$/i;
39
+ const ENV_NAME = /^PMOS_FACTORY_[A-Z0-9_]{1,50}$/; // lib/headless.js headlessEnv drops PMOS_FACTORY_* from every agent run
40
+ const EMAIL = /^[^\s<>@]+@[^\s<>@]+$/;
41
+ const BINS = Object.freeze(['docker', 'podman']);
42
+ const REGISTRY_CONFIG = Object.freeze(['package.json', '.npmrc', '.yarnrc', '.yarnrc.yml', 'pip.conf', '.pypirc', 'bunfig.toml']);
43
+ const NO_ID = 'No factory identity is set in pmos/factory.json, so factory commits use this repository\'s git identity and pull requests use your gh login.';
44
+ const one = (s, n) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim().slice(0, n);
45
+
46
+ function readJson(root) {
47
+ const dir = WK.factoryDir(root);
48
+ if (!dir) return null;
49
+ try { return JSON.parse(fs.readFileSync(path.join(dir, 'factory.json'), 'utf8')); } catch { return null; }
50
+ }
51
+
52
+ /** Any value in the file that looks like a token, or any secret-named key: the file is tracked, so it must hold none. */
53
+ function secretIn(v, at = '') {
54
+ if (typeof v === 'string') return TOKENISH.test(v.trim()) ? at || 'a value' : null;
55
+ if (!v || typeof v !== 'object') return null;
56
+ for (const [k, x] of Object.entries(v)) {
57
+ const here = at ? `${at}.${k}` : k;
58
+ if (SECRET_KEY.test(k) && x !== '' && x != null) return here;
59
+ const s = secretIn(x, here);
60
+ if (s) return s;
61
+ }
62
+ return null;
63
+ }
64
+
65
+ function identityOf(root, { env = process.env } = {}) {
66
+ const j = readJson(root);
67
+ const leak = j && secretIn(j);
68
+ if (leak) return { set: false, refused: true, why: `pmos/factory.json holds a token or secret at "${leak}". A token never goes in a tracked file: remove it, rotate it, and name an environment variable in identity.token_env. Until then the factory uses this repository's git identity and your gh login.` };
69
+ const id = j && j.identity;
70
+ if (!id || typeof id !== 'object') return { set: false, why: NO_ID };
71
+ const name = one(id.name, 100), email = one(id.email, 200);
72
+ if (!name || /[<>]/.test(name) || !EMAIL.test(email)) return { set: false, refused: true, why: 'pmos/factory.json names a factory identity without a valid name and email, so the factory uses this repository\'s git identity.' };
73
+ const tokenEnv = id.token_env == null || id.token_env === '' ? null : String(id.token_env);
74
+ if (tokenEnv && !ENV_NAME.test(tokenEnv)) return { set: false, refused: true, why: `identity.token_env in pmos/factory.json must be an environment variable whose name starts with PMOS_FACTORY_ (for example PMOS_FACTORY_GH_TOKEN), so that no agent run receives it, not "${one(tokenEnv, 20)}".` };
75
+ const token = tokenEnv && typeof env[tokenEnv] === 'string' && env[tokenEnv].trim() ? env[tokenEnv].trim() : null;
76
+ const tok = !tokenEnv ? 'No token variable is named, so pull requests use your gh login.'
77
+ : token ? `Pull requests use the token in ${tokenEnv}.` : `${tokenEnv} is not set here, so pull requests use your gh login.`;
78
+ return { set: true, name, email, tokenEnv, token, why: `Factory commits are authored by ${name} <${email}>, with you as co-author. ${tok}` };
79
+ }
80
+
81
+ /** The -c flags and trailer for one factory commit. pm = the repository's own identity (git-identity.localIdentity). */
82
+ function commitArgs(root, pm, { env = process.env } = {}) {
83
+ const id = identityOf(root, { env });
84
+ if (!id.set) return { args: ['-c', `user.name=${pm.name}`, '-c', `user.email=${pm.email}`], trailer: '' };
85
+ const same = String(pm.email).toLowerCase() === id.email.toLowerCase();
86
+ return { args: ['-c', `user.name=${id.name}`, '-c', `user.email=${id.email}`], trailer: same ? '' : `Co-authored-by: ${pm.name} <${pm.email}>` };
87
+ }
88
+
89
+ const ghTokenOf = (root, { env = process.env } = {}) => identityOf(root, { env }).token || null;
90
+
91
+ function hasBin(bin, env) {
92
+ const r = cp.spawnSync(bin, ['--version'], { encoding: 'utf8', env, timeout: 15000 });
93
+ return !r.error && r.status === 0;
94
+ }
95
+
96
+ function checkOf(root, item) {
97
+ const j = readJson(root) || {};
98
+ const c = j.check && typeof j.check === 'object' ? j.check : {};
99
+ let command = typeof c.command === 'string' && c.command.trim() ? c.command.trim() : null;
100
+ if (!command && item && item.criterion && item.criterion.check === 'assertion' && typeof item.criterion.ref === 'string' && item.criterion.ref.trim()) command = item.criterion.ref.trim();
101
+ if (!command) return null;
102
+ return { command, install: typeof c.install === 'string' && c.install.trim() ? c.install.trim() : null };
103
+ }
104
+
105
+ function sandboxOf(root, { env = process.env } = {}) {
106
+ const want = String(env.PMOS_BUILD_SANDBOX || '').trim().toLowerCase();
107
+ if (!want || want === 'off' || want === 'none') return { mode: 'worktree', why: 'No sandbox is set (PMOS_BUILD_SANDBOX), so the check runs in the worktree with this machine\'s network.' };
108
+ if (!BINS.includes(want)) return { mode: 'worktree', why: `PMOS_BUILD_SANDBOX=${one(want, 20)} is not docker or podman, so the check runs in the worktree.` };
109
+ if (!hasBin(want, env)) return { mode: 'worktree', why: `PMOS_BUILD_SANDBOX=${want}, but ${want} is not installed here, so the check runs in the worktree.` };
110
+ const j = readJson(root) || {};
111
+ const image = (j.check && typeof j.check.image === 'string' && j.check.image.trim()) || null;
112
+ if (!image) return { mode: 'worktree', why: `PMOS_BUILD_SANDBOX=${want}, but pmos/factory.json names no check.image, so the check runs in the worktree.` };
113
+ return { mode: want, bin: want, image, why: `The check runs in a ${want} container (${image}) with no network.` };
114
+ }
115
+
116
+ /** The files the item's worktree changes against the default branch, committed or not. */
117
+ function changedFiles(wt, base) {
118
+ const g = (args) => cp.spawnSync('git', args, { cwd: wt, encoding: 'utf8' });
119
+ const a = g(['diff', '--name-only', base]), b = g(['ls-files', '--others', '--exclude-standard']);
120
+ if (a.status !== 0 || b.status !== 0) return null;
121
+ return [...String(a.stdout).split('\n'), ...String(b.stdout).split('\n')].filter(Boolean);
122
+ }
123
+ function touchesDeps(root, files) {
124
+ let M = [], L = [];
125
+ try { const G = require(path.join(WK.factoryDir(root), 'scripts', 'factory-guardrail.js')); M = G.MANIFESTS || []; L = G.LOCKS || []; } catch { /* lists below */ }
126
+ if (!M.length || !L.length) return true; // cannot tell: treat as touched, so the networked step does not run
127
+ return files.some((f) => { const b = path.posix.basename(String(f).toLowerCase()); return M.includes(b) || L.includes(b) || REGISTRY_CONFIG.includes(b); });
128
+ }
129
+
130
+ function stateDir(root) {
131
+ const top = cp.spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd: root, encoding: 'utf8' });
132
+ return require('./driver.js').stateDirOf(top.status === 0 ? String(top.stdout).trim() : root, { create: true });
133
+ }
134
+ function record(root, line) {
135
+ const d = stateDir(root);
136
+ if (!d) return;
137
+ try { fs.appendFileSync(path.join(d, LEDGER), JSON.stringify({ at: new Date().toISOString(), ...line }) + '\n'); } catch { /* the result still returns */ }
138
+ }
139
+ function lastChecks(root) {
140
+ const m = new Map();
141
+ const d = stateDir(root);
142
+ let t = '';
143
+ try { t = d ? fs.readFileSync(path.join(d, LEDGER), 'utf8') : ''; } catch { return m; }
144
+ for (const l of t.split('\n')) { try { const x = JSON.parse(l); if (x && x.item) m.set(x.item, x); } catch { /* torn line */ } }
145
+ return m;
146
+ }
147
+
148
+ /** Run the item's check. wt = the item's worktree, base = the default branch's ref (lib/build-engine.js passes both). */
149
+ function runCheck(root, item, { env = process.env, wt, base, timeoutMs = 15 * 60 * 1000 } = {}) {
150
+ const id = item && item.item_id;
151
+ const c = checkOf(root, item);
152
+ if (!c) return { ok: false, error: `no check command is declared: set check.command in pmos/factory.json, or declare ${id} with --check assertion --ref "<command>"` };
153
+ if (!wt || !fs.existsSync(wt)) return { ok: false, error: `${id} has no worktree; claim it first` };
154
+ const sb = sandboxOf(root, { env });
155
+ if (sb.mode === 'worktree' && env.PMOS_TEAM_RUN) {
156
+ return { ok: false, error: `a role run runs its check only in a sandbox with no network. ${sb.why} Set PMOS_BUILD_SANDBOX=docker (or podman) and check.image, or the PM runs pmos build check ${id}` };
157
+ }
158
+ let install = 'none', out = '';
159
+ const run = (args, bin, opts = {}) => {
160
+ const r = cp.spawnSync(bin, args, { cwd: wt, encoding: 'utf8', env: opts.env || env, timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024 });
161
+ out += String(r.stdout || '') + String(r.stderr || '') + (r.error ? String(r.error.message) : '');
162
+ return r.error ? 1 : r.status == null ? 1 : r.status;
163
+ };
164
+ const inBox = (cmd, network) => [ 'run', '--rm', ...(network ? [] : ['--network', 'none']), '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges',
165
+ '-v', `${wt}:/work`, '-w', '/work', sb.image, 'sh', '-c', cmd ];
166
+ // the worktree check never gets PMOS's tokens: gh/GitHub variables are dropped from its environment
167
+ const clean = Object.fromEntries(Object.entries(env).filter(([k]) => !/^(GH_|GITHUB_)/.test(k) && !/TOKEN|SECRET|PASSWORD/i.test(k)));
168
+ if (c.install) {
169
+ if (sb.mode !== 'worktree') {
170
+ const files = base ? changedFiles(wt, base) : null;
171
+ if (!files || touchesDeps(root, files)) install = 'skipped';
172
+ else install = run(inBox(c.install, true), sb.bin) === 0 ? 'ran' : 'failed';
173
+ } else install = run(['-c', c.install], 'sh', { env: clean }) === 0 ? 'ran' : 'failed';
174
+ }
175
+ const exit = install === 'failed' ? 1 : sb.mode !== 'worktree' ? run(inBox(c.command, false), sb.bin) : run(['-c', c.command], 'sh', { env: clean });
176
+ const why = install === 'skipped' ? `${sb.why} The install step did not run: the diff changes a dependency or registry file, or PMOS could not read the diff.` : sb.why;
177
+ const line = { item: id, mode: sb.mode, ok: exit === 0, exit, install, command: one(c.command, 200) };
178
+ record(root, line);
179
+ return { ...line, out: out.slice(-4000), why };
180
+ }
181
+
182
+ module.exports = { LEDGER, NO_ID, identityOf, commitArgs, ghTokenOf, sandboxOf, checkOf, runCheck, lastChecks, secretIn };