@imdeadpool/guardex 7.0.43 → 7.1.1

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 (68) hide show
  1. package/README.md +35 -0
  2. package/package.json +4 -1
  3. package/scripts/prepublish-bump-version.js +191 -0
  4. package/skills/gx-act/SKILL.md +82 -0
  5. package/src/agents/activity.js +279 -0
  6. package/src/agents/inspect.js +17 -4
  7. package/src/agents/launch.js +10 -1
  8. package/src/agents/status.js +9 -6
  9. package/src/budget/index.js +2 -1
  10. package/src/cli/args.js +118 -5
  11. package/src/cli/commands/agents.js +381 -0
  12. package/src/cli/commands/bootstrap.js +92 -0
  13. package/src/cli/commands/branch.js +127 -0
  14. package/src/cli/commands/claude.js +674 -0
  15. package/src/cli/commands/doctor.js +268 -0
  16. package/src/cli/commands/finish.js +26 -0
  17. package/src/cli/commands/mcp.js +122 -0
  18. package/src/cli/commands/misc.js +304 -0
  19. package/src/cli/commands/pr.js +439 -0
  20. package/src/cli/commands/prompt.js +92 -0
  21. package/src/cli/commands/release.js +305 -0
  22. package/src/cli/commands/report.js +244 -0
  23. package/src/cli/commands/review.js +32 -0
  24. package/src/cli/commands/setup.js +242 -0
  25. package/src/cli/commands/status.js +338 -0
  26. package/src/cli/commands/watch.js +234 -0
  27. package/src/cli/main.js +68 -3726
  28. package/src/cli/shared/repo-env.js +161 -0
  29. package/src/cli/shared/sandbox.js +417 -0
  30. package/src/cli/shared/scaffolding.js +535 -0
  31. package/src/cli/shared/toolchain-shims.js +420 -0
  32. package/src/context.js +229 -11
  33. package/src/core/runtime.js +6 -1
  34. package/src/doctor/index.js +42 -13
  35. package/src/finish/index.js +147 -5
  36. package/src/finish/preflight.js +177 -0
  37. package/src/finish/review-gate.js +182 -0
  38. package/src/git/index.js +446 -4
  39. package/src/hooks/index.js +0 -64
  40. package/src/mcp/collect.js +394 -0
  41. package/src/mcp/server.js +163 -0
  42. package/src/output/index.js +67 -1
  43. package/src/pr-review.js +23 -0
  44. package/src/pr.js +381 -0
  45. package/src/sandbox/index.js +13 -2
  46. package/src/scaffold/agent-worktree-prep.js +220 -0
  47. package/src/scaffold/index.js +108 -10
  48. package/src/scaffold/provision-config.js +314 -0
  49. package/src/speckit/index.js +226 -0
  50. package/src/terminal/index.js +1 -76
  51. package/src/terminal/kitty.js +20 -0
  52. package/src/terminal/tmux.js +9 -1
  53. package/src/toolchain/index.js +20 -0
  54. package/templates/AGENTS.monorepo-apps.md +26 -0
  55. package/templates/AGENTS.multiagent-safety.md +68 -344
  56. package/templates/AGENTS.multiagent-safety.min.md +11 -0
  57. package/templates/codex/skills/gx-act/SKILL.md +82 -0
  58. package/templates/githooks/pre-commit +22 -19
  59. package/templates/scripts/agent-branch-finish.sh +17 -33
  60. package/templates/scripts/agent-branch-merge.sh +4 -1
  61. package/templates/scripts/agent-branch-start.sh +115 -6
  62. package/templates/scripts/agent-file-locks.py +245 -50
  63. package/templates/scripts/agent-preflight.sh +31 -5
  64. package/templates/scripts/agent-worktree-prune.sh +1 -1
  65. package/templates/scripts/codex-agent.sh +0 -91
  66. package/src/agents/detect.js +0 -160
  67. package/src/cockpit/keybindings.js +0 -224
  68. package/src/cockpit/layout.js +0 -224
