@jakobm/peacekeeper 0.20.0 → 0.22.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 (85) hide show
  1. package/README.md +82 -27
  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 +7 -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 +15 -13
  26. package/dist/src/modules/projects/check-project.js +344 -0
  27. package/dist/src/modules/projects/create-project-core.js +207 -0
  28. package/dist/src/modules/projects/create-project.js +19 -0
  29. package/dist/src/modules/projects/generate-github-setup.js +60 -0
  30. package/dist/src/modules/projects/github-setup-prefix.sh +5 -0
  31. package/dist/src/modules/projects/github-setup-repository-template.sh +40 -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/github-base-protection-policy.json +46 -0
  38. package/dist/src/modules/releases/github-owner-approval-policy.json +35 -0
  39. package/dist/src/modules/releases/github-policy.js +127 -0
  40. package/dist/src/modules/releases/interface.js +11 -0
  41. package/dist/src/modules/releases/release-core.js +529 -0
  42. package/dist/src/modules/releases/release-protection.js +194 -0
  43. package/dist/src/modules/releases/release.js +23 -0
  44. package/dist/src/modules/releases/verify-release-core.js +44 -0
  45. package/dist/src/modules/releases/verify-release-protection.js +25 -0
  46. package/dist/src/modules/releases/verify-release-version.js +14 -0
  47. package/dist/src/modules/releases/verify-release.js +30 -0
  48. package/dist/src/modules/testing/check-test-receipt.js +46 -0
  49. package/dist/src/modules/testing/interface.js +5 -0
  50. package/dist/src/modules/testing/receipt-state.js +99 -0
  51. package/dist/src/modules/testing/record-test-receipt.js +29 -0
  52. package/dist/src/modules/testing/run-tests.js +57 -0
  53. package/package.json +25 -9
  54. package/bin/peacekeeper.js +0 -68
  55. package/scripts/assess-release-core.js +0 -146
  56. package/scripts/assess-release.js +0 -7
  57. package/scripts/check-project.js +0 -346
  58. package/scripts/check-test-receipt.js +0 -49
  59. package/scripts/checkpoint-codex-changes.js +0 -232
  60. package/scripts/checkpoint-codex-session-start.js +0 -24
  61. package/scripts/checkpoint-codex-stop.js +0 -86
  62. package/scripts/checkpoint-instructions.js +0 -19
  63. package/scripts/cleanup-ended-session.js +0 -318
  64. package/scripts/cleanup-merged-branches.js +0 -382
  65. package/scripts/create-project-core.js +0 -278
  66. package/scripts/create-project.js +0 -26
  67. package/scripts/install-hooks.js +0 -155
  68. package/scripts/log-script-invocation.js +0 -125
  69. package/scripts/project-config.js +0 -120
  70. package/scripts/queue-merged-worktree-cleanup.js +0 -58
  71. package/scripts/receipt-state.js +0 -91
  72. package/scripts/record-test-receipt.js +0 -37
  73. package/scripts/release-core.js +0 -530
  74. package/scripts/release-protection.js +0 -135
  75. package/scripts/release.js +0 -18
  76. package/scripts/remove-empty-directories.js +0 -163
  77. package/scripts/run-tests.js +0 -66
  78. package/scripts/update-config.js +0 -41
  79. package/scripts/verify-release-core.js +0 -39
  80. package/scripts/verify-release-protection.js +0 -20
  81. package/scripts/verify-release-version.js +0 -14
  82. package/scripts/verify-release.js +0 -27
  83. /package/{scripts → dist/src/modules/configuration}/project-config-defaults.json +0 -0
  84. /package/{scripts → dist/src/modules/projects}/codex-setup-prefix.sh +0 -0
  85. /package/{scripts → dist/src/modules/releases}/assess-release-schema.json +0 -0
