@jakobm/peacekeeper 0.17.0 → 0.19.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
@@ -6,6 +6,50 @@ The public npm package is `@jakobm/peacekeeper`; its CLI command is `peacekeeper
6
6
  Install it with `npm install --save-exact @jakobm/peacekeeper@<version>`, selecting
7
7
  a published version. Replace the example dependency pin below with that version.
8
8
 
9
+ ## Create a compliant TypeScript project
10
+
11
+ `create-project` creates a minimal ESM TypeScript library in an existing, completely
12
+ empty GitHub repository. The command version owns the generated project contract,
13
+ all tool pins, and the exact `@jakobm/peacekeeper` development dependency. This
14
+ command additionally requires Volta so generation and verification use those pins.
15
+
16
+ ```sh
17
+ peacekeeper create-project \
18
+ --repository https://github.com/OWNER/REPOSITORY.git \
19
+ --directory /absolute/path/to/REPOSITORY \
20
+ --package-name @scope/REPOSITORY \
21
+ --author-name "Example Author" \
22
+ --author-email author@example.com \
23
+ --publish-to-npm true
24
+ ```
25
+
26
+ All arguments are mandatory. Only `https://github.com/OWNER/REPOSITORY[.git]`
27
+ URLs are accepted. The package basename must equal the repository name. Published
28
+ packages must be scoped; private packages must be unscoped and use
29
+ `--publish-to-npm false`.
30
+
31
+ Before creating the destination, the command verifies that it does not exist and
32
+ that the remote has no Git refs. It then installs dependencies, builds, typechecks,
33
+ runs the complete Peacekeeper test and project checks, and (for published packages)
34
+ tests the packed package from a temporary consumer. Only after every local check
35
+ passes does it create one initial commit on `main` and push without force.
36
+
37
+ An argument or preflight failure creates nothing. A later failure leaves the local
38
+ directory for inspection but does not commit or push. A push failure leaves the
39
+ verified local commit. Inspect or remove the directory before retrying.
40
+
41
+ The generated executable `setup-github-config.sh` is deliberately not run by the
42
+ generator. Run it afterwards and complete the manual checklist at its top. It
43
+ configures applicable GitHub policy through `gh`, including automatic head-branch
44
+ deletion, repository-level **Allow auto-merge**, and merge commits as the only
45
+ permitted pull-request merge method, and uses
46
+ `groundskeeper secrets sync --new-repo` to add the repository when synchronizing
47
+ `RELEASE_POLICY_TOKEN`. Published projects also document the required initial manual
48
+ publication with `npm login` and `npm publish`, followed by npm trusted publishing
49
+ setup. The authenticated `gh` token needs repository **Administration: write**
50
+ permission to configure repository settings and branch protection. The generator
51
+ never registers a publisher or publishes a package.
52
+
9
53
  When moving an existing project to Peacekeeper, update its dependency and lockfile,
10
54
  package scripts, and configuration filename together. Replace previous lifecycle
11
55
  hook commands with the definitions below before running `peacekeeper install-hooks`.
@@ -91,7 +135,7 @@ Complete example:
91
135
  }
92
136
  ```
93
137
 
94
- `git.remote` and `git.defaultBranch` identify the branch used for checkpointing and cleanup. `git.branchPrefix` names new task branches. `run-tests` always runs the local `check-project` validation first, even when reusing a test receipt. Explicit `check-project` invocations in `tests.commands` are rejected as redundant. The configured commands are complete shell commands, run in order from the caller's Git root; install any executables they use. The test runner stops on the first failure and records a receipt only after every command succeeds. `receiptMaxAgeMinutes` controls how long a receipt can be reused. Set `npmTestUsesRunner` to `true` only when the caller's `npm test` script invokes `peacekeeper run-tests`; this makes the rerun hint `npm test -- rerun`. Otherwise the hint uses the explicit package path. `loggingDirectory` stores hook invocation logs relative to the primary Git worktree's root.
138
+ `git.remote` and `git.defaultBranch` identify the branch used for checkpointing and cleanup. `git.branchPrefix` names new task branches. `run-tests` always runs the local `check-project` validation first, even when reusing a test receipt. Explicit `check-project` invocations in `tests.commands` are rejected as redundant. The configured commands are complete shell commands, run in order from the caller's Git root; install any executables they use. The test runner stops on the first failure and records a receipt only after every command succeeds. `receiptMaxAgeMinutes` controls how long a receipt can be reused. Set `npmTestUsesRunner` to `true` only when the caller's `npm test` script invokes `peacekeeper run-tests`; this makes the rerun hint `npm test -- --force`. Otherwise the hint uses the explicit package path. `loggingDirectory` stores hook invocation logs relative to the primary Git worktree's root.
95
139
 
96
140
  `loggingEnabled` has the bundled default `true`; set it to `false` to disable invocation logs and the background cleanup worker's log file. Existing logs are kept. The setting is read from the primary checkout's configuration, including for linked worktrees. SessionStart and Stop logs include the process and event working directories, event type, primary-checkout classification, and hook response or error. Only selected event fields are logged, never the full incoming payload. These logs require the Peacekeeper script to start; a missing Node.js executable or package must be diagnosed in Codex's own logs.
97
141
 
@@ -109,7 +153,7 @@ To publish checkpoint branches automatically, set `git.checkpointPushRemotes` (f
109
153
  ```
