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.
- package/package.json +27 -27
- package/payload/AGENTS.md +12 -0
- package/payload/KIT-VERSION +2 -2
- package/payload/planning/evals/eval-calibration.md +1 -1
- package/payload/planning/okrs/health-budgets.md +1 -1
- package/payload/planning/work-items.jsonl +0 -0
- package/payload/scripts/factory-guardrail.js +267 -0
- package/payload/scripts/lib/sink.js +321 -0
- package/payload/scripts/verify-work.js +149 -0
- package/payload/scripts/work-item.js +1484 -0
- package/payload/state/discoveries.md +1 -1
- package/payload/state/log.md +1 -1
- package/payload/templates/pmos-guardrail.yml +61 -0
- package/workspace/changelog.json +26 -0
- package/workspace/guide/cli.md +61 -1
- package/workspace/guide/initiatives-and-next-steps.md +1 -1
- package/workspace/guide/settings-and-switches.md +1 -0
- package/workspace/lib/agent-team.js +19 -4
- package/workspace/lib/autonomy.js +4 -1
- package/workspace/lib/build-cli.js +120 -0
- package/workspace/lib/build-engine.js +267 -0
- package/workspace/lib/factory-rollout.js +190 -0
- package/workspace/lib/headless.js +3 -1
- package/workspace/lib/pmos-verbs.js +3 -0
- package/workspace/lib/proposals.js +15 -4
- package/workspace/lib/routes-proposals.js +14 -3
- package/workspace/lib/team-cli.js +3 -1
- package/workspace/lib/team-runs.js +4 -0
- package/workspace/lib/verify-runs.js +17 -1
- package/workspace/lib/verify-work-cli.js +4 -2
- package/workspace/lib/work-kind.js +12 -6
- package/workspace/package-lock.json +2 -2
- package/workspace/package.json +1 -1
- package/workspace/public/pm/ini-props.js +3 -1
- package/workspace/test-lists/build-engine.json +11 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "create-pmos",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.571.0",
|
|
4
4
|
"description": "Scaffold the PMOS portable kit — run the PMOS product-management workflow (initiative → lane-fit spec → contract → build → three gates, with work-type lanes for features, research, maintenance, incidents, and content) entirely inside your own repo, with all state as git-versioned files. Includes `workflow-sweep`, which audits the state every board derives from and separates real defects from work you simply have not done. `create-pmos workspace` also installs + launches the local Terminal Workspace GUI. No database, no network, no telemetry.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"bin": {
|
|
@@ -33,6 +33,32 @@
|
|
|
33
33
|
"audit"
|
|
34
34
|
],
|
|
35
35
|
"pmosChanges": [
|
|
36
|
+
{
|
|
37
|
+
"v": "0.571.0",
|
|
38
|
+
"at": "2026-11-16T04:26:43.356Z",
|
|
39
|
+
"f": 4,
|
|
40
|
+
"prs": [
|
|
41
|
+
{
|
|
42
|
+
"n": 1303,
|
|
43
|
+
"t": "The factory merges behind a guardrail, and rolls out behind a flag",
|
|
44
|
+
"s": "The factory merges behind a guardrail, and rolls out behind a flag",
|
|
45
|
+
"k": "new"
|
|
46
|
+
}
|
|
47
|
+
]
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
"v": "0.570.0",
|
|
51
|
+
"at": "2026-11-15T17:32:20.370Z",
|
|
52
|
+
"f": 4,
|
|
53
|
+
"prs": [
|
|
54
|
+
{
|
|
55
|
+
"n": 1302,
|
|
56
|
+
"t": "The real build engine for Full SDLC (launch simulation W7)",
|
|
57
|
+
"s": "The real build engine for Full SDLC (launch simulation W7)",
|
|
58
|
+
"k": "new"
|
|
59
|
+
}
|
|
60
|
+
]
|
|
61
|
+
},
|
|
36
62
|
{
|
|
37
63
|
"v": "0.569.0",
|
|
38
64
|
"at": "2026-11-15T17:07:37.237Z",
|
|
@@ -284,32 +310,6 @@
|
|
|
284
310
|
"k": "fix"
|
|
285
311
|
}
|
|
286
312
|
]
|
|
287
|
-
},
|
|
288
|
-
{
|
|
289
|
-
"v": "0.551.0",
|
|
290
|
-
"at": "2026-11-10T11:25:58.991Z",
|
|
291
|
-
"f": 4,
|
|
292
|
-
"prs": [
|
|
293
|
-
{
|
|
294
|
-
"n": 1279,
|
|
295
|
-
"t": "Intent card on the product page; the Board by goal, and a Next column that says what Claude does next",
|
|
296
|
-
"s": "Intent card on the product page; the Board by goal, and a Next column that says what Claude does next",
|
|
297
|
-
"k": "new"
|
|
298
|
-
}
|
|
299
|
-
]
|
|
300
|
-
},
|
|
301
|
-
{
|
|
302
|
-
"v": "0.550.0",
|
|
303
|
-
"at": "2026-11-10T08:31:44.572Z",
|
|
304
|
-
"f": 4,
|
|
305
|
-
"prs": [
|
|
306
|
-
{
|
|
307
|
-
"n": 1278,
|
|
308
|
-
"t": "Run PMOS on an always-on cloud server — one paste on the Mac moves it, the Mac stays as the fallback",
|
|
309
|
-
"s": "Run PMOS on an always-on cloud server — one paste on the Mac moves it, the Mac stays as the fallback",
|
|
310
|
-
"k": "new"
|
|
311
|
-
}
|
|
312
|
-
]
|
|
313
313
|
}
|
|
314
314
|
]
|
|
315
315
|
}
|
package/payload/AGENTS.md
CHANGED
|
@@ -119,6 +119,18 @@ When an initiative is bigger than one run, break it into **tickets** — the pla
|
|
|
119
119
|
|
|
120
120
|
Before creating any new agent path or widening a tool grant, verify it does **not** hold all three of: **private data access + untrusted-content exposure + external communication**. An agent holding all three can be tricked by content it reads into exfiltrating what it knows — remove a leg (preferably external communication) structurally; prompt-level defenses alone are bypassed by adaptive attacks. If a path genuinely needs all three, its PRD/brief must name the compensating gate; silence is not a pass. The evaluator is the standing example: it reads adversarial diffs, so it stays read-only with its verdict append as the only write.
|
|
121
121
|
|
|
122
|
+
### The Builder (the D65 factory in this repository)
|
|
123
|
+
|
|
124
|
+
This kit carries the factory: `pmos/scripts/work-item.js` (the one writer of `pmos/planning/work-items.jsonl`) and `pmos/scripts/verify-work.js`. With the PMOS workspace installed, `pmos build` is the Builder:
|
|
125
|
+
|
|
126
|
+
1. `pmos build claim <item>` claims one declared work item. The work happens on a new branch `pmos/<item>`, in a worktree outside the repository folder.
|
|
127
|
+
2. `pmos build propose <item> "<what it does>" --evidence "<the check that passed>"` commits with the repository's own git identity (`pmos git-identity`) and the line `Work-Item: <item>`, marks the item verified, and files "Open a draft pull request" for the PM.
|
|
128
|
+
3. PMOS opens the pull request by itself (D108): the workspace applies the proposal, pushes the one branch and runs `gh pr create --draft`. Undo closes it. With `pmos ai off` it waits for the PM's ✓. The Builder's own run never pushes.
|
|
129
|
+
4. Who merges is the product's own check, `pmos-guardrail` (copy `pmos/templates/pmos-guardrail.yml` to `.github/workflows/`; D108). It runs the default branch's `pmos/scripts/factory-guardrail.js` on the pull request's diff and reads AUTO or HUMAN. On AUTO it turns on GitHub auto-merge with the workflow's own token, so GitHub merges when every required check is green. On HUMAN the PM merges. The triggers that always read HUMAN are listed in that script and in the workspace guide (`pmos build policy <item>` shows the answer).
|
|
130
|
+
5. After the merge, `pmos verify-work` marks the item integrated, and the item's flag rolls out 5% → 50% → 100% through the commands in `pmos/factory.json`. A metric over its budget turns the flag off, opens a revert pull request and puts the factory back to propose-only for 7 days.
|
|
131
|
+
|
|
132
|
+
The audit for this path: a Builder run reads private code and untrusted content, so it holds no outward channel. It has no `git push`, no `gh` and no merge, and `pmos build open` refuses a role run. A commit that touches `pmos/`, `.github/`, `CLAUDE.md` or `AGENTS.md` is refused. The guardrail workflow holds a write token and reads untrusted content (the diff), so it never runs the pull request's code: `pull_request_target` runs the default branch's workflow and script, and the head is only fetched and diffed. A pull request that changes CI, the guardrail or its own tests reads HUMAN. The compensating gate is the product's own CI and branch protection on the default branch: protect it, and make your CI required, before you use the guardrail.
|
|
133
|
+
|
|
122
134
|
## Escalation (stop and ask the PM)
|
|
123
135
|
|
|
124
136
|
An architectural choice with no recorded decision; a wrong or unsatisfiable contract; scope growth; any destructive/irreversible action; anything that would send product data outside this repo's remote. Confirm-first regardless of framing.
|
package/payload/KIT-VERSION
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
kernel-source: pmos@
|
|
2
|
-
assembled: 2026-11-
|
|
1
|
+
kernel-source: pmos@f2bfbfa4
|
|
2
|
+
assembled: 2026-11-16
|
|
3
3
|
mode: vendor
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
type: Reference
|
|
3
3
|
title: "Eval calibration log"
|
|
4
4
|
description: "Append-only record of every PM override of an evaluator verdict."
|
|
5
|
-
generated: {by: process:create-pmos, at: "2026-11-
|
|
5
|
+
generated: {by: process:create-pmos, at: "2026-11-16T04:26:40Z"}
|
|
6
6
|
status: stable
|
|
7
7
|
---
|
|
8
8
|
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
type: Reference
|
|
3
3
|
title: "Health budgets"
|
|
4
4
|
description: "Closed registry of health-budget anchors (D59), edited only by the PM."
|
|
5
|
-
generated: {by: process:create-pmos, at: "2026-11-
|
|
5
|
+
generated: {by: process:create-pmos, at: "2026-11-16T04:26:40Z"}
|
|
6
6
|
status: stable
|
|
7
7
|
---
|
|
8
8
|
|
|
File without changes
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
/* factory-guardrail.js — when a factory pull request may merge with no person (D108, initiative factory-guardrail-merge).
|
|
4
|
+
*
|
|
5
|
+
* Deterministic: it reads the diff, the work item and git history. No model call, no network except the two gh calls below.
|
|
6
|
+
* It is vendored with the factory into the kit (pmos/scripts/), and the product repository's workflow `pmos-guardrail`
|
|
7
|
+
* (kit/templates/pmos-guardrail.yml, on pull_request_target) runs THE DEFAULT BRANCH'S COPY of this file on the pull request's
|
|
8
|
+
* diff. The pull request's own code never runs, so a pull request cannot rewrite the rule that judges it.
|
|
9
|
+
*
|
|
10
|
+
* classify({ cwd, base, head, branch, body, ledgerText, now }) → { factory, item, verdict: 'auto'|'human'|'none', reasons, files }
|
|
11
|
+
*
|
|
12
|
+
* `none` not a factory pull request (no branch pmos/<item> and no line `Work-Item: <id>`): PMOS does nothing.
|
|
13
|
+
* `auto` ALL of: the item is verified in the default branch's ledger; every changed file is inside the item's declared scope;
|
|
14
|
+
* the change sits behind the item's flag (its name appears in the added lines) or the item is declared with no
|
|
15
|
+
* user-facing effect; and no trigger below fires. Required CI is GitHub's part: auto-merge waits for every required check.
|
|
16
|
+
* `human` any trigger, or any `auto` condition missing. Every reason is named.
|
|
17
|
+
*
|
|
18
|
+
* TRIGGERS (any one → human): migrations or data deletion · auth, permissions, payments, personal data or secrets · CI, gates,
|
|
19
|
+
* the guardrail, PMOS records or branch protection · a new dependency (a manifest line or a lock file) · a public API or contract ·
|
|
20
|
+
* anything sent outward · a new agent path · a changed existing test, test configuration or the item's own check reference ·
|
|
21
|
+
* the D11 triggers: the item failed before, a revert on the default branch in the last 14 days, a subsystem untouched 90 days ·
|
|
22
|
+
* the line `PMOS-Merge: human` (PMOS writes it when autonomy is off or the factory is demoted; the PM may add it to stop a merge) ·
|
|
23
|
+
* a pull request from a fork (a branch named pmos/… elsewhere is not PMOS's).
|
|
24
|
+
*
|
|
25
|
+
* CLI (the workflow's one step):
|
|
26
|
+
* node pmos/scripts/factory-guardrail.js --base <ref> --head <ref> [--branch <name>] [--body-file <f>] [--head-repo o/r --base-repo o/r] [--json]
|
|
27
|
+
* [--github --pr <number>] in GitHub Actions only: write verdict to GITHUB_OUTPUT and the step summary; on auto run
|
|
28
|
+
* `gh pr ready` and `gh pr merge --auto --squash` with the workflow's own token; on human turn
|
|
29
|
+
* auto-merge off. The agent never runs this: the Builder has no node, gh or push.
|
|
30
|
+
* Exit 0 for every verdict (the check reports, it does not block). A failure to read anything is `human`, never `auto`.
|
|
31
|
+
*/
|
|
32
|
+
const fs = require('fs');
|
|
33
|
+
const path = require('path');
|
|
34
|
+
const cp = require('child_process');
|
|
35
|
+
|
|
36
|
+
const DAY = 86400000;
|
|
37
|
+
const REVERT_DAYS = 14;
|
|
38
|
+
const STALE_DAYS = 90;
|
|
39
|
+
const ITEM_RE = /^[a-z0-9][a-z0-9_-]*\.[0-9]+$/;
|
|
40
|
+
|
|
41
|
+
/* ---- the trigger list. Paths are matched lower case on their segments, so "controller" is not "role". ---- */
|
|
42
|
+
const seg = (f) => String(f).toLowerCase().split(/[\/._-]+/).filter(Boolean);
|
|
43
|
+
const segHas = (f, words) => seg(f).some((s) => words.includes(s));
|
|
44
|
+
const SENSITIVE = ['auth', 'authn', 'authz', 'oauth', 'login', 'logout', 'signin', 'session', 'sessions', 'permission', 'permissions', 'rbac', 'acl',
|
|
45
|
+
'role', 'roles', 'payment', 'payments', 'billing', 'stripe', 'checkout', 'invoice', 'invoices', 'pii', 'gdpr', 'privacy', 'secret', 'secrets',
|
|
46
|
+
'credential', 'credentials', 'password', 'passwords', 'vault', 'kms', 'env', 'keystore'];
|
|
47
|
+
const MIGRATION = ['migration', 'migrations', 'migrate', 'alembic', 'flyway', 'liquibase', 'sql'];
|
|
48
|
+
const API = ['openapi', 'swagger', 'proto', 'graphql', 'gql', 'wsdl'];
|
|
49
|
+
const AGENT_PATH = ['agents', 'claude', 'prompts', 'prompt', 'skills', 'mcp'];
|
|
50
|
+
const MANIFESTS = ['requirements.txt', 'requirements-dev.txt', 'pyproject.toml', 'pipfile', 'setup.py', 'setup.cfg', 'go.mod', 'cargo.toml', 'gemfile',
|
|
51
|
+
'pom.xml', 'build.gradle', 'build.gradle.kts', 'composer.json', 'mix.exs', 'pubspec.yaml', 'package.swift', 'podfile', 'deno.json'];
|
|
52
|
+
const LOCKS = ['package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock', 'pnpm-lock.yaml', 'bun.lockb', 'poetry.lock', 'pipfile.lock', 'cargo.lock',
|
|
53
|
+
'go.sum', 'gemfile.lock', 'composer.lock', 'mix.lock', 'pubspec.lock', 'podfile.lock', 'uv.lock'];
|
|
54
|
+
const TEST_CONFIG = /(^|\/)(jest|vitest|playwright|cypress|karma|mocha|ava|babel|tsconfig)[^/]*\.(js|cjs|mjs|ts|json)$|(^|\/)(\.mocharc[^/]*|pytest\.ini|tox\.ini|conftest\.py|\.nycrc[^/]*|phpunit\.xml[^/]*)$/;
|
|
55
|
+
const TEST_FILE = /(^|\/)(tests?|__tests__|specs?|e2e|testdata|fixtures|__snapshots__)\//;
|
|
56
|
+
const TEST_NAME = /\.(test|spec)\.[a-z0-9]+$|_test\.(go|py|rb)$|(^|\/)test_[^/]*\.py$|\.snap$/;
|
|
57
|
+
const CI = /^(\.github\/|\.gitlab-ci\.yml$|\.gitlab\/|\.circleci\/|\.buildkite\/|\.drone\.yml$|azure-pipelines|bitbucket-pipelines\.yml$|jenkinsfile$|\.travis\.yml$|codeowners$|docs\/codeowners$|\.pre-commit-config\.yaml$|\.husky\/|lefthook\.yml$|pmos\/|\.pmos-profile$)/;
|
|
58
|
+
const GUARD_NAME = /(^|\/)(factory-guardrail\.js|pmos-guardrail\.ya?ml)$/;
|
|
59
|
+
const AGENT_FILES = /(^|\/)(agents\.md|claude\.md|gemini\.md|\.cursorrules|\.claude\/|\.cursor\/|\.codex\/)/;
|
|
60
|
+
|
|
61
|
+
const ADDED = [
|
|
62
|
+
{ rule: 'data-deletion', re: /\b(drop\s+(table|column|database|schema|index)|truncate\s+(table\s+)?\w|delete\s+from\s|alter\s+table\b[^;]*\bdrop\b)/i, why: 'deletes data or changes a schema' },
|
|
63
|
+
{ rule: 'data-deletion', re: /\.(deleteMany|dropCollection|dropDatabase|drop_table|remove_column|drop_column)\s*\(|\brm\s+-rf?\s+\//, why: 'deletes data' },
|
|
64
|
+
{ rule: 'secrets', re: /(api[_-]?key|secret[_-]?key|client[_-]?secret|private[_-]?key|access[_-]?token|auth[_-]?token|password\s*[:=]|BEGIN [A-Z ]*PRIVATE KEY|aws_secret|xox[abp]-|gh[pousr]_[A-Za-z0-9]{20,}|sk-[A-Za-z0-9]{20,})/i, why: 'names a secret or a credential' },
|
|
65
|
+
{ rule: 'outward', re: /\b(fetch\s*\(|axios\b|XMLHttpRequest|https?\.request\s*\(|https?\.get\s*\(|new\s+WebSocket\s*\(|navigator\.sendBeacon|sendMail|nodemailer|smtplib|smtp\b|webhook|twilio|sendgrid|mailgun|requests\.(get|post|put|delete|patch)\s*\(|urllib\.request|net\/http|http\.Post|curl\s|wget\s)/i, why: 'sends something outward' },
|
|
66
|
+
{ rule: 'agent-path', re: /(@anthropic-ai\/|\banthropic\b|\bopenai\b|\bclaude\s+-p\b|\blangchain\b|\bllm\b|child_process|\bexecSync\s*\(|\bexecFile(Sync)?\s*\(|\bspawn(Sync)?\s*\(|\beval\s*\(|new\s+Function\s*\(|subprocess\.|os\.system\s*\()/i, why: 'adds a model call or runs a program (a new agent path)' },
|
|
67
|
+
];
|
|
68
|
+
|
|
69
|
+
function git(cwd, args) {
|
|
70
|
+
const r = cp.spawnSync('git', args, { cwd, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, env: { ...process.env, GIT_TERMINAL_PROMPT: '0' } });
|
|
71
|
+
return { ok: !r.error && r.status === 0, out: String(r.stdout || ''), err: String(r.stderr || (r.error && r.error.message) || '').trim() };
|
|
72
|
+
}
|
|
73
|
+
const one = (s, n) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim().slice(0, n);
|
|
74
|
+
|
|
75
|
+
/** The ledger as the base has it: `git show <base>:<path>`, so a local preview reads exactly what CI reads. */
|
|
76
|
+
function baseLedger(cwd, base) {
|
|
77
|
+
const top = git(cwd, ['rev-parse', '--show-toplevel']).out.trim() || cwd;
|
|
78
|
+
const file = path.join(__dirname, '..', 'planning', 'work-items.jsonl');
|
|
79
|
+
const rel = path.relative(top, file).split(path.sep).join('/');
|
|
80
|
+
if (!rel.startsWith('..')) { const r = git(top, ['show', `${base}:${rel}`]); if (r.ok) return { text: r.out, rel }; }
|
|
81
|
+
return { text: null, rel };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Files and added lines of base...head (three dots: what the pull request adds to its merge base). */
|
|
85
|
+
function diffOf(cwd, base, head) {
|
|
86
|
+
const ns = git(cwd, ['diff', '--name-status', '-M', '--no-color', `${base}...${head}`]);
|
|
87
|
+
if (!ns.ok) return { error: `git could not diff ${base}...${head}: ${one(ns.err, 200)}` };
|
|
88
|
+
const files = [];
|
|
89
|
+
for (const l of ns.out.split('\n').filter(Boolean)) {
|
|
90
|
+
const p = l.split('\t');
|
|
91
|
+
const st = p[0][0];
|
|
92
|
+
files.push({ status: st, path: p[p.length - 1], from: st === 'R' || st === 'C' ? p[1] : null });
|
|
93
|
+
}
|
|
94
|
+
const u = git(cwd, ['diff', '-U0', '--no-color', '--no-ext-diff', `${base}...${head}`]);
|
|
95
|
+
const added = new Map();
|
|
96
|
+
let cur = null;
|
|
97
|
+
for (const l of u.out.split('\n')) {
|
|
98
|
+
if (l.startsWith('+++ ')) { cur = l.slice(4).replace(/^b\//, ''); if (!added.has(cur)) added.set(cur, []); continue; }
|
|
99
|
+
if (l.startsWith('+') && cur && cur !== '/dev/null') added.get(cur).push(l.slice(1));
|
|
100
|
+
}
|
|
101
|
+
return { files, added };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function depsOf(text) {
|
|
105
|
+
try {
|
|
106
|
+
const j = JSON.parse(text);
|
|
107
|
+
const out = new Set();
|
|
108
|
+
for (const k of ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies', 'bundledDependencies']) {
|
|
109
|
+
const v = j[k];
|
|
110
|
+
if (Array.isArray(v)) v.forEach((x) => out.add(k + ':' + x));
|
|
111
|
+
else if (v && typeof v === 'object') Object.keys(v).forEach((x) => out.add(k + ':' + x));
|
|
112
|
+
}
|
|
113
|
+
return out;
|
|
114
|
+
} catch { return null; }
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Was a merge reverted on the base lately? → days ago | null */
|
|
118
|
+
function recentRevert(cwd, base, nowMs) {
|
|
119
|
+
const r = git(cwd, ['log', `--since=${new Date(nowMs - REVERT_DAYS * DAY).toISOString()}`, '--format=%ct%x09%s', base]);
|
|
120
|
+
if (!r.ok) return null;
|
|
121
|
+
for (const l of r.out.split('\n').filter(Boolean)) {
|
|
122
|
+
const [ct, s] = l.split('\t');
|
|
123
|
+
if (/^revert\b/i.test(s || '')) return Math.max(0, Math.floor((nowMs - Number(ct) * 1000) / DAY));
|
|
124
|
+
}
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** The touched folders whose last change on the base is older than 90 days (D11: a subsystem untouched ~3 months). */
|
|
129
|
+
function staleDirs(cwd, base, files, nowMs) {
|
|
130
|
+
const dirs = [...new Set(files.filter((f) => f.status !== 'A').map((f) => path.posix.dirname(f.from || f.path)).filter((d) => d && d !== '.'))];
|
|
131
|
+
const out = [];
|
|
132
|
+
for (const d of dirs.slice(0, 40)) {
|
|
133
|
+
const r = git(cwd, ['log', '-1', '--format=%ct', base, '--', d]);
|
|
134
|
+
const ct = Number(r.out.trim());
|
|
135
|
+
if (ct && nowMs - ct * 1000 > STALE_DAYS * DAY) out.push({ dir: d, days: Math.floor((nowMs - ct * 1000) / DAY) });
|
|
136
|
+
}
|
|
137
|
+
return out;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const pathsIn = (ref) => String(ref || '').split(/\s+/).map((t) => t.replace(/^['"]|['"]$/g, '').replace(/^\.\//, '')).filter((t) => /[\/]|\.[a-z0-9]+$/i.test(t) && !t.startsWith('-'));
|
|
141
|
+
const inScope = (f, scope) => scope.some((s) => { const p = s.replace(/^\.\//, ''); return p.endsWith('/') ? f.startsWith(p) : f === p || f.startsWith(p + '/'); });
|
|
142
|
+
|
|
143
|
+
/** The verdict. Pure but for git reads in `cwd`. */
|
|
144
|
+
function classify({ cwd = process.cwd(), base, head, branch = '', body = '', ledgerText, now, headRepo = null, baseRepo = null } = {}) {
|
|
145
|
+
const nowMs = now == null ? Date.now() : (typeof now === 'number' ? now : Date.parse(now));
|
|
146
|
+
const fromBranch = /^(?:refs\/heads\/)?pmos\/(?:revert-)?([a-z0-9][a-z0-9_-]*\.[0-9]+)$/.exec(String(branch || ''));
|
|
147
|
+
const fromBody = /^Work-Item:\s*(\S+)\s*$/m.exec(String(body || ''));
|
|
148
|
+
const item = fromBranch ? fromBranch[1] : fromBody && ITEM_RE.test(fromBody[1]) ? fromBody[1] : null;
|
|
149
|
+
const isRevert = /^(?:refs\/heads\/)?pmos\/revert-/.test(String(branch || ''));
|
|
150
|
+
if (!item && !isRevert) return { factory: false, item: null, verdict: 'none', reasons: [{ rule: 'not-factory', detail: 'not a factory pull request (no branch pmos/<item>, no Work-Item line)' }], files: [] };
|
|
151
|
+
const reasons = [];
|
|
152
|
+
const human = (rule, detail) => reasons.push({ rule, detail });
|
|
153
|
+
if (isRevert) human('revert', 'a revert pull request opened by the rollout: the flag is already off, and the PM merges the revert');
|
|
154
|
+
if (headRepo && baseRepo && String(headRepo).toLowerCase() !== String(baseRepo).toLowerCase()) human('fork', `the pull request comes from ${one(headRepo, 100)}, not from this repository: PMOS pushes only here`);
|
|
155
|
+
if (/^PMOS-Merge:\s*human\s*$/mi.test(String(body || ''))) human('pmos-merge-human', 'PMOS asked for a person (autonomy is off, or the factory is back to propose-only)');
|
|
156
|
+
if (!base || !head) { human('unreadable', 'no base or head to compare'); return { factory: true, item, verdict: 'human', reasons, files: [] }; }
|
|
157
|
+
|
|
158
|
+
const d = diffOf(cwd, base, head);
|
|
159
|
+
if (d.error) { human('unreadable', d.error); return { factory: true, item, verdict: 'human', reasons, files: [] }; }
|
|
160
|
+
const files = d.files;
|
|
161
|
+
if (!files.length) human('empty', 'the pull request changes nothing');
|
|
162
|
+
|
|
163
|
+
// ---- the work item, as the default branch's ledger has it
|
|
164
|
+
let it = null;
|
|
165
|
+
const lt = ledgerText !== undefined ? { text: ledgerText } : baseLedger(cwd, base);
|
|
166
|
+
if (item) {
|
|
167
|
+
if (lt.text == null) human('no-ledger', 'the default branch has no work-item ledger');
|
|
168
|
+
else {
|
|
169
|
+
try {
|
|
170
|
+
const W = require('./work-item.js');
|
|
171
|
+
it = (W.deriveItems(lt.text, { now: new Date(nowMs).toISOString() }).items || []).find((x) => x.item_id === item) || null;
|
|
172
|
+
} catch (e) { human('unreadable', 'the ledger could not be read: ' + one(e.message, 160)); }
|
|
173
|
+
if (!it) human('not-declared', `${item} is not in the default branch's ledger. Push the PMOS records (Sync), then run this check again`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
const hist = (it && it.history) || [];
|
|
177
|
+
if (it && !hist.includes('verified')) human('not-verified', `${item} is ${it.state} on the default branch, not verified: its check has not passed there. Push the PMOS records (Sync), then run this check again`);
|
|
178
|
+
if (hist.includes('failed')) human('d11-failed', `${item} failed before (D11)`);
|
|
179
|
+
const g = (it && it.guard) || null;
|
|
180
|
+
const scope = g && Array.isArray(g.scope) ? g.scope.filter((s) => typeof s === 'string' && s.trim()) : [];
|
|
181
|
+
if (it && !scope.length) human('no-scope', `${item} declares no scope, so PMOS cannot tell whether the change stayed inside it`);
|
|
182
|
+
|
|
183
|
+
// ---- per file
|
|
184
|
+
const all = [];
|
|
185
|
+
for (const f of files) {
|
|
186
|
+
const p = f.path, l = p.toLowerCase(), base_ = path.posix.basename(l);
|
|
187
|
+
const add = d.added.get(p) || [];
|
|
188
|
+
all.push(...add.map((t) => [p, t]));
|
|
189
|
+
if (scope.length && !inScope(p, scope) && !(f.from && inScope(f.from, scope) && inScope(p, scope))) human('out-of-scope', `${p} is outside the declared scope (${scope.join(', ')})`);
|
|
190
|
+
if (CI.test(l) || GUARD_NAME.test(l)) human('ci-gates', `${p} is CI, a gate, the guardrail, a PMOS record or branch protection`);
|
|
191
|
+
if (AGENT_FILES.test(l) || segHas(p, AGENT_PATH)) human('agent-path', `${p} is an agent rule, prompt or skill (a new agent path)`);
|
|
192
|
+
if (segHas(p, MIGRATION) || /schema\.prisma$|(^|\/)db\/schema\./.test(l)) human('migration', `${p} is a migration or a schema`);
|
|
193
|
+
if (segHas(p, SENSITIVE) || /(^|\/)\.env(\.|$)|\.(pem|key|p12|pfx|jks)$/.test(l)) human('sensitive', `${p} touches auth, permissions, payments, personal data or secrets`);
|
|
194
|
+
if (segHas(p, API) || /(^|\/)index\.d\.ts$/.test(l)) human('public-api', `${p} is a public API or contract`);
|
|
195
|
+
if (LOCKS.includes(base_)) human('dependency', `${p} changes a lock file (a dependency may be new)`);
|
|
196
|
+
if (MANIFESTS.includes(base_) && add.some((t) => t.trim())) human('dependency', `${p} changes a dependency manifest`);
|
|
197
|
+
if (base_ === 'package.json') {
|
|
198
|
+
const before = git(cwd, ['show', `${base}:${f.from || p}`]), after = git(cwd, ['show', `${head}:${p}`]);
|
|
199
|
+
const a = before.ok ? depsOf(before.out) : new Set(), b = after.ok ? depsOf(after.out) : null;
|
|
200
|
+
if (!a || !b) human('dependency', `${p} could not be read`);
|
|
201
|
+
else { const added = [...b].filter((x) => !a.has(x)); if (added.length) human('dependency', `${p} adds ${added.map((x) => x.split(':')[1]).join(', ')}`); }
|
|
202
|
+
}
|
|
203
|
+
if (f.status !== 'A' && (TEST_FILE.test(l) || TEST_NAME.test(l))) human('self-test', `${p} changes an existing test (a pull request may not change what judges it)`);
|
|
204
|
+
if (TEST_CONFIG.test(l)) human('self-test', `${p} changes the test configuration`);
|
|
205
|
+
if (it && it.criterion) for (const r of pathsIn(it.criterion.ref)) if (p === r || p.startsWith(r.replace(/\/?$/, '/'))) human('self-test', `${p} is the item's own check (${it.criterion.ref})`);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// ---- added lines
|
|
209
|
+
const code = all.filter(([p]) => !/\.(md|mdx|txt|rst|adoc)$/i.test(p) && !TEST_FILE.test(p.toLowerCase()) && !TEST_NAME.test(p.toLowerCase()));
|
|
210
|
+
for (const t of ADDED) {
|
|
211
|
+
const hit = code.find(([, line]) => t.re.test(line));
|
|
212
|
+
if (hit) human(t.rule, `${hit[0]} ${t.why}: "${one(hit[1], 100)}"`);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// ---- the flag, or no user-facing effect
|
|
216
|
+
if (it && g) {
|
|
217
|
+
if (g.user_facing === false) { /* declared with no user-facing effect: no flag needed */ }
|
|
218
|
+
else if (!g.flag || !g.flag.name) human('no-flag', `${item} is user-facing and declares no flag. Declare --flag <name>, or --no-user-facing`);
|
|
219
|
+
else if (!code.some(([, line]) => line.includes(g.flag.name))) human('not-flagged', `the change does not read its flag ${g.flag.name}, so it would reach users at once`);
|
|
220
|
+
} else if (it) human('no-flag', `${item} declares neither a flag nor --no-user-facing`);
|
|
221
|
+
|
|
222
|
+
// ---- D11: history
|
|
223
|
+
const rv = recentRevert(cwd, base, nowMs);
|
|
224
|
+
if (rv !== null) human('d11-revert', `a merge was reverted on the default branch ${rv === 0 ? 'today' : rv + ' days ago'} (D11)`);
|
|
225
|
+
for (const s of staleDirs(cwd, base, files, nowMs)) human('d11-stale', `${s.dir} was last changed ${s.days} days ago (D11: a subsystem untouched about 3 months)`);
|
|
226
|
+
|
|
227
|
+
const seen = new Set();
|
|
228
|
+
const uniq = reasons.filter((r) => { const k = r.rule + '|' + r.detail; if (seen.has(k)) return false; seen.add(k); return true; });
|
|
229
|
+
return { factory: true, item, verdict: uniq.length ? 'human' : 'auto', reasons: uniq, files: files.map((f) => f.path) };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function summaryOf(v) {
|
|
233
|
+
if (v.verdict === 'none') return 'pmos-guardrail: not a factory pull request. Nothing to do.';
|
|
234
|
+
if (v.verdict === 'auto') return `pmos-guardrail: AUTO for ${v.item}. Auto-merge is on: GitHub merges when every required check is green. The change reaches users only through its flag.`;
|
|
235
|
+
return [`pmos-guardrail: HUMAN for ${v.item || 'this revert'}. A person merges this pull request, because:`, ...v.reasons.map((r) => `- ${r.detail}`)].join('\n');
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** GitHub Actions only: act on the verdict with the workflow's own token. The agent never reaches this. → [{ args, status }] */
|
|
239
|
+
function actOnGitHub(v, { pr, env = process.env } = {}) {
|
|
240
|
+
if (env.GITHUB_ACTIONS !== 'true') throw new Error('--github runs only inside GitHub Actions');
|
|
241
|
+
if (!/^[0-9]+$/.test(String(pr || ''))) throw new Error('--github needs --pr <number>');
|
|
242
|
+
const run = (args) => { const r = cp.spawnSync('gh', args, { encoding: 'utf8', env }); return { args, status: r.status, out: one(r.stdout || r.stderr || (r.error && r.error.message), 300) }; };
|
|
243
|
+
if (env.GITHUB_OUTPUT) fs.appendFileSync(env.GITHUB_OUTPUT, `verdict=${v.verdict}\nitem=${v.item || ''}\n`);
|
|
244
|
+
if (env.GITHUB_STEP_SUMMARY) fs.appendFileSync(env.GITHUB_STEP_SUMMARY, summaryOf(v) + '\n');
|
|
245
|
+
if (v.verdict === 'auto') return [run(['pr', 'ready', String(pr)]), run(['pr', 'merge', String(pr), '--auto', '--squash'])];
|
|
246
|
+
if (v.verdict === 'human') return [run(['pr', 'merge', String(pr), '--disable-auto'])];
|
|
247
|
+
return [];
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function cliMain(argv, { say = (s) => console.log(s), env = process.env, cwd = process.cwd() } = {}) {
|
|
251
|
+
const opt = (k) => { const i = argv.indexOf(k); return i !== -1 && argv[i + 1] !== undefined && !argv[i + 1].startsWith('--') ? argv[i + 1] : undefined; };
|
|
252
|
+
const base = opt('--base'), head = opt('--head');
|
|
253
|
+
if (!base || !head) { say('usage: node factory-guardrail.js --base <ref> --head <ref> [--branch <name>] [--body-file <f>] [--json] [--github --pr <n>]'); return 2; }
|
|
254
|
+
let body = '';
|
|
255
|
+
if (opt('--body-file')) { try { body = fs.readFileSync(opt('--body-file'), 'utf8'); } catch { body = 'PMOS-Merge: human'; } }
|
|
256
|
+
let v;
|
|
257
|
+
try { v = classify({ cwd, base, head, branch: opt('--branch') || '', body, headRepo: opt('--head-repo') || null, baseRepo: opt('--base-repo') || null }); }
|
|
258
|
+
catch (e) { v = { factory: true, item: null, verdict: 'human', reasons: [{ rule: 'unreadable', detail: 'the guardrail failed: ' + one(e.message, 200) }], files: [] }; }
|
|
259
|
+
say(argv.includes('--json') ? JSON.stringify(v) : summaryOf(v));
|
|
260
|
+
if (argv.includes('--github')) {
|
|
261
|
+
for (const r of actOnGitHub(v, { pr: opt('--pr'), env })) say(`gh ${r.args.join(' ')} → ${r.status}${r.out ? ' ' + r.out : ''}`);
|
|
262
|
+
}
|
|
263
|
+
return 0;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
module.exports = { classify, summaryOf, actOnGitHub, cliMain, REVERT_DAYS, STALE_DAYS };
|
|
267
|
+
if (require.main === module) process.exitCode = cliMain(process.argv.slice(2));
|