@jakobm/peacekeeper 0.20.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 +54 -16
  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/dist/src/modules/configuration/project-config.js +114 -0
  11. package/dist/src/modules/configuration/update-config.js +42 -0
  12. package/dist/src/modules/dependencies.yaml +16 -0
  13. package/dist/src/modules/external.js +48 -0
  14. package/dist/src/modules/lifecycle/checkpoint-codex-changes.js +204 -0
  15. package/dist/src/modules/lifecycle/checkpoint-codex-session-start.js +23 -0
  16. package/dist/src/modules/lifecycle/checkpoint-codex-stop.js +69 -0
  17. package/dist/src/modules/lifecycle/checkpoint-instructions.js +21 -0
  18. package/dist/src/modules/lifecycle/cleanup-ended-session.js +265 -0
  19. package/dist/src/modules/lifecycle/interface.js +7 -0
  20. package/dist/src/modules/lifecycle/log-script-invocation.js +115 -0
  21. package/dist/src/modules/lifecycle/queue-merged-worktree-cleanup.js +37 -0
  22. package/dist/src/modules/maintenance/cleanup-merged-branches.js +298 -0
  23. package/dist/src/modules/maintenance/interface.js +7 -0
  24. package/dist/src/modules/maintenance/remove-empty-directories.js +114 -0
  25. package/{scripts → dist/src/modules/projects}/check-project-requirements.txt +3 -3
  26. package/dist/src/modules/projects/check-project.js +344 -0
  27. package/dist/src/modules/projects/create-project-core.js +186 -0
  28. package/dist/src/modules/projects/create-project.js +19 -0
  29. package/dist/src/modules/projects/generate-github-setup.js +13 -0
  30. package/dist/src/modules/projects/github-setup-prefix.sh +5 -0
  31. package/dist/src/modules/projects/github-setup-repository-template.sh +90 -0
  32. package/dist/src/modules/projects/github-setup-suffix-template.sh +5 -0
  33. package/dist/src/modules/projects/install-hooks.js +151 -0
  34. package/dist/src/modules/projects/interface.js +6 -0
  35. package/dist/src/modules/releases/assess-release-core.js +145 -0
  36. package/dist/src/modules/releases/assess-release.js +8 -0
  37. package/dist/src/modules/releases/interface.js +9 -0
  38. package/dist/src/modules/releases/release-core.js +529 -0
  39. package/dist/src/modules/releases/release-protection.js +147 -0
  40. package/dist/src/modules/releases/release.js +23 -0
  41. package/dist/src/modules/releases/verify-release-core.js +44 -0
  42. package/dist/src/modules/releases/verify-release-protection.js +25 -0
  43. package/dist/src/modules/releases/verify-release-version.js +14 -0
  44. package/dist/src/modules/releases/verify-release.js +30 -0
  45. package/dist/src/modules/testing/check-test-receipt.js +46 -0
  46. package/dist/src/modules/testing/interface.js +5 -0
  47. package/dist/src/modules/testing/receipt-state.js +99 -0
  48. package/dist/src/modules/testing/record-test-receipt.js +29 -0
  49. package/dist/src/modules/testing/run-tests.js +57 -0
  50. package/package.json +25 -9
  51. package/bin/peacekeeper.js +0 -68
  52. package/scripts/assess-release-core.js +0 -146
  53. package/scripts/assess-release.js +0 -7
  54. package/scripts/check-project.js +0 -346
  55. package/scripts/check-test-receipt.js +0 -49
  56. package/scripts/checkpoint-codex-changes.js +0 -232
  57. package/scripts/checkpoint-codex-session-start.js +0 -24
  58. package/scripts/checkpoint-codex-stop.js +0 -86
  59. package/scripts/checkpoint-instructions.js +0 -19
  60. package/scripts/cleanup-ended-session.js +0 -318
  61. package/scripts/cleanup-merged-branches.js +0 -382
  62. package/scripts/create-project-core.js +0 -278
  63. package/scripts/create-project.js +0 -26
  64. package/scripts/install-hooks.js +0 -155
  65. package/scripts/log-script-invocation.js +0 -125
  66. package/scripts/project-config.js +0 -120
  67. package/scripts/queue-merged-worktree-cleanup.js +0 -58
  68. package/scripts/receipt-state.js +0 -91
  69. package/scripts/record-test-receipt.js +0 -37
  70. package/scripts/release-core.js +0 -530
  71. package/scripts/release-protection.js +0 -135
  72. package/scripts/release.js +0 -18
  73. package/scripts/remove-empty-directories.js +0 -163
  74. package/scripts/run-tests.js +0 -66
  75. package/scripts/update-config.js +0 -41
  76. package/scripts/verify-release-core.js +0 -39
  77. package/scripts/verify-release-protection.js +0 -20
  78. package/scripts/verify-release-version.js +0 -14
  79. package/scripts/verify-release.js +0 -27
  80. /package/{scripts → dist/src/modules/configuration}/project-config-defaults.json +0 -0
  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,7 +61,7 @@ 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
