@imdeadpool/guardex 8.4.25 → 8.4.27

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@imdeadpool/guardex",
3
- "version": "8.4.25",
3
+ "version": "8.4.27",
4
4
  "description": "Guardian T-Rex for your multi-agent repo. Isolated worktrees, file locks, and PR-only merges stop parallel Codex & Claude agents from overwriting each other's work. Auto-wires Oh My Codex, Oh My Claude, OpenSpec, and Caveman.",
5
5
  "license": "MIT",
6
6
  "preferGlobal": true,
@@ -65,5 +65,5 @@
65
65
  "prepublishOnly": "node scripts/prepublish-bump-version.js",
66
66
  "postinstall": "node -e \"require('./src/heavy').installReport()\""
67
67
  },
68
- "gitHead": "13d45cbde94a8cf9ccc3cdde0049d62c4d0baa11"
68
+ "gitHead": "92e9ace0b22f41a30616b0be1c12808c1a0863bd"
69
69
  }
@@ -353,7 +353,8 @@ function branch(rawArgs) {
353
353
  autoCommitWorktree ? 'checking worktree and pending changes' : 'resolving branch and finish policy',
354
354
  );
355
355
  const commitState = autoCommitWorktree
356
- ? autoCommitWorktreeForFinish(repoRoot, autoCommitWorktree, finishBranch, { noAutoCommit, commitMessage })
356
+ ? progress.trackFailure(() =>
357
+ autoCommitWorktreeForFinish(repoRoot, autoCommitWorktree, finishBranch, { noAutoCommit, commitMessage }))
357
358
  : { changed: false, committed: false };
