@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,265 @@
1
+ /**
2
+ * Queue targeted cleanup for the branch used by a Codex session that ended.
3
+ *
4
+ * SessionEnd hooks have a maximum runtime of three seconds, so the hook process
5
+ * captures the worktree identity and launches a detached worker. The worker
6
+ * removes only that worktree and branch, and only when the captured branch tip
7
+ * is still fully merged into the configured remote default branch.
8
+ */
9
+ export default ({ configuration, logScriptInvocation: invocation, maintenance, external: { buffer, clock, executablePath, fs, output, path, runtime, spawn, spawnSync } }) => {
10
+ const { projectConfig } = configuration;
11
+ const { applyPlan, buildPlan, listWorktrees } = maintenance;
12
+ const { isPrimaryWorktree, logScriptInvocation, sourceRepositoryRoot } = invocation;
13
+ const LOCK_MAX_AGE_MS = 10 * 60 * 1000;
14
+ const LOCK_WAIT_MS = 30 * 1000;
15
+ function runGit(args, options = {}) {
16
+ const result = spawnSync('git', args, {
17
+ cwd: options.cwd,
18
+ encoding: 'utf8',
19
+ stdio: ['ignore', 'pipe', 'pipe'],
20
+ });
21
+ if (result.status !== 0) {
22
+ const detail = result.stderr?.trim() || result.stdout?.trim();
23
+ throw new Error(detail || `git ${args.join(' ')} failed`);
24
+ }
25
+ return result.stdout.trim();
26
+ }
27
+ function tryGit(args, cwd) {
28
+ const result = spawnSync('git', args, {
29
+ cwd,
30
+ encoding: 'utf8',
31
+ stdio: ['ignore', 'pipe', 'pipe'],
32
+ });
33
+ return result.status === 0 ? result.stdout.trim() : null;
34
+ }
35
+ function samePath(first, second) {
36
+ try {
37
+ return fs.realpathSync(first) === fs.realpathSync(second);
38
+ }
39
+ catch {
40
+ return path.resolve(first) === path.resolve(second);
41
+ }
42
+ }
43
+ function captureWorktreeTarget(cwd, sessionId = null) {
44
+ if (typeof cwd !== 'string' || isPrimaryWorktree(cwd)) {
45
+ return null;
46
+ }
47
+ const { defaultBranch } = projectConfig(cwd).git;
48
+ const branch = tryGit(['symbolic-ref', '--quiet', '--short', 'HEAD'], cwd);
49
+ if (!branch || branch === defaultBranch) {
50
+ return null;
51
+ }
52
+ const objectId = runGit(['rev-parse', `refs/heads/${branch}`], { cwd });
53
+ const worktrees = listWorktrees(cwd);
54
+ const sessionWorktree = worktrees.find((item) => samePath(item.path, cwd));
55
+ if (!sessionWorktree || sessionWorktree.branch !== `refs/heads/${branch}`) {
56
+ return null;
57
+ }
58
+ const commonGitDirectory = runGit([
59
+ 'rev-parse',
60
+ '--path-format=absolute',
61
+ '--git-common-dir',
62
+ ], { cwd });
63
+ return {
64
+ branch,
65
+ commonGitDirectory,
66
+ objectId,
67
+ repositoryRoot: sourceRepositoryRoot(cwd),
68
+ sessionId,
69
+ worktreePath: sessionWorktree.path,
70
+ };
71
+ }
72
+ function captureTarget(event) {
73
+ if (event?.hook_event_name !== 'SessionEnd' || typeof event.cwd !== 'string') {
74
+ return null;
75
+ }
76
+ return captureWorktreeTarget(event.cwd, event.session_id || null);
77
+ }
78
+ function fastForwardLocalDefaultBranch(repositoryRoot, log) {
79
+ const primaryRoot = sourceRepositoryRoot(repositoryRoot);
80
+ const { remote, defaultBranch } = projectConfig(primaryRoot).git;
81
+ const localRef = `refs/heads/${defaultBranch}`;
82
+ const remoteRef = `refs/remotes/${remote}/${defaultBranch}`;
83
+ const localTip = tryGit(['show-ref', '--hash', '--verify', localRef], primaryRoot);
84
+ if (!localTip) {
85
+ return false;
86
+ }
87
+ const remoteTip = runGit(['rev-parse', remoteRef], {
88
+ cwd: primaryRoot,
89
+ });
90
+ if (localTip === remoteTip) {
91
+ return false;
92
+ }
93
+ if (tryGit(['merge-base', '--is-ancestor', localTip, remoteTip], primaryRoot) === null) {
94
+ log(`Keep ${defaultBranch}: it cannot fast-forward to ${remote}/${defaultBranch}.`);
95
+ return false;
96
+ }
97
+ const defaultWorktree = listWorktrees(primaryRoot)
98
+ .find((worktree) => worktree.branch === localRef);
99
+ if (defaultWorktree) {
100
+ const status = runGit(['status', '--porcelain', '--untracked-files=all'], {
101
+ cwd: defaultWorktree.path,
102
+ });
103
+ if (status !== '') {
104
+ log(`Keep ${defaultBranch}: its worktree has changes.`);
105
+ return false;
106
+ }
107
+ log(`Fast-forwarding ${defaultBranch} in its worktree to ${remote}/${defaultBranch}.`);
108
+ runGit(['merge', '--ff-only', remoteTip], { cwd: defaultWorktree.path });
109
+ return true;
110
+ }
111
+ log(`Fast-forwarding ${defaultBranch} reference to ${remote}/${defaultBranch}.`);
112
+ runGit([
113
+ 'update-ref',
114
+ '-m',
115
+ `fast-forward ${defaultBranch} to ${remote}/${defaultBranch}`,
116
+ localRef,
117
+ remoteTip,
118
+ localTip,
119
+ ], { cwd: primaryRoot });
120
+ return true;
121
+ }
122
+ function cleanupTarget(target, log = output.log) {
123
+ const { remote, defaultBranch } = projectConfig(target.repositoryRoot).git;
124
+ const branchRef = `refs/heads/${target.branch}`;
125
+ const currentObjectId = tryGit(['show-ref', '--hash', '--verify', branchRef], target.repositoryRoot);
126
+ if (currentObjectId !== target.objectId) {
127
+ log(`Skip ${target.branch}: the local branch changed after the session ended.`);
128
+ return false;
129
+ }
130
+ const currentWorktrees = listWorktrees(target.repositoryRoot);
131
+ const targetWorktree = currentWorktrees.find((item) => samePath(item.path, target.worktreePath));
132
+ if (targetWorktree) {
133
+ if (targetWorktree.branch !== branchRef) {
134
+ log(`Skip ${target.branch}: the worktree now uses a different branch.`);
135
+ return false;
136
+ }
137
+ if (Object.hasOwn(targetWorktree, 'locked')) {
138
+ log(`Skip ${target.branch}: its worktree is locked.`);
139
+ return false;
140
+ }
141
+ const worktreeObjectId = tryGit(['rev-parse', 'HEAD'], target.worktreePath);
142
+ if (worktreeObjectId !== target.objectId) {
143
+ log(`Skip ${target.branch}: the worktree HEAD changed after the session ended.`);
144
+ return false;
145
+ }
146
+ const status = runGit(['status', '--porcelain', '--untracked-files=all'], {
147
+ cwd: target.worktreePath,
148
+ });
149
+ if (status !== '') {
150
+ log(`Skip ${target.branch}: its worktree has changes.`);
151
+ return false;
152
+ }
153
+ }
154
+ log(`Fetching ${remote} before checking ${target.branch}.`);
155
+ runGit(['fetch', '--prune', remote], { cwd: target.repositoryRoot });
156
+ runGit(['show-ref', '--verify', '--quiet', `refs/remotes/${remote}/${defaultBranch}`], {
157
+ cwd: target.repositoryRoot,
158
+ });
159
+ fastForwardLocalDefaultBranch(target.repositoryRoot, log);
160
+ const item = buildPlan(target.repositoryRoot)
161
+ .find((candidate) => candidate.branch === target.branch);
162
+ if (!item?.local || item.localObjectId !== target.objectId) {
163
+ log(`Keep ${target.branch}: it is not fully merged into ${remote}/${defaultBranch}.`);
164
+ return false;
165
+ }
166
+ if (item.skipReason) {
167
+ log(`Skip ${target.branch}: ${item.skipReason}`);
168
+ return false;
169
+ }
170
+ if (item.worktrees.length > 0
171
+ && !item.worktrees.every((worktree) => samePath(worktree.path, target.worktreePath))) {
172
+ log(`Skip ${target.branch}: it is checked out in another worktree.`);
173
+ return false;
174
+ }
175
+ applyPlan(target.repositoryRoot, [item], true, log);
176
+ return true;
177
+ }
178
+ function acquireLock(lockPath) {
179
+ const deadline = clock.now() + LOCK_WAIT_MS;
180
+ while (clock.now() < deadline) {
181
+ try {
182
+ fs.mkdirSync(lockPath);
183
+ return;
184
+ }
185
+ catch (error) {
186
+ if (error.code !== 'EEXIST') {
187
+ throw error;
188
+ }
189
+ try {
190
+ const age = clock.now() - fs.statSync(lockPath).mtimeMs;
191
+ if (age > LOCK_MAX_AGE_MS) {
192
+ fs.rmSync(lockPath, { recursive: true, force: true });
193
+ continue;
194
+ }
195
+ }
196
+ catch (statError) {
197
+ if (statError.code !== 'ENOENT') {
198
+ throw statError;
199
+ }
200
+ }
201
+ clock.sleepSync(200);
202
+ }
203
+ }
204
+ throw new Error('timed out waiting for another session cleanup');
205
+ }
206
+ function runWorker(target) {
207
+ const lockPath = path.join(target.commonGitDirectory, 'cleanup-ended-session.lock');
208
+ acquireLock(lockPath);
209
+ try {
210
+ output.log(`\nSession cleanup for ${target.branch}`);
211
+ cleanupTarget(target);
212
+ }
213
+ finally {
214
+ fs.rmSync(lockPath, { recursive: true, force: true });
215
+ }
216
+ }
217
+ function launchWorker(target) {
218
+ const loggingEnabled = projectConfig(target.repositoryRoot).loggingEnabled !== false;
219
+ const logPath = loggingEnabled ? path.join(target.commonGitDirectory, 'cleanup-ended-session.log') : null;
220
+ const logFile = loggingEnabled ? fs.openSync(logPath, 'a') : 'ignore';
221
+ const payload = buffer.from(JSON.stringify(target)).toString('base64url');
222
+ const child = spawn(runtime.execPath, [executablePath, 'cleanup-ended-session', '--worker', payload], {
223
+ cwd: target.repositoryRoot,
224
+ detached: true,
225
+ stdio: ['ignore', logFile, logFile],
226
+ });
227
+ child.unref();
228
+ if (loggingEnabled)
229
+ fs.closeSync(logFile);
230
+ return { logPath, pid: child.pid };
231
+ }
232
+ function readHookEvent() {
233
+ const input = fs.readFileSync(0, 'utf8').trim();
234
+ return input === '' ? null : JSON.parse(input);
235
+ }
236
+ function main(args = []) {
237
+ logScriptInvocation();
238
+ if (args[0] === '--worker') {
239
+ const target = JSON.parse(buffer.from(args[1], 'base64url').toString('utf8'));
240
+ runWorker(target);
241
+ return;
242
+ }
243
+ const target = captureTarget(readHookEvent());
244
+ if (target) {
245
+ launchWorker(target);
246
+ }
247
+ }
248
+ function run(args = []) {
249
+ try {
250
+ main(args);
251
+ }
252
+ catch (error) {
253
+ output.error(`Error: ${error instanceof Error ? error.message : String(error)}`);
254
+ runtime.exitCode = 1;
255
+ }
256
+ }
257
+ const api = {
258
+ captureTarget,
259
+ captureWorktreeTarget,
260
+ cleanupTarget,
261
+ launchWorker,
262
+ run,
263
+ };
264
+ return api;
265
+ };
@@ -0,0 +1,7 @@
1
+ export default ({ checkpointCodexChanges, checkpointCodexSessionStart, checkpointCodexStop, cleanupEndedSession, queueMergedWorktreeCleanup }) => ({
2
+ checkpointCodexChanges: checkpointCodexChanges.run,
3
+ checkpointCodexSessionStart: checkpointCodexSessionStart.run,
4
+ checkpointCodexStop: checkpointCodexStop.run,
5
+ cleanupEndedSession: cleanupEndedSession.run,
6
+ queueMergedWorktreeCleanup: queueMergedWorktreeCleanup.run,
7
+ });
@@ -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
+ };