@@ -0,0 +1,115 @@
1
+ export default ({ configuration, external: { clock, fs, path, runtime, spawnSync } }) => {
2
+ const { projectConfig } = configuration;
3
+ function runGit(args, cwd) {
4
+ const result = spawnSync('git', args, {
5
+ cwd,
6
+ encoding: 'utf8',
7
+ stdio: ['ignore', 'pipe', 'pipe'],
8
+ });
9
+ if (result.status !== 0) {
10
+ const detail = result.stderr?.trim() || result.stdout?.trim();
11
+ throw new Error(detail || `git ${args.join(' ')} failed`);
12
+ }
13
+ return result.stdout;
14
+ }
15
+ function sourceRepositoryRoot(cwd) {
16
+ const output = runGit(['worktree', 'list', '--porcelain', '-z'], cwd);
17
+ const firstField = output.split('\0').find((field) => field.startsWith('worktree '));
18
+ if (!firstField) {
19
+ throw new Error('could not find the primary Git worktree');
20
+ }
21
+ return firstField.slice('worktree '.length);
22
+ }
23
+ function samePath(first, second) {
24
+ try {
25
+ return fs.realpathSync(first) === fs.realpathSync(second);
26
+ }
27
+ catch {
28
+ return path.resolve(first) === path.resolve(second);
29
+ }
30
+ }
31
+ function isPrimaryWorktree(cwd) {
32
+ const repositoryRoot = runGit(['rev-parse', '--show-toplevel'], cwd).trim();
33
+ return samePath(repositoryRoot, sourceRepositoryRoot(cwd));
34
+ }
35
+ function shellQuote(argument) {
36
+ if (/^[A-Za-z0-9_@%+=:,./-]+$/.test(argument)) {
37
+ return argument;
38
+ }
39
+ return `'${argument.replaceAll("'", `'"'"'`)}'`;
40
+ }
41
+ function filesystemTimestamp(date) {
42
+ return date.toISOString().replaceAll(':', '-');
43
+ }
44
+ function logScriptInvocation(options = {}) {
45
+ const argv = options.argv || runtime.argv;
46
+ const cwd = options.cwd || runtime.cwd();
47
+ const date = options.date || clock.date();
48
+ const processId = options.processId || runtime.pid;
49
+ const repositoryRoot = sourceRepositoryRoot(cwd);
50
+ const config = projectConfig(repositoryRoot);
51
+ if (config.loggingEnabled === false)
52
+ return null;
53
+ const logDirectory = path.join(repositoryRoot, config.loggingDirectory);
54
+ const scriptName = path.basename(argv[1] || 'unknown-script');
55
+ const fileName = `${filesystemTimestamp(date)}-${scriptName}-${processId}.log`;
56
+ const commandLine = argv.map(shellQuote).join(' ');
57
+ fs.mkdirSync(logDirectory, { recursive: true });
58
+ const logPath = path.join(logDirectory, fileName);
59
+ fs.writeFileSync(logPath, `${commandLine}\n${JSON.stringify({ cwd })}\n`, { flag: 'wx' });
60
+ return logPath;
61
+ }
62
+ // Only allowlisted event fields are recorded; hook payloads can contain user content.
63
+ function runLoggedCheckpointHook(buildResponse, errorPrefix) {
64
+ let logPath;
65
+ let event;
66
+ let response;
67
+ function log(action) {
68
+ try {
69
+ action();
70
+ }
71
+ catch (error) {
72
+ runtime.stderr.write(`${errorPrefix}: logging failed: ${error instanceof Error ? error.message : String(error)}\n`);
73
+ }
74
+ }
75
+ log(() => { logPath = logScriptInvocation(); });
76
+ function record(value) {
77
+ if (logPath)
78
+ log(() => fs.appendFileSync(logPath, `${JSON.stringify(value)}\n`));
79
+ }
80
+ try {
81
+ const input = fs.readFileSync(0, 'utf8').trim();
82
+ event = input === '' ? null : JSON.parse(input);
83
+ const details = {
84
+ hookEventName: event?.hook_event_name,
85
+ eventCwd: event?.cwd,
86
+ source: event?.source,
87
+ stopHookActive: event?.stop_hook_active,
88
+ };
89
+ record({ event: details });
90
+ if (typeof event?.cwd === 'string') {
91
+ const primaryWorktree = isPrimaryWorktree(event.cwd);
92
+ record({ primaryWorktree });
93
+ }
94
+ response = buildResponse(event);
95
+ }
96
+ catch (error) {
97
+ const message = `${errorPrefix}: ${error instanceof Error ? error.message : String(error)}`;
98
+ runtime.stderr.write(`${message}\n`);
99
+ runtime.exitCode = 2;
100
+ record({ error: message });
101
+ return;
102
+ }
103
+ record({ response });
104
+ runtime.stdout.write(`${JSON.stringify(response)}\n`);
105
+ }
106
+ const api = {
107
+ runLoggedCheckpointHook,
108
+ filesystemTimestamp,
109
+ isPrimaryWorktree,
110
+ logScriptInvocation,
111
+ shellQuote,
112
+ sourceRepositoryRoot,
113
+ };
114
+ return api;
115
+ };
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Queue targeted cleanup for the current linked feature worktree.
3
+ *
4
+ * This explicit entrypoint is intended for workflows that have already
5
+ * confirmed a pull request merge and need cleanup to start before the Codex
6
+ * task is archived. The detached worker performs the same safety checks as the
7
+ * SessionEnd hook.
8
+ */
9
+ export default ({ cleanupEndedSession, logScriptInvocation: invocation, external: { output, runtime } }) => {
10
+ const { captureWorktreeTarget, launchWorker } = cleanupEndedSession;
11
+ const { logScriptInvocation } = invocation;
12
+ function queueCurrentWorktree(cwd = runtime.cwd(), launch = launchWorker) {
13
+ const target = captureWorktreeTarget(cwd);
14
+ if (!target) {
15
+ throw new Error('the current directory must be a linked worktree on a non-default branch');
16
+ }
17
+ const job = launch(target);
18
+ return { ...job, target };
19
+ }
20
+ function main() {
21
+ logScriptInvocation();
22
+ const { logPath, pid, target } = queueCurrentWorktree();
23
+ output.log(`Queued cleanup for ${target.branch} at ${target.objectId}.`);
24
+ output.log(`Worker PID: ${pid}. Log: ${logPath}`);
25
+ }
26
+ function run() {
27
+ try {
28
+ main();
29
+ }
30
+ catch (error) {
31
+ output.error(`Error: ${error instanceof Error ? error.message : String(error)}`);
32
+ runtime.exitCode = 1;
33
+ }
34
+ }
35
+ const api = { queueCurrentWorktree, run };
36
+ return api;
37
+ };
@@ -0,0 +1,298 @@
1
+ /**
2
+ * Remove local and remote branches that are fully merged into the locally known
3
+ * the configured remote default branch. A worktree on an eligible local branch is removed first when it
4
+ * has no tracked or untracked changes.
5
+ *
6
+ * Recommended usage:
7
+ *
8
+ * npm exec --no -- peacekeeper cleanup-merged-branches # Dry-run (default).
9
+ * npm exec --no -- peacekeeper cleanup-merged-branches --dry-run # Explicit dry-run.
10
+ * npm exec --no -- peacekeeper cleanup-merged-branches --execute # Apply the displayed cleanup.
11
+ *
12
+ * Every run fetches the configured remote, including dry-runs, so the cleanup
13
+ * plan uses current remote references. Dry-run does not remove anything,
14
+ * but this fetch still updates local remote references. The script never deletes
15
+ * the configured default branch. It skips the current worktree, locked worktrees,
16
+ * and worktrees with tracked or untracked changes. Ignored files do not count as
17
+ * changes. Local and remote deletions are guarded by the exact commit IDs
18
+ * observed while building the cleanup plan, so a branch changed concurrently is
19
+ * preserved.
20
+ */
21
+ export default ({ configuration, external: { execFileSync, fs, output, path, runtime, spawnSync, } }) => {
22
+ const { projectConfig } = configuration;
23
+ function fail(message) {
24
+ output.error(`Error: ${message}`);
25
+ runtime.exit(1);
26
+ }
27
+ function runGit(args, options = {}) {
28
+ const result = spawnSync('git', args, {
29
+ cwd: options.cwd,
30
+ encoding: 'utf8',
31
+ stdio: options.stdio || ['ignore', 'pipe', 'pipe'],
32
+ });
33
+ if (result.status !== 0) {
34
+ const detail = result.stderr?.trim() || result.stdout?.trim();
35
+ throw new Error(detail || `git ${args.join(' ')} failed`);
36
+ }
37
+ return result.stdout;
38
+ }
39
+ function mergedBranches(repositoryRoot, namespace) {
40
+ const { remote, defaultBranch } = projectConfig(repositoryRoot).git;
41
+ const output = runGit([
42
+ 'for-each-ref',
43
+ `--merged=refs/remotes/${remote}/${defaultBranch}`,
44
+ '--format=%(refname)\t%(objectname)\t%(symref)',
45
+ namespace,
46
+ ], { cwd: repositoryRoot });
47
+ return output
48
+ .trimEnd()
49
+ .split('\n')
50
+ .filter(Boolean)
51
+ .map((line) => line.split('\t'))
52
+ .filter(([, , symbolicTarget]) => !symbolicTarget)
53
+ .map(([refName, objectId]) => ({ refName, objectId }));
54
+ }
55
+ function listWorktrees(repositoryRoot) {
56
+ const fields = runGit(['worktree', 'list', '--porcelain', '-z'], {
57
+ cwd: repositoryRoot,
58
+ }).split('\0');
59
+ const worktrees = [];
60
+ let current = null;
61
+ for (const field of fields) {
62
+ if (field === '') {
63
+ if (current) {
64
+ worktrees.push(current);
65
+ current = null;
66
+ }
67
+ continue;
68
+ }
69
+ const separator = field.indexOf(' ');
70
+ const key = separator === -1 ? field : field.slice(0, separator);
71
+ const value = separator === -1 ? '' : field.slice(separator + 1);
72
+ if (key === 'worktree') {
73
+ current = { path: value };
74
+ }
75
+ else if (current) {
76
+ current[key] = value;
77
+ }
78
+ }
79
+ return worktrees;
80
+ }
81
+ function samePath(first, second) {
82
+ try {
83
+ return fs.realpathSync(first) === fs.realpathSync(second);
84
+ }
85
+ catch {
86
+ return path.resolve(first) === path.resolve(second);
87
+ }
88
+ }
89
+ function branchNameFromLocalRef(refName) {
90
+ return refName.slice('refs/heads/'.length);
91
+ }
92
+ function branchNameFromRemoteRef(refName, remote) {
93
+ return refName.slice(`refs/remotes/${remote}/`.length);
94
+ }
95
+ function buildPlan(repositoryRoot) {
96
+ const { remote, defaultBranch } = projectConfig(repositoryRoot).git;
97
+ const localBranches = new Map(mergedBranches(repositoryRoot, 'refs/heads')
98
+ .map(({ refName, objectId }) => [branchNameFromLocalRef(refName), objectId]));
99
+ const remoteBranches = new Map(mergedBranches(repositoryRoot, `refs/remotes/${remote}`)
100
+ .map(({ refName, objectId }) => [branchNameFromRemoteRef(refName, remote), objectId])
101
+ .filter(([branch]) => branch !== 'HEAD'));
102
+ localBranches.delete(defaultBranch);
103
+ remoteBranches.delete(defaultBranch);
104
+ const currentRoot = runGit(['rev-parse', '--show-toplevel'], {
105
+ cwd: repositoryRoot,
106
+ }).trim();
107
+ const worktrees = listWorktrees(repositoryRoot);
108
+ const names = [...new Set([...localBranches.keys(), ...remoteBranches.keys()])].sort();
109
+ return names.map((branch) => {
110
+ const branchWorktrees = localBranches.has(branch)
111
+ ? worktrees.filter((worktree) => worktree.branch === `refs/heads/${branch}`)
112
+ : [];
113
+ let skipReason = null;
114
+ for (const worktree of branchWorktrees) {
115
+ if (samePath(worktree.path, currentRoot)) {
116
+ skipReason = `it is checked out in the current worktree: ${worktree.path}`;
117
+ break;
118
+ }
119
+ if (Object.hasOwn(worktree, 'locked')) {
120
+ skipReason = `its worktree is locked: ${worktree.path}`;
121
+ break;
122
+ }
123
+ try {
124
+ const status = runGit(['status', '--porcelain', '--untracked-files=all'], { cwd: worktree.path });
125
+ if (status !== '') {
126
+ skipReason = `its worktree has changes: ${worktree.path}`;
127
+ break;
128
+ }
129
+ }
130
+ catch (error) {
131
+ skipReason = `its worktree could not be inspected: ${worktree.path} (${error instanceof Error ? error.message : String(error)})`;
132
+ break;
133
+ }
134
+ }
135
+ return {
136
+ branch,
137
+ local: localBranches.has(branch),
138
+ localObjectId: localBranches.get(branch),
139
+ remote: remoteBranches.has(branch),
140
+ remoteObjectId: remoteBranches.get(branch),
141
+ worktrees: branchWorktrees,
142
+ skipReason,
143
+ };
144
+ });
145
+ }
146
+ function printAction(execute, dryRunText, executeText, log) {
147
+ log(execute ? executeText : `Would ${dryRunText}`);
148
+ }
149
+ function localPlanChangedReason(repositoryRoot, item) {
150
+ if (!item.local)
151
+ return null;
152
+ try {
153
+ const branchRef = `refs/heads/${item.branch}`;
154
+ const tip = runGit(['rev-parse', '--verify', branchRef], { cwd: repositoryRoot }).trim();
155
+ if (tip !== item.localObjectId)
156
+ return 'its local branch changed after planning';
157
+ const current = listWorktrees(repositoryRoot);
158
+ const attached = current.filter((worktree) => worktree.branch === branchRef);
159
+ if (attached.length !== item.worktrees.length)
160
+ return 'its worktrees changed after planning';
161
+ for (const planned of item.worktrees) {
162
+ const worktree = current.find((candidate) => samePath(candidate.path, planned.path));
163
+ if (!worktree || worktree.branch !== branchRef || worktree.HEAD !== item.localObjectId) {
164
+ return `its worktree changed after planning: ${planned.path}`;
165
+ }
166
+ if (Object.hasOwn(worktree, 'locked'))
167
+ return `its worktree is locked: ${planned.path}`;
168
+ if (samePath(worktree.path, repositoryRoot))
169
+ return `it is checked out in the current worktree: ${planned.path}`;
170
+ if (runGit(['status', '--porcelain', '--untracked-files=all'], { cwd: planned.path }) !== '') {
171
+ return `its worktree has changes: ${planned.path}`;
172
+ }
173
+ }
174
+ }
175
+ catch (error) {
176
+ return `its local state could not be verified: ${error instanceof Error ? error.message : String(error)}`;
177
+ }
178
+ return null;
179
+ }
180
+ function applyPlan(repositoryRoot, plan, execute, log = output.log) {
181
+ const { remote } = projectConfig(repositoryRoot).git;
182
+ let removedWorktrees = 0;
183
+ let deletedLocalBranches = 0;
184
+ let deletedRemoteBranches = 0;
185
+ let skippedBranches = 0;
186
+ items: for (const item of plan) {
187
+ const skipReason = item.skipReason || (execute && localPlanChangedReason(repositoryRoot, item));
188
+ if (skipReason) {
189
+ log(`Skip ${item.branch}: ${skipReason}`);
190
+ skippedBranches += 1;
191
+ continue;
192
+ }
193
+ for (const [index, worktree] of item.worktrees.entries()) {
194
+ printAction(execute, `remove worktree ${worktree.path} (branch ${item.branch})`, `Removing worktree ${worktree.path} (branch ${item.branch})`, log);
195
+ if (execute) {
196
+ const changedReason = localPlanChangedReason(repositoryRoot, {
197
+ ...item, worktrees: item.worktrees.slice(index),
198
+ });
199
+ if (changedReason) {
200
+ log(`Skip ${item.branch}: ${changedReason}`);
201
+ skippedBranches += 1;
202
+ continue items;
203
+ }
204
+ runGit(['worktree', 'remove', worktree.path], { cwd: repositoryRoot });
205
+ }
206
+ removedWorktrees += 1;
207
+ }
208
+ if (item.local) {
209
+ printAction(execute, `delete local branch ${item.branch}`, `Deleting local branch ${item.branch}`, log);
210
+ if (execute) {
211
+ const changedReason = localPlanChangedReason(repositoryRoot, { ...item, worktrees: [] });
212
+ if (changedReason) {
213
+ log(`Skip ${item.branch}: ${changedReason}`);
214
+ skippedBranches += 1;
215
+ continue;
216
+ }
217
+ runGit([
218
+ 'update-ref',
219
+ '-d',
220
+ `refs/heads/${item.branch}`,
221
+ item.localObjectId,
222
+ ], { cwd: repositoryRoot });
223
+ const configResult = spawnSync('git', ['config', '--remove-section', `branch.${item.branch}`], { cwd: repositoryRoot, encoding: 'utf8' });
224
+ if (configResult.status !== 0 && configResult.status !== 5) {
225
+ output.warn(`Warning: could not remove configuration for branch ${item.branch}: `
226
+ + configResult.stderr.trim());
227
+ }
228
+ }
229
+ deletedLocalBranches += 1;
230
+ }
231
+ if (item.remote) {
232
+ printAction(execute, `delete remote branch ${remote}/${item.branch}`, `Deleting remote branch ${remote}/${item.branch}`, log);
233
+ if (execute) {
234
+ runGit([
235
+ 'push',
236
+ `--force-with-lease=refs/heads/${item.branch}:${item.remoteObjectId}`,
237
+ remote,
238
+ `:refs/heads/${item.branch}`,
239
+ ], {
240
+ cwd: repositoryRoot,
241
+ });
242
+ }
243
+ deletedRemoteBranches += 1;
244
+ }
245
+ }
246
+ log('');
247
+ log(`${execute ? 'Removed' : 'Would remove'} ${removedWorktrees} worktree(s), `
248
+ + `${deletedLocalBranches} local branch(es), and ${deletedRemoteBranches} remote branch(es).`);
249
+ if (skippedBranches > 0) {
250
+ log(`Skipped ${skippedBranches} branch(es).`);
251
+ }
252
+ if (!execute) {
253
+ log('');
254
+ log('To apply this cleanup, run:');
255
+ log(' npm exec --no -- peacekeeper cleanup-merged-branches --execute');
256
+ }
257
+ }
258
+ function run({ execute = false } = {}) {
259
+ try {
260
+ execFileSync('git', ['--version'], { stdio: 'ignore' });
261
+ }
262
+ catch {
263
+ fail('required command not found: git');
264
+ }
265
+ let repositoryRoot;
266
+ try {
267
+ repositoryRoot = runGit(['rev-parse', '--show-toplevel']).trim();
268
+ runGit(['remote', 'get-url', projectConfig(repositoryRoot).git.remote], { cwd: repositoryRoot });
269
+ }
270
+ catch (error) {
271
+ fail(error instanceof Error ? error.message : String(error));
272
+ }
273
+ output.log(execute ? 'Execute mode.' : 'Dry-run mode. No worktrees or branches will be removed.');
274
+ output.log(`Fetching and pruning ${projectConfig(repositoryRoot).git.remote} before building the cleanup plan.`);
275
+ try {
276
+ const { remote, defaultBranch } = projectConfig(repositoryRoot).git;
277
+ runGit(['fetch', '--prune', remote], { cwd: repositoryRoot });
278
+ runGit(['show-ref', '--verify', '--quiet', `refs/remotes/${remote}/${defaultBranch}`], {
279
+ cwd: repositoryRoot,
280
+ });
281
+ }
282
+ catch (error) {
283
+ fail(error instanceof Error ? error.message : String(error));
284
+ }
285
+ output.log('');
286
+ try {
287
+ const plan = buildPlan(repositoryRoot);
288
+ applyPlan(repositoryRoot, plan, execute);
289
+ }
290
+ catch (error) {
291
+ fail(error instanceof Error ? error.message : String(error));
292
+ }
293
+ }
294
+ const api = {
295
+ applyPlan, buildPlan, listWorktrees, run,
296
+ };
297
+ return api;
298
+ };
@@ -0,0 +1,7 @@
1
+ export default ({ cleanupMergedBranches, removeEmptyDirectories }) => ({
2
+ applyPlan: cleanupMergedBranches.applyPlan,
3
+ buildPlan: cleanupMergedBranches.buildPlan,
4
+ cleanupMergedBranches: cleanupMergedBranches.run,
5
+ listWorktrees: cleanupMergedBranches.listWorktrees,
6
+ removeEmptyDirectories: removeEmptyDirectories.main,
7
+ });
@@ -0,0 +1,114 @@
1
+ export default ({ external: { execFileSync, fs, output, path, runtime, } }) => {
2
+ const PROTECTED_ROOT_DIRECTORIES = new Set(['.git', 'node_modules', 'tmp']);
3
+ function findRepositoryRoot(cwd) {
4
+ return execFileSync('git', ['-C', cwd, 'rev-parse', '--show-toplevel'], {
5
+ encoding: 'utf8',
6
+ }).trim();
7
+ }
8
+ function listPresentFiles(root) {
9
+ const output = execFileSync('git', [
10
+ '-C',
11
+ root,
12
+ 'ls-files',
13
+ '-z',
14
+ '--cached',
15
+ '--others',
16
+ '--exclude-standard',
17
+ ], { encoding: 'buffer' });
18
+ return output
19
+ .toString('utf8')
20
+ .split('\0')
21
+ .filter(Boolean)
22
+ .filter((relativePath) => fs.lstatSync(path.join(root, relativePath), {
23
+ throwIfNoEntry: false,
24
+ }));
25
+ }
26
+ function requiredDirectories(root, files) {
27
+ const required = new Set();
28
+ for (const file of files) {
29
+ const absolutePath = path.join(root, file);
30
+ let directory = fs.lstatSync(absolutePath).isDirectory()
31
+ ? file.replace(/\/+$/u, '')
32
+ : path.posix.dirname(file);
33
+ while (directory !== '.') {
34
+ required.add(directory);
35
+ directory = path.posix.dirname(directory);
36
+ }
37
+ }
38
+ return required;
39
+ }
40
+ function findEmptyDirectories(root) {
41
+ const required = requiredDirectories(root, listPresentFiles(root));
42
+ function visit(absoluteDirectory, relativeDirectory) {
43
+ // A nested repository owns its contents, even when its parent is ignored.
44
+ if (relativeDirectory !== '' && fs.lstatSync(path.join(absoluteDirectory, '.git'), {
45
+ throwIfNoEntry: false,
46
+ }))
47
+ return { keep: true, directories: [] };
48
+ let keep = relativeDirectory === '' || required.has(relativeDirectory);
49
+ const directories = [];
50
+ for (const entry of fs.readdirSync(absoluteDirectory, {
51
+ withFileTypes: true,
52
+ })) {
53
+ if (!entry.isDirectory())
54
+ continue;
55
+ if (relativeDirectory === ''
56
+ && PROTECTED_ROOT_DIRECTORIES.has(entry.name))
57
+ continue;
58
+ const relativePath = relativeDirectory
59
+ ? `${relativeDirectory}/${entry.name}`
60
+ : entry.name;
61
+ const absolutePath = path.join(absoluteDirectory, entry.name);
62
+ const child = visit(absolutePath, relativePath);
63
+ keep ||= child.keep;
64
+ directories.push(...child.directories);
65
+ }
66
+ return { keep, directories: keep ? directories : [relativeDirectory] };
67
+ }
68
+ return visit(root, '').directories;
69
+ }
70
+ function removeEmptyDirectories(root, directories) {
71
+ for (const directory of directories) {
72
+ fs.rmSync(path.join(root, directory), { recursive: true });
73
+ }
74
+ }
75
+ function run({ execute = false, cwd, log }) {
76
+ const root = findRepositoryRoot(cwd);
77
+ const directories = findEmptyDirectories(root);
78
+ if (directories.length === 0) {
79
+ log('No empty directories found.');
80
+ return;
81
+ }
82
+ if (execute) {
83
+ removeEmptyDirectories(root, directories);
84
+ for (const directory of directories)
85
+ log(`Removed ${directory}`);
86
+ return;
87
+ }
88
+ for (const directory of directories)
89
+ log(`Would remove ${directory}`);
90
+ log('');
91
+ log('To remove these directories, run:');
92
+ log(' npm exec --no -- peacekeeper remove-empty-directories --execute');
93
+ }
94
+ function main({ execute = false } = {}) {
95
+ try {
96
+ run({
97
+ execute,
98
+ cwd: runtime.cwd(),
99
+ log: output.log,
100
+ });
101
+ }
102
+ catch (error) {
103
+ output.error(`Error: ${error instanceof Error ? error.message : String(error)}`);
104
+ runtime.exitCode = 1;
105
+ }
106
+ }
107
+ const api = {
108
+ findEmptyDirectories,
109
+ main,
110
+ removeEmptyDirectories,
111
+ run,
112
+ };
113
+ return api;
114
+ };
@@ -80,7 +80,7 @@ Toolchain: package.json and all Node-based CI jobs
80
80
  Codex worktree environment
