@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
@@ -18,6 +18,10 @@ const MODE = 'git';
18
18
  const DEFAULT_REMOTE = 'origin';
19
19
  const LOCK_REF_PREFIX = 'refs/gitguardex/locks/';
20
20
  const MAX_REMOTE_LOCKS = 1000;
21
+ const CAS_MAX_ATTEMPTS = 5;
22
+ // Shared buffer for synchronous backoff between CAS retry attempts. Using
23
+ // Atomics.wait avoids a busy-spin while keeping the function synchronous.
24
+ const _casWaitArray = new Int32Array(new SharedArrayBuffer(4));
21
25
 
22
26
  class SharedGitStateError extends Error {
23
27
  constructor(code, message, details = {}) {
@@ -433,7 +437,13 @@ function claimLock(repoRoot, { file: rawFile, branch, agent = '', allowDelete =
433
437
  throw new SharedGitStateError('invalid', 'shared Git lock requires a branch');
434
438
  }
435
439
  let previous = getLock(repoRoot, file);
436
- for (let attempt = 0; attempt < 2; attempt += 1) {
440
+ for (let attempt = 0; attempt < CAS_MAX_ATTEMPTS; attempt += 1) {
441
+ if (attempt > 0) {
442
+ // Small exponential backoff between retries so that 3+ concurrent
443
+ // claimers do not all hammer the remote in lock-step. 50 ms * attempt
444
+ // gives 50 / 100 / 150 / 200 ms — well under a second in the worst case.
445
+ Atomics.wait(_casWaitArray, 0, 0, 50 * attempt);
446
+ }
437
447
  if (previous && !ownerMatches(previous, branch, agent)) {
438
448
  throw new SharedGitStateError(
439
449
  'conflict',
@@ -21,7 +21,7 @@ function whichSpecify() {
21
21
  }
22
22
 
23
23
  function specifyVersion(specifyPath) {
24
- const result = cp.spawnSync(specifyPath, ['--version'], { encoding: 'utf8' });
24
+ const result = cp.spawnSync(specifyPath, ['--version'], { encoding: 'utf8', timeout: 10_000 });
25
25
  if (result.status === 0 && result.stdout) {
26
26
  return result.stdout.trim();
27
27
  }
@@ -76,16 +76,27 @@ function pruneSpecKitScaffolds(target, { dryRun, logger }) {
76
76
  return removed;
77
77
  }
78
78
 
79
+ // Allow tests to inject a shorter timeout via env; production default is 5 minutes.
80
+ const SPECIFY_INIT_TIMEOUT_MS_DEFAULT = 5 * 60 * 1000;
81
+
79
82
  function runSpecifyInit(target, { dryRun, logger }) {
80
83
  const args = ['init', '--here', '--ai', 'claude', '--force', '--ignore-agent-tools'];
81
84
  if (dryRun) {
82
85
  logger(`[${TOOL_NAME}] dry-run: would run \`${SPECIFY_BIN} ${args.join(' ')}\` in ${target}`);
83
86
  return { status: 'dry-run' };
84
87
  }
88
+ const timeoutMs = Number(process.env.SPECIFY_INIT_TIMEOUT_MS_OVERRIDE) || SPECIFY_INIT_TIMEOUT_MS_DEFAULT;
85
89
  const result = cp.spawnSync(SPECIFY_BIN, args, {
86
90
  cwd: target,
87
91
  stdio: 'inherit',
92
+ timeout: timeoutMs,
88
93
  });
94
+ if (result.error && result.error.code === 'ETIMEDOUT') {
95
+ throw new Error(
96
+ `${SPECIFY_BIN} init timed out after ${timeoutMs / 60000} minute(s) (killed by SIGTERM). ` +
97
+ `Check that \`${SPECIFY_BIN}\` can complete without user interaction.`,
98
+ );
99
+ }
89
100
  if (result.status !== 0) {
90
101
  throw new Error(`${SPECIFY_BIN} init exited with status ${result.status}`);
91
102
  }
@@ -0,0 +1,185 @@
1
+ const fs = require('node:fs');
2
+ const path = require('node:path');
3
+ const crypto = require('node:crypto');
4
+ const { execFileSync } = require('node:child_process');
5
+
6
+ const RUN_ID = /^[a-f0-9-]{36}$/;
7
+ const NAME = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
8
+ const KINDS = new Set(['results', 'logs', 'cache']);
9
+ const DEFAULT_MAX_BYTES = 64 * 1024 * 1024;
10
+ const DEFAULT_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
11
+
12
+ function plainDirectory(directory) {
13
+ try {
14
+ return fs.lstatSync(directory).isDirectory();
15
+ } catch {
16
+ return false;
17
+ }
18
+ }
19
+
20
+ function artifactRoot(repoRoot) {
21
+ const common = execFileSync('git', ['-C', repoRoot, 'rev-parse', '--git-common-dir'], {
22
+ encoding: 'utf8',
23
+ stdio: ['ignore', 'pipe', 'pipe']
24
+ }).trim();
25
+ let directory = fs.realpathSync(path.resolve(repoRoot, common));
26
+ for (const part of ['guardex', 'runs']) {
27
+ directory = path.join(directory, part);
28
+ try {
29
+ fs.mkdirSync(directory, { mode: 0o700 });
30
+ } catch (error) {
31
+ if (error.code !== 'EEXIST') throw error;
32
+ }
33
+ if (!plainDirectory(directory)) throw new Error('Artifact store must not use symlinks');
34
+ }
35
+ return directory;
36
+ }
37
+
38
+ function createRun(repoRoot) {
39
+ const id = crypto.randomUUID();
40
+ const directory = path.join(artifactRoot(repoRoot), id);
41
+ fs.mkdirSync(directory, { mode: 0o700 });
42
+ const run = { id, directory, files: [] };
43
+ fs.writeFileSync(path.join(directory, 'run.json'), JSON.stringify({ version: 1, id }), {
44
+ flag: 'wx',
45
+ mode: 0o600
46
+ });
47
+ return run;
48
+ }
49
+
50
+ function writeRunFile(run, kind, name, content) {
51
+ if (!KINDS.has(kind) || typeof name !== 'string' || !NAME.test(name)) {
52
+ throw new Error('Invalid artifact kind or name');
53
+ }
54
+ if (!plainDirectory(run.directory)) throw new Error('Artifact run must not use symlinks');
55
+ if (fs.existsSync(path.join(run.directory, 'completed.json'))) {
56
+ throw new Error('Cannot write to a completed artifact run');
57
+ }
58
+ const directory = path.join(run.directory, kind);
59
+ try {
60
+ fs.mkdirSync(directory, { mode: 0o700 });
61
+ } catch (error) {
62
+ if (error.code !== 'EEXIST') throw error;
63
+ }
64
+ if (!plainDirectory(directory)) throw new Error('Artifact kind must not use symlinks');
65
+ const file = path.join(directory, name);
66
+ fs.writeFileSync(file, content, { flag: 'wx', mode: 0o600 });
67
+ const { dev, ino, size, mtimeMs } = fs.lstatSync(file);
68
+ run.files.push({ kind, name, dev, ino, size, mtimeMs });
69
+ return file;
70
+ }
71
+
72
+ function completeRun(run) {
73
+ if (!plainDirectory(run.directory)) throw new Error('Artifact run must not use symlinks');
74
+ fs.writeFileSync(
75
+ path.join(run.directory, 'completed.json'),
76
+ JSON.stringify({
77
+ version: 1,
78
+ id: run.id,
79
+ completedAt: Date.now(),
80
+ files: run.files
81
+ }),
82
+ { flag: 'wx', mode: 0o600 }
83
+ );
84
+ }
85
+
86
+ function readRecord(file) {
87
+ if (!fs.lstatSync(file).isFile()) throw new Error('Not a regular artifact record');
88
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
89
+ }
90
+
91
+ // Completion is explicit relinquishment of the disposable files. Neither age nor
92
+ // heartbeat expiry grants permission to touch an active, crashed, or unknown run.
93
+ function pruneDisposable(
94
+ repoRoot,
95
+ { maxBytes = DEFAULT_MAX_BYTES, maxAgeMs = DEFAULT_MAX_AGE_MS, now = Date.now() } = {}
96
+ ) {
97
+ for (const value of [maxBytes, maxAgeMs, now]) {
98
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error('Invalid retention limit');
99
+ }
100
+ const root = artifactRoot(repoRoot);
101
+ const candidates = [];
102
+ for (const id of fs.readdirSync(root)) {
103
+ const directory = path.join(root, id);
104
+ if (!RUN_ID.test(id) || !plainDirectory(directory)) continue;
105
+ try {
106
+ const manifest = readRecord(path.join(directory, 'run.json'));
107
+ const done = readRecord(path.join(directory, 'completed.json'));
108
+ if (
109
+ manifest.version !== 1 ||
110
+ manifest.id !== id ||
111
+ done.version !== 1 ||
112
+ done.id !== id ||
113
+ !Number.isSafeInteger(done.completedAt) ||
114
+ done.completedAt < 0 ||
115
+ done.completedAt > now ||
116
+ !Array.isArray(done.files)
117
+ )
118
+ continue;
119
+ const seen = new Set();
120
+ for (const entry of done.files) {
121
+ if (
122
+ !entry ||
123
+ !['logs', 'cache'].includes(entry.kind) ||
124
+ typeof entry.name !== 'string' ||
125
+ !NAME.test(entry.name)
126
+ )
127
+ continue;
128
+ const parent = path.join(directory, entry.kind);
129
+ if (!plainDirectory(parent)) continue;
130
+ const file = path.join(parent, entry.name);
131
+ if (seen.has(file)) continue;
132
+ seen.add(file);
133
+ try {
134
+ const stat = fs.lstatSync(file);
135
+ if (
136
+ stat.isFile() &&
137
+ stat.dev === entry.dev &&
138
+ stat.ino === entry.ino &&
139
+ stat.size === entry.size &&
140
+ stat.mtimeMs === entry.mtimeMs
141
+ ) {
142
+ candidates.push({ directory, file, stat, completedAt: done.completedAt });
143
+ }
144
+ } catch {
145
+ /* Missing or unreadable files are never deletion candidates. */
146
+ }
147
+ }
148
+ } catch {
149
+ /* Active runs and malformed ownership records fail closed. */
150
+ }
151
+ }
152
+ candidates.sort((a, b) => a.completedAt - b.completedAt || a.file.localeCompare(b.file));
153
+ let remainingBytes = candidates.reduce((sum, item) => sum + item.stat.size, 0);
154
+ const report = { removedFiles: 0, removedBytes: 0, remainingBytes };
155
+ for (const item of candidates) {
156
+ if (remainingBytes <= maxBytes && now - item.completedAt < maxAgeMs) continue;
157
+ try {
158
+ if (
159
+ !plainDirectory(root) ||
160
+ !plainDirectory(item.directory) ||
161
+ !plainDirectory(path.dirname(item.file))
162
+ )
163
+ continue;
164
+ const stat = fs.lstatSync(item.file);
165
+ if (
166
+ !stat.isFile() ||
167
+ stat.ino !== item.stat.ino ||
168
+ stat.dev !== item.stat.dev ||
169
+ stat.mtimeMs !== item.stat.mtimeMs ||
170
+ stat.size !== item.stat.size
171
+ )
172
+ continue;
173
+ fs.unlinkSync(item.file);
174
+ remainingBytes -= stat.size;
175
+ report.removedFiles += 1;
176
+ report.removedBytes += stat.size;
177
+ } catch {
178
+ /* Concurrent eviction and failed probes preserve remaining data. */
179
+ }
180
+ }
181
+ report.remainingBytes = remainingBytes;
182
+ return report;
183
+ }
184
+
185
+ module.exports = { artifactRoot, createRun, writeRunFile, completeRun, pruneDisposable };
@@ -6,6 +6,7 @@ const {
6
6
  TOOL_NAME,
7
7
  SHORT_TOOL_NAME,
8
8
  OPENSPEC_PACKAGE,
9
+ CODEGRAPH_BIN,
9
10
  NPX_BIN,
10
11
  GUARDEX_HOME_DIR,
11
12
  GLOBAL_TOOLCHAIN_SERVICES,
@@ -306,8 +307,13 @@ function detectGlobalToolchainPackages() {
306
307
  if (globalToolchainDetectionCache) {
307
308
  return globalToolchainDetectionCache;
308
309
  }
309
- globalToolchainDetectionCache = computeGlobalToolchainPackages();
310
- return globalToolchainDetectionCache;
310
+ const result = computeGlobalToolchainPackages();
311
+ // Only cache successful detections; a transient npm failure must not
312
+ // permanently poison the cache for the rest of the process lifetime.
313
+ if (result.ok) {
314
+ globalToolchainDetectionCache = result;
315
+ }
316
+ return result;
311
317
  }
312
318
 
313
319
  function computeGlobalToolchainPackages() {
@@ -565,6 +571,319 @@ function installGlobalToolchain(options) {
565
571
  return performCompanionInstall(missingPackages, missingLocalTools);
566
572
  }
567
573
 
574
+ function backupGlobalAgentFile(filePath) {
575
+ if (!fs.existsSync(filePath)) {
576
+ return { status: 'absent', path: filePath };
577
+ }
578
+ const defaultBackupPath = `${filePath}.guardex.bak`;
579
+ const backupPath = fs.existsSync(defaultBackupPath)
580
+ ? `${filePath}.guardex.${Date.now()}.bak`
581
+ : defaultBackupPath;
582
+ fs.copyFileSync(filePath, backupPath);
583
+ return { status: 'created', path: backupPath };
584
+ }
585
+
586
+ function stripTomlComment(line) {
587
+ let quote = null;
588
+ let escaped = false;
589
+ for (let index = 0; index < line.length; index += 1) {
590
+ const char = line[index];
591
+ if (quote === '"' && escaped) {
592
+ escaped = false;
593
+ continue;
594
+ }
595
+ if (quote === '"' && char === '\\') {
596
+ escaped = true;
597
+ continue;
598
+ }
599
+ if (char === '"' || char === "'") {
600
+ quote = quote === char ? null : quote || char;
601
+ continue;
602
+ }
603
+ if (!quote && char === '#') return line.slice(0, index);
604
+ }
605
+ return line;
606
+ }
607
+
608
+ function countTomlSyntaxCharacter(line, target) {
609
+ let quote = null;
610
+ let escaped = false;
611
+ let count = 0;
612
+ for (const char of line) {
613
+ if (quote === '"' && escaped) {
614
+ escaped = false;
615
+ continue;
616
+ }
617
+ if (quote === '"' && char === '\\') {
618
+ escaped = true;
619
+ continue;
620
+ }
621
+ if (char === '"' || char === "'") {
622
+ quote = quote === char ? null : quote || char;
623
+ continue;
624
+ }
625
+ if (!quote && char === target) count += 1;
626
+ }
627
+ return count;
628
+ }
629
+
630
+ function parseTomlString(value) {
631
+ const trimmed = value.trim();
632
+ if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
633
+ try {
634
+ return JSON.parse(trimmed);
635
+ } catch {
636
+ return null;
637
+ }
638
+ }
639
+ if (trimmed.startsWith("'") && trimmed.endsWith("'")) return trimmed.slice(1, -1);
640
+ return null;
641
+ }
642
+
643
+ function parseTomlStringArray(value) {
644
+ const trimmed = value.trim();
645
+ if (!trimmed.startsWith('[') || !trimmed.endsWith(']')) return null;
646
+ const items = [];
647
+ let index = 1;
648
+ while (index < trimmed.length - 1) {
649
+ while (/\s/.test(trimmed[index])) index += 1;
650
+ if (trimmed[index] === ']') break;
651
+ const quote = trimmed[index];
652
+ if (quote !== '"' && quote !== "'") return null;
653
+ const start = index;
654
+ index += 1;
655
+ let escaped = false;
656
+ while (index < trimmed.length - 1) {
657
+ const char = trimmed[index];
658
+ if (quote === '"' && escaped) escaped = false;
659
+ else if (quote === '"' && char === '\\') escaped = true;
660
+ else if (char === quote) break;
661
+ index += 1;
662
+ }
663
+ if (trimmed[index] !== quote) return null;
664
+ const parsed = parseTomlString(trimmed.slice(start, index + 1));
665
+ if (parsed === null) return null;
666
+ items.push(parsed);
667
+ index += 1;
668
+ while (/\s/.test(trimmed[index])) index += 1;
669
+ if (trimmed[index] === ',') index += 1;
670
+ else if (trimmed[index] !== ']') return null;
671
+ }
672
+ return items;
673
+ }
674
+
675
+ function withoutTomlMultilineStringLines(lines) {
676
+ let delimiter = null;
677
+ return lines.map((line) => {
678
+ let quote = null;
679
+ let escaped = false;
680
+ let containsMultilineString = Boolean(delimiter);
681
+ for (let index = 0; index < line.length; index += 1) {
682
+ if (delimiter) {
683
+ if (line.slice(index, index + 3) !== delimiter) continue;
684
+ if (delimiter === '"""') {
685
+ let backslashes = 0;
686
+ for (let offset = index - 1; offset >= 0 && line[offset] === '\\'; offset -= 1) {
687
+ backslashes += 1;
688
+ }
689
+ if (backslashes % 2 === 1) continue;
690
+ }
691
+ delimiter = null;
692
+ index += 2;
693
+ continue;
694
+ }
695
+ const char = line[index];
696
+ if (quote === '"' && escaped) {
697
+ escaped = false;
698
+ continue;
699
+ }
700
+ if (quote === '"' && char === '\\') {
701
+ escaped = true;
702
+ continue;
703
+ }
704
+ if (!quote && char === '#') break;
705
+ const candidate = line.slice(index, index + 3);
706
+ if (!quote && (candidate === '"""' || candidate === "'''")) {
707
+ delimiter = candidate;
708
+ containsMultilineString = true;
709
+ index += 2;
710
+ continue;
711
+ }
712
+ if (char === '"' || char === "'") quote = quote === char ? null : quote || char;
713
+ }
714
+ return containsMultilineString ? '' : line;
715
+ });
716
+ }
717
+
718
+ function findCodegraphMcpSection(lines) {
719
+ const syntaxLines = withoutTomlMultilineStringLines(lines);
720
+ const key = '(?:mcp_servers|"mcp_servers"|\'mcp_servers\')';
721
+ const codegraph = '(?:codegraph|"codegraph"|\'codegraph\')';
722
+ const headerPattern = new RegExp(`^\\[\\s*${key}\\s*\\.\\s*${codegraph}\\s*\\]$`);
723
+ const assignmentPattern = new RegExp(`^${key}\\s*\\.\\s*${codegraph}\\s*=`);
724
+ const parentHeaderPattern = new RegExp(`^\\[\\s*${key}\\s*\\]$`);
725
+ const childAssignmentPattern = new RegExp(`^${codegraph}\\s*=`);
726
+ for (let start = 0; start < syntaxLines.length; start += 1) {
727
+ const normalized = stripTomlComment(syntaxLines[start]).trim();
728
+ if (assignmentPattern.test(normalized)) return { start, end: start + 1, inline: true };
729
+ if (headerPattern.test(normalized)) {
730
+ const next = syntaxLines.findIndex((line, index) => (
731
+ index > start && /^\[\[?.+\]\]?$/.test(stripTomlComment(line).trim())
732
+ ));
733
+ return { start, end: next < 0 ? lines.length : next, inline: false };
734
+ }
735
+ if (!parentHeaderPattern.test(normalized)) continue;
736
+ for (let index = start + 1; index < syntaxLines.length; index += 1) {
737
+ const candidate = stripTomlComment(syntaxLines[index]).trim();
738
+ if (/^\[\[?.+\]\]?$/.test(candidate)) break;
739
+ if (childAssignmentPattern.test(candidate)) return { start: index, end: index + 1, inline: true };
740
+ }
741
+ }
742
+ return null;
743
+ }
744
+
745
+ function readCodegraphMcpConfig(config) {
746
+ const lines = config.split(/\r?\n/);
747
+ const section = findCodegraphMcpSection(lines);
748
+ if (!section) return null;
749
+ const assignments = new Map();
750
+ if (section.inline) {
751
+ const assignment = stripTomlComment(lines[section.start]).trim();
752
+ const value = assignment.slice(assignment.indexOf('=') + 1).trim();
753
+ if (!value.startsWith('{') || !value.endsWith('}')) return null;
754
+ const body = value.slice(1, -1);
755
+ const command = body.match(/(?:^|,)\s*(?:command|"command"|'command')\s*=\s*("(?:\\.|[^"\\])*"|'[^']*')\s*(?=,|$)/);
756
+ const args = body.match(/(?:^|,)\s*(?:args|"args"|'args')\s*=\s*(\[[^\]]*\])\s*(?=,|$)/);
757
+ return {
758
+ command: parseTomlString(command?.[1] || ''),
759
+ args: parseTomlStringArray(args?.[1] || ''),
760
+ };
761
+ }
762
+ let pending = '';
763
+ let arrayDepth = 0;
764
+ for (const rawLine of lines.slice(section.start + 1, section.end)) {
765
+ const line = stripTomlComment(rawLine).trim();
766
+ if (!line) continue;
767
+ pending = pending ? `${pending} ${line}` : line;
768
+ arrayDepth += countTomlSyntaxCharacter(line, '[');
769
+ arrayDepth -= countTomlSyntaxCharacter(line, ']');
770
+ if (arrayDepth > 0) continue;
771
+ const separator = pending.indexOf('=');
772
+ if (separator > 0) {
773
+ const rawKey = pending.slice(0, separator).trim();
774
+ const parsedKey = parseTomlString(rawKey);
775
+ assignments.set(parsedKey === null ? rawKey : parsedKey, pending.slice(separator + 1).trim());
776
+ }
777
+ pending = '';
778
+ }
779
+ return {
780
+ command: parseTomlString(assignments.get('command') || ''),
781
+ args: parseTomlStringArray(assignments.get('args') || ''),
782
+ };
783
+ }
784
+
785
+ function hasConfiguredCodegraphMcp(config) {
786
+ const parsed = readCodegraphMcpConfig(config);
787
+ return parsed?.command === 'codegraph'
788
+ && JSON.stringify(parsed.args) === JSON.stringify(['serve', '--mcp']);
789
+ }
790
+
791
+ function normalizePreservedText(content) {
792
+ return content.split(/\r?\n/).map((line) => line.trimEnd()).join('\n').trim();
793
+ }
794
+
795
+ function withoutCodegraphMcp(config) {
796
+ const lines = config.split(/\r?\n/);
797
+ const section = findCodegraphMcpSection(lines);
798
+ if (section) lines.splice(section.start, section.end - section.start);
799
+ return normalizePreservedText(lines.join('\n'));
800
+ }
801
+
802
+ function withoutCodegraphInstructions(content) {
803
+ const start = content.indexOf('<!-- CODEGRAPH_START -->');
804
+ if (start < 0) return normalizePreservedText(content);
805
+ const endMarker = '<!-- CODEGRAPH_END -->';
806
+ const end = content.indexOf(endMarker, start);
807
+ if (end < 0) return normalizePreservedText(content);
808
+ return normalizePreservedText(`${content.slice(0, start)}${content.slice(end + endMarker.length)}`);
809
+ }
810
+
811
+ function hasCodegraphInstructions(filePath) {
812
+ if (!fs.existsSync(filePath)) return false;
813
+ const content = fs.readFileSync(filePath, 'utf8');
814
+ const start = content.indexOf('<!-- CODEGRAPH_START -->');
815
+ return start >= 0 && content.indexOf('<!-- CODEGRAPH_END -->', start) > start;
816
+ }
817
+
818
+ function restoreCodegraphBackups(backups, targets) {
819
+ backups.forEach((backup, index) => {
820
+ if (backup.status === 'created') fs.copyFileSync(backup.path, targets[index]);
821
+ else if (fs.existsSync(targets[index])) fs.unlinkSync(targets[index]);
822
+ });
823
+ }
824
+
825
+ // CodeGraph owns the Codex TOML/AGENTS serialization. Guardex only invokes its
826
+ // documented non-interactive installer after global companion approval, and
827
+ // snapshots any existing user config before that external writer runs.
828
+ function configureCodegraphForCodex(options = {}) {
829
+ if (options.dryRun) return { status: 'dry-run-skip' };
830
+ if (options.noGlobalInstall) return { status: 'skipped', reason: 'global-install-disabled' };
831
+
832
+ const codexDir = path.join(GUARDEX_HOME_DIR, '.codex');
833
+ if (!fs.existsSync(codexDir)) {
834
+ return { status: 'skipped', reason: 'codex-not-detected' };
835
+ }
836
+
837
+ const configPath = path.join(codexDir, 'config.toml');
838
+ const config = fs.existsSync(configPath) ? fs.readFileSync(configPath, 'utf8') : '';
839
+ const agentsPath = path.join(codexDir, 'AGENTS.md');
840
+ const agents = fs.existsSync(agentsPath) ? fs.readFileSync(agentsPath, 'utf8') : '';
841
+ if (hasConfiguredCodegraphMcp(config)
842
+ && hasCodegraphInstructions(agentsPath)) {
843
+ return { status: 'already-configured', path: configPath };
844
+ }
845
+
846
+ const versionProbe = run(CODEGRAPH_BIN, ['--version'], {
847
+ env: { HOME: GUARDEX_HOME_DIR, USERPROFILE: GUARDEX_HOME_DIR },
848
+ });
849
+ if (versionProbe.status !== 0) {
850
+ return { status: 'skipped', reason: 'codegraph-unavailable' };
851
+ }
852
+
853
+ const backups = [
854
+ backupGlobalAgentFile(configPath),
855
+ backupGlobalAgentFile(agentsPath),
856
+ ];
857
+ const result = run(
858
+ CODEGRAPH_BIN,
859
+ ['install', '--target=codex', '--location=global', '--yes', '--no-permissions'],
860
+ {
861
+ stdio: 'inherit',
862
+ env: { HOME: GUARDEX_HOME_DIR, USERPROFILE: GUARDEX_HOME_DIR },
863
+ },
864
+ );
865
+ const targets = [configPath, agentsPath];
866
+ if (result.status !== 0) {
867
+ restoreCodegraphBackups(backups, targets);
868
+ return { status: 'failed', reason: 'codegraph Codex MCP installer failed', backups };
869
+ }
870
+ const installedConfig = fs.existsSync(configPath) ? fs.readFileSync(configPath, 'utf8') : '';
871
+ const installedAgents = fs.existsSync(agentsPath) ? fs.readFileSync(agentsPath, 'utf8') : '';
872
+ const configured = hasConfiguredCodegraphMcp(installedConfig)
873
+ && hasCodegraphInstructions(agentsPath)
874
+ && withoutCodegraphMcp(installedConfig) === withoutCodegraphMcp(config)
875
+ && withoutCodegraphInstructions(installedAgents) === withoutCodegraphInstructions(agents);
876
+ if (!configured) {
877
+ restoreCodegraphBackups(backups, targets);
878
+ return {
879
+ status: 'failed',
880
+ reason: 'codegraph Codex MCP installer produced an incomplete configuration',
881
+ backups,
882
+ };
883
+ }
884
+ return { status: 'configured', path: configPath, backups };
885
+ }
886
+
568
887
  function performCompanionInstall(missingPackages, missingLocalTools) {
569
888
  const installed = [];
570
889
  if (missingPackages.length > 0) {
@@ -626,4 +945,5 @@ module.exports = {
626
945
  maybeOpenSpecUpdateBeforeStatus,
627
946
  installGlobalToolchain,
628
947
  performCompanionInstall,
948
+ configureCodegraphForCodex,
629
949
  };