@jakobm/peacekeeper 0.19.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 +85 -32
  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/{scripts → dist/src/modules/configuration}/project-config-defaults.json +1 -0
  11. package/dist/src/modules/configuration/project-config.js +114 -0
  12. package/dist/src/modules/configuration/update-config.js +42 -0
  13. package/dist/src/modules/dependencies.yaml +16 -0
  14. package/dist/src/modules/external.js +48 -0
  15. package/dist/src/modules/lifecycle/checkpoint-codex-changes.js +204 -0
  16. package/dist/src/modules/lifecycle/checkpoint-codex-session-start.js +23 -0
  17. package/dist/src/modules/lifecycle/checkpoint-codex-stop.js +69 -0
  18. package/dist/src/modules/lifecycle/checkpoint-instructions.js +21 -0
  19. package/dist/src/modules/lifecycle/cleanup-ended-session.js +265 -0
  20. package/dist/src/modules/lifecycle/interface.js +7 -0
  21. package/dist/src/modules/lifecycle/log-script-invocation.js +115 -0
  22. package/dist/src/modules/lifecycle/queue-merged-worktree-cleanup.js +37 -0
  23. package/dist/src/modules/maintenance/cleanup-merged-branches.js +298 -0
  24. package/dist/src/modules/maintenance/interface.js +7 -0
  25. package/dist/src/modules/maintenance/remove-empty-directories.js +114 -0
  26. package/{scripts → dist/src/modules/projects}/check-project-requirements.txt +35 -22
  27. package/dist/src/modules/projects/check-project.js +344 -0
  28. package/dist/src/modules/projects/create-project-core.js +186 -0
  29. package/dist/src/modules/projects/create-project.js +19 -0
  30. package/dist/src/modules/projects/generate-github-setup.js +13 -0
  31. package/dist/src/modules/projects/github-setup-prefix.sh +5 -0
  32. package/dist/src/modules/projects/github-setup-repository-template.sh +90 -0
  33. package/dist/src/modules/projects/github-setup-suffix-template.sh +5 -0
  34. package/dist/src/modules/projects/install-hooks.js +151 -0
  35. package/dist/src/modules/projects/interface.js +6 -0
  36. package/dist/src/modules/releases/assess-release-core.js +145 -0
  37. package/dist/src/modules/releases/assess-release.js +8 -0
  38. package/dist/src/modules/releases/interface.js +9 -0
  39. package/dist/src/modules/releases/release-core.js +529 -0
  40. package/dist/src/modules/releases/release-protection.js +147 -0
  41. package/dist/src/modules/releases/release.js +23 -0
  42. package/dist/src/modules/releases/verify-release-core.js +44 -0
  43. package/dist/src/modules/releases/verify-release-protection.js +25 -0
  44. package/dist/src/modules/releases/verify-release-version.js +14 -0
  45. package/dist/src/modules/releases/verify-release.js +30 -0
  46. package/dist/src/modules/testing/check-test-receipt.js +46 -0
  47. package/dist/src/modules/testing/interface.js +5 -0
  48. package/dist/src/modules/testing/receipt-state.js +99 -0
  49. package/dist/src/modules/testing/record-test-receipt.js +29 -0
  50. package/dist/src/modules/testing/run-tests.js +57 -0
  51. package/package.json +25 -9
  52. package/bin/peacekeeper.js +0 -68
  53. package/scripts/assess-release-core.js +0 -146
  54. package/scripts/assess-release.js +0 -7
  55. package/scripts/check-project.js +0 -333
  56. package/scripts/check-test-receipt.js +0 -49
  57. package/scripts/checkpoint-codex-changes.js +0 -232
  58. package/scripts/checkpoint-codex-session-start.js +0 -24
  59. package/scripts/checkpoint-codex-stop.js +0 -86
  60. package/scripts/checkpoint-instructions.js +0 -19
  61. package/scripts/cleanup-ended-session.js +0 -318
  62. package/scripts/cleanup-merged-branches.js +0 -382
  63. package/scripts/create-project-core.js +0 -195
  64. package/scripts/create-project.js +0 -26
  65. package/scripts/install-hooks.js +0 -155
  66. package/scripts/log-script-invocation.js +0 -125
  67. package/scripts/project-config.js +0 -115
  68. package/scripts/queue-merged-worktree-cleanup.js +0 -58
  69. package/scripts/receipt-state.js +0 -91
  70. package/scripts/record-test-receipt.js +0 -37
  71. package/scripts/release-core.js +0 -529
  72. package/scripts/release-protection.js +0 -96
  73. package/scripts/release.js +0 -18
  74. package/scripts/remove-empty-directories.js +0 -163
  75. package/scripts/run-tests.js +0 -66
  76. package/scripts/update-config.js +0 -41
  77. package/scripts/verify-release-core.js +0 -39
  78. package/scripts/verify-release-protection.js +0 -19
  79. package/scripts/verify-release-version.js +0 -14
  80. package/scripts/verify-release.js +0 -26
  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
