@imdeadpool/guardex 8.4.0 → 8.4.2

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 (97) hide show
  1. package/CONTRIBUTING.md +13 -4
  2. package/README.md +223 -1
  3. package/THIRD-PARTY-NOTICES.md +29 -0
  4. package/bin/multiagent-safety.js +9 -12
  5. package/package.json +4 -2
  6. package/skills/gitguardex/SKILL.md +28 -0
  7. package/skills/pr-lens/SKILL.md +87 -0
  8. package/src/abide.js +534 -0
  9. package/src/agents/activity.js +23 -4
  10. package/src/agents/inspect.js +15 -6
  11. package/src/agents/launch.js +6 -1
  12. package/src/agents/process-lease.js +84 -0
  13. package/src/agents/sessions.js +96 -16
  14. package/src/agents/start.js +18 -9
  15. package/src/agents/status.js +35 -14
  16. package/src/agents/supervise.js +87 -0
  17. package/src/budget/index.js +6 -1
  18. package/src/cli/args.js +71 -77
  19. package/src/cli/commands/agents.js +38 -10
  20. package/src/cli/commands/branch.js +116 -103
  21. package/src/cli/commands/claude.js +604 -50
  22. package/src/cli/commands/codex.js +359 -0
  23. package/src/cli/commands/context.js +52 -0
  24. package/src/cli/commands/mcp.js +5 -1
  25. package/src/cli/commands/pr.js +138 -3
  26. package/src/cli/commands/review.js +3 -1
  27. package/src/cli/commands/setup.js +25 -0
  28. package/src/cli/commands/status.js +128 -60
  29. package/src/cli/commands/storage.js +24 -0
  30. package/src/cli/commands/usage.js +48 -0
  31. package/src/cli/commands/watch.js +157 -47
  32. package/src/cli/commands/worktree-copy-ignored.js +38 -0
  33. package/src/cli/commands/worktree-estimate.js +69 -0
  34. package/src/cli/commands/worktree-hooks.js +62 -0
  35. package/src/cli/commands/worktree-navigation.js +71 -0
  36. package/src/cli/commands/worktree-provision.js +92 -0
  37. package/src/cli/main.js +229 -110
  38. package/src/cli/shared/gate-flags.js +131 -0
  39. package/src/cli/shared/scaffolding.js +31 -3
  40. package/src/cli/shared-locks.js +3 -1
  41. package/src/cockpit/pane-actions.js +43 -7
  42. package/src/context.js +373 -17
  43. package/src/doctor/index.js +29 -35
  44. package/src/finish/events.js +254 -0
  45. package/src/finish/index.js +322 -62
  46. package/src/finish/post-branch-finish-cleanup.js +316 -22
  47. package/src/finish/preflight.js +44 -1
  48. package/src/finish/progress.js +36 -0
  49. package/src/finish/review-gate.js +317 -127
  50. package/src/finish/review-receipt.js +156 -0
  51. package/src/finish/with-claims-lock.py +29 -0
  52. package/src/git/index.js +179 -42
  53. package/src/hooks/index.js +68 -3
  54. package/src/mcp/collect.js +61 -5
  55. package/src/mcp/server.js +4 -0
  56. package/src/output/index.js +167 -1
  57. package/src/pr-lens-publish.js +93 -0
  58. package/src/pr-lens.js +184 -0
  59. package/src/pr-respond.js +860 -0
  60. package/src/pr-review.js +519 -159
  61. package/src/pr.js +73 -14
  62. package/src/provider-binary.js +21 -0
  63. package/src/review-diff-context.js +90 -0
  64. package/src/review-fix.js +23 -17
  65. package/src/scaffold/agent-worktree-prep.js +14 -12
  66. package/src/scaffold/dependency-store.js +234 -0
  67. package/src/scaffold/index.js +13 -1
  68. package/src/scaffold/provision-approvals.js +83 -0
  69. package/src/scaffold/provision-config.js +169 -40
  70. package/src/shared-git-state.js +11 -1
  71. package/src/speckit/index.js +12 -1
  72. package/src/storage/run-artifacts.js +185 -0
  73. package/src/toolchain/index.js +322 -2
  74. package/src/worktree-copy-ignored.js +200 -0
  75. package/src/worktree-hook-worker.js +29 -0
  76. package/src/worktree-hooks.js +333 -0
  77. package/src/worktree-navigation.js +248 -0
  78. package/src/worktree-picker.js +89 -0
  79. package/src/worktree-quota.js +100 -0
  80. package/src/worktree-start.js +100 -0
  81. package/templates/AGENTS.multiagent-safety.md +8 -0
  82. package/templates/AGENTS.multiagent-safety.min.md +3 -1
  83. package/templates/codex/skills/gitguardex/SKILL.md +28 -0
  84. package/templates/codex/skills/opensrc/SKILL.md +24 -0
  85. package/templates/githooks/post-merge +16 -2
  86. package/templates/scripts/agent-autofinish-watch.sh +17 -18
  87. package/templates/scripts/agent-branch-finish.sh +180 -19
  88. package/templates/scripts/agent-branch-merge.sh +7 -32
  89. package/templates/scripts/agent-branch-start.sh +202 -43
  90. package/templates/scripts/agent-claude-stop-finish.sh +4 -27
  91. package/templates/scripts/agent-file-locks.py +257 -29
  92. package/templates/scripts/agent-preflight.sh +3 -0
  93. package/templates/scripts/agent-worktree-prune.sh +975 -63
  94. package/templates/scripts/codex-agent.sh +55 -5
  95. package/templates/scripts/lib/guardex-base-branch.sh +207 -0
  96. package/templates/scripts/openspec/init-change-workspace.sh +10 -18
  97. package/templates/scripts/review-bot-watch.sh +171 -4
