@jakobm/peacekeeper 0.18.0 → 0.20.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 +44 -22
- package/bin/peacekeeper.js +51 -49
- package/bin/peacekeeper.yaml +101 -0
- package/package.json +2 -1
- package/scripts/check-project-requirements.txt +32 -19
- package/scripts/check-project.js +13 -0
- package/scripts/check-test-receipt.js +2 -2
- package/scripts/create-project-core.js +114 -4
- package/scripts/project-config-defaults.json +4 -1
- package/scripts/project-config.js +6 -1
- package/scripts/release-core.js +4 -3
- package/scripts/release-protection.js +70 -31
- package/scripts/run-tests.js +2 -2
- package/scripts/verify-release-core.js +2 -2
- package/scripts/verify-release-protection.js +3 -2
- package/scripts/verify-release.js +3 -2
package/README.md
CHANGED
|
@@ -40,9 +40,19 @@ verified local commit. Inspect or remove the directory before retrying.
|
|
|
40
40
|
|
|
41
41
|
The generated executable `setup-github-config.sh` is deliberately not run by the
|
|
42
42
|
generator. Run it afterwards and complete the manual checklist at its top. It
|
|
43
|
-
configures applicable GitHub policy through `gh
|
|
44
|
-
|
|
45
|
-
|
|
43
|
+
configures applicable GitHub policy through `gh`, including automatic head-branch
|
|
44
|
+
deletion, repository-level **Allow auto-merge**, and merge commits as the only
|
|
45
|
+
permitted pull-request merge method. It creates separate base-protection and
|
|
46
|
+
owner-approval rulesets for the personal account that owns the repository. The
|
|
47
|
+
base ruleset requires a PR and strict CI without bypass; the approval ruleset
|
|
48
|
+
requires the owner configured in `git.requiredApprover` while allowing only that
|
|
49
|
+
user to bypass that ruleset from a PR. It also uses
|
|
50
|
+
`groundskeeper secrets sync --new-repo` to add the repository when synchronizing
|
|
51
|
+
`RELEASE_POLICY_TOKEN`. Published projects also document the required initial manual
|
|
52
|
+
publication with `npm login` and `npm publish`, followed by npm trusted publishing
|
|
53
|
+
setup. The authenticated `gh` token needs repository **Administration: write**
|
|
54
|
+
permission to configure repository settings and rulesets. The generator
|
|
55
|
+
never registers a publisher or publishes a package.
|
|
46
56
|
|
|
47
57
|
When moving an existing project to Peacekeeper, update its dependency and lockfile,
|
|
48
58
|
package scripts, and configuration filename together. Replace previous lifecycle
|
|
@@ -110,6 +120,7 @@ Complete example:
|
|
|
110
120
|
"remote": "origin",
|
|
111
121
|
"defaultBranch": "main",
|
|
112
122
|
"branchPrefix": "codex/",
|
|
123
|
+
"requiredApprover": "OWNER",
|
|
113
124
|
"checkpointPushRemotes": ["origin"],
|
|
114
125
|
"releaseMergeMethod": "merge",
|
|
115
126
|
"releaseRequiredChecks": ["test"],
|
|
@@ -129,7 +140,7 @@ Complete example:
|
|
|
129
140
|
}
|
|
130
141
|
```
|
|
131
142
|
|
|
132
|
-
`git.remote` and `git.defaultBranch` identify the branch used for checkpointing and cleanup. `git.branchPrefix` names new task branches. `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 --
|
|
143
|
+
`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.
|
|
133
144
|
|
|
134
145
|
`loggingEnabled` has the bundled default `true`; set it to `false` to disable invocation logs and the background cleanup worker's log file. Existing logs are kept. The setting is read from the primary checkout's configuration, including for linked worktrees. SessionStart and Stop logs include the process and event working directories, event type, primary-checkout classification, and hook response or error. Only selected event fields are logged, never the full incoming payload. These logs require the Peacekeeper script to start; a missing Node.js executable or package must be diagnosed in Codex's own logs.
|
|
135
146
|
|
|
@@ -147,7 +158,7 @@ To publish checkpoint branches automatically, set `git.checkpointPushRemotes` (f
|
|
|
147
158
|
```
|
|
148
159
|
|
|
149
160
|
Each name must identify a Git remote configured in the calling repository. Checkpoints push to exactly those remotes, creating the task branch if
|
|
150
|
-
needed.
|
|
161
|
+
needed. The bundled default is `["origin"]`; set an empty list to disable checkpoint pushes.
|
|
151
162
|
The field must be present; there is no implicit push fallback. Pushes never use force. Only a push to `git.remote` sets the
|
|
152
163
|
branch's upstream. If a push fails, earlier pushes are kept and the checkpoint
|
|
153
164
|
records a failure; fix the cause and rerun the checkpoint command to retry without
|
|
@@ -254,7 +265,7 @@ them. The shared policy then follows the installed package version.
|
|
|
254
265
|
|
|
255
266
|
## Check the setup
|
|
256
267
|
|
|
257
|
-
From the caller's Git worktree, run `npm test` for the configured commands, `npm test --
|
|
268
|
+
From the caller's Git worktree, run `npm test` for the configured commands, `npm test -- --force` to bypass a reusable receipt, `npm run cleanup:branches` to preview merged branch cleanup, and `npm run cleanup:empty-directories` to preview removal of empty directories and directories containing only ignored files. The latter command protects the root `.git`, `node_modules`, and `tmp` directories; other selected directories are removed recursively, including their ignored contents. Add `-- --execute` to either cleanup package script to apply it. Run `npm exec --no -- peacekeeper --help` for the complete command list. To create a manual checkpoint, use `npm exec --no -- peacekeeper checkpoint-codex-changes --subject "<subject>" --body "<body paragraph>"`.
|
|
258
269
|
|
|
259
270
|
Directory cleanup also preserves nested Git repositories and linked worktrees,
|
|
260
271
|
including their parent directories when those parents are ignored. It does not
|
|
@@ -270,7 +281,7 @@ the root package's own bin, including the checkpoint command requested by the
|
|
|
270
281
|
Stop hook. Install dependencies with `npm ci` to run the full test suite.
|
|
271
282
|
|
|
272
283
|
Run `npm test` in this repository to verify the shared package itself, or
|
|
273
|
-
`npm test --
|
|
284
|
+
`npm test -- --force` to force a fresh run. Its configured test command runs Node's
|
|
274
285
|
test runner directly, avoiding recursion through `npm test`. The cleanup package
|
|
275
286
|
scripts work the same way as in calling projects.
|
|
276
287
|
|
|
@@ -432,18 +443,28 @@ artifacts of tested contents. Configure `git.releaseRequiredChecks` in the root
|
|
|
432
443
|
`peacekeeper.config.json` with the exact CI job names required for a release
|
|
433
444
|
(for this repository: `["test", "Test package"]`). These checks must be mandatory
|
|
434
445
|
with **Require branches to be up to date before merging** enabled. Classic branch
|
|
435
|
-
protection
|
|
436
|
-
|
|
437
|
-
|
|
446
|
+
protection may provide the base PR and check requirements. Active base rulesets
|
|
447
|
+
may provide them instead. Merge
|
|
448
|
+
queues are not currently an alternative
|
|
438
449
|
to this strict policy. Repositories must also enable **Automatically delete head
|
|
439
450
|
branches** (`delete_branch_on_merge=true`).
|
|
440
451
|
|
|
441
|
-
The default branch must
|
|
442
|
-
|
|
452
|
+
The default branch must also have exactly one active approval ruleset. It must
|
|
453
|
+
require one approval from the sole global code owner, dismiss stale approvals
|
|
454
|
+
after new pushes, and contain no rule except that pull-request approval rule. Its
|
|
455
|
+
only bypass actor must be the personal repository owner from `git.requiredApprover`,
|
|
456
|
+
with `bypass_mode: pull_request`. This lets the owner merge their own PR without
|
|
457
|
+
approval while the separate base policy still requires a PR and successful CI.
|
|
458
|
+
No other user, team, role, or app may bypass either policy. Peacekeeper does not
|
|
459
|
+
verify bypass actors because GitHub hides them from read-only administration
|
|
460
|
+
tokens; inspect them manually instead.
|
|
461
|
+
|
|
462
|
+
Only merge commits may be used. Either disable squash and rebase
|
|
443
463
|
in repository settings, or restrict the default branch's pull-request ruleset to
|
|
444
464
|
`allowed_merge_methods: ["merge"]`. Other branches are outside this policy.
|
|
445
465
|
Required linear history and any applicable PR rule excluding merge commits fail
|
|
446
|
-
verification. PR and strict-check rules
|
|
466
|
+
verification. Bypass actors for base PR and strict-check rules also require
|
|
467
|
+
manual inspection.
|
|
447
468
|
Enable `allow_auto_merge` in repository settings: this permits opting in per PR;
|
|
448
469
|
Peacekeeper never enables auto-merge on individual PRs.
|
|
449
470
|
|
|
@@ -482,15 +503,16 @@ jobs in its latest PR workflow run. Manual tags without that PR are rejected.
|
|
|
482
503
|
`verify-release-version` remains available for local version checks alone.
|
|
483
504
|
|
|
484
505
|
API failures, missing permissions, and unverifiable rules stop the commands.
|
|
506
|
+
Bypass actors are the exception: each policy verification prints `Cannot verify
|
|
507
|
+
bypass users unless given write access. Run a manual check instead; available as
|
|
508
|
+
a gist.` and continues without inspecting them.
|
|
485
509
|
The workflow expects a `RELEASE_POLICY_TOKEN` Actions secret, exposed to the
|
|
486
510
|
commands as `GH_TOKEN`. Use a fine-grained PAT or GitHub App token with access to
|
|
487
511
|
this repository and Administration read, Contents read/write, Pull requests read and
|
|
488
512
|
Actions read permissions. Contents write is required even to read merge-related
|
|
489
|
-
settings such as `delete_branch_on_merge`.
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
for inherited organization rulesets). Missing bypass information also fails.
|
|
493
|
-
The normal workflow `GITHUB_TOKEN` cannot be granted Administration permissions
|
|
513
|
+
settings such as `delete_branch_on_merge`. Administration read is sufficient
|
|
514
|
+
because bypass actors are checked manually.
|
|
515
|
+
The normal workflow `GITHUB_TOKEN` cannot be granted Administration permission
|
|
494
516
|
through workflow YAML. After correcting access or rules, rerun the failed job.
|
|
495
517
|
Fork PRs do not receive this secret and fail the policy check; do not expose it
|
|
496
518
|
by executing fork code with `pull_request_target`.
|
|
@@ -498,8 +520,7 @@ by executing fork code with `pull_request_target`.
|
|
|
498
520
|
To set this up for this repository:
|
|
499
521
|
|
|
500
522
|
1. Open the [token creation form with the required permissions prefilled](https://github.com/settings/personal-access-tokens/new?name=peacekeeper-release-policy&target_name=jakobmattsson&expires_in=90&administration=read&contents=write&pull_requests=read&actions=read).
|
|
501
|
-
For repository
|
|
502
|
-
so GitHub exposes bypass actors. For another repository, change the resource
|
|
523
|
+
For another repository, change the resource
|
|
503
524
|
owner. Select **Only select repositories**, choose `peacekeeper`, review
|
|
504
525
|
the permissions and expiration, and generate the token. If the owner requires
|
|
505
526
|
approval, wait until the token is approved.
|
|
@@ -597,8 +618,9 @@ Explicit alternative job conditions are not supported. Workspaces are not suppor
|
|
|
597
618
|
|
|
598
619
|
Configuration migration: previously optional fields must now be declared. Run
|
|
599
620
|
`peacekeeper update-config`, review the inserted defaults, and commit the result.
|
|
600
|
-
|
|
601
|
-
|
|
621
|
+
The default `git.checkpointPushRemotes` value publishes to `origin`; use an
|
|
622
|
+
explicit empty array to keep checkpoint branches local. Empty
|
|
623
|
+
`git.releaseRequiredChecks` is valid configuration but blocks release
|
|
602
624
|
policy verification; empty `tests.commands` blocks test execution and receipts.
|
|
603
625
|
`projectChecks` always explicitly selects the workflow and jobs. This change does
|
|
604
626
|
not add online GitHub verification to `check-project`.
|
package/bin/peacekeeper.js
CHANGED
|
@@ -1,54 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
const { spawnSync } = require('node:child_process');
|
|
4
|
+
const fs = require('node:fs');
|
|
4
5
|
const path = require('node:path');
|
|
5
6
|
|
|
6
|
-
const
|
|
7
|
-
['update-config', 'Create or complete project configuration using bundled defaults.'],
|
|
8
|
-
['create-project', 'Create and verify a compliant TypeScript library in an empty GitHub repository.'],
|
|
9
|
-
['check-project', 'Validate local toolchain, hooks, CI and publication conventions.'],
|
|
10
|
-
['install-hooks', 'Install or update project Codex hooks while preserving other hooks.'],
|
|
11
|
-
['verify-release', 'Verify release versions, required CI and strict branch protection.'],
|
|
12
|
-
['verify-release-protection', 'Require strict mandatory release checks without bypass.'],
|
|
13
|
-
['verify-release-version', 'Check a release tag against package and lockfile versions.'],
|
|
14
|
-
['release', 'Publish a version through a GitHub Actions npm workflow.'],
|
|
15
|
-
['assess-release', 'Assess unpublished changes with Codex and return a JSON recommendation.'],
|
|
16
|
-
['run-tests', 'Run configured tests, reusing a valid test receipt.'],
|
|
17
|
-
['check-test-receipt', 'Check whether a valid test receipt exists.'],
|
|
18
|
-
['record-test-receipt', 'Record a test receipt without running tests.'],
|
|
19
|
-
['checkpoint-codex-changes', 'Commit a linked worktree and push according to project configuration.'],
|
|
20
|
-
['checkpoint-codex-session-start', 'Load checkpoint instructions for a linked Codex worktree.'],
|
|
21
|
-
['checkpoint-codex-stop', 'Handle the Codex Stop hook and request a checkpoint if needed.'],
|
|
22
|
-
['cleanup-ended-session', 'Queue cleanup for a merged Codex session worktree.'],
|
|
23
|
-
['queue-merged-worktree-cleanup', 'Queue cleanup for the current merged worktree.'],
|
|
24
|
-
['cleanup-merged-branches', 'Preview or delete merged worktrees and branches.'],
|
|
25
|
-
['remove-empty-directories', 'Preview or remove directories containing only ignored files.'],
|
|
26
|
-
]);
|
|
7
|
+
const CONFIG_PATH = path.join(__dirname, 'peacekeeper.yaml');
|
|
27
8
|
|
|
28
|
-
function
|
|
29
|
-
const width = Math.max(...[...COMMANDS.keys()].map((command) => command.length));
|
|
30
|
-
const commands = [...COMMANDS]
|
|
31
|
-
.map(([command, description]) => ` ${command.padEnd(width)} ${description}`)
|
|
32
|
-
.join('\n');
|
|
33
|
-
return `Usage: peacekeeper <command> [arguments]\n\nCommands:\n${commands}\n\nOptions:\n -h, --help Show this help.\n`;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
function main() {
|
|
37
|
-
const [command, ...args] = process.argv.slice(2);
|
|
38
|
-
if (command === '--help' || command === '-h') {
|
|
39
|
-
process.stdout.write(helpText());
|
|
40
|
-
return;
|
|
41
|
-
}
|
|
42
|
-
if (!COMMANDS.has(command)) {
|
|
43
|
-
const detail = command ? `Unknown command: ${command}` : 'A command is required.';
|
|
44
|
-
process.stderr.write(`${detail}\n\n${helpText()}`);
|
|
45
|
-
process.exitCode = 2;
|
|
46
|
-
return;
|
|
47
|
-
}
|
|
48
|
-
const informational = (args.length === 1 && ['--help', '-h'].includes(args[0]))
|
|
49
|
-
|| (command === 'check-project' && args.length === 1 && args[0] === '--explain');
|
|
50
|
-
const checkpointHook = ['checkpoint-codex-session-start', 'checkpoint-codex-stop'].includes(command);
|
|
51
|
-
if (!['update-config', 'assess-release', 'create-project'].includes(command) && !checkpointHook && !informational) require('../scripts/project-config').projectConfig();
|
|
9
|
+
function runScript(command, args) {
|
|
52
10
|
const script = path.resolve(__dirname, '..', 'scripts', `${command}.js`);
|
|
53
11
|
const result = spawnSync(process.execPath, [script, ...args], {
|
|
54
12
|
cwd: process.cwd(),
|
|
@@ -58,9 +16,53 @@ function main() {
|
|
|
58
16
|
process.exitCode = result.status ?? 1;
|
|
59
17
|
}
|
|
60
18
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
19
|
+
async function main() {
|
|
20
|
+
const rawArgs = process.argv.slice(2);
|
|
21
|
+
const [command, ...args] = rawArgs;
|
|
22
|
+
const script = path.resolve(__dirname, '..', 'scripts', `${command}.js`);
|
|
23
|
+
const informational = args.length === 1 && (
|
|
24
|
+
['--help', '-h'].includes(args[0])
|
|
25
|
+
|| (command === 'check-project' && args[0] === '--explain')
|
|
26
|
+
);
|
|
27
|
+
const checkpointHook = ['checkpoint-codex-session-start', 'checkpoint-codex-stop'].includes(command);
|
|
28
|
+
if (
|
|
29
|
+
fs.existsSync(script)
|
|
30
|
+
&& !['update-config', 'assess-release', 'create-project'].includes(command)
|
|
31
|
+
&& !checkpointHook
|
|
32
|
+
&& !informational
|
|
33
|
+
) require('../scripts/project-config').projectConfig();
|
|
34
|
+
|
|
35
|
+
// assess-release guarantees machine-readable JSON even for invalid arguments.
|
|
36
|
+
// Preserve that application-level error contract instead of letting the CLI parser format it.
|
|
37
|
+
if (command === 'assess-release' && args.length > 0) {
|
|
38
|
+
runScript(command, args);
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
const dependencyFreeHooks = new Set([
|
|
42
|
+
'checkpoint-codex-session-start',
|
|
43
|
+
'checkpoint-codex-stop',
|
|
44
|
+
'checkpoint-codex-changes',
|
|
45
|
+
'cleanup-ended-session',
|
|
46
|
+
]);
|
|
47
|
+
if (dependencyFreeHooks.has(command) && !informational) {
|
|
48
|
+
runScript(command, args);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const { runCli } = await import('@jakobm/cmdabra');
|
|
53
|
+
const implementation = new Proxy({}, {
|
|
54
|
+
get: (_target, name) => () => runScript(name, args),
|
|
55
|
+
});
|
|
56
|
+
await runCli(CONFIG_PATH, implementation, rawArgs);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
main().catch(async (error) => {
|
|
60
|
+
const { CmdabraUsageError } = await import('@jakobm/cmdabra');
|
|
61
|
+
if (error instanceof CmdabraUsageError) {
|
|
62
|
+
process.stderr.write(`${error.message}\n\n${error.help}`);
|
|
63
|
+
process.exitCode = error.exitCode;
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
64
66
|
console.error(`Error: ${error.message}`);
|
|
65
67
|
process.exitCode = 1;
|
|
66
|
-
}
|
|
68
|
+
});
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
name: peacekeeper
|
|
2
|
+
description: Shared repository test, Git worktree, and Codex hook commands
|
|
3
|
+
commands:
|
|
4
|
+
update-config:
|
|
5
|
+
description: Create or complete project configuration using bundled defaults.
|
|
6
|
+
create-project:
|
|
7
|
+
description: Create and verify a compliant TypeScript library in an empty GitHub repository.
|
|
8
|
+
named-options:
|
|
9
|
+
repository:
|
|
10
|
+
description: GitHub HTTPS repository URL.
|
|
11
|
+
required: true
|
|
12
|
+
directory:
|
|
13
|
+
description: Directory in which to create the project.
|
|
14
|
+
required: true
|
|
15
|
+
package-name:
|
|
16
|
+
description: npm package name.
|
|
17
|
+
required: true
|
|
18
|
+
author-name:
|
|
19
|
+
description: Package author name.
|
|
20
|
+
required: true
|
|
21
|
+
author-email:
|
|
22
|
+
description: Package author email address.
|
|
23
|
+
required: true
|
|
24
|
+
publish-to-npm:
|
|
25
|
+
description: Whether the package will be published to npm.
|
|
26
|
+
type: enum
|
|
27
|
+
choices: ["true", "false"]
|
|
28
|
+
required: true
|
|
29
|
+
check-project:
|
|
30
|
+
description: Validate local toolchain, hooks, CI and publication conventions.
|
|
31
|
+
named-options:
|
|
32
|
+
explain:
|
|
33
|
+
description: Print the complete expected project architecture.
|
|
34
|
+
type: boolean
|
|
35
|
+
install-hooks:
|
|
36
|
+
description: Install or update project Codex hooks while preserving other hooks.
|
|
37
|
+
named-options:
|
|
38
|
+
dry-run:
|
|
39
|
+
description: Preview changes without writing hooks.
|
|
40
|
+
type: boolean
|
|
41
|
+
verify-release:
|
|
42
|
+
description: Verify release versions, required CI and strict branch protection.
|
|
43
|
+
verify-release-protection:
|
|
44
|
+
description: Require strict mandatory release checks without bypass.
|
|
45
|
+
verify-release-version:
|
|
46
|
+
description: Check a release tag against package and lockfile versions.
|
|
47
|
+
release:
|
|
48
|
+
description: Publish a version through a GitHub Actions npm workflow.
|
|
49
|
+
positional-arguments:
|
|
50
|
+
bump:
|
|
51
|
+
description: Version increment to publish.
|
|
52
|
+
type: enum
|
|
53
|
+
choices: [major, minor, patch]
|
|
54
|
+
assess-release:
|
|
55
|
+
description: Assess unpublished changes with Codex and return a JSON recommendation.
|
|
56
|
+
run-tests:
|
|
57
|
+
description: Run configured tests, reusing a valid test receipt.
|
|
58
|
+
named-options:
|
|
59
|
+
force:
|
|
60
|
+
description: Run tests even when a valid receipt exists.
|
|
61
|
+
type: boolean
|
|
62
|
+
check-test-receipt:
|
|
63
|
+
description: Check whether a valid test receipt exists.
|
|
64
|
+
record-test-receipt:
|
|
65
|
+
description: Record a test receipt without running tests.
|
|
66
|
+
checkpoint-codex-changes:
|
|
67
|
+
description: Commit a linked worktree and push according to project configuration.
|
|
68
|
+
named-options:
|
|
69
|
+
subject:
|
|
70
|
+
description: Commit subject.
|
|
71
|
+
required: true
|
|
72
|
+
body:
|
|
73
|
+
description: Commit body paragraph; may be repeated.
|
|
74
|
+
required: true
|
|
75
|
+
repeatable: true
|
|
76
|
+
checkpoint-codex-session-start:
|
|
77
|
+
description: Load checkpoint instructions for a linked Codex worktree.
|
|
78
|
+
checkpoint-codex-stop:
|
|
79
|
+
description: Handle the Codex Stop hook and request a checkpoint if needed.
|
|
80
|
+
cleanup-ended-session:
|
|
81
|
+
description: Queue cleanup for a merged Codex session worktree.
|
|
82
|
+
queue-merged-worktree-cleanup:
|
|
83
|
+
description: Queue cleanup for the current merged worktree.
|
|
84
|
+
cleanup-merged-branches:
|
|
85
|
+
description: Preview or delete merged worktrees and branches.
|
|
86
|
+
named-options:
|
|
87
|
+
dry-run:
|
|
88
|
+
description: Preview cleanup without deleting anything.
|
|
89
|
+
type: boolean
|
|
90
|
+
execute:
|
|
91
|
+
description: Delete the displayed worktrees and branches.
|
|
92
|
+
type: boolean
|
|
93
|
+
remove-empty-directories:
|
|
94
|
+
description: Preview or remove directories containing only ignored files.
|
|
95
|
+
named-options:
|
|
96
|
+
dry-run:
|
|
97
|
+
description: Preview cleanup without deleting anything.
|
|
98
|
+
type: boolean
|
|
99
|
+
execute:
|
|
100
|
+
description: Remove the displayed directories.
|
|
101
|
+
type: boolean
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jakobm/peacekeeper",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.20.0",
|
|
4
4
|
"description": "Shared repository test, Git worktree, and Codex hook commands",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Jakob Mattsson",
|
|
@@ -30,6 +30,7 @@
|
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {
|
|
32
32
|
"@iarna/toml": "^2.2.5",
|
|
33
|
+
"@jakobm/cmdabra": "^0.2.1",
|
|
33
34
|
"semver": "^7.8.5",
|
|
34
35
|
"yaml": "^2.9.1"
|
|
35
36
|
},
|
|
@@ -30,6 +30,7 @@ Project configuration
|
|
|
30
30
|
|
|
31
31
|
Example configuration fields (merge into the full project configuration):
|
|
32
32
|
"git": {
|
|
33
|
+
"requiredApprover": "OWNER",
|
|
33
34
|
"releaseTestWorkflow": "package.yml",
|
|
34
35
|
"releaseRequiredChecks": ["test"]
|
|
35
36
|
},
|
|
@@ -39,6 +40,14 @@ Project configuration
|
|
|
39
40
|
}
|
|
40
41
|
projectChecks and both its fields are mandatory in an existing configuration.
|
|
41
42
|
|
|
43
|
+
git.requiredApprover must identify the personal GitHub account that owns the
|
|
44
|
+
repository. Its bundled default is null so migrations must choose explicitly.
|
|
45
|
+
check-project requires .github/CODEOWNERS to contain exactly one non-comment
|
|
46
|
+
rule matching that account:
|
|
47
|
+
* @OWNER
|
|
48
|
+
Additional ownership patterns or owners are rejected because GitHub accepts
|
|
49
|
+
any matching code owner's approval, which would weaken the identity guarantee.
|
|
50
|
+
|
|
42
51
|
Package metadata: all projects, including private packages
|
|
43
52
|
package.json must declare author and repository.
|
|
44
53
|
author must be a nonblank string or an object with a nonblank string name.
|
|
@@ -246,30 +255,31 @@ Online release policy and GitHub token setup
|
|
|
246
255
|
|
|
247
256
|
Configure the default branch from git.defaultBranch with every exact job name
|
|
248
257
|
in git.releaseRequiredChecks mandatory and "Require branches to be up to date
|
|
249
|
-
before merging" enabled.
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
- Active branch rulesets requiring strict status checks, without any bypass
|
|
253
|
-
actors. Organization-inherited rulesets are included in verification.
|
|
258
|
+
before merging" enabled. The base policy may use either classic branch
|
|
259
|
+
protection with strict status checks or active branch rulesets requiring
|
|
260
|
+
strict status checks. Its bypass configuration must be inspected manually.
|
|
254
261
|
Merge queues are not currently an alternative to this strict policy. For the
|
|
255
262
|
matrix example, also require its matrix checks as described above.
|
|
256
263
|
|
|
264
|
+
Add exactly one active owner-approval ruleset. It must contain only one
|
|
265
|
+
pull_request rule requiring exactly one code-owner approval and stale approval
|
|
266
|
+
dismissal. Its only bypass actor must be the numeric user ID corresponding to
|
|
267
|
+
git.requiredApprover, with actor_type User and bypass_mode pull_request. The
|
|
268
|
+
configured account must be the personal repository owner. This approval-only
|
|
269
|
+
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.
|
|
272
|
+
|
|
257
273
|
Create a fine-grained GitHub PAT or GitHub App installation token with access
|
|
258
274
|
to this repository and these repository permissions:
|
|
259
275
|
Administration: read
|
|
260
276
|
Contents: read/write
|
|
261
277
|
Pull requests: read
|
|
262
278
|
Actions: read
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
Consult GitHub's organization ruleset endpoint documentation for supported
|
|
268
|
-
token types and organization permissions (the fine-grained token section):
|
|
269
|
-
https://docs.github.com/en/rest/orgs/rules#get-an-organization-repository-ruleset
|
|
270
|
-
The token must also have write access to the contributing ruleset for GitHub
|
|
271
|
-
to expose bypass actors. Missing bypass information causes verification to
|
|
272
|
-
fail; confirm access with verify-release-protection.
|
|
279
|
+
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
|
+
Cannot verify bypass users unless given write access. Run a manual check
|
|
282
|
+
instead; available as a gist.
|
|
273
283
|
|
|
274
284
|
Recommended Actions secret name: RELEASE_POLICY_TOKEN. A maintainer with
|
|
275
285
|
permission to manage Actions secrets can save it with:
|
|
@@ -392,13 +402,16 @@ Default-branch GitHub policy chain
|
|
|
392
402
|
This applies to private projects too; configure nonempty releaseRequiredChecks.
|
|
393
403
|
|
|
394
404
|
Online verification reads the actual GitHub default branch and requires PRs,
|
|
395
|
-
strict mandatory configured checks
|
|
396
|
-
|
|
397
|
-
|
|
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
|
|
408
|
+
repository allow_auto_merge; this only offers per-PR opt-in and does not
|
|
409
|
+
activate auto-merge for any PR.
|
|
398
410
|
Restrict merge methods either repository-wide (merge enabled, squash and rebase
|
|
399
411
|
disabled) or with a default-branch PR ruleset allowing only merge. Other branches
|
|
400
412
|
are not checked. Linear-history rules or PR rules excluding merge are errors.
|
|
401
|
-
|
|
413
|
+
Base PR requirements, like status checks, require active rules. Inspect all
|
|
414
|
+
bypass actors manually.
|
|
402
415
|
Existing automatic head-branch deletion requirements still apply.
|
|
403
416
|
|
|
404
417
|
Missing CI is detected on the next local npm test. GitHub settings are checked
|
package/scripts/check-project.js
CHANGED
|
@@ -56,6 +56,19 @@ function checkProject(cwd = process.cwd()) {
|
|
|
56
56
|
'package.json: repository must be a nonblank string or an object with a nonblank url.');
|
|
57
57
|
});
|
|
58
58
|
|
|
59
|
+
check('GitHub policy', () => {
|
|
60
|
+
const approver = config.git.requiredApprover;
|
|
61
|
+
requireThat(typeof approver === 'string',
|
|
62
|
+
'peacekeeper.config.json: set git.requiredApprover to the personal GitHub repository owner.');
|
|
63
|
+
if (typeof approver !== 'string') return;
|
|
64
|
+
const file = '.github/CODEOWNERS';
|
|
65
|
+
const lines = read(root, file, value => value.split(/\r?\n/u))
|
|
66
|
+
.map(line => line.trim())
|
|
67
|
+
.filter(line => line && !line.startsWith('#'));
|
|
68
|
+
requireThat(isDeepStrictEqual(lines, [`* @${approver}`]),
|
|
69
|
+
`${file}: use exactly one ownership rule, "* @${approver}", so only git.requiredApprover can satisfy required code-owner review.`);
|
|
70
|
+
});
|
|
71
|
+
|
|
59
72
|
const workflows = new Map();
|
|
60
73
|
check('CI', () => {
|
|
61
74
|
const directory = path.join(root, '.github/workflows');
|
|
@@ -5,8 +5,8 @@ const { ROOT, environmentFingerprint, receiptPath, snapshot } = require('./recei
|
|
|
5
5
|
const { projectConfig, requireTestCommands } = require('./project-config');
|
|
6
6
|
function successMessage(root = ROOT()) {
|
|
7
7
|
const command = projectConfig(root).tests.npmTestUsesRunner
|
|
8
|
-
? 'npm test --
|
|
9
|
-
: 'node node_modules/@jakobm/peacekeeper/bin/peacekeeper.js run-tests
|
|
8
|
+
? 'npm test -- --force'
|
|
9
|
+
: 'node node_modules/@jakobm/peacekeeper/bin/peacekeeper.js run-tests --force';
|
|
10
10
|
return `Tests already passed for this change set. In order to rerun tests anyway, use: ${command}`;
|
|
11
11
|
}
|
|
12
12
|
|
|
@@ -79,16 +79,124 @@ function write(root, name, contents, mode = 0o644) {
|
|
|
79
79
|
}
|
|
80
80
|
|
|
81
81
|
function workflow(published) {
|
|
82
|
-
return `name: Test\n\non:\n pull_request:\n branches: [main]\n\npermissions:\n contents: read\n\njobs:\n test:\n runs-on: ubuntu-24.04\n steps:\n - uses: actions/checkout@v7\n - uses: volta-cli/action@v5\n - run: npm ci\n - name: Verify strict release policy\n env:\n GH_TOKEN: \${{ secrets.RELEASE_POLICY_TOKEN }}\n run: peacekeeper verify-release-protection\n - run: npm test\n${published ? `\n package:\n name: Test package\n runs-on: ubuntu-24.04\n steps:\n - uses: actions/checkout@v7\n - uses: volta-cli/action@v5\n - run: npm ci\n - run: npm run test:package\n` : ''}`;
|
|
82
|
+
return `name: Test\n\non:\n pull_request:\n branches: [main]\n\npermissions:\n contents: read\n\njobs:\n test:\n runs-on: ubuntu-24.04\n steps:\n - uses: actions/checkout@v7\n - uses: volta-cli/action@v5\n - run: npm ci\n - name: Verify strict release policy\n env:\n GH_TOKEN: \${{ secrets.RELEASE_POLICY_TOKEN }}\n run: npm exec --no -- peacekeeper verify-release-protection\n - run: npm test\n${published ? `\n package:\n name: Test package\n runs-on: ubuntu-24.04\n steps:\n - uses: actions/checkout@v7\n - uses: volta-cli/action@v5\n - run: npm ci\n - run: npm run test:package\n` : ''}`;
|
|
83
83
|
}
|
|
84
84
|
|
|
85
85
|
function publishWorkflow() {
|
|
86
|
-
return `name: Publish\n\non:\n push:\n tags: ['v*']\n\npermissions:\n contents: read\n\njobs:\n publish:\n name: Publish to npm\n runs-on: ubuntu-24.04\n permissions:\n contents: read\n actions: read\n pull-requests: read\n id-token: write\n steps:\n - uses: actions/checkout@v7\n - uses: volta-cli/action@v5\n with:\n registry-url: https://registry.npmjs.org\n - run: npm ci\n - name: Verify release\n env:\n GH_TOKEN: \${{ secrets.RELEASE_POLICY_TOKEN }}\n RELEASE_TAG: \${{ github.ref_name }}\n run: peacekeeper verify-release\n - run: npm publish\n`;
|
|
86
|
+
return `name: Publish\n\non:\n push:\n tags: ['v*']\n\npermissions:\n contents: read\n\njobs:\n publish:\n name: Publish to npm\n runs-on: ubuntu-24.04\n permissions:\n contents: read\n actions: read\n pull-requests: read\n id-token: write\n steps:\n - uses: actions/checkout@v7\n - uses: volta-cli/action@v5\n with:\n registry-url: https://registry.npmjs.org\n - run: npm ci\n - name: Verify release\n env:\n GH_TOKEN: \${{ secrets.RELEASE_POLICY_TOKEN }}\n RELEASE_TAG: \${{ github.ref_name }}\n run: npm exec --no -- peacekeeper verify-release\n - run: npm publish\n`;
|
|
87
87
|
}
|
|
88
88
|
|
|
89
89
|
function githubSetup({ owner, repositoryName, published }) {
|
|
90
|
-
const npm = published ? `# -
|
|
91
|
-
|
|
90
|
+
const npm = published ? `# - Publish the package manually once from this directory before configuring npm trusted publishing:
|
|
91
|
+
# npm login
|
|
92
|
+
# npm publish
|
|
93
|
+
# - Configure npm trusted publishing for GitHub repository ${owner}/${repositoryName} and workflow publish.yml.
|
|
94
|
+
` : '';
|
|
95
|
+
return `#!/usr/bin/env bash
|
|
96
|
+
# Manual checklist:
|
|
97
|
+
# - Run this script yourself after the initial project has been pushed.
|
|
98
|
+
# - Authenticate gh with Administration: write access to this repository.
|
|
99
|
+
${npm}set -euo pipefail
|
|
100
|
+
|
|
101
|
+
repo=${owner}/${repositoryName}
|
|
102
|
+
required_approver=${owner}
|
|
103
|
+
gh auth status
|
|
104
|
+
gh repo view "$repo" >/dev/null
|
|
105
|
+
actual_owner=$(gh api "repos/$repo" --jq .owner.login)
|
|
106
|
+
if [[ "$actual_owner" != "$required_approver" ]]; then
|
|
107
|
+
printf 'Expected personal repository owner %s, found %s.\n' "$required_approver" "$actual_owner" >&2
|
|
108
|
+
exit 1
|
|
109
|
+
fi
|
|
110
|
+
approver_id=$(gh api "users/$required_approver" --jq .id)
|
|
111
|
+
gh api --method PATCH "repos/$repo" \\
|
|
112
|
+
-F delete_branch_on_merge=true \\
|
|
113
|
+
-F allow_auto_merge=true \\
|
|
114
|
+
-F allow_merge_commit=true \\
|
|
115
|
+
-F allow_squash_merge=false \\
|
|
116
|
+
-F allow_rebase_merge=false >/dev/null
|
|
117
|
+
policy_dir=$(mktemp -d)
|
|
118
|
+
trap 'rm -rf -- "$policy_dir"' EXIT
|
|
119
|
+
base_policy="$policy_dir/base.json"
|
|
120
|
+
approval_policy="$policy_dir/approval.json"
|
|
121
|
+
cat >"$base_policy" <<'JSON'
|
|
122
|
+
{
|
|
123
|
+
"name": "Peacekeeper base protection",
|
|
124
|
+
"target": "branch",
|
|
125
|
+
"enforcement": "active",
|
|
126
|
+
"bypass_actors": [],
|
|
127
|
+
"conditions": { "ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] } },
|
|
128
|
+
"rules": [
|
|
129
|
+
{ "type": "deletion" },
|
|
130
|
+
{ "type": "non_fast_forward" },
|
|
131
|
+
{
|
|
132
|
+
"type": "pull_request",
|
|
133
|
+
"parameters": {
|
|
134
|
+
"required_approving_review_count": 0,
|
|
135
|
+
"dismiss_stale_reviews_on_push": false,
|
|
136
|
+
"require_code_owner_review": false,
|
|
137
|
+
"require_last_push_approval": false,
|
|
138
|
+
"required_review_thread_resolution": false,
|
|
139
|
+
"allowed_merge_methods": ["merge"]
|
|
140
|
+
}
|
|
141
|
+
},
|
|
142
|
+
{
|
|
143
|
+
"type": "required_status_checks",
|
|
144
|
+
"parameters": {
|
|
145
|
+
"strict_required_status_checks_policy": true,
|
|
146
|
+
"do_not_enforce_on_create": false,
|
|
147
|
+
"required_status_checks": [{ "context": "test" }]
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
]
|
|
151
|
+
}
|
|
152
|
+
JSON
|
|
153
|
+
cat >"$approval_policy" <<JSON
|
|
154
|
+
{
|
|
155
|
+
"name": "Peacekeeper owner approval",
|
|
156
|
+
"target": "branch",
|
|
157
|
+
"enforcement": "active",
|
|
158
|
+
"bypass_actors": [
|
|
159
|
+
{ "actor_id": $approver_id, "actor_type": "User", "bypass_mode": "pull_request" }
|
|
160
|
+
],
|
|
161
|
+
"conditions": { "ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] } },
|
|
162
|
+
"rules": [
|
|
163
|
+
{
|
|
164
|
+
"type": "pull_request",
|
|
165
|
+
"parameters": {
|
|
166
|
+
"required_approving_review_count": 1,
|
|
167
|
+
"dismiss_stale_reviews_on_push": true,
|
|
168
|
+
"require_code_owner_review": true,
|
|
169
|
+
"require_last_push_approval": false,
|
|
170
|
+
"required_review_thread_resolution": false,
|
|
171
|
+
"allowed_merge_methods": ["merge"]
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
]
|
|
175
|
+
}
|
|
176
|
+
JSON
|
|
177
|
+
|
|
178
|
+
upsert_ruleset() {
|
|
179
|
+
local name=$1 payload=$2 ids count id
|
|
180
|
+
ids=$(gh api --paginate "repos/$repo/rulesets?includes_parents=false" --jq ".[] | select(.name == \"$name\") | .id")
|
|
181
|
+
count=$(printf '%s\n' "$ids" | sed '/^$/d' | wc -l | tr -d ' ')
|
|
182
|
+
if [[ "$count" == 0 ]]; then
|
|
183
|
+
gh api --method POST "repos/$repo/rulesets" --input "$payload" >/dev/null
|
|
184
|
+
elif [[ "$count" == 1 ]]; then
|
|
185
|
+
id=$ids
|
|
186
|
+
gh api --method PUT "repos/$repo/rulesets/$id" --input "$payload" >/dev/null
|
|
187
|
+
else
|
|
188
|
+
printf 'Multiple rulesets named %s exist; remove duplicates before retrying.\n' "$name" >&2
|
|
189
|
+
exit 1
|
|
190
|
+
fi
|
|
191
|
+
}
|
|
192
|
+
upsert_ruleset 'Peacekeeper base protection' "$base_policy"
|
|
193
|
+
upsert_ruleset 'Peacekeeper owner approval' "$approval_policy"
|
|
194
|
+
if gh api "repos/$repo/branches/main/protection" >/dev/null 2>&1; then
|
|
195
|
+
gh api --method DELETE "repos/$repo/branches/main/protection" >/dev/null
|
|
196
|
+
fi
|
|
197
|
+
groundskeeper secrets sync --name RELEASE_POLICY_TOKEN --new-repo "$repo"
|
|
198
|
+
printf 'GitHub configuration completed for %s.\\n' "$repo"
|
|
199
|
+
`;
|
|
92
200
|
}
|
|
93
201
|
|
|
94
202
|
function packageTest() {
|
|
@@ -116,6 +224,7 @@ function generate(root, options) {
|
|
|
116
224
|
if (options.published) write(root, 'scripts/test-package.cjs', packageTest().replace('${PACKAGE_NAME}', options.packageName));
|
|
117
225
|
const defaults = structuredClone(require('./project-config-defaults.json'));
|
|
118
226
|
defaults.publishesToNpm = options.published;
|
|
227
|
+
defaults.git.requiredApprover = options.owner;
|
|
119
228
|
defaults.tests.commands = ['npm run typecheck', 'npm run build', 'npm run test:unit', ...(options.published ? ['npm run test:package'] : [])];
|
|
120
229
|
defaults.tests.npmTestUsesRunner = true;
|
|
121
230
|
write(root, 'peacekeeper.config.json', json(defaults));
|
|
@@ -123,6 +232,7 @@ function generate(root, options) {
|
|
|
123
232
|
const prefix = fs.readFileSync(path.join(__dirname, 'codex-setup-prefix.sh'), 'utf8');
|
|
124
233
|
write(root, '.codex/environments/environment.toml', `version = 1\nname = ${JSON.stringify(options.repositoryName)}\n\n[setup]\nscript = '''\n${prefix}'''\n`);
|
|
125
234
|
write(root, '.github/workflows/test.yml', workflow(options.published));
|
|
235
|
+
write(root, '.github/CODEOWNERS', `* @${options.owner}\n`);
|
|
126
236
|
if (options.published) write(root, '.github/workflows/publish.yml', publishWorkflow());
|
|
127
237
|
write(root, '.gitignore', 'node_modules/\n*.tgz\ntmp/\n');
|
|
128
238
|
write(root, 'README.md', `# ${options.repositoryName}\n\nA TypeScript library generated by Peacekeeper.\n\n## API\n\n\`hello()\` returns \`"hello world"\`.\n`);
|
|
@@ -14,7 +14,7 @@ function repositoryRoot(cwd = process.cwd()) {
|
|
|
14
14
|
// Kept independent of the defaults so additions require an explicit default.
|
|
15
15
|
const CONFIG_SCHEMA = {
|
|
16
16
|
publishesToNpm: true,
|
|
17
|
-
git: { remote: true, defaultBranch: true, branchPrefix: true,
|
|
17
|
+
git: { remote: true, defaultBranch: true, branchPrefix: true, requiredApprover: true,
|
|
18
18
|
checkpointPushRemotes: true, releaseMergeMethod: true,
|
|
19
19
|
releaseRequiredChecks: true, releaseTestWorkflow: true },
|
|
20
20
|
tests: { commands: true, receiptMaxAgeMinutes: true, npmTestUsesRunner: true },
|
|
@@ -59,6 +59,11 @@ function validateConfig(config, file) {
|
|
|
59
59
|
for (const field of ['remote', 'defaultBranch', 'branchPrefix']) {
|
|
60
60
|
requireNonemptyString(config.git[field], `git.${field}`, file);
|
|
61
61
|
}
|
|
62
|
+
if (config.git.requiredApprover !== null
|
|
63
|
+
&& (typeof config.git.requiredApprover !== 'string'
|
|
64
|
+
|| !/^(?!-)(?!.*--)[A-Za-z0-9-]{1,39}(?<!-)$/u.test(config.git.requiredApprover))) {
|
|
65
|
+
throw new Error(`${file}: git.requiredApprover must be null or a valid GitHub username`);
|
|
66
|
+
}
|
|
62
67
|
const remotes = config.git.checkpointPushRemotes;
|
|
63
68
|
if (!Array.isArray(remotes)
|
|
64
69
|
|| remotes.some((remote) => typeof remote !== 'string' || remote.trim() === ''
|
package/scripts/release-core.js
CHANGED
|
@@ -3,7 +3,7 @@ const fs = require('node:fs');
|
|
|
3
3
|
const os = require('node:os');
|
|
4
4
|
const path = require('node:path');
|
|
5
5
|
const yaml = require('yaml');
|
|
6
|
-
const { githubApi,
|
|
6
|
+
const { bypassWarning, githubApi, requiredPolicy, verifyProtection } = require('./release-protection');
|
|
7
7
|
const { projectConfig } = require('./project-config');
|
|
8
8
|
const requiredCondition = "${{ github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') }}";
|
|
9
9
|
const stableVersion = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u;
|
|
@@ -235,7 +235,7 @@ function prepare(exec, cwd, bump, log) {
|
|
|
235
235
|
if (typeof defaultBranch !== 'string' || !defaultBranch) {
|
|
236
236
|
throw new ReleaseError('GitHub did not provide the default branch.');
|
|
237
237
|
}
|
|
238
|
-
verifyProtection({ api: githubApi(exec, cwd, host), slug, branch: defaultBranch,
|
|
238
|
+
verifyProtection({ api: githubApi(exec, cwd, host), slug, branch: defaultBranch, ...requiredPolicy(cwd) });
|
|
239
239
|
checked(exec, 'git', ['fetch', 'origin', defaultBranch], cwd);
|
|
240
240
|
const manifest = JSON.parse(checkedOutput(exec, 'git', ['show', `origin/${defaultBranch}:package.json`], cwd));
|
|
241
241
|
const packageInfo = { name: manifest.name, version: manifest.version };
|
|
@@ -373,7 +373,7 @@ async function mergeRelease(exec, cwd, details, now, sleep, log) {
|
|
|
373
373
|
if (pr.mergeable_state === 'dirty')
|
|
374
374
|
throw new ReleaseError(`Release PR #${details.pr} has conflicts; inspect it before continuing.`);
|
|
375
375
|
verifyProtection({ api: githubApi(exec, cwd, details.host), slug: details.slug,
|
|
376
|
-
branch: details.defaultBranch,
|
|
376
|
+
branch: details.defaultBranch, ...requiredPolicy(cwd) });
|
|
377
377
|
if (details.mergeMethod && details.mergeMethod !== 'merge') throw new ReleaseError('Release must use merge commits on the default branch; restart this release.');
|
|
378
378
|
// GitHub enforces required checks, reviews, and branch freshness on this request.
|
|
379
379
|
const result = exec('gh', ['api', '--hostname', details.host, '--method', 'PUT',
|
|
@@ -394,6 +394,7 @@ async function mergeRelease(exec, cwd, details, now, sleep, log) {
|
|
|
394
394
|
}
|
|
395
395
|
async function release(bump, dependencies) {
|
|
396
396
|
const { cwd, spawnSync, environment, now, sleep, log } = dependencies;
|
|
397
|
+
log(bypassWarning);
|
|
397
398
|
const exec = (command, args, options) => execute(spawnSync, environment, command, args, options);
|
|
398
399
|
const common = path.resolve(cwd, checked(exec, 'git', ['rev-parse', '--git-common-dir'], cwd));
|
|
399
400
|
const statePath = path.join(common, 'peacekeeper-release.json');
|
|
@@ -1,15 +1,30 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
function
|
|
3
|
+
function requiredPolicy(cwd) {
|
|
4
4
|
const { projectConfig } = require('./project-config');
|
|
5
|
-
const
|
|
6
|
-
if (!
|
|
7
|
-
|
|
5
|
+
const config = projectConfig(cwd).git;
|
|
6
|
+
if (!config.releaseRequiredChecks?.length) {
|
|
7
|
+
throw new Error('Configure git.releaseRequiredChecks with the CI jobs required for releases.');
|
|
8
|
+
}
|
|
9
|
+
if (!config.requiredApprover) {
|
|
10
|
+
throw new Error('Configure git.requiredApprover with the personal GitHub repository owner.');
|
|
11
|
+
}
|
|
12
|
+
return { checks: config.releaseRequiredChecks, requiredApprover: config.requiredApprover };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function approvalParameters(parameters) {
|
|
16
|
+
return parameters?.required_approving_review_count === 1
|
|
17
|
+
&& parameters.dismiss_stale_reviews_on_push === true
|
|
18
|
+
&& parameters.require_code_owner_review === true;
|
|
8
19
|
}
|
|
9
20
|
|
|
21
|
+
const bypassWarning = 'Cannot verify bypass users unless given write access. Run a manual check instead; available as a gist.';
|
|
22
|
+
|
|
10
23
|
// A missing classic protection is expected for ruleset-only repositories. All
|
|
11
24
|
// other API failures, including permission failures, must propagate.
|
|
12
|
-
function verifyProtection({ api, slug, branch, checks }) {
|
|
25
|
+
function verifyProtection({ api, slug, branch, checks, requiredApprover: approver, warn }) {
|
|
26
|
+
if (warn) warn(bypassWarning);
|
|
27
|
+
if (!approver) throw new Error('A required GitHub approver must be provided.');
|
|
13
28
|
const base = `repos/${slug}`;
|
|
14
29
|
const repository = api(base);
|
|
15
30
|
if (repository?.delete_branch_on_merge !== true) {
|
|
@@ -17,6 +32,11 @@ function verifyProtection({ api, slug, branch, checks }) {
|
|
|
17
32
|
}
|
|
18
33
|
if (repository.allow_auto_merge !== true) throw new Error('Repository must enable allow_auto_merge; this only makes auto-merge available per PR.');
|
|
19
34
|
if (repository.default_branch !== branch) throw new Error(`Verify the actual default branch (${repository.default_branch}), not ${branch}.`);
|
|
35
|
+
if (repository.owner?.type !== 'User'
|
|
36
|
+
|| repository.owner.login?.toLowerCase() !== approver.toLowerCase()
|
|
37
|
+
|| !Number.isInteger(repository.owner.id)) {
|
|
38
|
+
throw new Error(`git.requiredApprover (${approver}) must be the personal owner of repository ${slug}.`);
|
|
39
|
+
}
|
|
20
40
|
let protection;
|
|
21
41
|
try {
|
|
22
42
|
protection = api(`${base}/branches/${encodeURIComponent(branch)}/protection`);
|
|
@@ -33,51 +53,70 @@ function verifyProtection({ api, slug, branch, checks }) {
|
|
|
33
53
|
if (protection?.required_linear_history?.enabled || rules.some(rule => rule.type === 'required_linear_history')) {
|
|
34
54
|
throw new Error('Default branch must allow merge commits; disable required linear history.');
|
|
35
55
|
}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
&& !(protection.required_pull_request_reviews.bypass_pull_request_allowances?.teams?.length)
|
|
40
|
-
&& !(protection.required_pull_request_reviews.bypass_pull_request_allowances?.apps?.length));
|
|
41
|
-
let branchMergeOnly = false;
|
|
42
|
-
const verifiedRulesets = new Set();
|
|
43
|
-
function verifyRuleset(rule) {
|
|
56
|
+
|
|
57
|
+
const rulesets = new Map();
|
|
58
|
+
function rulesetFor(rule) {
|
|
44
59
|
if (!Number.isInteger(rule.ruleset_id)) throw new Error('GitHub did not identify the policy ruleset.');
|
|
45
|
-
if (
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
60
|
+
if (!rulesets.has(rule.ruleset_id)) {
|
|
61
|
+
const ruleset = api(`${base}/rulesets/${rule.ruleset_id}`);
|
|
62
|
+
if (ruleset.enforcement !== 'active') throw new Error('Policy rulesets must be active.');
|
|
63
|
+
if (!Array.isArray(ruleset.rules)) {
|
|
64
|
+
throw new Error('Cannot verify all rules in a policy ruleset; grant access to the complete ruleset, then rerun.');
|
|
65
|
+
}
|
|
66
|
+
rulesets.set(rule.ruleset_id, ruleset);
|
|
49
67
|
}
|
|
50
|
-
|
|
51
|
-
verifiedRulesets.add(rule.ruleset_id);
|
|
68
|
+
return rulesets.get(rule.ruleset_id);
|
|
52
69
|
}
|
|
53
|
-
for (const rule of
|
|
54
|
-
|
|
55
|
-
|
|
70
|
+
for (const rule of rules.filter(rule => Number.isInteger(rule.ruleset_id))) rulesetFor(rule);
|
|
71
|
+
|
|
72
|
+
const approvalRulesets = new Set();
|
|
73
|
+
for (const [id, ruleset] of rulesets) {
|
|
74
|
+
if (ruleset.rules.length === 1 && ruleset.rules[0].type === 'pull_request'
|
|
75
|
+
&& approvalParameters(ruleset.rules[0].parameters)) approvalRulesets.add(id);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const classicReviews = protection?.required_pull_request_reviews;
|
|
79
|
+
let requiresPullRequest = Boolean(classicReviews);
|
|
80
|
+
let branchMergeOnly = false;
|
|
81
|
+
let approvalPolicyCount = 0;
|
|
82
|
+
for (const rule of rules.filter(rule => rule.type === 'pull_request')) {
|
|
83
|
+
const ruleset = rulesetFor(rule);
|
|
84
|
+
if (approvalRulesets.has(rule.ruleset_id)) {
|
|
85
|
+
if (!approvalParameters(rule.parameters)) {
|
|
86
|
+
throw new Error('The effective owner approval rule must require one code-owner approval and dismiss stale approvals.');
|
|
87
|
+
}
|
|
88
|
+
approvalPolicyCount += 1;
|
|
89
|
+
} else {
|
|
90
|
+
requiresPullRequest = true;
|
|
91
|
+
}
|
|
56
92
|
const methods = rule.parameters?.allowed_merge_methods;
|
|
57
93
|
if (methods && !methods.includes('merge')) throw new Error('Default branch PR rules must allow merge commits.');
|
|
58
|
-
if (Array.isArray(methods) && methods.length === 1 && methods[0] === 'merge'
|
|
94
|
+
if (Array.isArray(methods) && methods.length === 1 && methods[0] === 'merge'
|
|
95
|
+
&& !approvalRulesets.has(rule.ruleset_id)) branchMergeOnly = true;
|
|
96
|
+
}
|
|
97
|
+
if (approvalPolicyCount !== 1 || approvalRulesets.size !== 1) {
|
|
98
|
+
throw new Error('Default branch must have exactly one owner approval ruleset requiring one code-owner approval and stale approval dismissal.');
|
|
59
99
|
}
|
|
100
|
+
|
|
60
101
|
const strictChecks = new Set();
|
|
61
102
|
const classic = protection?.required_status_checks;
|
|
62
|
-
if (classic?.strict === true
|
|
103
|
+
if (classic?.strict === true) {
|
|
63
104
|
for (const check of classic.checks || []) strictChecks.add(check.context);
|
|
64
105
|
for (const context of classic.contexts || []) strictChecks.add(context);
|
|
65
106
|
}
|
|
66
|
-
// Ruleset bypass actors are not included in the effective-rules response.
|
|
67
|
-
// Read every contributing ruleset and require that it has no bypass actors.
|
|
68
107
|
for (const rule of rules.filter(rule => rule.type === 'required_status_checks')) {
|
|
108
|
+
rulesetFor(rule);
|
|
69
109
|
if (rule.parameters?.strict_required_status_checks_policy !== true) continue;
|
|
70
|
-
verifyRuleset(rule);
|
|
71
110
|
for (const check of rule.parameters.required_status_checks || []) strictChecks.add(check.context);
|
|
72
111
|
}
|
|
73
112
|
const missing = checks.filter(check => !strictChecks.has(check));
|
|
74
113
|
if (!checks.length || missing.length) {
|
|
75
|
-
throw new Error(`Branch ${branch} must require strict status checks
|
|
114
|
+
throw new Error(`Branch ${branch} must require strict status checks for: ${missing.join(', ') || '(no checks configured)'}. Enable strict checks, then rerun.`);
|
|
76
115
|
}
|
|
77
|
-
if (!requiresPullRequest) throw new Error('Default branch must require pull requests
|
|
116
|
+
if (!requiresPullRequest) throw new Error('Default branch must require pull requests.');
|
|
78
117
|
if (repository.allow_merge_commit !== true || (!branchMergeOnly
|
|
79
118
|
&& (repository.allow_squash_merge !== false || repository.allow_rebase_merge !== false))) {
|
|
80
|
-
throw new Error('Default branch must allow only merge commits: restrict its pull request ruleset to merge, or disable repository squash and rebase merging.');
|
|
119
|
+
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.');
|
|
81
120
|
}
|
|
82
121
|
}
|
|
83
122
|
|
|
@@ -93,4 +132,4 @@ function githubApi(exec, cwd, host) {
|
|
|
93
132
|
};
|
|
94
133
|
}
|
|
95
134
|
|
|
96
|
-
module.exports = { githubApi,
|
|
135
|
+
module.exports = { bypassWarning, githubApi, requiredPolicy, verifyProtection };
|
package/scripts/run-tests.js
CHANGED
|
@@ -25,9 +25,9 @@ function hasReusableReceipt() {
|
|
|
25
25
|
function main() {
|
|
26
26
|
requireTestCommands();
|
|
27
27
|
const config = projectConfig();
|
|
28
|
-
const force = process.argv.length === 3 && [
|
|
28
|
+
const force = process.argv.length === 3 && process.argv[2] === '--force';
|
|
29
29
|
if (process.argv.length !== 2 && !force) {
|
|
30
|
-
console.error('Usage: node scripts/run-tests.js [
|
|
30
|
+
console.error('Usage: node scripts/run-tests.js [--force]');
|
|
31
31
|
process.exitCode = 2;
|
|
32
32
|
return;
|
|
33
33
|
}
|
|
@@ -12,9 +12,9 @@ function list(api, endpoint, member) {
|
|
|
12
12
|
}
|
|
13
13
|
}
|
|
14
14
|
|
|
15
|
-
function verifyRelease({ api, slug, sha, tag, branch, checks, workflow }) {
|
|
15
|
+
function verifyRelease({ api, slug, sha, tag, branch, checks, requiredApprover, workflow, warn }) {
|
|
16
16
|
if (!/^v\d+\.\d+\.\d+$/u.test(tag)) throw new Error('Expected a stable release tag');
|
|
17
|
-
verifyProtection({ api, slug, branch, checks });
|
|
17
|
+
verifyProtection({ api, slug, branch, checks, requiredApprover, warn });
|
|
18
18
|
const base = `repos/${slug}`;
|
|
19
19
|
const commit = api(`${base}/commits/${encodeURIComponent(sha)}`);
|
|
20
20
|
const comparison = api(`${base}/compare/${commit.sha}...${encodeURIComponent(branch)}`);
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
const { spawnSync } = require('node:child_process');
|
|
4
4
|
const { projectConfig } = require('./project-config');
|
|
5
5
|
const { originRepository } = require('./release-core');
|
|
6
|
-
const { githubApi,
|
|
6
|
+
const { githubApi, requiredPolicy, verifyProtection } = require('./release-protection');
|
|
7
7
|
|
|
8
8
|
try {
|
|
9
9
|
const cwd = process.cwd();
|
|
@@ -12,7 +12,8 @@ try {
|
|
|
12
12
|
if (remote.status !== 0) throw new Error(remote.stderr);
|
|
13
13
|
const { host, slug } = originRepository(remote.stdout.trim());
|
|
14
14
|
const api = githubApi((command, args, options) => spawnSync(command, args, { ...options, encoding: 'utf8' }), cwd, host);
|
|
15
|
-
verifyProtection({ api, slug, branch: api(`repos/${slug}`).default_branch,
|
|
15
|
+
verifyProtection({ api, slug, branch: api(`repos/${slug}`).default_branch,
|
|
16
|
+
...requiredPolicy(cwd), warn: message => console.warn(message) });
|
|
16
17
|
} catch (error) {
|
|
17
18
|
console.error(error.message);
|
|
18
19
|
process.exitCode = 1;
|
|
@@ -4,7 +4,7 @@ const { spawnSync, execFileSync } = require('node:child_process');
|
|
|
4
4
|
const path = require('node:path');
|
|
5
5
|
const { projectConfig } = require('./project-config');
|
|
6
6
|
const { originRepository, inspectWorkflow } = require('./release-core');
|
|
7
|
-
const { githubApi,
|
|
7
|
+
const { githubApi, requiredPolicy } = require('./release-protection');
|
|
8
8
|
const { verifyRelease } = require('./verify-release-core');
|
|
9
9
|
|
|
10
10
|
try {
|
|
@@ -19,7 +19,8 @@ try {
|
|
|
19
19
|
const sha = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();
|
|
20
20
|
inspectWorkflow(cwd, tag);
|
|
21
21
|
verifyRelease({ api, slug, sha, tag, branch: config.git.defaultBranch,
|
|
22
|
-
|
|
22
|
+
...requiredPolicy(cwd), workflow: config.git.releaseTestWorkflow,
|
|
23
|
+
warn: message => console.warn(message) });
|
|
23
24
|
} catch (error) {
|
|
24
25
|
console.error(error.message);
|
|
25
26
|
process.exitCode = 1;
|