@jakobm/peacekeeper 0.20.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +54 -16
  2. package/dist/bin/peacekeeper.js +36 -0
  3. package/{bin/peacekeeper.yaml → dist/cmdabra.yaml} +7 -0
  4. package/dist/package.json +57 -0
  5. package/dist/src/container.js +89 -0
  6. package/dist/src/modules/cli/interface.js +1 -0
  7. package/dist/src/modules/cli/service.js +48 -0
  8. package/dist/src/modules/cli/types.js +2 -0
  9. package/dist/src/modules/configuration/interface.js +6 -0
  10. package/dist/src/modules/configuration/project-config.js +114 -0
  11. package/dist/src/modules/configuration/update-config.js +42 -0
  12. package/dist/src/modules/dependencies.yaml +16 -0
  13. package/dist/src/modules/external.js +48 -0
  14. package/dist/src/modules/lifecycle/checkpoint-codex-changes.js +204 -0
  15. package/dist/src/modules/lifecycle/checkpoint-codex-session-start.js +23 -0
  16. package/dist/src/modules/lifecycle/checkpoint-codex-stop.js +69 -0
  17. package/dist/src/modules/lifecycle/checkpoint-instructions.js +21 -0
  18. package/dist/src/modules/lifecycle/cleanup-ended-session.js +265 -0
  19. package/dist/src/modules/lifecycle/interface.js +7 -0
  20. package/dist/src/modules/lifecycle/log-script-invocation.js +115 -0
  21. package/dist/src/modules/lifecycle/queue-merged-worktree-cleanup.js +37 -0
  22. package/dist/src/modules/maintenance/cleanup-merged-branches.js +298 -0
  23. package/dist/src/modules/maintenance/interface.js +7 -0
  24. package/dist/src/modules/maintenance/remove-empty-directories.js +114 -0
  25. package/{scripts → dist/src/modules/projects}/check-project-requirements.txt +3 -3
  26. package/dist/src/modules/projects/check-project.js +344 -0
  27. package/dist/src/modules/projects/create-project-core.js +186 -0
  28. package/dist/src/modules/projects/create-project.js +19 -0
  29. package/dist/src/modules/projects/generate-github-setup.js +13 -0
  30. package/dist/src/modules/projects/github-setup-prefix.sh +5 -0
  31. package/dist/src/modules/projects/github-setup-repository-template.sh +90 -0
  32. package/dist/src/modules/projects/github-setup-suffix-template.sh +5 -0
  33. package/dist/src/modules/projects/install-hooks.js +151 -0
  34. package/dist/src/modules/projects/interface.js +6 -0
  35. package/dist/src/modules/releases/assess-release-core.js +145 -0
  36. package/dist/src/modules/releases/assess-release.js +8 -0
  37. package/dist/src/modules/releases/interface.js +9 -0
  38. package/dist/src/modules/releases/release-core.js +529 -0
  39. package/dist/src/modules/releases/release-protection.js +147 -0
  40. package/dist/src/modules/releases/release.js +23 -0
  41. package/dist/src/modules/releases/verify-release-core.js +44 -0
  42. package/dist/src/modules/releases/verify-release-protection.js +25 -0
  43. package/dist/src/modules/releases/verify-release-version.js +14 -0
  44. package/dist/src/modules/releases/verify-release.js +30 -0
  45. package/dist/src/modules/testing/check-test-receipt.js +46 -0
  46. package/dist/src/modules/testing/interface.js +5 -0
  47. package/dist/src/modules/testing/receipt-state.js +99 -0
  48. package/dist/src/modules/testing/record-test-receipt.js +29 -0
  49. package/dist/src/modules/testing/run-tests.js +57 -0
  50. package/package.json +25 -9
  51. package/bin/peacekeeper.js +0 -68
  52. package/scripts/assess-release-core.js +0 -146
  53. package/scripts/assess-release.js +0 -7
  54. package/scripts/check-project.js +0 -346
  55. package/scripts/check-test-receipt.js +0 -49
  56. package/scripts/checkpoint-codex-changes.js +0 -232
  57. package/scripts/checkpoint-codex-session-start.js +0 -24
  58. package/scripts/checkpoint-codex-stop.js +0 -86
  59. package/scripts/checkpoint-instructions.js +0 -19
  60. package/scripts/cleanup-ended-session.js +0 -318
  61. package/scripts/cleanup-merged-branches.js +0 -382
  62. package/scripts/create-project-core.js +0 -278
  63. package/scripts/create-project.js +0 -26
  64. package/scripts/install-hooks.js +0 -155
  65. package/scripts/log-script-invocation.js +0 -125
  66. package/scripts/project-config.js +0 -120
  67. package/scripts/queue-merged-worktree-cleanup.js +0 -58
  68. package/scripts/receipt-state.js +0 -91
  69. package/scripts/record-test-receipt.js +0 -37
  70. package/scripts/release-core.js +0 -530
  71. package/scripts/release-protection.js +0 -135
  72. package/scripts/release.js +0 -18
  73. package/scripts/remove-empty-directories.js +0 -163
  74. package/scripts/run-tests.js +0 -66
  75. package/scripts/update-config.js +0 -41
  76. package/scripts/verify-release-core.js +0 -39
  77. package/scripts/verify-release-protection.js +0 -20
  78. package/scripts/verify-release-version.js +0 -14
  79. package/scripts/verify-release.js +0 -27
  80. /package/{scripts → dist/src/modules/configuration}/project-config-defaults.json +0 -0
  81. /package/{scripts → dist/src/modules/projects}/codex-setup-prefix.sh +0 -0
  82. /package/{scripts → dist/src/modules/releases}/assess-release-schema.json +0 -0
