@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
@@ -1,155 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- const fs = require('node:fs');
4
- const path = require('node:path');
5
- const { repositoryRoot } = require('./project-config');
6
-
7
- const DEFINITIONS = [
8
- ['SessionStart', 'checkpoint-codex-session-start', 30, 'Loading Codex checkpoint instructions'],
9
- ['Stop', 'checkpoint-codex-stop', 30, 'Checking for an uncommitted Codex checkpoint'],
10
- ['SessionEnd', 'cleanup-ended-session', 3, 'Scheduling merged branch cleanup'],
11
- ];
12
- const COMMANDS = DEFINITIONS.map(([, command]) => command);
13
-
14
- // Recognize complete, standalone invocations only. Shell composition, arguments,
15
- // environment assignments, and wrappers require inspection instead of replacement.
16
- function classifyCommand(command) {
17
- if (typeof command !== 'string') return 'other';
18
- const related = /peacekeeper|checkpoint-codex-(?:stop|session-start)|cleanup-ended-session/.test(command);
19
- if (!related) return 'other';
20
- const text = command.trim();
21
- const action = COMMANDS.find((name) => text.endsWith(` ${name}`) || text.endsWith(`\t${name}`));
22
- if (!action) {
23
- const legacy = /^(?:node\s+)(?:\.\/)?(?:node_modules\/@jakobm\/peacekeeper\/)?scripts\/(checkpoint-codex-stop|checkpoint-codex-session-start|cleanup-ended-session)\.js$/;
24
- return legacy.test(text) ? 'owned' : 'ambiguous';
25
- }
26
- const executable = text.slice(0, -action.length).trim();
27
- if (/^(?:peacekeeper|npm\s+exec\s+--no\s+--\s+peacekeeper|npx\s+--no-install\s+peacekeeper)$/.test(executable)) {
28
- return 'owned';
29
- }
30
- // Accept the documented Git-root resolution with optional path quotes.
31
- const gitRoot = '\\$\\(git\\s+rev-parse\\s+--show-toplevel\\)';
32
- const binPath = '(?:/node_modules/@jakobm/peacekeeper)?/bin/peacekeeper\\.js';
33
- const relativePath = '(?:\\./)?(?:node_modules/@jakobm/peacekeeper/)?bin/peacekeeper\\.js';
34
- const paths = [gitRoot + binPath, relativePath];
35
- const invocations = paths.flatMap((value) => [`"${value}"`, value]);
36
- invocations.push(`'${relativePath}'`);
37
- const directPath = new RegExp(`^node\\s+(?:${invocations.join('|')})$`);
38
- if (directPath.test(executable)) return 'owned';
39
- return 'ambiguous';
40
- }
41
-
42
- function object(value) {
43
- return value !== null && typeof value === 'object' && !Array.isArray(value);
44
- }
45
-
46
- function planHooks(document, localSource = false) {
47
- if (!object(document) || (document.hooks !== undefined && !object(document.hooks))) {
48
- throw new Error('hooks.json must contain an object with an optional hooks object');
49
- }
50
- const result = structuredClone(document);
51
- result.hooks ??= {};
52
- const changes = [];
53
- for (const [event, groups] of Object.entries(result.hooks)) {
54
- if (!Array.isArray(groups)) throw new Error(`hooks.${event} must be an array`);
55
- const keptGroups = [];
56
- for (const group of groups) {
57
- if (!object(group) || !Array.isArray(group.hooks)) {
58
- throw new Error(`hooks.${event} contains an invalid hook group`);
59
- }
60
- const kept = [];
61
- for (const handler of group.hooks) {
62
- if (!object(handler)) throw new Error(`hooks.${event} contains an invalid handler`);
63
- if (classifyCommand(handler.commandWindows) !== 'other') {
64
- throw new Error(`Review Windows-specific peacekeeper hook in ${event}: ${handler.commandWindows}`);
65
- }
66
- const classification = classifyCommand(handler.command);
67
- if (classification === 'ambiguous') {
68
- throw new Error(`Review possible peacekeeper hook in ${event}: ${handler.command}`);
69
- }
70
- if (classification === 'owned') {
71
- const allowed = ['type', 'command', 'timeout', 'statusMessage'];
72
- if (handler.type !== 'command' || Object.keys(handler).some((key) => !allowed.includes(key))) {
73
- throw new Error(`Review customized peacekeeper hook in ${event}: ${handler.command}`);
74
- }
75
- changes.push(`Replace existing peacekeeper hook in ${event}`);
76
- } else {
77
- kept.push(handler);
78
- }
79
- }
80
- if (kept.length || group.hooks.length === 0) keptGroups.push({ ...group, hooks: kept });
81
- }
82
- result.hooks[event] = keptGroups;
83
- }
84
- const prefix = localSource ? '' : 'node_modules/@jakobm/peacekeeper/';
85
- for (const [event, command, timeout, statusMessage] of DEFINITIONS) {
86
- result.hooks[event] ??= [];
87
- result.hooks[event].push({ hooks: [{
88
- type: 'command',
89
- command: `node "$(git rev-parse --show-toplevel)/${prefix}bin/peacekeeper.js" ${command}`,
90
- timeout,
91
- statusMessage,
92
- }] });
93
- changes.push(`Install ${event}: ${command}`);
94
- }
95
- return { document: result, changes };
96
- }
97
-
98
- function install({ cwd = process.cwd(), dryRun = false, log = console.log } = {}) {
99
- const root = repositoryRoot(cwd);
100
- const file = path.join(root, '.codex', 'hooks.json');
101
- let original = null;
102
- try {
103
- if (fs.lstatSync(file).isSymbolicLink()) throw new Error('refusing to replace a symlink hooks.json');
104
- original = fs.readFileSync(file, 'utf8');
105
- } catch (error) {
106
- if (error.code !== 'ENOENT') throw error;
107
- }
108
- const localSource = fs.realpathSync(root) === fs.realpathSync(path.resolve(__dirname, '..'));
109
- const plan = planHooks(original === null ? {} : JSON.parse(original), localSource);
110
- const serialized = `${JSON.stringify(plan.document, null, 2)}\n`;
111
- if (original !== null && JSON.stringify(JSON.parse(original)) === JSON.stringify(plan.document)) {
112
- log('Peacekeeper hooks are already up to date.');
113
- return;
114
- }
115
- for (const change of plan.changes) log(change);
116
- if (dryRun) {
117
- log(`Would update ${file}`);
118
- return;
119
- }
120
- fs.mkdirSync(path.dirname(file), { recursive: true });
121
- const temporary = `${file}.${process.pid}.tmp`;
122
- try {
123
- fs.writeFileSync(temporary, serialized, {
124
- flag: 'wx', mode: original === null ? 0o644 : fs.statSync(file).mode & 0o777,
125
- });
126
- // Avoid overwriting edits made while constructing the plan.
127
- const current = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null;
128
- if (current !== original) throw new Error('hooks.json changed during installation; retry');
129
- fs.renameSync(temporary, file);
130
- } finally {
131
- fs.rmSync(temporary, { force: true });
132
- }
133
- log(`Updated ${file}. Review and trust the hooks with /hooks in Codex.`);
134
- }
135
-
136
- function main() {
137
- const args = process.argv.slice(2);
138
- if (args.length === 1 && ['--help', '-h'].includes(args[0])) {
139
- console.log('Usage: peacekeeper install-hooks [--dry-run]');
140
- return;
141
- }
142
- if (args.length > 1 || (args.length === 1 && args[0] !== '--dry-run')) {
143
- throw new Error('Usage: peacekeeper install-hooks [--dry-run]');
144
- }
145
- install({ dryRun: args.includes('--dry-run') });
146
- }
147
-
148
- if (require.main === module) {
149
- try { main(); } catch (error) {
150
- console.error(`Error: ${error.message}`);
151
- process.exitCode = 1;
152
- }
153
- }
154
-
155
- module.exports = { classifyCommand, planHooks, install };
@@ -1,125 +0,0 @@
1
- const { spawnSync } = require('node:child_process');
2
- const fs = require('node:fs');
3
- const path = require('node:path');
4
- const { projectConfig } = require('./project-config');
5
-
6
- function runGit(args, cwd) {
7
- const result = spawnSync('git', args, {
8
- cwd,
9
- encoding: 'utf8',
10
- stdio: ['ignore', 'pipe', 'pipe'],
11
- });
12
-
13
- if (result.status !== 0) {
14
- const detail = result.stderr?.trim() || result.stdout?.trim();
15
- throw new Error(detail || `git ${args.join(' ')} failed`);
16
- }
17
-
18
- return result.stdout;
19
- }
20
-
21
- function sourceRepositoryRoot(cwd) {
22
- const output = runGit(['worktree', 'list', '--porcelain', '-z'], cwd);
23
- const firstField = output.split('\0').find((field) => field.startsWith('worktree '));
24
-
25
- if (!firstField) {
26
- throw new Error('could not find the primary Git worktree');
27
- }
28
-
29
- return firstField.slice('worktree '.length);
30
- }
31
-
32
- function samePath(first, second) {
33
- try {
34
- return fs.realpathSync(first) === fs.realpathSync(second);
35
- } catch {
36
- return path.resolve(first) === path.resolve(second);
37
- }
38
- }
39
-
40
- function isPrimaryWorktree(cwd) {
41
- const repositoryRoot = runGit(['rev-parse', '--show-toplevel'], cwd).trim();
42
- return samePath(repositoryRoot, sourceRepositoryRoot(cwd));
43
- }
44
-
45
- function shellQuote(argument) {
46
- if (/^[A-Za-z0-9_@%+=:,./-]+$/.test(argument)) {
47
- return argument;
48
- }
49
-
50
- return `'${argument.replaceAll("'", `'"'"'`)}'`;
51
- }
52
-
53
- function filesystemTimestamp(date) {
54
- return date.toISOString().replaceAll(':', '-');
55
- }
56
-
57
- function logScriptInvocation(options = {}) {
58
- const argv = options.argv || process.argv;
59
- const cwd = options.cwd || process.cwd();
60
- const date = options.date || new Date();
61
- const processId = options.processId || process.pid;
62
- const repositoryRoot = sourceRepositoryRoot(cwd);
63
- const config = projectConfig(repositoryRoot);
64
- if (config.loggingEnabled === false) return null;
65
- const logDirectory = path.join(repositoryRoot, config.loggingDirectory);
66
- const scriptName = path.basename(argv[1] || 'unknown-script');
67
- const fileName = `${filesystemTimestamp(date)}-${scriptName}-${processId}.log`;
68
- const commandLine = argv.map(shellQuote).join(' ');
69
-
70
- fs.mkdirSync(logDirectory, { recursive: true });
71
- const logPath = path.join(logDirectory, fileName);
72
- fs.writeFileSync(logPath, `${commandLine}\n${JSON.stringify({ cwd })}\n`, { flag: 'wx' });
73
- return logPath;
74
- }
75
-
76
- // Only allowlisted event fields are recorded; hook payloads can contain user content.
77
- function runLoggedCheckpointHook(buildResponse, errorPrefix) {
78
- let logPath;
79
- let event;
80
- let response;
81
- function log(action) {
82
- try {
83
- action();
84
- } catch (error) {
85
- process.stderr.write(`${errorPrefix}: logging failed: ${error.message}\n`);
86
- }
87
- }
88
- log(() => { logPath = logScriptInvocation(); });
89
- function record(value) {
90
- if (logPath) log(() => fs.appendFileSync(logPath, `${JSON.stringify(value)}\n`));
91
- }
92
- try {
93
- const input = fs.readFileSync(0, 'utf8').trim();
94
- event = input === '' ? null : JSON.parse(input);
95
- const details = {
96
- hookEventName: event?.hook_event_name,
97
- eventCwd: event?.cwd,
98
- source: event?.source,
99
- stopHookActive: event?.stop_hook_active,
100
- };
101
- record({ event: details });
102
- if (typeof event?.cwd === 'string') {
103
- const primaryWorktree = isPrimaryWorktree(event.cwd);
104
- record({ primaryWorktree });
105
- }
106
- response = buildResponse(event);
107
- } catch (error) {
108
- const message = `${errorPrefix}: ${error.message}`;
109
- process.stderr.write(`${message}\n`);
110
- process.exitCode = 2;
111
- record({ error: message });
112
- return;
113
- }
114
- record({ response });
115
- process.stdout.write(`${JSON.stringify(response)}\n`);
116
- }
117
-
118
- module.exports = {
119
- runLoggedCheckpointHook,
120
- filesystemTimestamp,
121
- isPrimaryWorktree,
122
- logScriptInvocation,
123
- shellQuote,
124
- sourceRepositoryRoot,
125
- };
@@ -1,115 +0,0 @@
1
- const { execFileSync } = require('node:child_process');
2
- const fs = require('node:fs');
3
- const path = require('node:path');
4
-
5
- const CONFIG_FILE = 'peacekeeper.config.json';
6
-
7
- function repositoryRoot(cwd = process.cwd()) {
8
- return execFileSync('git', ['rev-parse', '--show-toplevel'], {
9
- cwd,
10
- encoding: 'utf8',
11
- }).trim();
12
- }
13
-
14
- // Kept independent of the defaults so additions require an explicit default.
15
- const CONFIG_SCHEMA = {
16
- publishesToNpm: true,
17
- git: { remote: true, defaultBranch: true, branchPrefix: true,
18
- checkpointPushRemotes: true, releaseMergeMethod: true,
19
- releaseRequiredChecks: true, releaseTestWorkflow: true },
20
- tests: { commands: true, receiptMaxAgeMinutes: true, npmTestUsesRunner: true },
21
- loggingDirectory: true,
22
- loggingEnabled: true,
23
- projectChecks: { testWorkflow: true, requiredJobs: true },
24
- };
25
-
26
- function validateShape(value, schema, location, errors) {
27
- if (value === null || typeof value !== 'object' || Array.isArray(value)) {
28
- errors.push(`${location} must be an object`);
29
- return;
30
- }
31
- for (const key of Object.keys(value)) {
32
- if (!Object.hasOwn(schema, key)) errors.push(`unknown field ${location}.${key}`);
33
- }
34
- for (const [key, child] of Object.entries(schema)) {
35
- const name = location === 'config' ? key : `${location}.${key}`;
36
- if (!Object.hasOwn(value, key)) errors.push(`missing field ${name}`);
37
- else if (child !== true) validateShape(value[key], child, name, errors);
38
- }
39
- }
40
-
41
- function requireNonemptyString(value, location, file) {
42
- if (typeof value !== 'string' || value.trim() === '') {
43
- throw new Error(`${file}: ${location} must be a nonempty string`);
44
- }
45
- }
46
-
47
- function validateConfig(config, file) {
48
- const errors = [];
49
- validateShape(config, CONFIG_SCHEMA, 'config', errors);
50
- if (errors.length) throw new Error(`${file}: ${errors.join('; ')}. Run peacekeeper update-config to add missing fields.`);
51
- if (typeof config.projectChecks.testWorkflow !== 'string' || !/^[A-Za-z0-9_-]+\.ya?ml$/u.test(config.projectChecks.testWorkflow)) {
52
- throw new Error(`${file}: projectChecks.testWorkflow must be a workflow filename`);
53
- }
54
- const jobs = config.projectChecks.requiredJobs;
55
- if (!Array.isArray(jobs) || jobs.some(job => typeof job !== 'string' || !job.trim() || job !== job.trim()) || new Set(jobs).size !== jobs.length) {
56
- throw new Error(`${file}: projectChecks.requiredJobs must contain unique nonempty job names`);
57
- }
58
-
59
- for (const field of ['remote', 'defaultBranch', 'branchPrefix']) {
60
- requireNonemptyString(config.git[field], `git.${field}`, file);
61
- }
62
- const remotes = config.git.checkpointPushRemotes;
63
- if (!Array.isArray(remotes)
64
- || remotes.some((remote) => typeof remote !== 'string' || remote.trim() === ''
65
- || remote !== remote.trim() || remote.startsWith('-'))
66
- || new Set(remotes).size !== remotes.length) {
67
- throw new Error(`${file}: git.checkpointPushRemotes must be an array of unique remote names`);
68
- }
69
- if (typeof config.git.releaseTestWorkflow !== 'string' || !/^[A-Za-z0-9_-]+\.ya?ml$/u.test(config.git.releaseTestWorkflow)) {
70
- throw new Error(`${file}: git.releaseTestWorkflow must be a workflow filename ending in .yml or .yaml`);
71
- }
72
- const checks = config.git.releaseRequiredChecks;
73
- if (!Array.isArray(checks) || checks.some(check => typeof check !== 'string' || !check.trim() || check !== check.trim()) || new Set(checks).size !== checks.length) {
74
- throw new Error(`${file}: git.releaseRequiredChecks must be an array of unique check names`);
75
- }
76
- if (!['merge', 'squash', 'rebase'].includes(config.git.releaseMergeMethod)) {
77
- throw new Error(`${file}: git.releaseMergeMethod must be merge, squash, or rebase`);
78
- }
79
- if (typeof config.publishesToNpm !== 'boolean') {
80
- throw new Error(`${file}: publishesToNpm must be a boolean`);
81
- }
82
- if (typeof config.loggingEnabled !== 'boolean') {
83
- throw new Error(`${file}: loggingEnabled must be a boolean`);
84
- }
85
- requireNonemptyString(config.loggingDirectory, 'loggingDirectory', file);
86
- if (!Array.isArray(config.tests.commands)
87
- || config.tests.commands.some((command) => typeof command !== 'string' || command.trim() === '')) {
88
- throw new Error(`${file}: tests.commands must be an array of command strings`);
89
- }
90
- if (!Number.isSafeInteger(config.tests.receiptMaxAgeMinutes)
91
- || config.tests.receiptMaxAgeMinutes < 1) {
92
- throw new Error(`${file}: tests.receiptMaxAgeMinutes must be a positive integer`);
93
- }
94
- if (typeof config.tests.npmTestUsesRunner !== 'boolean') {
95
- throw new Error(`${file}: tests.npmTestUsesRunner must be a boolean`);
96
- }
97
- }
98
-
99
- function projectConfig(cwd = process.cwd()) {
100
- const root = repositoryRoot(cwd);
101
- const file = path.join(root, CONFIG_FILE);
102
- const config = fs.existsSync(file)
103
- ? JSON.parse(fs.readFileSync(file, 'utf8'))
104
- : structuredClone(require('./project-config-defaults.json'));
105
- validateConfig(config, file);
106
- return { root, ...config };
107
- }
108
-
109
- function requireTestCommands(root) {
110
- if (!projectConfig(root).tests.commands.length) {
111
- throw new Error('Configure tests.commands before running tests or using a test receipt.');
112
- }
113
- }
114
-
115
- module.exports = { CONFIG_FILE, CONFIG_SCHEMA, validateConfig, projectConfig, repositoryRoot, requireTestCommands };
@@ -1,58 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * Queue targeted cleanup for the current linked feature worktree.
5
- *
6
- * This explicit entrypoint is intended for workflows that have already
7
- * confirmed a pull request merge and need cleanup to start before the Codex
8
- * task is archived. The detached worker performs the same safety checks as the
9
- * SessionEnd hook.
10
- */
11
-
12
- const {
13
- captureWorktreeTarget,
14
- launchWorker,
15
- } = require('./cleanup-ended-session.js');
16
- const { logScriptInvocation } = require('./log-script-invocation.js');
17
-
18
- function helpText() {
19
- return 'Usage: peacekeeper queue-merged-worktree-cleanup\n';
20
- }
21
-
22
- function queueCurrentWorktree(cwd = process.cwd(), launch = launchWorker) {
23
- const target = captureWorktreeTarget(cwd);
24
- if (!target) {
25
- throw new Error(
26
- 'the current directory must be a linked worktree on a non-default branch',
27
- );
28
- }
29
-
30
- const job = launch(target);
31
- return { ...job, target };
32
- }
33
-
34
- function main(args = process.argv.slice(2)) {
35
- if (args.includes('--help') || args.includes('-h')) {
36
- process.stdout.write(helpText());
37
- return;
38
- }
39
- if (args.length > 0) {
40
- throw new Error(`unknown argument: ${args[0]}`);
41
- }
42
-
43
- logScriptInvocation();
44
- const { logPath, pid, target } = queueCurrentWorktree();
45
- console.log(`Queued cleanup for ${target.branch} at ${target.objectId}.`);
46
- console.log(`Worker PID: ${pid}. Log: ${logPath}`);
47
- }
48
-
49
- if (require.main === module) {
50
- try {
51
- main();
52
- } catch (error) {
53
- console.error(`Error: ${error.message}`);
54
- process.exitCode = 1;
55
- }
56
- }
57
-
58
- module.exports = { helpText, queueCurrentWorktree };
@@ -1,91 +0,0 @@
1
- const { execFileSync } = require('node:child_process');
2
- const crypto = require('node:crypto');
3
- const fs = require('node:fs');
4
- const os = require('node:os');
5
- const path = require('node:path');
6
- const { repositoryRoot } = require('./project-config');
7
-
8
- const ROOT = repositoryRoot;
9
- const RECEIPT_DIRECTORY = 'peacekeeper-test-receipts';
10
- const EMPTY_TREE = '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
11
-
12
- function git(root, args) {
13
- return execFileSync('git', args, { cwd: root, maxBuffer: 10 * 1024 * 1024,
14
- stdio: ['ignore', 'pipe', 'pipe'] });
15
- }
16
-
17
- function pathsFromOutput(output) {
18
- return output.toString('utf8').split('\0').filter(Boolean);
19
- }
20
-
21
- function changedPaths(root, baseCommit) {
22
- const tracked = pathsFromOutput(git(root, [
23
- 'diff', '--no-ext-diff', '--no-textconv', '--no-renames', '--name-only', '-z', baseCommit, '--',
24
- ]));
25
- const untracked = pathsFromOutput(git(root, ['ls-files', '--others', '--exclude-standard', '-z']));
26
- return [...new Set([...tracked, ...untracked])].sort();
27
- }
28
-
29
- function fileFingerprint(root, relative) {
30
- const fullPath = path.join(root, relative);
31
- let stat;
32
- try {
33
- stat = fs.lstatSync(fullPath);
34
- } catch (error) {
35
- if (error.code === 'ENOENT') return 'missing';
36
- throw error;
37
- }
38
- const hash = crypto.createHash('sha256');
39
- hash.update(`${stat.mode & 0o777}\0`);
40
- if (stat.isSymbolicLink()) hash.update(fs.readlinkSync(fullPath));
41
- else if (stat.isFile()) hash.update(fs.readFileSync(fullPath));
42
- else hash.update(`special:${stat.mode}`);
43
- return hash.digest('hex');
44
- }
45
-
46
- function sharedScriptsFingerprint() {
47
- const hash = crypto.createHash('sha256');
48
- for (const name of fs.readdirSync(__dirname).filter((file) => file.endsWith('.js') || file === 'project-config-defaults.json').sort()) {
49
- hash.update(name);
50
- hash.update('\0');
51
- hash.update(fs.readFileSync(path.join(__dirname, name)));
52
- hash.update('\0');
53
- }
54
- return hash.digest('hex');
55
- }
56
-
57
- function environmentFingerprint() {
58
- return JSON.stringify({
59
- node: process.version,
60
- platform: process.platform,
61
- architecture: process.arch,
62
- timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
63
- sharedScripts: sharedScriptsFingerprint(),
64
- environment: Object.fromEntries(['CI', 'TZ', 'LANG', 'LC_ALL', 'NODE_OPTIONS']
65
- .map((name) => [name, process.env[name] || ''])),
66
- });
67
- }
68
-
69
- function currentBase(root) {
70
- try { return git(root, ['rev-parse', '--verify', 'HEAD']).toString('utf8').trim(); }
71
- catch (error) {
72
- if (error.status === 128) return EMPTY_TREE;
73
- throw error;
74
- }
75
- }
76
-
77
- function snapshot(root = ROOT(), baseCommit = currentBase(root)) {
78
- return {
79
- baseCommit,
80
- environment: environmentFingerprint(),
81
- changedFiles: changedPaths(root, baseCommit)
82
- .map((relative) => [relative, fileFingerprint(root, relative)]),
83
- };
84
- }
85
-
86
- function receiptPath(root = ROOT()) {
87
- const id = crypto.createHash('sha256').update(fs.realpathSync(root)).digest('hex');
88
- return path.join(os.tmpdir(), RECEIPT_DIRECTORY, `${id}.git.json`);
89
- }
90
-
91
- module.exports = { ROOT, environmentFingerprint, receiptPath, snapshot };
@@ -1,37 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- const fs = require('node:fs');
4
- const path = require('node:path');
5
- const { requireTestCommands } = require('./project-config');
6
- const { ROOT, receiptPath, snapshot } = require('./receipt-state');
7
-
8
- function recordReceipt(root = ROOT(), testedSnapshot) {
9
- requireTestCommands(root);
10
- const current = snapshot(root, testedSnapshot?.baseCommit);
11
- if (testedSnapshot && JSON.stringify(current) !== JSON.stringify(testedSnapshot)) {
12
- throw new Error('Files or environment changed while tests ran; rerun tests before recording a receipt.');
13
- }
14
- const receipt = { version: 1, passedAt: Date.now(), ...current };
15
- const destination = receiptPath(root);
16
- fs.mkdirSync(path.dirname(destination), { recursive: true });
17
- const temporary = `${destination}.${process.pid}.tmp`;
18
- fs.writeFileSync(temporary, `${JSON.stringify(receipt)}\n`);
19
- fs.renameSync(temporary, destination);
20
- return receipt;
21
- }
22
-
23
- if (require.main === module) {
24
- if (process.argv.length !== 2) {
25
- console.error('Usage: node scripts/record-test-receipt.js');
26
- process.exitCode = 2;
27
- } else {
28
- try {
29
- recordReceipt();
30
- } catch (error) {
31
- console.error(error.message);
32
- process.exitCode = 1;
33
- }
34
- }
35
- }
36
-
37
- module.exports = { recordReceipt };