@imdeadpool/guardex 8.4.26 → 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.26",
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": "bf90aca41cc24d8b6dd8ec9e3706522196e664f0"
68
+ "gitHead": "92e9ace0b22f41a30616b0be1c12808c1a0863bd"
69
69
  }
@@ -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
  }
@@ -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 };