@@ -0,0 +1,200 @@
1
+ 'use strict';
2
+
3
+ // Worktrunk-inspired explicit ignored-file selection; native Git supplies the
4
+ // gitignore matcher, and GX provisioning retains ownership of safe copying.
5
+ const fs = require('node:fs');
6
+ const path = require('node:path');
7
+ const { execFileSync } = require('node:child_process');
8
+ const { applyCopy } = require('./scaffold/provision-config');
9
+ const sharedGitState = require('./shared-git-state');
10
+
11
+ function git(root, args) {
12
+ return execFileSync('git', ['-C', root, ...args], {
13
+ encoding: 'utf8',
14
+ maxBuffer: 64 * 1024 * 1024,
15
+ stdio: ['ignore', 'pipe', 'pipe']
16
+ });
17
+ }
18
+
19
+ function worktreeRoot(directory) {
20
+ const root = fs.realpathSync(directory);
21
+ if (fs.realpathSync(git(root, ['rev-parse', '--show-toplevel']).trim()) !== root) {
22
+ throw new Error('Source and target must be worktree root directories');
23
+ }
24
+ return root;
25
+ }
26
+
27
+ function present(file) {
28
+ try {
29
+ return fs.lstatSync(file);
30
+ } catch (error) {
31
+ if (error.code !== 'ENOENT') throw error;
32
+ return null;
33
+ }
34
+ }
35
+
36
+ function contained(root, file) {
37
+ const relative = path.relative(root, fs.realpathSync(file));
38
+ return relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
39
+ }
40
+
41
+ function runtimeState(file) {
42
+ const parts = file.split(/[\\/]/);
43
+ return parts.some(
44
+ (part, index) =>
45
+ ['.omx', '.omc'].includes(part) ||
46
+ (['.codex', '.claude'].includes(part) && parts[index + 1] === 'state')
47
+ );
48
+ }
49
+
50
+ function foreignClaimedFiles(target) {
51
+ // Remote inspection fetches lock objects into the repository. Refuse instead
52
+ // of silently bypassing remote ownership or making dry-run write Git state.
53
+ if (sharedGitState.settings(target).enabled) {
54
+ throw new Error(
55
+ 'copy-ignored cannot safely inspect shared remote claims without writing Git state'
56
+ );
57
+ }
58
+ const branch = git(target, ['rev-parse', '--abbrev-ref', 'HEAD']).trim();
59
+ const agent = process.env.GUARDEX_AGENT_ID || '';
60
+ const foreign = new Set();
61
+ const roots = git(target, ['worktree', 'list', '--porcelain', '-z'])
62
+ .split('\0')
63
+ .filter((field) => field.startsWith('worktree '))
64
+ .map((field) => field.slice(9));
65
+ for (const root of roots) {
66
+ const registry = path.join(root, '.omx/state/agent-file-locks.json');
67
+ if (!present(registry)) continue;
68
+ try {
69
+ if (!contained(fs.realpathSync(root), registry)) throw new Error('registry escapes worktree');
70
+ const state = JSON.parse(fs.readFileSync(registry, 'utf8'));
71
+ if (!state?.locks || typeof state.locks !== 'object' || Array.isArray(state.locks)) {
72
+ throw new Error('expected a locks object');
73
+ }
74
+ for (const [file, entry] of Object.entries(state.locks)) {
75
+ if (!entry || typeof entry.branch !== 'string' || !entry.branch)
76
+ throw new Error('invalid lock owner');
77
+ if (!sharedGitState.ownerMatches(entry, branch, agent)) foreign.add(file);
78
+ }
79
+ } catch (error) {
80
+ throw new Error(`Cannot safely inspect lock registry ${registry}: ${error.message}`);
81
+ }
82
+ }
83
+ return foreign;
84
+ }
85
+
86
+ function copyIgnoredUnlocked(sourceDirectory, targetDirectory, options = {}) {
87
+ const source = worktreeRoot(sourceDirectory);
88
+ const target = worktreeRoot(targetDirectory);
89
+ const common = (root) =>
90
+ fs.realpathSync(path.resolve(root, git(root, ['rev-parse', '--git-common-dir']).trim()));
91
+ if (common(source) !== common(target))
92
+ throw new Error('Source and target must belong to the same repository');
93
+ if (source === target) throw new Error('Source and target must be different worktrees');
94
+
95
+ const list = (root, args) =>
96
+ git(root, ['ls-files', '-z', ...args])
97
+ .split('\0')
98
+ .filter(Boolean);
99
+ let files = list(source, ['--others', '--ignored', '--exclude-standard']);
100
+ const include = path.join(source, '.worktreeinclude');
101
+ if (present(include)) {
102
+ if (!contained(source, include) || !fs.statSync(include).isFile()) {
103
+ throw new Error('.worktreeinclude must be a file inside the source worktree');
104
+ }
105
+ const selected = new Set(list(source, ['--others', '--ignored', `--exclude-from=${include}`]));
106
+ files = files.filter((file) => selected.has(file));
107
+ }
108
+ const tracked = new Set(list(target, ['--cached']));
109
+ const foreign = foreignClaimedFiles(target);
110
+ const operations = [];
111
+ for (const file of [...new Set(files)].sort()) {
112
+ const src = path.join(source, file);
113
+ const dest = path.join(target, file);
114
+ try {
115
+ if (runtimeState(file) || runtimeState(path.relative(source, fs.realpathSync(src)))) {
116
+ operations.push({ file, status: 'skipped', note: 'GX runtime state is never copied' });
117
+ continue;
118
+ }
119
+ const parts = file.split('/');
120
+ if (parts.some((part) => ['..', '.git', '.hg', '.svn'].includes(part))) {
121
+ throw new Error('metadata or unsafe path');
122
+ }
123
+ // Never descend into a nested repository, even if its directory is ignored.
124
+ if (
125
+ parts
126
+ .slice(0, -1)
127
+ .some((_, index) => present(path.join(source, ...parts.slice(0, index + 1), '.git')))
128
+ ) {
129
+ throw new Error('nested repository');
130
+ }
131
+ if (!contained(source, src) || !fs.statSync(src).isFile())
132
+ throw new Error('source is not a contained regular file');
133
+ if (tracked.has(file) || present(dest)) {
134
+ operations.push({
135
+ file,
136
+ status: 'unchanged',
137
+ note: 'already present or tracked in target'
138
+ });
139
+ continue;
140
+ }
141
+ if (foreign.has(file)) throw new Error('file is claimed by another branch or agent');
142
+ let parent = path.dirname(dest);
143
+ while (!present(parent)) parent = path.dirname(parent);
144
+ if (!contained(target, parent)) throw new Error('destination escapes worktree');
145
+ const resolvedFile = path.relative(
146
+ target,
147
+ path.join(fs.realpathSync(parent), path.relative(parent, dest))
148
+ );
149
+ if (runtimeState(resolvedFile)) throw new Error('destination resolves into GX runtime state');
150
+ if (foreign.has(resolvedFile))
151
+ throw new Error('destination is claimed by another branch or agent');
152
+ if (options.dryRun) {
153
+ operations.push({ file, status: 'planned', note: 'would copy from source worktree' });
154
+ } else {
155
+ operations.push(...applyCopy(source, target, [file], { literalPaths: true }));
156
+ }
157
+ } catch (error) {
158
+ operations.push({ file, status: 'failed', note: error.message });
159
+ }
160
+ }
161
+ return { source, target, dryRun: Boolean(options.dryRun), operations };
162
+ }
163
+
164
+ function copyIgnoredFiles(sourceDirectory, targetDirectory, options = {}) {
165
+ if (options.dryRun) return copyIgnoredUnlocked(sourceDirectory, targetDirectory, options);
166
+ const target = worktreeRoot(targetDirectory);
167
+ const common = fs.realpathSync(
168
+ path.resolve(target, git(target, ['rev-parse', '--git-common-dir']).trim())
169
+ );
170
+ const output = execFileSync(
171
+ 'python3',
172
+ [
173
+ path.join(__dirname, 'finish/with-claims-lock.py'),
174
+ path.join(common, 'agent-file-locks.lock'),
175
+ process.execPath,
176
+ __filename,
177
+ '--locked-copy',
178
+ path.resolve(sourceDirectory),
179
+ target
180
+ ],
181
+ { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] }
182
+ );
183
+ const response = JSON.parse(output);
184
+ if (response.error) throw new Error(response.error);
185
+ return response.result;
186
+ }
187
+
188
+ // Internal child entrypoint: invoked by the advisory-lock runner above. Keep
189
+ // ownership inspection and all copy writes in this same locked subprocess.
190
+ if (require.main === module && process.argv[2] === '--locked-copy') {
191
+ try {
192
+ process.stdout.write(
193
+ JSON.stringify({ result: copyIgnoredUnlocked(process.argv[3], process.argv[4]) })
194
+ );
195
+ } catch (error) {
196
+ process.stdout.write(JSON.stringify({ error: error.message }));
197
+ }
198
+ }
199
+
200
+ module.exports = { copyIgnoredFiles };
@@ -0,0 +1,29 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const { executeHookJob, runLifecycleHook } = require('./worktree-hooks');
5
+
6
+ async function main(jobFile) {
7
+ if (jobFile === '--run') {
8
+ const { repoRoot, event, context, stateDir } = JSON.parse(process.argv[3]);
9
+ const result = await runLifecycleHook(repoRoot, event, context, { stateDir });
10
+ console.log(JSON.stringify(result));
11
+ process.exitCode = result.ok ? 0 : 1;
12
+ return;
13
+ }
14
+ const { job, stateDir } = JSON.parse(fs.readFileSync(jobFile, 'utf8'));
15
+ try {
16
+ const result = await executeHookJob(job, { stateDir });
17
+ process.exitCode = result.ok ? 0 : 1;
18
+ } finally {
19
+ fs.rmSync(jobFile, { force: true });
20
+ }
21
+ }
22
+
23
+ if (require.main === module)
24
+ main(process.argv[2]).catch((error) => {
25
+ console.error(error.message);
26
+ process.exitCode = 1;
27
+ });
28
+
29
+ module.exports = { main };
@@ -0,0 +1,333 @@
1
+ 'use strict';
2
+
3
+ // Native GX implementation inspired by Worktrunk's lifecycle and frozen hook
4
+ // plans (max-sixty/worktrunk, MIT OR Apache-2.0). No upstream code is copied.
5
+ const fs = require('node:fs');
6
+ const path = require('node:path');
7
+ const { createHash, randomUUID } = require('node:crypto');
8
+ const { spawn, spawnSync } = require('node:child_process');
9
+ const jsonc = require('jsonc-parser');
10
+ const { GUARDEX_HOME_DIR } = require('./context');
11
+ const approvals = require('./scaffold/provision-approvals');
12
+ const { provisioningMode } = require('./scaffold/provision-config');
13
+
14
+ const EVENTS = ['start', 'switch', 'commit', 'merge', 'remove'].flatMap((name) => [
15
+ `pre-${name}`,
16
+ `post-${name}`
17
+ ]);
18
+
19
+ function validateEvent(event) {
20
+ if (!EVENTS.includes(event)) throw new Error(`Unknown lifecycle hook: ${event}`);
21
+ }
22
+
23
+ function loadHookPlan(repoRoot, event) {
24
+ validateEvent(event);
25
+ let text;
26
+ try {
27
+ text = fs.readFileSync(path.join(repoRoot, '.guardex.json'), 'utf8');
28
+ } catch (error) {
29
+ if (error.code === 'ENOENT') return { event, stages: [], timeoutMs: 600000 };
30
+ throw error;
31
+ }
32
+ const errors = [];
33
+ const config = jsonc.parse(text, errors, { allowTrailingComma: true });
34
+ if (errors.length || !config || typeof config !== 'object')
35
+ throw new Error('Invalid .guardex.json lifecycle configuration');
36
+ const value = config.hooks?.[event];
37
+ const timeoutMs = config.hookTimeoutMs ?? 600000;
38
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2147483647)
39
+ throw new Error('hookTimeoutMs must be a positive integer no larger than 2147483647');
40
+ const stages = (value === undefined ? [] : Array.isArray(value) ? value : [value]).map(
41
+ (stage, index) => {
42
+ const entries =
43
+ typeof stage === 'string'
44
+ ? [[`command-${index + 1}`, stage]]
45
+ : stage && typeof stage === 'object' && !Array.isArray(stage)
46
+ ? Object.entries(stage)
47
+ : [];
48
+ if (
49
+ !entries.length ||
50
+ entries.some(
51
+ ([name, command]) => !name.trim() || typeof command !== 'string' || !command.trim()
52
+ )
53
+ )
54
+ throw new Error('Each hook stage must be a command or a nonempty map of named commands');
55
+ return entries.map(([name, command]) => ({ name, command }));
56
+ }
57
+ );
58
+ return { event, stages, timeoutMs };
59
+ }
60
+
61
+ function stateDirectory(repoRoot, deps = {}) {
62
+ const identity = approvals.repositoryIdentity(repoRoot);
63
+ const key = createHash('sha256').update(identity).digest('hex');
64
+ return path.join(
65
+ deps.stateDir || path.join(GUARDEX_HOME_DIR, '.config', 'gitguardex', 'lifecycle-hooks'),
66
+ key
67
+ );
68
+ }
69
+
70
+ function approvalDeps(repoRoot, event, deps) {
71
+ validateEvent(event);
72
+ return { approvalDir: path.join(stateDirectory(repoRoot, deps), 'approvals', event) };
73
+ }
74
+
75
+ function isApproved(repoRoot, plan, deps) {
76
+ return approvals.hasApproval(
77
+ repoRoot,
78
+ [JSON.stringify(plan)],
79
+ approvalDeps(repoRoot, plan.event, deps)
80
+ );
81
+ }
82
+
83
+ async function approveLifecycleHooks(repoRoot, event, deps = {}) {
84
+ const plan = loadHookPlan(repoRoot, event);
85
+ if (!plan.stages.length) throw new Error(`No ${event} hooks configured`);
86
+ if (!(deps.interactive ?? (process.stdin.isTTY && process.stdout.isTTY)))
87
+ throw new Error('Lifecycle hook approval requires an interactive terminal');
88
+ const question =
89
+ `Approve arbitrary shell code for ${JSON.stringify(fs.realpathSync(repoRoot))}?\n` +
90
+ JSON.stringify(plan, null, 2) +
91
+ '\nScripts invoked by these commands can change independently. Approve? [y/N] ';
92
+ let accepted;
93
+ if (deps.confirm) accepted = await deps.confirm(question);
94
+ else {
95
+ const readline = require('node:readline/promises').createInterface({
96
+ input: process.stdin,
97
+ output: process.stdout
98
+ });
99
+ try {
100
+ accepted = /^(y|yes)$/i.test((await readline.question(question)).trim());
101
+ } finally {
102
+ readline.close();
103
+ }
104
+ }
105
+ if (!accepted) throw new Error('Lifecycle hook approval declined');
106
+ // Save exactly the snapshot shown, not a second read of mutable repo config.
107
+ approvals.saveApproval(repoRoot, [JSON.stringify(plan)], approvalDeps(repoRoot, event, deps));
108
+ return { ok: true, status: 'approved', event };
109
+ }
110
+
111
+ function revokeLifecycleHooks(repoRoot, event, deps = {}) {
112
+ approvals.revokeApproval(repoRoot, approvalDeps(repoRoot, event, deps));
113
+ return { ok: true, status: 'revoked', event };
114
+ }
115
+
116
+ function disabled(context = {}) {
117
+ return (
118
+ ['0', 'false', 'no', 'off'].includes(
119
+ String(process.env.GUARDEX_PROVISION_HOOKS || '')
120
+ .trim()
121
+ .toLowerCase()
122
+ ) || provisioningMode({ mode: context.mode }) !== 'full'
123
+ );
124
+ }
125
+
126
+ function saveResult(file, result) {
127
+ const temporary = `${file}.${randomUUID()}.tmp`;
128
+ try {
129
+ fs.writeFileSync(temporary, JSON.stringify(result), { mode: 0o600, flag: 'wx' });
130
+ fs.renameSync(temporary, file);
131
+ } finally {
132
+ fs.rmSync(temporary, { force: true });
133
+ }
134
+ }
135
+
136
+ function runCommand(entry, job, logFd) {
137
+ return new Promise((resolve) => {
138
+ const startedAt = new Date().toISOString();
139
+ fs.writeSync(
140
+ logFd,
141
+ `\n[${startedAt}] ${JSON.stringify(entry.name)}: ${JSON.stringify(entry.command)}\n`
142
+ );
143
+ const child = spawn(entry.command, [], {
144
+ shell: true,
145
+ cwd: job.cwd,
146
+ detached: process.platform !== 'win32',
147
+ stdio: ['ignore', logFd, logFd],
148
+ env: {
149
+ ...process.env,
150
+ GUARDEX_REPO_ROOT: job.repoRoot,
151
+ GUARDEX_WORKTREE: job.context.worktreePath || job.repoRoot,
152
+ GUARDEX_BRANCH: job.context.branch || '',
153
+ GUARDEX_HOOK_EVENT: job.plan.event
154
+ }
155
+ });
156
+ let timedOut = false;
157
+ const timer = setTimeout(() => {
158
+ timedOut = true;
159
+ try {
160
+ if (process.platform !== 'win32') process.kill(-child.pid, 'SIGKILL');
161
+ else child.kill('SIGKILL');
162
+ } catch (error) {
163
+ if (error.code !== 'ESRCH') child.kill('SIGKILL');
164
+ }
165
+ }, job.plan.timeoutMs);
166
+ const finish = (code, signal, error) => {
167
+ clearTimeout(timer);
168
+ resolve({
169
+ name: entry.name,
170
+ status: timedOut ? 'timeout' : code === 0 && !error ? 'ran' : 'failed',
171
+ code,
172
+ signal,
173
+ ...(error ? { error: error.message } : {}),
174
+ startedAt,
175
+ finishedAt: new Date().toISOString()
176
+ });
177
+ };
178
+ child.once('error', (error) => finish(null, null, error));
179
+ child.once('close', (code, signal) => finish(code, signal));
180
+ });
181
+ }
182
+
183
+ async function executeHookJob(job, deps = {}) {
184
+ const result = {
185
+ ok: false,
186
+ event: job.plan.event,
187
+ runId: job.runId,
188
+ logFile: job.logFile,
189
+ status: 'running',
190
+ results: []
191
+ };
192
+ let fd;
193
+ try {
194
+ if (disabled(job.context)) {
195
+ result.ok = true;
196
+ result.status = 'skipped';
197
+ } else if (!isApproved(job.repoRoot, job.plan, deps)) {
198
+ result.status = 'approval-required';
199
+ } else {
200
+ fd = fs.openSync(job.logFile, 'a', 0o600);
201
+ for (const stage of job.plan.stages) {
202
+ const results = await Promise.all(stage.map((entry) => runCommand(entry, job, fd)));
203
+ result.results.push(...results);
204
+ if (results.some((entry) => entry.status !== 'ran')) break;
205
+ }
206
+ result.ok = result.results.every((entry) => entry.status === 'ran');
207
+ result.status = result.ok ? 'completed' : 'failed';
208
+ }
209
+ } catch (error) {
210
+ result.status = 'failed';
211
+ result.error = error.message;
212
+ } finally {
213
+ if (fd !== undefined) fs.closeSync(fd);
214
+ result.finishedAt = new Date().toISOString();
215
+ saveResult(job.resultFile, result);
216
+ }
217
+ return result;
218
+ }
219
+
220
+ async function runLifecycleHook(repoRoot, event, context = {}, deps = {}) {
221
+ validateEvent(event);
222
+ if (disabled(context)) return { ok: true, status: 'skipped', event };
223
+ const plan = loadHookPlan(repoRoot, event);
224
+ if (!plan.stages.length) return { ok: true, status: 'skipped', event };
225
+ const approved = isApproved(repoRoot, plan, deps);
226
+ if (context.dryRun) return { ok: true, status: 'dry-run', event, approved, plan };
227
+ if (!approved) return { ok: false, status: 'approval-required', event };
228
+ const cwd = fs.realpathSync(
229
+ event === 'post-remove' ? repoRoot : context.worktreePath || repoRoot
230
+ );
231
+ const commonDirectory = (root) => {
232
+ const result = spawnSync('git', ['-C', root, 'rev-parse', '--git-common-dir'], {
233
+ encoding: 'utf8'
234
+ });
235
+ if (result.status !== 0) throw new Error('Lifecycle worktree is not a Git repository');
236
+ return fs.realpathSync(path.resolve(root, result.stdout.trim()));
237
+ };
238
+ if (commonDirectory(cwd) !== commonDirectory(repoRoot))
239
+ throw new Error('Lifecycle worktree must belong to the approved repository');
240
+ const directory = path.join(stateDirectory(repoRoot, deps), 'runs');
241
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
242
+ const runId = randomUUID();
243
+ const job = {
244
+ repoRoot: path.resolve(repoRoot),
245
+ plan,
246
+ context: { worktreePath: context.worktreePath, branch: context.branch, mode: context.mode },
247
+ cwd,
248
+ runId,
249
+ logFile: path.join(directory, `${runId}.log`),
250
+ resultFile: path.join(directory, `${runId}.json`)
251
+ };
252
+ if (event.startsWith('pre-')) return executeHookJob(job, deps);
253
+ const jobFile = path.join(directory, `${runId}.job`);
254
+ fs.writeFileSync(jobFile, JSON.stringify({ job, stateDir: deps.stateDir }), {
255
+ mode: 0o600,
256
+ flag: 'wx'
257
+ });
258
+ const result = { ok: true, status: 'queued', event, runId, logFile: job.logFile };
259
+ saveResult(job.resultFile, result);
260
+ const fd = fs.openSync(job.logFile, 'a', 0o600);
261
+ try {
262
+ const child = spawn(
263
+ process.execPath,
264
+ [path.join(__dirname, 'worktree-hook-worker.js'), jobFile],
265
+ {
266
+ detached: true,
267
+ stdio: ['ignore', fd, fd]
268
+ }
269
+ );
270
+ await new Promise((resolve, reject) => {
271
+ child.once('spawn', resolve);
272
+ child.once('error', reject);
273
+ });
274
+ child.unref();
275
+ } catch (error) {
276
+ result.ok = false;
277
+ result.status = 'failed';
278
+ result.error = error.message;
279
+ saveResult(job.resultFile, result);
280
+ fs.rmSync(jobFile, { force: true });
281
+ } finally {
282
+ fs.closeSync(fd);
283
+ }
284
+ return result;
285
+ }
286
+
287
+ function readHookLogs(repoRoot, event, deps = {}) {
288
+ if (event) validateEvent(event);
289
+ const directory = path.join(stateDirectory(repoRoot, deps), 'runs');
290
+ if (!fs.existsSync(directory)) return [];
291
+ return fs
292
+ .readdirSync(directory)
293
+ .filter((name) => name.endsWith('.json'))
294
+ .map((name) => JSON.parse(fs.readFileSync(path.join(directory, name), 'utf8')))
295
+ .filter((result) => !event || result.event === event);
296
+ }
297
+
298
+ function runLifecycleHookSync(repoRoot, event, context = {}, deps = {}) {
299
+ validateEvent(event);
300
+ if (disabled(context) || !loadHookPlan(repoRoot, event).stages.length)
301
+ return { ok: true, status: 'skipped', event };
302
+ // The worker entrypoint belongs to this package, not a PATH-selected gx binary.
303
+ // Command output goes to log files, leaving this pipe strictly machine-readable.
304
+ const child = spawnSync(
305
+ process.execPath,
306
+ [
307
+ path.join(__dirname, 'worktree-hook-worker.js'),
308
+ '--run',
309
+ JSON.stringify({ repoRoot, event, context, stateDir: deps.stateDir })
310
+ ],
311
+ { encoding: 'utf8' }
312
+ );
313
+ if (child.error) throw child.error;
314
+ if (!child.stdout.trim()) throw new Error(child.stderr.trim() || 'Lifecycle worker failed');
315
+ const result = JSON.parse(child.stdout);
316
+ if (!result.ok && event.startsWith('pre-')) {
317
+ const error = new Error(`Lifecycle hook ${event}: ${result.status}`);
318
+ error.result = result;
319
+ throw error;
320
+ }
321
+ return result;
322
+ }
323
+
324
+ module.exports = {
325
+ EVENTS,
326
+ loadHookPlan,
327
+ approveLifecycleHooks,
328
+ revokeLifecycleHooks,
329
+ runLifecycleHook,
330
+ runLifecycleHookSync,
331
+ executeHookJob,
332
+ readHookLogs
333
+ };