@jakobm/peacekeeper 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +85 -32
  2. package/dist/bin/peacekeeper.js +36 -0
  3. package/{bin/peacekeeper.yaml → dist/cmdabra.yaml} +7 -0
  4. package/dist/package.json +57 -0
  5. package/dist/src/container.js +89 -0
  6. package/dist/src/modules/cli/interface.js +1 -0
  7. package/dist/src/modules/cli/service.js +48 -0
  8. package/dist/src/modules/cli/types.js +2 -0
  9. package/dist/src/modules/configuration/interface.js +6 -0
  10. package/{scripts → dist/src/modules/configuration}/project-config-defaults.json +1 -0
  11. package/dist/src/modules/configuration/project-config.js +114 -0
  12. package/dist/src/modules/configuration/update-config.js +42 -0
  13. package/dist/src/modules/dependencies.yaml +16 -0
  14. package/dist/src/modules/external.js +48 -0
  15. package/dist/src/modules/lifecycle/checkpoint-codex-changes.js +204 -0
  16. package/dist/src/modules/lifecycle/checkpoint-codex-session-start.js +23 -0
  17. package/dist/src/modules/lifecycle/checkpoint-codex-stop.js +69 -0
  18. package/dist/src/modules/lifecycle/checkpoint-instructions.js +21 -0
  19. package/dist/src/modules/lifecycle/cleanup-ended-session.js +265 -0
  20. package/dist/src/modules/lifecycle/interface.js +7 -0
  21. package/dist/src/modules/lifecycle/log-script-invocation.js +115 -0
  22. package/dist/src/modules/lifecycle/queue-merged-worktree-cleanup.js +37 -0
  23. package/dist/src/modules/maintenance/cleanup-merged-branches.js +298 -0
  24. package/dist/src/modules/maintenance/interface.js +7 -0
  25. package/dist/src/modules/maintenance/remove-empty-directories.js +114 -0
  26. package/{scripts → dist/src/modules/projects}/check-project-requirements.txt +35 -22
  27. package/dist/src/modules/projects/check-project.js +344 -0
  28. package/dist/src/modules/projects/create-project-core.js +186 -0
  29. package/dist/src/modules/projects/create-project.js +19 -0
  30. package/dist/src/modules/projects/generate-github-setup.js +13 -0
  31. package/dist/src/modules/projects/github-setup-prefix.sh +5 -0
  32. package/dist/src/modules/projects/github-setup-repository-template.sh +90 -0
  33. package/dist/src/modules/projects/github-setup-suffix-template.sh +5 -0
  34. package/dist/src/modules/projects/install-hooks.js +151 -0
  35. package/dist/src/modules/projects/interface.js +6 -0
  36. package/dist/src/modules/releases/assess-release-core.js +145 -0
  37. package/dist/src/modules/releases/assess-release.js +8 -0
  38. package/dist/src/modules/releases/interface.js +9 -0
  39. package/dist/src/modules/releases/release-core.js +529 -0
  40. package/dist/src/modules/releases/release-protection.js +147 -0
  41. package/dist/src/modules/releases/release.js +23 -0
  42. package/dist/src/modules/releases/verify-release-core.js +44 -0
  43. package/dist/src/modules/releases/verify-release-protection.js +25 -0
  44. package/dist/src/modules/releases/verify-release-version.js +14 -0
  45. package/dist/src/modules/releases/verify-release.js +30 -0
  46. package/dist/src/modules/testing/check-test-receipt.js +46 -0
  47. package/dist/src/modules/testing/interface.js +5 -0
  48. package/dist/src/modules/testing/receipt-state.js +99 -0
  49. package/dist/src/modules/testing/record-test-receipt.js +29 -0
  50. package/dist/src/modules/testing/run-tests.js +57 -0
  51. package/package.json +25 -9
  52. package/bin/peacekeeper.js +0 -68
  53. package/scripts/assess-release-core.js +0 -146
  54. package/scripts/assess-release.js +0 -7
  55. package/scripts/check-project.js +0 -333
  56. package/scripts/check-test-receipt.js +0 -49
  57. package/scripts/checkpoint-codex-changes.js +0 -232
  58. package/scripts/checkpoint-codex-session-start.js +0 -24
  59. package/scripts/checkpoint-codex-stop.js +0 -86
  60. package/scripts/checkpoint-instructions.js +0 -19
  61. package/scripts/cleanup-ended-session.js +0 -318
  62. package/scripts/cleanup-merged-branches.js +0 -382
  63. package/scripts/create-project-core.js +0 -195
  64. package/scripts/create-project.js +0 -26
  65. package/scripts/install-hooks.js +0 -155
  66. package/scripts/log-script-invocation.js +0 -125
  67. package/scripts/project-config.js +0 -115
  68. package/scripts/queue-merged-worktree-cleanup.js +0 -58
  69. package/scripts/receipt-state.js +0 -91
  70. package/scripts/record-test-receipt.js +0 -37
  71. package/scripts/release-core.js +0 -529
  72. package/scripts/release-protection.js +0 -96
  73. package/scripts/release.js +0 -18
  74. package/scripts/remove-empty-directories.js +0 -163
  75. package/scripts/run-tests.js +0 -66
  76. package/scripts/update-config.js +0 -41
  77. package/scripts/verify-release-core.js +0 -39
  78. package/scripts/verify-release-protection.js +0 -19
  79. package/scripts/verify-release-version.js +0 -14
  80. package/scripts/verify-release.js +0 -26
  81. /package/{scripts → dist/src/modules/projects}/codex-setup-prefix.sh +0 -0
  82. /package/{scripts → dist/src/modules/releases}/assess-release-schema.json +0 -0
