@jakobm/peacekeeper 0.22.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -23,10 +23,9 @@ verifies that it is current before checking the TypeScript project.
23
23
  Generate the dependency views and SVG diagram with `npm run architecture`. The
24
24
  checked-in output lives in `architecture/`.
25
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.
26
+ Checkpoint and session lifecycle hooks use the same Cmdabra and Portico composition
27
+ as other CLI commands. Dependencies must therefore be installed in every worktree
28
+ before its hooks run; the required Codex environment setup performs `npm ci`.
30
29
 
31
30
  ## Create a compliant TypeScript project
32
31
 
@@ -55,6 +54,8 @@ that the remote has no Git refs. It then installs dependencies, builds, typechec
55
54
  runs the complete Peacekeeper test and project checks, and (for published packages)
56
55
  tests the packed package from a temporary consumer. Only after every local check
57
56
  passes does it create one initial commit on `main` and push without force.
57
+ Generated projects use npm's `prepare` lifecycle hook to build after dependency
58
+ installation, before packing or publishing, and when installed directly from Git.
58
59
 
59
60
  An argument or preflight failure creates nothing. A later failure leaves the local
60
61
  directory for inspection but does not commit or push. A push failure leaves the
@@ -86,7 +87,7 @@ peacekeeper generate-github-setup \
86
87
 
87
88
  Repeat `--repository` to configure any number of repositories in one script.
88
89
  At generation time the command reads and validates each repository's
89
- `peacekeeper.config.json` from its GitHub default branch, then embeds that
90
+ `peacekeeper.config.yaml` from its GitHub default branch, then embeds that
90
91
  repository's `git.releaseRequiredChecks` in the output. A repository without the
91
92
  file uses Peacekeeper's bundled defaults; an invalid file or unreadable repository
92
93
  stops generation. The command writes this configuration snapshot to stdout, so it
@@ -137,7 +138,7 @@ Include these entries in the caller's `package.json`, alongside its other script
137
138
 
138
139
  Run `npm install` from the project root and commit the resulting `package-lock.json`. npm adds `node_modules/.bin` to the `PATH` of package scripts, so package scripts can call `peacekeeper` by name.
139
140
 
140
- ### 2. `peacekeeper.config.json`
141
+ ### 2. `peacekeeper.config.yaml`
141
142
 
142
143
  Place this file at the caller's Git root. Every field, including nested fields,
143
144
  is required. Unknown fields and invalid values are rejected. If no file exists,
@@ -147,10 +148,14 @@ recording or reusing a test receipt.
147
148
 
148
149
  Run `peacekeeper update-config` to create the file or recursively fill missing
149
150
  fields from the defaults. Existing values, including empty arrays, are preserved.
150
- Review newly inserted values. Invalid JSON, unknown fields, or invalid existing
151
+ Comments in an existing YAML file are preserved. Review newly inserted values.
152
+ Invalid YAML, unknown fields, or invalid existing
151
153
  values cause failure without changing the file. Repeating the command on a
152
154
  complete valid file leaves it unchanged.
153
155
 
156
+ The former `peacekeeper.config.json` filename is not accepted. Rename and convert
157
+ it before upgrading so Peacekeeper cannot silently fall back to defaults.
158
+
154
159
  All CLI commands validate configuration before executing, except help,
155
160
  `check-project --explain`, and `update-config`. Checkpoint hooks instead validate
156
161
  the event worktree configuration when the event requires instructions or a check.
@@ -160,31 +165,31 @@ therefore require `peacekeeper update-config` before ordinary commands can run.
160
165
 
161
166
  Complete example:
162
167
 
163
- ```json
164
- {
165
- "publishesToNpm": false,
166
- "git": {
167
- "remote": "origin",
168
- "defaultBranch": "main",
169
- "branchPrefix": "codex/",
170
- "requiredApprover": "OWNER",
171
- "checkpointPushRemotes": ["origin"],
172
- "releaseMergeMethod": "merge",
173
- "releaseRequiredChecks": ["test"],
174
- "releaseTestWorkflow": "test.yml"
175
- },
176
- "tests": {
177
- "commands": ["eslint .", "node --test"],
178
- "receiptMaxAgeMinutes": 60,
179
- "npmTestUsesRunner": true
180
- },
181
- "loggingDirectory": "tmp/logs",
182
- "loggingEnabled": true,
183
- "projectChecks": {
184
- "testWorkflow": "test.yml",
185
- "requiredJobs": ["test"]
186
- }
187
- }
168
+ ```yaml
169
+ publishesToNpm: false
170
+ git:
171
+ remote: origin
172
+ defaultBranch: main
173
+ branchPrefix: codex/
174
+ requiredApprover: OWNER
175
+ checkpointPushRemotes:
176
+ - origin
177
+ releaseMergeMethod: merge
178
+ releaseRequiredChecks:
179
+ - test
180
+ releaseTestWorkflow: test.yml
181
+ tests:
182
+ commands:
183
+ - eslint .
184
+ - node --test
185
+ receiptMaxAgeMinutes: 60
186
+ npmTestUsesRunner: true
187
+ loggingDirectory: tmp/logs
188
+ loggingEnabled: true
189
+ projectChecks:
190
+ testWorkflow: test.yml
191
+ requiredJobs:
192
+ - test
188
193
  ```
189
194
 
190
195
  `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.
@@ -195,13 +200,13 @@ Checkpoint hook failures write the cause to stderr and exit with code 2 instead
195
200
 
196
201
  To publish checkpoint branches automatically, set `git.checkpointPushRemotes` (fragment):
197
202
 
198
- ```json
199
- {
200
- "remote": "origin",
201
- "defaultBranch": "main",
202
- "branchPrefix": "codex/",
203
- "checkpointPushRemotes": ["origin", "backup"]
204
- }
203
+ ```yaml
204
+ remote: origin
205
+ defaultBranch: main
206
+ branchPrefix: codex/
207
+ checkpointPushRemotes:
208
+ - origin
209
+ - backup
205
210
  ```
206
211
 
207
212
  Each name must identify a Git remote configured in the calling repository. Checkpoints push to exactly those remotes, creating the task branch if
@@ -333,7 +338,7 @@ test runner directly, avoiding recursion through `npm test`. The cleanup package
333
338
  scripts work the same way as in calling projects.
334
339
 
335
340
  When first adopting these hooks, make sure the primary checkout also contains
336
- `peacekeeper.config.json` before trusting them with `/hooks`: invocation logs
341
+ `peacekeeper.config.yaml` before trusting them with `/hooks`: invocation logs
337
342
  are stored there and session cleanup reads that checkout's configuration.
338
343
  The hook definitions can then be reviewed and trusted in Codex; committing them
339
344
  does not grant trust automatically.
@@ -342,7 +347,7 @@ does not grant trust automatically.
342
347
 
343
348
  Run `peacekeeper check-project` to check the local project configuration.
344
349
 
345
- Declare the mandatory boolean `publishesToNpm` in `peacekeeper.config.json`.
350
+ Declare the mandatory boolean `publishesToNpm` in `peacekeeper.config.yaml`.
346
351
  Its default is `false`; `update-config` inserts `false` without inferring intent
347
352
  from package metadata. Set it to `true` for packages published to npm (including
348
353
  restricted scoped packages). Peacekeeper itself sets it to `true`.
@@ -388,10 +393,35 @@ Add project-specific commands after `# Add custom project setup below`.
388
393
  Platform-specific `setup.linux.script`, `setup.macos.script`, and
