create-pmos 0.569.0 → 0.571.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 (35) hide show
  1. package/package.json +27 -27
  2. package/payload/AGENTS.md +12 -0
  3. package/payload/KIT-VERSION +2 -2
  4. package/payload/planning/evals/eval-calibration.md +1 -1
  5. package/payload/planning/okrs/health-budgets.md +1 -1
  6. package/payload/planning/work-items.jsonl +0 -0
  7. package/payload/scripts/factory-guardrail.js +267 -0
  8. package/payload/scripts/lib/sink.js +321 -0
  9. package/payload/scripts/verify-work.js +149 -0
  10. package/payload/scripts/work-item.js +1484 -0
  11. package/payload/state/discoveries.md +1 -1
  12. package/payload/state/log.md +1 -1
  13. package/payload/templates/pmos-guardrail.yml +61 -0
  14. package/workspace/changelog.json +26 -0
  15. package/workspace/guide/cli.md +61 -1
  16. package/workspace/guide/initiatives-and-next-steps.md +1 -1
  17. package/workspace/guide/settings-and-switches.md +1 -0
  18. package/workspace/lib/agent-team.js +19 -4
  19. package/workspace/lib/autonomy.js +4 -1
  20. package/workspace/lib/build-cli.js +120 -0
  21. package/workspace/lib/build-engine.js +267 -0
  22. package/workspace/lib/factory-rollout.js +190 -0
  23. package/workspace/lib/headless.js +3 -1
  24. package/workspace/lib/pmos-verbs.js +3 -0
  25. package/workspace/lib/proposals.js +15 -4
  26. package/workspace/lib/routes-proposals.js +14 -3
  27. package/workspace/lib/team-cli.js +3 -1
  28. package/workspace/lib/team-runs.js +4 -0
  29. package/workspace/lib/verify-runs.js +17 -1
  30. package/workspace/lib/verify-work-cli.js +4 -2
  31. package/workspace/lib/work-kind.js +12 -6
  32. package/workspace/package-lock.json +2 -2
  33. package/workspace/package.json +1 -1
  34. package/workspace/public/pm/ini-props.js +3 -1
  35. package/workspace/test-lists/build-engine.json +11 -0