@@ -1,382 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * Remove local and remote branches that are fully merged into the locally known
5
- * the configured remote default branch. A worktree on an eligible local branch is removed first when it
6
- * has no tracked or untracked changes.
7
- *
8
- * Recommended usage:
9
- *
10
- * npm exec --no -- peacekeeper cleanup-merged-branches # Dry-run (default).
11
- * npm exec --no -- peacekeeper cleanup-merged-branches --dry-run # Explicit dry-run.
12
- * npm exec --no -- peacekeeper cleanup-merged-branches --execute # Apply the displayed cleanup.
13
- *
14
- * Every run fetches the configured remote, including dry-runs, so the cleanup
15
- * plan uses current remote references. Dry-run does not remove anything,
16
- * but this fetch still updates local remote references. The script never deletes
17
- * the configured default branch. It skips the current worktree, locked worktrees,
18
- * and worktrees with tracked or untracked changes. Ignored files do not count as
19
- * changes. Local and remote deletions are guarded by the exact commit IDs
20
- * observed while building the cleanup plan, so a branch changed concurrently is
21
- * preserved.
22
- */
23
-
24
- const { execFileSync, spawnSync } = require('node:child_process');
25
- const fs = require('node:fs');
26
- const path = require('node:path');
27
- const { projectConfig } = require('./project-config');
28
-
29
- function fail(message) {
30
- console.error(`Error: ${message}`);
31
- process.exit(1);
32
- }
33
-
34
- function runGit(args, options = {}) {
35
- const result = spawnSync('git', args, {
36
- cwd: options.cwd,
37
- encoding: 'utf8',
38
- stdio: options.stdio || ['ignore', 'pipe', 'pipe'],
39
- });
40
-
41
- if (result.status !== 0) {
42
- const detail = result.stderr?.trim() || result.stdout?.trim();
43
- throw new Error(detail || `git ${args.join(' ')} failed`);
44
- }
45
-
46
- return result.stdout;
47
- }
48
-
49
- function parseArguments(args) {
50
- let execute = false;
51
-
52
- for (const argument of args) {
53
- if (argument === '--execute') {
54
- execute = true;
55
- } else if (argument === '--dry-run') {
56
- execute = false;
57
- } else if (argument === '--help' || argument === '-h') {
58
- console.log('Usage: cleanup-merged-branches.js [--dry-run | --execute]');
59
- console.log('');
60
- console.log('Dry-run is the default. Use --execute to remove eligible worktrees and branches.');
61
- process.exit(0);
62
- } else {
63
- fail(`unknown argument: ${argument}`);
64
- }
65
- }
66
-
67
- return { execute };
68
- }
69
-
70
- function mergedBranches(repositoryRoot, namespace) {
71
- const { remote, defaultBranch } = projectConfig(repositoryRoot).git;
72
- const output = runGit([
73
- 'for-each-ref',
74
- `--merged=refs/remotes/${remote}/${defaultBranch}`,
75
- '--format=%(refname)\t%(objectname)\t%(symref)',
76
- namespace,
77
- ], { cwd: repositoryRoot });
78
-
79
- return output
80
- .trimEnd()
81
- .split('\n')
82
- .filter(Boolean)
83
- .map((line) => line.split('\t'))
84
- .filter(([, , symbolicTarget]) => !symbolicTarget)
85
- .map(([refName, objectId]) => ({ refName, objectId }));
86
- }
87
-
88
- function listWorktrees(repositoryRoot) {
89
- const fields = runGit(['worktree', 'list', '--porcelain', '-z'], {
90
- cwd: repositoryRoot,
91
- }).split('\0');
92
- const worktrees = [];
93
- let current = null;
94
-
95
- for (const field of fields) {
96
- if (field === '') {
97
- if (current) {
98
- worktrees.push(current);
99
- current = null;
100
- }
101
- continue;
102
- }
103
-
104
- const separator = field.indexOf(' ');
105
- const key = separator === -1 ? field : field.slice(0, separator);
106
- const value = separator === -1 ? '' : field.slice(separator + 1);
107
-
108
- if (key === 'worktree') {
109
- current = { path: value };
110
- } else if (current) {
111
- current[key] = value;
112
- }
113
- }
114
-
115
- return worktrees;
116
- }
117
-
118
- function samePath(first, second) {
119
- try {
120
- return fs.realpathSync(first) === fs.realpathSync(second);
121
- } catch {
122
- return path.resolve(first) === path.resolve(second);
123
- }
124
- }
125
-
126
- function branchNameFromLocalRef(refName) {
127
- return refName.slice('refs/heads/'.length);
128
- }
129
-
130
- function branchNameFromRemoteRef(refName, remote) {
131
- return refName.slice(`refs/remotes/${remote}/`.length);
132
- }
133
-
134
- function buildPlan(repositoryRoot) {
135
- const { remote, defaultBranch } = projectConfig(repositoryRoot).git;
136
- const localBranches = new Map(
137
- mergedBranches(repositoryRoot, 'refs/heads')
138
- .map(({ refName, objectId }) => [branchNameFromLocalRef(refName), objectId]),
139
- );
140
- const remoteBranches = new Map(
141
- mergedBranches(repositoryRoot, `refs/remotes/${remote}`)
142
- .map(({ refName, objectId }) => [branchNameFromRemoteRef(refName, remote), objectId])
143
- .filter(([branch]) => branch !== 'HEAD'),
144
- );
145
-
146
- localBranches.delete(defaultBranch);
147
- remoteBranches.delete(defaultBranch);
148
-
149
- const currentRoot = runGit(['rev-parse', '--show-toplevel'], {
150
- cwd: repositoryRoot,
151
- }).trim();
152
- const worktrees = listWorktrees(repositoryRoot);
153
- const names = [...new Set([...localBranches.keys(), ...remoteBranches.keys()])].sort();
154
-
155
- return names.map((branch) => {
156
- const branchWorktrees = localBranches.has(branch)
157
- ? worktrees.filter((worktree) => worktree.branch === `refs/heads/${branch}`)
158
- : [];
159
- let skipReason = null;
160
-
161
- for (const worktree of branchWorktrees) {
162
- if (samePath(worktree.path, currentRoot)) {
163
- skipReason = `it is checked out in the current worktree: ${worktree.path}`;
164
- break;
165
- }
166
- if (Object.hasOwn(worktree, 'locked')) {
167
- skipReason = `its worktree is locked: ${worktree.path}`;
168
- break;
169
- }
170
-
171
- try {
172
- const status = runGit(
173
- ['status', '--porcelain', '--untracked-files=all'],
174
- { cwd: worktree.path },
175
- );
176
- if (status !== '') {
177
- skipReason = `its worktree has changes: ${worktree.path}`;
178
- break;
179
- }
180
- } catch (error) {
181
- skipReason = `its worktree could not be inspected: ${worktree.path} (${error.message})`;
182
- break;
183
- }
184
- }
185
-
186
- return {
187
- branch,
188
- local: localBranches.has(branch),
189
- localObjectId: localBranches.get(branch),
190
- remote: remoteBranches.has(branch),
191
- remoteObjectId: remoteBranches.get(branch),
192
- worktrees: branchWorktrees,
193
- skipReason,
194
- };
195
- });
196
- }
197
-
198
- function printAction(execute, dryRunText, executeText, log) {
199
- log(execute ? executeText : `Would ${dryRunText}`);
200
- }
201
-
202
- function localPlanChangedReason(repositoryRoot, item) {
203
- if (!item.local) return null;
204
- try {
205
- const branchRef = `refs/heads/${item.branch}`;
206
- const tip = runGit(['rev-parse', '--verify', branchRef], { cwd: repositoryRoot }).trim();
207
- if (tip !== item.localObjectId) return 'its local branch changed after planning';
208
-
209
- const current = listWorktrees(repositoryRoot);
210
- const attached = current.filter((worktree) => worktree.branch === branchRef);
211
- if (attached.length !== item.worktrees.length) return 'its worktrees changed after planning';
212
-
213
- for (const planned of item.worktrees) {
214
- const worktree = current.find((candidate) => samePath(candidate.path, planned.path));
215
- if (!worktree || worktree.branch !== branchRef || worktree.HEAD !== item.localObjectId) {
216
- return `its worktree changed after planning: ${planned.path}`;
217
- }
218
- if (Object.hasOwn(worktree, 'locked')) return `its worktree is locked: ${planned.path}`;
219
- if (samePath(worktree.path, repositoryRoot)) return `it is checked out in the current worktree: ${planned.path}`;
220
- if (runGit(['status', '--porcelain', '--untracked-files=all'], { cwd: planned.path }) !== '') {
221
- return `its worktree has changes: ${planned.path}`;
222
- }
223
- }
224
- } catch (error) {
225
- return `its local state could not be verified: ${error.message}`;
226
- }
227
- return null;
228
- }
229
-
230
- function applyPlan(repositoryRoot, plan, execute, log = console.log) {
231
- const { remote } = projectConfig(repositoryRoot).git;
232
- let removedWorktrees = 0;
233
- let deletedLocalBranches = 0;
234
- let deletedRemoteBranches = 0;
235
- let skippedBranches = 0;
236
-
237
- items: for (const item of plan) {
238
- const skipReason = item.skipReason || (execute && localPlanChangedReason(repositoryRoot, item));
239
- if (skipReason) {
240
- log(`Skip ${item.branch}: ${skipReason}`);
241
- skippedBranches += 1;
242
- continue;
243
- }
244
-
245
- for (const [index, worktree] of item.worktrees.entries()) {
246
- printAction(
247
- execute,
248
- `remove worktree ${worktree.path} (branch ${item.branch})`,
249
- `Removing worktree ${worktree.path} (branch ${item.branch})`,
250
- log,
251
- );
252
- if (execute) {
253
- const changedReason = localPlanChangedReason(repositoryRoot, {
254
- ...item, worktrees: item.worktrees.slice(index),
255
- });
256
- if (changedReason) {
257
- log(`Skip ${item.branch}: ${changedReason}`);
258
- skippedBranches += 1;
259
- continue items;
260
- }
261
- runGit(['worktree', 'remove', worktree.path], { cwd: repositoryRoot });
262
- }
263
- removedWorktrees += 1;
264
- }
265
-
266
- if (item.local) {
267
- printAction(
268
- execute,
269
- `delete local branch ${item.branch}`,
270
- `Deleting local branch ${item.branch}`,
271
- log,
272
- );
273
- if (execute) {
274
- const changedReason = localPlanChangedReason(repositoryRoot, { ...item, worktrees: [] });
275
- if (changedReason) {
276
- log(`Skip ${item.branch}: ${changedReason}`);
277
- skippedBranches += 1;
278
- continue;
279
- }
280
- runGit([
281
- 'update-ref',
282
- '-d',
283
- `refs/heads/${item.branch}`,
284
- item.localObjectId,
285
- ], { cwd: repositoryRoot });
286
-
287
- const configResult = spawnSync(
288
- 'git',
289
- ['config', '--remove-section', `branch.${item.branch}`],
290
- { cwd: repositoryRoot, encoding: 'utf8' },
291
- );
292
- if (configResult.status !== 0 && configResult.status !== 5) {
293
- console.warn(
294
- `Warning: could not remove configuration for branch ${item.branch}: `
295
- + configResult.stderr.trim(),
296
- );
297
- }
298
- }
299
- deletedLocalBranches += 1;
300
- }
301
-
302
- if (item.remote) {
303
- printAction(
304
- execute,
305
- `delete remote branch ${remote}/${item.branch}`,
306
- `Deleting remote branch ${remote}/${item.branch}`,
307
- log,
308
- );
309
- if (execute) {
310
- runGit([
311
- 'push',
312
- `--force-with-lease=refs/heads/${item.branch}:${item.remoteObjectId}`,
313
- remote,
314
- `:refs/heads/${item.branch}`,
315
- ], {
316
- cwd: repositoryRoot,
317
- });
318
- }
319
- deletedRemoteBranches += 1;
320
- }
321
- }
322
-
323
- log('');
324
- log(
325
- `${execute ? 'Removed' : 'Would remove'} ${removedWorktrees} worktree(s), `
326
- + `${deletedLocalBranches} local branch(es), and ${deletedRemoteBranches} remote branch(es).`,
327
- );
328
- if (skippedBranches > 0) {
329
- log(`Skipped ${skippedBranches} branch(es).`);
330
- }
331
- if (!execute) {
332
- log('');
333
- log('To apply this cleanup, run:');
334
- log(' npm exec --no -- peacekeeper cleanup-merged-branches --execute');
335
- }
336
- }
337
-
338
- function main() {
339
- const { execute } = parseArguments(process.argv.slice(2));
340
-
341
- try {
342
- execFileSync('git', ['--version'], { stdio: 'ignore' });
343
- } catch {
344
- fail('required command not found: git');
345
- }
346
-
347
- let repositoryRoot;
348
- try {
349
- repositoryRoot = runGit(['rev-parse', '--show-toplevel']).trim();
350
- runGit(['remote', 'get-url', projectConfig(repositoryRoot).git.remote], { cwd: repositoryRoot });
351
- } catch (error) {
352
- fail(error.message);
353
- }
354
-
355
- console.log(execute ? 'Execute mode.' : 'Dry-run mode. No worktrees or branches will be removed.');
356
- console.log(`Fetching and pruning ${projectConfig(repositoryRoot).git.remote} before building the cleanup plan.`);
357
-
358
- try {
359
- const { remote, defaultBranch } = projectConfig(repositoryRoot).git;
360
- runGit(['fetch', '--prune', remote], { cwd: repositoryRoot });
361
- runGit(['show-ref', '--verify', '--quiet', `refs/remotes/${remote}/${defaultBranch}`], {
362
- cwd: repositoryRoot,
363
- });
364
- } catch (error) {
365
- fail(error.message);
366
- }
367
-
368
- console.log('');
369
-
370
- try {
371
- const plan = buildPlan(repositoryRoot);
372
- applyPlan(repositoryRoot, plan, execute);
373
- } catch (error) {
374
- fail(error.message);
375
- }
376
- }
377
-
378
- if (require.main === module) {
379
- main();
380
- }
381
-
382
- module.exports = { applyPlan, buildPlan, listWorktrees, parseArguments };
@@ -1,278 +0,0 @@
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
- required_approver=${owner}
103
- gh auth status
104
- gh repo view "$repo" >/dev/null
105
- actual_owner=$(gh api "repos/$repo" --jq .owner.login)
106
- if [[ "$actual_owner" != "$required_approver" ]]; then
107
- printf 'Expected personal repository owner %s, found %s.\n' "$required_approver" "$actual_owner" >&2
108
- exit 1
109
- fi
110
- approver_id=$(gh api "users/$required_approver" --jq .id)
111
- gh api --method PATCH "repos/$repo" \\
112
- -F delete_branch_on_merge=true \\
113
- -F allow_auto_merge=true \\
114
- -F allow_merge_commit=true \\
115
- -F allow_squash_merge=false \\
116
- -F allow_rebase_merge=false >/dev/null
117
- policy_dir=$(mktemp -d)
118
- trap 'rm -rf -- "$policy_dir"' EXIT
119
- base_policy="$policy_dir/base.json"
120
- approval_policy="$policy_dir/approval.json"
121
- cat >"$base_policy" <<'JSON'
122
- {
123
- "name": "Peacekeeper base protection",
124
- "target": "branch",
125
- "enforcement": "active",
126
- "bypass_actors": [],
127
- "conditions": { "ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] } },
128
- "rules": [
129
- { "type": "deletion" },
130
- { "type": "non_fast_forward" },
131
- {
132
- "type": "pull_request",
133
- "parameters": {
134
- "required_approving_review_count": 0,
135
- "dismiss_stale_reviews_on_push": false,
136
- "require_code_owner_review": false,
137
- "require_last_push_approval": false,
138
- "required_review_thread_resolution": false,
139
- "allowed_merge_methods": ["merge"]
140
- }
141
- },
142
- {
143
- "type": "required_status_checks",
144
- "parameters": {
145
- "strict_required_status_checks_policy": true,
146
- "do_not_enforce_on_create": false,
147
- "required_status_checks": [{ "context": "test" }]
148
- }
149
- }
150
- ]
151
- }
152
- JSON
153
- cat >"$approval_policy" <<JSON
154
- {
155
- "name": "Peacekeeper owner approval",
156
- "target": "branch",
157
- "enforcement": "active",
158
- "bypass_actors": [
159
- { "actor_id": $approver_id, "actor_type": "User", "bypass_mode": "pull_request" }
160
- ],
161
- "conditions": { "ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] } },
162
- "rules": [
163
- {
164
- "type": "pull_request",
165
- "parameters": {
166
- "required_approving_review_count": 1,
167
- "dismiss_stale_reviews_on_push": true,
168
- "require_code_owner_review": true,
169
- "require_last_push_approval": false,
170
- "required_review_thread_resolution": false,
171
- "allowed_merge_methods": ["merge"]
172
- }
173
- }
174
- ]
175
- }
176
- JSON
177
-
178
- upsert_ruleset() {
179
- local name=$1 payload=$2 ids count id
180
- ids=$(gh api --paginate "repos/$repo/rulesets?includes_parents=false" --jq ".[] | select(.name == \"$name\") | .id")
181
- count=$(printf '%s\n' "$ids" | sed '/^$/d' | wc -l | tr -d ' ')
182
- if [[ "$count" == 0 ]]; then
183
- gh api --method POST "repos/$repo/rulesets" --input "$payload" >/dev/null
184
- elif [[ "$count" == 1 ]]; then
185
- id=$ids
186
- gh api --method PUT "repos/$repo/rulesets/$id" --input "$payload" >/dev/null
187
- else
188
- printf 'Multiple rulesets named %s exist; remove duplicates before retrying.\n' "$name" >&2
189
- exit 1
190
- fi
191
- }
192
- upsert_ruleset 'Peacekeeper base protection' "$base_policy"
193
- upsert_ruleset 'Peacekeeper owner approval' "$approval_policy"
194
- if gh api "repos/$repo/branches/main/protection" >/dev/null 2>&1; then
195
- gh api --method DELETE "repos/$repo/branches/main/protection" >/dev/null
196
- fi
197
- groundskeeper secrets sync --name RELEASE_POLICY_TOKEN --new-repo "$repo"
198
- printf 'GitHub configuration completed for %s.\\n' "$repo"
199
- `;
200
- }
201
-
202
- function packageTest() {
203
- 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`;
204
- }
205
-
206
- function generate(root, options) {
207
- const version = require('../package.json').version;
208
- const manifest = {
209
- name: options.packageName, version: '0.1.0', description: `${options.repositoryName} TypeScript library`,
210
- type: 'module', ...(options.published ? {} : { private: true }),
211
- author: { name: options.authorName, email: options.authorEmail },
212
- repository: { type: 'git', url: `git+${options.repository}` }, license: 'MIT',
213
- engines: { node: '>=20' }, volta: { node: TOOLCHAIN.node, npm: TOOLCHAIN.npm },
214
- main: './dist/index.js', types: './dist/index.d.ts', exports: { '.': { types: './dist/index.d.ts', import: './dist/index.js' } },
215
- scripts: { build: 'tsc -p tsconfig.json', typecheck: 'tsc -p tsconfig.json --noEmit', test: 'peacekeeper run-tests', 'test:unit': 'node --test test/*.test.js',
216
- ...(options.published ? { 'test:package': 'node scripts/test-package.cjs', release: 'peacekeeper release' } : {}) },
217
- devDependencies: { '@jakobm/peacekeeper': version, '@types/node': TOOLCHAIN.nodeTypes, typescript: TOOLCHAIN.typescript },
218
- ...(options.published ? { files: ['dist/'], publishConfig: { access: 'public', registry: 'https://registry.npmjs.org/' } } : {}),
219
- };
220
- write(root, 'package.json', json(manifest));
221
- 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'] }));
222
- write(root, 'src/index.ts', "export function hello(): string {\n return 'hello world';\n}\n");
223
- 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`);
224
- if (options.published) write(root, 'scripts/test-package.cjs', packageTest().replace('${PACKAGE_NAME}', options.packageName));
225
- const defaults = structuredClone(require('./project-config-defaults.json'));
226
- defaults.publishesToNpm = options.published;
227
- defaults.git.requiredApprover = options.owner;
228
- defaults.tests.commands = ['npm run typecheck', 'npm run build', 'npm run test:unit', ...(options.published ? ['npm run test:package'] : [])];
229
- defaults.tests.npmTestUsesRunner = true;
230
- write(root, 'peacekeeper.config.json', json(defaults));
231
- write(root, '.codex/hooks.json', json(planHooks({}).document));
232
- const prefix = fs.readFileSync(path.join(__dirname, 'codex-setup-prefix.sh'), 'utf8');
233
- write(root, '.codex/environments/environment.toml', `version = 1\nname = ${JSON.stringify(options.repositoryName)}\n\n[setup]\nscript = '''\n${prefix}'''\n`);
234
- write(root, '.github/workflows/test.yml', workflow(options.published));
235
- write(root, '.github/CODEOWNERS', `* @${options.owner}\n`);
236
- if (options.published) write(root, '.github/workflows/publish.yml', publishWorkflow());
237
- write(root, '.gitignore', 'node_modules/\n*.tgz\ntmp/\n');
238
- write(root, 'README.md', `# ${options.repositoryName}\n\nA TypeScript library generated by Peacekeeper.\n\n## API\n\n\`hello()\` returns \`"hello world"\`.\n`);
239
- 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`);
240
- write(root, 'setup-github-config.sh', githubSetup(options), 0o755);
241
- }
242
-
243
- function createProject(options, dependencies = {}) {
244
- const run = dependencies.run || commandRunner;
245
- const voltaHome = process.env.VOLTA_HOME;
246
- const volta = voltaHome && fs.existsSync(path.join(voltaHome, 'bin', 'volta'))
247
- ? path.join(voltaHome, 'bin', 'volta') : 'volta';
248
- const npm = args => run(volta, ['run', '--node', TOOLCHAIN.node, '--npm', TOOLCHAIN.npm, 'npm', ...args], { cwd: normalized });
249
- const target = path.resolve(options.directory);
250
- if (fs.existsSync(target)) throw new Error(`Destination already exists: ${target}`);
251
- const parent = path.dirname(target);
252
- let realParent;
253
- try { realParent = fs.realpathSync(parent); } catch { throw new Error(`Destination parent does not exist: ${parent}`); }
254
- const normalized = path.join(realParent, path.basename(target));
255
- if (fs.existsSync(normalized)) throw new Error(`Destination already exists after path normalization: ${normalized}`);
256
- const refs = run('git', ['ls-remote', options.repository], { capture: true }).trim();
257
- if (refs) throw new Error('The repository is not empty; refusing to create a project');
258
- fs.mkdirSync(normalized);
259
- try {
260
- run('git', ['init', '--initial-branch=main'], { cwd: normalized });
261
- run('git', ['remote', 'add', 'origin', options.repository], { cwd: normalized });
262
- generate(normalized, options);
263
- npm(['install', '--ignore-scripts']);
264
- npm(['run', 'build']);
265
- npm(['run', 'typecheck']);
266
- npm(['test']);
267
- run('bash', ['-n', 'setup-github-config.sh'], { cwd: normalized });
268
- if (run('git', ['ls-remote', options.repository], { capture: true }).trim()) throw new Error('The repository gained refs while the project was being created');
269
- run('git', ['add', '--all'], { cwd: normalized });
270
- run('git', ['-c', `user.name=${options.authorName}`, '-c', `user.email=${options.authorEmail}`, 'commit', '-m', 'Initial project'], { cwd: normalized });
271
- run('git', ['push', '--set-upstream', 'origin', 'main:main'], { cwd: normalized });
272
- } catch (error) {
273
- throw new Error(`${error.message}. Inspect or remove ${normalized} before retrying.`);
274
- }
275
- return { directory: normalized, packageName: options.packageName };
276
- }
277
-
278
- module.exports = { TOOLCHAIN, UsageError, createProject, generate, parseArguments, repositoryIdentity, usage };