389
394
  `setup.windows.script` overrides, when present, must start with the same prefix.
390
395
  The setup requires Bash and curl, activates or installs Volta, logs tool versions,
391
- and runs `npm ci` using the package.json pins. A passing check validates the
392
- parsed script text; it does not run setup or prove that a fresh environment works.
393
- Verify that separately in a new Codex worktree. Prefix changes in future
394
- Peacekeeper versions require updating each project's environment configuration.
396
+ and runs `npm ci` using the package.json pins. It then runs
397
+ `peacekeeper initialize-codex-worktree --sync-primary` before any project-specific
398
+ setup, initializing each new linked worktree from the exact commit fetched from
399
+ the configured remote default branch and safely synchronizing the primary checkout.
400
+ A passing check validates the parsed script text; it does not run setup or prove
401
+ that a fresh environment works. Verify that separately in a new Codex worktree.
402
+ Prefix changes in future Peacekeeper versions require updating each project's
403
+ environment configuration.
404
+
405
+ The required sequence ends like this:
406
+
407
+ ```toml
408
+ [setup]
409
+ script = '''
410
+ # ...the required Peacekeeper setup prefix...
411
+ npm ci
412
+ npm exec --no -- peacekeeper initialize-codex-worktree --sync-primary
413
+ # Add custom project setup below
414
+ '''
415
+ ```
416
+
417
+ `--sync-primary` makes Peacekeeper also update a clean primary checkout when its
418
+ default branch can be fast-forwarded safely. A clean non-default branch there is
419
+ first synchronized
420
+ with the configured remote; divergent history is published under the next free
421
+ versioned name such as `feature-v2`. Dirty, detached, ahead, or divergent primary
422
+ checkouts are left untouched with an explicit skip message. The command records
423
+ completion in the linked worktree's private Git directory, retries interrupted
424
+ `npm ci` runs, and does not move an established worktree on later setup runs.
395
425
 
396
426
  ## Assess unpublished changes
397
427
 
@@ -490,7 +520,7 @@ another run.
490
520
 
491
521
  Release verification uses GitHub's enforced branch policy instead of retaining
492
522
  artifacts of tested contents. Configure `git.releaseRequiredChecks` in the root
493
- `peacekeeper.config.json` with the exact CI job names required for a release
523
+ `peacekeeper.config.yaml` with the exact CI job names required for a release
494
524
  (for this repository: `["test", "Test package"]`). These checks must be mandatory
495
525
  with **Require branches to be up to date before merging** enabled. Classic branch
496
526
  protection may provide the base PR and check requirements. Active base rulesets
@@ -617,6 +647,10 @@ squash or rebase must be restarted. `git.releaseMergeMethod` remains accepted fo
617
647
  configuration compatibility, but no longer selects the default-branch merge method.
618
648
 
619
649
  From a clean repository root, run `npm run release -- patch`, `minor`, or `major`.
650
+ The required `prerelease` script runs `npm ci` first, replacing `node_modules`
651
+ with the exact dependency versions in the committed lockfile before npm resolves
652
+ and starts Peacekeeper. Always use the npm script; invoking `peacekeeper release`
653
+ directly bypasses this dependency bootstrap.
620
654
  The command fetches the default branch and uses a temporary detached worktree to
621
655
  increment the package and lockfile versions. Your current branch and local default
622
656
  branch stay unchanged, including when the default branch is checked out elsewhere.
@@ -652,9 +686,10 @@ an altered release. Temporary worktrees are removed when the command exits
652
686
  normally or with a handled error; a killed process may leave a temporary worktree
653
687
  that needs manual cleanup.
654
688
 
655
- Other npm projects can use this command through a package script such as
656
- `"release": "peacekeeper release"`. The project must use a root package
657
- with a stable version, a `peacekeeper.config.json` with
689
+ Other npm projects can use this command through package scripts such as
690
+ `"prerelease": "npm ci"` and `"release": "peacekeeper release"`. npm runs the
691
+ former automatically before the latter. The project must use a root package
692
+ with a stable version, a `peacekeeper.config.yaml` with
658
693
  `git.releaseRequiredChecks`, and the supported tag-triggered GitHub Actions
659
694
  publish job. Add `peacekeeper verify-release-protection` to a required PR
660
695
  test job and `peacekeeper verify-release` before publishing, with `GH_TOKEN`
@@ -1,36 +1,5 @@
1
1
  #!/usr/bin/env node
2
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
- });
3
+ const rawArgs = process.argv.slice(2);
4
+ const container = await createContainer();
5
+ await container.resolve('cli').run(rawArgs);
package/dist/cmdabra.yaml CHANGED
@@ -88,6 +88,12 @@ commands:
88
88
  description: Queue cleanup for a merged Codex session worktree.
89
89
  queue-merged-worktree-cleanup:
90
90
  description: Queue cleanup for the current merged worktree.
91
+ initialize-codex-worktree:
92
+ description: Initialize a linked Codex worktree from the configured default branch.
93
+ named-options:
94
+ sync-primary:
95
+ description: Safely publish and update the primary checkout too.
96
+ type: boolean
91
97
  cleanup-merged-branches:
92
98
  description: Preview or delete merged worktrees and branches.
93
99
  named-options:
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jakobm/peacekeeper",
3
- "version": "0.22.0",
3
+ "version": "0.24.0",
4
4
  "description": "Shared repository test, Git worktree, and Codex hook commands",
5
5
  "license": "MIT",
6
6
  "author": "Jakob Mattsson",
@@ -31,6 +31,7 @@
31
31
  "test": "npm run build && node dist/bin/peacekeeper.js run-tests",
32
32
  "prepare": "npm run build",
