@jakobm/peacekeeper 0.21.0 → 0.23.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/README.md CHANGED
@@ -85,9 +85,21 @@ peacekeeper generate-github-setup \
85
85
  ```
86
86
 
87
87
  Repeat `--repository` to configure any number of repositories in one script.
88
- The command writes the setup to stdout, so it can be inspected, pasted into a
89
- shell, or redirected to a file. Repository and owner values are inlined in the
90
- output; the command does not require npm publication information.
88
+ At generation time the command reads and validates each repository's
89
+ `peacekeeper.config.yaml` from its GitHub default branch, then embeds that
90
+ repository's `git.releaseRequiredChecks` in the output. A repository without the
91
+ file uses Peacekeeper's bundled defaults; an invalid file or unreadable repository
92
+ stops generation. The command writes this configuration snapshot to stdout, so it
93
+ can be inspected, pasted into a shell, or redirected to a file and run immediately.
94
+ Repository and owner values are also inlined; the command does not require npm
95
+ publication information.
96
+
97
+ The generator and `verify-release-protection` consume one internal GitHub policy
98
+ model. The generator materializes its canonical repository settings and ruleset
99
+ JSON into the shell script; the script itself does not read configuration or
100
+ interpret policy at runtime. Verification normalizes GitHub's response and checks
101
+ it against the same model, while continuing to accept documented semantic
102
+ alternatives such as equivalent classic branch protection.
91
103
 
92
104
  When moving an existing project to Peacekeeper, update its dependency and lockfile,
93
105
  package scripts, and configuration filename together. Replace previous lifecycle
@@ -125,7 +137,7 @@ Include these entries in the caller's `package.json`, alongside its other script
125
137
 
126
138
  Run `npm install` from the project root and commit the resulting `package-lock.json`. npm adds `node_modules/.bin` to the `PATH` of package scripts, so package scripts can call `peacekeeper` by name.
127
139
 
128
- ### 2. `peacekeeper.config.json`
140
+ ### 2. `peacekeeper.config.yaml`
129
141
 
130
142
  Place this file at the caller's Git root. Every field, including nested fields,
131
143
  is required. Unknown fields and invalid values are rejected. If no file exists,
@@ -135,10 +147,14 @@ recording or reusing a test receipt.
135
147
 
136
148
  Run `peacekeeper update-config` to create the file or recursively fill missing
137
149
  fields from the defaults. Existing values, including empty arrays, are preserved.
138
- Review newly inserted values. Invalid JSON, unknown fields, or invalid existing
150
+ Comments in an existing YAML file are preserved. Review newly inserted values.
151
+ Invalid YAML, unknown fields, or invalid existing
139
152
  values cause failure without changing the file. Repeating the command on a
140
153
  complete valid file leaves it unchanged.
141
154
 
155
+ The former `peacekeeper.config.json` filename is not accepted. Rename and convert
156
+ it before upgrading so Peacekeeper cannot silently fall back to defaults.
157
+
142
158
  All CLI commands validate configuration before executing, except help,
143
159
  `check-project --explain`, and `update-config`. Checkpoint hooks instead validate
144
160
  the event worktree configuration when the event requires instructions or a check.
@@ -148,31 +164,31 @@ therefore require `peacekeeper update-config` before ordinary commands can run.
148
164
 
149
165
  Complete example:
150
166
 
151
- ```json
152
- {
153
- "publishesToNpm": false,
154
- "git": {
155
- "remote": "origin",
156
- "defaultBranch": "main",
157
- "branchPrefix": "codex/",
158
- "requiredApprover": "OWNER",
159
- "checkpointPushRemotes": ["origin"],
160
- "releaseMergeMethod": "merge",
161
- "releaseRequiredChecks": ["test"],
162
- "releaseTestWorkflow": "test.yml"
163
- },
164
- "tests": {
165
- "commands": ["eslint .", "node --test"],
166
- "receiptMaxAgeMinutes": 60,
167
- "npmTestUsesRunner": true
168
- },
169
- "loggingDirectory": "tmp/logs",
170
- "loggingEnabled": true,
171
- "projectChecks": {
172
- "testWorkflow": "test.yml",
173
- "requiredJobs": ["test"]
174
- }
175
- }
167
+ ```yaml
168
+ publishesToNpm: false
169
+ git:
170
+ remote: origin
171
+ defaultBranch: main
172
+ branchPrefix: codex/
173
+ requiredApprover: OWNER
174
+ checkpointPushRemotes:
175
+ - origin
176
+ releaseMergeMethod: merge
177
+ releaseRequiredChecks:
178
+ - test
179
+ releaseTestWorkflow: test.yml
180
+ tests:
181
+ commands:
182
+ - eslint .
183
+ - node --test
184
+ receiptMaxAgeMinutes: 60
185
+ npmTestUsesRunner: true
186
+ loggingDirectory: tmp/logs
187
+ loggingEnabled: true
188
+ projectChecks:
189
+ testWorkflow: test.yml
190
+ requiredJobs:
191
+ - test
176
192
  ```
177
193
 
178
194
  `git.remote` and `git.defaultBranch` identify the branch used for checkpointing and cleanup. `git.branchPrefix` names new task branches. `git.requiredApprover` names the personal GitHub repository owner who must approve other users' PRs and may bypass only the approval ruleset from a PR. Set it explicitly after `update-config`; its bundled default is `null`. The root project must contain `.github/CODEOWNERS` with the single non-comment rule `* @OWNER`, matching this value. `run-tests` always runs the local `check-project` validation first, even when reusing a test receipt. Explicit `check-project` invocations in `tests.commands` are rejected as redundant. The configured commands are complete shell commands, run in order from the caller's Git root; install any executables they use. The test runner stops on the first failure and records a receipt only after every command succeeds. `receiptMaxAgeMinutes` controls how long a receipt can be reused. Set `npmTestUsesRunner` to `true` only when the caller's `npm test` script invokes `peacekeeper run-tests`; this makes the rerun hint `npm test -- --force`. Otherwise the hint uses the explicit package path. `loggingDirectory` stores hook invocation logs relative to the primary Git worktree's root.
@@ -183,13 +199,13 @@ Checkpoint hook failures write the cause to stderr and exit with code 2 instead
183
199
 
184
200
  To publish checkpoint branches automatically, set `git.checkpointPushRemotes` (fragment):
185
201
 