package/README.md CHANGED
@@ -1,11 +1,33 @@
1
1
  # Peacekeeper
2
2
 
3
- Node.js scripts for Codex Git worktree hooks, merged branch cleanup, and cached test receipts. The package requires Node.js 20 or newer and Git. Each calling project supplies its own configuration at its Git root.
3
+ TypeScript tools for Codex Git worktree hooks, merged branch cleanup, and cached test receipts. The package supports Node.js 22.14 or later in the 22.x line and requires Git. Each calling project supplies its own configuration at its Git root.
4
4
 
5
5
  The public npm package is `@jakobm/peacekeeper`; its CLI command is `peacekeeper`.
6
6
  Install it with `npm install --save-exact @jakobm/peacekeeper@<version>`, selecting
7
7
  a published version. Replace the example dependency pin below with that version.
8
8
 
9
+ ## Architecture
10
+
11
+ All application code and tests are authored in TypeScript. Domain modules belong to the
12
+ [Portico](https://github.com/jakobmattsson/portico) tree under `src/modules`.
13
+ The flat module set consists of `cli`, `configuration`, `projects`, `testing`,
14
+ `releases`, `lifecycle`, and `maintenance`. The `cli` module alone maps command
15
+ names to explicit operations on each domain's frozen facade. Modules
16
+ receive private factories, permitted module facades, and external services through
17
+ Portico injection; direct runtime imports inside the module tree are rejected by
18
+ the configured `portico check`. Permitted dependencies are declared in
19
+ `src/modules/dependencies.yaml`. Cmdabra generates the CLI implementation contract
20
+ as `src/modules/cli/types.ts` from the root `cmdabra.yaml`; `npm run typecheck`
21
+ verifies that it is current before checking the TypeScript project.
22
+
23
+ Generate the dependency views and SVG diagram with `npm run architecture`. The
24
+ checked-in output lives in `architecture/`.
25
+
26
+ The checkpoint and session lifecycle hooks deliberately take a small bootstrap
27
+ path before Portico is loaded. Those hooks must remain usable when a calling
28
+ project's dependency installation is incomplete; their command implementations
29
+ therefore continue to use only Peacekeeper files and Node.js built-ins.
30
+
9
31
  ## Create a compliant TypeScript project
10
32
 
11
33
  `create-project` creates a minimal ESM TypeScript library in an existing, completely
@@ -39,17 +61,34 @@ directory for inspection but does not commit or push. A push failure leaves the
39
61
  verified local commit. Inspect or remove the directory before retrying.
40
62
 
41
63
  The generated executable `setup-github-config.sh` is deliberately not run by the
42
- generator. Run it afterwards and complete the manual checklist at its top. It
64
+ generator. Run it afterwards. It
43
65
  configures applicable GitHub policy through `gh`, including automatic head-branch
44
66
  deletion, repository-level **Allow auto-merge**, and merge commits as the only
45
- permitted pull-request merge method, and uses
67
+ permitted pull-request merge method. It creates separate base-protection and
68
+ owner-approval rulesets for the personal account that owns the repository. The
69
+ base ruleset requires a PR and strict CI without bypass; the approval ruleset
70
+ requires the owner configured in `git.requiredApprover` while allowing only that
71
+ user to bypass that ruleset from a PR. It also uses
46
72
  `groundskeeper secrets sync --new-repo` to add the repository when synchronizing
47
73
  `RELEASE_POLICY_TOKEN`. Published projects also document the required initial manual
48
74
  publication with `npm login` and `npm publish`, followed by npm trusted publishing
49
75
  setup. The authenticated `gh` token needs repository **Administration: write**
50
- permission to configure repository settings and branch protection. The generator
76
+ permission to configure repository settings and rulesets. The generator
51
77
  never registers a publisher or publishes a package.
52
78
 
79
+ To print only the same executable GitHub setup without creating a project, run:
80
+
81
+ ```sh
82
+ peacekeeper generate-github-setup \
83
+ --repository https://github.com/OWNER/REPOSITORY.git \
84
+ --repository https://github.com/OWNER/ANOTHER-REPOSITORY.git
85
+ ```
86
+
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.
91
+
53
92
  When moving an existing project to Peacekeeper, update its dependency and lockfile,
54
93
  package scripts, and configuration filename together. Replace previous lifecycle
55
94
  hook commands with the definitions below before running `peacekeeper install-hooks`.
@@ -90,7 +129,7 @@ Run `npm install` from the project root and commit the resulting `package-lock.j
90
129
 
91
130
  Place this file at the caller's Git root. Every field, including nested fields,
92
131
  is required. Unknown fields and invalid values are rejected. If no file exists,
93
- Peacekeeper uses the complete bundled [defaults](scripts/project-config-defaults.json).
132
+ Peacekeeper uses the complete bundled [defaults](src/modules/configuration/project-config-defaults.json).
94
133
  The defaults contain no test commands; configure those before running tests or
95
134
  recording or reusing a test receipt.
96
135
 
@@ -116,6 +155,7 @@ Complete example:
116
155
  "remote": "origin",
117
156
  "defaultBranch": "main",
118
157
  "branchPrefix": "codex/",
158
+ "requiredApprover": "OWNER",
119
159
  "checkpointPushRemotes": ["origin"],
120
160
  "releaseMergeMethod": "merge",
121
161
  "releaseRequiredChecks": ["test"],
@@ -135,7 +175,7 @@ Complete example:
135
175
  }
136
176
  ```
137
177
 
138
- `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 -- --force`. Otherwise the hint uses the explicit package path. `loggingDirectory` stores hook invocation logs relative to the primary Git worktree's root.
178
+ `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.
139
179
 
140
180
  `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.
141
181
 
@@ -207,7 +247,7 @@ The installed file contains these definitions (other existing hooks are retained
207
247
  "hooks": [
208
248
  {
209
249
  "type": "command",
210
- "command": "node \"$(git rev-parse --show-toplevel)/node_modules/@jakobm/peacekeeper/bin/peacekeeper.js\" checkpoint-codex-session-start",
250
+ "command": "node \"$(git rev-parse --show-toplevel)/node_modules/@jakobm/peacekeeper/dist/bin/peacekeeper.js\" checkpoint-codex-session-start",
211
251
  "timeout": 30,
212
252
  "statusMessage": "Loading Codex checkpoint instructions"
213
253
  }
@@ -219,7 +259,7 @@ The installed file contains these definitions (other existing hooks are retained
219
259
  "hooks": [
220
260
  {
221
261
  "type": "command",
222
- "command": "node \"$(git rev-parse --show-toplevel)/node_modules/@jakobm/peacekeeper/bin/peacekeeper.js\" checkpoint-codex-stop",
262
+ "command": "node \"$(git rev-parse --show-toplevel)/node_modules/@jakobm/peacekeeper/dist/bin/peacekeeper.js\" checkpoint-codex-stop",
223
263
  "timeout": 30,
224
264
  "statusMessage": "Checking for an uncommitted Codex checkpoint"
225
265
  }
@@ -231,7 +271,7 @@ The installed file contains these definitions (other existing hooks are retained
231
271
  "hooks": [
232
272
  {
233
273
  "type": "command",
234
- "command": "node \"$(git rev-parse --show-toplevel)/node_modules/@jakobm/peacekeeper/bin/peacekeeper.js\" cleanup-ended-session",
274
+ "command": "node \"$(git rev-parse --show-toplevel)/node_modules/@jakobm/peacekeeper/dist/bin/peacekeeper.js\" cleanup-ended-session",
235
275
  "timeout": 3,
236
276
  "statusMessage": "Scheduling merged branch cleanup"
237
277
  }
@@ -270,7 +310,7 @@ before deleting the affected worktree or branches. Remote branch deletion still
270
310
  uses an exact-commit lease.
271
311
 
272
312
  This repository uses the same hooks and configuration, with commands pointing to
273
- its own `bin/peacekeeper.js` instead of an installed copy. Its `git.checkpointPushRemotes` is set to `["origin"]` to publish checkpoint branches automatically. There is no dependency
313
+ its own `dist/bin/peacekeeper.js` instead of an installed copy. Its `git.checkpointPushRemotes` is set to `["origin"]` to publish checkpoint branches automatically. There is no dependency
274
314
  on a published version of itself. `npm exec --no -- peacekeeper` also resolves
275
315
  the root package's own bin, including the checkpoint command requested by the
276
316
  Stop hook. Install dependencies with `npm ci` to run the full test suite.
@@ -323,12 +363,12 @@ All projects must declare nonblank `author` and `repository` values in
323
363
  and `repository.url` strings.
324
364
  Run `peacekeeper check-project --explain` for the complete expected
325
365
  architecture, requirements, configuration examples, and verification limits.
326
- The command prints the bundled [formal requirements](scripts/check-project-requirements.txt),
366
+ The command prints the bundled [formal requirements](src/modules/projects/check-project-requirements.txt),
327
367
  which can also be read without a repository or project configuration.
328
368
 
329
369
  Codex worktree setup requires `.codex/environments/environment.toml` with
330
370
  `version = 1` and a `setup.script` value starting exactly with the bundled
331
- [setup prefix](scripts/codex-setup-prefix.sh), including its final newline.
371
+ [setup prefix](src/modules/projects/codex-setup-prefix.sh), including its final newline.
332
372
  The shell file is a readable reference used for validation; it is not executed
333
373
  by Peacekeeper. Copy its contents into a TOML multiline literal string
334
374
  (`script = '''` followed by a newline, the prefix, and closing `'''`).
@@ -344,9 +384,9 @@ Peacekeeper versions require updating each project's environment configuration.
344
384
  ## Assess unpublished changes
345
385
 
346
386
  Run `peacekeeper assess-release` (or `npm exec --no -- peacekeeper assess-release`)
347
- from a project using Peacekeeper. It always writes one pretty-printed JSON object
348
- to stdout, with fields ordered as `recommendation`, `model`, `releaseSha`,
349
- `previousReleaseSha`, and `motivation`:
387
+ from a project using Peacekeeper. A syntactically valid invocation writes one
388
+ pretty-printed JSON object to stdout, with fields ordered as `recommendation`,
389
+ `model`, `releaseSha`, `previousReleaseSha`, and `motivation`:
350
390
 
351
391
  ```json
352
392
  {
@@ -360,9 +400,12 @@ to stdout, with fields ordered as `recommendation`, `model`, `releaseSha`,
360
400
 
361
401
  `recommendation` is `patch`, `minor`, `major`, `noop` (no publication needed), or
362
402
  `undetermined` (insufficient evidence or a failed assessment). `motivation`
363
- explains the decision. The command takes no arguments; even invalid arguments
364
- produce an `undetermined` JSON response. Assessment outcomes, including operational
365
- failures, exit with status zero: callers must inspect `recommendation`.
403
+ explains the decision. The command takes no arguments. Assessment outcomes,
404
+ including operational failures, exit with status zero and return JSON; callers
405
+ must inspect `recommendation`. This differs from CLI syntax and usage failures,
406
+ which Cmdabra reports as exit status 2 with help text on stderr and no JSON on
407
+ stdout. This distinction was introduced after Peacekeeper 0.20.0; integrations
408
+ upgrading from that version must check the process status before parsing stdout.
366
409
 
367
410
  `model` is the model name reported in Codex's startup metadata on stderr. It is
368
411
  `null` if Codex does not report recognizable model metadata or cannot start.
@@ -421,7 +464,7 @@ Check `volta which node`, `node --version`, and `npm --version` to verify your
421
464
  setup. Use `volta pin node@<version> npm@<version>` to update the project versions;
422
465
  `engines.node` separately describes supported consumer versions.
423
466
  Review `npm pack --dry-run --json` before
424
- publishing; npm includes only `bin/`, `scripts/`, the README, and package metadata.
467
+ publishing; npm includes the compiled `dist/` tree, the README, and package metadata.
425
468
 
426
469
  Configure npm trusted publishing for `@jakobm/peacekeeper` with repository owner
427
470
  `jakobmattsson`, repository `peacekeeper`, and workflow filename `package.yml`,
@@ -438,18 +481,28 @@ artifacts of tested contents. Configure `git.releaseRequiredChecks` in the root
438
481
  `peacekeeper.config.json` with the exact CI job names required for a release
439
482
  (for this repository: `["test", "Test package"]`). These checks must be mandatory
440
483
  with **Require branches to be up to date before merging** enabled. Classic branch
441
- protection must enforce checks for administrators too. Alternatively, active
442
- rulesets must require strict checks and have no bypass actors. Rules inherited
443
- from the organization are included. Merge queues are not currently an alternative
484
+ protection may provide the base PR and check requirements. Active base rulesets
485
+ may provide them instead. Merge
486
+ queues are not currently an alternative
444
487
  to this strict policy. Repositories must also enable **Automatically delete head
445
488
  branches** (`delete_branch_on_merge=true`).
446
489
 
447
- The default branch must require pull requests (zero required reviewer approvals
448
- is allowed), and only merge commits may be used. Either disable squash and rebase
490
+ The default branch must also have exactly one active approval ruleset. It must
491
+ require one approval from the sole global code owner, dismiss stale approvals
492
+ after new pushes, and contain no rule except that pull-request approval rule. Its
493
+ only bypass actor must be the personal repository owner from `git.requiredApprover`,
494
+ with `bypass_mode: pull_request`. This lets the owner merge their own PR without
495
+ 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.
499
+
500
+ Only merge commits may be used. Either disable squash and rebase
449
501
  in repository settings, or restrict the default branch's pull-request ruleset to
450
502
  `allowed_merge_methods: ["merge"]`. Other branches are outside this policy.
451
503
  Required linear history and any applicable PR rule excluding merge commits fail
452
- verification. PR and strict-check rules must enforce the policy without bypass.
504
+ verification. Bypass actors for base PR and strict-check rules also require
505
+ manual inspection.
453
506
  Enable `allow_auto_merge` in repository settings: this permits opting in per PR;
454
507
  Peacekeeper never enables auto-merge on individual PRs.
455
508
 
@@ -488,15 +541,16 @@ jobs in its latest PR workflow run. Manual tags without that PR are rejected.
488
541
  `verify-release-version` remains available for local version checks alone.
489
542
 
490
543
  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.
491
547
  The workflow expects a `RELEASE_POLICY_TOKEN` Actions secret, exposed to the
492
548
  commands as `GH_TOKEN`. Use a fine-grained PAT or GitHub App token with access to
493
549
  this repository and Administration read, Contents read/write, Pull requests read and
494
550
  Actions read permissions. Contents write is required even to read merge-related
495
- settings such as `delete_branch_on_merge`. GitHub only exposes ruleset bypass actors to callers
496
- with write access to the ruleset; ruleset users must additionally grant that
497
- access (Administration write for repository rulesets, or the appropriate access
498
- for inherited organization rulesets). Missing bypass information also fails.
499
- The normal workflow `GITHUB_TOKEN` cannot be granted Administration permissions
551
+ settings such as `delete_branch_on_merge`. Administration read is sufficient
552
+ because bypass actors are checked manually.
553
+ The normal workflow `GITHUB_TOKEN` cannot be granted Administration permission
500
554
  through workflow YAML. After correcting access or rules, rerun the failed job.
501
555
  Fork PRs do not receive this secret and fail the policy check; do not expose it
502
556
  by executing fork code with `pull_request_target`.
@@ -504,8 +558,7 @@ by executing fork code with `pull_request_target`.
504
558
  To set this up for this repository:
505
559
 
506
560
  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).
507
- For repository rulesets, use the [form with Administration write instead](https://github.com/settings/personal-access-tokens/new?name=peacekeeper-release-policy&target_name=jakobmattsson&expires_in=90&administration=write&contents=write&pull_requests=read&actions=read)
508
- so GitHub exposes bypass actors. For another repository, change the resource
561
+ For another repository, change the resource
509
562
  owner. Select **Only select repositories**, choose `peacekeeper`, review
510
563
  the permissions and expiration, and generate the token. If the owner requires
511
564
  approval, wait until the token is approved.
@@ -0,0 +1,36 @@
1
+ #!/usr/bin/env node
2
+ import { createContainer } from '../src/container.js';
3
+ const dependencyFreeLifecycleCommands = new Set([
4
+ 'checkpoint-codex-session-start',
5
+ 'checkpoint-codex-stop',
6
+ 'checkpoint-codex-changes',
7
+ 'cleanup-ended-session',
8
+ ]);
9
+ async function main() {
10
+ const rawArgs = process.argv.slice(2);
11
+ const [command, ...args] = rawArgs;
12
+ const informational = args.length === 1 && ['--help', '-h'].includes(args[0]);
13
+ const dependencyFree = command !== undefined
14
+ && dependencyFreeLifecycleCommands.has(command)
15
+ && !informational;
16
+ const container = await createContainer(dependencyFree);
17
+ if (dependencyFree) {
18
+ const operation = (command.replace(/-([a-z])/gu, (_match, letter) => letter.toUpperCase()));
19
+ await container.resolve('lifecycle')[operation](args);
20
+ return;
21
+ }
22
+ await container.resolve('cli').run(rawArgs.length === 0 ? ['--help'] : rawArgs);
23
+ }
24
+ main().catch(async (error) => {
25
+ const { CmdabraUsageError } = await import('@jakobm/cmdabra').catch(() => ({
26
+ CmdabraUsageError: undefined,
27
+ }));
28
+ if (CmdabraUsageError && error instanceof CmdabraUsageError) {
29
+ const usageError = error;
30
+ process.stderr.write(`${usageError.message}\n\n${usageError.help}`);
31
+ process.exitCode = usageError.exitCode;
32
+ return;
33
+ }
34
+ console.error(error instanceof Error ? `Error: ${error.message}` : String(error));
35
+ process.exitCode = 1;
36
+ });
@@ -26,6 +26,13 @@ commands:
26
26
  type: enum
27
27
  choices: ["true", "false"]
28
28
  required: true
29
+ generate-github-setup:
30
+ description: Print commands that configure GitHub policy for one or more repositories.
31
+ named-options:
32
+ repository:
33
+ description: GitHub HTTPS repository URL; may be repeated.
34
+ required: true
35
+ repeatable: true
29
36
  check-project:
30
37
  description: Validate local toolchain, hooks, CI and publication conventions.
31
38
  named-options:
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@jakobm/peacekeeper",
3
+ "version": "0.21.0",
4
+ "description": "Shared repository test, Git worktree, and Codex hook commands",
5
+ "license": "MIT",
6
+ "author": "Jakob Mattsson",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/jakobmattsson/peacekeeper.git"
10
+ },
11
+ "type": "module",
12
+ "publishConfig": {
13
+ "access": "public",
14
+ "registry": "https://registry.npmjs.org/"
15
+ },
16
+ "bin": {
17
+ "peacekeeper": "dist/bin/peacekeeper.js"
18
+ },
19
+ "files": [
20
+ "dist/bin/",
21
+ "dist/src/",
22
+ "dist/cmdabra.yaml",
23
+ "dist/package.json"
24
+ ],
25
+ "scripts": {
26
+ "generate:cli-types": "cmdabra generate-types cmdabra.yaml --output src/modules/cli/types.ts",
27
+ "check:cli-types": "cmdabra generate-types cmdabra.yaml --output src/modules/cli/types.ts --check",
28
+ "clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
29
+ "build": "npm run clean && npm run check:cli-types && tsc && tsc -p tsconfig.test.json && node dist/scripts/copy-assets.js",
30
+ "typecheck": "npm run check:cli-types && tsc --noEmit && tsc -p tsconfig.test.json --noEmit",
31
+ "test": "npm run build && node dist/bin/peacekeeper.js run-tests",
32
+ "prepare": "npm run build",
33
+ "architecture": "npm run build && portico architecture --modules dist/src/modules --output architecture",
34
+ "release": "node dist/bin/peacekeeper.js release",
35
+ "cleanup:branches": "node dist/bin/peacekeeper.js cleanup-merged-branches",
36
+ "cleanup:empty-directories": "node dist/bin/peacekeeper.js remove-empty-directories"
37
+ },
38
+ "engines": {
39
+ "node": "^22.14.0"
40
+ },
41
+ "dependencies": {
42
+ "@iarna/toml": "^2.2.5",
43
+ "@jakobm/cmdabra": "^0.2.1",
44
+ "@jakobm/portico": "^0.7.0",
45
+ "semver": "^7.8.5",
46
+ "yaml": "^2.9.1"
47
+ },
48
+ "devDependencies": {
49
+ "@types/node": "^22.20.5",
50
+ "@types/semver": "^7.7.1",
51
+ "typescript": "^6.0.3"
52
+ },
53
+ "volta": {
54
+ "node": "22.14.0",
55
+ "npm": "11.21.0"
56
+ }
57
+ }
@@ -0,0 +1,89 @@
1
+ import { execFileSync, spawn, spawnSync } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import projectConfigDefaults from './modules/configuration/project-config-defaults.json' with { type: 'json' };
6
+ import createProjectConfig from './modules/configuration/project-config.js';
7
+ import createLifecycle from './modules/lifecycle/interface.js';
8
+ import createCheckpointChanges from './modules/lifecycle/checkpoint-codex-changes.js';
9
+ import createCheckpointSessionStart from './modules/lifecycle/checkpoint-codex-session-start.js';
10
+ import createCheckpointStop from './modules/lifecycle/checkpoint-codex-stop.js';
11
+ import createCheckpointInstructions from './modules/lifecycle/checkpoint-instructions.js';
12
+ import createCleanupEndedSession from './modules/lifecycle/cleanup-ended-session.js';
13
+ import createLogScriptInvocation from './modules/lifecycle/log-script-invocation.js';
14
+ import createQueueMergedWorktreeCleanup from './modules/lifecycle/queue-merged-worktree-cleanup.js';
15
+ import createCleanupMergedBranches from './modules/maintenance/cleanup-merged-branches.js';
16
+ const currentDirectory = path.dirname(fileURLToPath(import.meta.url));
17
+ const clock = Object.freeze({
18
+ date: () => new Date(),
19
+ now: () => Date.now(),
20
+ parse: (value) => Date.parse(value),
21
+ sleep: (milliseconds) => new Promise(resolve => setTimeout(resolve, milliseconds)),
22
+ sleepSync: (milliseconds) => {
23
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds);
24
+ },
25
+ timezone: () => Intl.DateTimeFormat().resolvedOptions().timeZone,
26
+ });
27
+ const output = console;
28
+ function dependencyFreeLifecycleContainer() {
29
+ const runtime = process;
30
+ const projectConfig = createProjectConfig({
31
+ external: { execFileSync, fs, path, projectConfigDefaults, runtime },
32
+ });
33
+ const configuration = Object.freeze({
34
+ projectConfig: projectConfig.projectConfig,
35
+ repositoryRoot: projectConfig.repositoryRoot,
36
+ requireTestCommands: projectConfig.requireTestCommands,
37
+ });
38
+ const invocation = createLogScriptInvocation({
39
+ configuration, external: { clock, fs, path, runtime, spawnSync },
40
+ });
41
+ const instructions = createCheckpointInstructions();
42
+ const checkpointChanges = createCheckpointChanges({
43
+ configuration, logScriptInvocation: invocation,
44
+ external: { clock, fs, output, path, runtime, spawnSync },
45
+ });
46
+ const cleanupMergedBranches = createCleanupMergedBranches({
47
+ configuration, external: { execFileSync, fs, output, path, runtime, spawnSync },
48
+ });
49
+ const maintenance = Object.freeze({
50
+ applyPlan: cleanupMergedBranches.applyPlan,
51
+ buildPlan: cleanupMergedBranches.buildPlan,
52
+ listWorktrees: cleanupMergedBranches.listWorktrees,
53
+ });
54
+ const cleanupEndedSession = createCleanupEndedSession({
55
+ configuration, logScriptInvocation: invocation, maintenance,
56
+ external: {
57
+ buffer: Buffer, clock, executablePath: path.resolve(currentDirectory, '../bin/peacekeeper.js'),
58
+ fs, output, path, runtime, spawn, spawnSync,
59
+ },
60
+ });
61
+ const lifecycle = Object.freeze(createLifecycle({
62
+ checkpointCodexChanges: checkpointChanges,
63
+ checkpointCodexSessionStart: createCheckpointSessionStart({
64
+ checkpointInstructions: instructions, configuration, logScriptInvocation: invocation,
65
+ }),
66
+ checkpointCodexStop: createCheckpointStop({
67
+ checkpointCodexChanges: checkpointChanges, checkpointInstructions: instructions,
68
+ configuration, logScriptInvocation: invocation, external: { fs, spawnSync },
69
+ }),
70
+ cleanupEndedSession,
71
+ queueMergedWorktreeCleanup: createQueueMergedWorktreeCleanup({
72
+ cleanupEndedSession, logScriptInvocation: invocation, external: { output, runtime },
73
+ }),
74
+ }));
75
+ return {
76
+ resolve(name) {
77
+ if (name !== 'lifecycle') {
78
+ throw new Error(`Dependency-free container only provides lifecycle, not ${name}`);
79
+ }
80
+ return lifecycle;
81
+ },
82
+ };
83
+ }
84
+ export async function createContainer(dependencyFree = false) {
85
+ if (dependencyFree)
86
+ return dependencyFreeLifecycleContainer();
87
+ const { default: portico } = await import('@jakobm/portico');
88
+ return await portico.createRepositoryContainerAsync(path.resolve(currentDirectory, 'modules'));
89
+ }
@@ -0,0 +1 @@
1
+ export default ({ service }) => ({ run: service.run });
@@ -0,0 +1,48 @@
1
+ export default ({ configuration, lifecycle, maintenance, projects, releases, testing, external: { cliConfigPath, runCli }, }) => {
2
+ function executionMode({ dryRun, execute }) {
3
+ if (dryRun && execute)
4
+ throw new Error('--dry-run and --execute cannot be combined');
5
+ return Boolean(execute);
6
+ }
7
+ const implementation = {
8
+ 'update-config': () => configuration.updateConfig(),
9
+ 'check-project': options => projects.checkProject({ explain: options.explain }),
10
+ 'create-project': options => projects.createProject({
11
+ repository: options.repository,
12
+ directory: options.directory,
13
+ packageName: options.packageName,
14
+ authorName: options.authorName,
15
+ authorEmail: options.authorEmail,
16
+ published: options.publishToNpm === 'true',
17
+ }),
18
+ 'generate-github-setup': options => projects.generateGithubSetup({ repository: options.repository }),
19
+ 'install-hooks': options => projects.installHooks({ dryRun: options.dryRun }),
20
+ 'check-test-receipt': () => testing.checkTestReceipt(),
21
+ 'record-test-receipt': () => testing.recordTestReceipt(),
22
+ 'run-tests': options => testing.runTests({ force: options.force }),
23
+ 'assess-release': () => releases.assessRelease(),
24
+ release: bump => releases.release(bump),
25
+ 'verify-release': () => releases.verifyRelease(),
26
+ 'verify-release-protection': () => releases.verifyReleaseProtection(),
27
+ 'verify-release-version': () => releases.verifyReleaseVersion(),
28
+ 'checkpoint-codex-changes': options => lifecycle.checkpointCodexChanges({
29
+ subject: options.subject,
30
+ bodyParagraphs: options.body,
31
+ }),
32
+ 'checkpoint-codex-session-start': () => lifecycle.checkpointCodexSessionStart(),
33
+ 'checkpoint-codex-stop': () => lifecycle.checkpointCodexStop(),
34
+ 'cleanup-ended-session': () => lifecycle.cleanupEndedSession(),
35
+ 'queue-merged-worktree-cleanup': () => lifecycle.queueMergedWorktreeCleanup(),
36
+ 'cleanup-merged-branches': options => maintenance.cleanupMergedBranches({
37
+ execute: executionMode(options),
38
+ }),
39
+ 'remove-empty-directories': options => maintenance.removeEmptyDirectories({
40
+ execute: executionMode(options),
41
+ }),
42
+ };
43
+ return {
44
+ async run(rawArgs) {
45
+ await runCli(cliConfigPath, implementation, rawArgs);
46
+ },
47
+ };
48
+ };
@@ -0,0 +1,2 @@
1
+ // Generated by Cmdabra. Do not edit.
2
+ export {};
@@ -0,0 +1,6 @@
1
+ export default ({ projectConfig, updateConfig }) => ({
2
+ projectConfig: projectConfig.projectConfig,
3
+ repositoryRoot: projectConfig.repositoryRoot,
4
+ requireTestCommands: projectConfig.requireTestCommands,
5
+ updateConfig: updateConfig.run,
6
+ });
@@ -3,6 +3,7 @@
3
3
  "remote": "origin",
4
4
  "defaultBranch": "main",
5
5
  "branchPrefix": "codex/",
6
+ "requiredApprover": null,
6
7
  "checkpointPushRemotes": [
7
8
  "origin"
8
9
  ],
@@ -0,0 +1,114 @@
1
+ export default ({ external: { execFileSync, fs, path, projectConfigDefaults, runtime, } }) => {
2
+ const CONFIG_FILE = 'peacekeeper.config.json';
3
+ function repositoryRoot(cwd = runtime.cwd()) {
4
+ return execFileSync('git', ['rev-parse', '--show-toplevel'], {
5
+ cwd,
6
+ encoding: 'utf8',
7
+ }).trim();
8
+ }
9
+ // Kept independent of the defaults so additions require an explicit default.
10
+ const CONFIG_SCHEMA = {
11
+ publishesToNpm: true,
12
+ git: { remote: true, defaultBranch: true, branchPrefix: true, requiredApprover: true,
13
+ checkpointPushRemotes: true, releaseMergeMethod: true,
14
+ releaseRequiredChecks: true, releaseTestWorkflow: true },
15
+ tests: { commands: true, receiptMaxAgeMinutes: true, npmTestUsesRunner: true },
16
+ loggingDirectory: true,
17
+ loggingEnabled: true,
18
+ projectChecks: { testWorkflow: true, requiredJobs: true },
19
+ };
20
+ function validateShape(value, schema, location, errors) {
21
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
22
+ errors.push(`${location} must be an object`);
23
+ return;
24
+ }
25
+ for (const key of Object.keys(value)) {
26
+ if (!Object.hasOwn(schema, key))
27
+ errors.push(`unknown field ${location}.${key}`);
28
+ }
29
+ for (const [key, child] of Object.entries(schema)) {
30
+ const name = location === 'config' ? key : `${location}.${key}`;
31
+ if (!Object.hasOwn(value, key))
32
+ errors.push(`missing field ${name}`);
33
+ else if (child !== true)
34
+ validateShape(value[key], child, name, errors);
35
+ }
36
+ }
37
+ function requireNonemptyString(value, location, file) {
38
+ if (typeof value !== 'string' || value.trim() === '') {
39
+ throw new Error(`${file}: ${location} must be a nonempty string`);
40
+ }
41
+ }
42
+ function validateConfig(config, file) {
43
+ const errors = [];
44
+ validateShape(config, CONFIG_SCHEMA, 'config', errors);
45
+ if (errors.length)
46
+ throw new Error(`${file}: ${errors.join('; ')}. Run peacekeeper update-config to add missing fields.`);
47
+ if (typeof config.projectChecks.testWorkflow !== 'string' || !/^[A-Za-z0-9_-]+\.ya?ml$/u.test(config.projectChecks.testWorkflow)) {
48
+ throw new Error(`${file}: projectChecks.testWorkflow must be a workflow filename`);
49
+ }
50
+ const jobs = config.projectChecks.requiredJobs;
51
+ if (!Array.isArray(jobs) || jobs.some(job => typeof job !== 'string' || !job.trim() || job !== job.trim()) || new Set(jobs).size !== jobs.length) {
52
+ throw new Error(`${file}: projectChecks.requiredJobs must contain unique nonempty job names`);
53
+ }
54
+ for (const field of ['remote', 'defaultBranch', 'branchPrefix']) {
55
+ requireNonemptyString(config.git[field], `git.${field}`, file);
56
+ }
57
+ if (config.git.requiredApprover !== null
58
+ && (typeof config.git.requiredApprover !== 'string'
59
+ || !/^(?!-)(?!.*--)[A-Za-z0-9-]{1,39}(?<!-)$/u.test(config.git.requiredApprover))) {
60
+ throw new Error(`${file}: git.requiredApprover must be null or a valid GitHub username`);
61
+ }
62
+ const remotes = config.git.checkpointPushRemotes;
63
+ if (!Array.isArray(remotes)
64
+ || remotes.some((remote) => typeof remote !== 'string' || remote.trim() === ''
65
+ || remote !== remote.trim() || remote.startsWith('-'))
66
+ || new Set(remotes).size !== remotes.length) {
67
+ throw new Error(`${file}: git.checkpointPushRemotes must be an array of unique remote names`);
68
+ }
69
+ if (typeof config.git.releaseTestWorkflow !== 'string' || !/^[A-Za-z0-9_-]+\.ya?ml$/u.test(config.git.releaseTestWorkflow)) {
70
+ throw new Error(`${file}: git.releaseTestWorkflow must be a workflow filename ending in .yml or .yaml`);
71
+ }
72
+ const checks = config.git.releaseRequiredChecks;
73
+ if (!Array.isArray(checks) || checks.some(check => typeof check !== 'string' || !check.trim() || check !== check.trim()) || new Set(checks).size !== checks.length) {
74
+ throw new Error(`${file}: git.releaseRequiredChecks must be an array of unique check names`);
75
+ }
76
+ if (!['merge', 'squash', 'rebase'].includes(config.git.releaseMergeMethod)) {
77
+ throw new Error(`${file}: git.releaseMergeMethod must be merge, squash, or rebase`);
78
+ }
79
+ if (typeof config.publishesToNpm !== 'boolean') {
80
+ throw new Error(`${file}: publishesToNpm must be a boolean`);
81
+ }
82
+ if (typeof config.loggingEnabled !== 'boolean') {
83
+ throw new Error(`${file}: loggingEnabled must be a boolean`);
84
+ }
85
+ requireNonemptyString(config.loggingDirectory, 'loggingDirectory', file);
86
+ if (!Array.isArray(config.tests.commands)
87
+ || config.tests.commands.some((command) => typeof command !== 'string' || command.trim() === '')) {
88
+ throw new Error(`${file}: tests.commands must be an array of command strings`);
89
+ }
90
+ if (!Number.isSafeInteger(config.tests.receiptMaxAgeMinutes)
91
+ || config.tests.receiptMaxAgeMinutes < 1) {
92
+ throw new Error(`${file}: tests.receiptMaxAgeMinutes must be a positive integer`);
93
+ }
94
+ if (typeof config.tests.npmTestUsesRunner !== 'boolean') {
95
+ throw new Error(`${file}: tests.npmTestUsesRunner must be a boolean`);
96
+ }
97
+ }
98
+ function projectConfig(cwd = runtime.cwd()) {
99
+ const root = repositoryRoot(cwd);
100
+ const file = path.join(root, CONFIG_FILE);
101
+ const config = fs.existsSync(file)
102
+ ? JSON.parse(fs.readFileSync(file, 'utf8'))
103
+ : JSON.parse(JSON.stringify(projectConfigDefaults));
104
+ validateConfig(config, file);
105
+ return { root, ...config };
106
+ }
107
+ function requireTestCommands(root) {
108
+ if (!projectConfig(root).tests.commands.length) {
109
+ throw new Error('Configure tests.commands before running tests or using a test receipt.');
110
+ }
111
+ }
112
+ const api = { CONFIG_FILE, CONFIG_SCHEMA, validateConfig, projectConfig, repositoryRoot, requireTestCommands };
113
+ return api;
114
+ };