81
81
  .codex/environments/environment.toml must be valid TOML with version = 1.
82
82
  setup.script must start character-for-character with the contents of the
83
- bundled scripts/codex-setup-prefix.sh reference file, including comments,
83
+ bundled src/modules/projects/codex-setup-prefix.sh reference file, including comments,
84
84
  whitespace and the newline after "# Add custom project setup below".
85
85
  Comparison uses the parsed TOML string, not the file's quoting style.
86
86
  Arbitrary custom setup may follow, or the script may end at that newline.
@@ -203,8 +203,8 @@ Publication: publishesToNpm=true
203
203
  Accepted direct verification commands:
204
204
  peacekeeper verify-release
205
205
  npm exec --no -- peacekeeper verify-release
206
- node bin/peacekeeper.js verify-release
207
- node node_modules/@jakobm/peacekeeper/bin/peacekeeper.js verify-release
206
+ node dist/bin/peacekeeper.js verify-release
207
+ node node_modules/@jakobm/peacekeeper/dist/bin/peacekeeper.js verify-release
208
208
  The node paths may also start with ./.
209
209
 
210
210
  Verification must receive these environment inputs, directly on the step or
@@ -253,11 +253,12 @@ Online release policy and GitHub token setup
253
253
  Enable "Automatically delete head branches" (delete_branch_on_merge=true) in