186
- ```json
187
- {
188
- "remote": "origin",
189
- "defaultBranch": "main",
190
- "branchPrefix": "codex/",
191
- "checkpointPushRemotes": ["origin", "backup"]
192
- }
202
+ ```yaml
203
+ remote: origin
204
+ defaultBranch: main
205
+ branchPrefix: codex/
206
+ checkpointPushRemotes:
207
+ - origin
208
+ - backup
193
209
  ```
194
210
 
195
211
  Each name must identify a Git remote configured in the calling repository. Checkpoints push to exactly those remotes, creating the task branch if
@@ -321,7 +337,7 @@ test runner directly, avoiding recursion through `npm test`. The cleanup package
321
337
  scripts work the same way as in calling projects.
322
338
 
323
339
  When first adopting these hooks, make sure the primary checkout also contains
324
- `peacekeeper.config.json` before trusting them with `/hooks`: invocation logs
340
+ `peacekeeper.config.yaml` before trusting them with `/hooks`: invocation logs
325
341
  are stored there and session cleanup reads that checkout's configuration.
326
342
  The hook definitions can then be reviewed and trusted in Codex; committing them
327
343
  does not grant trust automatically.
@@ -330,7 +346,7 @@ does not grant trust automatically.
330
346
 
331
347
  Run `peacekeeper check-project` to check the local project configuration.
332
348
 
333
- Declare the mandatory boolean `publishesToNpm` in `peacekeeper.config.json`.
349
+ Declare the mandatory boolean `publishesToNpm` in `peacekeeper.config.yaml`.
334
350
  Its default is `false`; `update-config` inserts `false` without inferring intent
335
351
  from package metadata. Set it to `true` for packages published to npm (including
336
352
  restricted scoped packages). Peacekeeper itself sets it to `true`.
@@ -478,7 +494,7 @@ another run.
478
494
 
479
495
  Release verification uses GitHub's enforced branch policy instead of retaining
480
496
  artifacts of tested contents. Configure `git.releaseRequiredChecks` in the root
481
- `peacekeeper.config.json` with the exact CI job names required for a release
497
+ `peacekeeper.config.yaml` with the exact CI job names required for a release
482
498
  (for this repository: `["test", "Test package"]`). These checks must be mandatory
483
499
  with **Require branches to be up to date before merging** enabled. Classic branch
484
500
  protection may provide the base PR and check requirements. Active base rulesets
@@ -493,16 +509,17 @@ after new pushes, and contain no rule except that pull-request approval rule. It
493
509
  only bypass actor must be the personal repository owner from `git.requiredApprover`,
494
510
  with `bypass_mode: pull_request`. This lets the owner merge their own PR without
495
511
  approval while the separate base policy still requires a PR and successful CI.
496
- No other user, team, role, or app may bypass either policy. Peacekeeper does not
497
- verify bypass actors because GitHub hides them from read-only administration
498
- tokens; inspect them manually instead.
512
+ No other user, team, role, or app may bypass either policy. Peacekeeper verifies
513
+ bypass actors when GitHub returns them. GitHub hides them from read-only
514
+ administration tokens, in which case Peacekeeper warns that this part remains
515
+ unknown instead of reporting a false success or failure.
499
516
 
500
517
  Only merge commits may be used. Either disable squash and rebase
501
518
  in repository settings, or restrict the default branch's pull-request ruleset to
502
519
  `allowed_merge_methods: ["merge"]`. Other branches are outside this policy.
503
520
  Required linear history and any applicable PR rule excluding merge commits fail
504
- verification. Bypass actors for base PR and strict-check rules also require
505
- manual inspection.
521
+ verification. Bypass actors for base PR and strict-check rules require manual
522
+ inspection only when GitHub omits them from its response.
506
523
  Enable `allow_auto_merge` in repository settings: this permits opting in per PR;
507
524
  Peacekeeper never enables auto-merge on individual PRs.
508
525
 
@@ -512,7 +529,8 @@ PR workflow uses only `pull_request`, with `branches` set to exactly
512
529
  `[git.defaultBranch]`, and runs `verify-release-protection` with `GH_TOKEN` after `npm ci` and
513
530
  before tests in a job listed in `git.releaseRequiredChecks`. The job and step must
514
531
  not skip verification or ignore failures. The online verifier then checks that
515
- all those configured check names are mandatory on GitHub, including its own job.
532
+ exactly those configured check names are mandatory on GitHub, including its own
533
+ job; missing and additional checks are both configuration drift.
516
534
  Push, manual, scheduled, and other triggers are rejected in this workflow. Keep
517
535
  publishing, deployment, reports, and benchmarks in separate workflows.
518
536
  For example, in a required `test` job:
@@ -541,15 +559,18 @@ jobs in its latest PR workflow run. Manual tags without that PR are rejected.
541
559
  `verify-release-version` remains available for local version checks alone.
542
560
 
543
561
  API failures, missing permissions, and unverifiable rules stop the commands.
544
- Bypass actors are the exception: each policy verification prints `Cannot verify
545
- bypass users unless given write access. Run a manual check instead; available as
546
- a gist.` and continues without inspecting them.
562
+ Bypass actors are the exception when GitHub omits them: policy verification then
563
+ prints `Cannot verify bypass users unless given write access. Run a manual check
564
+ instead; available as a gist.` and continues with that part marked unknown. When
565
+ the API returns bypass actors, Peacekeeper compares them with the same policy used
566
+ to generate the setup script and rejects drift.
547
567
  The workflow expects a `RELEASE_POLICY_TOKEN` Actions secret, exposed to the
548
568
  commands as `GH_TOKEN`. Use a fine-grained PAT or GitHub App token with access to
549
569
  this repository and Administration read, Contents read/write, Pull requests read and
550
570
  Actions read permissions. Contents write is required even to read merge-related
551
- settings such as `delete_branch_on_merge`. Administration read is sufficient
552
- because bypass actors are checked manually.
571
+ settings such as `delete_branch_on_merge`. Administration read is sufficient for
572
+ the remaining checks; ruleset write access is required for GitHub to reveal
573
+ bypass actors.
553
574
  The normal workflow `GITHUB_TOKEN` cannot be granted Administration permission
554
575
  through workflow YAML. After correcting access or rules, rerun the failed job.
555
576
  Fork PRs do not receive this secret and fail the policy check; do not expose it
@@ -637,7 +658,7 @@ that needs manual cleanup.
637
658
 
638
659
  Other npm projects can use this command through a package script such as
639
660
  `"release": "peacekeeper release"`. The project must use a root package
640
- with a stable version, a `peacekeeper.config.json` with
661
+ with a stable version, a `peacekeeper.config.yaml` with
641
662
  `git.releaseRequiredChecks`, and the supported tag-triggered GitHub Actions
642
663
  publish job. Add `peacekeeper verify-release-protection` to a required PR
643
664
  test job and `peacekeeper verify-release` before publishing, with `GH_TOKEN`
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jakobm/peacekeeper",
3
- "version": "0.21.0",
3
+ "version": "0.23.0",
4
4
  "description": "Shared repository test, Git worktree, and Codex hook commands",
5
5
  "license": "MIT",
6
6
  "author": "Jakob Mattsson",
@@ -2,6 +2,7 @@ import { execFileSync, spawn, spawnSync } from 'node:child_process';
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
+ import YAML from 'yaml';
5
6
  import projectConfigDefaults from './modules/configuration/project-config-defaults.json' with { type: 'json' };
6
7
  import createProjectConfig from './modules/configuration/project-config.js';
7
8
  import createLifecycle from './modules/lifecycle/interface.js';
@@ -28,7 +29,7 @@ const output = console;
28
29
  function dependencyFreeLifecycleContainer() {
29
30
  const runtime = process;
30
31
  const projectConfig = createProjectConfig({
31
- external: { execFileSync, fs, path, projectConfigDefaults, runtime },
32
+ external: { execFileSync, fs, path, projectConfigDefaults, runtime, YAML },
32
33
  });
33
34
  const configuration = Object.freeze({
34
35
  projectConfig: projectConfig.projectConfig,
@@ -2,5 +2,6 @@ export default ({ projectConfig, updateConfig }) => ({
2
2
  projectConfig: projectConfig.projectConfig,
3
3
  repositoryRoot: projectConfig.repositoryRoot,
4
4
  requireTestCommands: projectConfig.requireTestCommands,
5
+ validateConfig: projectConfig.validateConfig,
5
6
  updateConfig: updateConfig.run,
6
7
  });
@@ -1,5 +1,6 @@
1
- export default ({ external: { execFileSync, fs, path, projectConfigDefaults, runtime, } }) => {
2
- const CONFIG_FILE = 'peacekeeper.config.json';
1
+ export default ({ external: { execFileSync, fs, path, projectConfigDefaults, runtime, YAML, } }) => {
2
+ const CONFIG_FILE = 'peacekeeper.config.yaml';
3
+ const LEGACY_CONFIG_FILE = 'peacekeeper.config.json';
3
4
  function repositoryRoot(cwd = runtime.cwd()) {
4
5
  return execFileSync('git', ['rev-parse', '--show-toplevel'], {
5
6
  cwd,
@@ -98,8 +99,12 @@ export default ({ external: { execFileSync, fs, path, projectConfigDefaults, run
98
99
  function projectConfig(cwd = runtime.cwd()) {
99
100
  const root = repositoryRoot(cwd);
100
101
  const file = path.join(root, CONFIG_FILE);
102
+ const legacyFile = path.join(root, LEGACY_CONFIG_FILE);
103
+ if (!fs.existsSync(file) && fs.existsSync(legacyFile)) {
104
+ throw new Error(`${legacyFile}: rename this legacy JSON configuration to ${CONFIG_FILE} and convert it to YAML.`);
105
+ }
101
106
  const config = fs.existsSync(file)
102
- ? JSON.parse(fs.readFileSync(file, 'utf8'))
107
+ ? YAML.parse(fs.readFileSync(file, 'utf8'))
103
108
  : JSON.parse(JSON.stringify(projectConfigDefaults));
104
109
  validateConfig(config, file);
105
110
  return { root, ...config };
@@ -109,6 +114,6 @@ export default ({ external: { execFileSync, fs, path, projectConfigDefaults, run
109
114
  throw new Error('Configure tests.commands before running tests or using a test receipt.');
110
115
  }
111
116
  }
112
- const api = { CONFIG_FILE, CONFIG_SCHEMA, validateConfig, projectConfig, repositoryRoot, requireTestCommands };
117
+ const api = { CONFIG_FILE, LEGACY_CONFIG_FILE, CONFIG_SCHEMA, validateConfig, projectConfig, repositoryRoot, requireTestCommands };
113
118
  return api;
114
119
  };
@@ -1,5 +1,5 @@
1
- export default ({ projectConfig, external: { fs, isDeepStrictEqual, output, path, projectConfigDefaults, runtime, } }) => {
2
- const { CONFIG_FILE, repositoryRoot, validateConfig } = projectConfig;
1
+ export default ({ projectConfig, external: { fs, isDeepStrictEqual, output, path, projectConfigDefaults, runtime, YAML, } }) => {
2
+ const { CONFIG_FILE, LEGACY_CONFIG_FILE, repositoryRoot, validateConfig } = projectConfig;
3
3
  function complete(value, defaults) {
4
4
  if (value === null || typeof value !== 'object' || Array.isArray(value))
5
5
  return value;
@@ -13,16 +13,35 @@ export default ({ projectConfig, external: { fs, isDeepStrictEqual, output, path
13
13
  }
14
14
  return result;
15
15
  }
16
+ function addMissing(document, value, defaults, keys = []) {
17
+ for (const [key, fallback] of Object.entries(defaults)) {
18
+ const childKeys = [...keys, key];
19
+ if (!Object.hasOwn(value, key))
20
+ document.setIn(childKeys, JSON.parse(JSON.stringify(fallback)));
21
+ else if (fallback !== null && typeof fallback === 'object' && !Array.isArray(fallback)) {
22
+ addMissing(document, value[key], fallback, childKeys);
23
+ }
24
+ }
25
+ }
16
26
  function updateConfig(cwd = runtime.cwd()) {
17
- const file = path.join(repositoryRoot(cwd), CONFIG_FILE);
27
+ const root = repositoryRoot(cwd);
28
+ const file = path.join(root, CONFIG_FILE);
29
+ const legacyFile = path.join(root, LEGACY_CONFIG_FILE);
30
+ if (!fs.existsSync(file) && fs.existsSync(legacyFile)) {
31
+ throw new Error(`${legacyFile}: rename this legacy JSON configuration to ${CONFIG_FILE} and convert it to YAML.`);
32
+ }
18
33
  const defaults = projectConfigDefaults;
19
34
  validateConfig(defaults, 'bundled defaults');
20
35
  const exists = fs.existsSync(file);
21
- const original = exists ? JSON.parse(fs.readFileSync(file, 'utf8')) : {};
36
+ const document = exists ? YAML.parseDocument(fs.readFileSync(file, 'utf8')) : new YAML.Document({});
37
+ if (document.errors.length)
38
+ throw new Error(`${file}: ${document.errors.map(error => error.message).join('; ')}`);
39
+ const original = document.toJS();
22
40
  const updated = complete(original, defaults);
23
41
  validateConfig(updated, file);
24
42
  if (!exists || !isDeepStrictEqual(original, updated)) {
25
- fs.writeFileSync(file, `${JSON.stringify(updated, null, 2)}\n`);
43
+ addMissing(document, original, defaults);
44
+ fs.writeFileSync(file, document.toString({ lineWidth: 0 }));
26
45
  output.log(`Updated ${file}. Review defaults before using project commands.`);
27
46
  }
28
47
  else
@@ -8,9 +8,9 @@ allowed-modules:
8
8
  testing: [configuration, projects]
9
9
  allowed-external:
10
10
  cli: [cliConfigPath, runCli]
11
- configuration: [execFileSync, fs, isDeepStrictEqual, output, path, projectConfigDefaults, runtime]
11
+ configuration: [execFileSync, fs, isDeepStrictEqual, output, path, projectConfigDefaults, runtime, YAML]
12
12
  lifecycle: [buffer, clock, executablePath, fs, output, path, runtime, spawn, spawnSync]
13
13
  maintenance: [execFileSync, fs, output, path, runtime, spawnSync]
14
- projects: [fs, isDeepStrictEqual, modulesRoot, output, packageVersion, path, projectConfigDefaults, runtime, semver, spawnSync, TOML, url, YAML]
14
+ projects: [buffer, fs, isDeepStrictEqual, modulesRoot, output, packageVersion, path, projectConfigDefaults, runtime, semver, spawnSync, TOML, url, YAML]
15
15
  releases: [assessReleaseSchema, clock, execFileSync, fs, modulesRoot, os, output, path, runtime, semver, spawnSync, url, YAML]
16
16
  testing: [clock, crypto, execFileSync, fs, modulesRoot, os, output, path, runtime, spawnSync]
@@ -13,7 +13,7 @@ Purpose and scope
13
13
  --explain prints this entire document without loading or checking a project.
14
14
 
15
15
  Project configuration
16
- package.json is required at the Git root. Without peacekeeper.config.json,
16
+ package.json is required at the Git root. Without peacekeeper.config.yaml,
17
17
  bundled defaults apply. An existing configuration must declare every schema
18
18
  field, including nested fields; unknown fields and invalid values fail.
19
19
  Run peacekeeper update-config to create or complete it without overwriting
@@ -253,11 +253,12 @@ Online release policy and GitHub token setup
253
253
  Enable "Automatically delete head branches" (delete_branch_on_merge=true) in
254
254
  the repository settings. The online release policy commands require it.
255
255
 
256
- Configure the default branch from git.defaultBranch with every exact job name
256
+ Configure the default branch from git.defaultBranch with exactly the job names
257
257
  in git.releaseRequiredChecks mandatory and "Require branches to be up to date
258
258
  before merging" enabled. The base policy may use either classic branch
259
259
  protection with strict status checks or active branch rulesets requiring
260
- strict status checks. Its bypass configuration must be inspected manually.
260
+ strict status checks. Its bypass configuration is compared when GitHub exposes
261
+ it and otherwise must be inspected manually.
261
262
  Merge queues are not currently an alternative to this strict policy. For the
262
263
  matrix example, also require its matrix checks as described above.
263
264
 
@@ -267,8 +268,8 @@ Online release policy and GitHub token setup
267
268
  git.requiredApprover, with actor_type User and bypass_mode pull_request. The
268
269
  configured account must be the personal repository owner. This approval-only
269
270
  bypass lets that owner merge a PR they authored, but the separate base policy
270
- still prevents direct pushes and requires strict CI. Any other bypass violates
271
- the policy and must be caught by the manual inspection.
271
+ still prevents direct pushes and requires strict CI. Any other visible bypass
272
+ violates the policy; inspect it manually when GitHub omits the actors.
272
273
 
273
274
  Create a fine-grained GitHub PAT or GitHub App installation token with access
274
275
  to this repository and these repository permissions:
@@ -277,7 +278,7 @@ Online release policy and GitHub token setup
277
278
  Pull requests: read
278
279
  Actions: read
279
280
  GitHub exposes bypass actors only to callers with write access to the ruleset.
280
- Peacekeeper therefore does not verify them and prints this warning instead:
281
+ Peacekeeper verifies them when exposed and otherwise prints this warning:
281
282
  Cannot verify bypass users unless given write access. Run a manual check
282
283
  instead; available as a gist.
283
284
 
@@ -402,16 +403,17 @@ Default-branch GitHub policy chain
402
403
  This applies to private projects too; configure nonempty releaseRequiredChecks.
403
404
 
404
405
  Online verification reads the actual GitHub default branch and requires PRs,
405
- strict mandatory configured checks, and merge commits only. It also verifies
406
- the separate owner-approval ruleset described above, except for its bypass
407
- actors. Enable
406
+ exactly the configured strict mandatory checks, and merge commits only. It also
407
+ verifies the separate owner-approval ruleset described above. Bypass actors are
408
+ compared when GitHub returns them; otherwise verification warns that they are
409
+ unknown. Enable
408
410
  repository allow_auto_merge; this only offers per-PR opt-in and does not
409
411
  activate auto-merge for any PR.
410
412
  Restrict merge methods either repository-wide (merge enabled, squash and rebase
411
413
  disabled) or with a default-branch PR ruleset allowing only merge. Other branches
412
414
  are not checked. Linear-history rules or PR rules excluding merge are errors.
413
- Base PR requirements, like status checks, require active rules. Inspect all
414
- bypass actors manually.
415
+ Base PR requirements, like status checks, require active rules. Inspect bypass
416
+ actors manually only when GitHub omits them from the response.
415
417
  Existing automatic head-branch deletion requirements still apply.
416
418
 
417
419
  Missing CI is detected on the next local npm test. GitHub settings are checked
@@ -56,7 +56,7 @@ export default ({ configuration, installHooks, releases, external: { fs, isDeepS
56
56
  });
57
57
  check('GitHub policy', () => {
58
58
  const approver = config.git.requiredApprover;
59
- requireThat(typeof approver === 'string', 'peacekeeper.config.json: set git.requiredApprover to the personal GitHub repository owner.');
59
+ requireThat(typeof approver === 'string', 'peacekeeper.config.yaml: set git.requiredApprover to the personal GitHub repository owner.');
60
60
  if (typeof approver !== 'string')
61
61
  return;
62
62
  const file = '.github/CODEOWNERS';
@@ -231,7 +231,7 @@ export default ({ configuration, installHooks, releases, external: { fs, isDeepS
231
231
  check('CI', () => {
232
232
  const workflow = workflows.get(filename);
233
233
  if (!workflow) {
234
- requireThat(false, `${filename}: configured PR workflow is missing (selected by projectChecks.testWorkflow). Set projectChecks.testWorkflow${published ? ' and git.releaseTestWorkflow to the same existing file' : ' to an existing file'} in peacekeeper.config.json. PR checks are blocked until it can be read.`);
234
+ requireThat(false, `${filename}: configured PR workflow is missing (selected by projectChecks.testWorkflow). Set projectChecks.testWorkflow${published ? ' and git.releaseTestWorkflow to the same existing file' : ' to an existing file'} in peacekeeper.config.yaml. PR checks are blocked until it can be read.`);
235
235
  return;
236
236
  }
237
237
  const jobs = workflow.jobs;
@@ -1,5 +1,6 @@
1
- export default ({ installHooks, external: { fs, modulesRoot, packageVersion, path, projectConfigDefaults, runtime, spawnSync, url: Url, } }) => {
1
+ export default ({ installHooks, releases, external: { fs, modulesRoot, packageVersion, path, projectConfigDefaults, runtime, spawnSync, url: Url, YAML, } }) => {
2
2
  const { planHooks } = installHooks;
3
+ const { createGithubPolicy, githubSetupPlan } = releases;
3
4
  const TOOLCHAIN = Object.freeze({
4
5
  node: '22.14.0',
5
6
  npm: '11.21.0',
@@ -70,20 +71,37 @@ export default ({ installHooks, external: { fs, modulesRoot, packageVersion, pat
70
71
  }
71
72
  function renderTemplate(filename, replacements) {
72
73
  let template = fs.readFileSync(path.join(modulesRoot, `projects/${filename}`), 'utf8');
74
+ const placeholders = [...template.matchAll(/\{\{([A-Z_]+)\}\}/gu)].map(match => match[1]);
75
+ const unknown = placeholders.find(name => !Object.hasOwn(replacements, name));
76
+ if (unknown)
77
+ throw new Error(`Unknown GitHub setup template placeholder: {{${unknown}}}`);
73
78
  for (const [name, value] of Object.entries(replacements)) {
74
79
  template = template.replaceAll(`{{${name}}}`, value);
75
80
  }
76
- const unresolved = template.match(/\{\{[A-Z_]+\}\}/u);
77
- if (unresolved)
78
- throw new Error(`Unknown GitHub setup template placeholder: ${unresolved[0]}`);
79
81
  return template.trim();
80
82
  }
81
83
  function githubSetup(repositories) {
82
84
  const prefix = renderTemplate('github-setup-prefix.sh', {});
83
- const configured = repositories.map(({ owner, repositoryName }) => renderTemplate('github-setup-repository-template.sh', {
84
- OWNER: shellSingleQuotedContent(owner),
85
- REPOSITORY_NAME: shellSingleQuotedContent(repositoryName),
86
- }));
85
+ const configured = repositories.map(({ owner, repositoryName, requiredChecks, requiredApprover = owner, defaultBranch = 'main' }) => {
86
+ let plan;
87
+ try {
88
+ plan = githubSetupPlan(createGithubPolicy({ branch: defaultBranch,
89
+ checks: requiredChecks, requiredApprover }));
90
+ }
91
+ catch (error) {
92
+ throw new Error(`GitHub setup for ${owner}/${repositoryName}: ${error instanceof Error ? error.message : String(error)}`);
93
+ }
94
+ return renderTemplate('github-setup-repository-template.sh', {
95
+ OWNER: shellSingleQuotedContent(owner),
96
+ REPOSITORY_NAME: shellSingleQuotedContent(repositoryName),
97
+ DEFAULT_BRANCH: shellSingleQuotedContent(plan.branchPath),
98
+ REPOSITORY_PATCH_ARGUMENTS: plan.repositoryPatchArguments,
99
+ BASE_RULESET: plan.baseRuleset,
100
+ APPROVAL_RULESET: plan.approvalRuleset,
101
+ REQUIRED_APPROVER: shellSingleQuotedContent(requiredApprover),
102
+ REQUIRED_APPROVER_LOWER: shellSingleQuotedContent(requiredApprover.toLowerCase()),
103
+ });
104
+ });
87
105
  const argumentsValue = repositories
88
106
  .map(({ owner, repositoryName }) => `--new-repo ${shellLiteral(`${owner}/${repositoryName}`)}`)
89
107
  .join(' ');
@@ -124,7 +142,7 @@ export default ({ installHooks, external: { fs, modulesRoot, packageVersion, pat
124
142
  defaults.git.requiredApprover = options.owner;
125
143
  defaults.tests.commands = ['npm run typecheck', 'npm run build', 'npm run test:unit', ...(options.published ? ['npm run test:package'] : [])];
126
144
  defaults.tests.npmTestUsesRunner = true;
127
- write(root, 'peacekeeper.config.json', json(defaults));
145
+ write(root, 'peacekeeper.config.yaml', YAML.stringify(defaults, { lineWidth: 0 }));
128
146
  write(root, '.codex/hooks.json', json(planHooks({}).document));
129
147
  const prefix = fs.readFileSync(path.join(modulesRoot, 'projects/codex-setup-prefix.sh'), 'utf8');
130
148
  write(root, '.codex/environments/environment.toml', `version = 1\nname = ${JSON.stringify(options.repositoryName)}\n\n[setup]\nscript = '''\n${prefix}'''\n`);
@@ -135,7 +153,10 @@ export default ({ installHooks, external: { fs, modulesRoot, packageVersion, pat
135
153
  write(root, '.gitignore', 'node_modules/\n*.tgz\ntmp/\n');
136
154
  write(root, 'README.md', `# ${options.repositoryName}\n\nA TypeScript library generated by Peacekeeper.\n\n## API\n\n\`hello()\` returns \`"hello world"\`.\n`);
