@jakobm/peacekeeper 0.23.0 → 0.25.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
@@ -392,10 +393,38 @@ Add project-specific commands after `# Add custom project setup below`.
392
393
  Platform-specific `setup.linux.script`, `setup.macos.script`, and
393
394
  `setup.windows.script` overrides, when present, must start with the same prefix.
394
395
  The setup requires Bash and curl, activates or installs Volta, logs tool versions,
395
- and runs `npm ci` using the package.json pins. A passing check validates the
396
- parsed script text; it does not run setup or prove that a fresh environment works.
397
- Verify that separately in a new Codex worktree. Prefix changes in future
398
- 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` followed by
398
+ `peacekeeper cleanup-merged-branches --execute` before any project-specific setup,
399
+ initializing each new linked worktree from the exact commit fetched from the
400
+ configured remote default branch, safely synchronizing the primary checkout, and
401
+ removing merged branches and their linked worktrees.
402
+ A passing check validates the parsed script text; it does not run setup or prove
403
+ that a fresh environment works. Verify that separately in a new Codex worktree.
404
+ Prefix changes in future Peacekeeper versions require updating each project's
405
+ environment configuration.
406
+
407
+ The required sequence ends like this:
408
+
409
+ ```toml
410
+ [setup]
411
+ script = '''
412
+ # ...the required Peacekeeper setup prefix...
413
+ npm ci
414
+ npm exec --no -- peacekeeper initialize-codex-worktree --sync-primary
415
+ npm exec --no -- peacekeeper cleanup-merged-branches --execute
416
+ # Add custom project setup below
417
+ '''
418
+ ```
419
+
420
+ `--sync-primary` makes Peacekeeper also update a clean primary checkout when its
421
+ default branch can be fast-forwarded safely. A clean non-default branch there is
422
+ first synchronized
423
+ with the configured remote; divergent history is published under the next free
424
+ versioned name such as `feature-v2`. Dirty, detached, ahead, or divergent primary
425
+ checkouts are left untouched with an explicit skip message. The command records
426
+ completion in the linked worktree's private Git directory, retries interrupted
427
+ `npm ci` runs, and does not move an established worktree on later setup runs.
399
428
 
400
429
  ## Assess unpublished changes
401
430
 
@@ -621,6 +650,10 @@ squash or rebase must be restarted. `git.releaseMergeMethod` remains accepted fo
621
650
  configuration compatibility, but no longer selects the default-branch merge method.
622
651
 
623
652
  From a clean repository root, run `npm run release -- patch`, `minor`, or `major`.
653
+ The required `prerelease` script runs `npm ci` first, replacing `node_modules`
654
+ with the exact dependency versions in the committed lockfile before npm resolves
655
+ and starts Peacekeeper. Always use the npm script; invoking `peacekeeper release`
656
+ directly bypasses this dependency bootstrap.
624
657
  The command fetches the default branch and uses a temporary detached worktree to
625
658
  increment the package and lockfile versions. Your current branch and local default
626
659
  branch stay unchanged, including when the default branch is checked out elsewhere.
@@ -656,8 +689,9 @@ an altered release. Temporary worktrees are removed when the command exits
656
689
  normally or with a handled error; a killed process may leave a temporary worktree
657
690
  that needs manual cleanup.
658
691
 
659
- Other npm projects can use this command through a package script such as
660
- `"release": "peacekeeper release"`. The project must use a root package
692
+ Other npm projects can use this command through package scripts such as
693
+ `"prerelease": "npm ci"` and `"release": "peacekeeper release"`. npm runs the
694
+ former automatically before the latter. The project must use a root package
661
695
  with a stable version, a `peacekeeper.config.yaml` with
662
696
  `git.releaseRequiredChecks`, and the supported tag-triggered GitHub Actions
663
697
  publish job. Add `peacekeeper verify-release-protection` to a required PR
@@ -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.23.0",
3
+ "version": "0.25.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,90 +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 YAML from 'yaml';
6
- import projectConfigDefaults from './modules/configuration/project-config-defaults.json' with { type: 'json' };
7
- import createProjectConfig from './modules/configuration/project-config.js';
8
- import createLifecycle from './modules/lifecycle/interface.js';
9
- import createCheckpointChanges from './modules/lifecycle/checkpoint-codex-changes.js';
10
- import createCheckpointSessionStart from './modules/lifecycle/checkpoint-codex-session-start.js';
11
- import createCheckpointStop from './modules/lifecycle/checkpoint-codex-stop.js';
12
- import createCheckpointInstructions from './modules/lifecycle/checkpoint-instructions.js';
13
- import createCleanupEndedSession from './modules/lifecycle/cleanup-ended-session.js';
14
- import createLogScriptInvocation from './modules/lifecycle/log-script-invocation.js';
15
- import createQueueMergedWorktreeCleanup from './modules/lifecycle/queue-merged-worktree-cleanup.js';
16
- import createCleanupMergedBranches from './modules/maintenance/cleanup-merged-branches.js';
17
3
  const currentDirectory = path.dirname(fileURLToPath(import.meta.url));
18
- const clock = Object.freeze({
19
- date: () => new Date(),
20
- now: () => Date.now(),
21
- parse: (value) => Date.parse(value),
22
- sleep: (milliseconds) => new Promise(resolve => setTimeout(resolve, milliseconds)),
23
- sleepSync: (milliseconds) => {
24
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds);
25
- },
26
- timezone: () => Intl.DateTimeFormat().resolvedOptions().timeZone,
27
- });
28
- const output = console;
29
- function dependencyFreeLifecycleContainer() {
30
- const runtime = process;
31
- const projectConfig = createProjectConfig({
32
- external: { execFileSync, fs, path, projectConfigDefaults, runtime, YAML },
33
- });
34
- const configuration = Object.freeze({
35
- projectConfig: projectConfig.projectConfig,
36
- repositoryRoot: projectConfig.repositoryRoot,
37
- requireTestCommands: projectConfig.requireTestCommands,
38
- });
39
- const invocation = createLogScriptInvocation({
40
- configuration, external: { clock, fs, path, runtime, spawnSync },
41
- });
42
- const instructions = createCheckpointInstructions();
43
- const checkpointChanges = createCheckpointChanges({
44
- configuration, logScriptInvocation: invocation,
45
- external: { clock, fs, output, path, runtime, spawnSync },
46
- });
47
- const cleanupMergedBranches = createCleanupMergedBranches({
48
- configuration, external: { execFileSync, fs, output, path, runtime, spawnSync },
49
- });
50
- const maintenance = Object.freeze({
51
- applyPlan: cleanupMergedBranches.applyPlan,
52
- buildPlan: cleanupMergedBranches.buildPlan,
53
- listWorktrees: cleanupMergedBranches.listWorktrees,
54
- });
55
- const cleanupEndedSession = createCleanupEndedSession({
56
- configuration, logScriptInvocation: invocation, maintenance,
57
- external: {
58
- buffer: Buffer, clock, executablePath: path.resolve(currentDirectory, '../bin/peacekeeper.js'),
59
- fs, output, path, runtime, spawn, spawnSync,
60
- },
61
- });
62
- const lifecycle = Object.freeze(createLifecycle({
63
- checkpointCodexChanges: checkpointChanges,
64
- checkpointCodexSessionStart: createCheckpointSessionStart({
65
- checkpointInstructions: instructions, configuration, logScriptInvocation: invocation,
66
- }),
67
- checkpointCodexStop: createCheckpointStop({
68
- checkpointCodexChanges: checkpointChanges, checkpointInstructions: instructions,
69
- configuration, logScriptInvocation: invocation, external: { fs, spawnSync },
70
- }),
71
- cleanupEndedSession,
72
- queueMergedWorktreeCleanup: createQueueMergedWorktreeCleanup({
73
- cleanupEndedSession, logScriptInvocation: invocation, external: { output, runtime },
74
- }),
75
- }));
76
- return {
77
- resolve(name) {
78
- if (name !== 'lifecycle') {
79
- throw new Error(`Dependency-free container only provides lifecycle, not ${name}`);
80
- }
81
- return lifecycle;
82
- },
83
- };
84
- }
85
- export async function createContainer(dependencyFree = false) {
86
- if (dependencyFree)
87
- return dependencyFreeLifecycleContainer();
4
+ export async function createContainer() {
88
5
  const { default: portico } = await import('@jakobm/portico');
89
6
  return await portico.createRepositoryContainerAsync(path.resolve(currentDirectory, 'modules'));
90
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
  };
@@ -7,7 +7,7 @@ allowed-modules:
7
7
  releases: [configuration]
8
8
  testing: [configuration, projects]
9
9
  allowed-external:
10
- cli: [cliConfigPath, runCli]
10
+ cli: [cliConfigPath, runCli, runtime]
11
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]
@@ -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
  });
@@ -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.
@@ -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) => {
@@ -18,4 +18,8 @@ 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
+ npm exec --no -- peacekeeper cleanup-merged-branches --execute
24
+
21
25
  # Add custom project setup below
@@ -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
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jakobm/peacekeeper",
3
- "version": "0.23.0",
3
+ "version": "0.25.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"