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
@@ -2,7 +2,7 @@
2
2
  type: Reference
3
3
  title: "Discoveries and friction log"
4
4
  description: "Append-only record of what runs discovered and where the process rubbed."
5
- generated: {by: process:create-pmos, at: "2026-11-15T17:07:33Z"}
5
+ generated: {by: process:create-pmos, at: "2026-11-16T04:26:40Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -2,6 +2,6 @@
2
2
 
3
3
  Newest first, ISO dates.
4
4
 
5
- ## 2026-11-15
5
+ ## 2026-11-16
6
6
 
7
7
  - Adopted OKF v0.2 (D73).
@@ -0,0 +1,61 @@
1
+ # PMOS factory guardrail (D108). Copy to .github/workflows/pmos-guardrail.yml in the product repository, then make
2
+ # "pmos-guardrail / classify" a required check on the default branch, together with your own CI.
3
+ #
4
+ # What it does: for a pull request the PMOS factory opened (branch pmos/<item>), it reads AUTO or HUMAN from the default
5
+ # branch's copy of pmos/scripts/factory-guardrail.js. On AUTO it marks the pull request ready and turns on GitHub auto-merge
6
+ # with this workflow's own token: GitHub then merges only when every required check is green. On HUMAN it turns auto-merge
7
+ # off and names every reason in the run summary; a person merges. Any other pull request: nothing. To stop one merge, add the
8
+ # line "PMOS-Merge: human" to the pull request's description: the edit runs this check again and turns auto-merge off.
9
+ #
10
+ # Why pull_request_target: it runs THIS workflow and THE DEFAULT BRANCH'S guardrail, never the pull request's code. The head
11
+ # is fetched and diffed only. Do not add a step that runs, installs or builds anything from the head in this workflow.
12
+ #
13
+ # Before it can merge anything:
14
+ # - Settings > General > "Allow auto-merge" is on.
15
+ # - Branch protection (or a ruleset) on the default branch requires your CI checks. Without required checks GitHub could
16
+ # merge before CI runs, so leave this workflow out until they exist.
17
+ # - A merge made with this token does not start other workflows on the default branch (GitHub's rule). If your release
18
+ # runs on push to the default branch, start it from a pull_request "closed" event or give this job a GitHub App token.
19
+ name: pmos-guardrail
20
+ on:
21
+ pull_request_target:
22
+ types: [opened, synchronize, reopened, ready_for_review, edited]
23
+
24
+ permissions:
25
+ contents: write
26
+ pull-requests: write
27
+
28
+ concurrency:
29
+ group: pmos-guardrail-${{ github.event.pull_request.number }}
30
+ cancel-in-progress: true
31
+
32
+ jobs:
33
+ classify:
34
+ name: classify
35
+ if: startsWith(github.event.pull_request.head.ref, 'pmos/')
36
+ runs-on: ubuntu-latest
37
+ steps:
38
+ - uses: actions/checkout@v4
39
+ with:
40
+ ref: ${{ github.event.pull_request.base.sha }}
41
+ fetch-depth: 0
42
+ persist-credentials: false
43
+ - name: Fetch the pull request's head (diffed, never run)
44
+ env:
45
+ PR: ${{ github.event.pull_request.number }}
46
+ run: git fetch --no-tags origin "+refs/pull/${PR}/head:refs/remotes/pmos-pr/head"
47
+ - name: Guardrail
48
+ env:
49
+ GH_TOKEN: ${{ github.token }}
50
+ GH_REPO: ${{ github.repository }}
51
+ PR: ${{ github.event.pull_request.number }}
52
+ HEAD_REF: ${{ github.event.pull_request.head.ref }}
53
+ BASE_SHA: ${{ github.event.pull_request.base.sha }}
54
+ PR_BODY: ${{ github.event.pull_request.body }}
55
+ HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }}
56
+ BASE_REPO: ${{ github.repository }}
57
+ run: |
58
+ printf '%s' "$PR_BODY" > "$RUNNER_TEMP/pmos-pr-body.txt"
59
+ node pmos/scripts/factory-guardrail.js --base "$BASE_SHA" --head refs/remotes/pmos-pr/head \
60
+ --branch "$HEAD_REF" --body-file "$RUNNER_TEMP/pmos-pr-body.txt" --head-repo "$HEAD_REPO" --base-repo "$BASE_REPO" \
61
+ --github --pr "$PR"
@@ -1,4 +1,30 @@
1
1
  [
2
+ {
3
+ "v": "0.571.0",
4
+ "at": "2026-11-16T04:26:43.356Z",
5
+ "f": 4,
6
+ "prs": [
7
+ {
8
+ "n": 1303,
9
+ "t": "The factory merges behind a guardrail, and rolls out behind a flag",
10
+ "s": "The factory merges behind a guardrail, and rolls out behind a flag",
11
+ "k": "new"
12
+ }
13
+ ]
14
+ },
15
+ {
16
+ "v": "0.570.0",
17
+ "at": "2026-11-15T17:32:20.370Z",
18
+ "f": 4,
19
+ "prs": [
20
+ {
21
+ "n": 1302,
22
+ "t": "The real build engine for Full SDLC (launch simulation W7)",
23
+ "s": "The real build engine for Full SDLC (launch simulation W7)",
24
+ "k": "new"
25
+ }
26
+ ]
27
+ },
2
28
  {
3
29
  "v": "0.569.0",
4
30
  "at": "2026-11-15T17:07:37.237Z",
@@ -428,7 +428,7 @@ Options:
428
428
  - `--json` prints the result as JSON.
429
429
  - `--root <dir>` runs in a different repository.
430
430
 
431
- The command runs the repository's own copy of `scripts/verify-work.js`. A repository with no factory writer has no work items, and the command tells you so.
431
+ The command runs the repository's own copy of `scripts/verify-work.js`. In a repository made by `create-pmos`, that copy is `pmos/scripts/verify-work.js`. A repository with no factory writer has no work items, and the command tells you so.
432
432
 
433
433
  The command reports these cases and writes nothing for them:
434
434
 
@@ -437,6 +437,66 @@ The command reports these cases and writes nothing for them:
437
437
 
438
438
  A commit that is only on another branch is not read.
439
439
 
440
+ ### pmos build: PMOS builds a work item as a draft pull request
441
+
442
+ In a repository with a factory, PMOS can build a declared work item. A repository made by `create-pmos` has a factory: `pmos/scripts/work-item.js`, `pmos/scripts/verify-work.js` and `pmos/planning/work-items.jsonl`. Elsewhere the command says that PMOS does not build there.
443
+
444
+ The Builder does these steps:
445
+
446
+ 1. `pmos build next [<initiative>]` lists the declared work items that no Builder has taken.
447
+ 2. `pmos build claim <item>` claims one item. PMOS makes the branch `pmos/<item>` from the default branch, in a worktree outside your folder. Your own checkout does not change.
448
+ 3. The Builder changes files in that worktree only, and runs the item's check.
449
+ 4. `pmos build propose <item> "<what it does>" --evidence "<the check that passed>"` commits the change with the line `Work-Item: <item>`, marks the item verified, and puts "Open a draft pull request" under the initiative's ✦. Nothing is pushed yet.
450
+ 5. PMOS opens the pull request by itself: it pushes only `pmos/<item>` and opens a draft pull request with `gh`. The push comes from PMOS, never from the Builder's run. Undo on the ✦ closes the pull request. When agents are off (`pmos ai off`), or the factory is back to propose-only after a revert, the proposal waits for your ✓. You can also run `pmos build open <item>` yourself.
451
+ 6. The product's `pmos-guardrail` check decides who merges (see below). Then `pmos verify-work` marks the item integrated.
452
+
453
+ `pmos build status` lists every work item, its branch and whether its worktree is on this computer.
454
+
455
+ #### Who merges: the guardrail
456
+
457
+ PMOS never merges and the Builder holds no merge right (D108). The product repository's own check decides. Copy `pmos/templates/pmos-guardrail.yml` to `.github/workflows/`, turn on "Allow auto-merge" in the repository settings, and make your CI checks required on the default branch.
458
+
459
+ For each pull request on a `pmos/` branch, the check runs the default branch's copy of `pmos/scripts/factory-guardrail.js`. It reads the pull request's changes and never runs its code. The answer is one of these:
460
+
461
+ - **AUTO.** The item is verified in the default branch's records, every changed file is inside the item's declared scope, the change reads its flag (or the item has no user-facing effect), and no trigger fires. The check marks the pull request ready and turns on auto-merge. GitHub merges when every required check is green.
462
+ - **HUMAN.** The check names every reason and turns auto-merge off. You merge.
463
+
464
+ These triggers always make the answer HUMAN: migrations or data deletion; auth, permissions, payments, personal data or secrets; CI, gates, the guardrail or PMOS records; a new dependency; a public API or contract; anything sent outward; a new agent path; a changed existing test, test configuration or the item's own check; an item that failed before; a revert on the default branch in the last 14 days; a folder untouched for 90 days. When agents are switched off (`pmos ai off`) or the factory is back to propose-only after a revert, PMOS writes `PMOS-Merge: human` in the pull request, and the check reads HUMAN. To stop one merge yourself, add that line to the pull request's description. A pull request from a fork always reads HUMAN.
465
+
466
+ `pmos build policy <item>` shows the answer on this computer before the check runs.
467
+
468
+ A work item says what the guardrail reads when it is declared: `node pmos/scripts/work-item.js declare <initiative> … --scope src/login/ --flag otp_login --metric login_errors --budget 0.02`. Use `--no-user-facing` instead of a flag for a change users cannot see, and `--kr` for an item that moves a key result.
469
+
470
+ #### The flag rollout
471
+
472
+ After the merge, PMOS moves the item's flag to 5%, then 50%, then 100%. Each step holds for an hour (`hold_minutes`) and moves only while the item's metric stays inside its budget. A key-result item stops before 100% and waits for you. When the metric goes over its budget, PMOS turns the flag off, opens a revert pull request for you to merge, and puts the factory back to propose-only for 7 days.
473
+
474
+ PMOS uses your flag service through the commands in `pmos/factory.json`:
475
+
476
+ ```json
477
+ { "flags": { "set": "my-flags set {flag} {percent}" },
478
+ "metrics": { "login_errors": "node ops/login-error-rate.js" },
479
+ "hold_minutes": 60 }
480
+ ```
481
+
482
+ `{flag}` and `{percent}` are filled in. Each metric command prints one number. With no `factory.json`, or no metric for the item, PMOS says so and moves nothing: the change merged with its flag off, and you turn it on.
483
+
484
+ - `pmos build rollout` shows where every flag stands.
485
+ - `pmos build rollout <item> [--to <percent>]` moves one flag yourself.
486
+ - `pmos build rollback <item>` turns the flag off and stops its rollout.
487
+
488
+ `pmos ai off` stops the rollout too.
489
+
490
+ The command refuses these cases:
491
+
492
+ - The repository has no git identity of its own. Set it once with `pmos git-identity set`. PMOS never guesses who commits.
493
+ - The change touches a PMOS record, CI or the agent rules: `pmos/`, `.github/`, `planning/initiatives/`, `CLAUDE.md`, `AGENTS.md`.
494
+ - `propose` without `--evidence`. The check comes before the pull request.
495
+ - `open` inside a role run. PMOS or you open the pull request, never the Builder's run.
496
+ - `open` without `gh`. The branch is pushed, and the command tells you to open the pull request on your Git host.
497
+
498
+ PMOS never pushes to the default branch and never merges. Every command takes `--json` and `--root <dir>`.
499
+
440
500
  ### pmos jira
441
501
 
442
502
  [Jira tickets](jira.md) explains each step with its examples.
@@ -135,7 +135,7 @@ The writer makes the record in `planning/initiatives/<id>.md` with its type, tit
135
135
  **New initiative** asks for one kind of work. PMOS works out the rest from it.
136
136
 
137
137
  - **Product.** Product management. You decide what to build and whether it worked. Engineers build it, and PMOS writes the specs.
138
- - **Full SDLC.** From idea to shipped. Where a factory runs in the repository, PMOS also builds it, as pull requests that you merge. Elsewhere PMOS writes the done test and the pull request plan, and the team's agents build it. A factory runs where the repository has `planning/work-items.jsonl` and `scripts/verify-work.js`. A repository made with `create-pmos` has no factory yet.
138
+ - **Full SDLC.** From idea to shipped. Where a factory runs in the repository, PMOS also builds it, as pull requests. The product's guardrail check merges the safe ones and leaves the rest for you. Elsewhere PMOS writes the done test and the pull request plan, and the team's agents build it. A factory runs where the repository has `planning/work-items.jsonl` and `scripts/verify-work.js`. A repository made with `create-pmos` has no factory yet.
139
139
  - **Project.** Project management. Others do the work. PMOS chases, syncs the dates and reports.
140
140
 
141
141
  PMOS picks a kind from the name as you type, and a blue line says so. Tap another kind to change it. After you tap a kind, PMOS does not change it. When the name gives no hint, the kind is Product.
@@ -257,6 +257,7 @@ PMOS sets these in the environment of a terminal session or a background run. Do
257
257
  | `PMOS_SHARE_PARENT` | The process id of the workspace server, so the share server stops with it. | none | — |
258
258
  | `PMOS_AI_RUN` | Set inside an AI run, so the run cannot change its own switch. | none | — |
259
259
  | `PMOS_VERIFY_RUN` | Set inside a verifier run: the one run its verdict may be recorded for, never the builder's own session. | none | — |
260
+ | `PMOS_BUILD_DIR` | The folder where `pmos build claim` makes each work item's worktree, outside the repository. | `~/.pmos/build` | — |
260
261
  | `PMOS_TEAM_FILE`, `PMOS_TEAM_ROOT`, `PMOS_TEAM_WS`, `PMOS_TEAM_ROLE`, `PMOS_TEAM_RUN`, `PMOS_TEAM_INI`, `PMOS_TEAM_MODE` | Set inside a role agent's run: its ledger, product folder, workspace, role, run, initiative, and whether it proposes or applies (`auto`). | none | — |
261
262
  | `PMOS_GRILL_FILE`, `PMOS_GRILL_LOG`, `PMOS_GRILL_ROOT`, `PMOS_GRILL_BOARD`, `PMOS_GRILL_INI`, `PMOS_GRILL_RUN`, `PMOS_GRILL_BUDGET`, `PMOS_GRILL_WS` | Pin a grill run to its ledger, log, repository, board, initiative, run id and budget. No command reads `PMOS_GRILL_WS`. | none | — |
262
263
  | `PMOS_PROPOSE_FILE`, `PMOS_PROPOSE_BOARD`, `PMOS_PROPOSE_INI`, `PMOS_PROPOSE_RUN`, `PMOS_PROPOSE_WS` | Pin a proposal run to its ledger, board, initiative and run id. No command reads `PMOS_PROPOSE_WS`. | none | — |
@@ -101,12 +101,18 @@ const TEAM = Object.freeze({
101
101
  comms: role('comms', { cls: 'B', runs: true, skills: ['stakeholder-update', 'weekly-update'], budget: 2,
102
102
  owns: { paths: ['planning/reports/'], verbs: ['pmos report draft'] }, reads: ['planning/', 'the reports'], triggers: [{ on: 'asked' }],
103
103
  connectors: ['docs'], what: 'reports and drafts; sending is class C' }),
104
- build: role('build', { cls: 'C', runs: false, skills: ['builder'], budget: 0, owns: { paths: [] }, reads: ['planning/prd/', 'planning/evals/'],
104
+ /* The Builder (launch simulation W7, kit-factory-builder). It runs only where a factory runs (lib/work-kind.js factoryRuns; team-cli refuses
105
+ * a dispatch elsewhere) and only when dispatched. Class C: it claims a declared work item, builds it in a worktree of its own, commits and
106
+ * FILES "Open a draft pull request" under the ✦ (lib/build-engine.js). The push and the PR wait for the PM's ✓; it holds no push, no gh and
107
+ * no merge (the lethal-trifecta audit in kit/AGENTS.md). It writes no repository path of the PM's checkout: its Write and Edit reach its
108
+ * worktrees only (toolsOf). */
109
+ build: role('build', { cls: 'C', runs: true, skills: ['builder'], budget: 2,
110
+ owns: { paths: [], verbs: ['pmos build next', 'pmos build claim', 'pmos build propose', 'pmos build status'] }, reads: ['planning/prd/', 'planning/evals/', 'the work items'],
105
111
  triggers: [{ on: 'asked' }], connectors: [],
106
- what: 'pull requests (the factory, propose-only, D65: it opens them and never merges); never a run of this team' }),
112
+ what: 'draft pull requests for declared work items (the factory, D65: it files them for your ✓ and never merges)' }),
107
113
  });
108
114
  /* The order roles hand off in. A dispatch keeps this order whatever roles it picks. */
109
- const ORDER = Object.freeze(['strategy', 'research', 'spec', 'design', 'eval', 'delivery', 'comms']);
115
+ const ORDER = Object.freeze(['strategy', 'research', 'spec', 'design', 'eval', 'delivery', 'comms', 'build']);
110
116
 
111
117
  const roleOf = (key) => TEAM[String(key || '')] || null;
112
118
 
@@ -224,7 +230,8 @@ function planDispatch({ kind = 'initiative', facts = {}, roles = null } = {}) {
224
230
  let pick;
225
231
  if (Array.isArray(roles) && roles.length) {
226
232
  pick = roles.map(String).filter((k) => TEAM[k] && TEAM[k].runs);
227
- if (pick.length && !pick.includes('eval') && pick.some((k) => k !== 'eval')) pick.push('eval');
233
+ // the Builder's work is checked by the product's own CI on its draft PR, not by the Evaluator (W7)
234
+ if (pick.length && !pick.includes('eval') && pick.some((k) => k !== 'eval' && k !== 'build')) pick.push('eval');
228
235
  } else if (kind === 'goal') {
229
236
  pick = ['strategy', 'research', 'eval'];
230
237
  } else {
@@ -245,6 +252,14 @@ function toolsOf(r, { root = null, mode = 'propose' } = {}) {
245
252
  const writePaths = [];
246
253
  if (!ro) return { tools, writePaths };
247
254
  if (ro.key === 'eval') tools.push('Bash(pmos team verdict *)');
255
+ if (ro.key === 'build') {
256
+ // W7: its verbs and read-only git in any mode, and Write/Edit in its worktrees only. No git push, no gh, no merge: the outward step
257
+ // (pmos build open) is the PM's ✓, and it refuses a role run anyway.
258
+ for (const v of ro.owns.verbs) tools.push(`Bash(${v} *)`);
259
+ tools.push('Bash(git status *)', 'Bash(git diff *)');
260
+ writePaths.push(path.join(process.env.PMOS_BUILD_DIR || path.join(require('os').homedir(), '.pmos', 'build')) + '/');
261
+ return { tools, writePaths };
262
+ }
248
263
  if (mode === 'auto') {
249
264
  tools.push('Bash(pmos team wrote *)');
250
265
  for (const v of ro.owns.verbs) if (v !== 'pmos team verdict') tools.push(`Bash(${v} *)`);
@@ -119,7 +119,10 @@ function classOfProposal(p) {
119
119
  if (!isObj(p)) return 'C';
120
120
  const c = PROPOSAL_CLASS[p.group] || 'C';
121
121
  if (p.group === 'status' && (p.items || []).some((x) => x && x.jira)) return 'C';
122
- if (p.group === 'outcome' && p.type === 'refuted') return 'C'; // stopping or replacing an experiment is the PM's call (launch simulation W2)
122
+ if (p.group === 'outcome' && p.type === 'refuted') return 'C';
123
+ // D108 as amended 2026-11-16 (Wawan: "Open them automatically"): the factory's pull request opens by itself, from the server (never the
124
+ // Builder's run), and Undo closes it. The guardrail and CI decide merge or review. `pmos ai off` or a demotion returns it to the ✓.
125
+ if (p.group === 'build') return 'B'; // stopping or replacing an experiment is the PM's call (launch simulation W2)
123
126
  // a maybe, or a duplicate already in another initiative (type link, or an item with `other`), is a question for the PM, not a change
124
127
  // found type stage moves the initiative's stage: a stage move is C (as the Driver's `move`)
125
128
  if (p.group === 'found' && (p.type === 'stage' || p.type === 'maybe' || p.type === 'link' || (p.items || []).some((x) => x && x.other))) return 'C';
@@ -0,0 +1,120 @@
1
+ 'use strict';
2
+ /* build-cli.js — `pmos build`: the factory's Builder in this repository (launch simulation W7, initiative kit-factory-builder).
3
+ * The engine is lib/build-engine.js; this file parses and prints. Guide page: guide/cli.md.
4
+ *
5
+ * pmos build next [<initiative>] [--json] the declared work items no Builder has taken
6
+ * pmos build claim <item> [--json] claim one, on a new branch pmos/<item> in a worktree of its own
7
+ * pmos build propose <item> "<what it does>" --evidence "<the check that passed>" [--json]
8
+ * commit, mark verified, and file "Open a draft pull request" under the ✦
9
+ * pmos build open <item> [--json] the PM only: push the branch and open the DRAFT pull request
10
+ * pmos build status [--json] every work item, its branch and whether its worktree is here
11
+ * pmos build policy <item> [--json] what the merge guardrail reads for it now: auto or human, and why (D108)
12
+ * pmos build rollout [<item> [--to <percent>]] [--json] no item: where every flag stands; an item: the PM's own next step
13
+ * pmos build rollback <item> [--json] undo a rollout: the item's flag to 0
14
+ * common: [--root <dir>]
15
+ *
16
+ * `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
17
+ * are off. A role run (PMOS_TEAM_RUN set) cannot run it: the push comes from PMOS, never from the Builder's own run. Nothing here merges: the product's pmos-guardrail check turns on auto-merge for a pull request it
18
+ * reads AUTO (D108; lib/build-engine.js mergePolicy previews it). The flag rollout runs by itself (lib/factory-rollout.js).
19
+ * Exit codes: 0 done, 1 refused, 2 usage.
20
+ */
21
+ const path = require('path');
22
+ const { execFileSync } = require('child_process');
23
+ const BE = require('./build-engine.js');
24
+
25
+ const COMMANDS = { build: ['next', 'claim', 'propose', 'open', 'status', 'policy', 'rollout', 'rollback'] };
26
+ const USAGE = [
27
+ 'usage: pmos build next|claim|propose|open|status|policy|rollout|rollback — the Builder: PMOS builds a declared work item as a pull request',
28
+ ' pmos build next [<initiative>] the declared work items no Builder has taken',
29
+ ' pmos build claim <item> claim one; PMOS makes the branch pmos/<item> in a worktree outside this folder',
30
+ ' pmos build propose <item> "<what it does>" --evidence "<the check that passed>"',
31
+ ' commit it and file "Open a draft pull request" under the initiative\'s ✦',
32
+ ' pmos build open <item> you only (the ✓ runs it): push pmos/<item> and open the draft pull request',
33
+ ' pmos build status every work item and its branch',
34
+ ' pmos build policy <item> auto or human: whether its pull request merges by itself, and why',
35
+ ' pmos build rollout [<item> [--to <percent>]] where every flag stands; with an item, take its flag to the next step',
36
+ ' pmos build rollback <item> turn the item\'s flag off and stop its rollout',
37
+ 'every command: [--json] [--root <dir>]. PMOS never merges: the product\'s pmos-guardrail check turns on auto-merge, or you merge.',
38
+ ];
39
+
40
+ function parse(argv) {
41
+ const pos = [], flags = {};
42
+ for (let i = 0; i < argv.length; i++) {
43
+ const a = argv[i];
44
+ if (!a.startsWith('--')) { pos.push(a); continue; }
45
+ const k = a.slice(2);
46
+ if (k === 'json') { flags.json = true; continue; }
47
+ const v = argv[i + 1];
48
+ if (v === undefined || v.startsWith('--')) flags[k] = ''; else { flags[k] = v; i++; }
49
+ }
50
+ return { pos, flags };
51
+ }
52
+ function repoRoot(cwd) {
53
+ try { return execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || cwd; }
54
+ catch { return cwd; }
55
+ }
56
+
57
+ async function run(argv, { say = (s) => console.log(s), env = process.env, cwd = process.cwd() } = {}) {
58
+ const args = argv[0] === 'build' ? argv.slice(1) : argv.slice();
59
+ const verb = args[0];
60
+ if (!verb || ['help', '--help', '-h'].includes(verb)) { for (const l of USAGE) say(l); return verb ? 0 : 1; }
61
+ if (!COMMANDS.build.includes(verb)) { say(`unknown build command "${verb}" — one of ${COMMANDS.build.join(', ')}`); return 2; }
62
+ const { pos, flags } = parse(args.slice(1));
63
+ const json = !!flags.json;
64
+ // a role run works in its worktree, so the repository is the one the server pinned (PMOS_TEAM_ROOT), not the worktree
65
+ const root = flags.root ? path.resolve(cwd, flags.root) : env.PMOS_TEAM_ROOT || repoRoot(cwd);
66
+ const fail = (error, code = 1) => { say(json ? JSON.stringify({ ok: false, error }) : `✗ ${error}`); return code; };
67
+ const ok = (obj, text) => { say(json ? JSON.stringify({ ok: true, ...obj }) : text); return 0; };
68
+ 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');
69
+
70
+ if (verb === 'next' || verb === 'status') {
71
+ const list = verb === 'next' ? BE.next(root, pos[0]) : BE.status(root);
72
+ if (json) return ok({ items: list });
73
+ if (!list.length) { say(verb === 'next' ? 'No declared work item waits for a Builder.' : 'No work items.'); return 0; }
74
+ 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)' : ''}`);
75
+ return 0;
76
+ }
77
+ if (verb === 'rollout' && !pos[0]) {
78
+ const list = require('./factory-rollout.js').statusOf(root);
79
+ if (json) return ok({ flags: list });
80
+ if (!list.length) { say('No flag is rolling out.'); return 0; }
81
+ for (const x of list) say(`${x.item} ${x.flag} ${x.percent}% ${x.step} ${x.why || ''}`);
82
+ return 0;
83
+ }
84
+ const item = pos[0];
85
+ if (!item) return fail(`usage: pmos build ${verb} <item>`, 2);
86
+ if (verb === 'policy') {
87
+ const it = BE.itemsOf(root).find((x) => x.item_id === item);
88
+ if (!it) return fail(`${item} is not a work item here`);
89
+ const p = BE.mergePolicy(root, it, { env });
90
+ return ok({ item, ...p }, `${p.verdict === 'auto' ? 'AUTO' : 'HUMAN'} ${item}: ${p.why}`);
91
+ }
92
+ if (verb === 'rollout' || verb === 'rollback') {
93
+ 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');
94
+ const FR = require('./factory-rollout.js');
95
+ const r = verb === 'rollout' ? FR.rollout(root, item, { to: flags.to !== undefined && flags.to !== '' ? Number(flags.to) : null, env }) : FR.rollback(root, item, { env });
96
+ if (!r.ok) return fail(r.error);
97
+ return ok(r, `✓ ${r.flag} is at ${r.percent}%${verb === 'rollback' ? '. Its rollout stops until you run pmos build rollout ' + item : ''}`);
98
+ }
99
+ if (verb === 'claim') {
100
+ const agent = env.PMOS_TEAM_RUN ? `pmos:builder:${env.PMOS_TEAM_RUN}` : 'pmos:builder';
101
+ const r = BE.claim(root, item, { agent });
102
+ if (!r.ok) return fail(r.error);
103
+ return ok(r, `✓ claimed ${item} on ${r.branch} (from ${r.base}). Work only in ${r.worktree}. When its check passes: pmos build propose ${item} "<what it does>" --evidence "<the check>"`);
104
+ }
105
+ if (verb === 'propose') {
106
+ const summary = pos.slice(1).join(' ');
107
+ if (!summary) return fail(`usage: pmos build propose ${item} "<what it does>" --evidence "<the check that passed>"`, 2);
108
+ const r = BE.propose(root, item, { summary, evidence: flags.evidence || '', run: env.PMOS_TEAM_RUN || null });
109
+ if (!r.ok) return fail(r.error);
110
+ 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.`);
111
+ }
112
+ if (verb === 'open') {
113
+ const r = BE.open(root, item, { env });
114
+ if (!r.ok) return fail(r.error);
115
+ return ok(r, `✓ opened a draft pull request from ${r.branch} into ${r.base}${r.url ? ': ' + r.url : ''}. ${r.policy.why}`);
116
+ }
117
+ return fail('unknown command', 2);
118
+ }
119
+
120
+ module.exports = { run, COMMANDS, USAGE };