137
155
  write(root, 'LICENSE', `MIT License\n\nCopyright (c) ${options.authorName}\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n`);
138
- write(root, 'setup-github-config.sh', githubSetup([options]), 0o755);
156
+ write(root, 'setup-github-config.sh', githubSetup([{
157
+ ...options, requiredChecks: defaults.git.releaseRequiredChecks,
158
+ requiredApprover: defaults.git.requiredApprover, defaultBranch: defaults.git.defaultBranch,
159
+ }]), 0o755);
139
160
  }
140
161
  function createProject(options, dependencies = {}) {
141
162
  const run = dependencies.run || commandRunner;
@@ -1,8 +1,59 @@
1
- export default ({ createProjectCore, external: { runtime } }) => {
1
+ export default ({ configuration, createProjectCore, external: { buffer: Buffer, projectConfigDefaults, runtime, spawnSync, YAML, } }) => {
2
+ const { validateConfig } = configuration;
2
3
  const { githubSetup, repositoryIdentity } = createProjectCore;
4
+ function api(endpoint, missingAllowed = false) {
5
+ const response = spawnSync('gh', ['api', '--hostname', 'github.com', '--method', 'GET', endpoint], {
6
+ encoding: 'utf8',
7
+ });
8
+ if (response.status === 0) {
9
+ try {
10
+ return JSON.parse(response.stdout);
11
+ }
12
+ catch {
13
+ throw new Error(`GitHub returned invalid JSON for ${endpoint}.`);
14
+ }
15
+ }
16
+ if (missingAllowed && /HTTP 404\b/u.test(response.stderr || ''))
17
+ return undefined;
18
+ throw new Error(`Cannot read GitHub configuration (${endpoint}): ${response.error?.message
19
+ || response.stderr?.trim() || `exit ${response.status}`}`);
20
+ }
21
+ function loadRepositorySetup(repository) {
22
+ const identity = repositoryIdentity(repository);
23
+ const slug = `${identity.owner}/${identity.repositoryName}`;
24
+ const metadata = api(`repos/${slug}`);
25
+ if (typeof metadata?.default_branch !== 'string' || !metadata.default_branch) {
26
+ throw new Error(`GitHub did not return a default branch for ${slug}.`);
27
+ }
28
+ const endpoint = `repos/${slug}/contents/peacekeeper.config.yaml?ref=${encodeURIComponent(metadata.default_branch)}`;
29
+ const file = api(endpoint, true);
30
+ let config;
31
+ if (file === undefined) {
32
+ const legacyEndpoint = `repos/${slug}/contents/peacekeeper.config.json?ref=${encodeURIComponent(metadata.default_branch)}`;
33
+ if (api(legacyEndpoint, true) !== undefined) {
34
+ throw new Error(`${slug}/peacekeeper.config.json: rename this legacy JSON configuration to peacekeeper.config.yaml and convert it to YAML.`);
35
+ }
36
+ config = structuredClone(projectConfigDefaults);
37
+ }
38
+ else {
39
+ if (file.type !== 'file' || file.encoding !== 'base64' || typeof file.content !== 'string') {
40
+ throw new Error(`${slug}/peacekeeper.config.yaml: GitHub returned invalid file contents.`);
41
+ }
42
+ try {
43
+ config = YAML.parse(Buffer.from(file.content, 'base64').toString('utf8'));
44
+ }
45
+ catch (error) {
46
+ throw new Error(`${slug}/peacekeeper.config.yaml: ${error instanceof Error ? error.message : String(error)}`);
47
+ }
48
+ }
49
+ validateConfig(config, `${slug}/peacekeeper.config.yaml`);
50
+ return { ...identity, requiredChecks: config.git.releaseRequiredChecks,
51
+ requiredApprover: config.git.requiredApprover || identity.owner,
52
+ defaultBranch: metadata.default_branch };
53
+ }
3
54
  function run({ repository: repositories }) {
4
55
  try {
5
- runtime.stdout.write(githubSetup(repositories.map(repositoryIdentity)));
56
+ runtime.stdout.write(githubSetup(repositories.map(loadRepositorySetup)));
6
57
  }
7
58
  catch (error) {
8
59
  runtime.stderr.write(`Error: ${error instanceof Error ? error.message : String(error)}\n`);
@@ -1,12 +1,12 @@
1
1
  # Verify repository access and personal ownership for {{OWNER}}/{{REPOSITORY_NAME}}.
2
2
  gh repo view '{{OWNER}}/{{REPOSITORY_NAME}}' >/dev/null
3
- if [[ "$(gh api 'repos/{{OWNER}}/{{REPOSITORY_NAME}}' --jq .owner.login)" != '{{OWNER}}' ]]; then
4
- printf 'Expected %s/%s to be owned by the personal account %s.\n' '{{OWNER}}' '{{REPOSITORY_NAME}}' '{{OWNER}}' >&2
3
+ if [[ "$(gh api 'repos/{{OWNER}}/{{REPOSITORY_NAME}}' --jq '.owner.login | ascii_downcase')" != '{{REQUIRED_APPROVER_LOWER}}' ]]; then
4
+ printf 'Expected %s/%s to be owned by the personal account %s.\n' '{{OWNER}}' '{{REPOSITORY_NAME}}' '{{REQUIRED_APPROVER}}' >&2
5
5
  exit 1
6
6
  fi
7
7
 
8
8
  # Configure repository-wide branch cleanup, auto-merge, and merge methods.
9
- gh api --method PATCH 'repos/{{OWNER}}/{{REPOSITORY_NAME}}' -F delete_branch_on_merge=true -F allow_auto_merge=true -F allow_merge_commit=true -F allow_squash_merge=false -F allow_rebase_merge=false >/dev/null
9
+ gh api --method PATCH 'repos/{{OWNER}}/{{REPOSITORY_NAME}}' {{REPOSITORY_PATCH_ARGUMENTS}} >/dev/null
10
10
 
11
11
  # Create or update one named ruleset without changing unrelated rulesets.
12
12
  upsert_ruleset() {
@@ -26,65 +26,15 @@ upsert_ruleset() {
26
26
 
27
27
  # Protect the default branch with pull requests, merge commits, and strict CI.
28
28
  upsert_ruleset 'Peacekeeper base protection' <<'JSON'
29
- {
30
- "name": "Peacekeeper base protection",
31
- "target": "branch",
32
- "enforcement": "active",
33
- "bypass_actors": [],
34
- "conditions": { "ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] } },
35
- "rules": [
36
- { "type": "deletion" },
37
- { "type": "non_fast_forward" },
38
- {
39
- "type": "pull_request",
40
- "parameters": {
41
- "required_approving_review_count": 0,
42
- "dismiss_stale_reviews_on_push": false,
43
- "require_code_owner_review": false,
44
- "require_last_push_approval": false,
45
- "required_review_thread_resolution": false,
46
- "allowed_merge_methods": ["merge"]
47
- }
48
- },
49
- {
50
- "type": "required_status_checks",
51
- "parameters": {
52
- "strict_required_status_checks_policy": true,
53
- "do_not_enforce_on_create": false,
54
- "required_status_checks": [{ "context": "test" }]
55
- }
56
- }
57
- ]
58
- }
29
+ {{BASE_RULESET}}
59
30
  JSON
60
31
 
61
32
  # Require fresh code-owner approval while allowing the owner to bypass this rule.
62
33
  upsert_ruleset 'Peacekeeper owner approval' <<JSON
63
- {
64
- "name": "Peacekeeper owner approval",
65
- "target": "branch",
66
- "enforcement": "active",
67
- "bypass_actors": [
68
- { "actor_id": $(gh api 'users/{{OWNER}}' --jq .id), "actor_type": "User", "bypass_mode": "pull_request" }
69
- ],
70
- "conditions": { "ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] } },
71
- "rules": [
72
- {
73
- "type": "pull_request",
74
- "parameters": {
75
- "required_approving_review_count": 1,
76
- "dismiss_stale_reviews_on_push": true,
77
- "require_code_owner_review": true,
78
- "require_last_push_approval": false,
79
- "required_review_thread_resolution": false,
80
- "allowed_merge_methods": ["merge"]
81
- }
82
- }
83
- ]
84
- }
34
+ {{APPROVAL_RULESET}}
85
35
  JSON
86
36
 
87
37
  # Remove legacy branch protection now superseded by the rulesets above.
88
- if gh api 'repos/{{OWNER}}/{{REPOSITORY_NAME}}/branches/main/protection' >/dev/null 2>&1; then
89
- gh api --method DELETE 'repos/{{OWNER}}/{{REPOSITORY_NAME}}/branches/main/protection' >/dev/null
38
+ if gh api 'repos/{{OWNER}}/{{REPOSITORY_NAME}}/branches/{{DEFAULT_BRANCH}}/protection' >/dev/null 2>&1; then
39
+ gh api --method DELETE 'repos/{{OWNER}}/{{REPOSITORY_NAME}}/branches/{{DEFAULT_BRANCH}}/protection' >/dev/null
90
40
  fi
@@ -0,0 +1,46 @@
1
+ {
2
+ "repository": {
3
+ "delete_branch_on_merge": true,
4
+ "allow_auto_merge": true,
5
+ "allow_merge_commit": true,
6
+ "allow_squash_merge": false,
7
+ "allow_rebase_merge": false
8
+ },
9
+ "ruleset": {
10
+ "name": "Peacekeeper base protection",
11
+ "target": "branch",
12
+ "enforcement": "active",
13
+ "bypass_actors": [],
14
+ "conditions": {
15
+ "ref_name": {
16
+ "include": ["~DEFAULT_BRANCH"],
17
+ "exclude": []
18
+ }
19
+ },
20
+ "rules": [
21
+ { "type": "deletion" },
22
+ { "type": "non_fast_forward" },
23
+ {
24
+ "type": "pull_request",
25
+ "parameters": {
26
+ "required_approving_review_count": 0,
27
+ "dismiss_stale_reviews_on_push": false,
28
+ "require_code_owner_review": false,
29
+ "require_last_push_approval": false,
30
+ "required_review_thread_resolution": false,
31
+ "allowed_merge_methods": ["merge"]
32
+ }
33
+ },
34
+ {
35
+ "type": "required_status_checks",
36
+ "parameters": {
37
+ "strict_required_status_checks_policy": true,
38
+ "do_not_enforce_on_create": false,
39
+ "required_status_checks": {
40
+ "$peacekeeper": "releaseRequiredChecks"
41
+ }
42
+ }
43
+ }
44
+ ]
45
+ }
46
+ }
@@ -0,0 +1,35 @@
1
+ {
2
+ "ruleset": {
3
+ "name": "Peacekeeper owner approval",
4
+ "target": "branch",
5
+ "enforcement": "active",
6
+ "conditions": {
7
+ "ref_name": {
8
+ "include": ["~DEFAULT_BRANCH"],
9
+ "exclude": []
10
+ }
11
+ },
12
+ "bypass_actors": [
13
+ {
14
+ "actor_id": {
15
+ "$peacekeeper": "requiredApproverId"
16
+ },
17
+ "actor_type": "User",
18
+ "bypass_mode": "pull_request"
19
+ }
20
+ ],
21
+ "rules": [
22
+ {
23
+ "type": "pull_request",
24
+ "parameters": {
25
+ "required_approving_review_count": 1,
26
+ "dismiss_stale_reviews_on_push": true,
27
+ "require_code_owner_review": true,
28
+ "require_last_push_approval": false,
29
+ "required_review_thread_resolution": false,
30
+ "allowed_merge_methods": ["merge"]
31
+ }
32
+ }
33
+ ]
34
+ }
35
+ }
@@ -0,0 +1,127 @@
1
+ export default ({ external: { fs, modulesRoot, path } }) => {
2
+ const ownerIdMarker = '__PEACEKEEPER_OWNER_ID__';
3
+ const directive = '$peacekeeper';
4
+ function readDocument(filename) {
5
+ const file = path.join(modulesRoot, `releases/${filename}`);
6
+ try {
7
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
8
+ }
9
+ catch (error) {
10
+ throw new Error(`Cannot read bundled GitHub policy ${filename}: ${error instanceof Error ? error.message : String(error)}`);
11
+ }
12
+ }
13
+ const baseDocument = readDocument('github-base-protection-policy.json');
14
+ const approvalDocument = readDocument('github-owner-approval-policy.json');
15
+ function materialize(value, variables, filename) {
16
+ if (Array.isArray(value))
17
+ return value.map(item => materialize(item, variables, filename));
18
+ if (!value || typeof value !== 'object')
19
+ return value;
20
+ if (Object.hasOwn(value, directive)) {
21
+ if (Object.keys(value).length !== 1 || typeof value[directive] !== 'string'
22
+ || !Object.hasOwn(variables, value[directive])) {
23
+ throw new Error(`${filename}: invalid Peacekeeper policy directive`);
24
+ }
25
+ return structuredClone(variables[value[directive]]);
26
+ }
27
+ return Object.fromEntries(Object.entries(value)
28
+ .map(([key, item]) => [key, materialize(item, variables, filename)]));
29
+ }
30
+ function policyDocument(document, filename, variables) {
31
+ const policy = materialize(document, variables, filename);
32
+ if (!policy.ruleset || typeof policy.ruleset !== 'object' || !Array.isArray(policy.ruleset.rules)) {
33
+ throw new Error(`${filename}: bundled GitHub policy must contain a ruleset with rules`);
34
+ }
35
+ return policy;
36
+ }
37
+ function uniqueChecks(checks) {
38
+ return Array.isArray(checks) && checks.length > 0
39
+ && checks.every(check => typeof check === 'string' && check.trim() === check && check.length > 0)
40
+ && new Set(checks).size === checks.length;
41
+ }
42
+ function createGithubPolicy({ branch = 'main', checks, requiredApprover }) {
43
+ if (!uniqueChecks(checks))
44
+ throw new Error('GitHub policy requires unique nonempty status check names.');
45
+ if (typeof requiredApprover !== 'string' || !requiredApprover.trim()) {
46
+ throw new Error('A required GitHub approver must be provided.');
47
+ }
48
+ if (typeof branch !== 'string' || !branch)
49
+ throw new Error('GitHub policy requires a default branch.');
50
+ const base = policyDocument(baseDocument, 'github-base-protection-policy.json', {
51
+ releaseRequiredChecks: checks.map(context => ({ context })),
52
+ });
53
+ const ownerApproval = policyDocument(approvalDocument, 'github-owner-approval-policy.json', {
54
+ requiredApproverId: ownerIdMarker,
55
+ });
56
+ if (!base.repository || typeof base.repository !== 'object') {
57
+ throw new Error('github-base-protection-policy.json: bundled GitHub policy must contain repository settings');
58
+ }
59
+ return {
60
+ branch,
61
+ checks: [...checks],
62
+ requiredApprover,
63
+ repository: base.repository,
64
+ baseRuleset: base.ruleset,
65
+ approvalRuleset: ownerApproval.ruleset,
66
+ };
67
+ }
68
+ function setupPlan(policy) {
69
+ return {
70
+ branch: policy.branch,
71
+ branchPath: encodeURIComponent(policy.branch),
72
+ repositoryPatchArguments: Object.entries(policy.repository)
73
+ .map(([name, value]) => `-F ${name}=${value}`).join(' '),
74
+ baseRuleset: JSON.stringify(policy.baseRuleset, null, 2),
75
+ approvalRuleset: JSON.stringify(policy.approvalRuleset, null, 2)
76
+ .replace(JSON.stringify(ownerIdMarker), "$(gh api 'users/{{REQUIRED_APPROVER}}' --jq .id)"),
77
+ };
78
+ }
79
+ function sameMembers(actual, expected) {
80
+ return actual.length === expected.length
81
+ && actual.every(value => expected.includes(value));
82
+ }
83
+ function approvalParameters(policy, parameters) {
84
+ const expected = policy.approvalRuleset.rules[0].parameters;
85
+ return parameters?.required_approving_review_count === expected.required_approving_review_count
86
+ && parameters.dismiss_stale_reviews_on_push === expected.dismiss_stale_reviews_on_push
87
+ && parameters.require_code_owner_review === expected.require_code_owner_review;
88
+ }
89
+ function requiredCheckContexts(policy) {
90
+ return policy.baseRuleset.rules
91
+ .find(rule => rule.type === 'required_status_checks').parameters.required_status_checks
92
+ .map(check => check.context);
93
+ }
94
+ function managedRulesetMatches(policy, actual) {
95
+ const expected = [policy.baseRuleset, policy.approvalRuleset]
96
+ .find(ruleset => ruleset.name === actual?.name);
97
+ if (!expected)
98
+ return true;
99
+ function matchesShape(wanted, observed) {
100
+ if (Array.isArray(wanted))
101
+ return Array.isArray(observed)
102
+ && wanted.length === observed.length
103
+ && (() => {
104
+ const unmatched = [...observed];
105
+ return wanted.every(value => {
106
+ const index = unmatched.findIndex(candidate => matchesShape(value, candidate));
107
+ if (index < 0)
108
+ return false;
109
+ unmatched.splice(index, 1);
110
+ return true;
111
+ });
112
+ })();
113
+ if (wanted && typeof wanted === 'object')
114
+ return observed && typeof observed === 'object'
115
+ && Object.entries(wanted).every(([key, value]) => matchesShape(value, observed[key]));
116
+ return wanted === observed;
117
+ }
118
+ const withoutBypass = ruleset => {
119
+ const { bypass_actors: _bypass, ...rest } = ruleset;
120
+ return rest;
121
+ };
122
+ return matchesShape(withoutBypass(expected), actual);
123
+ }
124
+ const api = { approvalParameters, createGithubPolicy, managedRulesetMatches,
125
+ requiredCheckContexts, sameMembers, setupPlan };
126
+ return api;
127
+ };
@@ -1,6 +1,8 @@
1
- export default ({ assessRelease, release, releaseCore, verifyRelease, verifyReleaseProtection, verifyReleaseVersion }) => ({
1
+ export default ({ assessRelease, githubPolicy, release, releaseCore, verifyRelease, verifyReleaseProtection, verifyReleaseVersion }) => ({
2
2
  assessRelease: assessRelease.run,
3
+ createGithubPolicy: githubPolicy.createGithubPolicy,
3
4
  ensureLockfilesMatch: releaseCore.ensureLockfilesMatch,
5
+ githubSetupPlan: githubPolicy.setupPlan,
4
6
  inspectWorkflow: releaseCore.inspectWorkflow,
5
7
  release: release.run,
6
8
  verifyRelease: verifyRelease.run,
@@ -1,4 +1,5 @@
1
- export default ({ configuration }) => {
1
+ export default ({ configuration, githubPolicy }) => {
2
+ const { approvalParameters, createGithubPolicy, managedRulesetMatches, requiredCheckContexts, sameMembers } = githubPolicy;
2
3
  function requiredPolicy(cwd) {
3
4
  const { projectConfig } = configuration;
4
5
  const config = projectConfig(cwd).git;
@@ -10,32 +11,24 @@ export default ({ configuration }) => {
10
11
  }
11
12
  return { checks: config.releaseRequiredChecks, requiredApprover: config.requiredApprover };
12
13
  }
13
- function approvalParameters(parameters) {
14
- return parameters?.required_approving_review_count === 1
15
- && parameters.dismiss_stale_reviews_on_push === true
16
- && parameters.require_code_owner_review === true;
17
- }
18
14
  const bypassWarning = 'Cannot verify bypass users unless given write access. Run a manual check instead; available as a gist.';
19
15
  // A missing classic protection is expected for ruleset-only repositories. All
20
16
  // other API failures, including permission failures, must propagate.
21
17
  function verifyProtection({ api, slug, branch, checks, requiredApprover: approver, warn }) {
22
- if (warn)
23
- warn(bypassWarning);
24
- if (!approver)
25
- throw new Error('A required GitHub approver must be provided.');
18
+ const policy = createGithubPolicy({ branch, checks, requiredApprover: approver });
26
19
  const base = `repos/${slug}`;
27
20
  const repository = api(base);
28
- if (repository?.delete_branch_on_merge !== true) {
21
+ if (repository?.delete_branch_on_merge !== policy.repository.delete_branch_on_merge) {
29
22
  throw new Error(`Repository ${slug} must enable delete_branch_on_merge. Run gh api --method PATCH ${base} -F delete_branch_on_merge=true, then rerun.`);
30
23
  }
31
- if (repository.allow_auto_merge !== true)
24
+ if (repository.allow_auto_merge !== policy.repository.allow_auto_merge)
32
25
  throw new Error('Repository must enable allow_auto_merge; this only makes auto-merge available per PR.');
33
26
  if (repository.default_branch !== branch)
34
27
  throw new Error(`Verify the actual default branch (${repository.default_branch}), not ${branch}.`);
35
28
  if (repository.owner?.type !== 'User'
36
- || repository.owner.login?.toLowerCase() !== approver.toLowerCase()
29
+ || repository.owner.login?.toLowerCase() !== policy.requiredApprover.toLowerCase()
37
30
  || !Number.isInteger(repository.owner.id)) {
38
- throw new Error(`git.requiredApprover (${approver}) must be the personal owner of repository ${slug}.`);
31
+ throw new Error(`git.requiredApprover (${policy.requiredApprover}) must be the personal owner of repository ${slug}.`);
39
32
  }
40
33
  let protection;
41
34
  try {
@@ -57,6 +50,20 @@ export default ({ configuration }) => {
57
50
  if (protection?.required_linear_history?.enabled || rules.some(rule => rule.type === 'required_linear_history')) {
58
51
  throw new Error('Default branch must allow merge commits; disable required linear history.');
59
52
  }
53
+ if (protection) {
54
+ if (protection.allow_deletions?.enabled === true)
55
+ throw new Error('Default branch must prevent deletion.');
56
+ if (protection.allow_force_pushes?.enabled === true)
57
+ throw new Error('Default branch must prevent force pushes.');
58
+ if (protection.enforce_admins?.enabled !== true)
59
+ throw new Error('Classic branch protection must include administrators.');
60
+ }
61
+ else {
62
+ if (!rules.some(rule => rule.type === 'deletion'))
63
+ throw new Error('Default branch rulesets must prevent deletion.');
64
+ if (!rules.some(rule => rule.type === 'non_fast_forward'))
65
+ throw new Error('Default branch rulesets must prevent force pushes.');
66
+ }
60
67
  const rulesets = new Map();
61
68
  function rulesetFor(rule) {
62
69
  if (!Number.isInteger(rule.ruleset_id))
@@ -68,26 +75,39 @@ export default ({ configuration }) => {
68
75
  if (!Array.isArray(ruleset.rules)) {
69
76
  throw new Error('Cannot verify all rules in a policy ruleset; grant access to the complete ruleset, then rerun.');
70
77
  }
78
+ if (!managedRulesetMatches(policy, ruleset)) {
79
+ throw new Error(`Managed ruleset ${ruleset.name} differs from Peacekeeper's generated policy. Regenerate and run the GitHub setup script.`);
80
+ }
71
81
  rulesets.set(rule.ruleset_id, ruleset);
72
82
  }
73
83
  return rulesets.get(rule.ruleset_id);
74
84
  }
75
85
  for (const rule of rules.filter(rule => Number.isInteger(rule.ruleset_id)))
76
86
  rulesetFor(rule);
87
+ for (const name of [policy.baseRuleset.name, policy.approvalRuleset.name]) {
88
+ if ([...rulesets.values()].filter(ruleset => ruleset.name === name).length > 1) {
89
+ throw new Error(`Default branch has multiple managed rulesets named ${name}. Remove duplicates, then rerun.`);
90
+ }
91
+ }
77
92
  const approvalRulesets = new Set();
78
93
  for (const [id, ruleset] of rulesets) {
79
94
  if (ruleset.rules.length === 1 && ruleset.rules[0].type === 'pull_request'
80
- && approvalParameters(ruleset.rules[0].parameters))
95
+ && approvalParameters(policy, ruleset.rules[0].parameters))
81
96
  approvalRulesets.add(id);
82
97
  }
83
98
  const classicReviews = protection?.required_pull_request_reviews;
99
+ const classicBypasses = classicReviews?.bypass_pull_request_allowances;
100
+ if (classicBypasses && ['users', 'teams', 'apps']
101
+ .some(kind => Array.isArray(classicBypasses[kind]) && classicBypasses[kind].length > 0)) {
102
+ throw new Error('Classic branch protection must not allow pull-request bypass actors.');
103
+ }
84
104
  let requiresPullRequest = Boolean(classicReviews);
85
105
  let branchMergeOnly = false;
86
106
  let approvalPolicyCount = 0;
87
107
  for (const rule of rules.filter(rule => rule.type === 'pull_request')) {
88
108
  const ruleset = rulesetFor(rule);
89
109
  if (approvalRulesets.has(rule.ruleset_id)) {
90
- if (!approvalParameters(rule.parameters)) {
110
+ if (!approvalParameters(policy, rule.parameters)) {
91
111
  throw new Error('The effective owner approval rule must require one code-owner approval and dismiss stale approvals.');
92
112
  }
93
113
  approvalPolicyCount += 1;
@@ -105,6 +125,27 @@ export default ({ configuration }) => {
105
125
  if (approvalPolicyCount !== 1 || approvalRulesets.size !== 1) {
106
126
  throw new Error('Default branch must have exactly one owner approval ruleset requiring one code-owner approval and stale approval dismissal.');
107
127
  }
128
+ let bypassUnknown = Boolean(protection);
129
+ for (const [id, ruleset] of rulesets) {
130
+ const protectsRelease = approvalRulesets.has(id)
131
+ || ruleset.rules.some(rule => ['pull_request', 'required_status_checks'].includes(rule.type || ''));
132
+ if (!protectsRelease)
133
+ continue;
134
+ if (!Array.isArray(ruleset.bypass_actors)) {
135
+ bypassUnknown = true;
136
+ continue;
137
+ }
138
+ const expected = approvalRulesets.has(id)
139
+ ? [{ actor_id: repository.owner.id, actor_type: 'User', bypass_mode: 'pull_request' }]
140
+ : [];
141
+ const actual = ruleset.bypass_actors.map(actor => ({ actor_id: actor.actor_id,
142
+ actor_type: actor.actor_type, bypass_mode: actor.bypass_mode }));
143
+ if (JSON.stringify(actual) !== JSON.stringify(expected)) {
144
+ throw new Error('Ruleset bypass actors do not match the generated Peacekeeper policy.');
145
+ }
146
+ }
147
+ if (bypassUnknown && warn)
148
+ warn(bypassWarning);
108
149
  const strictChecks = new Set();
109
150
  const classic = protection?.required_status_checks;
110
151
  if (classic?.strict === true) {
@@ -120,14 +161,20 @@ export default ({ configuration }) => {
120
161
  for (const check of rule.parameters.required_status_checks || [])
121
162
  strictChecks.add(check.context);
122
163
  }
123
- const missing = checks.filter(check => !strictChecks.has(check));
124
- if (!checks.length || missing.length) {
125
- throw new Error(`Branch ${branch} must require strict status checks for: ${missing.join(', ') || '(no checks configured)'}. Enable strict checks, then rerun.`);
164
+ const expectedChecks = requiredCheckContexts(policy);
165
+ const actualChecks = [...strictChecks];
166
+ const missing = expectedChecks.filter(check => !strictChecks.has(check));
167
+ const extra = actualChecks.filter(check => !expectedChecks.includes(check));
168
+ if (!sameMembers(actualChecks, expectedChecks)) {
169
+ const detail = [missing.length ? `missing: ${missing.join(', ')}` : '',
170
+ extra.length ? `extra: ${extra.join(', ')}` : ''].filter(Boolean).join('; ');
171
+ throw new Error(`Branch ${branch} must require exactly these strict status checks: ${expectedChecks.join(', ')}${detail ? ` (${detail})` : ''}. Enable strict checks, then rerun.`);
126
172
  }
127
173
  if (!requiresPullRequest)
128
174
  throw new Error('Default branch must require pull requests.');
129
- if (repository.allow_merge_commit !== true || (!branchMergeOnly
130
- && (repository.allow_squash_merge !== false || repository.allow_rebase_merge !== false))) {
175
+ if (repository.allow_merge_commit !== policy.repository.allow_merge_commit || (!branchMergeOnly
176
+ && (repository.allow_squash_merge !== policy.repository.allow_squash_merge
177
+ || repository.allow_rebase_merge !== policy.repository.allow_rebase_merge))) {
131
178
  throw new Error('Default branch must allow only merge commits: restrict its base pull request ruleset to merge, or disable repository squash and rebase merging.');
132
179
  }
133
180
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jakobm/peacekeeper",
3
- "version": "0.21.0",
3
+ "version": "0.23.0",
4
4
  "description": "Shared repository test, Git worktree, and Codex hook commands",
5
5
  "license": "MIT",
6
6
  "author": "Jakob Mattsson",