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
@@ -7,11 +7,23 @@
7
7
  * pmos build propose <item> "<what it does>" --evidence "<the check that passed>" [--json]
8
8
  * commit, mark verified, and file "Open a draft pull request" under the ✦
9
9
  * (PMOS opens it by itself, D108 point 6; with agents off it waits for the ✓)
10
+ * pmos build check <item> [--json] run the checks pmos/factory.json declares, in the item's worktree, with no network
11
+ * pmos build fix <item> [--json] a CI-fix round: claim a verified item again on its own branch (lib/factory-ci.js)
10
12
  * pmos build open <item> [--json] never a role run: push the branch and open the DRAFT pull request
11
13
  * pmos build status [--json] every work item, its branch and whether its worktree is here
14
+ * pmos build check <item> [--json] with no checks map: the item's one check; in a container with no
15
+ * network when PMOS_BUILD_SANDBOX is set (lib/factory-identity.js). A role
16
+ * run is refused outside the sandbox.
12
17
  * pmos build policy <item> [--json] what the merge guardrail reads for it now: auto or human, and why (D108)
13
18
  * pmos build rollout [<item> [--to <percent>]] [--json] no item: where every flag stands; an item: the PM's own next step
14
19
  * pmos build rollback <item> [--json] undo a rollout: the item's flag to 0
20
+ * pmos build review <item> [--json] the independent review of its pull request: the verdict, and post it as pmos-review
21
+ * pmos build reviewed <item> --sha <commit> --verdict PASS|FAIL --why "<one line>"
22
+ * the review run's one write (lib/factory-review.js); never a role run
23
+ * pmos build metrics [--days <n>] [--json] the factory's numbers over the last n days (default 30; lib/factory-traces.js)
24
+ * pmos build bench [--model <id>] [--only <n,…>] [--keep] [--json] the golden benchmark: the Builder on 10 items in a sandbox, one row
25
+ * to planning/runs/builder-bench.jsonl (lib/builder-bench.js)
26
+ * pmos build bench --report [--json] pass rate, cost and duration per model and harness version
15
27
  * common: [--root <dir>]
16
28
  *
17
29
  * `open` is what the ✦ runs by itself (class B since D108 as amended 2026-11-16; Undo closes the pull request), or the ✓ when agents
@@ -23,19 +35,26 @@ const path = require('path');
23
35
  const { execFileSync } = require('child_process');
24
36
  const BE = require('./build-engine.js');
25
37
 
26
- const COMMANDS = { build: ['next', 'claim', 'propose', 'open', 'status', 'policy', 'rollout', 'rollback'] };
38
+ const COMMANDS = { build: ['next', 'claim', 'propose', 'open', 'status', 'policy', 'rollout', 'rollback', 'check', 'fix', 'review', 'reviewed', 'metrics', 'bench', 'integrate'] };
27
39
  const USAGE = [
28
- 'usage: pmos build next|claim|propose|open|status|policy|rollout|rollback — the Builder: PMOS builds a declared work item as a pull request',
40
+ 'usage: pmos build next|claim|propose|check|fix|open|status|policy|rollout|rollback|review|metrics|bench|integrate — the Builder: PMOS builds a declared work item as a pull request',
29
41
  ' pmos build next [<initiative>] the declared work items no Builder has taken',
30
42
  ' pmos build claim <item> claim one; PMOS makes the branch pmos/<item> in a worktree outside this folder',
31
43
  ' pmos build propose <item> "<what it does>" --evidence "<the check that passed>"',
32
44
  ' commit it; PMOS then opens the draft pull request by itself (Undo closes it)',
33
45
  ' pmos build open <item> open it now yourself: push pmos/<item> and open the draft pull request',
34
46
  ' (with pmos ai off, the pull request waits for this or your ✓)',
35
- ' pmos build status every work item and its branch',
47
+ ' pmos build check <item> run the product\'s declared checks with no network; with none declared, the item\'s check (in a container when PMOS_BUILD_SANDBOX is set)',
48
+ ' pmos build fix <item> start a fix round on a verified item whose pull request failed CI',
49
+ ' pmos build status every work item, its branch and how its last check ran',
36
50
  ' pmos build policy <item> auto or human: whether its pull request merges by itself, and why',
37
51
  ' pmos build rollout [<item> [--to <percent>]] where every flag stands; with an item, take its flag to the next step',
52
+ ' pmos build integrate rebase each open factory pull request that a merged change overlaps',
38
53
  ' pmos build rollback <item> turn the item\'s flag off and stop its rollout',
54
+ ' pmos build review <item> the independent review of its pull request; posts pmos-review when it has a verdict',
55
+ ' pmos build metrics [--days <n>] the factory\'s numbers: claims, merges, cost, corrections (default 30 days)',
56
+ ' pmos build bench [--model <id>] [--only <n,…>] run the Builder on the golden set and record its pass rate, cost and time',
57
+ ' pmos build bench --report the recorded pass rates, per model and harness version',
39
58
  'every command: [--json] [--root <dir>]. PMOS never merges: the product\'s pmos-guardrail check turns on auto-merge, or you merge.',
40
59
  ];
41
60
 