254
254
  the repository settings. The online release policy commands require it.
255
255
 
256
- Configure the default branch from git.defaultBranch with every exact job name
256
+ Configure the default branch from git.defaultBranch with exactly the job names
257
257
  in git.releaseRequiredChecks mandatory and "Require branches to be up to date
258
258
  before merging" enabled. The base policy may use either classic branch
259
259
  protection with strict status checks or active branch rulesets requiring
260
- strict status checks. Its bypass configuration must be inspected manually.
260
+ strict status checks. Its bypass configuration is compared when GitHub exposes
261
+ it and otherwise must be inspected manually.
261
262
  Merge queues are not currently an alternative to this strict policy. For the
262
263
  matrix example, also require its matrix checks as described above.
263
264
 
@@ -267,8 +268,8 @@ Online release policy and GitHub token setup
267
268
  git.requiredApprover, with actor_type User and bypass_mode pull_request. The
268
269
  configured account must be the personal repository owner. This approval-only
269
270
  bypass lets that owner merge a PR they authored, but the separate base policy
270
- still prevents direct pushes and requires strict CI. Any other bypass violates
271
- the policy and must be caught by the manual inspection.
271
+ still prevents direct pushes and requires strict CI. Any other visible bypass
272
+ violates the policy; inspect it manually when GitHub omits the actors.
272
273
 