@@ -0,0 +1,344 @@
1
+ export default ({ configuration, installHooks, releases, external: { fs, isDeepStrictEqual, modulesRoot, output, path, runtime, semver, TOML, YAML, } }) => {
2
+ const { projectConfig } = configuration;
3
+ const { planHooks, classifyCommand } = installHooks;
4
+ const { inspectWorkflow, ensureLockfilesMatch } = releases;
5
+ function read(root, file, parse = JSON.parse) {
6
+ try {
7
+ return parse(fs.readFileSync(path.join(root, file), 'utf8'));
8
+ }
9
+ catch (error) {
10
+ throw new Error(`${file}: ${error instanceof Error ? error.message : String(error)}`);
11
+ }
12
+ }
13
+ function unconditional(value) {
14
+ return value === undefined || value === 'success()' || value === '${{ success() }}';
15
+ }
16
+ function directCommand(step, expression) {
17
+ return typeof step?.run === 'string' && expression.test(step.run.trim());
18
+ }
19
+ const testCommand = /^npm (?:test|run test(?::[\w-]+)?|pack --dry-run(?: --json)?)$/u;
20
+ const installCommand = /^npm ci$/u;
21
+ const verifyCommand = /^(?:peacekeeper|npm exec --no -- peacekeeper|node (?:\.\/)?(?:node_modules\/@jakobm\/peacekeeper\/)?(?:dist\/)?bin\/peacekeeper\.js) verify-release$/u;
22
+ function checkProject(cwd = runtime.cwd()) {
23
+ const config = projectConfig(cwd);
24
+ const root = config.root;
25
+ const manifest = read(root, 'package.json');
26
+ const errors = [];
27
+ let category;
28
+ const requireThat = (condition, message) => {
29
+ if (!condition)
30
+ errors.push(`[${category}] ${message}`);
31
+ return Boolean(condition);
32
+ };
33
+ const check = (nextCategory, action) => {
34
+ const previous = category;
35
+ category = nextCategory;
36
+ try {
37
+ action();
38
+ }
39
+ catch (error) {
40
+ errors.push(`[${category}] ${error instanceof Error ? error.message : String(error)}`);
41
+ }
42
+ finally {
43
+ category = previous;
44
+ }
45
+ };
46
+ check('tests', () => {
47
+ const projectCheck = /(?:^|&&|\|\||;|\n)\s*(?:peacekeeper|npm\s+exec\s+--no\s+--\s+peacekeeper|npx\s+--no-install\s+peacekeeper|node\s+(?:\.\/)?(?:node_modules\/@jakobm\/peacekeeper\/)?bin\/peacekeeper\.js)\s+check-project(?=\s|$|;|&|\|)/u;
48
+ for (const [index, command] of config.tests.commands.entries()) {
49
+ requireThat(!projectCheck.test(command), `tests.commands[${index}]: remove check-project; it is redundant because Peacekeeper always includes it automatically before the configured test commands, even when reusing a test receipt.`);
50
+ }
51
+ });
52
+ check('package', () => {
53
+ const nonblank = value => typeof value === 'string' && value.trim().length > 0;
54
+ requireThat(nonblank(manifest.author) || nonblank(manifest.author?.name), 'package.json: author must be a nonblank string or an object with a nonblank name.');
55
+ requireThat(nonblank(manifest.repository) || nonblank(manifest.repository?.url), 'package.json: repository must be a nonblank string or an object with a nonblank url.');
56
+ });
57
+ check('GitHub policy', () => {
58
+ const approver = config.git.requiredApprover;
59
+ requireThat(typeof approver === 'string', 'peacekeeper.config.json: set git.requiredApprover to the personal GitHub repository owner.');
60
+ if (typeof approver !== 'string')
61
+ return;
62
+ const file = '.github/CODEOWNERS';
63
+ const lines = read(root, file, value => value.split(/\r?\n/u))
64
+ .map(line => line.trim())
65
+ .filter(line => line && !line.startsWith('#'));
66
+ requireThat(isDeepStrictEqual(lines, [`* @${approver}`]), `${file}: use exactly one ownership rule, "* @${approver}", so only git.requiredApprover can satisfy required code-owner review.`);
67
+ });
68
+ const workflows = new Map();
69
+ check('CI', () => {
70
+ const directory = path.join(root, '.github/workflows');
71
+ for (const file of fs.readdirSync(directory).filter(file => /\.ya?ml$/u.test(file))) {
72
+ check('CI', () => {
73
+ const document = read(root, `.github/workflows/${file}`, YAML.parse);
74
+ if (!requireThat(document && typeof document.jobs === 'object' && document.jobs !== null && !Array.isArray(document.jobs), `${file}: declare workflow jobs; dependent checks are blocked.`))
75
+ return;
76
+ workflows.set(file, document);
77
+ });
78
+ }
79
+ requireThat(workflows.size, 'Add a PR workflow in .github/workflows.');
80
+ });
81
+ // These are runtime compatibility floors, not a list of latest releases.
82
+ const actionMinimums = new Map([['actions/checkout', 5], ['volta-cli/action', 5]]);
83
+ for (const [file, workflow] of workflows) {
84
+ for (const [id, rawJob] of Object.entries(workflow.jobs)) {
85
+ const job = rawJob;
86
+ check('CI', () => {
87
+ const runner = job?.['runs-on'];
88
+ const labels = typeof runner === 'object' && runner !== null && !Array.isArray(runner)
89
+ ? runner.labels
90
+ : runner;
91
+ const values = (Array.isArray(labels) ? labels : [labels]).flatMap(label => {
92
+ if (typeof label !== 'string')
93
+ return [];
94
+ const keys = [...label.matchAll(/\$\{\{\s*matrix\.([\w-]+)\s*\}\}/gu)].map(match => match[1]);
95
+ return [label, ...keys.flatMap(key => {
96
+ const matrix = job.strategy?.matrix;
97
+ return [matrix?.[key], ...(matrix?.include || []).map(entry => entry[key])].flat();
98
+ })];
99
+ });
100
+ const moving = [...new Set(values.filter(value => typeof value === 'string' && /(?:^|[^\w-])[\w-]+-latest(?:$|[^\w-])/u.test(value)))];
101
+ requireThat(!moving.length, `${file}/${id}: found ${moving.join(', ')}; pin runner images (for example ubuntu-24.04) instead of moving *-latest labels.`);
102
+ for (const step of job?.steps || []) {
103
+ if (typeof step?.uses !== 'string')
104
+ continue;
105
+ const separator = step.uses.lastIndexOf('@');
106
+ const action = step.uses.slice(0, separator);
107
+ const minimum = actionMinimums.get(action);
108
+ if (!minimum)
109
+ continue;
110
+ const version = /^v(\d+)(?:\.\d+){0,2}$/u.exec(step.uses.slice(separator + 1));
111
+ requireThat(version && Number(version[1]) >= minimum, `${file}/${id}: found ${step.uses}; use ${action}@v${minimum} or newer with a stable version tag; older releases use deprecated Node.js action runtimes. SHA and branch refs cannot be verified offline.`);
112
+ }
113
+ });
114
+ }
115
+ }
116
+ check('tools', () => {
117
+ for (const name of ['node', 'npm']) {
118
+ requireThat(semver.valid(manifest.volta?.[name]) === manifest.volta?.[name] && typeof manifest.volta?.[name] === 'string', `package.json: pin an exact volta.${name} version with volta pin.`);
119
+ }
120
+ requireThat(typeof manifest.engines?.node === 'string' && semver.validRange(manifest.engines.node)
121
+ && semver.satisfies(manifest.volta?.node, manifest.engines.node), 'package.json: volta.node must satisfy engines.node.');
122
+ requireThat(!fs.existsSync(path.join(root, '.nvmrc')), '.nvmrc must be removed; package.json volta pins select the Node and npm versions.');
123
+ });
124
+ for (const [file, workflow] of workflows) {
125
+ for (const [id, rawJob] of Object.entries(workflow.jobs)) {
126
+ const job = rawJob;
127
+ check('tools', () => {
128
+ const steps = job?.steps || [];
129
+ const nodeSteps = steps.filter(step => /^(?:actions\/setup-node|volta-cli\/action)@/u.test(step?.uses || '')
130
+ || /\b(?:node|npm|npx|volta)\s/u.test(step?.run || ''));
131
+ if (!nodeSteps.length)
132
+ return;
133
+ const toolIndex = steps.findIndex(step => /^volta-cli\/action@/u.test(step?.uses || ''));
134
+ requireThat(toolIndex >= 0, `${file}/${id}: use volta-cli/action to select project Node and npm versions. Volta setup checks are blocked until that step exists.`);
135
+ requireThat(steps.filter(step => /^volta-cli\/action@/u.test(step?.uses || '')).length <= 1, `${file}/${id}: use one Volta setup step per job.`);
136
+ requireThat(!steps.some(step => /^actions\/setup-node@/u.test(step?.uses || '')
137
+ || /\b(?:nvm\s+(?:use|install)|volta\s+(?:install|pin|run)|npm\s+(?:i|install)\s+(?:--global|-g)\b)/u.test(step?.run || '')), `${file}/${id}: remove competing Node/npm setup commands.`);
138
+ if (toolIndex < 0)
139
+ return; // Remaining setup checks need a Volta step.
140
+ const tool = steps[toolIndex];
141
+ requireThat(unconditional(tool.if) && !tool['continue-on-error'], `${file}/${id}: Volta setup must not be conditional or allowed to fail.`);
142
+ requireThat(steps.slice(0, toolIndex).some(step => /^actions\/checkout@/u.test(step?.uses || '') && unconditional(step.if) && !step['continue-on-error']), `${file}/${id}: check out the project before Volta setup.`);
143
+ requireThat(!['node-version', 'npm-version', 'package-json-path'].some(key => Object.hasOwn(tool.with || {}, key)), `${file}/${id}: remove Volta version/path overrides; use package.json.`);
144
+ requireThat(!steps.slice(0, toolIndex).some(step => /\b(?:node|npm|npx)\s/u.test(step?.run || '')), `${file}/${id}: set up Volta before Node/npm commands.`);
145
+ });
146
+ }
147
+ }
148
+ check('environment', () => {
149
+ const file = '.codex/environments/environment.toml';
150
+ const document = read(root, file, TOML.parse);
151
+ requireThat(document.version === 1, `${file}: version must be 1.`);
152
+ const prefix = fs.readFileSync(path.join(modulesRoot, 'projects/codex-setup-prefix.sh'), 'utf8');
153
+ requireThat(typeof document.setup?.script === 'string' && document.setup.script.startsWith(prefix), `${file}: setup.script must start with the exact prefix below, including the newline after the final comment. Preserve custom project setup after that comment.\n${prefix}`);
154
+ // Platform overrides replace the default setup and must preserve its contract too.
155
+ for (const platform of ['linux', 'macos', 'windows']) {
156
+ if (!Object.hasOwn(document.setup || {}, platform))
157
+ continue;
158
+ const script = document.setup[platform]?.script;
159
+ requireThat(typeof script === 'string' && script.startsWith(prefix), `${file}: setup.${platform}.script must start with the same required setup prefix.\n${prefix}`);
160
+ }
161
+ });
162
+ check('hooks', () => {
163
+ const document = read(root, '.codex/hooks.json');
164
+ const localSource = fs.realpathSync(root) === fs.realpathSync(path.resolve(modulesRoot, '../../..'));
165
+ const expected = planHooks(document, localSource).document;
166
+ for (const event of new Set([...Object.keys(document.hooks || {}), ...Object.keys(expected.hooks)])) {
167
+ const owned = groups => groups.flatMap(group => {
168
+ const handlers = group.hooks.filter(hook => classifyCommand(hook.command) !== 'other');
169
+ if (handlers.length)
170
+ requireThat(Object.keys(group).every(key => key === 'hooks'), '.codex/hooks.json: peacekeeper lifecycle hooks must not have group conditions.');
171
+ return handlers;
172
+ });
173
+ requireThat(isDeepStrictEqual(owned(document.hooks?.[event] || []), owned(expected.hooks[event] || [])), `.codex/hooks.json: missing, duplicate or outdated ${event} lifecycle hooks; run peacekeeper install-hooks.`);
174
+ }
175
+ });
176
+ const published = config.publishesToNpm;
177
+ check('publication', () => {
178
+ const nonblank = value => typeof value === 'string' && value.trim().length > 0;
179
+ const scripts = manifest.scripts || {};
180
+ const releaseCommand = /^(?:peacekeeper|npm exec --no -- peacekeeper|node (?:\.\/)?(?:node_modules\/@jakobm\/peacekeeper\/)?(?:dist\/)?bin\/peacekeeper\.js) release$/u;
181
+ // Resolve npm script aliases without executing project code. Cycles stop here.
182
+ function commands(command, seen = new Set()) {
183
+ if (typeof command !== 'string')
184
+ return [];
185
+ const parts = command.split(/&&|\|\||;|\n/u).map(part => part.trim());
186
+ return parts.flatMap(part => {
187
+ const alias = /^npm (?:run(?:-script)? ([\w:.-]+)|(?:run )?(test|publish|pack))(?:\s|$)/u.exec(part);
188
+ const name = alias?.[1] || alias?.[2];
189
+ return [part, ...(name && !seen.has(name) ? commands(scripts[name], new Set([...seen, name])) : [])];
190
+ });
191
+ }
192
+ const publicationCommand = command => commands(command).some(part => /^(?:npm (?:publish\b|(?:exec|x)\b.*\b(?:npm-publish|np)\b)|npx\b.*\b(?:npm-publish|np)\b)/u.test(part)
193
+ || releaseCommand.test(part) || verifyCommand.test(part));
194
+ requireThat(published ? manifest.private === undefined || manifest.private === false : manifest.private === true, `package.json: publishesToNpm=${published} requires private ${published ? 'to be absent or false' : 'to be true'}.`);
195
+ if (published) {
196
+ requireThat(nonblank(manifest.name) && manifest.name.length <= 214
197
+ && /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u.test(manifest.name), 'package.json: declare a valid npm package name.');
198
+ for (const field of ['description', 'license'])
199
+ requireThat(nonblank(manifest[field]), `package.json: published packages require a nonblank ${field}.`);
200
+ requireThat(manifest.publishConfig?.registry === 'https://registry.npmjs.org/'
201
+ && ['public', 'restricted'].includes(manifest.publishConfig?.access), 'package.json: publishConfig must declare registry https://registry.npmjs.org/ and access public or restricted.');
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.release === 'string' && releaseCommand.test(scripts.release.trim()), 'package.json: scripts.release must invoke peacekeeper release directly.');
204
+ const testWorkflow = workflows.get(config.projectChecks.testWorkflow);
205
+ requireThat(testWorkflow && Object.values(testWorkflow.jobs).some((rawJob) => {
206
+ const job = rawJob;
207
+ const steps = job.steps || [];
208
+ const installed = steps.findIndex(step => directCommand(step, installCommand)
209
+ && unconditional(step.if) && !step['continue-on-error']);
210
+ return unconditional(job.if) && !job['continue-on-error'] && installed >= 0
211
+ && steps.some((step, index) => index > installed && unconditional(step.if)
212
+ && !step['continue-on-error'] && commands(step.run).some(command => /^npm (?:pack(?: --dry-run(?: --json)?)?|run test:package)$/u.test(command)));
213
+ }), 'Add an unconditional npm pack or npm run test:package CI check after npm ci in projectChecks.testWorkflow for published packages.');
214
+ }
215
+ else {
216
+ for (const field of ['publishConfig', 'files'])
217
+ requireThat(!Object.hasOwn(manifest, field), `package.json: remove ${field} when publishesToNpm=false.`);
218
+ for (const [name, command] of Object.entries(scripts))
219
+ requireThat(!publicationCommand(command), `package.json: remove npm publication command scripts.${name} when publishesToNpm=false.`);
220
+ for (const [file, workflow] of workflows)
221
+ for (const [id, rawJob] of Object.entries(workflow.jobs)) {
222
+ const job = rawJob;
223
+ for (const step of job.steps || [])
224
+ requireThat(!publicationCommand(step.run)
225
+ && !/npm-publish/iu.test(step.uses || ''), `${file}/${id}: remove npm publication steps when publishesToNpm=false.`);
226
+ }
227
+ }
228
+ });
229
+ const filename = config.projectChecks.testWorkflow;
230
+ const required = [...new Set([...(config.projectChecks.requiredJobs), ...(published ? config.git.releaseRequiredChecks : [])])];
231
+ check('CI', () => {
232
+ const workflow = workflows.get(filename);
233
+ if (!workflow) {
234
+ requireThat(false, `${filename}: configured PR workflow is missing (selected by projectChecks.testWorkflow). Set projectChecks.testWorkflow${published ? ' and git.releaseTestWorkflow to the same existing file' : ' to an existing file'} in peacekeeper.config.json. PR checks are blocked until it can be read.`);
235
+ return;
236
+ }
237
+ const jobs = workflow.jobs;
238
+ const on = workflow.on;
239
+ requireThat(on && typeof on === 'object' && !Array.isArray(on)
240
+ && Object.hasOwn(on, 'pull_request') && Object.keys(on).length === 1, `${filename}: declare only an on.pull_request trigger; remove push, manual, scheduled, and other triggers from the PR test workflow. Keep publishing and deployment in separate workflows.`);
241
+ const filters = on?.pull_request;
242
+ requireThat(filters && typeof filters === 'object' && !Array.isArray(filters)
243
+ && !['paths', 'paths-ignore', 'branches-ignore', 'types'].some(key => Object.hasOwn(filters, key))
244
+ && Array.isArray(filters.branches) && filters.branches.length === 1
245
+ && filters.branches[0] === config.git.defaultBranch, `${filename}: PR filters must set branches to exactly ["${config.git.defaultBranch}"] (git.defaultBranch) and must not skip required checks by path or event type.`);
246
+ let policyJobs = 0;
247
+ const checked = new Set();
248
+ function requiredJob(id, job, testsRequired) {
249
+ if (!requireThat(job && typeof job === 'object', `${filename}/${id}: required job is missing; checks for this job are blocked.`))
250
+ return;
251
+ requireThat(unconditional(job.if) || job.if === "${{ github.event_name == 'pull_request' }}", `${filename}/${id}: required PR job must not be skipped by an if condition.`);
252
+ requireThat(!job['continue-on-error'] && !job.uses, `${filename}/${id}: required jobs must have verifiable local steps and must not allow failure.`);
253
+ if (checked.has(id))
254
+ return;
255
+ checked.add(id);
256
+ const needs = job.needs === undefined ? [] : Array.isArray(job.needs) ? job.needs : [job.needs];
257
+ for (const dependency of needs)
258
+ requiredJob(dependency, jobs[dependency], false);
259
+ if (!testsRequired)
260
+ return;
261
+ const steps = job.steps || [];
262
+ const installed = steps.findIndex(step => directCommand(step, installCommand) && unconditional(step.if) && !step['continue-on-error']);
263
+ const tested = steps.findIndex(step => directCommand(step, testCommand) && unconditional(step.if) && !step['continue-on-error']);
264
+ const policy = steps.findIndex(step => directCommand(step, /^(?:peacekeeper|npm exec --no -- peacekeeper|node (?:\.\/)?(?:node_modules\/@jakobm\/peacekeeper\/)?(?:dist\/)?bin\/peacekeeper\.js) verify-release-protection$/u)
265
+ && unconditional(step.if) && !step['continue-on-error'] && step.env?.GH_TOKEN);
266
+ if (policy > installed && installed >= 0 && policy < tested && config.git.releaseRequiredChecks.includes(job.name || id))
267
+ policyJobs += 1;
268
+ requireThat(installed >= 0 && tested > installed, `${filename}/${id}: run unconditional npm ci before npm test, npm run test:<name>, or npm pack --dry-run (without continue-on-error).`);
269
+ }
270
+ for (const name of required) {
271
+ const matching = Object.entries(jobs)
272
+ .filter(([id, job]) => (job.name || id) === name);
273
+ if (!requireThat(matching.length === 1 && !name.includes('${{'), `${filename}: required job ${name} must have a unique static name. Match a job name (or ID when name is absent); checks for this job are blocked.`))
274
+ continue;
275
+ // Validate the test steps even if this job was visited as a dependency.
276
+ checked.clear();
277
+ requiredJob(...matching[0], true);
278
+ }
279
+ requireThat(policyJobs > 0, `${filename}: a job in git.releaseRequiredChecks must run unconditional verify-release-protection with GH_TOKEN after npm ci and before tests.`);
280
+ });
281
+ if (published)
282
+ check('publication', () => {
283
+ requireThat(config.git.releaseRequiredChecks?.length, 'Configure git.releaseRequiredChecks for a published package.');
284
+ requireThat(config.git.releaseTestWorkflow === filename, 'projectChecks.testWorkflow must match git.releaseTestWorkflow.');
285
+ requireThat(semver.valid(manifest.version) === manifest.version && !semver.prerelease(manifest.version), 'package.json: published packages need an exact stable version.');
286
+ requireThat(['package-lock.json', 'npm-shrinkwrap.json'].some(file => fs.existsSync(path.join(root, file))), 'Commit a package lockfile before publishing.');
287
+ check('publication', () => ensureLockfilesMatch(root, manifest.version));
288
+ let publishing;
289
+ try {
290
+ publishing = inspectWorkflow(root, `v${manifest.version}`);
291
+ }
292
+ catch (error) {
293
+ requireThat(false, `${error instanceof Error ? error.message : String(error)} Publish-step checks are blocked until a supported publish workflow can be identified.`);
294
+ return;
295
+ }
296
+ const workflow = workflows.get(path.basename(publishing.path));
297
+ if (!workflow)
298
+ throw new Error(`${publishing.path}: selected publish workflow was not loaded.`);
299
+ const job = workflow.jobs.publish;
300
+ const steps = job.steps || [];
301
+ requireThat(!job['continue-on-error'], `${publishing.path}: publication must not allow failure.`);
302
+ const installed = steps.findIndex(step => directCommand(step, installCommand) && unconditional(step.if) && !step['continue-on-error']);
303
+ const verify = steps.findIndex(step => directCommand(step, verifyCommand));
304
+ const publish = steps.findIndex(step => step.run === 'npm publish');
305
+ requireThat(publish >= 0 && unconditional(steps[publish].if) && !steps[publish]['continue-on-error'], `${publishing.path}: npm publish must be unconditional and must not allow failure.`);
306
+ const publishEnvironment = { ...workflow.env, ...job.env, ...steps[publish]?.env };
307
+ requireThat(!['NPM_TOKEN', 'NODE_AUTH_TOKEN'].some(key => Object.hasOwn(publishEnvironment, key)), `${publishing.path}: remove npm publishing tokens from the publish step; use OIDC. Scope private dependency read authentication to npm ci.`);
308
+ requireThat(installed >= 0 && verify > installed && verify < publish && unconditional(steps[verify].if) && !steps[verify]['continue-on-error'], `${publishing.path}: run verify-release unconditionally before npm publish.`);
309
+ const environment = { ...workflow.env, ...job.env, ...steps[verify]?.env };
310
+ requireThat(environment.RELEASE_TAG === '${{ github.ref_name }}' && environment.GH_TOKEN, `${publishing.path}: verify-release needs RELEASE_TAG from github.ref_name and GH_TOKEN.`);
311
+ const permissions = job.permissions || workflow.permissions;
312
+ requireThat(permissions && permissions['id-token'] === 'write' && ['read', 'write'].includes(permissions.contents), `${publishing.path}: declare contents: read and id-token: write for publishing.`);
313
+ const selected = config.git.releaseTestWorkflow;
314
+ requireThat(selected === filename, 'Configure git.releaseTestWorkflow to select the checked PR workflow.');
315
+ });
316
+ return { errors, published };
317
+ }
318
+ function main({ explain = false } = {}) {
319
+ if (explain) {
320
+ runtime.stdout.write(fs.readFileSync(path.join(modulesRoot, 'projects/check-project-requirements.txt'), 'utf8'));
321
+ return;
322
+ }
323
+ output.log('Run peacekeeper check-project --explain for the complete expected project architecture and requirements.');
324
+ const { errors, published } = checkProject();
325
+ if (errors.length) {
326
+ for (const error of errors)
327
+ output.error(`FAIL ${error}`);
328
+ runtime.exitCode = 1;
329
+ }
330
+ else
331
+ output.log(`Project checks passed: package, tools, environment, hooks, CI${published ? ', publication' : ' (publishesToNpm=false; publication skipped)'}.`);
332
+ }
333
+ function run(options = {}) {
334
+ try {
335
+ main(options);
336
+ }
337
+ catch (error) {
338
+ output.error(`FAIL ${error instanceof Error ? error.message : String(error)}`);
339
+ runtime.exitCode = 1;
340
+ }
341
+ }
342
+ const api = { checkProject, run };
343
+ return api;
344
+ };
@@ -0,0 +1,186 @@
1
+ export default ({ installHooks, external: { fs, modulesRoot, packageVersion, path, projectConfigDefaults, runtime, spawnSync, url: Url, } }) => {
2
+ const { planHooks } = installHooks;
3
+ const TOOLCHAIN = Object.freeze({
4
+ node: '22.14.0',
5
+ npm: '11.21.0',
6
+ typescript: '5.9.3',
7
+ nodeTypes: '24.10.0',
8
+ });
9
+ class ProjectInputError extends Error {
10
+ }
11
+ function repositoryIdentity(repository) {
12
+ let url;
13
+ try {
14
+ url = new Url(repository);
15
+ }
16
+ catch {
17
+ throw new ProjectInputError('--repository must be a valid GitHub HTTPS URL');
18
+ }
19
+ if (url.protocol !== 'https:' || url.hostname !== 'github.com' || url.username || url.password || url.port || url.search || url.hash) {
20
+ throw new ProjectInputError('--repository must use https://github.com/owner/repo.git');
21
+ }
22
+ const match = /^\/([^/]+)\/([^/]+?)(?:\.git)?$/u.exec(url.pathname);
23
+ if (!match || !match[1] || !match[2] || match[1] === '.' || match[2] === '.') {
24
+ throw new ProjectInputError('--repository must use https://github.com/owner/repo.git');
25
+ }
26
+ return { owner: match[1], repositoryName: match[2] };
27
+ }
28
+ function normalizeOptions({ repository, directory, packageName, authorName, authorEmail, published }) {
29
+ const identity = repositoryIdentity(repository);
30
+ if (typeof directory !== 'string' || !directory.trim())
31
+ throw new ProjectInputError('--directory must be nonempty');
32
+ if (typeof authorName !== 'string' || !authorName.trim())
33
+ throw new ProjectInputError('--author-name must be nonempty');
34
+ if (typeof authorEmail !== 'string' || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(authorEmail)) {
35
+ throw new ProjectInputError('--author-email must be a valid email address');
36
+ }
37
+ if (typeof published !== 'boolean')
38
+ throw new ProjectInputError('publish state must be boolean');
39
+ if (packageName.length > 214 || !/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u.test(packageName)) {
40
+ throw new ProjectInputError('--package-name must be a valid lowercase npm package name');
41
+ }
42
+ const scoped = packageName.startsWith('@');
43
+ if (published !== scoped)
44
+ throw new ProjectInputError(`--package-name must be ${published ? 'scoped' : 'unscoped'} when --publish-to-npm is ${published}`);
45
+ if (packageName.split('/').at(-1) !== identity.repositoryName)
46
+ throw new ProjectInputError('The package basename must exactly match the repository name');
47
+ return { repository, directory, packageName, authorName, authorEmail, published, ...identity };
48
+ }
49
+ function commandRunner(command, args, options = {}) {
50
+ const result = spawnSync(command, args, { encoding: 'utf8', stdio: options.capture ? 'pipe' : 'inherit', ...options });
51
+ if (result.error)
52
+ throw result.error;
53
+ if (result.status !== 0) {
54
+ const detail = options.capture ? (result.stderr || result.stdout || '').trim() : '';
55
+ throw new Error(`${command} ${args.join(' ')} failed${detail ? `: ${detail}` : ` with exit ${result.status}`}`);
56
+ }
57
+ return result.stdout || '';
58
+ }
59
+ function json(value) { return `${JSON.stringify(value, null, 2)}\n`; }
60
+ function write(root, name, contents, mode = 0o644) {
61
+ const target = path.join(root, name);
62
+ fs.mkdirSync(path.dirname(target), { recursive: true });
63
+ fs.writeFileSync(target, contents, { mode });
64
+ }
65
+ function workflow(published) {
66
+ 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` : ''}`;
67
+ }
68
+ function publishWorkflow() {
69
+ 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`;
70
+ }
71
+ function renderTemplate(filename, replacements) {
72
+ let template = fs.readFileSync(path.join(modulesRoot, `projects/${filename}`), 'utf8');
73
+ for (const [name, value] of Object.entries(replacements)) {
74
+ template = template.replaceAll(`{{${name}}}`, value);
75
+ }
76
+ const unresolved = template.match(/\{\{[A-Z_]+\}\}/u);
77
+ if (unresolved)
78
+ throw new Error(`Unknown GitHub setup template placeholder: ${unresolved[0]}`);
79
+ return template.trim();
80
+ }
81
+ function githubSetup(repositories) {
82
+ const prefix = renderTemplate('github-setup-prefix.sh', {});
83
+ const configured = repositories.map(({ owner, repositoryName }) => renderTemplate('github-setup-repository-template.sh', {
84
+ OWNER: shellSingleQuotedContent(owner),
85
+ REPOSITORY_NAME: shellSingleQuotedContent(repositoryName),
86
+ }));
87
+ const argumentsValue = repositories
88
+ .map(({ owner, repositoryName }) => `--new-repo ${shellLiteral(`${owner}/${repositoryName}`)}`)
89
+ .join(' ');
90
+ const suffix = renderTemplate('github-setup-suffix-template.sh', { NEW_REPO_ARGUMENTS: argumentsValue });
91
+ return `${[prefix, ...configured, suffix].join('\n\n')}\n\n`;
92
+ }
93
+ function shellSingleQuotedContent(value) {
94
+ return value.replaceAll("'", `'\\''`);
95
+ }
96
+ function shellLiteral(value) {
97
+ return `'${shellSingleQuotedContent(value)}'`;
98
+ }
99
+ function packageTest() {
100
+ 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`;
101
+ }
102
+ function generate(root, options) {
103
+ const version = packageVersion;
104
+ const manifest = {
105
+ name: options.packageName, version: '0.1.0', description: `${options.repositoryName} TypeScript library`,
106
+ type: 'module', ...(options.published ? {} : { private: true }),
107
+ author: { name: options.authorName, email: options.authorEmail },
108
+ repository: { type: 'git', url: `git+${options.repository}` }, license: 'MIT',
109
+ engines: { node: '>=20' }, volta: { node: TOOLCHAIN.node, npm: TOOLCHAIN.npm },
110
+ main: './dist/index.js', types: './dist/index.d.ts', exports: { '.': { types: './dist/index.d.ts', import: './dist/index.js' } },
111
+ scripts: { build: 'tsc -p tsconfig.json', typecheck: 'tsc -p tsconfig.json --noEmit', test: 'peacekeeper run-tests', 'test:unit': 'node --test test/*.test.js',
112
+ ...(options.published ? { 'test:package': 'node scripts/test-package.cjs', release: 'peacekeeper release' } : {}) },
113
+ devDependencies: { '@jakobm/peacekeeper': version, '@types/node': TOOLCHAIN.nodeTypes, typescript: TOOLCHAIN.typescript },
114
+ ...(options.published ? { files: ['dist/'], publishConfig: { access: 'public', registry: 'https://registry.npmjs.org/' } } : {}),
115
+ };
116
+ write(root, 'package.json', json(manifest));
117
+ 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'] }));
118
+ write(root, 'src/index.ts', "export function hello(): string {\n return 'hello world';\n}\n");
119
+ 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`);
120
+ if (options.published)
121
+ write(root, 'scripts/test-package.cjs', packageTest().replace('${PACKAGE_NAME}', options.packageName));
122
+ const defaults = JSON.parse(JSON.stringify(projectConfigDefaults));
123
+ defaults.publishesToNpm = options.published;
124
+ defaults.git.requiredApprover = options.owner;
125
+ defaults.tests.commands = ['npm run typecheck', 'npm run build', 'npm run test:unit', ...(options.published ? ['npm run test:package'] : [])];
126
+ defaults.tests.npmTestUsesRunner = true;
127
+ write(root, 'peacekeeper.config.json', json(defaults));
128
+ write(root, '.codex/hooks.json', json(planHooks({}).document));
129
+ const prefix = fs.readFileSync(path.join(modulesRoot, 'projects/codex-setup-prefix.sh'), 'utf8');
130
+ write(root, '.codex/environments/environment.toml', `version = 1\nname = ${JSON.stringify(options.repositoryName)}\n\n[setup]\nscript = '''\n${prefix}'''\n`);
131
+ write(root, '.github/workflows/test.yml', workflow(options.published));
132
+ write(root, '.github/CODEOWNERS', `* @${options.owner}\n`);
133
+ if (options.published)
134
+ write(root, '.github/workflows/publish.yml', publishWorkflow());
135
+ write(root, '.gitignore', 'node_modules/\n*.tgz\ntmp/\n');
136
+ write(root, 'README.md', `# ${options.repositoryName}\n\nA TypeScript library generated by Peacekeeper.\n\n## API\n\n\`hello()\` returns \`"hello world"\`.\n`);
137
+ 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`);
138
+ write(root, 'setup-github-config.sh', githubSetup([options]), 0o755);
139
+ }
140
+ function createProject(options, dependencies = {}) {
141
+ const run = dependencies.run || commandRunner;
142
+ const voltaHome = runtime.env.VOLTA_HOME;
143
+ const volta = voltaHome && fs.existsSync(path.join(voltaHome, 'bin', 'volta'))
144
+ ? path.join(voltaHome, 'bin', 'volta') : 'volta';
145
+ const npm = args => run(volta, ['run', '--node', TOOLCHAIN.node, '--npm', TOOLCHAIN.npm, 'npm', ...args], { cwd: normalized });
146
+ const target = path.resolve(options.directory);
147
+ if (fs.existsSync(target))
148
+ throw new Error(`Destination already exists: ${target}`);
149
+ const parent = path.dirname(target);
150
+ let realParent;
151
+ try {
152
+ realParent = fs.realpathSync(parent);
153
+ }
154
+ catch {
155
+ throw new Error(`Destination parent does not exist: ${parent}`);
156
+ }
157
+ const normalized = path.join(realParent, path.basename(target));
158
+ if (fs.existsSync(normalized))
159
+ throw new Error(`Destination already exists after path normalization: ${normalized}`);
160
+ const refs = run('git', ['ls-remote', options.repository], { capture: true }).trim();
161
+ if (refs)
162
+ throw new Error('The repository is not empty; refusing to create a project');
163
+ fs.mkdirSync(normalized);
164
+ try {
165
+ run('git', ['init', '--initial-branch=main'], { cwd: normalized });
166
+ run('git', ['remote', 'add', 'origin', options.repository], { cwd: normalized });
167
+ generate(normalized, options);
168
+ npm(['install', '--ignore-scripts']);
169
+ npm(['run', 'build']);
170
+ npm(['run', 'typecheck']);
171
+ npm(['test']);
172
+ run('bash', ['-n', 'setup-github-config.sh'], { cwd: normalized });
173
+ if (run('git', ['ls-remote', options.repository], { capture: true }).trim())
174
+ throw new Error('The repository gained refs while the project was being created');
175
+ run('git', ['add', '--all'], { cwd: normalized });
176
+ run('git', ['-c', `user.name=${options.authorName}`, '-c', `user.email=${options.authorEmail}`, 'commit', '-m', 'Initial project'], { cwd: normalized });
177
+ run('git', ['push', '--set-upstream', 'origin', 'main:main'], { cwd: normalized });
178
+ }
179
+ catch (error) {
180
+ throw new Error(`${error instanceof Error ? error.message : String(error)}. Inspect or remove ${normalized} before retrying.`);
181
+ }
182
+ return { directory: normalized, packageName: options.packageName };
183
+ }
184
+ const api = { TOOLCHAIN, ProjectInputError, createProject, generate, githubSetup, normalizeOptions, repositoryIdentity };
185
+ return api;
186
+ };
@@ -0,0 +1,19 @@
1
+ export default ({ createProjectCore, external: { runtime } }) => {
2
+ const { createProject, normalizeOptions } = createProjectCore;
3
+ async function main(input) {
4
+ const options = normalizeOptions(input);
5
+ const result = createProject(options);
6
+ runtime.stdout.write(`Created ${result.packageName} at ${result.directory}\n`);
7
+ runtime.stdout.write(`Next: run ${result.directory}/setup-github-config.sh.\n`);
8
+ }
9
+ async function run(options) {
10
+ try {
11
+ await main(options);
12
+ }
13
+ catch (error) {
14
+ runtime.stderr.write(`Error: ${error instanceof Error ? error.message : String(error)}\n`);
15
+ runtime.exitCode = 1;
16
+ }
17
+ }
18
+ return { run };
19
+ };
@@ -0,0 +1,13 @@
1
+ export default ({ createProjectCore, external: { runtime } }) => {
2
+ const { githubSetup, repositoryIdentity } = createProjectCore;
3
+ function run({ repository: repositories }) {
4
+ try {
5
+ runtime.stdout.write(githubSetup(repositories.map(repositoryIdentity)));
6
+ }
7
+ catch (error) {
8
+ runtime.stderr.write(`Error: ${error instanceof Error ? error.message : String(error)}\n`);
9
+ runtime.exitCode = 1;
10
+ }
11
+ }
12
+ return { run };
13
+ };
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ # Verify GitHub authentication.
5
+ gh auth status