67
  permitted pull-request merge method. It creates separate base-protection and
@@ -54,6 +76,19 @@ setup. The authenticated `gh` token needs repository **Administration: write**
54
76
  permission to configure repository settings and rulesets. The generator
55
77
  never registers a publisher or publishes a package.
56
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
+
57
92
  When moving an existing project to Peacekeeper, update its dependency and lockfile,
58
93
  package scripts, and configuration filename together. Replace previous lifecycle
59
94
  hook commands with the definitions below before running `peacekeeper install-hooks`.
@@ -94,7 +129,7 @@ Run `npm install` from the project root and commit the resulting `package-lock.j
94
129
 
95
130
  Place this file at the caller's Git root. Every field, including nested fields,
96
131
  is required. Unknown fields and invalid values are rejected. If no file exists,
97
- 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).
98
133
  The defaults contain no test commands; configure those before running tests or
99
134
  recording or reusing a test receipt.
100
135
 
@@ -212,7 +247,7 @@ The installed file contains these definitions (other existing hooks are retained
212
247
  "hooks": [
213
248
  {
214
249
  "type": "command",
215
- "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",
216
251
  "timeout": 30,
217
252
  "statusMessage": "Loading Codex checkpoint instructions"
218
253
  }
@@ -224,7 +259,7 @@ The installed file contains these definitions (other existing hooks are retained
224
259
  "hooks": [
225
260
  {
226
261
  "type": "command",
227
- "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",
228
263
  "timeout": 30,
229
264
  "statusMessage": "Checking for an uncommitted Codex checkpoint"
230
265
  }
@@ -236,7 +271,7 @@ The installed file contains these definitions (other existing hooks are retained
236
271
  "hooks": [
237
272
  {
238
273
  "type": "command",
239
- "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",
240
275
  "timeout": 3,
241
276
  "statusMessage": "Scheduling merged branch cleanup"
242
277
  }
@@ -275,7 +310,7 @@ before deleting the affected worktree or branches. Remote branch deletion still
275
310
  uses an exact-commit lease.
276
311
 
277
312
  This repository uses the same hooks and configuration, with commands pointing to
278
- 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
279
314
  on a published version of itself. `npm exec --no -- peacekeeper` also resolves
280
315
  the root package's own bin, including the checkpoint command requested by the
281
316
  Stop hook. Install dependencies with `npm ci` to run the full test suite.
@@ -328,12 +363,12 @@ All projects must declare nonblank `author` and `repository` values in
328
363
  and `repository.url` strings.
329
364
  Run `peacekeeper check-project --explain` for the complete expected
330
365
  architecture, requirements, configuration examples, and verification limits.
331
- 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),
332
367
  which can also be read without a repository or project configuration.
333
368
 
334
369
  Codex worktree setup requires `.codex/environments/environment.toml` with
335
370
  `version = 1` and a `setup.script` value starting exactly with the bundled
336
- [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.
337
372
  The shell file is a readable reference used for validation; it is not executed
338
373
  by Peacekeeper. Copy its contents into a TOML multiline literal string
339
374
  (`script = '''` followed by a newline, the prefix, and closing `'''`).
@@ -349,9 +384,9 @@ Peacekeeper versions require updating each project's environment configuration.
349
384
  ## Assess unpublished changes
350
385
 
351
386
  Run `peacekeeper assess-release` (or `npm exec --no -- peacekeeper assess-release`)
352
- from a project using Peacekeeper. It always writes one pretty-printed JSON object
353
- to stdout, with fields ordered as `recommendation`, `model`, `releaseSha`,
354
- `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`:
355
390
 
356
391
  ```json