110
154
 
111
155
  Each name must identify a Git remote configured in the calling repository. Checkpoints push to exactly those remotes, creating the task branch if
112
- needed. An empty list disables checkpoint pushes and is the bundled default.
156
+ needed. The bundled default is `["origin"]`; set an empty list to disable checkpoint pushes.
113
157
  The field must be present; there is no implicit push fallback. Pushes never use force. Only a push to `git.remote` sets the
114
158
  branch's upstream. If a push fails, earlier pushes are kept and the checkpoint
115
159
  records a failure; fix the cause and rerun the checkpoint command to retry without
@@ -216,7 +260,7 @@ them. The shared policy then follows the installed package version.
216
260
 
217
261
  ## Check the setup
218
262
 
219
- From the caller's Git worktree, run `npm test` for the configured commands, `npm test -- rerun` to bypass a reusable receipt, `npm run cleanup:branches` to preview merged branch cleanup, and `npm run cleanup:empty-directories` to preview removal of empty directories and directories containing only ignored files. The latter command protects the root `.git`, `node_modules`, and `tmp` directories; other selected directories are removed recursively, including their ignored contents. Add `-- --execute` to either cleanup package script to apply it. Run `npm exec --no -- peacekeeper --help` for the complete command list. To create a manual checkpoint, use `npm exec --no -- peacekeeper checkpoint-codex-changes --subject "<subject>" --body "<body paragraph>"`.
263
+ From the caller's Git worktree, run `npm test` for the configured commands, `npm test -- --force` to bypass a reusable receipt, `npm run cleanup:branches` to preview merged branch cleanup, and `npm run cleanup:empty-directories` to preview removal of empty directories and directories containing only ignored files. The latter command protects the root `.git`, `node_modules`, and `tmp` directories; other selected directories are removed recursively, including their ignored contents. Add `-- --execute` to either cleanup package script to apply it. Run `npm exec --no -- peacekeeper --help` for the complete command list. To create a manual checkpoint, use `npm exec --no -- peacekeeper checkpoint-codex-changes --subject "<subject>" --body "<body paragraph>"`.
220
264
 
221
265
  Directory cleanup also preserves nested Git repositories and linked worktrees,
222
266
  including their parent directories when those parents are ignored. It does not
@@ -232,7 +276,7 @@ the root package's own bin, including the checkpoint command requested by the
232
276
  Stop hook. Install dependencies with `npm ci` to run the full test suite.
233
277
 
234
278
  Run `npm test` in this repository to verify the shared package itself, or
235
- `npm test -- rerun` to force a fresh run. Its configured test command runs Node's
279
+ `npm test -- --force` to force a fresh run. Its configured test command runs Node's
236
280
  test runner directly, avoiding recursion through `npm test`. The cleanup package
237
281
  scripts work the same way as in calling projects.
238
282
 
@@ -559,8 +603,9 @@ Explicit alternative job conditions are not supported. Workspaces are not suppor
559
603
 
560
604
  Configuration migration: previously optional fields must now be declared. Run
561
605
  `peacekeeper update-config`, review the inserted defaults, and commit the result.
562
- In particular, set `git.checkpointPushRemotes` explicitly to retain automatic
563
- pushes. Empty `git.releaseRequiredChecks` is valid configuration but blocks release
606
+ The default `git.checkpointPushRemotes` value publishes to `origin`; use an
607
+ explicit empty array to keep checkpoint branches local. Empty
608
+ `git.releaseRequiredChecks` is valid configuration but blocks release
564
609
  policy verification; empty `tests.commands` blocks test execution and receipts.
565
610
  `projectChecks` always explicitly selects the workflow and jobs. This change does
566
611
  not add online GitHub verification to `check-project`.
@@ -1,53 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  const { spawnSync } = require('node:child_process');
4
+ const fs = require('node:fs');
4
5
  const path = require('node:path');
5
6
 