@@ -67,6 +86,7 @@ async function run(argv, { say = (s) => console.log(s), env = process.env, cwd =
67
86
  const root = flags.root ? path.resolve(cwd, flags.root) : env.PMOS_TEAM_ROOT || repoRoot(cwd);
68
87
  const fail = (error, code = 1) => { say(json ? JSON.stringify({ ok: false, error }) : `✗ ${error}`); return code; };
69
88
  const ok = (obj, text) => { say(json ? JSON.stringify({ ok: true, ...obj }) : text); return 0; };
89
+ if (verb === 'bench') return bench(root, flags, { say, env, json, fail, ok });
70
90
  if (!require('./work-kind.js').factoryRuns(root)) return fail('no factory runs in this repository (no work-item ledger and verify-work script), so PMOS does not build here. The team\'s agents build from the done test and the pull request plan');
71
91
 
72
92
  if (verb === 'next' || verb === 'status') {
@@ -76,10 +96,14 @@ async function run(argv, { say = (s) => console.log(s), env = process.env, cwd =
76
96
  if (verb !== 'next') { say('No work items.'); return 0; }
77
97
  const taken = BE.itemsOf(root).filter((x) => x.state === 'claimed' && (!pos[0] || x.initiative_id === pos[0]));
78
98
  say('No declared work item waits for a Builder.');
99
+ const all = BE.itemsOf(root), FL = require('./factory-fleet.js');
100
+ const held = all.filter((x) => x.state === 'declared' && (!pos[0] || x.initiative_id === pos[0]) && FL.waitingOn(x, all).length);
101
+ if (held.length) say(`${held.length === 1 ? '1 item waits' : held.length + ' items wait'} for a dependency: ${held.slice(0, 5).map((x) => `${x.item_id} for ${FL.waitingOn(x, all).join(', ')}`).join('; ')}.`);
79
102
  if (taken.length) say(`${taken.length === 1 ? '1 item is' : taken.length + ' items are'} claimed already: ${taken.slice(0, 5).map((x) => `${x.item_id} by ${(x.claim && x.claim.agent) || 'someone'}`).join(', ')}. To leave an item for the Builder, declare it with --no-claim.`);
80
103
  return 0;
81
104
  }
82
- for (const x of list) say(verb === 'next' ? `${x.item_id} ${x.type || ''} ${(x.criterion && x.criterion.text) || ''}` : `${x.item} ${x.state} ${x.branch}${x.here ? ' (worktree here)' : ''}`);
105
+ const ran = (c) => (c ? ` check ${c.ok ? 'passed' : 'failed'} (${c.mode === 'worktree' ? 'worktree' : c.mode + ' sandbox, no network'})` : '');
106
+ for (const x of list) say(verb === 'next' ? `${x.item_id} ${x.type || ''} ${(x.criterion && x.criterion.text) || ''}` : `${x.item} ${x.state} ${x.branch}${x.here ? ' (worktree here)' : ''}${ran(x.check)}`);
83
107
  return 0;
84
108
  }
85
109
  if (verb === 'rollout' && !pos[0]) {
@@ -89,13 +113,32 @@ async function run(argv, { say = (s) => console.log(s), env = process.env, cwd =
89
113
  for (const x of list) say(`${x.item} ${x.flag} ${x.percent}% ${x.step} ${x.why || ''}`);
90
114
  return 0;
91
115
  }
116
+ if (verb === 'metrics') {
117
+ const days = flags.days !== undefined && flags.days !== '' ? Number(flags.days) : 30;
118
+ if (!Number.isInteger(days) || days < 1 || days > 365) return fail('--days is a whole number from 1 to 365', 2);
119
+ const FT = require('./factory-traces.js');
120
+ const m = FT.metricsOf(root, { days }) || { days, runs: 0, empty: true };
121
+ if (json) return ok({ metrics: m });
122
+ for (const l of FT.linesOf(m)) say(l);
123
+ return 0; // zero is silence: no factory runs in the window, no lines
124
+ }
125
+ if (verb === 'integrate') {
126
+ const r = require('./factory-fleet.js').integrate(root, { env });
127
+ if (!r.ok) return fail(r.error);
128
+ if (json) return ok(r);
129
+ if (!r.acted.length) { say(r.why || 'No factory pull request needs a rebase.'); return 0; }
130
+ for (const x of r.acted) say(`${x.item} ${x.step} ${x.why}`);
131
+ return 0;
132
+ }
92
133
  const item = pos[0];
93
134
  if (!item) return fail(`usage: pmos build ${verb} <item>`, 2);
94
135
  if (verb === 'policy') {
95
136
  const it = BE.itemsOf(root).find((x) => x.item_id === item);
96
137
  if (!it) return fail(`${item} is not a work item here`);
97
138
  const p = BE.mergePolicy(root, it, { env });
98
- return ok({ item, ...p }, `${p.verdict === 'auto' ? 'AUTO' : 'HUMAN'} ${item}: ${p.why}`);
139
+ const id = require('./factory-identity.js').identityOf(root, { env });
140
+ // ADLC P1: one line on who the factory acts as; with no identity, today's behaviour, said once here
141
+ return ok({ item, ...p, identity: { set: id.set, why: id.why } }, `${p.verdict === 'auto' ? 'AUTO' : 'HUMAN'} ${item}: ${p.why}\n${id.why}`);
99
142
  }
100
143
  if (verb === 'rollout' || verb === 'rollback') {
101
144
  if (env.PMOS_TEAM_RUN) return fail('a role run cannot move a flag. The rollout runs by itself, and the PM moves it by hand');
@@ -104,6 +147,24 @@ async function run(argv, { say = (s) => console.log(s), env = process.env, cwd =
104
147
  if (!r.ok) return fail(r.error);
105
148
  return ok(r, `✓ ${r.flag} is at ${r.percent}%${verb === 'rollback' ? '. Its rollout stops until you run pmos build rollout ' + item : ''}`);
106
149
  }
150
+ if (verb === 'reviewed') {
151
+ // the review run's one write (headless kind review): PMOS_REVIEW_RUN pins the item and commit; a role run is refused
152
+ const r = require('./factory-review.js').record(root, { item, sha: flags.sha || '', verdict: flags.verdict || '', why: flags.why || '',
153
+ by: env.PMOS_REVIEW_RUN ? 'review' : 'pm' }, { env });
154
+ if (!r.ok) return fail(r.error);
155
+ return ok(r, `✓ recorded ${r.verdict} for ${item} at ${r.sha.slice(0, 8)}. PMOS posts it as the pmos-review check.${r.demoted ? ` The factory is back to propose-only until ${String(r.demoted.until).slice(0, 10)}.` : ''}`);
156
+ }
157
+ if (verb === 'review') {
158
+ if (env.PMOS_TEAM_RUN || env.PMOS_REVIEW_RUN) return fail('a role or review run cannot post a review. PMOS posts it from its own process');
159
+ const FRV = require('./factory-review.js');
160
+ const sha = FRV.headOf(root, item);
161
+ if (!sha) return fail(`${item} has no pushed branch ${BE.branchOf(item)}, so there is no pull request to review`);
162
+ const l = FRV.latest(root, item, sha);
163
+ if (!l || !l.verdict) return ok({ item, sha, verdict: null }, `${item} at ${sha.slice(0, 8)} has no review yet. The verifier job starts one by itself; until then the guardrail reads HUMAN.`);
164
+ const r = FRV.finish(root, item, sha, { env });
165
+ if (r.error) return fail(r.error);
166
+ return ok({ item, sha, ...r }, `${r.verdict} ${item} at ${sha.slice(0, 8)}: ${l.why}. pmos-review is ${r.state || 'not posted'}.`);
167
+ }
107
168
  if (verb === 'claim') {
108
169
  const agent = env.PMOS_TEAM_RUN ? `pmos:builder:${env.PMOS_TEAM_RUN}` : 'pmos:builder';
109
170
  const r = BE.claim(root, item, { agent });
@@ -113,10 +174,33 @@ async function run(argv, { say = (s) => console.log(s), env = process.env, cwd =
113
174
  if (verb === 'propose') {
114
175
  const summary = pos.slice(1).join(' ');
115
176
  if (!summary) return fail(`usage: pmos build propose ${item} "<what it does>" --evidence "<the check that passed>"`, 2);
116
- const r = BE.propose(root, item, { summary, evidence: flags.evidence || '', run: env.PMOS_TEAM_RUN || null });
177
+ const r = BE.propose(root, item, { summary, evidence: flags.evidence || '', run: env.PMOS_TEAM_RUN || null, env });
117
178
  if (!r.ok) return fail(r.error);
118
179
  return ok(r, `✓ committed ${r.commit.slice(0, 8)} (${r.files.length} ${r.files.length === 1 ? 'file' : 'files'}) and filed "Open a draft pull request" under the ✦. PMOS opens it by itself (with Undo); when agents are off it waits for the PM's ✓. Nothing is pushed by this run.`);
119
180
  }
181
+ if (verb === 'check') {
182
+ const FC = require('./factory-checks.js');
183
+ if (!FC.checksOf(root).checks.length) {
184
+ // no checks map: the item's single check (ADLC P1, lib/factory-identity.js), in a container with no network when PMOS_BUILD_SANDBOX is set
185
+ const r = BE.check(root, item, { env });
186
+ if (r.error) return fail(r.error);
187
+ const where = r.mode === 'worktree' ? 'in the worktree' : `in a ${r.mode} container with no network`;
188
+ if (!r.ok) { if (!json && r.out) say(r.out.trim().split('\n').slice(-20).join('\n')); return fail(`the check failed (exit ${r.exit}) ${where}: ${r.command}. ${r.why}`); }
189
+ return ok(r, `✓ the check passed ${where}: ${r.command}. ${r.why} Use it as evidence: pmos build propose ${item} "<what it does>" --evidence "${r.command} passed (${r.mode})"`);
190
+ }
191
+ const r = FC.runChecks(root, item, { env });
192
+ if (r.results.length) FC.record(root, item, r);
193
+ if (json) { say(JSON.stringify({ ok: r.ok, ...r })); return r.ok ? 0 : 1; }
194
+ if (r.error) return fail(r.error);
195
+ for (const x of r.results) { say(`${x.code === 0 ? '✓' : '✗'} ${x.name}: ${x.code == null ? 'timed out' : 'exit ' + x.code} (${Math.round(x.ms / 100) / 10} s)`); if (x.code !== 0) say(x.tail); }
196
+ return r.ok ? 0 : 1;
197
+ }
198
+ if (verb === 'fix') {
199
+ const agent = env.PMOS_TEAM_RUN ? `pmos:builder:${env.PMOS_TEAM_RUN}` : 'pmos:builder';
200
+ const r = BE.refix(root, item, { agent });
201
+ if (!r.ok) return fail(r.error);
202
+ return ok(r, `✓ fix round ${r.round} of ${BE.FIX_ROUNDS} for ${item} on ${r.branch}. Work only in ${r.worktree}. Run pmos build check ${item}, then pmos build propose ${item} "<what the fix does>"`);
203
+ }
120
204
  if (verb === 'open') {
121
205
  const r = BE.open(root, item, { env });
122
206
  if (!r.ok) return fail(r.error);
@@ -125,4 +209,32 @@ async function run(argv, { say = (s) => console.log(s), env = process.env, cwd =
125
209
  return fail('unknown command', 2);
126
210
  }
127
211
 
128
- module.exports = { run, COMMANDS, USAGE };
212
+ /** `pmos build bench`: the golden benchmark (lib/builder-bench.js). It needs no factory here: it builds its own sandbox product. */
213
+ async function bench(root, flags, { say, env, json, fail, ok, runner } = {}) {
214
+ const B = require('./builder-bench.js');
215
+ const pct = (x) => (x == null ? '—' : Math.round(x * 100) + '%');
216
+ const usd = (x) => (x == null ? 'cost unknown' : '$' + x.toFixed(2));
217
+ const secs = (ms) => (ms == null ? '—' : Math.round(ms / 1000) + ' s');
218
+ if (flags.report !== undefined) {
219
+ const { rows, torn } = B.readRows(B.benchFile(root));
220
+ const groups = B.rollup(rows);
221
+ if (json) return ok({ groups, torn });
222
+ if (!groups.length) { say('No benchmark run yet. Run pmos build bench.'); return 0; }
223
+ for (const g of groups) say(`${g.model} harness ${g.harness} set ${g.set} ${pct(g.pass_rate)} (${g.passed}/${g.items} in ${g.runs} ${g.runs === 1 ? 'run' : 'runs'}) ${g.cost_items ? usd(g.cost_per_item_usd) + ' per item' : 'cost unknown'} ${secs(g.duration_per_item_ms)} per item`);
224
+ if (torn) say(`${torn} ${torn === 1 ? 'line' : 'lines'} of the record could not be read.`);
225
+ return 0;
226
+ }
227
+ let only = null;
228
+ if (flags.only !== undefined) {
229
+ only = String(flags.only).split(',').map((x) => Number(x.trim())).filter((x) => Number.isInteger(x) && x > 0);
230
+ if (!only.length) return fail('usage: pmos build bench --only <n,…>, for example --only 1,4', 2);
231
+ }
232
+ if (!json) say('PMOS runs the Builder on each golden item in a sandbox. This takes a few minutes per item.');
233
+ const r = await B.run({ root, model: flags.model || null, only, env, keep: flags.keep !== undefined, ...(runner ? { runner } : {}) });
234
+ if (!r.ok) return fail(r.error);
235
+ const x = r.row;
236
+ if (!json) for (const it of x.items) say(`${it.pass ? '✓' : '✗'} ${it.item} ${it.why}${it.run_error ? ' (run: ' + it.run_error + ')' : ''}`);
237
+ return ok({ row: x, file: r.file, sandbox: r.sandbox }, `${x.model}: ${x.passed}/${x.n} passed (${pct(x.pass_rate)}), ${usd(x.cost_usd)}, ${secs(x.duration_ms)}. Harness ${x.harness}. Recorded in ${path.relative(root, r.file) || r.file}.`);
238
+ }
239
+
240
+ module.exports = { run, bench, COMMANDS, USAGE };
@@ -4,12 +4,15 @@
4
4
  * group `build`) runs open().
5
5
  *
6
6
  * itemsOf(root) → [item] the work items, folded by the repository's own scripts/work-item.js
7
- * next(root, ini?) → [item] declared and not claimed: what a Builder may take
7
+ * next(root, ini?) → [item] declared, not claimed, every depends_on integrated: what a Builder may take
8
8
  * claim(root, item, { agent }) → { ok, branch, worktree, base } | { ok: false, error }
9
9
  * propose(root, item, { summary, evidence, run? }) → { ok, commit, files, proposal } | { ok: false, error }
10
10
  * open(root, item, { env, title, revert }) → { ok, pushed, url, policy } | { ok: false, pushed, error }
11
11
  * revert(root, item, { env, why }) → { ok, branch, url } | { ok: false, error } the rollout's revert pull request (lib/factory-rollout.js)
12
- * status(root) → [{ item, state, branch, worktree, here }]
12
+ * status(root) → [{ item, state, branch, worktree, here, check }] check: the last `pmos build check` ({ mode, ok, at }) or null
13
+ * refix(root, item, { agent }) → { ok, branch, worktree, round } | { ok: false, error } a CI-fix round on a verified item's own branch
14
+ * roundsOf(item) → n · FIX_ROUNDS the fix rounds an item had (its claims after the first); at most FIX_ROUNDS (lib/factory-ci.js)
15
+ * check(root, item, { env }) → { ok, mode, exit, install, out, why } | { ok: false, error } the item's check (lib/factory-identity.js)
13
16
  * mergePolicy(root, item, { env }) → { merge, verdict, why, reasons, mark } when a PR merges with no person (see MERGE POLICY)
14
17
  * FORBIDDEN · forbiddenIn(files) · worktreeOf(root, item) · branchOf(item) · defaultBranch(root)
15
18
  *
@@ -20,7 +23,10 @@
20
23
  * dirtied, and the Builder's Write and Edit are scoped to that folder (lib/agent-team.js toolsOf).
21
24
  * 2. propose the Builder's last step. Refuses with no local git identity (`pmos git-identity`: PMOS never guesses who commits),
22
25
  * with nothing changed, without evidence that the item's check passed, and when the diff touches a control-graph record
23
- * (FORBIDDEN: the kit's pmos/ folder, .github/, the agent rules; D65: the factory may never write one). Then it commits
26
+ * (FORBIDDEN: the kit's pmos/ folder, .github/, the agent rules; D65: the factory may never write one). When the product
27
+ * declares checks in <kit>/factory.json (lib/factory-checks.js), propose RUNS them in the worktree with no network and
28
+ * refuses on a failing one; the evidence is then their exit codes, written by PMOS, not the Builder's sentence
29
+ * (factory-builder-inner-loop). With no checks declared, the Builder's --evidence stays the evidence. Then it commits
24
30
  * with the line `Work-Item: <id>`, appends `verified` with the evidence, and FILES a class C ✦ proposal "Open a draft
25
31
  * pull request". It pushes nothing.
26
32
  * 3. open never the Builder's run (refused when PMOS_TEAM_RUN is set). D108 as amended 2026-11-16: the proposal is class B, so the
@@ -38,6 +44,8 @@
38
44
  * mergePolicy() runs the SAME classifier here, as a preview for the PM and the ✦, and adds what only this machine knows: autonomy off
39
45
  * (`pmos ai off`, PMOS_AUTONOMY=off) or the factory demoted after a revert (D106 (5), job ai:factory). Then `mark` is true and open()
40
46
  * writes `PMOS-Merge: human` into the pull request body, which the guardrail reads as human.
47
+ * The preview does not judge the independent review (lib/factory-review.js): the product's guardrail reads AUTO only when the commit status
48
+ * `pmos-review` is success on the head it diffs (initiative factory-premerge-reviewer).
41
49
  */
42
50
  const fs = require('fs');
43
51
  const os = require('os');
@@ -73,14 +81,14 @@ function mergePolicy(root, it, { env = process.env } = {}) {
73
81
  try { v = require(gpath).classify({ cwd: top, base: d.ref, head: 'refs/heads/' + branchOf(it.item_id), branch: branchOf(it.item_id) }); }
74
82
  catch (e) { return human(`A person merges this pull request: the guardrail failed here (${one(e.message, 160)}).`); }
75
83
  if (v.verdict === 'auto') return { merge: true, verdict: 'auto', reasons: [], mark: false,
76
- why: 'The guardrail reads AUTO: once every required check is green, the product\'s pmos-guardrail check turns on auto-merge. The change reaches users only through its flag.' };
84
+ why: 'The guardrail reads AUTO: once the independent pmos-review check passes on this head and every required check is green, the product\'s pmos-guardrail check turns on auto-merge. The change reaches users only through its flag.' };
77
85
  return human(`A person merges this pull request (the guardrail reads HUMAN): ${v.reasons.map((r) => r.detail).join('; ')}.`, v.reasons);
78
86
  }
79
87
 
80
88
  /* What a factory commit may not touch (D65: the factory never writes a control-graph record). Lower case; a folder ends in "/".
81
89
  * Product code under scripts/ or workspace/ is fine here: this is a product repository, not PMOS-self. */
82
90
  const FORBIDDEN = Object.freeze(['pmos/', '.github/', 'planning/initiatives/', 'planning/runs/', 'decisions.md', 'pm-decisions.md', 'principles.md',
83
- 'claude.md', 'agents.md', '.pmos-profile', '.gitattributes']);
91
+ 'claude.md', 'agents.md', '.pmos-profile', '.gitattributes', 'factory.json']); // factory.json: the PM's identity, check and flag commands
84
92
  const forbiddenIn = (files) => files.filter((f) => { const l = String(f).toLowerCase(); return FORBIDDEN.some((x) => (x.endsWith('/') ? l.startsWith(x) : l === x)); });
85
93
 
86
94
  const ITEM_RE = /^[a-z0-9][a-z0-9_-]*\.[0-9]+$/;
@@ -125,14 +133,21 @@ function itemsOf(root) {
125
133
  try { const a = JSON.parse(r.out.split('\n').pop()); return Array.isArray(a) ? a : []; } catch { return []; }
126
134
  }
127
135
  const itemOf = (root, item) => itemsOf(root).find((x) => x.item_id === item) || null;
128
- const next = (root, ini) => itemsOf(root).filter((x) => x.state === 'declared' && (!ini || x.initiative_id === ini));
136
+ // factory-fleet-scale: an item whose dependencies are not integrated yet is not offered (lib/factory-fleet.js waitingOn)
137
+ const next = (root, ini) => { const all = itemsOf(root); return all.filter((x) => x.state === 'declared' && (!ini || x.initiative_id === ini) && !require('./factory-fleet.js').waitingOn(x, all).length); };
129
138
 
130
139
  function claim(root, item, { agent = 'pmos:builder' } = {}) {
131
140
  if (!ITEM_RE.test(String(item || ''))) return { ok: false, error: 'name a work item, <initiative>.<n>' };
132
141
  if (!WK.factoryRuns(root)) return { ok: false, error: 'no factory runs in this repository, so there is nothing to claim' };
133
- const it = itemOf(root, item);
142
+ const all = itemsOf(root);
143
+ const it = all.find((x) => x.item_id === item) || null;
134
144
  if (!it) return { ok: false, error: `${item} is not a declared work item` };
135
145
  if (it.state !== 'declared') return { ok: false, error: `${item} is ${it.state}, not waiting for a Builder` };
146
+ const FL = require('./factory-fleet.js');
147
+ const wait = FL.waitingOn(it, all);
148
+ if (wait.length) return { ok: false, error: `${item} waits for ${wait.join(', ')}. It can be claimed once ${wait.length === 1 ? 'that item is' : 'those items are'} integrated` };
149
+ const room = FL.claimRoom(root, all);
150
+ if (!room.ok) return { ok: false, error: room.error };
136
151
  const d = defaultBranch(root);
137
152
  if (!d) return { ok: false, error: 'this repository has no default branch (main or master)' };
138
153
  const wt = worktreeOf(root, item), branch = branchOf(item);
@@ -148,7 +163,7 @@ function claim(root, item, { agent = 'pmos:builder' } = {}) {
148
163
  return { ok: true, item, branch, worktree: wt, base: d.name };
149
164
  }
150
165
 
151
- function propose(root, item, { summary = '', evidence = '', run = null } = {}) {
166
+ function propose(root, item, { summary = '', evidence = '', run = null, env = process.env } = {}) {
152
167
  const it = itemOf(root, item);
153
168
  if (!it) return { ok: false, error: `${item} is not a work item here` };
154
169
  if (it.state !== 'claimed') return { ok: false, error: `${item} is ${it.state}; claim it first (pmos build claim ${item})` };
@@ -156,7 +171,9 @@ function propose(root, item, { summary = '', evidence = '', run = null } = {}) {
156
171
  if (!fs.existsSync(wt)) return { ok: false, error: `${item} has no worktree at ${wt}` };
157
172
  const text = one(summary, 200);
158
173
  if (text.length < 8) return { ok: false, error: 'say what the change does, in one line' };
159
- if (one(evidence, 300).length < 4) return { ok: false, error: 'say what passed: --evidence "<the check that passed>". Verify comes before the pull request (D65)' };
174
+ const FC = require('./factory-checks.js');
175
+ const declared = FC.checksOf(root).checks.length > 0;
176
+ if (!declared && one(evidence, 300).length < 4) return { ok: false, error: 'say what passed: --evidence "<the check that passed>". Verify comes before the pull request (D65)' };
160
177
  const id = require('./git-identity.js').localIdentity(topOf(root) || root);
161
178
  if (!id.name || !id.email) return { ok: false, error: 'this repository has no git identity of its own, and PMOS never guesses who commits. Set it once with pmos git-identity set' };
162
179
  git(wt, ['add', '-A']);
@@ -164,14 +181,27 @@ function propose(root, item, { summary = '', evidence = '', run = null } = {}) {
164
181
  if (!files.length) return { ok: false, error: 'nothing changed in the worktree' };
165
182
  const bad = forbiddenIn(files);
166
183
  if (bad.length) return { ok: false, error: `the factory may not change ${bad.join(', ')} (a PMOS record, CI or the agent rules, D65). Take those changes out and propose again` };
167
- const msg = `${text}\n\nWork-Item: ${item}\n`;
168
- const c = git(wt, ['-c', `user.name=${id.name}`, '-c', `user.email=${id.email}`, 'commit', '-q', '-m', msg]);
184
+ let checks = null;
185
+ if (declared) {
186
+ checks = FC.runChecks(root, item, { env });
187
+ if (!checks.ok) {
188
+ FC.record(root, item, checks);
189
+ const bad1 = checks.results.find((r) => r.code !== 0);
190
+ return { ok: false, checks: checks.results, error: checks.error || `the product's check "${bad1.name}" failed (${checks.evidence}). Nothing is committed. Fix it and propose again. Its output ends: ${one(bad1.tail, 400)}` };
191
+ }
192
+ evidence = checks.evidence;
193
+ }
194
+ // ADLC P1: with a factory identity in pmos/factory.json the bot is the author and the PM the co-author (lib/factory-identity.js)
195
+ const who = require('./factory-identity.js').commitArgs(root, id);
196
+ const msg = `${text}\n\nWork-Item: ${item}\n${who.trailer ? who.trailer + '\n' : ''}`;
197
+ const c = git(wt, [...who.args, 'commit', '-q', '-m', msg]);
169
198
  if (!c.ok) return { ok: false, error: `the commit failed: ${one(c.err, 300)}` };
170
199
  const commit = git(wt, ['rev-parse', 'HEAD']).out;
200
+ if (checks) FC.record(root, item, checks, { commit });
171
201
  const v = ledger(root, ['verify', item, '--evidence', one(evidence, 300)]);
172
202
  if (v.status !== 0) return { ok: false, error: `committed ${commit.slice(0, 8)}, but the ledger refused verified: ${one(v.out, 300)}` };
173
- const proposal = fileProposal(root, it, { branch: branchOf(item), base: (defaultBranch(root) || {}).name || 'main', commit, files, summary: text, evidence: one(evidence, 300), run });
174
- return { ok: true, item, commit, files, proposal };
203
+ const proposal = fileProposal(root, it, { branch: branchOf(item), base: (defaultBranch(root) || {}).name || 'main', commit, files, summary: text, evidence: one(evidence, 300), run, round: roundsOf(it) });
204
+ return { ok: true, item, commit, files, proposal, evidence: one(evidence, 300), ...(checks ? { checks: checks.results } : {}) };
175
205
  }
176
206
 
177
207
  /** The class C ✦ proposal the PM's ✓ answers (lib/proposals.js group build, type pr). */
@@ -183,7 +213,8 @@ function fileProposal(root, it, d) {
183
213
  sources: [{ label: 'Branch ' + d.branch, ref: d.commit }], items: [{ id: it.item_id, title: d.summary, ref: d.branch }],
184
214
  data: { item: it.item_id, branch: d.branch, base: d.base, commit: d.commit, files: d.files } });
185
215
  if (c.error) return null;
186
- const prop = { id: PR.idOf(it.initiative_id, 'build', 'pr', it.item_id), ...c.prop };
216
+ // a CI-fix round files its own proposal: the first one was kept already, so the same id would read as done
217
+ const prop = { id: PR.idOf(it.initiative_id, 'build', 'pr', d.round ? `${it.item_id}#fix${d.round}` : it.item_id), ...c.prop };
187
218
  PR.append(dir, null, { kind: 'propose', ini: it.initiative_id, board: '', run: d.run || 'build:' + it.item_id, ...prop });
188
219
  return prop.id;
189
220
  }
@@ -199,19 +230,26 @@ function open(root, item, { env = process.env, title = '', revert = null } = {})
199
230
  const it = itemOf(root, item);
200
231
  if (!it) return { ok: false, pushed: false, error: `${item} is not a work item here` };
201
232
  if (!revert && it.state !== 'verified') return { ok: false, pushed: false, error: `${item} is ${it.state}; only a verified item gets a pull request` };
233
+ // factory-fleet-scale: an item in a fix round has its pull request already; the integrator's draft-only, leased push updates it
234
+ if (!revert && require('./factory-fleet.js').inFixRound(root, item)) return { ...require('./factory-fleet.js').finishFix(root, item, { env }), policy: mergePolicy(root, it, { env }) };
202
235
  const d = defaultBranch(root);
203
236
  const branch = revert ? revertBranchOf(item) : branchOf(item);
204
237
  if (!d) return { ok: false, pushed: false, error: 'this repository has no default branch' };
205
238
  if (!branch.startsWith('pmos/') || branch === d.name || branch.replace(/^refs\/heads\//, '') === d.name) return { ok: false, pushed: false, error: `PMOS never pushes to ${d.name}` };
206
239
  if (!git(root, ['rev-parse', '--verify', '--quiet', 'refs/heads/' + branch]).ok) return { ok: false, pushed: false, error: `there is no branch ${branch}` };
207
240
  const top = topOf(root) || root;
208
- const login = require('./git-identity.js').pushLogin(top);
209
241
  const p = git(top, ['push', 'origin', `refs/heads/${branch}:refs/heads/${branch}`]);
210
242
  if (!p.ok) return { ok: false, pushed: false, error: `the push of ${branch} failed: ${one(p.err, 300)}` };
211
243
  const policy = revert ? { merge: false, verdict: 'human', why: 'A person merges this revert. Its flag is already off.', reasons: [], mark: true } : mergePolicy(root, it, { env });
212
- let ghEnv = { ...env };
213
- if (login) { const t = cp.spawnSync('gh', ['auth', 'token', '--user', login], { encoding: 'utf8', env }); if (t.status === 0 && String(t.stdout).trim()) ghEnv = { ...ghEnv, GH_TOKEN: String(t.stdout).trim() }; }
244
+ const ghEnv = ghEnvOf(top, env, root);
214
245
  if (!hasGh(ghEnv)) return { ok: false, pushed: true, policy, error: `${branch} is pushed, but gh is not installed here, so no pull request was opened. Open a draft pull request from ${branch} into ${d.name} on your Git host` };
246
+ if (!revert) {
247
+ // a CI-fix round (lib/factory-ci.js): the pull request is open already, so the push above updated it; open no second one
248
+ const v = cp.spawnSync('gh', ['pr', 'view', branch, '--json', 'url,state'], { cwd: top, encoding: 'utf8', env: ghEnv });
249
+ let pr = null;
250
+ try { pr = v.status === 0 ? JSON.parse(v.stdout || 'null') : null; } catch { pr = null; }
251
+ if (pr && pr.state === 'OPEN') return { ok: true, pushed: true, updated: true, url: (String(pr.url || '').match(/^https?:\/\/\S+$/) || [''])[0], branch, base: d.name, policy };
252
+ }
215
253
  const it2 = itemOf(root, item);
216
254
  const body = (revert
217
255
  ? [`PMOS reverts work item ${item}: ${revert.why}.`, '', policy.why, '', 'PMOS-Merge: human', `Work-Item: ${item}`]
@@ -220,6 +258,8 @@ function open(root, item, { env = process.env, title = '', revert = null } = {})
220
258
  const r = cp.spawnSync('gh', ['pr', 'create', ...(revert ? [] : ['--draft']), '--base', d.name, '--head', branch, '--title', one(title || (revert ? `Revert ${item}` : `PMOS: ${item}`), 120), '--body', body], { cwd: top, encoding: 'utf8', env: ghEnv });
221
259
  if (r.error || r.status !== 0) return { ok: false, pushed: true, policy, error: `${branch} is pushed, but gh could not open the pull request: ${one(r.stderr || (r.error && r.error.message), 300)}` };
222
260
  const url = (String(r.stdout).match(/https?:\/\/\S+/) || [''])[0];
261
+ // the factory's numbers (lib/factory-traces.js): the guardrail's verdict on this pull request, auto or human
262
+ if (!revert) { try { require('./factory-traces.js').note(root, { item, kind: 'opened', verdict: policy.verdict, rules: policy.reasons }); } catch { /* a lost note never stops the open */ } }
223
263
  return { ok: true, pushed: true, url, branch, base: d.name, policy };
224
264
  }
225
265
 
@@ -245,13 +285,17 @@ function revert(root, item, { env = process.env, why = 'its guard metric left it
245
285
  fs.mkdirSync(path.dirname(wt), { recursive: true });
246
286
  const w = git(top, ['worktree', 'add', '-b', branch, wt, d.ref]);
247
287
  if (!w.ok) return { ok: false, error: `the revert worktree could not be made: ${one(w.err, 300)}` };
248
- const r = git(wt, ['-c', `user.name=${id.name}`, '-c', `user.email=${id.email}`, 'revert', '--no-edit', ...(parents.length > 1 ? ['-m', '1'] : []), sha]);
288
+ const r = git(wt, [...require('./factory-identity.js').commitArgs(root, id, { env }).args, 'revert', '--no-edit', ...(parents.length > 1 ? ['-m', '1'] : []), sha]);
249
289
  if (!r.ok) return { ok: false, error: `git could not revert ${sha.slice(0, 8)}: ${one(r.err, 300)}` };
250
290
  const o = open(root, item, { env, revert: { why } });
251
291
  return o.ok ? { ok: true, branch, url: o.url } : { ok: false, branch, error: o.error };
252
292
  }
253
293
 
254
- function ghEnvOf(top, env) {
294
+ /** gh's environment for PMOS's own gh calls: the factory token (pmos/factory.json identity.token_env, lib/factory-identity.js) when
295
+ * one is set, else the PM's pushLogin token. GH_TOKEN goes into the child's environment only. */
296
+ function ghEnvOf(top, env, root = top) {
297
+ const bot = require('./factory-identity.js').ghTokenOf(root, { env });
298
+ if (bot) return { ...env, GH_TOKEN: bot };
255
299
  const login = require('./git-identity.js').pushLogin(top);
256
300
  if (!login) return { ...env };
257
301
  const t = cp.spawnSync('gh', ['auth', 'token', '--user', login], { encoding: 'utf8', env });
@@ -264,7 +308,7 @@ function ghEnvOf(top, env) {
264
308
  function holdOpen(root, { env = process.env, why = 'agents are off' } = {}) {
265
309
  if (env.PMOS_TEAM_RUN) return { ok: false, error: 'a role run cannot change pull requests' };
266
310
  const top = topOf(root) || root;
267
- const ghEnv = ghEnvOf(top, env);
311
+ const ghEnv = ghEnvOf(top, env, root);
268
312
  const l = cp.spawnSync('gh', ['pr', 'list', '--state', 'open', '--limit', '100', '--json', 'number,headRefName,body,isDraft'], { cwd: top, encoding: 'utf8', env: ghEnv });
269
313
  if (l.error || l.status !== 0) return { ok: false, error: `gh could not list the open pull requests: ${one(l.stderr || (l.error && l.error.message), 200)}. Turn auto-merge off on PMOS's pull requests by hand` };
270
314
  let list = [];
@@ -287,15 +331,52 @@ function close(root, item, { url = '', env = process.env } = {}) {
287
331
  if (env.PMOS_TEAM_RUN) return { ok: false, error: 'a role run cannot close a pull request' };
288
332
  const target = /^https?:\/\/\S+$/.test(String(url || '')) ? url : branchOf(item);
289
333
  const top = topOf(root) || root;
290
- const login = require('./git-identity.js').pushLogin(top);
291
- let ghEnv = { ...env };
292
- if (login) { const t = cp.spawnSync('gh', ['auth', 'token', '--user', login], { encoding: 'utf8', env }); if (t.status === 0 && String(t.stdout).trim()) ghEnv = { ...ghEnv, GH_TOKEN: String(t.stdout).trim() }; }
334
+ const ghEnv = ghEnvOf(top, env, root);
293
335
  const r = cp.spawnSync('gh', ['pr', 'close', target, '--comment', 'Closed by Undo in PMOS.'], { cwd: top, encoding: 'utf8', env: ghEnv });
336
+ if (!r.error && r.status === 0) { try { require('./factory-traces.js').note(root, { item, kind: 'undo' }); } catch { /* a lost note never stops the Undo */ } }
294
337
  return r.error || r.status !== 0 ? { ok: false, error: one(r.stderr || (r.error && r.error.message) || 'gh could not close it', 300) } : { ok: true };
295
338
  }
296
339
 
340
+ const FIX_ROUNDS = 2;
341
+ /** The CI-fix rounds an item had: every claim after the first one is a round (refix appends it). */
342
+ const roundsOf = (it) => Math.max(0, ((it && it.history) || []).filter((e) => e === 'claimed').length - 1);
343
+
344
+ /** A CI-fix round (factory-builder-inner-loop): the product's CI failed on the item's open pull request, and PMOS dispatched the Builder
345
+ * again (lib/factory-ci.js). It claims the VERIFIED item once more through the ledger's writer and gives the Builder its worktree on the
346
+ * SAME branch pmos/<item> (made again from the branch when it was removed). Then the Builder fixes, and propose() runs the checks,
347
+ * commits on top and files the next proposal; open() pushes the branch and the open pull request picks up the commit. */
348
+ function refix(root, item, { agent = 'pmos:builder' } = {}) {
349
+ if (!ITEM_RE.test(String(item || ''))) return { ok: false, error: 'name a work item, <initiative>.<n>' };
350
+ const it = itemOf(root, item);
351
+ if (!it) return { ok: false, error: `${item} is not a work item here` };
352
+ if (it.state !== 'verified') return { ok: false, error: `${item} is ${it.state}; only a verified item with an open pull request gets a fix round` };
353
+ if (roundsOf(it) >= FIX_ROUNDS) return { ok: false, error: `${item} had ${FIX_ROUNDS} fix rounds already; it waits for the PM` };
354
+ const branch = branchOf(item), wt = worktreeOf(root, item);
355
+ if (!git(root, ['rev-parse', '--verify', '--quiet', 'refs/heads/' + branch]).ok) return { ok: false, error: `there is no branch ${branch}` };
356
+ if (!fs.existsSync(wt)) {
357
+ fs.mkdirSync(path.dirname(wt), { recursive: true });
358
+ const w = git(root, ['worktree', 'add', wt, branch]);
359
+ if (!w.ok) return { ok: false, error: `the worktree could not be made: ${one(w.err, 300)}` };
360
+ }
361
+ const c = ledger(root, ['claim', item, '--agent', agent]);
362
+ if (c.status !== 0) return { ok: false, error: one(c.out.replace(/^✗\s*/, ''), 400) };
363
+ return { ok: true, item, branch, worktree: wt, round: roundsOf(itemOf(root, item)) };
364
+ }
365
+
297
366
  function status(root) {
298
- return itemsOf(root).map((x) => { const wt = worktreeOf(root, x.item_id); return { item: x.item_id, state: x.state, branch: branchOf(x.item_id), worktree: wt, here: fs.existsSync(wt) }; });
367
+ const checks = require('./factory-identity.js').lastChecks(root);
368
+ return itemsOf(root).map((x) => { const wt = worktreeOf(root, x.item_id); const c = checks.get(x.item_id);
369
+ return { item: x.item_id, state: x.state, branch: branchOf(x.item_id), worktree: wt, here: fs.existsSync(wt), check: c ? { mode: c.mode, ok: c.ok, at: c.at } : null }; });
370
+ }
371
+
372
+ /** `pmos build check <item>` (ADLC P1): run the item's declared check in its worktree, in a container with no network when
373
+ * PMOS_BUILD_SANDBOX is set (lib/factory-identity.js runCheck). A role run is refused outside the sandbox. */
374
+ function check(root, item, { env = process.env } = {}) {
375
+ const it = itemOf(root, item);
376
+ if (!it) return { ok: false, error: `${item} is not a work item here` };
377
+ if (it.state !== 'claimed') return { ok: false, error: `${item} is ${it.state}; only a claimed item is checked in its worktree` };
378
+ const d = defaultBranch(root);
379
+ return require('./factory-identity.js').runCheck(root, it, { env, wt: worktreeOf(root, item), base: d && d.ref });
299
380
  }
300
381
 
301
- module.exports = { POLICY, FACTORY_JOB, FORBIDDEN, mergePolicy, forbiddenIn, branchOf, revertBranchOf, worktreeOf, defaultBranch, itemsOf, next, claim, propose, open, revert, close, holdOpen, status };
382
+ module.exports = { git, ledger, FIX_ROUNDS, roundsOf, refix, POLICY, FACTORY_JOB, FORBIDDEN, mergePolicy, forbiddenIn, branchOf, revertBranchOf, worktreeOf, defaultBranch, itemsOf, next, claim, propose, open, revert, close, holdOpen, status, ghEnvOf, check };