@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
@@ -8,7 +8,8 @@
8
8
 
9
9
  const fs = require('fs');
10
10
  const path = require('path');
11
- const { spawnSync } = require('child_process');
11
+ const { spawnSync, execFile } = require('child_process');
12
+ const { setTimeout: delay } = require('node:timers/promises');
12
13
  const { resolveRepoRoot } = require('../../git');
13
14
 
14
15
  const ALT_SCREEN_ON = '\x1b[?1049h';
@@ -37,6 +38,10 @@ function parseWatchArgs(rawArgs) {
37
38
  i += 1;
38
39
  } else if (arg === '--once') {
39
40
  options.once = true;
41
+ } else if (arg === '--pr-cache-ms') {
42
+ const ttl = Number(rawArgs[++i]);
43
+ if (!Number.isInteger(ttl) || ttl < 0 || ttl > 60000) throw new Error('--pr-cache-ms must be between 0 and 60000');
44
+ options.prCacheMs = ttl;
40
45
  } else if (arg === '--help' || arg === '-h') {
41
46
  options.help = true;
42
47
  }
@@ -44,17 +49,22 @@ function parseWatchArgs(rawArgs) {
44
49
  return options;
45
50
  }
46
51
 
47
- function gitCapture(repoRoot, args, timeoutMs = 4000) {
48
- const r = spawnSync('git', ['-C', repoRoot, ...args], {
49
- stdio: ['ignore', 'pipe', 'pipe'],
50
- timeout: timeoutMs,
52
+ function capture(command, args, cwd, timeout, signal) {
53
+ return new Promise((resolve) => {
54
+ execFile(command, args, {
55
+ cwd, timeout, signal, killSignal: 'SIGKILL', maxBuffer: 1024 * 1024,
56
+ encoding: 'utf8',
57
+ }, (error, stdout) => resolve(error ? null : stdout));
51
58
  });
52
- if (r.status !== 0) return null;
53
- return (r.stdout || '').toString();
54
59
  }
55
60
 
56
- function listAgentWorktrees(repoRoot) {
57
- const out = gitCapture(repoRoot, ['worktree', 'list', '--porcelain']);
61
+ function gitCapture(repoRoot, args, signal) {
62
+ return capture('git', ['-C', repoRoot, ...args], repoRoot, 4000, signal);
63
+ }
64
+
65
+ async function listAgentWorktrees(repoRoot, signal) {
66
+ const out = await gitCapture(repoRoot, ['worktree', 'list', '--porcelain'], signal);
67
+ if (out === null) throw new Error('Could not read worktrees');
58
68
  if (!out) return [];
59
69
  const entries = [];
60
70
  let current = {};
@@ -72,15 +82,15 @@ function listAgentWorktrees(repoRoot) {
72
82
  return entries.filter((e) => e.branch && e.branch.startsWith('agent/'));
73
83
  }
74
84
 
75
- function lastCommit(worktreePath) {
76
- const out = gitCapture(worktreePath, ['log', '-1', '--format=%h%x09%cr%x09%s']);
85
+ async function lastCommit(worktreePath, signal) {
86
+ const out = await gitCapture(worktreePath, ['log', '-1', '--format=%h%x09%cr%x09%s'], signal);
77
87
  if (!out) return null;
78
88
  const [sha, age, ...rest] = out.trim().split('\t');
79
89
  return { sha, age, subject: rest.join('\t') };
80
90
  }
81
91
 
82
- function dirtyCount(worktreePath) {
83
- const out = gitCapture(worktreePath, ['status', '--porcelain']);
92
+ async function dirtyCount(worktreePath, signal) {
93
+ const out = await gitCapture(worktreePath, ['status', '--porcelain'], signal);
84
94
  if (out === null) return null;
85
95
  return out.split('\n').filter(Boolean).length;
86
96
  }
@@ -109,21 +119,113 @@ function readPortFromEnvLocal(worktreePath) {
109
119
  return ports;
110
120
  }
111
121
 
112
- function ghPrStatus(repoRoot, branch) {
113
- const r = spawnSync(
122
+ async function ghPrStatus(repoRoot, branch, signal) {
123
+ const out = await capture(
114
124
  'gh',
115
125
  ['pr', 'list', '--head', branch, '--state', 'all', '--limit', '1', '--json', 'number,state,url'],
116
- { cwd: repoRoot, stdio: ['ignore', 'pipe', 'pipe'], timeout: 3000 },
126
+ repoRoot, 3000, signal,
117
127
  );
118
- if (r.error || r.status !== 0) return null;
128
+ if (out === null) return { state: 'UNKNOWN' };
119
129
  try {
120
- const arr = JSON.parse((r.stdout || '').toString());
121
- return arr[0] || null;
130
+ const arr = JSON.parse(out);
131
+ if (!Array.isArray(arr)) return { state: 'UNKNOWN' };
132
+ if (arr.length === 0) return null;
133
+ const pr = arr[0];
134
+ return pr && Number.isInteger(pr.number) && ['OPEN', 'MERGED', 'CLOSED'].includes(pr.state)
135
+ ? pr : { state: 'UNKNOWN' };
122
136
  } catch {
123
- return null;
137
+ return { state: 'UNKNOWN' };
124
138
  }
125
139
  }
126
140
 
141
+ // Observation only. This cache is never used by merge/preflight gates.
142
+ function createPrObservationCache(ttlMs, now = Date.now) {
143
+ if (!Number.isInteger(ttlMs) || ttlMs < 1 || ttlMs > 60000) throw new Error('Invalid PR cache TTL');
144
+ const entries = new Map();
145
+ const observation = (entry) => ({ value: entry.value, observedAt: entry.observedAt,
146
+ ageMs: Math.max(0, now() - entry.observedAt), stale: false });
147
+ return {
148
+ get(key, load, signal) {
149
+ signal?.throwIfAborted();
150
+ for (const [id, item] of entries) {
151
+ if (!item.pending && (now() - item.observedAt >= ttlMs || entries.size >= 256)) entries.delete(id);
152
+ }
153
+ let entry = entries.get(key);
154
+ if (entry && !entry.pending) return Promise.resolve(observation(entry));
155
+ if (!entry) {
156
+ entry = { controller: new AbortController(), users: 0, pending: true };
157
+ entries.set(key, entry);
158
+ entry.promise = Promise.resolve().then(() => load(entry.controller.signal)).then((value) => {
159
+ entry.value = value;
160
+ entry.observedAt = now();
161
+ entry.pending = false;
162
+ if (value?.state === 'UNKNOWN' || entry.controller.signal.aborted) {
163
+ if (entries.get(key) === entry) entries.delete(key);
164
+ }
165
+ return observation(entry);
166
+ }, (error) => {
167
+ if (entries.get(key) === entry) entries.delete(key);
168
+ throw error;
169
+ });
170
+ }
171
+ entry.users++;
172
+ return new Promise((resolve, reject) => {
173
+ let finished = false;
174
+ const finish = (callback, value) => {
175
+ if (finished) return;
176
+ finished = true;
177
+ signal?.removeEventListener('abort', abort);
178
+ entry.users--;
179
+ callback(value);
180
+ };
181
+ const abort = () => {
182
+ finish(reject, signal.reason);
183
+ if (entry.pending && entry.users === 0) {
184
+ if (entries.get(key) === entry) entries.delete(key);
185
+ entry.controller.abort();
186
+ }
187
+ };
188
+ signal?.addEventListener('abort', abort, { once: true });
189
+ entry.promise.then((value) => finish(resolve, value), (error) => finish(reject, error));
190
+ if (signal?.aborted) abort();
191
+ });
192
+ }
193
+ };
194
+ }
195
+
196
+ async function watchCacheIdentity(repoRoot, signal) {
197
+ const remote = await gitCapture(repoRoot, ['remote', 'get-url', 'origin'], signal);
198
+ return remote ? JSON.stringify([fs.realpathSync(repoRoot), remote.trim(), process.env.GH_HOST || '', process.env.GH_REPO || '']) : null;
199
+ }
200
+
201
+ async function collectWatchRows(repoRoot, hasGh, { signal, concurrency = 4, prCache, ...deps } = {}) {
202
+ if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 4) {
203
+ throw new Error('Watch concurrency must be between 1 and 4');
204
+ }
205
+ const worktrees = await (deps.listAgentWorktrees || listAgentWorktrees)(repoRoot, signal);
206
+ const identity = hasGh && prCache ? await (deps.cacheIdentity || watchCacheIdentity)(repoRoot, signal) : null;
207
+ const rows = new Array(worktrees.length);
208
+ let next = 0;
209
+ await Promise.all(Array.from({ length: Math.min(concurrency, worktrees.length) }, async () => {
210
+ while (next < worktrees.length) {
211
+ signal?.throwIfAborted();
212
+ const index = next++;
213
+ const wt = worktrees[index];
214
+ const commit = await (deps.lastCommit || lastCommit)(wt.path, signal)
215
+ || { sha: '—', age: '—', subject: '(no commits)' };
216
+ const dirty = await (deps.dirtyCount || dirtyCount)(wt.path, signal);
217
+ const ports = (deps.readPortFromEnvLocal || readPortFromEnvLocal)(wt.path);
218
+ const probe = (probeSignal) => (deps.ghPrStatus || ghPrStatus)(repoRoot, wt.branch, probeSignal);
219
+ const observation = hasGh && identity && wt.head && prCache
220
+ ? await prCache.get(JSON.stringify([identity, wt.branch, wt.head, 'pr-list']), probe, signal) : null;
221
+ const pr = observation ? observation.value : hasGh ? await probe(signal) : null;
222
+ rows[index] = { ...wt, commit, dirty, ports, pr,
223
+ ...(observation ? { prObservation: { observedAt: observation.observedAt, ageMs: observation.ageMs, stale: observation.stale } } : {}) };
224
+ }
225
+ }));
226
+ return rows;
227
+ }
228
+
127
229
  function paintStatus(state) {
128
230
  const upper = state ? state.toUpperCase() : '';
129
231
  if (upper === 'OPEN') return green('OPEN');
@@ -132,7 +234,7 @@ function paintStatus(state) {
132
234
  return dim('—');
133
235
  }
134
236
 
135
- function render(repoRoot, hasGh) {
237
+ async function render(repoRoot, hasGh, options = {}) {
136
238
  const lines = [];
137
239
  const now = new Date().toLocaleTimeString();
138
240
  lines.push(
@@ -141,26 +243,23 @@ function render(repoRoot, hasGh) {
141
243
  );
142
244
  lines.push(dim('─'.repeat(78)));
143
245
 
144
- const worktrees = listAgentWorktrees(repoRoot);
145
- if (worktrees.length === 0) {
246
+ const rows = await collectWatchRows(repoRoot, hasGh, options);
247
+ if (rows.length === 0) {
146
248
  lines.push(dim(' (no agent/* worktrees — use `gx pivot` or `gx branch start` to spawn one)'));
147
249
  lines.push('');
148
250
  lines.push(dim('Press Ctrl+C to exit'));
149
251
  return lines.join('\n');
150
252
  }
151
253
 
152
- for (const wt of worktrees) {
153
- const commit = lastCommit(wt.path) || { sha: '—', age: '—', subject: '(no commits)' };
154
- const dirty = dirtyCount(wt.path);
155
- const ports = readPortFromEnvLocal(wt.path);
156
- const pr = hasGh ? ghPrStatus(repoRoot, wt.branch) : null;
254
+ for (const wt of rows) {
255
+ const { commit, dirty, ports, pr } = wt;
157
256
  const dirtyTag = dirty == null
158
257
  ? dim('—')
159
258
  : dirty === 0
160
259
  ? green('clean')
161
260
  : yellow(`${dirty} dirty`);
162
261
  const prTag = hasGh
163
- ? (pr ? `${paintStatus(pr.state)} #${pr.number}` : dim('no PR'))
262
+ ? (pr?.state === 'UNKNOWN' ? yellow('PR unknown') : pr ? `${paintStatus(pr.state)} #${pr.number}` : dim('no PR'))
164
263
  : dim('gh n/a');
165
264
  const portsTag = ports.length
166
265
  ? ports.map((p) => `${p.app}:${cyan(String(p.port))}`).join(' · ')
@@ -171,7 +270,7 @@ function render(repoRoot, hasGh) {
171
270
  ` ${cyan(commit.sha)} ${dim(commit.age)} — ${commit.subject.slice(0, 60)}`,
172
271
  );
173
272
  lines.push(
174
- ` ${dirtyTag} · ${portsTag} · ${prTag}`,
273
+ ` ${dirtyTag} · ${portsTag} · ${prTag}${wt.prObservation ? dim(` · observed ${wt.prObservation.ageMs}ms ago`) : ''}`,
175
274
  );
176
275
  lines.push(dim(` ${wt.path}`));
177
276
  lines.push('');
@@ -196,10 +295,11 @@ Options:
196
295
  --interval N Refresh interval in seconds (default 2)
197
296
  --target PATH Repo root (default: current dir)
198
297
  --once Render once and exit (good for scripting)
298
+ --pr-cache-ms N Opt-in PR observation TTL, 1–60000ms (default: disabled)
199
299
  `);
200
300
  }
201
301
 
202
- function watch(rawArgs) {
302
+ async function watch(rawArgs) {
203
303
  const options = parseWatchArgs(rawArgs);
204
304
  if (options.help) {
205
305
  printHelp();
@@ -207,28 +307,38 @@ function watch(rawArgs) {
207
307
  }
208
308
  const repoRoot = resolveRepoRoot(options.target);
209
309
  const hasGh = detectGh();
310
+ const prCache = options.prCacheMs ? createPrObservationCache(options.prCacheMs) : undefined;
210
311
 
211
- if (options.once) {
212
- process.stdout.write(render(repoRoot, hasGh) + '\n');
213
- return;
214
- }
215
-
216
- process.stdout.write(ALT_SCREEN_ON + CURSOR_HIDE);
312
+ if (!options.once) process.stdout.write(ALT_SCREEN_ON + CURSOR_HIDE);
217
313
  const restore = () => {
218
- process.stdout.write(CURSOR_SHOW + ALT_SCREEN_OFF);
314
+ if (!options.once) process.stdout.write(CURSOR_SHOW + ALT_SCREEN_OFF);
219
315
  };
220
- const onExit = () => { restore(); process.exit(0); };
316
+ const controller = new AbortController();
317
+ const onExit = () => controller.abort();
221
318
  process.on('SIGINT', onExit);
222
319
  process.on('SIGTERM', onExit);
223
320
  process.on('exit', restore);
224
321
 
225
- const tick = () => {
226
- process.stdout.write(CLEAR_HOME + render(repoRoot, hasGh));
227
- };
228
- tick();
229
- const id = setInterval(tick, options.intervalMs);
230
- // Keep the process alive; clearInterval happens via SIGINT only.
231
- void id;
322
+ try {
323
+ // Schedule after collection: a slow refresh must never overlap the next one.
324
+ while (!controller.signal.aborted) {
325
+ const output = await render(repoRoot, hasGh, { signal: controller.signal, prCache });
326
+ if (controller.signal.aborted) break;
327
+ if (options.once) {
328
+ process.stdout.write(output + '\n');
329
+ break;
330
+ }
331
+ process.stdout.write(CLEAR_HOME + output);
332
+ await delay(options.intervalMs, undefined, { signal: controller.signal });
333
+ }
334
+ } catch (error) {
335
+ if (!controller.signal.aborted) throw error;
336
+ } finally {
337
+ restore();
338
+ process.removeListener('SIGINT', onExit);
339
+ process.removeListener('SIGTERM', onExit);
340
+ process.removeListener('exit', restore);
341
+ }
232
342
  }
233
343
 
234
- module.exports = { watch, parseWatchArgs };
344
+ module.exports = { watch, parseWatchArgs, collectWatchRows, render, ghPrStatus, createPrObservationCache };
@@ -0,0 +1,38 @@
1
+ 'use strict';
2
+
3
+ const { copyIgnoredFiles } = require('../../worktree-copy-ignored');
4
+
5
+ function copyIgnored(rawArgs, deps = {}) {
6
+ const log = deps.log || console.log;
7
+ if (rawArgs.includes('--help') || rawArgs.includes('-h')) {
8
+ log(
9
+ 'Usage: gx worktree copy-ignored --source <worktree> --target <worktree> [--dry-run] [--json]\nCopies only ignored files, filtered by source .worktreeinclude when present. Never overwrites.'
10
+ );
11
+ return;
12
+ }
13
+ let source;
14
+ let target;
15
+ let dryRun = false;
16
+ let json = false;
17
+ for (let index = 0; index < rawArgs.length; index++) {
18
+ const arg = rawArgs[index];
19
+ if (arg === '--source' || arg === '--target') {
20
+ const value = rawArgs[++index];
21
+ if (!value || value.startsWith('--')) throw new Error(`Missing value for ${arg}`);
22
+ if (arg === '--source') source = value;
23
+ else target = value;
24
+ } else if (arg === '--dry-run') dryRun = true;
25
+ else if (arg === '--json') json = true;
26
+ else throw new Error(`Unknown copy-ignored option: ${arg}`);
27
+ }
28
+ if (!source || !target) throw new Error('copy-ignored requires --source and --target');
29
+ const result = copyIgnoredFiles(source, target, { dryRun });
30
+ if (json) log(JSON.stringify(result));
31
+ else
32
+ for (const operation of result.operations)
33
+ log(`${operation.status}: ${JSON.stringify(operation.file)} (${operation.note})`);
34
+ if (result.operations.some((operation) => operation.status === 'failed')) process.exitCode = 1;
35
+ return result;
36
+ }
37
+
38
+ module.exports = { copyIgnored, worktreeCopyIgnored: copyIgnored };
@@ -0,0 +1,69 @@
1
+ const { resolveRepoRoot } = require('../../git');
2
+ const { extractTargetedArgs, run } = require('../../core/runtime');
3
+ const { estimateCheckout } = require('../../worktree-start');
4
+
5
+ function worktreeEstimate(args) {
6
+ if (args.length === 1 && ['--help', '-h'].includes(args[0])) {
7
+ console.log(
8
+ 'Usage: gx worktree estimate [--target <repo>] [--ref <ref>] [--sparse-exclude <dir>] [--json]\nRead-only tracked blob estimate; not a filesystem-space guarantee.'
9
+ );
10
+ return;
11
+ }
12
+ const { target, passthrough } = extractTargetedArgs(args);
13
+ const repoRoot = resolveRepoRoot(target);
14
+ let ref = 'HEAD';
15
+ let json = false;
16
+ let checkQuota = false;
17
+ let destination = repoRoot;
18
+ const exclusions = [];
19
+ for (let index = 0; index < passthrough.length; index++) {
20
+ const arg = passthrough[index];
21
+ if (arg === '--json') json = true;
22
+ else if (arg === '--check-quota') checkQuota = true;
23
+ else if (['--ref', '--sparse-exclude', '--destination'].includes(arg) && passthrough[index + 1]) {
24
+ const value = passthrough[++index];
25
+ if (arg === '--ref') ref = value;
26
+ else if (arg === '--destination') destination = value;
27
+ else exclusions.push(value);
28
+ } else throw new Error(`Unexpected estimate option: ${arg}`);
29
+ }
30
+ if (!exclusions.length) {
31
+ const config = run('git', [
32
+ '-C',
33
+ repoRoot,
34
+ 'config',
35
+ '--null',
36
+ '--get-all',
37
+ 'multiagent.worktreeSparseExclude'
38
+ ]);
39
+ if (config.status !== 0 && config.status !== 1)
40
+ throw new Error('Cannot read sparse configuration');
41
+ exclusions.push(
42
+ ...String(config.stdout || '')
43
+ .split('\0')
44
+ .filter(Boolean)
45
+ );
46
+ }
47
+ const report = estimateCheckout(repoRoot, ref, exclusions);
48
+ report.quota = require('../../worktree-quota').inspectWorktreeQuota(repoRoot, report.checkoutBytes, destination);
49
+ if (checkQuota && report.quota?.violations.length) {
50
+ throw new Error(report.quota.violations.join(', ') + ': reuse an existing task or inspect safe cleanup before creating another worktree. No new checkout was created.');
51
+ }
52
+ if (json) console.log(JSON.stringify(report));
53
+ else {
54
+ console.log(
55
+ `[agent-branch-start] Checkout estimate: ${report.checkoutBytes} bytes; excluded: ${report.excludedBytes}; full: ${report.trackedBytes}.`
56
+ );
57
+ for (const dir of report.directories.filter((item) => item.bytes >= 100 * 1024 * 1024)) {
58
+ console.log(
59
+ ` Large directory: ${JSON.stringify(dir.path)} (${dir.bytes} bytes). Consider --sparse-exclude for this directory only if the task does not need it.`
60
+ );
61
+ }
62
+ console.log(`[agent-branch-start] ${report.note}`);
63
+ if (report.quota) {
64
+ console.log('[agent-branch-start] Quota: ' + JSON.stringify(report.quota));
65
+ }
66
+ }
67
+ }
68
+
69
+ module.exports = { worktreeEstimate };
@@ -0,0 +1,62 @@
1
+ 'use strict';
2
+
3
+ const { resolveRepoRoot } = require('../../git');
4
+ const hooks = require('../../worktree-hooks');
5
+
6
+ async function runWorktreeHooksCommand(args, deps = {}) {
7
+ if (args.includes('--help') || args.includes('-h')) {
8
+ console.log(
9
+ 'gx worktree hook <event>|approve <event>|logs [--event <event>] [--source <repo>]\n' +
10
+ ' --revoke (approve only), --dry-run, --worktree <path>, --branch <name>, --mode minimal|docs|full, --json'
11
+ );
12
+ return;
13
+ }
14
+ const [action, ...rest] = args;
15
+ const options = {};
16
+ let event;
17
+ for (let index = 0; index < rest.length; index++) {
18
+ const arg = rest[index];
19
+ if (['--json', '--dry-run', '--revoke'].includes(arg)) options[arg.slice(2)] = true;
20
+ else if (
21
+ ['--source', '--target', '--worktree', '--branch', '--mode', '--event'].includes(arg)
22
+ ) {
23
+ if (!rest[index + 1] || rest[index + 1].startsWith('--'))
24
+ throw new Error(`Missing value for ${arg}`);
25
+ options[arg.slice(2)] = rest[++index];
26
+ } else if (action === 'approve' && !event && !arg.startsWith('-')) event = arg;
27
+ else throw new Error(`Unexpected lifecycle option: ${arg}`);
28
+ }
29
+ if (options.revoke && action !== 'approve') throw new Error('--revoke requires approve');
30
+ if (
31
+ ['approve', 'logs'].includes(action) &&
32
+ ['dry-run', 'worktree', 'branch', 'mode'].some((key) => options[key] !== undefined)
33
+ )
34
+ throw new Error('Execution options require a lifecycle event');
35
+ if (options.event && action !== 'logs') throw new Error('--event requires logs');
36
+ if (options.source && options.target) throw new Error('Use either --source or --target');
37
+ const repoRoot = resolveRepoRoot(options.source || options.target);
38
+ let result;
39
+ if (action === 'approve')
40
+ result = options.revoke
41
+ ? hooks.revokeLifecycleHooks(repoRoot, event, deps)
42
+ : await hooks.approveLifecycleHooks(repoRoot, event, deps);
43
+ else if (action === 'logs') result = hooks.readHookLogs(repoRoot, options.event, deps);
44
+ else
45
+ result = await hooks.runLifecycleHook(
46
+ repoRoot,
47
+ action,
48
+ {
49
+ worktreePath: options.worktree,
50
+ branch: options.branch,
51
+ mode: options.mode,
52
+ dryRun: options['dry-run']
53
+ },
54
+ deps
55
+ );
56
+ if (options.json || result.status !== 'skipped')
57
+ console.log(JSON.stringify(result, null, options.json ? undefined : 2));
58
+ if (result.ok === false) throw new Error(`Lifecycle hook ${result.event}: ${result.status}`);
59
+ return result;
60
+ }
61
+
62
+ module.exports = { runWorktreeHooksCommand };
@@ -0,0 +1,71 @@
1
+ const { resolveRepoRoot } = require('../../git');
2
+ const { resolveWorktree, shellIntegration } = require('../../worktree-navigation');
3
+ const { pickWorktree } = require('../../worktree-picker');
4
+
5
+ async function switchWorktree(args = [], deps = {}) {
6
+ const options = { cwd: process.cwd() };
7
+ let selector;
8
+ let target = options.cwd;
9
+ let json = false;
10
+ let print = false;
11
+ for (let index = 0; index < args.length; index += 1) {
12
+ const arg = args[index];
13
+ if (arg === '--help' || arg === '-h') {
14
+ console.log(
15
+ 'Usage: gx switch [branch|path|-|pr:N|PR-URL] [--create] [--print|--json] [--target path]\nNo selector opens a TTY picker. Creation uses guarded GX branch start, never raw checkout.\nInstall shell navigation: eval "$(gx shell-init bash)" (also zsh/fish).'
16
+ );
17
+ return;
18
+ }
19
+ if (arg === '--create') options.create = true;
20
+ else if (arg === '--json') json = true;
21
+ else if (arg === '--print') print = true;
22
+ else if (arg === '--target') {
23
+ target = args[++index];
24
+ if (!target || target.startsWith('-')) throw new Error('--target requires a path');
25
+ options.cwd = target;
26
+ } else if (arg.startsWith('-') && arg !== '-') throw new Error(`Unknown option: ${arg}`);
27
+ else if (selector !== undefined) throw new Error('Provide exactly one selector');
28
+ else selector = arg;
29
+ }
30
+ if (json && print) throw new Error('--json and --print are mutually exclusive');
31
+ if (options.create && !selector) throw new Error('--create requires an explicit selector');
32
+ const repoRoot = (deps.resolveRepoRoot || resolveRepoRoot)(target);
33
+ const entry = selector
34
+ ? resolveWorktree(repoRoot, selector, options, deps)
35
+ : await (deps.pickWorktree || pickWorktree)(repoRoot, {}, deps);
36
+ if (!entry) return null;
37
+ if (/[\x00-\x1f\x7f]/.test(entry.path))
38
+ throw new Error('Navigation path contains unsupported control characters');
39
+ const hook = deps.runLifecycleHook || require('../../worktree-hooks').runLifecycleHook;
40
+ const context = {
41
+ worktreePath: entry.path,
42
+ branch: entry.branch,
43
+ from: repoRoot,
44
+ to: entry.path
45
+ };
46
+ const pre = await hook(repoRoot, 'pre-switch', context);
47
+ if (pre.ok === false) throw new Error(`pre-switch hook blocked navigation: ${pre.status}`);
48
+ try {
49
+ const post = await hook(repoRoot, 'post-switch', context);
50
+ if (post.ok === false) console.error(`post-switch hook warning: ${post.status}`);
51
+ } catch (error) {
52
+ console.error(`post-switch hook warning: ${error.message}`);
53
+ }
54
+ console.log(json ? JSON.stringify(entry) : entry.path);
55
+ if (!json && !print)
56
+ console.error('Use gx shell-init integration to change your shell directory.');
57
+ return entry;
58
+ }
59
+
60
+ function shellInit(args = []) {
61
+ if (args.length === 1 && ['--help', '-h'].includes(args[0])) {
62
+ console.log(
63
+ 'Usage: gx shell-init [bash|zsh|fish]\nPrint a shell function for gx switch; evaluate it in your interactive shell.'
64
+ );
65
+ return;
66
+ }
67
+ if (args.length > 1) throw new Error('Usage: gx shell-init [bash|zsh|fish]');
68
+ process.stdout.write(shellIntegration(args[0] || 'bash'));
69
+ }
70
+
71
+ module.exports = { switchWorktree, shellInit };
@@ -0,0 +1,92 @@
1
+ const { fs, path, TOOL_NAME } = require('../../context');
2
+ const { resolveRepoRoot, currentBranchName, readProtectedBranches } = require('../../git');
3
+ const { extractTargetedArgs } = require('../../core/runtime');
4
+ const {
5
+ loadProvisionConfig,
6
+ applyProvisionConfig,
7
+ provisioningMode
8
+ } = require('../../scaffold/provision-config');
9
+ const {
10
+ repositoryIdentity,
11
+ requestApproval,
12
+ revokeApproval
13
+ } = require('../../scaffold/provision-approvals');
14
+
15
+ function worktreeProvision(subcommand, args) {
16
+ if (args.includes('--help') || args.includes('-h')) {
17
+ console.log(
18
+ 'gx worktree approve-hooks [--target <repo>] [--revoke]\ngx worktree provision --source <repo> [--target <worktree>] [--with-defaults] [--mode minimal|docs|full]'
19
+ );
20
+ return;
21
+ }
22
+ const { target, passthrough } = extractTargetedArgs(args);
23
+ const repoRoot = resolveRepoRoot(target);
24
+ if (subcommand === 'approve-hooks') {
25
+ if (passthrough.some((arg) => arg !== '--revoke'))
26
+ throw new Error('Unexpected approval option; automatic approval is not supported');
27
+ if (passthrough.includes('--revoke')) {
28
+ revokeApproval(repoRoot);
29
+ console.log(`[${TOOL_NAME}] Provision hook approval revoked.`);
30
+ return;
31
+ }
32
+ const commands = loadProvisionConfig(repoRoot)?.postCreate || [];
33
+ if (commands.length === 0) throw new Error('No postCreate commands configured');
34
+ if (!requestApproval(repoRoot, commands))
35
+ throw new Error('Hook approval requires explicit consent in an interactive terminal');
36
+ console.log(
37
+ `[${TOOL_NAME}] Approved the current postCreate command list; changes require new approval.`
38
+ );
39
+ return;
40
+ }
41
+ let source = '';
42
+ let withDefaults = false;
43
+ let mode;
44
+ for (let index = 0; index < passthrough.length; index++) {
45
+ const arg = passthrough[index];
46
+ if (arg === '--with-defaults') withDefaults = true;
47
+ else if (arg === '--mode' && passthrough[index + 1] && !passthrough[index + 1].startsWith('--'))
48
+ mode = passthrough[++index];
49
+ else if (
50
+ arg === '--source' &&
51
+ passthrough[index + 1] &&
52
+ !passthrough[index + 1].startsWith('--')
53
+ )
54
+ source = passthrough[++index];
55
+ else throw new Error(`Unexpected provisioning option: ${arg}`);
56
+ }
57
+ if (!source) throw new Error('Provisioning requires --source <repo>');
58
+ mode = provisioningMode({ mode });
59
+ source = resolveRepoRoot(source);
60
+ if (
61
+ source === repoRoot ||
62
+ !fs.statSync(path.join(repoRoot, '.git')).isFile() ||
63
+ repositoryIdentity(source) !== repositoryIdentity(repoRoot) ||
64
+ readProtectedBranches(repoRoot).includes(currentBranchName(repoRoot))
65
+ ) {
66
+ throw new Error(
67
+ 'Provision target must be a non-protected linked worktree of the source repository'
68
+ );
69
+ }
70
+ const config = loadProvisionConfig(source) || {
71
+ files: { copy: [], symlink: [] },
72
+ postCreate: []
73
+ };
74
+ if (withDefaults) {
75
+ config.files.symlink = [
76
+ ...new Set([
77
+ ...config.files.symlink,
78
+ '.venv',
79
+ 'node_modules',
80
+ 'apps/frontend/node_modules',
81
+ 'apps/backend/node_modules'
82
+ ])
83
+ ];
84
+ }
85
+ for (const operation of applyProvisionConfig(source, repoRoot, config, { mode })) {
86
+ console.log(
87
+ `[${TOOL_NAME}] provision ${operation.status}${operation.code ? ` ${operation.code}` : ''}: ${JSON.stringify(operation.file)} (${operation.note})`
88
+ );
89
+ }
90
+ }
91
+
92
+ module.exports = { worktreeProvision };