358
359
  if (commitState.committed && !agentQuiet) {
359
360
  console.log(`[${TOOL_NAME}] Auto-committed '${finishBranch}' before finish.`);
@@ -367,7 +368,7 @@ function branch(rawArgs) {
367
368
  // the merge never happens.
368
369
  let gateResult;
369
370
  if (gateReview) {
370
- gateResult = runReviewGate({
371
+ gateResult = progress.trackFailure(() => runReviewGate({
371
372
  repoRoot,
372
373
  branch: finishBranch,
373
374
  // Must match how the shell resolves --base when it is omitted, which
@@ -390,7 +391,7 @@ function branch(rawArgs) {
390
391
  },
391
392
  progress,
392
393
  preflight: branchPreflightDuringCi(repoRoot, scriptArgs, { activeCwd, agentQuiet, progress }),
393
- });
394
+ }));
394
395
  } else {
395
396
  progress.skip('review', 'review gate disabled');
396
397
  progress.skip('autofix', 'review gate disabled');
@@ -60,12 +60,13 @@ async function switchWorktree(args = [], deps = {}) {
60
60
  function shellInit(args = []) {
61
61
  if (args.length === 1 && ['--help', '-h'].includes(args[0])) {
62
62
  console.log(
63
- 'Usage: gx shell-init [bash|zsh|fish]\nPrint a shell function for gx switch; evaluate it in your interactive shell.'
63
+ 'Usage: gx shell-init [bash|zsh|fish] [--agent-updates]\nPrint shell integration for gx switch. Add --agent-updates to offer GitGuardex updates before interactive codex and claude launches.\nBash/Zsh: eval "$(gx shell-init bash --agent-updates)" (use zsh for Zsh).\nFish: gx shell-init fish --agent-updates | source\nAdd the matching command to your shell startup file to keep it enabled. Existing agent aliases and functions are left alone.'
64
64
  );
65
65
  return;
66
66
  }
67
- if (args.length > 1) throw new Error('Usage: gx shell-init [bash|zsh|fish]');
68
- process.stdout.write(shellIntegration(args[0] || 'bash'));
67
+ const shells = args.filter((arg) => arg !== '--agent-updates');
68
+ if (shells.length > 1) throw new Error('Usage: gx shell-init [bash|zsh|fish] [--agent-updates]');
69
+ process.stdout.write(shellIntegration(shells[0] || 'bash', { agentUpdates: args.includes('--agent-updates') }));
69
70
  }
70
71
 
71
72
  module.exports = { switchWorktree, shellInit };
package/src/cli/main.js CHANGED
@@ -328,6 +328,7 @@ async function main() {
328
328
  if (command === 'branch') return require('./commands/branch').branch(rest);
329
329
  if (command === 'switch') return require('./commands/worktree-navigation').switchWorktree(rest);
330
330
  if (command === 'shell-init') return require('./commands/worktree-navigation').shellInit(rest);
331
+ if (command === 'update') return require('../toolchain').update(rest);
331
332
  if (command === 'pivot') return require('./commands/branch').pivot(rest);
332
333
  if (command === 'ship') return require('./commands/branch').ship(rest);
333
334
  if (command === 'locks') return require('./commands/branch').locks(rest);
package/src/context.js CHANGED
@@ -365,6 +365,7 @@ const SUGGESTIBLE_COMMANDS = [
365
365
  'pivot',
366
366
  'switch',
367
367
  'shell-init',
368
+ 'update',
368
369
  'ship',
369
370
  'locks',
370
371
  'worktree',
@@ -411,6 +412,7 @@ const CLI_COMMAND_GROUPS = [
411
412
  ['setup', 'Install, repair, and verify guardrails (flags: --repair, --install-only, --target, --current)'],
412
413
  ['doctor', 'Repair drift + verify (flags: --target, --current; auto-sandboxes on protected main)'],
413
414
  ['status', 'Show GitGuardex CLI + service health without modifying files'],
415
+ ['update', 'Check for a GitGuardex update and ask before installing it'],
414
416
  ['mem-doctor', 'Show live RAM, swap, and heavy-job queue capacity'],
415
417
  ['run-heavy', 'Run a local build or test through the adaptive memory queue'],
416
418
  ['migrate', 'Convert legacy repo-local installs to the zero-copy CLI-owned surface'],
@@ -423,7 +425,7 @@ const CLI_COMMAND_GROUPS = [
423
425
  ['pivot', 'Auto-pivot from a protected branch into a fresh agent worktree (single tool call for AI agents)'],
424
426
  ['branch', 'CLI-owned branch workflow surface (start/finish/merge)'],
425
427
  ['switch', 'Navigate by branch, path or PR, with searchable worktree picker'],
426
- ['shell-init', 'Print shell integration for gx switch (bash, zsh, fish)'],
428
+ ['shell-init', 'Print shell integration for gx switch and optional agent launch updates'],
427
429
  ['ship', 'Stage + commit + push + PR + auto-merge + cleanup (alias for `finish --via-pr --wait-for-merge --cleanup`)'],
428
430
  ['finish', 'Commit + PR + merge completed agent branches (--all, --branch)'],
429
431
  ['merge', 'Create/reuse an integration lane and merge overlapping agent branches'],
@@ -491,6 +493,7 @@ const CLI_COMMAND_HELP = {
491
493
  pivot: { nativeHelp: true },
492
494
  switch: { nativeHelp: true },
493
495
  'shell-init': { nativeHelp: true },
496
+ update: { nativeHelp: true },
494
497
  cleanup: { nativeHelp: true },
495
498
  locks: { nativeHelp: true },
496
499
  hook: { nativeHelp: true },
package/src/core/stdin.js CHANGED
@@ -29,7 +29,7 @@ function readSingleLineFromStdin(options = {}) {
29
29
  }
30
30
 
31
31
  if (bytesRead === 0) {
32
- if (input.isTTY) {
32
+ if (input.isTTY && !options.allowTtyEof) {
33
33
  sleepSync(retryDelayMs);
34
34
  continue;
35
35
  }
@@ -128,6 +128,7 @@ function startHeartbeat({
128
128
  runId: String(event.runId || ''),
129
129
  branch: String(event.branch || ''),
130
130
  baseBranch: String(event.baseBranch || ''),
131
+ ...(event.recovery ? { recovery: event.recovery } : {}),
131
132
  };
132
133
  stdio.push(eventDescriptor);
133
134
  }
@@ -569,7 +569,7 @@ function finish(rawArgs, defaults = {}) {
569
569
  progress.start('prepare', worktreePath ? 'checking worktree and pending changes' : 'checking branch');
570
570
  let commitState = { changed: false, committed: false };
571
571
  if (worktreePath) {
572
- commitState = autoCommitWorktreeForFinish(repoRoot, worktreePath, branch, options);
572
+ commitState = progress.trackFailure(() => autoCommitWorktreeForFinish(repoRoot, worktreePath, branch, options));
573
573
  }
574
574
 
575
575
  if (terse) {
@@ -694,12 +694,12 @@ function finish(rawArgs, defaults = {}) {
694
694
  finishArgs.push('--no-preflight');
695
695
  }
696
696
  if (options.mergeMode === 'pr' && options.gateReview) {
697
- gateResult = runReviewGate({
697
+ gateResult = progress.trackFailure(() => runReviewGate({
698
698
  repoRoot, worktreePath, branch, baseBranch, options, progress,
699
699
  preflight: branchPreflightDuringCi(repoRoot, finishArgs, {
700
700
  activeCwd, agentQuiet: options.agentQuiet, progress,
701
701
  }),
702
- });
702
+ }));
703
703
  } else {
704
704
  progress.skip('review', 'review gate disabled');
705
705
  progress.skip('autofix', 'review gate disabled');
@@ -20,6 +20,28 @@ const SYMBOLS = {
20
20
 
21
21
  const TIMED_STAGES = new Set(['review', 'autofix']);
22
22
 
23
+ const RECOVERY_ACTIONS = {
24
+ prepare: 'Inspect the worktree and pending changes before retrying finish.',
25
+ preflight: 'Inspect the local check output and correct the failure before retrying finish.',
26
+ pr: 'Check whether the branch was pushed and the PR already exists before retrying finish.',
27
+ review: 'Check the current PR head and base and the posted review before retrying gated finish.',
28
+ autofix: 'Check the repair commit and whether it was pushed before applying another fix.',
29
+ ci: 'Refresh checks and required approvals on the current PR head before retrying gated finish.',
30
+ merge: 'Check whether GitHub already merged the PR before retrying gated finish.',
31
+ cleanup: 'Confirm the PR merged and the worktree is safe to remove before retrying cleanup.',
32
+ };
33
+
34
+ function recoveryFields(stage, state, detail) {
35
+ if (state !== 'running' && state !== 'failed') return {};
36
+ return {
37
+ recovery: {
38
+ outcome: state === 'failed' ? 'failed' : 'unconfirmed',
39
+ reason: state === 'failed' ? (detail || 'Stage failed') : 'No completed outcome recorded yet',
40
+ nextAction: RECOVERY_ACTIONS[stage],
41
+ },
42
+ };
43
+ }
44
+
23
45
  function createRunId(branch) {
24
46
  const digest = crypto.createHash('sha256').update(String(branch || '')).digest('hex').slice(0, 8);
25
47
  return `finish-${Date.now().toString(36)}-${process.pid}-${digest}`;
@@ -148,6 +170,8 @@ function createFinishProgress({
148
170
  const stageStartedAt = new Map();
149
171
  let activeTimedStage = '';
150
172
  let stopActiveHeartbeat = null;
173
+ let lastPrimaryStage = 'prepare';
174
+ let failures = 0;
151
175
 
152
176
  output(`[gx:finish] ╭─ 🚀 GX FINISH · ${branch || 'current branch'} → ${baseBranch || 'configured base'}`);
153
177
  if (eventStream) {
@@ -189,6 +213,10 @@ function createFinishProgress({
189
213
  if (stage.state === state && stage.detail === normalizedDetail) return false;
190
214
  stage.state = state;
191
215
  stage.detail = normalizedDetail;
216
+ // Skips do not advance the gate. Preflight can overlap CI and reports
217
+ // its own failures; it must not inherit a subsequent gate exception.
218
+ if (state !== 'skipped' && id !== 'preflight') lastPrimaryStage = id;
219
+ if (state === 'failed') failures += 1;
192
220
  const connector = id === 'cleanup' && state !== 'running' ? '╰─' : '├─';
193
221
  output(
194
222
  `[gx:finish] ${connector} ${SYMBOLS[state]} ${stage.index}/${STAGES.length} ${stage.label}`
@@ -202,6 +230,7 @@ function createFinishProgress({
202
230
  total: STAGES.length,
203
231
  label: stage.label,
204
232
  detail: normalizedDetail,
233
+ ...recoveryFields(id, state, normalizedDetail),
205
234
  });
206
235
  }
207
236
  return true;
@@ -231,7 +260,7 @@ function createFinishProgress({
231
260
  startAt,
232
261
  ...(eventStream ? {
233
262
  eventDescriptor: eventStream.descriptor,
234
- event: eventStream.event,
263
+ event: { ...eventStream.event, ...recoveryFields(id, 'running', normalizedDetail) },
235
264
  } : {}),
236
265
  });
237
266
  } catch (_error) {
@@ -249,8 +278,36 @@ function createFinishProgress({
249
278
  update(id, state, detail, displaySuffix);
250
279
  }
251
280
 
281
+ // Gate checks may throw after a stage reports success (e.g. the base moves).
282
+ // Preserve the error without replacing a more specific phase failure.
283
+ function trackFailure(operation) {
284
+ const previousFailures = failures;
285
+ try {
286
+ return operation();
287
+ } catch (error) {
288
+ if (failures === previousFailures) {
289
+ const reason = String(error?.message || 'Finish stopped').split('\n', 1)[0].slice(0, 500);
290
+ const stage = stageMap.get(lastPrimaryStage);
291
+ if (stage.state === 'complete') {
292
+ // A later guard can stop finish without undoing a completed check.
293
+ eventStream?.write({
294
+ ...stage,
295
+ stage: lastPrimaryStage,
296
+ total: STAGES.length,
297
+ kind: 'guard-failure',
298
+ ...recoveryFields(lastPrimaryStage, 'failed', reason),
299
+ });
300
+ } else {
301
+ settle(lastPrimaryStage, 'failed', reason);
302
+ }
303
+ }
304
+ throw error;
305
+ }
306
+ }
307
+
252
308
  return {
253
309
  start,
310
+ trackFailure,
254
311
  complete: (id, detail) => settle(id, 'complete', detail),
255
312
  skip: (id, detail) => settle(id, 'skipped', detail),
256
313
  fail: (id, detail) => settle(id, 'failed', detail),
@@ -181,8 +181,6 @@ function reviewValueLines(value, truncated, reviewDiffPath) {
181
181
  ...(impactScore !== null || riskScore !== null
182
182
  ? ['```text', `Impact ${scoreBar(impactScore)}`, `Risk ${scoreBar(riskScore)}`, '```', '']
183
183
  : []),
184
- 'AI estimates from diff evidence, not a merge verdict. The strongest supported benefit and risk set their own scores. Risk scores show severity if the issue occurs, not likelihood. “Not established” does not mean zero.',
185
- '',
186
184
  ...(priority
187
185
  ? [
188
186
  `> **Priority fix · risk ${priority.magnitude}/100** — ${sourceFor(priority.evidence)}`,
@@ -195,6 +193,11 @@ function reviewValueLines(value, truncated, reviewDiffPath) {
195
193
  ''
196
194
  ]
197
195
  : []),
196
+ '<details>',
197
+ `<summary>Score evidence · ${value.drivers.length} diff-backed item(s)</summary>`,
198
+ '',
199
+ 'AI estimates, not a merge verdict. Each score reflects the strongest supported item on its own axis. Risk is severity, not likelihood. “Not established” does not mean zero.',
200
+ '',
198
201
  '| Driver | Magnitude | Likelihood | Evidence and rationale |',
199
202
  '| :--- | ---: | :--- | :--- |',
200
203
  ...value.drivers.map((driver) => {
@@ -219,6 +222,8 @@ function reviewValueLines(value, truncated, reviewDiffPath) {
219
222
  }
220
223
  return `| **${IMPACTS[impact]}** · ${AREAS[area]} | ${magnitude ? `**${magnitude}/100**` : '—'} | ${LIKELIHOOD[likelihood] ?? '—'} | **${escapeValueText(label)}:** ${escapeValueText(reason)} — ${sourceFor(evidence)}${advice} |`;
221
224
  }),
225
+ '',
226
+ '</details>',
222
227
  ...(value.improvements.length
223
228
  ? [
224
229
  '',
@@ -0,0 +1,154 @@
1
+ const fs = require('node:fs');
2
+ const path = require('node:path');
3
+ const { evidenceLink, escapeValueText } = require('../pull-request/value');
4
+
5
+ const MAX_BYTES = 1024 * 1024;
6
+ const MAX_REPORTS = 12;
7
+ const MAX_SHOWN = 12;
8
+
9
+ function text(value, limit = 320) {
10
+ return typeof value === 'string'
11
+ ? value
12
+ .replace(/[\s\u0000-\u001f]+/g, ' ')
13
+ .trim()
14
+ .slice(0, limit)
15
+ : '';
16
+ }
17
+
18
+ function relativePath(value) {
19
+ if (typeof value !== 'string' || value.length > 512 || /[\\:\u0000-\u001f]/.test(value))
20
+ return '';
21
+ const normalized = value.replace(/^\.\//, '');
22
+ return normalized.split('/').every((piece) => piece && piece !== '.' && piece !== '..')
23
+ ? normalized
24
+ : '';
25
+ }
26
+
27
+ function diagnostic({ message, level, file, line, rule }) {
28
+ const detail = text(message);
29
+ const severity = text(level, 16).toLowerCase();
30
+ return (
31
+ detail && {
32
+ message: detail,
33
+ severity: severity === 'error' ? 'error' : severity === 'warning' ? 'warning' : 'note',
34
+ path: relativePath(file),
35
+ line: Number.isSafeInteger(line) && line > 0 ? line : null,
36
+ rule: text(rule, 80)
37
+ }
38
+ );
39
+ }
40
+
41
+ function parseCheckReport(data, fallback) {
42
+ if (Array.isArray(data?.diagnostics)) {
43
+ return [
44
+ {
45
+ name: text(data.source?.name, 80) || fallback,
46
+ total: data.diagnostics.length,
47
+ diagnostics: data.diagnostics
48
+ .map((item) =>
49
+ diagnostic({
50
+ message: item?.message,
51
+ level: item?.severity,
52
+ file: item?.location?.path,
53
+ line: item?.location?.range?.start?.line,
54
+ rule: item?.code?.value
55
+ })
56
+ )
57
+ .filter(Boolean)
58
+ }
59
+ ];
60
+ }
61
+ if (data?.version !== '2.1.0' || !Array.isArray(data?.runs))
62
+ throw new Error('Unsupported report format');
63
+ return data.runs.slice(0, MAX_REPORTS).map((run) => {
64
+ if (!Array.isArray(run?.results)) throw new Error('Missing SARIF results');
65
+ return {
66
+ name: text(run.tool?.driver?.name, 80) || fallback,
67
+ total: run.results.length,
68
+ diagnostics: run.results
69
+ .map((item) => {
70
+ const location = item?.locations?.[0]?.physicalLocation;
71
+ const artifact = location?.artifactLocation;
72
+ let file = artifact?.uri ?? run.artifacts?.[artifact?.index]?.location?.uri;
73
+ try {
74
+ if (typeof file === 'string') file = decodeURIComponent(file);
75
+ } catch {
76
+ file = '';
77
+ }
78
+ return diagnostic({
79
+ message: item?.message?.text ?? item?.message?.markdown,
80
+ level: item?.level,
81
+ file,
82
+ line: location?.region?.startLine,
83
+ rule: item?.ruleId
84
+ });
85
+ })
86
+ .filter(Boolean)
87
+ };
88
+ });
89
+ }
90
+
91
+ function readCheckReports(files = []) {
92
+ return files.slice(0, MAX_REPORTS).flatMap((file) => {
93
+ const name = text(path.basename(file), 80) || 'report';
94
+ try {
95
+ const stat = fs.lstatSync(file);
96
+ if (!stat.isFile() || stat.size > MAX_BYTES) throw new Error('Not a bounded report file');
97
+ const reports = parseCheckReport(JSON.parse(fs.readFileSync(file, 'utf8')), name);
98
+ if (!reports.length) throw new Error('No runs');
99
+ return reports;
100
+ } catch {
101
+ return [{ name, unavailable: true, diagnostics: [] }];
102
+ }
103
+ });
104
+ }
105
+
106
+ function checkReportLines(reports = [], lineMap = new Map(), reviewDiffPath = '') {
107
+ if (reports.length === 0) return [];
108
+ const lines = [
109
+ '',
110
+ '### Checks (advisory)',
111
+ '',
112
+ 'External tool reports; they do not change the merge gate.',
113
+ ''
114
+ ];
115
+ let remaining = MAX_SHOWN;
116
+ for (const report of reports) {
117
+ const name = escapeValueText(report.name);
118
+ if (report.unavailable || (report.total > 0 && report.diagnostics.length === 0)) {
119
+ lines.push('- **' + name + '** — report unavailable or unreadable.');
120
+ continue;
121
+ }
122
+ const count = report.diagnostics.length;
123
+ lines.push(
124
+ '- **' +
125
+ name +
126
+ '** — ' +
127
+ (count === 0 ? 'no diagnostics reported.' : count + ' diagnostic(s).')
128
+ );
129
+ const shown = report.diagnostics.slice(0, remaining);
130
+ for (const item of shown) {
131
+ let source = '';
132
+ if (item.path) {
133
+ const label = escapeValueText(item.path + (item.line ? ':' + item.line : ''));
134
+ const link = lineMap.get(item.path)?.has(item.line)
135
+ ? evidenceLink(label, item, reviewDiffPath)
136
+ : label;
137
+ source = link + ' — ';
138
+ }
139
+ lines.push(
140
+ ' - ' +
141
+ source +
142
+ escapeValueText(
143
+ item.severity + (item.rule ? ' / ' + item.rule : '') + ': ' + item.message
144
+ )
145
+ );
146
+ }
147
+ remaining -= shown.length;
148
+ if (shown.length < count)
149
+ lines.push(' - ' + (count - shown.length) + ' more in the original report.');
150
+ }
151
+ return lines;
152
+ }
153
+
154
+ module.exports = { readCheckReports, checkReportLines };
@@ -83,12 +83,12 @@ function checkForGuardexUpdate() {
83
83
  };
84
84
  }
85
85
 
86
- function printUpdateAvailableBanner(current, latest) {
86
+ function printUpdateAvailableBanner(current, latest, target = 'latest') {
87
87
  const title = colorize('UPDATE AVAILABLE', '1;33');
88
88
  console.log(`[${TOOL_NAME}] ${title}`);
89
89
  console.log(`[${TOOL_NAME}] Current: ${current}`);
90
90
  console.log(`[${TOOL_NAME}] Latest : ${latest}`);
91
- console.log(`[${TOOL_NAME}] Command: ${NPM_BIN} i -g ${packageJson.name}@latest`);
91
+ console.log(`[${TOOL_NAME}] Command: ${NPM_BIN} i -g ${packageJson.name}@${target}`);
92
92
  }
93
93
 
94
94
  function readInstalledGuardexVersion() {
@@ -440,7 +440,12 @@ function maybeSelfUpdateBeforeStatus() {
440
440
  return;
441
441
  }
442
442
 
443
- const installResult = run(NPM_BIN, ['i', '-g', `${packageJson.name}@latest`], { stdio: 'inherit' });
443
+ installGuardexUpdate(check, true);
444
+ }
445
+
446
+ function installGuardexUpdate(check, restart = false) {
447
+ const target = restart ? 'latest' : check.latest;
448
+ const installResult = run(NPM_BIN, ['i', '-g', `${packageJson.name}@${target}`], { stdio: 'inherit' });
444
449
  if (installResult.status !== 0) {
445
450
  console.log(`[${TOOL_NAME}] Update failed. You can retry manually.`);
446
451
  return;
@@ -448,6 +453,10 @@ function maybeSelfUpdateBeforeStatus() {
448
453
 
449
454
  const postInstallVersion = readInstalledGuardexVersion();
450
455
  if (postInstallVersion != null && postInstallVersion !== check.latest) {
456
+ if (!restart) {
457
+ console.log(`[${TOOL_NAME}] Installed version is ${postInstallVersion} (expected ${check.latest}).`);
458
+ return;
459
+ }
451
460
  console.log(
452
461
  `[${TOOL_NAME}] Installed version is still ${postInstallVersion} (expected ${check.latest}). ` +
453
462
  `Retrying with pinned version ${check.latest}...`,
@@ -474,7 +483,79 @@ function maybeSelfUpdateBeforeStatus() {
474
483
  }
475
484
 
476
485
  console.log(`[${TOOL_NAME}] Updated to latest published version.`);
477
- restartIntoUpdatedGuardex(check.latest);
486
+ if (restart) restartIntoUpdatedGuardex(check.latest);
487
+ }
488
+
489
+ const AGENT_NON_SESSION_COMMANDS = {
490
+ codex: new Set([
491
+ 'exec', 'e', 'review', 'login', 'logout', 'mcp', 'plugin', 'app-server', 'remote-control',
492
+ 'completion', 'update', 'doctor', 'sandbox', 'debug', 'apply', 'a', 'queue', 'archive',
493
+ 'delete', 'migrate-rollouts', 'migrate-nfs-db', 'unarchive', 'cloud', 'exec-server', 'features', 'help',
494
+ ]),
495
+ claude: new Set([
496
+ 'agents', 'auth', 'doctor', 'gateway', 'help', 'import', 'install', 'mcp', 'plugin',
497
+ 'purge', 'respawn', 'setup-token', 'ultrareview', 'update', 'upgrade',
498
+ ]),
499
+ };
500
+
501
+ const AGENT_OPTIONS_WITH_VALUE = {
502
+ codex: new Set([
503
+ '-c', '--config', '--enable', '--disable', '--remote', '--remote-auth-token-env', '-i', '--image',
504
+ '-m', '--model', '--local-provider', '-p', '--profile', '-s', '--sandbox', '-C', '--cd',
505
+ '--add-dir', '-a', '--ask-for-approval',
506
+ ]),
507
+ claude: new Set([
508
+ '--model', '--fallback-model', '--agent', '--effort', '--name', '-n', '--session-id',
509
+ '--resume', '-r', '--from-pr', '--worktree', '-w', '--permission-mode', '--settings',
510
+ '--system-prompt', '--append-system-prompt', '--mcp-config', '--add-dir', '--output-format',
511
+ ]),
512
+ };
513
+
514
+ function isInteractiveAgentLaunch(agent, args) {
515
+ let subcommand;
516
+ for (let index = 0; index < args.length; index += 1) {
517
+ const arg = args[index];
518
+ if (arg === '--') break;
519
+ if (
520
+ ['-h', '--help', '-V', '-v', '--version'].includes(arg) ||
521
+ (agent === 'claude' && (arg === '-p' || arg === '--print'))
522
+ ) return false;
523
+ if (AGENT_OPTIONS_WITH_VALUE[agent].has(arg) && args[index + 1] && !args[index + 1].startsWith('-')) {
524
+ index += 1;
525
+ } else if (!arg.startsWith('-')) {
526
+ subcommand ??= arg;
527
+ }
528
+ }
529
+ return !AGENT_NON_SESSION_COMMANDS[agent].has(subcommand);
530
+ }
531
+
532
+ function update(args) {
533
+ const beforeAgent = args[0] === '--before-agent';
534
+ const usage = 'Usage: gx update\nCheck for a GitGuardex update and install it only after confirmation in a terminal.';
535
+ if (!beforeAgent && args.length === 1 && ['--help', '-h'].includes(args[0])) {
536
+ console.log(usage);
537
+ return;
538
+ }
539
+ if (beforeAgent) {
540
+ const [, agent, ...agentArgs] = args;
541
+ if (!Object.hasOwn(AGENT_NON_SESSION_COMMANDS, agent)) throw new Error('Expected codex or claude');
542
+ if (!isInteractiveAgentLaunch(agent, agentArgs)) return;
543
+ } else if (args.length) {
544
+ throw new Error(usage);
545
+ }
546
+ if (!isInteractiveTerminal()) return;
547
+
548
+ const check = checkForGuardexUpdate();
549
+ if (!check.checked || !parseVersionString(check.latest) || !check.updateAvailable) {
550
+ if (!beforeAgent)
551
+ console.log(`[${TOOL_NAME}] ${check.checked && !check.updateAvailable ? 'Already up to date.' : 'Could not check for updates.'}`);
552
+ return;
553
+ }
554
+ printUpdateAvailableBanner(check.current, check.latest, check.latest);
555
+ process.stdout.write('Update now? [y/N] ');
556
+ const answer = readSingleLineFromStdin({ allowTtyEof: true }).trim().toLowerCase();
557
+ if (answer === 'y' || answer === 'yes') installGuardexUpdate(check);
558
+ else console.log(`\n[${TOOL_NAME}] Skipped update.`);
478
559
  }
479
560
 
480
561
  function maybeOpenSpecUpdateBeforeStatus() {
@@ -942,6 +1023,7 @@ module.exports = {
942
1023
  detectOptionalLocalCompanionTools,
943
1024
  askGlobalInstallForMissing,
944
1025
  maybeSelfUpdateBeforeStatus,
1026
+ update,
945
1027
  maybeOpenSpecUpdateBeforeStatus,
946
1028
  installGlobalToolchain,
947
1029
  performCompanionInstall,
@@ -210,9 +210,35 @@ function resolveWorktree(repoRoot, selector, options = {}, deps = {}) {
210
210
  return createLane(repoRoot, selector, selector, deps);
211
211
  }
212
212
 
213
- function shellIntegration(shell = 'bash') {
213
+ function agentUpdateIntegration(shell) {
214
+ // In Bash/Zsh, parse the function definition only after checking for aliases.
215
+ return ['codex', 'claude']
216
+ .map((agent) =>
217
+ shell === 'fish'
218
+ ? `if not functions --query ${agent}
219
+ function ${agent}
220
+ if status is-interactive
221
+ command gx update --before-agent ${agent} $argv; or true
222
+ end
223
+ command ${agent} $argv
224
+ end
225
+ end
226
+ `
227
+ : `if ! alias ${agent} >/dev/null 2>&1 && ! typeset -f ${agent} >/dev/null 2>&1; then
228
+ eval '${agent}() {
229
+ case $- in *i*) command gx update --before-agent ${agent} "$@" || : ;; esac
230
+ command ${agent} "$@"
231
+ }'
232
+ fi
233
+ `,
234
+ )
235
+ .join('');
236
+ }
237
+
238
+ function shellIntegration(shell = 'bash', { agentUpdates = false } = {}) {
214
239
  if (!['bash', 'zsh', 'fish'].includes(shell))
215
240
  throw new Error('Supported shells: bash, zsh, fish');
241
+ const agentCode = agentUpdates ? agentUpdateIntegration(shell) : '';
216
242
  if (shell === 'fish')
217
243
  return `function gx
218
244
  if test "$argv[1]" = switch; and not contains -- --print $argv; and not contains -- --json $argv; and not contains -- --help $argv; and not contains -- -h $argv
@@ -226,7 +252,7 @@ function shellIntegration(shell = 'bash') {
226
252
  command gx $argv
227
253
  end
228
254
  end
229
- `;
255
+ ${agentCode}`;
230
256
  return `gx() {
231
257
  if [ "\${1-}" = switch ]; then
232
258
  case " $* " in
@@ -242,7 +268,7 @@ end
242
268
  command gx "$@"
243
269
  fi
244
270
  }
245
- `;
271
+ ${agentCode}`;
246
272
  }
247
273
 
248
274
  module.exports = { checkedRun, listWorktrees, resolveWorktree, shellIntegration };
@@ -107,9 +107,27 @@ finish_event() {
107
107
  local label="${4:-}"
108
108
  local detail="${5:-}"
109
109
  local timestamp=""
110
+ local recovery="" outcome="" reason="" next_action=""
110
111
  [[ -n "$FINISH_EVENT_FILE" && -n "$FINISH_RUN_ID" ]] || return 0
112
+ if [[ "$state" == "running" || "$state" == "failed" ]]; then
113
+ case "$stage" in
114
+ preflight) next_action="Inspect the local check output and correct the failure before retrying finish." ;;
115
+ pr) next_action="Check whether the branch was pushed and the PR already exists before retrying finish." ;;
116
+ merge) next_action="Check whether GitHub already merged the PR before retrying gated finish." ;;
117
+ cleanup) next_action="Confirm the PR merged and the worktree is safe to remove before retrying cleanup." ;;
118
+ esac
119
+ if [[ "$state" == "failed" ]]; then
120
+ outcome="failed"
121
+ reason="${detail:-Stage failed}"
122
+ else
123
+ outcome="unconfirmed"
124
+ reason="No completed outcome recorded yet"
125
+ fi
126
+ recovery="$(printf ',"recovery":{"outcome":"%s","reason":"%s","nextAction":"%s"}' \
127
+ "$outcome" "$(finish_json_escape "$reason")" "$(finish_json_escape "$next_action")")"
128
+ fi
111
129
  timestamp="$(date -u '+%Y-%m-%dT%H:%M:%SZ')"
112
- printf '{"schemaVersion":1,"runId":"%s","timestamp":"%s","branch":"%s","baseBranch":"%s","stage":"%s","state":"%s","index":%s,"total":8,"label":"%s","detail":"%s"}\n' \
130
+ printf '{"schemaVersion":1,"runId":"%s","timestamp":"%s","branch":"%s","baseBranch":"%s","stage":"%s","state":"%s","index":%s,"total":8,"label":"%s","detail":"%s"%s}\n' \
113
131
  "$(finish_json_escape "$FINISH_RUN_ID")" \
114
132
  "$timestamp" \
115
133
  "$(finish_json_escape "$FINISH_EVENT_BRANCH")" \
@@ -119,6 +137,7 @@ finish_event() {
119
137
  "$number" \
120
138
  "$(finish_json_escape "$label")" \
121
139
  "$(finish_json_escape "$detail")" \
140
+ "$recovery" \
122
141
  >> "$FINISH_EVENT_FILE" 2>/dev/null || true
123
142
  }
124
143
 
@@ -350,7 +369,7 @@ run_preflight() {
350
369
  echo "[agent-branch-finish] Pre-flight passed." >&2
351
370
  return 0
352
371
  fi
353
- finish_progress failed preflight "failed"
372
+ finish_progress failed preflight "preflight exited with status ${preflight_status}"
354
373
  echo "[agent-branch-finish] Pre-flight FAILED; refusing push. Override with --no-preflight if you really mean it." >&2
355
374
  return 1
356
375
  }