6
- const COMMANDS = new Map([
7
- ['update-config', 'Create or complete project configuration using bundled defaults.'],
8
- ['check-project', 'Validate local toolchain, hooks, CI and publication conventions.'],
9
- ['install-hooks', 'Install or update project Codex hooks while preserving other hooks.'],
10
- ['verify-release', 'Verify release versions, required CI and strict branch protection.'],
11
- ['verify-release-protection', 'Require strict mandatory release checks without bypass.'],
12
- ['verify-release-version', 'Check a release tag against package and lockfile versions.'],
13
- ['release', 'Publish a version through a GitHub Actions npm workflow.'],
14
- ['assess-release', 'Assess unpublished changes with Codex and return a JSON recommendation.'],
15
- ['run-tests', 'Run configured tests, reusing a valid test receipt.'],
16
- ['check-test-receipt', 'Check whether a valid test receipt exists.'],
17
- ['record-test-receipt', 'Record a test receipt without running tests.'],
18
- ['checkpoint-codex-changes', 'Commit a linked worktree and push according to project configuration.'],
19
- ['checkpoint-codex-session-start', 'Load checkpoint instructions for a linked Codex worktree.'],
20
- ['checkpoint-codex-stop', 'Handle the Codex Stop hook and request a checkpoint if needed.'],
21
- ['cleanup-ended-session', 'Queue cleanup for a merged Codex session worktree.'],
22
- ['queue-merged-worktree-cleanup', 'Queue cleanup for the current merged worktree.'],
23
- ['cleanup-merged-branches', 'Preview or delete merged worktrees and branches.'],
24
- ['remove-empty-directories', 'Preview or remove directories containing only ignored files.'],
25
- ]);
7
+ const CONFIG_PATH = path.join(__dirname, 'peacekeeper.yaml');
26
8
 