273
274
  Create a fine-grained GitHub PAT or GitHub App installation token with access
274
275
  to this repository and these repository permissions:
@@ -277,7 +278,7 @@ Online release policy and GitHub token setup
277
278
  Pull requests: read
278
279
  Actions: read
279
280
  GitHub exposes bypass actors only to callers with write access to the ruleset.
280
- Peacekeeper therefore does not verify them and prints this warning instead:
281
+ Peacekeeper verifies them when exposed and otherwise prints this warning:
281
282
  Cannot verify bypass users unless given write access. Run a manual check
282
283
  instead; available as a gist.
283
284
 
@@ -402,16 +403,17 @@ Default-branch GitHub policy chain
402
403
  This applies to private projects too; configure nonempty releaseRequiredChecks.
403
404
 
404
405
  Online verification reads the actual GitHub default branch and requires PRs,
405
- strict mandatory configured checks, and merge commits only. It also verifies
406
- the separate owner-approval ruleset described above, except for its bypass
407
- actors. Enable
406
+ exactly the configured strict mandatory checks, and merge commits only. It also
407
+ verifies the separate owner-approval ruleset described above. Bypass actors are
408
+ compared when GitHub returns them; otherwise verification warns that they are
409
+ unknown. Enable
408
410
  repository allow_auto_merge; this only offers per-PR opt-in and does not
409
411
  activate auto-merge for any PR.
410
412
  Restrict merge methods either repository-wide (merge enabled, squash and rebase
411
413
  disabled) or with a default-branch PR ruleset allowing only merge. Other branches
412
414
  are not checked. Linear-history rules or PR rules excluding merge are errors.
413
- Base PR requirements, like status checks, require active rules. Inspect all
414
- bypass actors manually.
415
+ Base PR requirements, like status checks, require active rules. Inspect bypass
416
+ actors manually only when GitHub omits them from the response.
415
417
  Existing automatic head-branch deletion requirements still apply.
416
418
 
417
419
  Missing CI is detected on the next local npm test. GitHub settings are checked