33
33
  "architecture": "npm run build && portico architecture --modules dist/src/modules --output architecture",
34
+ "prerelease": "npm ci",
34
35
  "release": "node dist/bin/peacekeeper.js release",
35
36
  "cleanup:branches": "node dist/bin/peacekeeper.js cleanup-merged-branches",
36
37
  "cleanup:empty-directories": "node dist/bin/peacekeeper.js remove-empty-directories"
@@ -40,7 +41,7 @@
40
41
  },
41
42
  "dependencies": {
42
43
  "@iarna/toml": "^2.2.5",
43
- "@jakobm/cmdabra": "^0.2.1",
44
+ "@jakobm/cmdabra": "^0.6.0",
44
45
  "@jakobm/portico": "^0.7.0",
45
46
  "semver": "^7.8.5",
46
47
  "yaml": "^2.9.1"
@@ -1,89 +1,7 @@
1
- import { execFileSync, spawn, spawnSync } from 'node:child_process';
2
- import fs from 'node:fs';
3
1
  import path from 'node:path';
4
2
  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
3
  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();
4
+ export async function createContainer() {
87
5
  const { default: portico } = await import('@jakobm/portico');
88
6
  return await portico.createRepositoryContainerAsync(path.resolve(currentDirectory, 'modules'));
89
7
  }
@@ -1,13 +1,13 @@
1
- export default ({ configuration, lifecycle, maintenance, projects, releases, testing, external: { cliConfigPath, runCli }, }) => {
1
+ export default ({ configuration, lifecycle, maintenance, projects, releases, testing, external: { cliConfigPath, runCli, runtime }, }) => {
2
2
  function executionMode({ dryRun, execute }) {
3
3
  if (dryRun && execute)
4
4
  throw new Error('--dry-run and --execute cannot be combined');
5
5
  return Boolean(execute);
6
6
  }
7
7
  const implementation = {
8
- 'update-config': () => configuration.updateConfig(),
9
- 'check-project': options => projects.checkProject({ explain: options.explain }),
10
- 'create-project': options => projects.createProject({
8
+ updateConfig: () => configuration.updateConfig(),
9
+ checkProject: options => projects.checkProject({ explain: options.explain }),
10
+ createProject: options => projects.createProject({
11
11
  repository: options.repository,
12
12
  directory: options.directory,
13
13
  packageName: options.packageName,
@@ -15,34 +15,49 @@ export default ({ configuration, lifecycle, maintenance, projects, releases, tes
15
15
  authorEmail: options.authorEmail,
16
16
  published: options.publishToNpm === 'true',
17
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(),
18
+ generateGithubSetup: options => projects.generateGithubSetup({ repository: options.repository }),
19
+ installHooks: options => projects.installHooks({ dryRun: options.dryRun }),
20
+ checkTestReceipt: () => testing.checkTestReceipt(),
21
+ recordTestReceipt: () => testing.recordTestReceipt(),
22
+ runTests: options => testing.runTests({ force: options.force }),
23
+ assessRelease: () => releases.assessRelease(),
24
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({
25
+ verifyRelease: () => releases.verifyRelease(),
26
+ verifyReleaseProtection: () => releases.verifyReleaseProtection(),
27
+ verifyReleaseVersion: () => releases.verifyReleaseVersion(),
28
+ checkpointCodexChanges: options => lifecycle.checkpointCodexChanges({
29
29
  subject: options.subject,
30
30
  bodyParagraphs: options.body,
31
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({
32
+ checkpointCodexSessionStart: () => lifecycle.checkpointCodexSessionStart(),
33
+ checkpointCodexStop: () => lifecycle.checkpointCodexStop(),
34
+ cleanupEndedSession: () => lifecycle.cleanupEndedSession(),
35
+ queueMergedWorktreeCleanup: () => lifecycle.queueMergedWorktreeCleanup(),
36
+ initializeCodexWorktree: options => maintenance.initializeCodexWorktree({
37
+ syncPrimary: options.syncPrimary,
38
+ }),
39
+ cleanupMergedBranches: options => maintenance.cleanupMergedBranches({
37
40
  execute: executionMode(options),
38
41
  }),
39
- 'remove-empty-directories': options => maintenance.removeEmptyDirectories({
42
+ removeEmptyDirectories: options => maintenance.removeEmptyDirectories({
40
43
  execute: executionMode(options),
41
44
  }),
42
45
  };
46
+ function cliProcess(rawArgs) {
47
+ return {
48
+ argv: [runtime.execPath, runtime.argv[1] || 'peacekeeper', ...rawArgs],
49
+ env: runtime.env,
50
+ stdin: runtime.stdin,
51
+ stdout: runtime.stdout,
52
+ stderr: runtime.stderr,
53
+ get exitCode() { return runtime.exitCode; },
54
+ set exitCode(value) { runtime.exitCode = value; },
55
+ exit: code => runtime.exit(code),
56
+ };
57
+ }
43
58
  return {
44
59
  async run(rawArgs) {
45
- await runCli(cliConfigPath, implementation, rawArgs);
60
+ await runCli(cliConfigPath, implementation, cliProcess(rawArgs));
46
61
  },
47
62
  };
48
63
  };
@@ -1,5 +1,6 @@
1
- export default ({ external: { execFileSync, fs, path, projectConfigDefaults, runtime, } }) => {
2
- const CONFIG_FILE = 'peacekeeper.config.json';
1
+ export default ({ external: { execFileSync, fs, path, projectConfigDefaults, runtime, YAML, } }) => {
2
+ const CONFIG_FILE = 'peacekeeper.config.yaml';
3
+ const LEGACY_CONFIG_FILE = 'peacekeeper.config.json';
3
4
  function repositoryRoot(cwd = runtime.cwd()) {
4
5
  return execFileSync('git', ['rev-parse', '--show-toplevel'], {
5
6
  cwd,
@@ -98,8 +99,12 @@ export default ({ external: { execFileSync, fs, path, projectConfigDefaults, run
98
99
  function projectConfig(cwd = runtime.cwd()) {
99
100
  const root = repositoryRoot(cwd);
100
101
  const file = path.join(root, CONFIG_FILE);
102
+ const legacyFile = path.join(root, LEGACY_CONFIG_FILE);
103
+ if (!fs.existsSync(file) && fs.existsSync(legacyFile)) {
104
+ throw new Error(`${legacyFile}: rename this legacy JSON configuration to ${CONFIG_FILE} and convert it to YAML.`);
105
+ }
101
106
  const config = fs.existsSync(file)
102
- ? JSON.parse(fs.readFileSync(file, 'utf8'))
107
+ ? YAML.parse(fs.readFileSync(file, 'utf8'))
103
108
  : JSON.parse(JSON.stringify(projectConfigDefaults));
104
109
  validateConfig(config, file);
105
110
  return { root, ...config };
@@ -109,6 +114,6 @@ export default ({ external: { execFileSync, fs, path, projectConfigDefaults, run
109
114
  throw new Error('Configure tests.commands before running tests or using a test receipt.');
110
115
  }
111
116
  }
112
- const api = { CONFIG_FILE, CONFIG_SCHEMA, validateConfig, projectConfig, repositoryRoot, requireTestCommands };
117
+ const api = { CONFIG_FILE, LEGACY_CONFIG_FILE, CONFIG_SCHEMA, validateConfig, projectConfig, repositoryRoot, requireTestCommands };
113
118
  return api;
114
119
  };
@@ -1,5 +1,5 @@
1
- export default ({ projectConfig, external: { fs, isDeepStrictEqual, output, path, projectConfigDefaults, runtime, } }) => {
2
- const { CONFIG_FILE, repositoryRoot, validateConfig } = projectConfig;
1
+ export default ({ projectConfig, external: { fs, isDeepStrictEqual, output, path, projectConfigDefaults, runtime, YAML, } }) => {
2
+ const { CONFIG_FILE, LEGACY_CONFIG_FILE, repositoryRoot, validateConfig } = projectConfig;
3
3
  function complete(value, defaults) {
4
4
  if (value === null || typeof value !== 'object' || Array.isArray(value))
5
5
  return value;
@@ -13,16 +13,35 @@ export default ({ projectConfig, external: { fs, isDeepStrictEqual, output, path
13
13
  }
14
14
  return result;
15
15
  }
16
+ function addMissing(document, value, defaults, keys = []) {
17
+ for (const [key, fallback] of Object.entries(defaults)) {
18
+ const childKeys = [...keys, key];
19
+ if (!Object.hasOwn(value, key))
20
+ document.setIn(childKeys, JSON.parse(JSON.stringify(fallback)));
21
+ else if (fallback !== null && typeof fallback === 'object' && !Array.isArray(fallback)) {
22
+ addMissing(document, value[key], fallback, childKeys);
23
+ }
24
+ }
25
+ }
16
26
  function updateConfig(cwd = runtime.cwd()) {
17
- const file = path.join(repositoryRoot(cwd), CONFIG_FILE);
27
+ const root = repositoryRoot(cwd);
28
+ const file = path.join(root, CONFIG_FILE);
29
+ const legacyFile = path.join(root, LEGACY_CONFIG_FILE);
30
+ if (!fs.existsSync(file) && fs.existsSync(legacyFile)) {
31
+ throw new Error(`${legacyFile}: rename this legacy JSON configuration to ${CONFIG_FILE} and convert it to YAML.`);
32
+ }
18
33
  const defaults = projectConfigDefaults;
19
34
  validateConfig(defaults, 'bundled defaults');
20
35
  const exists = fs.existsSync(file);
21
- const original = exists ? JSON.parse(fs.readFileSync(file, 'utf8')) : {};
36
+ const document = exists ? YAML.parseDocument(fs.readFileSync(file, 'utf8')) : new YAML.Document({});
37
+ if (document.errors.length)
38
+ throw new Error(`${file}: ${document.errors.map(error => error.message).join('; ')}`);
39
+ const original = document.toJS();
22
40
  const updated = complete(original, defaults);
23
41
  validateConfig(updated, file);
24
42
  if (!exists || !isDeepStrictEqual(original, updated)) {
25
- fs.writeFileSync(file, `${JSON.stringify(updated, null, 2)}\n`);
43
+ addMissing(document, original, defaults);
44
+ fs.writeFileSync(file, document.toString({ lineWidth: 0 }));
26
45
  output.log(`Updated ${file}. Review defaults before using project commands.`);
27
46
  }
28
47
  else
@@ -7,8 +7,8 @@ allowed-modules:
7
7
  releases: [configuration]
8
8
  testing: [configuration, projects]
9
9
  allowed-external:
10
- cli: [cliConfigPath, runCli]
11
- configuration: [execFileSync, fs, isDeepStrictEqual, output, path, projectConfigDefaults, runtime]
10
+ cli: [cliConfigPath, runCli, runtime]
11
+ configuration: [execFileSync, fs, isDeepStrictEqual, output, path, projectConfigDefaults, runtime, YAML]
12
12
  lifecycle: [buffer, clock, executablePath, fs, output, path, runtime, spawn, spawnSync]
13
13
  maintenance: [execFileSync, fs, output, path, runtime, spawnSync]
14
14
  projects: [buffer, fs, isDeepStrictEqual, modulesRoot, output, packageVersion, path, projectConfigDefaults, runtime, semver, spawnSync, TOML, url, YAML]
@@ -0,0 +1,301 @@
1
+ /**
2
+ * Initialize the current linked Codex worktree from one captured remote commit.
3
+ *
4
+ * State is kept in the linked worktree's private Git directory. That makes an
5
+ * interrupted dependency installation retryable while preventing a later setup
6
+ * invocation from moving an already established worktree.
7
+ */
8
+ export default ({ configuration, external: { fs, output, path, runtime, spawnSync, } }) => {
9
+ const { projectConfig } = configuration;
10
+ const MARKER_FILE = 'peacekeeper-codex-worktree.json';
11
+ function tryCommand(command, args, cwd) {
12
+ return spawnSync(command, args, {
13
+ cwd,
14
+ encoding: 'utf8',
15
+ stdio: ['ignore', 'pipe', 'pipe'],
16
+ });
17
+ }
18
+ function command(commandName, args, cwd) {
19
+ const result = tryCommand(commandName, args, cwd);
20
+ if (result.status !== 0) {
21
+ const detail = result.stderr?.trim() || result.stdout?.trim();
22
+ throw new Error(detail || `${commandName} ${args.join(' ')} failed`);
23
+ }
24
+ return result.stdout?.trim() || '';
25
+ }
26
+ function git(cwd, ...args) {
27
+ return command('git', args, cwd);
28
+ }
29
+ function samePath(first, second) {
30
+ try {
31
+ return fs.realpathSync(first) === fs.realpathSync(second);
32
+ }
33
+ catch {
34
+ return path.resolve(first) === path.resolve(second);
35
+ }
36
+ }
37
+ function primaryWorktree(cwd) {
38
+ const fields = git(cwd, 'worktree', 'list', '--porcelain', '-z').split('\0');
39
+ const field = fields.find(value => value.startsWith('worktree '));
40
+ if (!field)
41
+ throw new Error('could not locate the primary Git worktree');
42
+ return field.slice('worktree '.length);
43
+ }
44
+ function markerPath(root) {
45
+ const directory = git(root, 'rev-parse', '--path-format=absolute', '--git-dir');
46
+ return path.join(directory, MARKER_FILE);
47
+ }
48
+ function readState(root) {
49
+ const file = markerPath(root);
50
+ if (!fs.existsSync(file))
51
+ return null;
52
+ const state = JSON.parse(fs.readFileSync(file, 'utf8'));
53
+ if (state?.version !== 1
54
+ || typeof state.target !== 'string'
55
+ || typeof state.worktree?.complete !== 'boolean'
56
+ || typeof state.worktree?.installPending !== 'boolean')
57
+ throw new Error(`${file}: invalid initialization state`);
58
+ return state;
59
+ }
60
+ function writeState(root, state) {
61
+ const file = markerPath(root);
62
+ const temporary = `${file}.tmp-${runtime.pid}`;
63
+ fs.writeFileSync(temporary, `${JSON.stringify(state, null, 2)}\n`, { flag: 'wx' });
64
+ fs.renameSync(temporary, file);
65
+ }
66
+ function currentHead(root) {
67
+ return git(root, 'rev-parse', 'HEAD^{commit}');
68
+ }
69
+ function currentBranch(root) {
70
+ const result = tryCommand('git', ['symbolic-ref', '--quiet', '--short', 'HEAD'], root);
71
+ if (result.status === 0)
72
+ return result.stdout.trim();
73
+ if (result.status === 1)
74
+ return null;
75
+ const detail = result.stderr?.trim() || result.stdout?.trim();
76
+ throw new Error(detail || 'could not inspect the current branch');
77
+ }
78
+ function isAncestor(root, ancestor, descendant) {
79
+ const result = tryCommand('git', ['merge-base', '--is-ancestor', ancestor, descendant], root);
80
+ if (result.status === 0)
81
+ return true;
82
+ if (result.status === 1)
83
+ return false;
84
+ const detail = result.stderr?.trim() || result.stdout?.trim();
85
+ throw new Error(detail || `could not compare ${ancestor} and ${descendant}`);
86
+ }
87
+ function localBranchHead(root, branch) {
88
+ const result = tryCommand('git', ['rev-parse', '--verify', '--quiet', `refs/heads/${branch}^{commit}`], root);
89
+ if (result.status === 0)
90
+ return result.stdout.trim();
91
+ if (result.status === 1)
92
+ return null;
93
+ const detail = result.stderr?.trim() || result.stdout?.trim();
94
+ throw new Error(detail || `could not inspect local branch ${branch}`);
95
+ }
96
+ function remoteBranchHead(root, remote, branch) {
97
+ const result = tryCommand('git', ['ls-remote', '--exit-code', '--heads', remote, `refs/heads/${branch}`], root);
98
+ if (result.status === 2)
99
+ return null;
100
+ if (result.status !== 0) {
101
+ const detail = result.stderr?.trim() || result.stdout?.trim();
102
+ throw new Error(detail || `could not inspect ${remote}/${branch}`);
103
+ }
104
+ return result.stdout.trim().split(/\s+/u)[0];
105
+ }
106
+ function installDependencies(root) {
107
+ command('npm', ['ci'], root);
108
+ }
109
+ function captureTarget(root, remote, defaultBranch) {
110
+ git(root, 'fetch', '--no-tags', remote, `refs/heads/${defaultBranch}`);
111
+ return git(root, 'rev-parse', 'FETCH_HEAD^{commit}');
112
+ }
113
+ function initializeLinkedWorktree(root, state, log) {
114
+ if (state.worktree.complete) {
115
+ log(`Linked worktree already initialized at ${state.target}.`);
116
+ return;
117
+ }
118
+ const head = currentHead(root);
119
+ if (head !== state.target) {
120
+ const changes = git(root, 'status', '--porcelain', '--untracked-files=no');
121
+ if (changes)
122
+ throw new Error('refusing to move a linked worktree with tracked changes');
123
+ state.worktree.installPending = true;
124
+ writeState(root, state);
125
+ git(root, 'switch', '--detach', state.target);
126
+ log(`Moved linked worktree from ${head} to ${state.target}.`);
127
+ }
128
+ if (state.worktree.installPending) {
129
+ installDependencies(root);
130
+ state.worktree.installPending = false;
131
+ log('Installed linked-worktree dependencies with npm ci.');
132
+ }
133
+ state.worktree.complete = true;
134
+ writeState(root, state);
135
+ }
136
+ function nextVersionedBranch(root, remote, branch) {
137
+ const match = /^(.*)-v([0-9]+)$/u.exec(branch);
138
+ const base = match ? match[1] : branch;
139
+ let version = match ? Number(match[2]) + 1 : 2;
140
+ while (true) {
141
+ const candidate = `${base}-v${version}`;
142
+ if (!localBranchHead(root, candidate) && !remoteBranchHead(root, remote, candidate)) {
143
+ return candidate;
144
+ }
145
+ version += 1;
146
+ }
147
+ }
148
+ function setAndVerifyUpstream(root, remote, branch, expectedHead) {
149
+ git(root, 'branch', '--set-upstream-to', `${remote}/${branch}`, branch);
150
+ const local = git(root, 'rev-parse', `refs/heads/${branch}^{commit}`);
151
+ const upstream = git(root, 'rev-parse', `refs/remotes/${remote}/${branch}^{commit}`);
152
+ if (local !== expectedHead || upstream !== expectedHead) {
153
+ throw new Error(`${branch} does not exactly match its upstream after synchronization`);
154
+ }
155
+ }
156
+ function finishStoredPreservation(root, remote, preservation, log) {
157
+ const local = localBranchHead(root, preservation.branch);
158
+ if (local && local !== preservation.head) {
159
+ throw new Error(`preserved branch ${preservation.branch} no longer points to ${preservation.head}`);
160
+ }
161
+ if (!local)
162
+ git(root, 'switch', '--create', preservation.branch, preservation.head);
163
+ else if (currentBranch(root) !== preservation.branch)
164
+ git(root, 'switch', preservation.branch);
165
+ const remoteHead = remoteBranchHead(root, remote, preservation.branch);
166
+ if (remoteHead && remoteHead !== preservation.head) {
167
+ throw new Error(`remote preserved branch ${remote}/${preservation.branch} changed unexpectedly`);
168
+ }
169
+ if (!remoteHead) {
170
+ git(root, 'push', '--set-upstream', remote, preservation.branch);
171
+ }
172
+ else {
173
+ git(root, 'fetch', '--no-tags', remote, `+refs/heads/${preservation.branch}:refs/remotes/${remote}/${preservation.branch}`);
174
+ }
175
+ setAndVerifyUpstream(root, remote, preservation.branch, preservation.head);
176
+ log(`Preserved divergent ${preservation.sourceBranch} as ${remote}/${preservation.branch}.`);
177
+ }
178
+ function synchronizeCurrentBranch(linkedRoot, primaryRoot, remote, branch, state, log) {
179
+ const primary = state.primary;
180
+ if (primary.preservation) {
181
+ finishStoredPreservation(primaryRoot, remote, primary.preservation, log);
182
+ return;
183
+ }
184
+ const localHead = currentHead(primaryRoot);
185
+ const remoteHead = remoteBranchHead(primaryRoot, remote, branch);
186
+ if (!remoteHead) {
187
+ git(primaryRoot, 'push', '--set-upstream', remote, branch);
188
+ log(`Published ${branch} to ${remote}/${branch}.`);
189
+ }
190
+ else {
191
+ git(primaryRoot, 'fetch', '--no-tags', remote, `+refs/heads/${branch}:refs/remotes/${remote}/${branch}`);
192
+ if (localHead === remoteHead) {
193
+ log(`${branch} already matches ${remote}/${branch}.`);
194
+ }
195
+ else if (isAncestor(primaryRoot, localHead, remoteHead)) {
196
+ git(primaryRoot, 'merge', '--ff-only', remoteHead);
197
+ log(`Fast-forwarded ${branch} to ${remote}/${branch}.`);
198
+ }
199
+ else if (isAncestor(primaryRoot, remoteHead, localHead)) {
200
+ git(primaryRoot, 'push', remote, `HEAD:refs/heads/${branch}`);
201
+ log(`Pushed ${branch} to ${remote}/${branch}.`);
202
+ }
203
+ else {
204
+ const versioned = nextVersionedBranch(primaryRoot, remote, branch);
205
+ primary.preservation = { sourceBranch: branch, branch: versioned, head: localHead };
206
+ writeState(linkedRoot, state);
207
+ finishStoredPreservation(primaryRoot, remote, primary.preservation, log);
208
+ return;
209
+ }
210
+ }
211
+ const synchronizedHead = currentHead(primaryRoot);
212
+ setAndVerifyUpstream(primaryRoot, remote, branch, synchronizedHead);
213
+ }
214
+ function synchronizePrimary(linkedRoot, primaryRoot, state, config, log) {
215
+ state.primary ||= { complete: false, installPending: false };
216
+ if (state.primary.complete) {
217
+ log(`Primary checkout already synchronized at ${state.target}.`);
218
+ return;
219
+ }
220
+ const status = git(primaryRoot, 'status', '--porcelain', '--untracked-files=all');
221
+ if (status) {
222
+ log('Skipped primary checkout synchronization: it has tracked or untracked changes.');
223
+ return;
224
+ }
225
+ const branch = currentBranch(primaryRoot);
226
+ if (!branch) {
227
+ log('Skipped primary checkout synchronization: its HEAD is detached.');
228
+ return;
229
+ }
230
+ const { defaultBranch, remote } = config.git;
231
+ const defaultHead = localBranchHead(primaryRoot, defaultBranch);
232
+ if (!defaultHead) {
233
+ log(`Skipped primary checkout synchronization: local default branch ${defaultBranch} does not exist.`);
234
+ return;
235
+ }
236
+ if (!isAncestor(primaryRoot, defaultHead, state.target)) {
237
+ log(`Skipped primary checkout synchronization: local ${defaultBranch} is ahead of or diverged from ${remote}/${defaultBranch}.`);
238
+ return;
239
+ }
240
+ if (branch !== defaultBranch) {
241
+ synchronizeCurrentBranch(linkedRoot, primaryRoot, remote, branch, state, log);
242
+ git(primaryRoot, 'switch', defaultBranch);
243
+ }
244
+ const before = currentHead(primaryRoot);
245
+ if (before !== state.target) {
246
+ state.primary.installPending = true;
247
+ writeState(linkedRoot, state);
248
+ git(primaryRoot, 'merge', '--ff-only', state.target);
249
+ if (currentHead(primaryRoot) !== state.target) {
250
+ throw new Error(`primary ${defaultBranch} did not reach captured target ${state.target}`);
251
+ }
252
+ log(`Fast-forwarded primary ${defaultBranch} to ${state.target}.`);
253
+ }
254
+ if (state.primary.installPending) {
255
+ installDependencies(primaryRoot);
256
+ state.primary.installPending = false;
257
+ writeState(linkedRoot, state);
258
+ log('Installed primary-checkout dependencies with npm ci.');
259
+ }
260
+ state.primary.complete = true;
261
+ writeState(linkedRoot, state);
262
+ }
263
+ function run({ syncPrimary = false, cwd = runtime.cwd(), log = output.log } = {}) {
264
+ const root = git(cwd, 'rev-parse', '--show-toplevel');
265
+ const primaryRoot = primaryWorktree(root);
266
+ if (samePath(root, primaryRoot)) {
267
+ throw new Error('initialize-codex-worktree must run from a linked Git worktree');
268
+ }
269
+ const config = projectConfig(root);
270
+ let state = readState(root);
271
+ if (!state) {
272
+ const target = captureTarget(root, config.git.remote, config.git.defaultBranch);
273
+ state = {
274
+ version: 1,
275
+ target,
276
+ worktree: { complete: false, installPending: false },
277
+ };
278
+ writeState(root, state);
279
+ }
280
+ initializeLinkedWorktree(root, state, log);
281
+ if (syncPrimary)
282
+ synchronizePrimary(root, primaryRoot, state, config, log);
283
+ return state;
284
+ }
285
+ function main(options = {}) {
286
+ try {
287
+ return run(options);
288
+ }
289
+ catch (error) {
290
+ output.error(`Error: ${error instanceof Error ? error.message : String(error)}`);
291
+ runtime.exitCode = 1;
292
+ }
293
+ }
294
+ return {
295
+ MARKER_FILE,
296
+ captureTarget,
297
+ main,
298
+ nextVersionedBranch,
299
+ run,
300
+ };
301
+ };
@@ -1,7 +1,8 @@
1
- export default ({ cleanupMergedBranches, removeEmptyDirectories }) => ({
1
+ export default ({ cleanupMergedBranches, initializeCodexWorktree, removeEmptyDirectories }) => ({
2
2
  applyPlan: cleanupMergedBranches.applyPlan,
3
3
  buildPlan: cleanupMergedBranches.buildPlan,
4
4
  cleanupMergedBranches: cleanupMergedBranches.run,
5
+ initializeCodexWorktree: initializeCodexWorktree.main,
5
6
  listWorktrees: cleanupMergedBranches.listWorktrees,
6
7
  removeEmptyDirectories: removeEmptyDirectories.main,
7
8
  });
@@ -13,7 +13,7 @@ Purpose and scope
13
13
  --explain prints this entire document without loading or checking a project.
14
14
 
15
15
  Project configuration
16
- package.json is required at the Git root. Without peacekeeper.config.json,
16
+ package.json is required at the Git root. Without peacekeeper.config.yaml,
17
17
  bundled defaults apply. An existing configuration must declare every schema
18
18
  field, including nested fields; unknown fields and invalid values fail.
19
19
  Run peacekeeper update-config to create or complete it without overwriting
@@ -90,7 +90,8 @@ Codex worktree environment
90
90
  Copy the reference into a TOML multiline literal string to preserve shell
91
91
  backslashes. Preserve project-specific steps when replacing an older prefix.
92
92
  The prefix requires Bash and curl, activates or installs Volta without editing
93
- shell profiles, logs tool versions and runs npm ci using package.json pins.
93
+ shell profiles, logs tool versions, runs npm ci using package.json pins, then
94
+ initializes the linked worktree and safely synchronizes the primary checkout.
94
95
  Peacekeeper only reads this reference; it never executes the shell file or
95
96
  the project's setup script. Passing validates declarations, not successful
96
97
  provisioning, network access or availability of project-specific prerequisites.
@@ -224,8 +225,12 @@ Publication: publishesToNpm=true
224
225
  With true, package.json private must be absent or false. Require a valid npm
225
226
  name, nonblank description and license, nonempty files list, and publishConfig
226
227
  registry https://registry.npmjs.org/ with access public or restricted.
227
- scripts.release must directly invoke peacekeeper release (also supported:
228
- npm exec --no -- peacekeeper release or the local Node CLI forms).
228
+ scripts.prerelease must be exactly npm ci. npm runs it before scripts.release,
229
+ so release starts with the dependency versions committed in the lockfile even
230
+ when node_modules was installed before the latest pull. scripts.release must
231
+ directly invoke peacekeeper release (also supported: npm exec --no --
232
+ peacekeeper release or the local Node CLI forms). Run releases through
233
+ npm run release so npm does not bypass the prerelease installation.
229
234
  The selected PR workflow must declare an unconditional packaging check after
230
235
  npm ci: npm pack (optionally
231
236
  --dry-run, optionally followed by --json), or npm run test:package.
@@ -56,7 +56,7 @@ export default ({ configuration, installHooks, releases, external: { fs, isDeepS
56
56
  });
57
57
  check('GitHub policy', () => {
58
58
  const approver = config.git.requiredApprover;
59
- requireThat(typeof approver === 'string', 'peacekeeper.config.json: set git.requiredApprover to the personal GitHub repository owner.');
59
+ requireThat(typeof approver === 'string', 'peacekeeper.config.yaml: set git.requiredApprover to the personal GitHub repository owner.');
60
60
  if (typeof approver !== 'string')
61
61
  return;
62
62
  const file = '.github/CODEOWNERS';
@@ -200,6 +200,7 @@ export default ({ configuration, installHooks, releases, external: { fs, isDeepS
200
200
  requireThat(manifest.publishConfig?.registry === 'https://registry.npmjs.org/'
201
201
  && ['public', 'restricted'].includes(manifest.publishConfig?.access), 'package.json: publishConfig must declare registry https://registry.npmjs.org/ and access public or restricted.');
202
202
  requireThat(Array.isArray(manifest.files) && manifest.files.length > 0 && manifest.files.every(nonblank), 'package.json: published packages require a nonempty files list.');
203
+ requireThat(typeof scripts.prerelease === 'string' && scripts.prerelease.trim() === 'npm ci', 'package.json: scripts.prerelease must be exactly npm ci so release uses the locked dependencies.');
203
204
  requireThat(typeof scripts.release === 'string' && releaseCommand.test(scripts.release.trim()), 'package.json: scripts.release must invoke peacekeeper release directly.');
204
205
  const testWorkflow = workflows.get(config.projectChecks.testWorkflow);
205
206
  requireThat(testWorkflow && Object.values(testWorkflow.jobs).some((rawJob) => {
@@ -231,7 +232,7 @@ export default ({ configuration, installHooks, releases, external: { fs, isDeepS
231
232
  check('CI', () => {
232
233
  const workflow = workflows.get(filename);
233
234
  if (!workflow) {
234
- requireThat(false, `${filename}: configured PR workflow is missing (selected by projectChecks.testWorkflow). Set projectChecks.testWorkflow${published ? ' and git.releaseTestWorkflow to the same existing file' : ' to an existing file'} in peacekeeper.config.json. PR checks are blocked until it can be read.`);
235
+ requireThat(false, `${filename}: configured PR workflow is missing (selected by projectChecks.testWorkflow). Set projectChecks.testWorkflow${published ? ' and git.releaseTestWorkflow to the same existing file' : ' to an existing file'} in peacekeeper.config.yaml. PR checks are blocked until it can be read.`);
235
236
  return;
236
237
  }
237
238
  const jobs = workflow.jobs;
@@ -18,4 +18,7 @@ npm --version
18
18
  # Install the exact dependency versions recorded in the lockfile.
19
19
  npm ci
20
20
 
21
+ # Initialize the linked worktree and safely synchronize the primary checkout.
22
+ npm exec --no -- peacekeeper initialize-codex-worktree --sync-primary
23
+
21
24
  # Add custom project setup below
@@ -1,4 +1,4 @@
1
- export default ({ installHooks, releases, external: { fs, modulesRoot, packageVersion, path, projectConfigDefaults, runtime, spawnSync, url: Url, } }) => {
1
+ export default ({ installHooks, releases, external: { fs, modulesRoot, packageVersion, path, projectConfigDefaults, runtime, spawnSync, url: Url, YAML, } }) => {
2
2
  const { planHooks } = installHooks;
3
3
  const { createGithubPolicy, githubSetupPlan } = releases;
4
4
  const TOOLCHAIN = Object.freeze({
@@ -126,8 +126,8 @@ export default ({ installHooks, releases, external: { fs, modulesRoot, packageVe
126
126
  repository: { type: 'git', url: `git+${options.repository}` }, license: 'MIT',
127
127
  engines: { node: '>=20' }, volta: { node: TOOLCHAIN.node, npm: TOOLCHAIN.npm },
128
128
  main: './dist/index.js', types: './dist/index.d.ts', exports: { '.': { types: './dist/index.d.ts', import: './dist/index.js' } },
129
- scripts: { build: 'tsc -p tsconfig.json', typecheck: 'tsc -p tsconfig.json --noEmit', test: 'peacekeeper run-tests', 'test:unit': 'node --test test/*.test.js',
130
- ...(options.published ? { 'test:package': 'node scripts/test-package.cjs', release: 'peacekeeper release' } : {}) },
129
+ scripts: { build: 'tsc -p tsconfig.json', prepare: 'npm run build', typecheck: 'tsc -p tsconfig.json --noEmit', test: 'peacekeeper run-tests', 'test:unit': 'node --test test/*.test.js',
130
+ ...(options.published ? { 'test:package': 'node scripts/test-package.cjs', prerelease: 'npm ci', release: 'peacekeeper release' } : {}) },
131
131
  devDependencies: { '@jakobm/peacekeeper': version, '@types/node': TOOLCHAIN.nodeTypes, typescript: TOOLCHAIN.typescript },
132
132
  ...(options.published ? { files: ['dist/'], publishConfig: { access: 'public', registry: 'https://registry.npmjs.org/' } } : {}),
133
133
  };
@@ -142,7 +142,7 @@ export default ({ installHooks, releases, external: { fs, modulesRoot, packageVe
142
142
  defaults.git.requiredApprover = options.owner;
143
143
  defaults.tests.commands = ['npm run typecheck', 'npm run build', 'npm run test:unit', ...(options.published ? ['npm run test:package'] : [])];
144
144
  defaults.tests.npmTestUsesRunner = true;
145
- write(root, 'peacekeeper.config.json', json(defaults));
145
+ write(root, 'peacekeeper.config.yaml', YAML.stringify(defaults, { lineWidth: 0 }));
146
146
  write(root, '.codex/hooks.json', json(planHooks({}).document));
147
147
  const prefix = fs.readFileSync(path.join(modulesRoot, 'projects/codex-setup-prefix.sh'), 'utf8');
148
148
  write(root, '.codex/environments/environment.toml', `version = 1\nname = ${JSON.stringify(options.repositoryName)}\n\n[setup]\nscript = '''\n${prefix}'''\n`);
@@ -1,4 +1,4 @@
1
- export default ({ configuration, createProjectCore, external: { buffer: Buffer, projectConfigDefaults, runtime, spawnSync, } }) => {
1
+ export default ({ configuration, createProjectCore, external: { buffer: Buffer, projectConfigDefaults, runtime, spawnSync, YAML, } }) => {
2
2
  const { validateConfig } = configuration;
3
3
  const { githubSetup, repositoryIdentity } = createProjectCore;
4
4
  function api(endpoint, missingAllowed = false) {
@@ -25,24 +25,28 @@ export default ({ configuration, createProjectCore, external: { buffer: Buffer,
25
25
  if (typeof metadata?.default_branch !== 'string' || !metadata.default_branch) {
26
26
  throw new Error(`GitHub did not return a default branch for ${slug}.`);
27
27
  }
28
- const endpoint = `repos/${slug}/contents/peacekeeper.config.json?ref=${encodeURIComponent(metadata.default_branch)}`;
28
+ const endpoint = `repos/${slug}/contents/peacekeeper.config.yaml?ref=${encodeURIComponent(metadata.default_branch)}`;
29
29
  const file = api(endpoint, true);
30
30
  let config;
31
31
  if (file === undefined) {
32
+ const legacyEndpoint = `repos/${slug}/contents/peacekeeper.config.json?ref=${encodeURIComponent(metadata.default_branch)}`;
33
+ if (api(legacyEndpoint, true) !== undefined) {
34
+ throw new Error(`${slug}/peacekeeper.config.json: rename this legacy JSON configuration to peacekeeper.config.yaml and convert it to YAML.`);
35
+ }
32
36
  config = structuredClone(projectConfigDefaults);
33
37
  }
34
38
  else {
35
39
  if (file.type !== 'file' || file.encoding !== 'base64' || typeof file.content !== 'string') {
36
- throw new Error(`${slug}/peacekeeper.config.json: GitHub returned invalid file contents.`);
40
+ throw new Error(`${slug}/peacekeeper.config.yaml: GitHub returned invalid file contents.`);
37
41
  }
38
42
  try {
39
- config = JSON.parse(Buffer.from(file.content, 'base64').toString('utf8'));
43
+ config = YAML.parse(Buffer.from(file.content, 'base64').toString('utf8'));
40
44
  }
41
45
  catch (error) {
42
- throw new Error(`${slug}/peacekeeper.config.json: ${error instanceof Error ? error.message : String(error)}`);
46
+ throw new Error(`${slug}/peacekeeper.config.yaml: ${error instanceof Error ? error.message : String(error)}`);
43
47
  }
44
48
  }
45
- validateConfig(config, `${slug}/peacekeeper.config.json`);
49
+ validateConfig(config, `${slug}/peacekeeper.config.yaml`);
46
50
  return { ...identity, requiredChecks: config.git.releaseRequiredChecks,
47
51
  requiredApprover: config.git.requiredApprover || identity.owner,
48
52
  defaultBranch: metadata.default_branch };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jakobm/peacekeeper",
3
- "version": "0.22.0",
3
+ "version": "0.24.0",
4
4
  "description": "Shared repository test, Git worktree, and Codex hook commands",
5
5
  "license": "MIT",
6
6
  "author": "Jakob Mattsson",
@@ -31,6 +31,7 @@
31
31
  "test": "npm run build && node dist/bin/peacekeeper.js run-tests",
32
32
  "prepare": "npm run build",
33
33
  "architecture": "npm run build && portico architecture --modules dist/src/modules --output architecture",
34
+ "prerelease": "npm ci",
34
35
  "release": "node dist/bin/peacekeeper.js release",
35
36
  "cleanup:branches": "node dist/bin/peacekeeper.js cleanup-merged-branches",
36
37
  "cleanup:empty-directories": "node dist/bin/peacekeeper.js remove-empty-directories"
@@ -40,7 +41,7 @@
40
41
  },
41
42
  "dependencies": {
42
43
  "@iarna/toml": "^2.2.5",
43
- "@jakobm/cmdabra": "^0.2.1",
44
+ "@jakobm/cmdabra": "^0.6.0",
44
45
  "@jakobm/portico": "^0.7.0",
45
46
  "semver": "^7.8.5",
46
47
  "yaml": "^2.9.1"