357
392
  {
@@ -365,9 +400,12 @@ to stdout, with fields ordered as `recommendation`, `model`, `releaseSha`,
365
400
 
366
401
  `recommendation` is `patch`, `minor`, `major`, `noop` (no publication needed), or
367
402
  `undetermined` (insufficient evidence or a failed assessment). `motivation`
368
- explains the decision. The command takes no arguments; even invalid arguments
369
- produce an `undetermined` JSON response. Assessment outcomes, including operational
370
- 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.
371
409
 
372
410
  `model` is the model name reported in Codex's startup metadata on stderr. It is
373
411
  `null` if Codex does not report recognizable model metadata or cannot start.
@@ -426,7 +464,7 @@ Check `volta which node`, `node --version`, and `npm --version` to verify your
426
464
  setup. Use `volta pin node@<version> npm@<version>` to update the project versions;
427
465
  `engines.node` separately describes supported consumer versions.
428
466
  Review `npm pack --dry-run --json` before
429
- publishing; npm includes only `bin/`, `scripts/`, the README, and package metadata.
467
+ publishing; npm includes the compiled `dist/` tree, the README, and package metadata.
430
468
 
431
469
  Configure npm trusted publishing for `@jakobm/peacekeeper` with repository owner
432
470
  `jakobmattsson`, repository `peacekeeper`, and workflow filename `package.yml`,
@@ -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
+ });
@@ -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
+ };
@@ -0,0 +1,42 @@
1
+ export default ({ projectConfig, external: { fs, isDeepStrictEqual, output, path, projectConfigDefaults, runtime, } }) => {
2
+ const { CONFIG_FILE, repositoryRoot, validateConfig } = projectConfig;
3
+ function complete(value, defaults) {
4
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
5
+ return value;
6
+ const result = { ...value };
7
+ for (const [key, fallback] of Object.entries(defaults)) {
8
+ if (!Object.hasOwn(value, key))
9
+ result[key] = JSON.parse(JSON.stringify(fallback));
10
+ else if (fallback !== null && typeof fallback === 'object' && !Array.isArray(fallback)) {
11
+ result[key] = complete(value[key], fallback);
12
+ }
13
+ }
14
+ return result;
15
+ }
16
+ function updateConfig(cwd = runtime.cwd()) {
17
+ const file = path.join(repositoryRoot(cwd), CONFIG_FILE);
18
+ const defaults = projectConfigDefaults;
19
+ validateConfig(defaults, 'bundled defaults');
20
+ const exists = fs.existsSync(file);
21
+ const original = exists ? JSON.parse(fs.readFileSync(file, 'utf8')) : {};
22
+ const updated = complete(original, defaults);
23
+ validateConfig(updated, file);
24
+ if (!exists || !isDeepStrictEqual(original, updated)) {
25
+ fs.writeFileSync(file, `${JSON.stringify(updated, null, 2)}\n`);
26
+ output.log(`Updated ${file}. Review defaults before using project commands.`);
27
+ }
28
+ else
29
+ output.log(`Configuration already complete: ${file}`);
30
+ }
31
+ function run() {
32
+ try {
33
+ updateConfig();
34
+ }
35
+ catch (error) {
36
+ output.error(error instanceof Error ? error.message : String(error));
37
+ runtime.exitCode = 1;
38
+ }
39
+ }
40
+ const api = { run, updateConfig };
41
+ return api;
42
+ };
@@ -0,0 +1,16 @@
1
+ allowed-modules:
2
+ cli: [configuration, lifecycle, maintenance, projects, releases, testing]
3
+ configuration: []
4
+ lifecycle: [configuration, maintenance]
5
+ maintenance: [configuration]
6
+ projects: [configuration, releases]
7
+ releases: [configuration]
8
+ testing: [configuration, projects]
9
+ allowed-external:
10
+ cli: [cliConfigPath, runCli]
11
+ configuration: [execFileSync, fs, isDeepStrictEqual, output, path, projectConfigDefaults, runtime]
12
+ lifecycle: [buffer, clock, executablePath, fs, output, path, runtime, spawn, spawnSync]
13
+ maintenance: [execFileSync, fs, output, path, runtime, spawnSync]
14
+ projects: [fs, isDeepStrictEqual, modulesRoot, output, packageVersion, path, projectConfigDefaults, runtime, semver, spawnSync, TOML, url, YAML]
15
+ releases: [assessReleaseSchema, clock, execFileSync, fs, modulesRoot, os, output, path, runtime, semver, spawnSync, url, YAML]
16
+ testing: [clock, crypto, execFileSync, fs, modulesRoot, os, output, path, runtime, spawnSync]
@@ -0,0 +1,48 @@
1
+ import { execFileSync, spawn, spawnSync } from 'node:child_process';
2
+ import crypto from 'node:crypto';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { isDeepStrictEqual } from 'node:util';
7
+ import { fileURLToPath } from 'node:url';
8
+ import TOML from '@iarna/toml';
9
+ import semver from 'semver';
10
+ import YAML from 'yaml';
11
+ import assessReleaseSchema from './releases/assess-release-schema.json' with { type: 'json' };
12
+ import packageManifest from '../../package.json' with { type: 'json' };
13
+ import projectConfigDefaults from './configuration/project-config-defaults.json' with { type: 'json' };
14
+ const moduleDirectory = path.dirname(fileURLToPath(import.meta.url));
15
+ export default () => ({
16
+ buffer: Buffer,
17
+ 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
+ cliConfigPath: path.resolve(moduleDirectory, '../../cmdabra.yaml'),
28
+ executablePath: path.resolve(moduleDirectory, '../../bin/peacekeeper.js'),
29
+ assessReleaseSchema,
30
+ crypto,
31
+ execFileSync,
32
+ fs,
33
+ isDeepStrictEqual,
34
+ modulesRoot: moduleDirectory,
35
+ os,
36
+ output: console,
37
+ packageVersion: packageManifest.version,
38
+ path,
39
+ projectConfigDefaults,
40
+ runCli: async (...args) => (await import('@jakobm/cmdabra')).runCli(...args),
41
+ runtime: process,
42
+ semver,
43
+ spawn,
44
+ spawnSync,
45
+ TOML,
46
+ url: URL,
47
+ YAML,
48
+ });