@@ -0,0 +1,267 @@
1
+ 'use strict';
2
+ /* build-engine.js — the Builder of the D65 factory in any repository that carries it (launch simulation W7, initiative
3
+ * kit-factory-builder, done test F3). `pmos build` (lib/build-cli.js) is its terminal face; the ✦ ✓ (lib/routes-proposals.js,
4
+ * group `build`) runs open().
5
+ *
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
8
+ * claim(root, item, { agent }) → { ok, branch, worktree, base } | { ok: false, error }
9
+ * propose(root, item, { summary, evidence, run? }) → { ok, commit, files, proposal } | { ok: false, error }
10
+ * open(root, item, { env, title, revert }) → { ok, pushed, url, policy } | { ok: false, pushed, error }
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 }]
13
+ * mergePolicy(root, item, { env }) → { merge, verdict, why, reasons, mark } when a PR merges with no person (see MERGE POLICY)
14
+ * FORBIDDEN · forbiddenIn(files) · worktreeOf(root, item) · branchOf(item) · defaultBranch(root)
15
+ *
16
+ * THE STEPS, in order. Each one is a separate verb, so each refusal is its own and a test can reach it:
17
+ * 1. claim appends `claimed` through the ledger's ONE writer (scripts/work-item.js claim; the factory never writes the ledger by
18
+ * hand) and adds a git worktree on a new branch pmos/<item> from the default branch. The worktree is OUTSIDE the
19
+ * repository (PMOS_BUILD_DIR, else ~/.pmos/build/<repo>-<hash>/<item>), so the PM's own checkout is never switched or
20
+ * dirtied, and the Builder's Write and Edit are scoped to that folder (lib/agent-team.js toolsOf).
21
+ * 2. propose the Builder's last step. Refuses with no local git identity (`pmos git-identity`: PMOS never guesses who commits),
22
+ * 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
24
+ * with the line `Work-Item: <id>`, appends `verified` with the evidence, and FILES a class C ✦ proposal "Open a draft
25
+ * pull request". It pushes nothing.
26
+ * 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
27
+ * server's ✦ applies it by itself (routes-proposals autoKeep) and Undo closes the pull request; with `pmos ai off` or a
28
+ * demoted factory it waits for the PM's ✓. The PM can still run `pmos build open`.
29
+ * It pushes the ONE branch by an explicit refspec (refs/heads/pmos/<item>, never forced) and refuses a branch that is not
30
+ * pmos/… or that names the default branch. Then `gh pr create --draft`. With no gh it says so and claims no PR.
31
+ *
32
+ * THE TRIFECTA, structurally (kit/AGENTS.md): a Builder run reads private code and untrusted content, so it holds no outward channel:
33
+ * no git push, no gh, no network tool, and open() refuses it. The one outward step runs in PMOS's own process (the ✦, class B since D108), never in the Builder's run.
34
+ *
35
+ * MERGE POLICY (D108). Nothing here merges, and the Builder never holds a merge right. The product repository's own workflow
36
+ * `pmos-guardrail` (kit/templates/pmos-guardrail.yml) runs the default branch's scripts/factory-guardrail.js on each factory pull
37
+ * request and, on `auto`, turns on GitHub auto-merge with the workflow's token: GitHub merges when every required check is green.
38
+ * mergePolicy() runs the SAME classifier here, as a preview for the PM and the ✦, and adds what only this machine knows: autonomy off
39
+ * (`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
+ * writes `PMOS-Merge: human` into the pull request body, which the guardrail reads as human.
41
+ */
42
+ const fs = require('fs');
43
+ const os = require('os');
44
+ const path = require('path');
45
+ const crypto = require('crypto');
46
+ const cp = require('child_process');
47
+ const WK = require('./work-kind.js');
48
+
49
+ const POLICY = 'guardrail';
50
+ const FACTORY_JOB = 'ai:factory';
51
+ /** The merge seam (D108). → { merge, verdict: 'auto'|'human', why, reasons: [{ rule, detail }], mark } */
52
+ function mergePolicy(root, it, { env = process.env } = {}) {
53
+ const human = (why, reasons = [], mark = false) => ({ merge: false, verdict: 'human', why, reasons, mark });
54
+ const A = require('./autonomy.js');
55
+ const k = A.killed({ env });
56
+ if (k) return human(`A person merges this pull request: ${k}.`, [{ rule: 'autonomy-off', detail: k }], true);
57
+ if (typeof root !== 'string' || !it || !it.item_id) return human('A person merges this pull request.');
58
+ const top = topOf(root) || root;
59
+ try {
60
+ const sd = require('./driver.js').stateDirOf(top, { create: false });
61
+ const dm = sd ? A.demotedNow(A.fold(A.read(sd)), FACTORY_JOB, null) : null;
62
+ if (dm) return human(`A person merges this pull request: the factory is back to propose-only until ${String(dm.until).slice(0, 10)} (${dm.why}).`, [{ rule: 'demoted', detail: dm.why }], true);
63
+ } catch { /* no autonomy ledger: nothing demoted */ }
64
+ const dir = WK.factoryDir(root);
65
+ const gpath = dir && path.join(dir, 'scripts', 'factory-guardrail.js');
66
+ if (!gpath || !fs.existsSync(gpath)) return human('A person merges this pull request: this repository\'s PMOS kit has no merge guardrail yet. Update PMOS to get it.');
67
+ const d = defaultBranch(root);
68
+ if (!d) return human('A person merges this pull request: there is no default branch to compare with.');
69
+ let v;
70
+ try { v = require(gpath).classify({ cwd: top, base: d.ref, head: 'refs/heads/' + branchOf(it.item_id), branch: branchOf(it.item_id) }); }
71
+ catch (e) { return human(`A person merges this pull request: the guardrail failed here (${one(e.message, 160)}).`); }
72
+ if (v.verdict === 'auto') return { merge: true, verdict: 'auto', reasons: [], mark: false,
73
+ 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.' };
74
+ return human(`A person merges this pull request (the guardrail reads HUMAN): ${v.reasons.map((r) => r.detail).join('; ')}.`, v.reasons);
75
+ }
76
+
77
+ /* What a factory commit may not touch (D65: the factory never writes a control-graph record). Lower case; a folder ends in "/".
78
+ * Product code under scripts/ or workspace/ is fine here: this is a product repository, not PMOS-self. */
79
+ const FORBIDDEN = Object.freeze(['pmos/', '.github/', 'planning/initiatives/', 'planning/runs/', 'decisions.md', 'pm-decisions.md', 'principles.md',
80
+ 'claude.md', 'agents.md', '.pmos-profile', '.gitattributes']);
81
+ const forbiddenIn = (files) => files.filter((f) => { const l = String(f).toLowerCase(); return FORBIDDEN.some((x) => (x.endsWith('/') ? l.startsWith(x) : l === x)); });
82
+
83
+ const ITEM_RE = /^[a-z0-9][a-z0-9_-]*\.[0-9]+$/;
84
+ const branchOf = (item) => 'pmos/' + item;
85
+ const one = (s, n) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim().slice(0, n);
86
+
87
+ function git(cwd, args, o = {}) {
88
+ const r = cp.spawnSync('git', args, { cwd, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, env: { ...process.env, GIT_TERMINAL_PROMPT: '0', ...(o.env || {}) } });
89
+ return { ok: !r.error && r.status === 0, out: String(r.stdout || '').trim(), err: String(r.stderr || (r.error && r.error.message) || '').trim() };
90
+ }
91
+ function topOf(root) { const r = git(root, ['rev-parse', '--show-toplevel']); return r.ok ? r.out : null; }
92
+
93
+ /** The default branch: origin's HEAD, else main or master as the local repository has them. → { name, ref } | null */
94
+ function defaultBranch(root) {
95
+ const h = git(root, ['symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD']);
96
+ if (h.ok && h.out.startsWith('origin/')) return { name: h.out.slice(7), ref: h.out };
97
+ for (const n of ['main', 'master']) {
98
+ if (git(root, ['rev-parse', '--verify', '--quiet', `refs/remotes/origin/${n}`]).ok) return { name: n, ref: 'origin/' + n };
99
+ if (git(root, ['rev-parse', '--verify', '--quiet', `refs/heads/${n}`]).ok) return { name: n, ref: n };
100
+ }
101
+ return null;
102
+ }
103
+
104
+ /** Where the worktree of one item lives: outside the repository, one folder per repository. */
105
+ function worktreeOf(root, item) {
106
+ const top = topOf(root) || path.resolve(root);
107
+ const base = process.env.PMOS_BUILD_DIR || path.join(os.homedir(), '.pmos', 'build');
108
+ const slug = path.basename(top).replace(/[^A-Za-z0-9_-]/g, '-').slice(0, 40) + '-' + crypto.createHash('sha1').update(top).digest('hex').slice(0, 8);
109
+ return path.join(base, slug, item);
110
+ }
111
+
112
+ /** Run the repository's own ledger writer. → { status, out } */
113
+ function ledger(root, args) {
114
+ const dir = WK.factoryDir(root);
115
+ if (!dir) return { status: 1, out: 'no factory runs in this repository (no work-item ledger and verify-work script)' };
116
+ const r = cp.spawnSync(process.execPath, [path.join(dir, 'scripts', 'work-item.js'), ...args], { cwd: dir, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
117
+ return { status: r.status == null ? 1 : r.status, out: (String(r.stdout || '') + String(r.stderr || '')).trim() };
118
+ }
119
+ function itemsOf(root) {
120
+ const r = ledger(root, ['show', '--json']);
121
+ if (r.status !== 0) return [];
122
+ try { const a = JSON.parse(r.out.split('\n').pop()); return Array.isArray(a) ? a : []; } catch { return []; }
123
+ }
124
+ const itemOf = (root, item) => itemsOf(root).find((x) => x.item_id === item) || null;
125
+ const next = (root, ini) => itemsOf(root).filter((x) => x.state === 'declared' && (!ini || x.initiative_id === ini));
126
+
127
+ function claim(root, item, { agent = 'pmos:builder' } = {}) {
128
+ if (!ITEM_RE.test(String(item || ''))) return { ok: false, error: 'name a work item, <initiative>.<n>' };
129
+ if (!WK.factoryRuns(root)) return { ok: false, error: 'no factory runs in this repository, so there is nothing to claim' };
130
+ const it = itemOf(root, item);
131
+ if (!it) return { ok: false, error: `${item} is not a declared work item` };
132
+ if (it.state !== 'declared') return { ok: false, error: `${item} is ${it.state}, not waiting for a Builder` };
133
+ const d = defaultBranch(root);
134
+ if (!d) return { ok: false, error: 'this repository has no default branch (main or master)' };
135
+ const wt = worktreeOf(root, item), branch = branchOf(item);
136
+ if (fs.existsSync(wt)) return { ok: false, error: `${wt} already exists; remove it or finish that build first` };
137
+ const c = ledger(root, ['claim', item, '--agent', agent]);
138
+ if (c.status !== 0) return { ok: false, error: one(c.out.replace(/^✗\s*/, ''), 400) };
139
+ fs.mkdirSync(path.dirname(wt), { recursive: true });
140
+ const w = git(root, ['worktree', 'add', '-b', branch, wt, d.ref]);
141
+ if (!w.ok) {
142
+ // the claim stays recorded and lapses with its lease (72 h); claim() refuses an existing worktree, so nothing doubles
143
+ return { ok: false, error: `the claim is recorded, but the worktree could not be made: ${one(w.err, 300)}` };
144
+ }
145
+ return { ok: true, item, branch, worktree: wt, base: d.name };
146
+ }
147
+
148
+ function propose(root, item, { summary = '', evidence = '', run = null } = {}) {
149
+ const it = itemOf(root, item);
150
+ if (!it) return { ok: false, error: `${item} is not a work item here` };
151
+ if (it.state !== 'claimed') return { ok: false, error: `${item} is ${it.state}; claim it first (pmos build claim ${item})` };
152
+ const wt = worktreeOf(root, item);
153
+ if (!fs.existsSync(wt)) return { ok: false, error: `${item} has no worktree at ${wt}` };
154
+ const text = one(summary, 200);
155
+ if (text.length < 8) return { ok: false, error: 'say what the change does, in one line' };
156
+ 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)' };
157
+ const id = require('./git-identity.js').localIdentity(topOf(root) || root);
158
+ 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' };
159
+ git(wt, ['add', '-A']);
160
+ const files = git(wt, ['diff', '--cached', '--name-only']).out.split('\n').filter(Boolean);
161
+ if (!files.length) return { ok: false, error: 'nothing changed in the worktree' };
162
+ const bad = forbiddenIn(files);
163
+ 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` };
164
+ const msg = `${text}\n\nWork-Item: ${item}\n`;
165
+ const c = git(wt, ['-c', `user.name=${id.name}`, '-c', `user.email=${id.email}`, 'commit', '-q', '-m', msg]);
166
+ if (!c.ok) return { ok: false, error: `the commit failed: ${one(c.err, 300)}` };
167
+ const commit = git(wt, ['rev-parse', 'HEAD']).out;
168
+ const v = ledger(root, ['verify', item, '--evidence', one(evidence, 300)]);
169
+ if (v.status !== 0) return { ok: false, error: `committed ${commit.slice(0, 8)}, but the ledger refused verified: ${one(v.out, 300)}` };
170
+ const proposal = fileProposal(root, it, { branch: branchOf(item), base: (defaultBranch(root) || {}).name || 'main', commit, files, summary: text, evidence: one(evidence, 300), run });
171
+ return { ok: true, item, commit, files, proposal };
172
+ }
173
+
174
+ /** The class C ✦ proposal the PM's ✓ answers (lib/proposals.js group build, type pr). */
175
+ function fileProposal(root, it, d) {
176
+ const PR = require('./proposals.js');
177
+ const dir = require('./driver.js').stateDirOf(topOf(root) || root, { create: true });
178
+ if (!dir) return null;
179
+ const c = PR.clean('build', 'pr', { title: d.summary, why: `PMOS built ${it.item_id} on ${d.branch}. Its check passed: ${d.evidence}`,
180
+ sources: [{ label: 'Branch ' + d.branch, ref: d.commit }], items: [{ id: it.item_id, title: d.summary, ref: d.branch }],
181
+ data: { item: it.item_id, branch: d.branch, base: d.base, commit: d.commit, files: d.files } });
182
+ if (c.error) return null;
183
+ const prop = { id: PR.idOf(it.initiative_id, 'build', 'pr', it.item_id), ...c.prop };
184
+ PR.append(dir, null, { kind: 'propose', ini: it.initiative_id, board: '', run: d.run || 'build:' + it.item_id, ...prop });
185
+ return prop.id;
186
+ }
187
+
188
+ function hasGh(env) {
189
+ const r = cp.spawnSync('gh', ['--version'], { encoding: 'utf8', env });
190
+ return !r.error && r.status === 0;
191
+ }
192
+
193
+ /** The outward step. Only the PM: the ✓ or the PM's own command. */
194
+ function open(root, item, { env = process.env, title = '', revert = null } = {}) {
195
+ if (env.PMOS_TEAM_RUN) return { ok: false, pushed: false, error: 'a role run cannot open a pull request. It waits for the PM\'s ✓ under the ✦' };
196
+ const it = itemOf(root, item);
197
+ if (!it) return { ok: false, pushed: false, error: `${item} is not a work item here` };
198
+ if (!revert && it.state !== 'verified') return { ok: false, pushed: false, error: `${item} is ${it.state}; only a verified item gets a pull request` };
199
+ const d = defaultBranch(root);
200
+ const branch = revert ? revertBranchOf(item) : branchOf(item);
201
+ if (!d) return { ok: false, pushed: false, error: 'this repository has no default branch' };
202
+ 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}` };
203
+ if (!git(root, ['rev-parse', '--verify', '--quiet', 'refs/heads/' + branch]).ok) return { ok: false, pushed: false, error: `there is no branch ${branch}` };
204
+ const top = topOf(root) || root;
205
+ const login = require('./git-identity.js').pushLogin(top);
206
+ const p = git(top, ['push', 'origin', `refs/heads/${branch}:refs/heads/${branch}`]);
207
+ if (!p.ok) return { ok: false, pushed: false, error: `the push of ${branch} failed: ${one(p.err, 300)}` };
208
+ 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 });
209
+ let ghEnv = { ...env };
210
+ 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() }; }
211
+ 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` };
212
+ const it2 = itemOf(root, item);
213
+ const body = (revert
214
+ ? [`PMOS reverts work item ${item}: ${revert.why}.`, '', policy.why, '', 'PMOS-Merge: human', `Work-Item: ${item}`]
215
+ : [`PMOS built work item ${item}.`, '', it2 && it2.evidence ? `Check that passed: ${it2.evidence}` : '', '', policy.why, '', ...(policy.mark ? ['PMOS-Merge: human'] : []), `Work-Item: ${item}`])
216
+ .filter((x, i, a) => x || a[i - 1]).join('\n');
217
+ 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 });
218
+ 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)}` };
219
+ const url = (String(r.stdout).match(/https?:\/\/\S+/) || [''])[0];
220
+ return { ok: true, pushed: true, url, branch, base: d.name, policy };
221
+ }
222
+
223
+ const revertBranchOf = (item) => 'pmos/revert-' + item;
224
+
225
+ /** The rollout's breach (lib/factory-rollout.js): revert the merged change on pmos/revert-<item> and open a pull request through open().
226
+ * It reads the default branch as this checkout last fetched it (the PM's sync fetches); it fetches nothing itself. */
227
+ function revert(root, item, { env = process.env, why = 'its guard metric left its budget' } = {}) {
228
+ if (env.PMOS_TEAM_RUN) return { ok: false, error: 'a role run cannot revert' };
229
+ const it = itemOf(root, item);
230
+ if (!it) return { ok: false, error: `${item} is not a work item here` };
231
+ const d = defaultBranch(root);
232
+ if (!d) return { ok: false, error: 'this repository has no default branch' };
233
+ const top = topOf(root) || root;
234
+ const hit = git(top, ['log', '--format=%H %P', '-E', `--grep=^Work-Item: ${item.replace(/\./g, '\\.')}$`, d.ref]).out.split('\n').filter(Boolean);
235
+ if (!hit.length) return { ok: false, error: `no commit on ${d.name} carries Work-Item: ${item}` };
236
+ // the newest commit naming the item: a merge commit reverts against its first parent; a squash merge is one commit
237
+ const [sha, ...parents] = hit[0].split(' ');
238
+ const id = require('./git-identity.js').localIdentity(top);
239
+ if (!id.name || !id.email) return { ok: false, error: 'this repository has no git identity of its own, and PMOS never guesses who commits' };
240
+ const branch = revertBranchOf(item), wt = worktreeOf(root, 'revert-' + item);
241
+ if (fs.existsSync(wt)) return { ok: false, error: `${wt} already exists` };
242
+ fs.mkdirSync(path.dirname(wt), { recursive: true });
243
+ const w = git(top, ['worktree', 'add', '-b', branch, wt, d.ref]);
244
+ if (!w.ok) return { ok: false, error: `the revert worktree could not be made: ${one(w.err, 300)}` };
245
+ const r = git(wt, ['-c', `user.name=${id.name}`, '-c', `user.email=${id.email}`, 'revert', '--no-edit', ...(parents.length > 1 ? ['-m', '1'] : []), sha]);
246
+ if (!r.ok) return { ok: false, error: `git could not revert ${sha.slice(0, 8)}: ${one(r.err, 300)}` };
247
+ const o = open(root, item, { env, revert: { why } });
248
+ return o.ok ? { ok: true, branch, url: o.url } : { ok: false, branch, error: o.error };
249
+ }
250
+
251
+ /** Undo of an opened pull request (D108): close it with gh, comment why, leave the branch. → { ok } | { ok: false, error } */
252
+ function close(root, item, { url = '', env = process.env } = {}) {
253
+ if (env.PMOS_TEAM_RUN) return { ok: false, error: 'a role run cannot close a pull request' };
254
+ const target = /^https?:\/\/\S+$/.test(String(url || '')) ? url : branchOf(item);
255
+ const top = topOf(root) || root;
256
+ const login = require('./git-identity.js').pushLogin(top);
257
+ let ghEnv = { ...env };
258
+ 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() }; }
259
+ const r = cp.spawnSync('gh', ['pr', 'close', target, '--comment', 'Closed by Undo in PMOS.'], { cwd: top, encoding: 'utf8', env: ghEnv });
260
+ 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 };
261
+ }
262
+
263
+ function status(root) {
264
+ 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) }; });
265
+ }
266
+
267
+ module.exports = { POLICY, FACTORY_JOB, FORBIDDEN, mergePolicy, forbiddenIn, branchOf, revertBranchOf, worktreeOf, defaultBranch, itemsOf, next, claim, propose, open, revert, close, status };
@@ -0,0 +1,190 @@
1
+ 'use strict';
2
+ /* factory-rollout.js — a merged factory change reaches users through its flag, 5% → 50% → 100%, and rolls itself back (D108,
3
+ * initiative factory-guardrail-merge, done test G5). No model.
4
+ *
5
+ * tick(root, { now, env }) → { acted: [{ item, step, percent, why }], why? } what the server's verify tick runs for each product
6
+ * rollout(root, item, { to, now, env, by }) → { ok, percent } | { ok: false, error } the PM's own flip (`pmos build rollout`)
7
+ * rollback(root, item, { now, env, by }) → { ok } | { ok: false, error } undo: the flag to 0 (`pmos build rollback`)
8
+ * statusOf(root) → [{ item, flag, percent, step, at, why }]
9
+ * configOf(root) → { set, get?, metrics, hold_minutes } | null
10
+ *
11
+ * THE PROVIDER is the PM's: `<kit>/factory.json` (pmos/factory.json in a product repository) names the commands, so PMOS holds no
12
+ * flag service key and runs nothing the PM did not write there:
13
+ * { "flags": { "set": "my-flags set {flag} {percent}" }, {flag} and {percent} are filled in; nothing else is
14
+ * "metrics": { "login_errors": "node ops/login-error-rate.js" }, each prints one number
15
+ * "hold_minutes": 60 } how long each step holds before the next (default 60)
16
+ * A work item names its flag and metric when it is declared: `work-item.js declare … --flag otp_login --metric login_errors --budget 0.02`.
17
+ *
18
+ * THE RULES, per merged (integrated) item with a flag:
19
+ * - autonomy off (`pmos ai off`, PMOS_AUTONOMY=off): nothing moves.
20
+ * - no provider, or no metric for the item: PMOS says so once (`wait-pm`). The change merged default-off; the PM flips the flag.
21
+ * - the metric is read before every step. Above its budget: BREACH. The flag goes to 0, a revert pull request is opened
22
+ * (lib/build-engine.js revert, the PM's own push path), and the autonomy ledger records a revert: the factory is back to
23
+ * propose-only for 7 days (D106 (5)), so open() writes `PMOS-Merge: human` and the guardrail reads human.
24
+ * - inside budget and the step has held hold_minutes: the next step. A key-result item (`--kr`) stops before 100% (`wait-pm`).
25
+ * - a metric that cannot be read holds the step; it never advances on a missing number.
26
+ * Every step is one line in <state>/factory-rollout.jsonl; `pmos build rollback` sets the flag to 0 and records it.
27
+ */
28
+ const fs = require('fs');
29
+ const path = require('path');
30
+ const cp = require('child_process');
31
+ const WK = require('./work-kind.js');
32
+
33
+ const STEPS = Object.freeze([5, 50, 100]);
34
+ const JOB = 'ai:factory';
35
+ const OPEN_JOB = 'propose:build'; // the ✦ job that opens the factory's pull request by itself (D108 as amended 2026-11-16)
36
+ const LEDGER = 'factory-rollout.jsonl';
37
+ const FLAG_RE = /^[A-Za-z0-9_.:-]{2,80}$/;
38
+ const one = (s, n) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim().slice(0, n);
39
+
40
+ function configOf(root) {
41
+ const dir = WK.factoryDir(root);
42
+ if (!dir) return null;
43
+ let j;
44
+ try { j = JSON.parse(fs.readFileSync(path.join(dir, 'factory.json'), 'utf8')); } catch { return null; }
45
+ const set = j && j.flags && typeof j.flags.set === 'string' && j.flags.set.includes('{flag}') && j.flags.set.includes('{percent}') ? j.flags.set : null;
46
+ if (!set) return null;
47
+ const metrics = j.metrics && typeof j.metrics === 'object' ? Object.fromEntries(Object.entries(j.metrics).filter(([, v]) => typeof v === 'string' && v.trim())) : {};
48
+ const hold = Number(j.hold_minutes);
49
+ return { set, metrics, hold_minutes: Number.isFinite(hold) && hold >= 0 ? hold : 60, dir };
50
+ }
51
+
52
+ function stateDir(root) {
53
+ const top = topOf(root) || root;
54
+ return require('./driver.js').stateDirOf(top, { create: true });
55
+ }
56
+ function topOf(root) {
57
+ const r = cp.spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd: root, encoding: 'utf8' });
58
+ return r.status === 0 ? String(r.stdout).trim() : null;
59
+ }
60
+ function lines(root) {
61
+ const d = stateDir(root);
62
+ if (!d) return [];
63
+ let t = '';
64
+ try { t = fs.readFileSync(path.join(d, LEDGER), 'utf8'); } catch { return []; }
65
+ return t.split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
66
+ }
67
+ function log(root, line, now) {
68
+ const d = stateDir(root);
69
+ if (!d) return line;
70
+ const full = { at: new Date(now == null ? Date.now() : now).toISOString(), ...line };
71
+ fs.appendFileSync(path.join(d, LEDGER), JSON.stringify(full) + '\n');
72
+ return full;
73
+ }
74
+ /** The newest line per item. */
75
+ function lastOf(root) {
76
+ const m = new Map();
77
+ for (const l of lines(root)) if (l.item) m.set(l.item, l);
78
+ return m;
79
+ }
80
+
81
+ /** Run one of the PM's commands. Placeholders are filled from checked values only. → { ok, out } */
82
+ function sh(cmd, cwd, env) {
83
+ const r = cp.spawnSync('sh', ['-c', cmd], { cwd, encoding: 'utf8', timeout: 60000, env });
84
+ return { ok: !r.error && r.status === 0, out: one(r.stdout, 300), err: one(r.stderr || (r.error && r.error.message), 300) };
85
+ }
86
+ function setFlag(cfg, flag, percent, env) {
87
+ if (!FLAG_RE.test(flag) || !Number.isInteger(percent) || percent < 0 || percent > 100) return { ok: false, err: 'refused: a flag name or a percent that is not plain' };
88
+ return sh(cfg.set.split('{flag}').join(flag).split('{percent}').join(String(percent)), cfg.dir, env);
89
+ }
90
+ function readMetric(cfg, name, env) {
91
+ const cmd = cfg.metrics[name];
92
+ if (!cmd) return { ok: false, err: `no metric "${name}" in factory.json` };
93
+ const r = sh(cmd, cfg.dir, env);
94
+ const v = r.ok ? Number((r.out.match(/-?[0-9]+(\.[0-9]+)?(e-?[0-9]+)?/i) || [])[0]) : NaN;
95
+ return Number.isFinite(v) ? { ok: true, value: v } : { ok: false, err: r.ok ? `"${name}" printed no number` : `"${name}" failed: ${r.err}` };
96
+ }
97
+
98
+ function flagged(root) {
99
+ return require('./build-engine.js').itemsOf(root).filter((x) => x.guard && x.guard.flag && x.guard.flag.name && x.state === 'integrated');
100
+ }
101
+
102
+ function tick(root, { now = Date.now(), env = process.env } = {}) {
103
+ const A = require('./autonomy.js');
104
+ const k = A.killed({ env });
105
+ if (k) return { acted: [], why: k };
106
+ const items = flagged(root);
107
+ if (!items.length) return { acted: [] };
108
+ const cfg = configOf(root);
109
+ const last = lastOf(root);
110
+ const acted = [];
111
+ const say = (line) => { const l = log(root, line, now); acted.push(l); return l; };
112
+ for (const it of items) {
113
+ const f = it.guard.flag, prev = last.get(it.item_id) || null;
114
+ const percent = prev ? Number(prev.percent) || 0 : 0;
115
+ if (prev && ['breach', 'rollback', 'error'].includes(prev.step)) continue; // stopped: only the PM moves it again
116
+ if (percent >= 100) continue;
117
+ if (!cfg) {
118
+ if (!prev || prev.step !== 'wait-pm') say({ item: it.item_id, flag: f.name, percent, step: 'wait-pm', why: `No flag provider is set in pmos/factory.json, so PMOS cannot roll ${f.name} out. The change merged with the flag off; turn it on when you choose` });
119
+ continue;
120
+ }
121
+ if (!f.metric || !cfg.metrics[f.metric] || !Number.isFinite(Number(f.budget))) {
122
+ if (!prev || prev.step !== 'wait-pm') say({ item: it.item_id, flag: f.name, percent, step: 'wait-pm', why: `${it.item_id} names no guard metric with a budget that factory.json can read, so PMOS does not roll ${f.name} out by itself. The flag stays off; turn it on when you choose` });
123
+ continue;
124
+ }
125
+ const m = readMetric(cfg, f.metric, env);
126
+ if (!m.ok) { if (!prev || prev.why !== m.err) say({ item: it.item_id, flag: f.name, percent, step: 'hold', why: `the step holds: ${m.err}` }); continue; }
127
+ if (m.value > Number(f.budget)) {
128
+ const s = setFlag(cfg, f.name, 0, env);
129
+ const rv = require('./build-engine.js').revert(root, it.item_id, { env, why: `${f.metric} read ${m.value}, above its budget ${f.budget}` });
130
+ const sd = stateDir(root);
131
+ const sb = sd ? A.recordSetback(sd, { job: JOB, product: null, ref: it.item_id, kind: 'revert' }, { now }) : { demoted: null };
132
+ // the factory's pull requests stop opening by themselves too (they wait for the PM's ✓ again)
133
+ if (sd) A.recordSetback(sd, { job: OPEN_JOB, product: null, ref: it.item_id, kind: 'revert' }, { now });
134
+ say({ item: it.item_id, flag: f.name, percent: s.ok ? 0 : percent, from: percent, step: 'breach', value: m.value, budget: Number(f.budget),
135
+ why: `${f.metric} read ${m.value}, above its budget ${f.budget}. ${s.ok ? `${f.name} is off` : `Turning ${f.name} off FAILED (${s.err}); turn it off now`}. ${rv.ok ? `Revert pull request: ${rv.url || rv.branch}` : `No revert pull request: ${rv.error}`}. ${sb.demoted ? 'The factory is back to propose-only until ' + sb.demoted.until.slice(0, 10) : 'Recorded as a revert'}.`,
136
+ ...(rv.ok && rv.url ? { revert: rv.url } : {}) });
137
+ continue;
138
+ }
139
+ const nextP = STEPS.find((p) => p > percent);
140
+ if (nextP === 100 && it.guard.kr) {
141
+ if (!prev || prev.step !== 'wait-pm') say({ item: it.item_id, flag: f.name, percent, step: 'wait-pm', value: m.value, why: `${it.item_id} moves a key result, so ${f.name} stays at ${percent}% until you take it to 100% (pmos build rollout ${it.item_id} --to 100)` });
142
+ continue;
143
+ }
144
+ if (prev && percent > 0 && now - Date.parse(prev.at) < cfg.hold_minutes * 60000) continue;
145
+ const s = setFlag(cfg, f.name, nextP, env);
146
+ if (!s.ok) { say({ item: it.item_id, flag: f.name, percent, step: 'error', why: `the provider refused ${f.name} at ${nextP}%: ${s.err}. The rollout stops here` }); continue; }
147
+ say({ item: it.item_id, flag: f.name, percent: nextP, from: percent, step: 'set', value: m.value, budget: Number(f.budget), by: 'pmos', why: `${f.metric} read ${m.value} (budget ${f.budget}); ${f.name} ${percent}% → ${nextP}%` });
148
+ }
149
+ return { acted };
150
+ }
151
+
152
+ function itemFlag(root, item) {
153
+ const it = require('./build-engine.js').itemsOf(root).find((x) => x.item_id === item);
154
+ if (!it) return { error: `${item} is not a work item here` };
155
+ if (!it.guard || !it.guard.flag || !it.guard.flag.name) return { error: `${item} declares no flag` };
156
+ return { it, flag: it.guard.flag.name };
157
+ }
158
+
159
+ function rollout(root, item, { to = null, now = Date.now(), env = process.env, by = 'pm' } = {}) {
160
+ const f = itemFlag(root, item);
161
+ if (f.error) return { ok: false, error: f.error };
162
+ const cfg = configOf(root);
163
+ if (!cfg) return { ok: false, error: 'no flag provider is set in pmos/factory.json; turn the flag on in your flag service' };
164
+ const prev = lastOf(root).get(item);
165
+ const percent = prev ? Number(prev.percent) || 0 : 0;
166
+ const target = to == null ? STEPS.find((p) => p > percent) : Number(to);
167
+ if (!Number.isInteger(target) || target < 0 || target > 100) return { ok: false, error: 'the percent is a whole number from 0 to 100' };
168
+ const s = setFlag(cfg, f.flag, target, env);
169
+ if (!s.ok) return { ok: false, error: `the provider refused: ${s.err}` };
170
+ log(root, { item, flag: f.flag, percent: target, from: percent, step: 'set', by, why: `${f.flag} ${percent}% → ${target}% by ${by}` }, now);
171
+ return { ok: true, item, flag: f.flag, percent: target };
172
+ }
173
+
174
+ function rollback(root, item, { now = Date.now(), env = process.env, by = 'pm' } = {}) {
175
+ const f = itemFlag(root, item);
176
+ if (f.error) return { ok: false, error: f.error };
177
+ const cfg = configOf(root);
178
+ if (!cfg) return { ok: false, error: 'no flag provider is set in pmos/factory.json; turn the flag off in your flag service' };
179
+ const prev = lastOf(root).get(item);
180
+ const s = setFlag(cfg, f.flag, 0, env);
181
+ if (!s.ok) return { ok: false, error: `the provider refused: ${s.err}` };
182
+ log(root, { item, flag: f.flag, percent: 0, from: prev ? Number(prev.percent) || 0 : 0, step: 'rollback', by, why: `${f.flag} rolled back to 0% by ${by}; the rollout stops until you run pmos build rollout ${item}` }, now);
183
+ return { ok: true, item, flag: f.flag, percent: 0 };
184
+ }
185
+
186
+ function statusOf(root) {
187
+ return [...lastOf(root).values()].map((l) => ({ item: l.item, flag: l.flag, percent: Number(l.percent) || 0, step: l.step, at: l.at, why: l.why }));
188
+ }
189
+
190
+ module.exports = { STEPS, JOB, LEDGER, configOf, tick, rollout, rollback, statusOf };
@@ -443,7 +443,9 @@ function argsFor(kind, { modelArgs = [], addDirs = [], writePaths = [], budgetUs
443
443
  if (AT.roleOf(team.role)) {
444
444
  const mode = team.mode === 'auto' ? 'auto' : 'propose';
445
445
  tools = AT.toolsOf(team.role, { mode }).tools;
446
- if (mode === 'auto') for (const p of Array.isArray(writePaths) ? writePaths : []) {
446
+ // the Builder (W7): Write and Edit in its worktree folder only, whatever the caller passes
447
+ if (team.role === 'build') for (const p of AT.toolsOf('build', { mode }).writePaths) { const b = p.replace(/\/+$/, ''); if (b.startsWith('/') && !/[\s,*?()\[\]{}]/.test(b) && !b.includes('..')) tools.push(`Write(/${b}/**)`, `Edit(/${b}/**)`); }
448
+ else if (mode === 'auto') for (const p of Array.isArray(writePaths) ? writePaths : []) {
447
449
  const s = String(p || ''), dir = s.endsWith('/'), b = s.replace(/\/+$/, '');
448
450
  if (!b.startsWith('/') || /[\s,*?()\[\]{}]/.test(b) || b.includes('..')) continue;
449
451
  // only a path that IS one of the role's own artifacts, whatever the caller passes
@@ -33,6 +33,9 @@ const VERBS = Object.freeze({
33
33
  help: 'pmos board [--mine] [--init <id>] — the items of every initiative, by column' }),
34
34
  'verify-work': Object.freeze({ module: 'verify-work-cli.js', run: 4, guide: 'cli.md',
35
35
  help: 'pmos verify-work — mark work items integrated from the default branch (local refs only)' }),
36
+ // Not a pm-os-absorb verb (run: null): launch simulation W7 (kit-factory-builder) added it through the same table.
37
+ build: Object.freeze({ module: 'build-cli.js', run: null, guide: 'cli.md',
38
+ help: 'pmos build next|claim|propose|open|status|policy|rollout|rollback — the Builder: a declared work item becomes a pull request; the product\'s guardrail decides who merges (pmos build help)' }),
36
39
  report: Object.freeze({ module: 'report-cli.js', run: 5, guide: 'cli.md',
37
40
  help: 'pmos report draft|issue|list … — draft and issue reports (pmos report help)' }),
38
41
  // Not a pm-os-absorb verb (run: null): initiative jira-wbs added it through the same table.
@@ -22,6 +22,9 @@
22
22
  * description the record's own description (initiative-description-field; filed by lib/description-props.js): type new (none yet) or
23
23
  * enrich (the PRD says more). data { text, from? }; one item { id: 'description', title: the text cut }. Always section 'check'.
24
24
  * ✓ writes the record's description line (lib/initiative-writer.js setDescription)
25
+ * build the factory's draft pull request (launch simulation W7; filed by lib/build-engine.js propose): type pr, data { item, branch,
26
+ * base, commit, files }; one item { id: the work item, title: what it does }. Class C, always section 'check': ✓ pushes the one
27
+ * branch and opens the DRAFT pull request (build-engine open). Nothing merges here (build-engine mergePolicy)
25
28
  * prototyped · improved · scanned what the idle lab made while the PM was away (lib/idle-lab.js result): a first round of 2–3 specimens,
26
29
  * a new round of one, a scan finding to attach as evidence. No items; always section 'check'. ✓ keeps it as a document
27
30
  * grill what Claude found when it grilled the initiative by itself (lib/grill.js): type = the angle, no items, a next step in data.next;
@@ -72,8 +75,8 @@ const KINDS = new Set(['epoch', 'look', 'src', 'end', 'propose', 'drop', 'keep',
72
75
  /* chief-of-staff C3: a filed ✦ with no answer for this many days expires (left as it was, the reason kept) */
73
76
  const EXPIRE_DAYS = 14;
74
77
  const EXPIRE_WHY = 'No answer in 14 days, so I left it as it was.';
75
- const GROUPS = ['found', 'dates', 'status', 'names', 'outcome', 'description'];
76
- const TYPES = { found: ['stage', 'docs', 'tasks', 'link', 'maybe', 'unplaced'], dates: ['stage', 'task'], status: ['done'], names: ['tidy'], outcome: ['new', 'date', 'refuted'], description: ['new', 'enrich'] };
78
+ const GROUPS = ['found', 'dates', 'status', 'names', 'outcome', 'description', 'build'];
79
+ const TYPES = { found: ['stage', 'docs', 'tasks', 'link', 'maybe', 'unplaced'], dates: ['stage', 'task'], status: ['done'], names: ['tidy'], outcome: ['new', 'date', 'refuted'], description: ['new', 'enrich'], build: ['pr'] };
77
80
  const SOURCES = ['drive', 'docs', 'sheets', 'slides', 'jira', 'calendar', 'notes', 'mail', 'slack', 'confluence', 'chat', 'repo'];
78
81
  const SOURCE_NAMES = { drive: 'Drive and Slides', docs: 'Docs', sheets: 'Sheets', slides: 'Slides', jira: 'Jira', calendar: 'Calendar and meeting notes', notes: 'Meeting notes',
79
82
  mail: 'Gmail', slack: 'Slack', confluence: 'Confluence', chat: 'Chat', repo: 'This repository' };
@@ -186,7 +189,15 @@ function clean(group, type, input) {
186
189
  if (text.length < 12) return { error: 'data.text is the description, one paragraph of 12 to 700 characters' };
187
190
  data.text = text; if (str(d.from)) data.from = one(d.from, 700);
188
191
  }
189
- return { prop: { group, type, section: group === 'outcome' || group === 'description' ? 'check' : section, title: one(input.title, LIM.title) || null, why, sources: s.v, items, data } };
192
+ if (group === 'build') {
193
+ // the factory's draft pull request (launch simulation W7, lib/build-engine.js propose). Class C: only the PM's ✓ pushes and opens it
194
+ const d = isObj(input.data) ? input.data : {};
195
+ if (!/^[a-z0-9][a-z0-9_-]*\.[0-9]+$/.test(str(d.item))) return { error: 'data.item is the work item, <initiative>.<n>' };
196
+ if (str(d.branch) !== 'pmos/' + str(d.item)) return { error: 'data.branch is pmos/<item>' };
197
+ if (!/^[0-9a-f]{40}$/.test(str(d.commit))) return { error: 'data.commit is the commit sha' };
198
+ Object.assign(data, { item: str(d.item), branch: str(d.branch), base: one(d.base || 'main', 80), commit: str(d.commit), files: (Array.isArray(d.files) ? d.files : []).slice(0, 50).map((f) => one(f, 200)) });
199
+ }
200
+ return { prop: { group, type, section: group === 'outcome' || group === 'description' || group === 'build' ? 'check' : section, title: one(input.title, LIM.title) || null, why, sources: s.v, items, data } };
190
201
  }
191
202
  /** The proposal's own id: one per initiative, group, type and key, so a newer run files over the older one. */
192
203
  const idOf = (ini, group, type, key) => 'pr-' + hash([ini, group, type, key || ''].join('|'));
@@ -395,7 +406,7 @@ function datesOf(ini, T, o = {}) {
395
406
  }
396
407
 
397
408
  /* ── what r.props carries ── */
398
- const ORDER = { description: -2, outcome: -1, prototyped: -0.6, improved: -0.5, scanned: -0.4, found: 0, dates: 1, status: 2, names: 3, links: 4, grill: 5 };
409
+ const ORDER = { build: -3, description: -2, outcome: -1, prototyped: -0.6, improved: -0.5, scanned: -0.4, found: 0, dates: 1, status: 2, names: 3, links: 4, grill: 5 };
399
410
  const GRILL_SHOWN = 3;
400
411
  /**
401
412
  * One initiative's proposals, as the ✦ and the Viewer draw them, or null when there is nothing to show.
@@ -70,7 +70,7 @@ const W = {
70
70
  };
71
71
  /** Keep these proposals: their writes, then one `keep` line. extra: D106 { auto: true, group } for a change an agent applied by itself. */
72
72
  function keepCore(ctx, p, g, f, ini, want, choices = {}, extra = {}) {
73
- const dir = dirOf(ctx, p.w), wrote = [], keptIds = [], outbox = [];
73
+ const dir = dirOf(ctx, p.w), wrote = [], keptIds = [], outbox = [], failed = [];
74
74
  let plans = 0;
75
75
  for (const x of want) {
76
76
  if (x.group === 'links') {
@@ -79,6 +79,7 @@ function keepCore(ctx, p, g, f, ini, want, choices = {}, extra = {}) {
79
79
  continue;
80
80
  }
81
81
  const w = applyOne(ctx, p, g, f, ini, x, choices, outbox);
82
+ if (x.group === 'build' && !w.length) { failed.push({ id: x.id, why: x.failed || 'not opened' }); continue; } // stays open, says why
82
83
  wrote.push(...w);
83
84
  if (x.group === 'dates' && x.plan && w.some((y) => y.op === 'dates')) plans++;
84
85
  keptIds.push(x.group === 'dates' ? x.id + ':' + x.sig : x.id);
@@ -86,7 +87,7 @@ function keepCore(ctx, p, g, f, ini, want, choices = {}, extra = {}) {
86
87
  for (const a of outbox) { const id = toOutbox(ctx, a); if (id) wrote.push({ op: 'outbox', task: a.task, entry: id, why: a.text }); }
87
88
  const batch = PR.newBatch();
88
89
  PR.append(dir, g.actor, { kind: 'keep', ini, board: p.board.id, batch, ids: keptIds, wrote, ...extra });
89
- return { batch, wrote, plans, keptIds };
90
+ return { batch, wrote, plans, keptIds, failed };
90
91
  }
91
92
 
92
93
  /** Undo one kept batch. → { ok, back, kept } | { ok: false, status, error }. A task changed since keeps its change. */
@@ -117,6 +118,7 @@ function undoCore(ctx, p, g, id) {
117
118
  else if (w.op === 'life') { const r2 = require('./outcomes.js').setLife(p.w.root, k.ini, w.from === 'cancelled' ? 'cancelled' : 'active', 'Undo: PMOS ✦ stopped it', g.actor); if (r2.ok) back++; else kept++; continue; }
118
119
  // a new experiment the ✦ made goes from every list (the Board's own Delete: the record file stays, a restore brings it back)
119
120
  else if (w.op === 'created') { r = RB.writeAs(ctx, '/api/boards/ini-delete', { ws: p.w.id, board: p.board.id, id: w.id }, g); }
121
+ else if (w.op === 'pr') { const r2 = require('./build-engine.js').close(p.w.root, w.item, { url: w.url }); if (r2.ok) back++; else kept++; continue; } // D108: Undo closes the pull request (the branch stays)
120
122
  else if (w.op === 'outcome') { const r2 = require('./initiative-writer.js').restoreOutcome(p.w.root, k.ini, w.from || {}, w.to || {}, { actor: g.actor }); if (r2.ok && !r2.kept) back++; else kept++; continue; } // a record edited since keeps its edit
121
123
  if (r && r.body && r.body.ok) back++; else kept++;
122
124
  }
@@ -231,6 +233,13 @@ function applyOne(ctx, p, g, f, ini, x, choices, outbox) {
231
233
  if (was) { TL.append(dir, g.actor, { kind: 'unlink', from: l.from, to: l.to }); add({ op: 'unlink', from: l.from, to: l.to, link: { type: was.type, lag: was.lag, source: was.source } }); }
232
234
  }
233
235
  }
236
+ } else if (x.group === 'build') {
237
+ // the factory's draft pull request (launch simulation W7). Class C: only the PM's ✓ reaches here. It pushes the one branch and
238
+ // opens the DRAFT PR; it merges nothing. A failure writes nothing, so the proposal stays open (keepCore).
239
+ const d = x.data || {};
240
+ const r = require('./build-engine.js').open(p.w.root, d.item, { title: x.title || '' });
241
+ if (r.ok) add({ op: 'pr', item: d.item, branch: d.branch, url: r.url || '' });
242
+ else x.failed = r.error;
234
243
  } else if (x.group === 'outcome' && x.type === 'refuted') {
235
244
  // a refuted outcome's next step (launch simulation W2; lib/outcomes.js refutedDrafts). Class C: only the PM's ✓ reaches here.
236
245
  // kill the experiment is cancelled with the check as its reason (the D70 lifecycle line the Board's ⋯ Cancel writes)
@@ -376,7 +385,9 @@ const WRITES = {
376
385
  const want = body.all === true ? all.filter((x) => x.section === 'sure') : all.filter((x) => ids.includes(x.id));
377
386
  if (!want.length) return fail(ctx, res, 409, 'Those proposals are no longer open');
378
387
  const dir = dirOf(ctx, p.w);
379
- const { batch, wrote, plans } = keepCore(ctx, p, g, f, ini, want, isObj(body.choices) ? body.choices : {});
388
+ const { batch, wrote, plans, failed } = keepCore(ctx, p, g, f, ini, want, isObj(body.choices) ? body.choices : {});
389
+ // a draft pull request that could not open (W7): nothing was written, the proposal stays open, and the page says why
390
+ if (failed.length && !wrote.length) return fail(ctx, res, 409, failed[0].why);
380
391
  const v2 = view(ctx, p, ini);
381
392
  const left = v2 ? v2.groups.flatMap((x) => x.props).filter((x) => x.section === 'check').length : 0;
382
393
  ctx.json(res, { ok: true, batch, said: saidOf(wrote, plans, body.all === true ? left : 0), counts: { wrote: wrote.length }, props: v2, found: PR.foundOf(PR.read(dir), ini) });
@@ -77,7 +77,7 @@ async function run(argv, { say = (s) => console.log(s), env = process.env, cwd =
77
77
  say(` owns: ${r.what}`);
78
78
  if (r.owns.paths.length || r.owns.verbs.length) say(` writes only: ${[...r.owns.paths, ...r.owns.verbs].join(', ')}`);
79
79
  say(` wakes on: ${r.triggers.map((x) => (x.on === 'stage' ? `stage ${x.stage}${x.unless ? ' without ' + x.unless : ''}` : x.on === 'written' ? 'a write by another role' : 'a dispatch')).join(', ')}`);
80
- if (r.key === 'build') say(` here: ${factory ? 'the factory runs in this repository. It opens pull requests and never merges them; you merge.' : 'no factory runs in this repository, so the Builder does not run. The team\'s agents build from the done test and the pull request plan PMOS writes.'}`);
80
+ if (r.key === 'build') say(` here: ${factory ? 'the factory runs in this repository. The Builder\'s pull requests open by themselves (pmos build); the product\'s guardrail decides who merges.' : 'no factory runs in this repository, so the Builder does not run. The team\'s agents build from the done test and the pull request plan PMOS writes.'}`);
81
81
  }
82
82
  return 0;
83
83
  }
@@ -108,6 +108,8 @@ async function run(argv, { say = (s) => console.log(s), env = process.env, cwd =
108
108
  if (!target) return fail('usage: pmos team dispatch <initiative> | --goal "<goal>"', 2);
109
109
  const roles = typeof flags.roles === 'string' && flags.roles ? flags.roles.split(',').map((s) => s.trim()).filter(Boolean) : null;
110
110
  if (roles) for (const k of roles) if (!T.roleOf(k)) return fail(`"${k}" is not a role (${Object.keys(T.TEAM).join(', ')})`, 2);
111
+ // the Builder runs only where a factory runs (W7): elsewhere it would claim from a ledger that is not there
112
+ if (roles && roles.includes('build') && !require('./work-kind.js').factoryRuns(root)) return fail('no factory runs in this repository, so the Builder cannot run here. The team\'s agents build from the done test and the pull request plan');
111
113
  const facts = goal != null ? {} : R.factsOf(root, target);
112
114
  const r = R.dispatch(dir, { kind: goal != null ? 'goal' : 'initiative', target, ws: require('./driver.js').wsIdOf(root), facts, roles, now });
113
115
  if (!r.ok) return fail(r.error);