27
- function helpText() {
28
- const width = Math.max(...[...COMMANDS.keys()].map((command) => command.length));
29
- const commands = [...COMMANDS]
30
- .map(([command, description]) => ` ${command.padEnd(width)} ${description}`)
31
- .join('\n');
32
- return `Usage: peacekeeper <command> [arguments]\n\nCommands:\n${commands}\n\nOptions:\n -h, --help Show this help.\n`;
33
- }
34
-
35
- function main() {
36
- const [command, ...args] = process.argv.slice(2);
37
- if (command === '--help' || command === '-h') {
38
- process.stdout.write(helpText());
39
- return;
40
- }
41
- if (!COMMANDS.has(command)) {
42
- const detail = command ? `Unknown command: ${command}` : 'A command is required.';
43
- process.stderr.write(`${detail}\n\n${helpText()}`);
44
- process.exitCode = 2;
45
- return;
46
- }
47
- const informational = (args.length === 1 && ['--help', '-h'].includes(args[0]))
48
- || (command === 'check-project' && args.length === 1 && args[0] === '--explain');
49
- const checkpointHook = ['checkpoint-codex-session-start', 'checkpoint-codex-stop'].includes(command);
50
- if (!['update-config', 'assess-release'].includes(command) && !checkpointHook && !informational) require('../scripts/project-config').projectConfig();
9
+ function runScript(command, args) {
51
10
  const script = path.resolve(__dirname, '..', 'scripts', `${command}.js`);
52
11
  const result = spawnSync(process.execPath, [script, ...args], {
53
12
  cwd: process.cwd(),
@@ -57,9 +16,53 @@ function main() {
57
16
  process.exitCode = result.status ?? 1;
58
17
  }
59
18
 
60
- try {
61
- main();
62
- } catch (error) {
19
+ async function main() {
20
+ const rawArgs = process.argv.slice(2);
21
+ const [command, ...args] = rawArgs;
22
+ const script = path.resolve(__dirname, '..', 'scripts', `${command}.js`);
23
+ const informational = args.length === 1 && (
24
+ ['--help', '-h'].includes(args[0])
25
+ || (command === 'check-project' && args[0] === '--explain')
26
+ );
27
+ const checkpointHook = ['checkpoint-codex-session-start', 'checkpoint-codex-stop'].includes(command);
28
+ if (
29
+ fs.existsSync(script)
30
+ && !['update-config', 'assess-release', 'create-project'].includes(command)
31
+ && !checkpointHook
32
+ && !informational
33
+ ) require('../scripts/project-config').projectConfig();
34
+
35
+ // assess-release guarantees machine-readable JSON even for invalid arguments.
36
+ // Preserve that application-level error contract instead of letting the CLI parser format it.
37
+ if (command === 'assess-release' && args.length > 0) {
38
+ runScript(command, args);
39
+ return;
40
+ }
41
+ const dependencyFreeHooks = new Set([
42
+ 'checkpoint-codex-session-start',
43
+ 'checkpoint-codex-stop',
44
+ 'checkpoint-codex-changes',
45
+ 'cleanup-ended-session',
46
+ ]);
47
+ if (dependencyFreeHooks.has(command) && !informational) {
48
+ runScript(command, args);
49
+ return;
50
+ }
51
+
52
+ const { runCli } = await import('@jakobm/cmdabra');
53
+ const implementation = new Proxy({}, {
54
+ get: (_target, name) => () => runScript(name, args),
55
+ });
56
+ await runCli(CONFIG_PATH, implementation, rawArgs);
57
+ }
58
+
59
+ main().catch(async (error) => {
60
+ const { CmdabraUsageError } = await import('@jakobm/cmdabra');
61
+ if (error instanceof CmdabraUsageError) {
62
+ process.stderr.write(`${error.message}\n\n${error.help}`);
63
+ process.exitCode = error.exitCode;
64
+ return;
65
+ }
63
66
  console.error(`Error: ${error.message}`);
64
67
  process.exitCode = 1;
65
- }
68
+ });
@@ -0,0 +1,101 @@
1
+ name: peacekeeper
2
+ description: Shared repository test, Git worktree, and Codex hook commands
3
+ commands:
4
+ update-config:
5
+ description: Create or complete project configuration using bundled defaults.
6
+ create-project:
7
+ description: Create and verify a compliant TypeScript library in an empty GitHub repository.
8
+ named-options:
9
+ repository:
10
+ description: GitHub HTTPS repository URL.
11
+ required: true
12
+ directory:
13
+ description: Directory in which to create the project.
14
+ required: true
15
+ package-name:
16
+ description: npm package name.
17
+ required: true
18
+ author-name:
19
+ description: Package author name.
20
+ required: true
21
+ author-email:
22
+ description: Package author email address.
23
+ required: true
24
+ publish-to-npm:
25
+ description: Whether the package will be published to npm.
26
+ type: enum
27
+ choices: ["true", "false"]
28
+ required: true
29
+ check-project:
30
+ description: Validate local toolchain, hooks, CI and publication conventions.
31
+ named-options:
32
+ explain:
33
+ description: Print the complete expected project architecture.
34
+ type: boolean
35
+ install-hooks:
36
+ description: Install or update project Codex hooks while preserving other hooks.
37
+ named-options:
38
+ dry-run:
39
+ description: Preview changes without writing hooks.
40
+ type: boolean
41
+ verify-release:
42
+ description: Verify release versions, required CI and strict branch protection.
43
+ verify-release-protection:
44
+ description: Require strict mandatory release checks without bypass.
45
+ verify-release-version:
46
+ description: Check a release tag against package and lockfile versions.
47
+ release:
48
+ description: Publish a version through a GitHub Actions npm workflow.
49
+ positional-arguments:
50
+ bump:
51
+ description: Version increment to publish.
52
+ type: enum
53
+ choices: [major, minor, patch]
54
+ assess-release:
55
+ description: Assess unpublished changes with Codex and return a JSON recommendation.
56
+ run-tests:
57
+ description: Run configured tests, reusing a valid test receipt.
58
+ named-options:
59
+ force:
60
+ description: Run tests even when a valid receipt exists.
61
+ type: boolean
62
+ check-test-receipt:
63
+ description: Check whether a valid test receipt exists.
64
+ record-test-receipt:
65
+ description: Record a test receipt without running tests.
66
+ checkpoint-codex-changes:
67
+ description: Commit a linked worktree and push according to project configuration.
68
+ named-options:
69
+ subject:
70
+ description: Commit subject.
71
+ required: true
72
+ body:
73
+ description: Commit body paragraph; may be repeated.
74
+ required: true
75
+ repeatable: true
76
+ checkpoint-codex-session-start:
77
+ description: Load checkpoint instructions for a linked Codex worktree.
78
+ checkpoint-codex-stop:
79
+ description: Handle the Codex Stop hook and request a checkpoint if needed.
80
+ cleanup-ended-session:
81
+ description: Queue cleanup for a merged Codex session worktree.
82
+ queue-merged-worktree-cleanup:
83
+ description: Queue cleanup for the current merged worktree.
84
+ cleanup-merged-branches:
85
+ description: Preview or delete merged worktrees and branches.
86
+ named-options:
87
+ dry-run:
88
+ description: Preview cleanup without deleting anything.
89
+ type: boolean
90
+ execute:
91
+ description: Delete the displayed worktrees and branches.
92
+ type: boolean
93
+ remove-empty-directories:
94
+ description: Preview or remove directories containing only ignored files.
95
+ named-options:
96
+ dry-run:
97
+ description: Preview cleanup without deleting anything.
98
+ type: boolean
99
+ execute:
100
+ description: Remove the displayed directories.
101
+ type: boolean
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jakobm/peacekeeper",
3
- "version": "0.17.0",
3
+ "version": "0.19.0",
4
4
  "description": "Shared repository test, Git worktree, and Codex hook commands",
5
5
  "license": "MIT",
6
6
  "author": "Jakob Mattsson",
@@ -30,6 +30,7 @@
30
30
  },
31
31
  "dependencies": {
32
32
  "@iarna/toml": "^2.2.5",
33
+ "@jakobm/cmdabra": "^0.2.1",
33
34
  "semver": "^7.8.5",
34
35
  "yaml": "^2.9.1"
35
36
  },
@@ -5,8 +5,8 @@ const { ROOT, environmentFingerprint, receiptPath, snapshot } = require('./recei
5
5
  const { projectConfig, requireTestCommands } = require('./project-config');
6
6
  function successMessage(root = ROOT()) {
7
7
  const command = projectConfig(root).tests.npmTestUsesRunner
8
- ? 'npm test -- rerun'
9
- : 'node node_modules/@jakobm/peacekeeper/bin/peacekeeper.js run-tests rerun';
8
+ ? 'npm test -- --force'
9
+ : 'node node_modules/@jakobm/peacekeeper/bin/peacekeeper.js run-tests --force';
10
10
  return `Tests already passed for this change set. In order to rerun tests anyway, use: ${command}`;
11
11
  }
12
12
 
@@ -0,0 +1,195 @@
1
+ 'use strict';
2
+
3
+ const { spawnSync } = require('node:child_process');
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+ const { planHooks } = require('./install-hooks');
7
+
8
+ const TOOLCHAIN = Object.freeze({
9
+ node: '22.14.0',
10
+ npm: '11.21.0',
11
+ typescript: '5.9.3',
12
+ nodeTypes: '24.10.0',
13
+ });
14
+
15
+ class UsageError extends Error {}
16
+
17
+ function usage() {
18
+ return 'Usage: peacekeeper create-project --repository <https://github.com/owner/repo.git> --directory <path> --package-name <name> --author-name <name> --author-email <email> --publish-to-npm <true|false>\n';
19
+ }
20
+
21
+ function repositoryIdentity(repository) {
22
+ let url;
23
+ try { url = new URL(repository); } catch { throw new UsageError('--repository must be a valid GitHub HTTPS URL'); }
24
+ if (url.protocol !== 'https:' || url.hostname !== 'github.com' || url.username || url.password || url.port || url.search || url.hash) {
25
+ throw new UsageError('--repository must use https://github.com/owner/repo.git');
26
+ }
27
+ const match = /^\/([^/]+)\/([^/]+?)(?:\.git)?$/u.exec(url.pathname);
28
+ if (!match || !match[1] || !match[2] || match[1] === '.' || match[2] === '.') {
29
+ throw new UsageError('--repository must use https://github.com/owner/repo.git');
30
+ }
31
+ return { owner: match[1], repositoryName: match[2] };
32
+ }
33
+
34
+ function parseArguments(args) {
35
+ const names = ['repository', 'directory', 'package-name', 'author-name', 'author-email', 'publish-to-npm'];
36
+ const values = {};
37
+ for (let index = 0; index < args.length; index += 2) {
38
+ const flag = args[index];
39
+ const name = flag?.startsWith('--') ? flag.slice(2) : '';
40
+ if (!names.includes(name)) throw new UsageError(`Unknown argument: ${flag || '(missing)'}`);
41
+ if (Object.hasOwn(values, name)) throw new UsageError(`Duplicate argument: --${name}`);
42
+ if (index + 1 >= args.length || args[index + 1].startsWith('--')) throw new UsageError(`Missing value for --${name}`);
43
+ values[name] = args[index + 1];
44
+ }
45
+ const missing = names.filter(name => !Object.hasOwn(values, name));
46
+ if (missing.length) throw new UsageError(`Missing required argument${missing.length === 1 ? '' : 's'}: ${missing.map(name => `--${name}`).join(', ')}`);
47
+ const identity = repositoryIdentity(values.repository);
48
+ if (!values.directory.trim()) throw new UsageError('--directory must be nonempty');
49
+ if (!values['author-name'].trim()) throw new UsageError('--author-name must be nonempty');
50
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(values['author-email'])) throw new UsageError('--author-email must be a valid email address');
51
+ if (!['true', 'false'].includes(values['publish-to-npm'])) throw new UsageError('--publish-to-npm must be true or false');
52
+ const packageName = values['package-name'];
53
+ if (packageName.length > 214 || !/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u.test(packageName)) {
54
+ throw new UsageError('--package-name must be a valid lowercase npm package name');
55
+ }
56
+ const published = values['publish-to-npm'] === 'true';
57
+ const scoped = packageName.startsWith('@');
58
+ if (published !== scoped) throw new UsageError(`--package-name must be ${published ? 'scoped' : 'unscoped'} when --publish-to-npm is ${published}`);
59
+ if (packageName.split('/').at(-1) !== identity.repositoryName) throw new UsageError('The package basename must exactly match the repository name');
60
+ return { repository: values.repository, directory: values.directory, packageName,
61
+ authorName: values['author-name'], authorEmail: values['author-email'], published, ...identity };
62
+ }
63
+
64
+ function commandRunner(command, args, options = {}) {
65
+ const result = spawnSync(command, args, { encoding: 'utf8', stdio: options.capture ? 'pipe' : 'inherit', ...options });
66
+ if (result.error) throw result.error;
67
+ if (result.status !== 0) {
68
+ const detail = options.capture ? (result.stderr || result.stdout || '').trim() : '';
69
+ throw new Error(`${command} ${args.join(' ')} failed${detail ? `: ${detail}` : ` with exit ${result.status}`}`);
70
+ }
71
+ return result.stdout || '';
72
+ }
73
+
74
+ function json(value) { return `${JSON.stringify(value, null, 2)}\n`; }
75
+ function write(root, name, contents, mode = 0o644) {
76
+ const target = path.join(root, name);
77
+ fs.mkdirSync(path.dirname(target), { recursive: true });
78
+ fs.writeFileSync(target, contents, { mode });
79
+ }
80
+
81
+ function workflow(published) {
82
+ return `name: Test\n\non:\n pull_request:\n branches: [main]\n\npermissions:\n contents: read\n\njobs:\n test:\n runs-on: ubuntu-24.04\n steps:\n - uses: actions/checkout@v7\n - uses: volta-cli/action@v5\n - run: npm ci\n - name: Verify strict release policy\n env:\n GH_TOKEN: \${{ secrets.RELEASE_POLICY_TOKEN }}\n run: npm exec --no -- peacekeeper verify-release-protection\n - run: npm test\n${published ? `\n package:\n name: Test package\n runs-on: ubuntu-24.04\n steps:\n - uses: actions/checkout@v7\n - uses: volta-cli/action@v5\n - run: npm ci\n - run: npm run test:package\n` : ''}`;
83
+ }
84
+
85
+ function publishWorkflow() {
86
+ return `name: Publish\n\non:\n push:\n tags: ['v*']\n\npermissions:\n contents: read\n\njobs:\n publish:\n name: Publish to npm\n runs-on: ubuntu-24.04\n permissions:\n contents: read\n actions: read\n pull-requests: read\n id-token: write\n steps:\n - uses: actions/checkout@v7\n - uses: volta-cli/action@v5\n with:\n registry-url: https://registry.npmjs.org\n - run: npm ci\n - name: Verify release\n env:\n GH_TOKEN: \${{ secrets.RELEASE_POLICY_TOKEN }}\n RELEASE_TAG: \${{ github.ref_name }}\n run: npm exec --no -- peacekeeper verify-release\n - run: npm publish\n`;
87
+ }
88
+
89
+ function githubSetup({ owner, repositoryName, published }) {
90
+ const npm = published ? `# - Publish the package manually once from this directory before configuring npm trusted publishing:
91
+ # npm login
92
+ # npm publish
93
+ # - Configure npm trusted publishing for GitHub repository ${owner}/${repositoryName} and workflow publish.yml.
94
+ ` : '';
95
+ return `#!/usr/bin/env bash
96
+ # Manual checklist:
97
+ # - Run this script yourself after the initial project has been pushed.
98
+ # - Authenticate gh with Administration: write access to this repository.
99
+ ${npm}set -euo pipefail
100
+
101
+ repo=${owner}/${repositoryName}
102
+ gh auth status
103
+ gh repo view "$repo" >/dev/null
104
+ gh api --method PATCH "repos/$repo" \\
105
+ -F delete_branch_on_merge=true \\
106
+ -F allow_auto_merge=true \\
107
+ -F allow_merge_commit=true \\
108
+ -F allow_squash_merge=false \\
109
+ -F allow_rebase_merge=false >/dev/null
110
+ gh api --method PUT "repos/$repo/branches/main/protection" \\
111
+ -F 'required_status_checks[strict]=true' \\
112
+ -f 'required_status_checks[contexts][]=test' \\
113
+ -F enforce_admins=true \\
114
+ -F 'required_pull_request_reviews[required_approving_review_count]=0' \\
115
+ -F restrictions=null >/dev/null
116
+ groundskeeper secrets sync --name RELEASE_POLICY_TOKEN --new-repo "$repo"
117
+ printf 'GitHub configuration completed for %s.\\n' "$repo"
118
+ `;
119
+ }
120
+
121
+ function packageTest() {
122
+ return `'use strict';\nconst assert = require('node:assert/strict');\nconst { execFileSync } = require('node:child_process');\nconst fs = require('node:fs');\nconst os = require('node:os');\nconst path = require('node:path');\nconst root = path.resolve(__dirname, '..');\nconst output = JSON.parse(execFileSync('npm', ['pack', '--json'], { cwd: root, encoding: 'utf8' }));\nconst tarball = path.join(root, output[0].filename);\nconst consumer = fs.mkdtempSync(path.join(os.tmpdir(), 'package-consumer-'));\ntry {\n fs.writeFileSync(path.join(consumer, 'package.json'), '{"type":"module"}\\n');\n execFileSync('npm', ['install', '--ignore-scripts', tarball], { cwd: consumer, stdio: 'inherit' });\n const value = execFileSync(process.execPath, ['--input-type=module', '--eval', "import { hello } from '\${PACKAGE_NAME}'; process.stdout.write(hello())"], { cwd: consumer, encoding: 'utf8' });\n assert.equal(value, 'hello world');\n} finally {\n fs.rmSync(consumer, { recursive: true, force: true });\n fs.rmSync(tarball, { force: true });\n}\n`;
123
+ }
124
+
125
+ function generate(root, options) {
126
+ const version = require('../package.json').version;
127
+ const manifest = {
128
+ name: options.packageName, version: '0.1.0', description: `${options.repositoryName} TypeScript library`,
129
+ type: 'module', ...(options.published ? {} : { private: true }),
130
+ author: { name: options.authorName, email: options.authorEmail },
131
+ repository: { type: 'git', url: `git+${options.repository}` }, license: 'MIT',
132
+ engines: { node: '>=20' }, volta: { node: TOOLCHAIN.node, npm: TOOLCHAIN.npm },
133
+ main: './dist/index.js', types: './dist/index.d.ts', exports: { '.': { types: './dist/index.d.ts', import: './dist/index.js' } },
134
+ scripts: { build: 'tsc -p tsconfig.json', typecheck: 'tsc -p tsconfig.json --noEmit', test: 'peacekeeper run-tests', 'test:unit': 'node --test test/*.test.js',
135
+ ...(options.published ? { 'test:package': 'node scripts/test-package.cjs', release: 'peacekeeper release' } : {}) },
136
+ devDependencies: { '@jakobm/peacekeeper': version, '@types/node': TOOLCHAIN.nodeTypes, typescript: TOOLCHAIN.typescript },
137
+ ...(options.published ? { files: ['dist/'], publishConfig: { access: 'public', registry: 'https://registry.npmjs.org/' } } : {}),
138
+ };
139
+ write(root, 'package.json', json(manifest));
140
+ write(root, 'tsconfig.json', json({ compilerOptions: { target: 'ES2022', module: 'NodeNext', moduleResolution: 'NodeNext', rootDir: 'src', outDir: 'dist', declaration: true, strict: true, noUncheckedIndexedAccess: true }, include: ['src/**/*.ts'] }));
141
+ write(root, 'src/index.ts', "export function hello(): string {\n return 'hello world';\n}\n");
142
+ write(root, 'test/index.test.js', `import assert from 'node:assert/strict';\nimport test from 'node:test';\nimport { hello } from '../dist/index.js';\ntest('public hello API', () => assert.equal(hello(), 'hello world'));\n`);
143
+ if (options.published) write(root, 'scripts/test-package.cjs', packageTest().replace('${PACKAGE_NAME}', options.packageName));
144
+ const defaults = structuredClone(require('./project-config-defaults.json'));
145
+ defaults.publishesToNpm = options.published;
146
+ defaults.tests.commands = ['npm run typecheck', 'npm run build', 'npm run test:unit', ...(options.published ? ['npm run test:package'] : [])];
147
+ defaults.tests.npmTestUsesRunner = true;
148
+ write(root, 'peacekeeper.config.json', json(defaults));
149
+ write(root, '.codex/hooks.json', json(planHooks({}).document));
150
+ const prefix = fs.readFileSync(path.join(__dirname, 'codex-setup-prefix.sh'), 'utf8');
151
+ write(root, '.codex/environments/environment.toml', `version = 1\nname = ${JSON.stringify(options.repositoryName)}\n\n[setup]\nscript = '''\n${prefix}'''\n`);
152
+ write(root, '.github/workflows/test.yml', workflow(options.published));
153
+ if (options.published) write(root, '.github/workflows/publish.yml', publishWorkflow());
154
+ write(root, '.gitignore', 'node_modules/\n*.tgz\ntmp/\n');
155
+ write(root, 'README.md', `# ${options.repositoryName}\n\nA TypeScript library generated by Peacekeeper.\n\n## API\n\n\`hello()\` returns \`"hello world"\`.\n`);
156
+ write(root, 'LICENSE', `MIT License\n\nCopyright (c) ${options.authorName}\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n`);
157
+ write(root, 'setup-github-config.sh', githubSetup(options), 0o755);
158
+ }
159
+
160
+ function createProject(options, dependencies = {}) {
161
+ const run = dependencies.run || commandRunner;
162
+ const voltaHome = process.env.VOLTA_HOME;
163
+ const volta = voltaHome && fs.existsSync(path.join(voltaHome, 'bin', 'volta'))
164
+ ? path.join(voltaHome, 'bin', 'volta') : 'volta';
165
+ const npm = args => run(volta, ['run', '--node', TOOLCHAIN.node, '--npm', TOOLCHAIN.npm, 'npm', ...args], { cwd: normalized });
166
+ const target = path.resolve(options.directory);
167
+ if (fs.existsSync(target)) throw new Error(`Destination already exists: ${target}`);
168
+ const parent = path.dirname(target);
169
+ let realParent;
170
+ try { realParent = fs.realpathSync(parent); } catch { throw new Error(`Destination parent does not exist: ${parent}`); }
171
+ const normalized = path.join(realParent, path.basename(target));
172
+ if (fs.existsSync(normalized)) throw new Error(`Destination already exists after path normalization: ${normalized}`);
173
+ const refs = run('git', ['ls-remote', options.repository], { capture: true }).trim();
174
+ if (refs) throw new Error('The repository is not empty; refusing to create a project');
175
+ fs.mkdirSync(normalized);
176
+ try {
177
+ run('git', ['init', '--initial-branch=main'], { cwd: normalized });
178
+ run('git', ['remote', 'add', 'origin', options.repository], { cwd: normalized });
179
+ generate(normalized, options);
180
+ npm(['install', '--ignore-scripts']);
181
+ npm(['run', 'build']);
182
+ npm(['run', 'typecheck']);
183
+ npm(['test']);
184
+ run('bash', ['-n', 'setup-github-config.sh'], { cwd: normalized });
185
+ if (run('git', ['ls-remote', options.repository], { capture: true }).trim()) throw new Error('The repository gained refs while the project was being created');
186
+ run('git', ['add', '--all'], { cwd: normalized });
187
+ run('git', ['-c', `user.name=${options.authorName}`, '-c', `user.email=${options.authorEmail}`, 'commit', '-m', 'Initial project'], { cwd: normalized });
188
+ run('git', ['push', '--set-upstream', 'origin', 'main:main'], { cwd: normalized });
189
+ } catch (error) {
190
+ throw new Error(`${error.message}. Inspect or remove ${normalized} before retrying.`);
191
+ }
192
+ return { directory: normalized, packageName: options.packageName };
193
+ }
194
+
195
+ module.exports = { TOOLCHAIN, UsageError, createProject, generate, parseArguments, repositoryIdentity, usage };
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const { createProject, parseArguments, usage, UsageError } = require('./create-project-core');
5
+
6
+ async function main() {
7
+ const args = process.argv.slice(2);
8
+ if (args.length === 1 && ['--help', '-h'].includes(args[0])) {
9
+ process.stdout.write(usage());
10
+ return;
11
+ }
12
+ const options = parseArguments(args);
13
+ const result = createProject(options);
14
+ process.stdout.write(`Created ${result.packageName} at ${result.directory}\n`);
15
+ process.stdout.write(`Next: run ${result.directory}/setup-github-config.sh and complete its manual checklist.\n`);
16
+ }
17
+
18
+ main().catch(error => {
19
+ if (error instanceof UsageError) {
20
+ process.stderr.write(`${error.message}\n\n${usage()}`);
21
+ process.exitCode = 2;
22
+ } else {
23
+ process.stderr.write(`Error: ${error.message}\n`);
24
+ process.exitCode = 1;
25
+ }
26
+ });
@@ -3,7 +3,9 @@
3
3
  "remote": "origin",
4
4
  "defaultBranch": "main",
5
5
  "branchPrefix": "codex/",
6
- "checkpointPushRemotes": [],
6
+ "checkpointPushRemotes": [
7
+ "origin"
8
+ ],
7
9
  "releaseMergeMethod": "merge",
8
10
  "releaseRequiredChecks": [
9
11
  "test"
@@ -7,9 +7,11 @@ const { repositoryRoot } = require('./project-config');
7
7
 
8
8
  const ROOT = repositoryRoot;
9
9
  const RECEIPT_DIRECTORY = 'peacekeeper-test-receipts';
10
+ const EMPTY_TREE = '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
10
11
 
11
12
  function git(root, args) {
12
- return execFileSync('git', args, { cwd: root, maxBuffer: 10 * 1024 * 1024 });
13
+ return execFileSync('git', args, { cwd: root, maxBuffer: 10 * 1024 * 1024,
14
+ stdio: ['ignore', 'pipe', 'pipe'] });
13
15
  }
14
16
 
15
17
  function pathsFromOutput(output) {
@@ -64,7 +66,15 @@ function environmentFingerprint() {
64
66
  });
65
67
  }
66
68
 
67
- function snapshot(root = ROOT(), baseCommit = git(root, ['rev-parse', 'HEAD']).toString('utf8').trim()) {
69
+ function currentBase(root) {
70
+ try { return git(root, ['rev-parse', '--verify', 'HEAD']).toString('utf8').trim(); }
71
+ catch (error) {
72
+ if (error.status === 128) return EMPTY_TREE;
73
+ throw error;
74
+ }
75
+ }
76
+
77
+ function snapshot(root = ROOT(), baseCommit = currentBase(root)) {
68
78
  return {
69
79
  baseCommit,
70
80
  environment: environmentFingerprint(),
@@ -25,9 +25,9 @@ function hasReusableReceipt() {
25
25
  function main() {
26
26
  requireTestCommands();
27
27
  const config = projectConfig();
28
- const force = process.argv.length === 3 && ['rerun', '--force'].includes(process.argv[2]);
28
+ const force = process.argv.length === 3 && process.argv[2] === '--force';
29
29
  if (process.argv.length !== 2 && !force) {
30
- console.error('Usage: node scripts/run-tests.js [rerun|--force]');
30
+ console.error('Usage: node scripts/run-tests.js [--force]');
31
31
  process.exitCode = 2;
32
32
  return;
33
33
  }