@@ -1,5 +1,5 @@
1
1
  const { fs, path, LOCK_FILE_RELATIVE, TOOL_NAME } = require('../context');
2
- const { changedFiles } = require('./inspect');
2
+ const { changedFiles, listWorktrees } = require('./inspect');
3
3
  const { listAgentSessions } = require('./sessions');
4
4
 
5
5
  function uniqueSorted(values) {
@@ -35,10 +35,10 @@ function readLockDetails(repoRoot) {
35
35
  return { counts, files };
36
36
  }
37
37
 
38
- function readChangedFiles(repoRoot, branch) {
38
+ function readChangedFiles(repoRoot, branch, worktrees) {
39
39
  if (!branch) return [];
40
40
  try {
41
- return changedFiles({ target: repoRoot, branch }).files || [];
41
+ return changedFiles({ target: repoRoot, branch, worktrees }).files || [];
42
42
  } catch (_error) {
43
43
  return [];
44
44
  }
@@ -53,7 +53,7 @@ function normalizePr(session) {
53
53
  };
54
54
  }
55
55
 
56
- function normalizeSessionForStatus(session, lockDetails, repoRoot) {
56
+ function normalizeSessionForStatus(session, lockDetails, repoRoot, worktrees) {
57
57
  const branch = session.branch || '';
58
58
  const worktreePath = session.worktreePath || '';
59
59
  const claimedFiles = uniqueSorted([
@@ -73,7 +73,7 @@ function normalizeSessionForStatus(session, lockDetails, repoRoot) {
73
73
  worktreeExists: worktreePath ? fs.existsSync(worktreePath) : false,
74
74
  lockCount: lockDetails.counts.get(branch) || 0,
75
75
  claimedFiles,
76
- changedFiles: readChangedFiles(repoRoot, branch),
76
+ changedFiles: readChangedFiles(repoRoot, branch, worktrees),
77
77
  metadata: session.metadata && typeof session.metadata === 'object' ? session.metadata : {},
78
78
  launchCommand: session.launchCommand || '',
79
79
  tmux: session.tmux && typeof session.tmux === 'object' ? session.tmux : null,
@@ -85,10 +85,13 @@ function normalizeSessionForStatus(session, lockDetails, repoRoot) {
85
85
 
86
86
  function buildAgentsStatusPayload(repoRoot) {
87
87
  const lockDetails = readLockDetails(repoRoot);
88
+ // Hoist the invariant `git worktree list` out of the per-session loop: fetch it
89
+ // once here instead of once inside every session's changedFiles() (~6N -> ~6+N).
90
+ const worktrees = listWorktrees(repoRoot);
88
91
  return {
89
92
  schemaVersion: 1,
90
93
  repoRoot,
91
- sessions: listAgentSessions(repoRoot).map((session) => normalizeSessionForStatus(session, lockDetails, repoRoot)),
94
+ sessions: listAgentSessions(repoRoot).map((session) => normalizeSessionForStatus(session, lockDetails, repoRoot, worktrees)),
92
95
  };
93
96
  }
94
97
 
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const cp = require('node:child_process');
4
+ const { GH_BIN } = require('../context');
4
5
 
5
6
  const TOOL_NAME = 'gx';
6
7
 
@@ -8,7 +9,7 @@ const DEFAULT_WARN_NET_USD = 1; // any paid spend at all
8
9
  const DEFAULT_CRITICAL_NET_USD = 10; // paid spend that has caused merge blocks before
9
10
 
10
11
  function runGh(args) {
11
- const result = cp.spawnSync('gh', args, { encoding: 'utf8' });
12
+ const result = cp.spawnSync(GH_BIN, args, { encoding: 'utf8' });
12
13
  if (result.error) {
13
14
  const err = new Error(`gh binary not found: ${result.error.message}`);
14
15
  err.code = 'GH_BIN_MISSING';
package/src/cli/args.js CHANGED
@@ -108,6 +108,14 @@ function parseCommonArgs(rawArgs, defaults) {
108
108
  options.allowProtectedBaseWrite = true;
109
109
  continue;
110
110
  }
111
+ if (arg === '--contract' || arg === '--full') {
112
+ options.contract = true;
113
+ continue;
114
+ }
115
+ if (arg === '--minimal' || arg === '--no-contract') {
116
+ options.contract = false;
117
+ continue;
118
+ }
111
119
  if (Object.prototype.hasOwnProperty.call(options, 'waitForMerge') && arg === '--wait-for-merge') {
112
120
  options.waitForMerge = true;
113
121
  continue;
@@ -177,6 +185,8 @@ function parseSetupArgs(rawArgs, defaults) {
177
185
  const setupDefaults = {
178
186
  ...defaults,
179
187
  parentWorkspaceView: false,
188
+ speckit: true,
189
+ speckitForce: false,
180
190
  };
181
191
  const forwardedArgs = [];
182
192
 
@@ -190,6 +200,19 @@ function parseSetupArgs(rawArgs, defaults) {
190
200
  setupDefaults.parentWorkspaceView = false;
191
201
  continue;
192
202
  }
203
+ if (arg === '--no-speckit' || arg === '--skip-speckit') {
204
+ setupDefaults.speckit = false;
205
+ continue;
206
+ }
207
+ if (arg === '--speckit') {
208
+ setupDefaults.speckit = true;
209
+ continue;
210
+ }
211
+ if (arg === '--speckit-force' || arg === '--reinstall-speckit') {
212
+ setupDefaults.speckit = true;
213
+ setupDefaults.speckitForce = true;
214
+ continue;
215
+ }
193
216
  forwardedArgs.push(arg);
194
217
  }
195
218
 
@@ -350,6 +373,12 @@ function parseAgentsArgs(rawArgs) {
350
373
  sessionId: '',
351
374
  finishArgs: [],
352
375
  metadata: {},
376
+ activity: '',
377
+ worktree: '',
378
+ backend: '',
379
+ waiting: false,
380
+ done: false,
381
+ print: false,
353
382
  };
354
383
  let terminalProvided = false;
355
384
 
@@ -398,6 +427,54 @@ function parseAgentsArgs(rawArgs) {
398
427
  index += 1;
399
428
  continue;
400
429
  }
430
+ if (arg === '--session') {
431
+ const next = rest[index + 1];
432
+ if (!next) {
433
+ throw new Error('--session requires an agent session id');
434
+ }
435
+ options.sessionId = next;
436
+ index += 1;
437
+ continue;
438
+ }
439
+ if (arg === '--activity' || arg === '--status') {
440
+ const next = rest[index + 1];
441
+ if (!next || next.startsWith('-')) {
442
+ throw new Error('--activity requires a state (working, waiting, done, idle)');
443
+ }
444
+ options.activity = next;
445
+ index += 1;
446
+ continue;
447
+ }
448
+ if (arg === '--worktree') {
449
+ const next = rest[index + 1];
450
+ if (!next) {
451
+ throw new Error('--worktree requires a path');
452
+ }
453
+ options.worktree = next;
454
+ index += 1;
455
+ continue;
456
+ }
457
+ if (arg === '--backend') {
458
+ const next = rest[index + 1];
459
+ if (!next || next.startsWith('-')) {
460
+ throw new Error('--backend requires auto, kitty, or tmux');
461
+ }
462
+ options.backend = next;
463
+ index += 1;
464
+ continue;
465
+ }
466
+ if (arg === '--waiting') {
467
+ options.waiting = true;
468
+ continue;
469
+ }
470
+ if (arg === '--done') {
471
+ options.done = true;
472
+ continue;
473
+ }
474
+ if (arg === '--print') {
475
+ options.print = true;
476
+ continue;
477
+ }
401
478
  if (arg === '--json') {
402
479
  options.json = true;
403
480
  continue;
@@ -569,7 +646,7 @@ function parseAgentsArgs(rawArgs) {
569
646
  throw new Error(`Unknown option: ${arg}`);
570
647
  }
571
648
 
572
- if (!['start', 'stop', 'status', 'files', 'diff', 'locks', 'finish', 'cleanup-sessions'].includes(options.subcommand)) {
649
+ if (!['start', 'stop', 'status', 'files', 'diff', 'locks', 'finish', 'cleanup-sessions', 'set-status', 'jump'].includes(options.subcommand)) {
573
650
  throw new Error(`Unknown agents subcommand: ${options.subcommand}`);
574
651
  }
575
652
  if (options.pid !== null && options.subcommand !== 'stop') {
@@ -615,8 +692,17 @@ function parseAgentsArgs(rawArgs) {
615
692
  throw new Error('agents finish accepts only one of --session or --branch');
616
693
  }
617
694
  }
618
- if (options.branch && !['files', 'diff', 'locks', 'finish'].includes(options.subcommand)) {
619
- throw new Error('--branch is only supported with `gx agents files|diff|locks|finish`');
695
+ if (options.branch && !['files', 'diff', 'locks', 'finish', 'set-status', 'jump'].includes(options.subcommand)) {
696
+ throw new Error('--branch is only supported with `gx agents files|diff|locks|finish|set-status|jump`');
697
+ }
698
+ if ((options.activity || options.worktree) && !['set-status'].includes(options.subcommand)) {
699
+ throw new Error('--activity and --worktree are only supported with `gx agents set-status`');
700
+ }
701
+ if ((options.waiting || options.done || options.print) && !['jump'].includes(options.subcommand)) {
702
+ throw new Error('--waiting, --done, and --print are only supported with `gx agents jump`');
703
+ }
704
+ if (options.subcommand === 'set-status' && !options.activity) {
705
+ throw new Error('gx agents set-status requires --activity <working|waiting|done|idle>');
620
706
  }
621
707
  if (
622
708
  options.json &&
@@ -1069,6 +1155,10 @@ function parseFinishArgs(rawArgs, defaults = {}) {
1069
1155
  failFast: false,
1070
1156
  commitMessage: '',
1071
1157
  mergeMode: defaults.mergeMode || 'pr',
1158
+ skipPreflight: false,
1159
+ gateReview: defaults.gateReview ?? false,
1160
+ reviewProvider: defaults.reviewProvider || 'codex',
1161
+ allowNoChecks: false,
1072
1162
  };
1073
1163
 
1074
1164
  for (let index = 0; index < rawArgs.length; index += 1) {
@@ -1181,6 +1271,31 @@ function parseFinishArgs(rawArgs, defaults = {}) {
1181
1271
  options.advanceSubmodules = false;
1182
1272
  continue;
1183
1273
  }
1274
+ if (arg === '--skip-preflight') {
1275
+ options.skipPreflight = true;
1276
+ continue;
1277
+ }
1278
+ if (arg === '--gate-review') {
1279
+ options.gateReview = true;
1280
+ continue;
1281
+ }
1282
+ if (arg === '--no-gate-review' || arg === '--skip-review-gate') {
1283
+ options.gateReview = false;
1284
+ continue;
1285
+ }
1286
+ if (arg === '--allow-no-checks') {
1287
+ options.allowNoChecks = true;
1288
+ continue;
1289
+ }
1290
+ if (arg === '--review-provider') {
1291
+ const next = rawArgs[index + 1];
1292
+ if (!next || !['codex', 'claude'].includes(next)) {
1293
+ throw new Error('--review-provider requires a value of codex|claude');
1294
+ }
1295
+ options.reviewProvider = next;
1296
+ index += 1;
1297
+ continue;
1298
+ }
1184
1299
  throw new Error(`Unknown option: ${arg}`);
1185
1300
  }
1186
1301
 
@@ -1194,9 +1309,7 @@ function parseFinishArgs(rawArgs, defaults = {}) {
1194
1309
  module.exports = {
1195
1310
  requireValue,
1196
1311
  normalizeManagedForcePath,
1197
- collectForceManagedPaths,
1198
1312
  parseCommonArgs,
1199
- parseRepoTraversalArgs,
1200
1313
  parseSetupArgs,
1201
1314
  parseDoctorArgs,
1202
1315
  parseTargetFlag,
@@ -0,0 +1,381 @@
1
+ // `gx agents` — repo-scoped review + cleanup bots. Pure code-motion from
2
+ // src/cli/main.js.
3
+ const {
4
+ fs,
5
+ path,
6
+ cp,
7
+ TOOL_NAME,
8
+ AGENTS_BOTS_STATE_RELATIVE,
9
+ } = require('../../context');
10
+ const { resolveRepoRoot } = require('../../git');
11
+ const { run } = require('../../core/runtime');
12
+ const agentInspect = require('../../agents/inspect');
13
+ const agentStatus = require('../../agents/status');
14
+ const agentActivity = require('../../agents/activity');
15
+ const agentCleanupSessions = require('../../agents/cleanup-sessions');
16
+ const agentsFinishModule = require('../../agents/finish');
17
+ const agentsStart = require('../../agents/start');
18
+ const { parseAgentsArgs } = require('../args');
19
+
20
+ const finishAgentSession = (...callArgs) => agentsFinishModule.finishAgentSession(...callArgs);
21
+
22
+ function agentsStatePathForRepo(repoRoot) {
23
+ return path.join(repoRoot, AGENTS_BOTS_STATE_RELATIVE);
24
+ }
25
+
26
+ function readAgentsState(repoRoot) {
27
+ const statePath = agentsStatePathForRepo(repoRoot);
28
+ if (!fs.existsSync(statePath)) {
29
+ return null;
30
+ }
31
+ try {
32
+ return JSON.parse(fs.readFileSync(statePath, 'utf8'));
33
+ } catch (_error) {
34
+ return null;
35
+ }
36
+ }
37
+
38
+ function writeAgentsState(repoRoot, state) {
39
+ const statePath = agentsStatePathForRepo(repoRoot);
40
+ fs.mkdirSync(path.dirname(statePath), { recursive: true });
41
+ fs.writeFileSync(statePath, `${JSON.stringify(state, null, 2)}\n`, 'utf8');
42
+ }
43
+
44
+ function processAlive(pid) {
45
+ const normalizedPid = Number.parseInt(String(pid || ''), 10);
46
+ if (!Number.isInteger(normalizedPid) || normalizedPid <= 0) {
47
+ return false;
48
+ }
49
+ try {
50
+ process.kill(normalizedPid, 0);
51
+ } catch (_error) {
52
+ return false;
53
+ }
54
+
55
+ const state = readProcessState(normalizedPid);
56
+ if (state.startsWith('Z')) {
57
+ return false;
58
+ }
59
+ return true;
60
+ }
61
+
62
+ function sleepSeconds(seconds) {
63
+ const result = run('sleep', [String(seconds)]);
64
+ if (Boolean(result?.error) && typeof result?.status !== 'number') {
65
+ throw new Error(`sleep command failed for ${seconds}s`);
66
+ }
67
+ if (result.status !== 0) {
68
+ throw new Error(`sleep command failed for ${seconds}s`);
69
+ }
70
+ }
71
+
72
+ function readProcessCommand(pid) {
73
+ const result = run('ps', ['-o', 'command=', '-p', String(pid)]);
74
+ if ((Boolean(result?.error) && typeof result?.status !== 'number') || result.status !== 0) {
75
+ return '';
76
+ }
77
+ return String(result.stdout || '').trim();
78
+ }
79
+
80
+ function readProcessState(pid) {
81
+ const result = run('ps', ['-o', 'stat=', '-p', String(pid)]);
82
+ if ((Boolean(result?.error) && typeof result?.status !== 'number') || result.status !== 0) {
83
+ return '';
84
+ }
85
+ return String(result.stdout || '').trim();
86
+ }
87
+
88
+ function stopAgentProcessByPid(pid, expectedToken = '') {
89
+ const normalizedPid = Number.parseInt(String(pid || ''), 10);
90
+ if (!Number.isInteger(normalizedPid) || normalizedPid <= 0) {
91
+ return { status: 'invalid', pid: normalizedPid };
92
+ }
93
+ if (!processAlive(normalizedPid)) {
94
+ return { status: 'not-running', pid: normalizedPid };
95
+ }
96
+
97
+ if (expectedToken) {
98
+ const cmdline = readProcessCommand(normalizedPid);
99
+ if (cmdline && !cmdline.includes(expectedToken)) {
100
+ return { status: 'mismatch', pid: normalizedPid, command: cmdline };
101
+ }
102
+ }
103
+
104
+ try {
105
+ process.kill(-normalizedPid, 'SIGTERM');
106
+ } catch (_error) {
107
+ try {
108
+ process.kill(normalizedPid, 'SIGTERM');
109
+ } catch (_err) {
110
+ return { status: 'term-failed', pid: normalizedPid };
111
+ }
112
+ }
113
+
114
+ const deadline = Date.now() + 3_000;
115
+ while (Date.now() < deadline) {
116
+ if (!processAlive(normalizedPid)) {
117
+ return { status: 'stopped', pid: normalizedPid };
118
+ }
119
+ sleepSeconds(0.1);
120
+ }
121
+
122
+ try {
123
+ process.kill(-normalizedPid, 'SIGKILL');
124
+ } catch (_error) {
125
+ try {
126
+ process.kill(normalizedPid, 'SIGKILL');
127
+ } catch (_err) {
128
+ return { status: 'kill-failed', pid: normalizedPid };
129
+ }
130
+ }
131
+ sleepSeconds(0.1);
132
+
133
+ return {
134
+ status: processAlive(normalizedPid) ? 'kill-failed' : 'stopped',
135
+ pid: normalizedPid,
136
+ };
137
+ }
138
+
139
+ function spawnDetachedAgentProcess({ command, args, cwd, logPath }) {
140
+ fs.mkdirSync(path.dirname(logPath), { recursive: true });
141
+ const logHandle = fs.openSync(logPath, 'a');
142
+ fs.writeSync(
143
+ logHandle,
144
+ `[${new Date().toISOString()}] spawn: ${command} ${args.join(' ')}\n`,
145
+ );
146
+ const child = cp.spawn(command, args, {
147
+ cwd,
148
+ detached: true,
149
+ stdio: ['ignore', logHandle, logHandle],
150
+ env: process.env,
151
+ });
152
+ fs.closeSync(logHandle);
153
+ if (child.error) {
154
+ throw child.error;
155
+ }
156
+ child.unref();
157
+ const pid = Number.parseInt(String(child.pid || ''), 10);
158
+ if (!Number.isInteger(pid) || pid <= 0) {
159
+ throw new Error(`Failed to spawn detached process for ${command}`);
160
+ }
161
+ return pid;
162
+ }
163
+
164
+ function agents(rawArgs) {
165
+ const options = parseAgentsArgs(rawArgs);
166
+ if (['files', 'diff', 'locks'].includes(options.subcommand)) {
167
+ process.stdout.write(agentInspect.runInspectCommand(options));
168
+ process.exitCode = 0;
169
+ return;
170
+ }
171
+
172
+ const repoRoot = resolveRepoRoot(options.target);
173
+ const statePath = agentsStatePathForRepo(repoRoot);
174
+
175
+ if (options.subcommand === 'set-status') {
176
+ const result = agentActivity.runSetStatusCommand(repoRoot, options);
177
+ if (result.stdout) process.stdout.write(result.stdout);
178
+ if (result.stderr) process.stderr.write(result.stderr);
179
+ process.exitCode = result.status;
180
+ return;
181
+ }
182
+
183
+ if (options.subcommand === 'jump') {
184
+ const result = agentActivity.runJumpCommand(repoRoot, options);
185
+ if (result.stdout) process.stdout.write(result.stdout);
186
+ if (result.stderr) process.stderr.write(result.stderr);
187
+ process.exitCode = result.status;
188
+ return;
189
+ }
190
+
191
+ if (options.subcommand === 'finish') {
192
+ const result = finishAgentSession(repoRoot, options);
193
+ if (options.json) {
194
+ process.stdout.write(`${JSON.stringify(result.evidence, null, 2)}\n`);
195
+ }
196
+ process.exitCode = 0;
197
+ return;
198
+ }
199
+
200
+ if (options.subcommand === 'cleanup-sessions') {
201
+ process.stdout.write(agentCleanupSessions.runCleanupSessionsCommand(repoRoot, options));
202
+ process.exitCode = 0;
203
+ return;
204
+ }
205
+
206
+ if (options.subcommand === 'start') {
207
+ if (agentsStart.shouldUseInteractivePanel(options, process.stdin, process.stdout)) {
208
+ agentsStart.startInteractiveAgentPanel(repoRoot, options, {
209
+ onDone(result) {
210
+ process.exitCode = result.status;
211
+ },
212
+ });
213
+ return;
214
+ }
215
+ if (options.dryRun) {
216
+ const output = agentsStart.dryRunStart(options, repoRoot);
217
+ process.stdout.write(output.endsWith('\n') ? output : `${output}\n`);
218
+ process.exitCode = 0;
219
+ return;
220
+ }
221
+ if (options.panel && !options.task) {
222
+ process.stderr.write('[gitguardex] gx agents start --panel requires an interactive terminal when no task is provided.\n');
223
+ process.exitCode = 1;
224
+ return;
225
+ }
226
+ if (options.task) {
227
+ const result = agentsStart.startAgentLane(repoRoot, options);
228
+ if (result.stdout) process.stdout.write(result.stdout);
229
+ if (result.stderr) process.stderr.write(result.stderr);
230
+ process.exitCode = result.status;
231
+ return;
232
+ }
233
+
234
+ const existingState = readAgentsState(repoRoot);
235
+ const existingReviewPid = Number.parseInt(String(existingState?.review?.pid || ''), 10);
236
+ const existingCleanupPid = Number.parseInt(String(existingState?.cleanup?.pid || ''), 10);
237
+ const reviewRunning = processAlive(existingReviewPid);
238
+ const cleanupRunning = processAlive(existingCleanupPid);
239
+
240
+ if (reviewRunning && cleanupRunning) {
241
+ console.log(
242
+ `[${TOOL_NAME}] Repo agents already running (review pid=${existingReviewPid}, cleanup pid=${existingCleanupPid}).`,
243
+ );
244
+ process.exitCode = 0;
245
+ return;
246
+ }
247
+
248
+ const reviewLogPath = path.join(repoRoot, '.omx', 'logs', 'agent-review.log');
249
+ const cleanupLogPath = path.join(repoRoot, '.omx', 'logs', 'agent-cleanup.log');
250
+
251
+ let reviewPid = existingReviewPid;
252
+ let cleanupPid = existingCleanupPid;
253
+ let startedAny = false;
254
+ let reusedAny = false;
255
+
256
+ const mainScriptPath = require.resolve('../main.js');
257
+ if (!reviewRunning) {
258
+ reviewPid = spawnDetachedAgentProcess({
259
+ command: process.execPath,
260
+ args: [
261
+ mainScriptPath,
262
+ 'internal',
263
+ 'run-shell',
264
+ 'reviewBot',
265
+ '--target',
266
+ repoRoot,
267
+ '--interval',
268
+ String(options.reviewIntervalSeconds),
269
+ ],
270
+ cwd: repoRoot,
271
+ logPath: reviewLogPath,
272
+ });
273
+ startedAny = true;
274
+ } else {
275
+ reusedAny = true;
276
+ }
277
+
278
+ if (!cleanupRunning) {
279
+ cleanupPid = spawnDetachedAgentProcess({
280
+ command: process.execPath,
281
+ args: [
282
+ mainScriptPath,
283
+ 'cleanup',
284
+ '--target',
285
+ repoRoot,
286
+ '--watch',
287
+ '--interval',
288
+ String(options.cleanupIntervalSeconds),
289
+ '--idle-minutes',
290
+ String(options.idleMinutes),
291
+ ],
292
+ cwd: repoRoot,
293
+ logPath: cleanupLogPath,
294
+ });
295
+ startedAny = true;
296
+ } else {
297
+ reusedAny = true;
298
+ }
299
+
300
+ const priorReviewInterval = Number.parseInt(String(existingState?.review?.intervalSeconds || ''), 10);
301
+ const priorCleanupInterval = Number.parseInt(String(existingState?.cleanup?.intervalSeconds || ''), 10);
302
+ const priorIdleMinutes = Number.parseInt(String(existingState?.cleanup?.idleMinutes || ''), 10);
303
+ const reviewIntervalSeconds = reviewRunning && Number.isInteger(priorReviewInterval) && priorReviewInterval >= 5
304
+ ? priorReviewInterval
305
+ : options.reviewIntervalSeconds;
306
+ const cleanupIntervalSeconds = cleanupRunning && Number.isInteger(priorCleanupInterval) && priorCleanupInterval >= 5
307
+ ? priorCleanupInterval
308
+ : options.cleanupIntervalSeconds;
309
+ const idleMinutes = cleanupRunning && Number.isInteger(priorIdleMinutes) && priorIdleMinutes >= 1
310
+ ? priorIdleMinutes
311
+ : options.idleMinutes;
312
+
313
+ writeAgentsState(repoRoot, {
314
+ schemaVersion: 1,
315
+ repoRoot,
316
+ startedAt: new Date().toISOString(),
317
+ review: {
318
+ pid: reviewPid,
319
+ intervalSeconds: reviewIntervalSeconds,
320
+ script: mainScriptPath,
321
+ logPath: reviewLogPath,
322
+ },
323
+ cleanup: {
324
+ pid: cleanupPid,
325
+ intervalSeconds: cleanupIntervalSeconds,
326
+ idleMinutes,
327
+ script: mainScriptPath,
328
+ logPath: cleanupLogPath,
329
+ },
330
+ });
331
+
332
+ console.log(
333
+ `[${TOOL_NAME}] Started repo agents in ${repoRoot} (review pid=${reviewPid}, cleanup pid=${cleanupPid}).`,
334
+ );
335
+ if (reusedAny && startedAny) {
336
+ console.log(`[${TOOL_NAME}] Reused healthy bot process(es) and started only missing ones.`);
337
+ }
338
+ console.log(`[${TOOL_NAME}] Logs: ${reviewLogPath}, ${cleanupLogPath}`);
339
+ process.exitCode = 0;
340
+ return;
341
+ }
342
+
343
+ if (options.subcommand === 'stop') {
344
+ if (options.pid) {
345
+ const stopResult = stopAgentProcessByPid(options.pid);
346
+ const success = ['stopped', 'not-running'].includes(stopResult.status);
347
+ console.log(
348
+ `[${TOOL_NAME}] Stopped agent pid ${options.pid} (${stopResult.status}).`,
349
+ );
350
+ process.exitCode = success ? 0 : 1;
351
+ return;
352
+ }
353
+
354
+ const existingState = readAgentsState(repoRoot);
355
+ if (!existingState) {
356
+ console.log(`[${TOOL_NAME}] Repo agents are not running for ${repoRoot}.`);
357
+ process.exitCode = 0;
358
+ return;
359
+ }
360
+
361
+ const reviewStop = stopAgentProcessByPid(existingState?.review?.pid, 'internal run-shell reviewBot');
362
+ const cleanupStop = stopAgentProcessByPid(existingState?.cleanup?.pid, `${path.basename(require.resolve('../main.js'))} cleanup`);
363
+
364
+ if (fs.existsSync(statePath)) {
365
+ fs.unlinkSync(statePath);
366
+ }
367
+
368
+ console.log(
369
+ `[${TOOL_NAME}] Stopped repo agents in ${repoRoot} (review=${reviewStop.status}, cleanup=${cleanupStop.status}).`,
370
+ );
371
+ process.exitCode = 0;
372
+ return;
373
+ }
374
+
375
+ process.stdout.write(agentStatus.runStatusCommand(repoRoot, options));
376
+ process.exitCode = 0;
377
+ }
378
+
379
+ module.exports = {
380
+ agents,
381
+ };