@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,39 +1,5 @@
1
1
  const path = require('node:path');
2
2
 
3
- function requireFlagValue(rawArgs, index, flagName) {
4
- const value = rawArgs[index + 1];
5
- if (!value || value.startsWith('--')) {
6
- throw new Error(`${flagName} requires a value`);
7
- }
8
- return value;
9
- }
10
-
11
- function parseHeartbeatArgs(rawArgs) {
12
- let branch = '';
13
- let state = '';
14
-
15
- for (let index = 0; index < rawArgs.length; index += 1) {
16
- const arg = rawArgs[index];
17
- if (arg === '--branch') {
18
- branch = requireFlagValue(rawArgs, index, '--branch');
19
- index += 1;
20
- continue;
21
- }
22
- if (arg === '--state') {
23
- state = requireFlagValue(rawArgs, index, '--state');
24
- index += 1;
25
- continue;
26
- }
27
- throw new Error(`Unknown heartbeat option: ${arg}`);
28
- }
29
-
30
- if (!branch) {
31
- throw new Error('heartbeat requires --branch <agent/...>');
32
- }
33
-
34
- return { branch, state };
35
- }
36
-
37
3
  function hook(rawArgs, deps) {
38
4
  const {
39
5
  extractTargetedArgs,
@@ -89,36 +55,6 @@ function internal(rawArgs, deps) {
89
55
  } = deps;
90
56
 
91
57
  const [subcommand, assetKey, ...rest] = rawArgs;
92
- if (subcommand === 'heartbeat') {
93
- const { target, passthrough } = extractTargetedArgs([assetKey, ...rest].filter(Boolean));
94
- const repoRoot = resolveRepoRoot(target);
95
- const options = parseHeartbeatArgs(passthrough);
96
- const heartbeatArgs = ['heartbeat', '--repo', repoRoot, '--branch', options.branch];
97
- if (options.state) {
98
- heartbeatArgs.push('--state', options.state);
99
- }
100
- const result = runPackageAsset('sessionState', heartbeatArgs, { cwd: repoRoot });
101
- if (result.stdout) process.stdout.write(result.stdout);
102
- if (result.stderr) process.stderr.write(result.stderr);
103
- process.exitCode = result.status;
104
- return;
105
- }
106
- if (subcommand === 'stop-session') {
107
- const { target, passthrough } = extractTargetedArgs([assetKey, ...rest].filter(Boolean));
108
- const repoRoot = resolveRepoRoot(target);
109
- const options = parseHeartbeatArgs(passthrough);
110
- const result = runPackageAsset('sessionState', [
111
- 'terminate',
112
- '--repo',
113
- repoRoot,
114
- '--branch',
115
- options.branch,
116
- ], { cwd: repoRoot });
117
- if (result.stdout) process.stdout.write(result.stdout);
118
- if (result.stderr) process.stderr.write(result.stderr);
119
- process.exitCode = result.status;
120
- return;
121
- }
122
58
  if (subcommand !== 'run-shell') {
123
59
  throw new Error(`Unknown internal command: ${subcommand || '(missing)'}`);
124
60
  }
@@ -0,0 +1,394 @@
1
+ 'use strict';
2
+
3
+ // Read-only collector for the gx MCP server. Assembles a cross-repo picture of
4
+ // "which agent is on which branch / worktree / PR, and what file locks they
5
+ // hold" purely from git + gitguardex on-disk state — no manual bookkeeping.
6
+ //
7
+ // Sources (all already maintained by gitguardex):
8
+ // - repo discovery : cockpit/projects-finder.findProjects()
9
+ // - branches/worktrees: `git worktree list --porcelain`
10
+ // - file locks : .omx/state/agent-file-locks.json
11
+ // - PR state : pr.findOpenPrForBranch() (gh, best-effort)
12
+
13
+ const cp = require('node:child_process');
14
+ const fs = require('node:fs');
15
+ const path = require('node:path');
16
+
17
+ const { findProjects } = require('../cockpit/projects-finder');
18
+ const { findOpenPrForBranch, listOpenPrsForRepo } = require('../pr');
19
+
20
+ const PROTECTED_BRANCHES = new Set(['main', 'master', 'dev']);
21
+ const LOCK_FILE_RELATIVE = path.join('.omx', 'state', 'agent-file-locks.json');
22
+ // A lane older than this (days since last commit), with no open PR and no
23
+ // uncommitted work, is flagged `stale: true` — a candidate for cleanup.
24
+ const STALE_DAYS = Number(process.env.GUARDEX_MCP_STALE_DAYS) || 14;
25
+
26
+ function git(repoRoot, args) {
27
+ // Bounded: a hung git call must not stall the whole MCP request past the
28
+ // client timeout. On timeout spawnSync sets status=null -> we return null.
29
+ const res = cp.spawnSync('git', args, {
30
+ cwd: repoRoot,
31
+ encoding: 'utf8',
32
+ timeout: 7000,
33
+ maxBuffer: 8 * 1024 * 1024,
34
+ });
35
+ if (!res || res.status !== 0) return null;
36
+ return (res.stdout || '').trim();
37
+ }
38
+
39
+ // Files an agent is changing RIGHT NOW in a worktree (uncommitted). Unlike
40
+ // locks (written at commit time), this reflects in-progress edits — the most
41
+ // direct "who is working on what" signal.
42
+ function dirtyFiles(worktreePath, cap = 25) {
43
+ // NB: parse RAW stdout (not the trimmed git() helper) — porcelain is
44
+ // column-sensitive ("XY PATH"); trimming eats the first line's leading
45
+ // status space and shifts the path by one.
46
+ const res = cp.spawnSync('git', ['status', '--porcelain'], {
47
+ cwd: worktreePath,
48
+ encoding: 'utf8',
49
+ timeout: 7000,
50
+ maxBuffer: 8 * 1024 * 1024,
51
+ });
52
+ if (!res || res.status !== 0 || !res.stdout) return [];
53
+ const files = res.stdout
54
+ .split('\n')
55
+ .filter((line) => line.length > 3)
56
+ .map((line) => line.slice(3))
57
+ .filter(Boolean)
58
+ // Exclude gitguardex runtime state — it's bookkeeping churn, not the
59
+ // agent's work (and is gitignored in real repos anyway).
60
+ .filter((f) => !f.startsWith('.omx/') && !f.startsWith('.omc/'));
61
+ if (files.length <= cap) return files;
62
+ return files.slice(0, cap).concat([`…(+${files.length - cap} more)`]);
63
+ }
64
+
65
+ function isProtectedBranch(branch) {
66
+ return !branch || branch === 'HEAD' || PROTECTED_BRANCHES.has(branch);
67
+ }
68
+
69
+ function parseAgentName(branch) {
70
+ // agent/<name>/<slug> -> name
71
+ const parts = String(branch || '').split('/');
72
+ if (parts.length >= 3 && parts[0] === 'agent') return parts[1];
73
+ return null;
74
+ }
75
+
76
+ function humanizeSlug(branch) {
77
+ const parts = String(branch || '').split('/');
78
+ const slug = (parts.length >= 3 ? parts.slice(2).join('/') : parts.slice(1).join('/')) || branch;
79
+ return slug.replace(/-\d{4}-\d{2}-\d{2}.*$/, '').replace(/-/g, ' ').trim() || branch;
80
+ }
81
+
82
+ function repoName(repoPath) {
83
+ return path.basename(repoPath || '');
84
+ }
85
+
86
+ function listWorktrees(repoRoot) {
87
+ const out = git(repoRoot, ['worktree', 'list', '--porcelain']);
88
+ if (out == null) return [];
89
+ const worktrees = [];
90
+ out.split(/\n\n+/).forEach((block, idx) => {
91
+ let wtPath = null;
92
+ let branch = null;
93
+ let head = null;
94
+ let detached = false;
95
+ for (const line of block.split('\n')) {
96
+ if (line.startsWith('worktree ')) wtPath = line.slice(9).trim();
97
+ else if (line.startsWith('branch ')) branch = line.slice(7).trim().replace(/^refs\/heads\//, '');
98
+ else if (line.startsWith('HEAD ')) head = line.slice(5).trim();
99
+ else if (line.trim() === 'detached') detached = true;
100
+ }
101
+ if (wtPath) worktrees.push({ path: wtPath, branch: detached ? null : branch, head, isPrimary: idx === 0 });
102
+ });
103
+ return worktrees;
104
+ }
105
+
106
+ function readLockMap(repoRoot) {
107
+ const lockPath = path.join(repoRoot, LOCK_FILE_RELATIVE);
108
+ let raw;
109
+ try {
110
+ raw = fs.readFileSync(lockPath, 'utf8');
111
+ } catch {
112
+ return {};
113
+ }
114
+ try {
115
+ const data = JSON.parse(raw);
116
+ return (data && data.locks) || {};
117
+ } catch {
118
+ // stdout is reserved for JSON-RPC; surface the problem on stderr so a
119
+ // poisoned lock file doesn't silently hide claims.
120
+ process.stderr.write(`[gx mcp] warning: ignoring corrupt lock file ${lockPath}\n`);
121
+ return {};
122
+ }
123
+ }
124
+
125
+ function locksByBranch(repoRoot) {
126
+ const map = readLockMap(repoRoot);
127
+ const byBranch = {};
128
+ for (const [file, meta] of Object.entries(map)) {
129
+ const b = meta && meta.branch;
130
+ if (!b) continue;
131
+ (byBranch[b] = byBranch[b] || []).push(file);
132
+ }
133
+ return byBranch;
134
+ }
135
+
136
+ // Resolve the MAIN repository root from any path inside it (a linked agent
137
+ // worktree resolves up to the primary checkout). Worktrees share one ref store
138
+ // via --git-common-dir, so all git ref ops below run against the main root.
139
+ function mainRepoRoot(somePath) {
140
+ const top = git(somePath, ['rev-parse', '--show-toplevel']);
141
+ if (!top) return null;
142
+ const common = git(somePath, ['rev-parse', '--git-common-dir']);
143
+ if (!common) return top;
144
+ const commonAbs = path.isAbsolute(common) ? common : path.resolve(top, common);
145
+ return path.basename(commonAbs) === '.git' ? path.dirname(commonAbs) : top;
146
+ }
147
+
148
+ function branchHasUpstream(repoRoot, branch) {
149
+ return Boolean(git(repoRoot, ['rev-parse', '--abbrev-ref', `${branch}@{upstream}`]));
150
+ }
151
+
152
+ function lastCommit(repoRoot, branch) {
153
+ const out = git(repoRoot, ['log', '-1', '--format=%cI%x09%s', branch]);
154
+ if (!out) return null;
155
+ const tab = out.indexOf('\t');
156
+ if (tab === -1) return { date: out, subject: '' };
157
+ return { date: out.slice(0, tab), subject: out.slice(tab + 1) };
158
+ }
159
+
160
+ // Best-effort PR lookup. Skips gh entirely for un-pushed branches, and never
161
+ // throws (gh missing / unauthed / offline -> null).
162
+ function safePr(repoRoot, branch) {
163
+ if (!branchHasUpstream(repoRoot, branch)) return null;
164
+ try {
165
+ const pr = findOpenPrForBranch(repoRoot, branch);
166
+ return pr ? slimPr(pr) : null;
167
+ } catch {
168
+ return null;
169
+ }
170
+ }
171
+
172
+ function slimPr(pr) {
173
+ return {
174
+ number: pr.number,
175
+ url: pr.url,
176
+ state: pr.state,
177
+ isDraft: pr.isDraft,
178
+ title: pr.title,
179
+ baseRefName: pr.baseRefName,
180
+ reviewDecision: pr.reviewDecision || null,
181
+ mergeable: pr.mergeable || null,
182
+ mergeStateStatus: pr.mergeStateStatus || null,
183
+ };
184
+ }
185
+
186
+ // Pure: index a `gh pr list` array by its branch (headRefName) for O(1) lookup.
187
+ function indexPrsByBranch(prs) {
188
+ const map = {};
189
+ for (const pr of prs || []) {
190
+ if (pr && pr.headRefName) map[pr.headRefName] = slimPr(pr);
191
+ }
192
+ return map;
193
+ }
194
+
195
+ // One gh call per repo -> { map: branch->PR, error }. Best-effort (never throws).
196
+ // `error` is set when the lookup itself failed (gh missing/unauthed/offline),
197
+ // distinct from a successful lookup that found no open PRs.
198
+ function prMapForRepo(mainRoot) {
199
+ try {
200
+ const { prs, error } = listOpenPrsForRepo(mainRoot);
201
+ return { map: indexPrsByBranch(prs), error: error || null };
202
+ } catch (err) {
203
+ return { map: {}, error: String((err && err.message) || err) };
204
+ }
205
+ }
206
+
207
+ // Whole days since an ISO timestamp, or null. Pure (now injected) for testing.
208
+ function daysSince(iso, nowMs) {
209
+ if (!iso) return null;
210
+ const t = Date.parse(iso);
211
+ if (Number.isNaN(t)) return null;
212
+ return Math.floor((nowMs - t) / 86400000);
213
+ }
214
+
215
+ function buildAgentRecord(mainRoot, wt, locks, prInfo, nowMs) {
216
+ const branch = wt.branch;
217
+ const record = {
218
+ repo: repoName(mainRoot),
219
+ repoPath: mainRoot,
220
+ branch,
221
+ agent: parseAgentName(branch),
222
+ task: humanizeSlug(branch),
223
+ worktree: wt.path,
224
+ onPrimaryCheckout: Boolean(wt.isPrimary),
225
+ pushed: branchHasUpstream(mainRoot, branch),
226
+ dirty: dirtyFiles(wt.path),
227
+ locks,
228
+ lastCommit: lastCommit(mainRoot, branch),
229
+ pr: prInfo ? prInfo.map[branch] || null : null,
230
+ prLookupError: prInfo ? prInfo.error : null,
231
+ };
232
+ // Stale = old, no open PR, no uncommitted work — a safe prune candidate.
233
+ record.ageDays = record.lastCommit ? daysSince(record.lastCommit.date, nowMs) : null;
234
+ record.stale = record.ageDays != null
235
+ && record.ageDays > STALE_DAYS
236
+ && !record.pr
237
+ && record.dirty.length === 0;
238
+ if (wt.isPrimary) {
239
+ record.warning =
240
+ 'on the PRIMARY checkout, not an isolated worktree — edits here risk auto-stash/revert when another lane switches branches. Use `gx branch start`.';
241
+ }
242
+ return record;
243
+ }
244
+
245
+ function isAgentLane(wt) {
246
+ // An active agent lane = a worktree on a non-protected branch (or the primary
247
+ // checkout sitting on a working branch, surfaced later with a warning).
248
+ if (!wt.branch) return false;
249
+ if (isProtectedBranch(wt.branch) && !wt.isPrimary) return false;
250
+ if (wt.isPrimary && isProtectedBranch(wt.branch)) return false;
251
+ return true;
252
+ }
253
+
254
+ function collectRepoAgents(repoPath, { includePrs = true } = {}) {
255
+ const mainRoot = mainRepoRoot(repoPath) || repoPath;
256
+ const lanes = listWorktrees(mainRoot).filter(isAgentLane);
257
+ if (lanes.length === 0) return []; // no lanes -> no gh call for this repo
258
+ // ONE gh call for the whole repo, only when there is at least one lane.
259
+ const prInfo = includePrs ? prMapForRepo(mainRoot) : null;
260
+ const nowMs = Date.now();
261
+ return lanes.map((wt) => {
262
+ // Each worktree owns its OWN lock file; a lane's locks are the entries in
263
+ // its own worktree keyed to its branch.
264
+ const locks = locksByBranch(wt.path)[wt.branch] || [];
265
+ return buildAgentRecord(mainRoot, wt, locks, prInfo, nowMs);
266
+ });
267
+ }
268
+
269
+ function collectAllAgents({ roots, includePrs = true, limit } = {}) {
270
+ const found = findProjects(roots && roots.length ? { roots } : {});
271
+ const projects = Array.isArray(found.projects) ? found.projects : [];
272
+ // Collapse discovered paths to unique MAIN repo roots — a repo and its linked
273
+ // worktrees must not be counted as separate "repos".
274
+ const seen = new Set();
275
+ const mainRoots = [];
276
+ for (const project of projects) {
277
+ const root = mainRepoRoot(project.path) || project.path;
278
+ if (seen.has(root)) continue;
279
+ seen.add(root);
280
+ mainRoots.push(root);
281
+ if (limit && mainRoots.length >= limit) break;
282
+ }
283
+ const agents = [];
284
+ const errors = [];
285
+ for (const root of mainRoots) {
286
+ try {
287
+ agents.push(...collectRepoAgents(root, { includePrs }));
288
+ } catch (err) {
289
+ errors.push({ repo: root, error: String((err && err.message) || err) });
290
+ }
291
+ }
292
+ agents.sort((a, b) => {
293
+ const da = (a.lastCommit && a.lastCommit.date) || '';
294
+ const db = (b.lastCommit && b.lastCommit.date) || '';
295
+ return db.localeCompare(da); // most recent activity first
296
+ });
297
+ return { agents, scannedRepos: mainRoots.length, roots: found.roots || [], errors };
298
+ }
299
+
300
+ function repoState(repoOrCwd, { includePrs = true } = {}) {
301
+ const root = mainRepoRoot(repoOrCwd) || repoOrCwd;
302
+ return { repo: repoName(root), repoPath: root, agents: collectRepoAgents(root, { includePrs }) };
303
+ }
304
+
305
+ // Aggregate locks across ALL worktrees of the repo. Lock files are per-worktree
306
+ // on disk, so a single worktree's file only shows its own claims — the
307
+ // collision view requires the union.
308
+ function whoOwns(file, { cwd = process.cwd(), repoPath } = {}) {
309
+ if (!file) return { file: null, owner: null, error: 'no file given' };
310
+ const mainRoot = mainRepoRoot(repoPath || cwd);
311
+ if (!mainRoot) return { file, owner: null, error: 'not a git repo' };
312
+ const rel = path.isAbsolute(file) ? path.relative(mainRoot, file) : file;
313
+ const owners = [];
314
+ const seenBranch = new Set();
315
+ for (const wt of listWorktrees(mainRoot)) {
316
+ const map = readLockMap(wt.path);
317
+ const entry = map[rel] || map[file];
318
+ if (entry && entry.branch && !seenBranch.has(entry.branch)) {
319
+ seenBranch.add(entry.branch);
320
+ owners.push({
321
+ branch: entry.branch,
322
+ agent: parseAgentName(entry.branch),
323
+ claimed_at: entry.claimed_at || null,
324
+ worktree: wt.path,
325
+ });
326
+ }
327
+ }
328
+ if (owners.length === 0) return { file: rel, owner: null };
329
+ return { file: rel, owner: owners.length === 1 ? owners[0] : null, owners, conflict: owners.length > 1 };
330
+ }
331
+
332
+ // Slim "radar" projection of a lane for list_agents — who-is-on-what at a
333
+ // glance, ~80% smaller than the full record. File LISTS collapse to counts and
334
+ // the worktree path is dropped; an agent that needs detail (worktree path,
335
+ // exact dirty/lock files, full PR) calls repo_state / my_context, or passes
336
+ // detail:true to list_agents. Pure.
337
+ function radarRecord(a) {
338
+ const r = { repo: a.repo, branch: a.branch };
339
+ if (a.agent) r.agent = a.agent;
340
+ if (a.task && a.task !== a.branch) r.task = a.task;
341
+ if (a.dirty && a.dirty.length) r.dirty = a.dirty.length;
342
+ if (a.locks && a.locks.length) r.locks = a.locks.length;
343
+ if (a.pr && a.pr.number != null) r.pr = a.pr.number;
344
+ if (a.prLookupError) r.prLookupError = a.prLookupError;
345
+ if (a.lastCommit && a.lastCommit.date) r.last = a.lastCommit.date.slice(0, 10);
346
+ if (a.stale) {
347
+ r.stale = true;
348
+ if (a.ageDays != null) r.ageDays = a.ageDays; // age is the actionable bit for a prune candidate
349
+ }
350
+ if (a.warning) r.onPrimary = true; // lane editing the primary checkout (unsafe)
351
+ if (a.pushed === false) r.unpushed = true;
352
+ return r;
353
+ }
354
+
355
+ function myContext({ cwd = process.cwd(), includePr = true } = {}) {
356
+ const here = git(cwd, ['rev-parse', '--show-toplevel']);
357
+ if (!here) return { error: 'not a git repo', cwd };
358
+ const mainRoot = mainRepoRoot(cwd) || here;
359
+ const branch = git(here, ['rev-parse', '--abbrev-ref', 'HEAD']);
360
+ const self = listWorktrees(mainRoot).find((w) => path.resolve(w.path) === path.resolve(here));
361
+ const lc = branch ? lastCommit(mainRoot, branch) : null;
362
+ return {
363
+ repo: repoName(mainRoot),
364
+ repoPath: mainRoot,
365
+ worktree: here,
366
+ branch,
367
+ agent: parseAgentName(branch),
368
+ onPrimaryCheckout: self ? Boolean(self.isPrimary) : null,
369
+ protected: isProtectedBranch(branch),
370
+ dirty: dirtyFiles(here),
371
+ locks: branch ? locksByBranch(here)[branch] || [] : [], // this lane's own claims
372
+ pr: includePr && branch ? safePr(mainRoot, branch) : null,
373
+ lastCommit: lc,
374
+ ageDays: lc ? daysSince(lc.date, Date.now()) : null,
375
+ };
376
+ }
377
+
378
+ module.exports = {
379
+ collectAllAgents,
380
+ collectRepoAgents,
381
+ repoState,
382
+ whoOwns,
383
+ myContext,
384
+ radarRecord,
385
+ indexPrsByBranch,
386
+ daysSince,
387
+ STALE_DAYS,
388
+ listWorktrees,
389
+ locksByBranch,
390
+ parseAgentName,
391
+ humanizeSlug,
392
+ isProtectedBranch,
393
+ LOCK_FILE_RELATIVE,
394
+ };
@@ -0,0 +1,163 @@
1
+ 'use strict';
2
+
3
+ // Minimal Model Context Protocol server over stdio, hand-rolled to keep
4
+ // gitguardex dependency-light (no @modelcontextprotocol/sdk). MCP stdio is
5
+ // newline-delimited JSON-RPC 2.0; we implement the small surface an agent
6
+ // needs: initialize, tools/list, tools/call, ping.
7
+ //
8
+ // All tools are READ-ONLY — the server only reflects git/worktree/lock/PR
9
+ // state, it never mutates a repo.
10
+
11
+ const readline = require('node:readline');
12
+
13
+ const collect = require('./collect');
14
+ const { packageJson } = require('../context');
15
+
16
+ const PROTOCOL_VERSION = '2024-11-05';
17
+
18
+ const TOOLS = [
19
+ {
20
+ name: 'list_agents',
21
+ description:
22
+ 'List every active agent lane across all discovered repos. Returns a COMPACT radar by default — per lane: repo, branch, agent, task, dirty (count of files changed right now), locks (count), pr (number), last (commit date), and flags stale / onPrimary / unpushed when set. Use it to see who is working on what before you start. For full detail on a lane (worktree path, the actual dirty/lock file lists, full PR), call repo_state or my_context, or pass detail:true here (where the onPrimary flag appears as warning + onPrimaryCheckout instead). Read-only.',
23
+ inputSchema: {
24
+ type: 'object',
25
+ properties: {
26
+ include_prs: {
27
+ type: 'boolean',
28
+ description: 'Fetch PR state via gh (one call per repo that has lanes). Default true; pass false to skip gh entirely.',
29
+ },
30
+ roots: {
31
+ type: 'array',
32
+ items: { type: 'string' },
33
+ description: 'Override repo search roots. Default: ~/Documents, ~/code, ~/src, ~/projects.',
34
+ },
35
+ limit: { type: 'number', description: 'Max number of repos to scan.' },
36
+ detail: { type: 'boolean', description: 'Return full lane records (worktree path, dirty/lock file lists, full PR) instead of the compact radar. Default false.' },
37
+ },
38
+ },
39
+ },
40
+ {
41
+ name: 'repo_state',
42
+ description:
43
+ 'Agent lanes for a single repository (branches, worktrees, file locks, PRs). Pass a repo path; defaults to the current working repo.',
44
+ inputSchema: {
45
+ type: 'object',
46
+ properties: {
47
+ repo: { type: 'string', description: 'Path inside the target repo. Defaults to cwd.' },
48
+ include_prs: { type: 'boolean', description: 'Fetch PR state. Default true.' },
49
+ },
50
+ },
51
+ },
52
+ {
53
+ name: 'who_owns',
54
+ description:
55
+ 'Check which agent/branch holds the gitguardex file lock on a path BEFORE you edit it, to avoid colliding with another agent. Returns owner=null when the file is unclaimed.',
56
+ inputSchema: {
57
+ type: 'object',
58
+ properties: {
59
+ file: { type: 'string', description: 'Repo-relative or absolute path to check.' },
60
+ repo: { type: 'string', description: 'Path inside the target repo. Defaults to cwd.' },
61
+ },
62
+ required: ['file'],
63
+ },
64
+ },
65
+ {
66
+ name: 'my_context',
67
+ description:
68
+ 'Report THIS session: current repo, branch, worktree, whether it is the protected primary checkout (where edits are unsafe), held locks, and the PR for the branch.',
69
+ inputSchema: { type: 'object', properties: {} },
70
+ },
71
+ ];
72
+
73
+ function callTool(name, args = {}) {
74
+ switch (name) {
75
+ case 'list_agents': {
76
+ // PRs on by default: one gh call per repo that has active lanes (most
77
+ // repos have none, so they cost nothing). Pass include_prs:false to skip.
78
+ const full = collect.collectAllAgents({
79
+ roots: args.roots,
80
+ includePrs: args.include_prs !== false,
81
+ limit: args.limit,
82
+ });
83
+ // Compact radar by default (~80% fewer tokens); detail:true keeps the
84
+ // full records for callers that need worktree paths / file lists.
85
+ if (args.detail) return full;
86
+ return { ...full, agents: full.agents.map(collect.radarRecord) };
87
+ }
88
+ case 'repo_state':
89
+ return collect.repoState(args.repo || process.cwd(), { includePrs: args.include_prs !== false });
90
+ case 'who_owns':
91
+ return collect.whoOwns(args.file, { repoPath: args.repo });
92
+ case 'my_context':
93
+ return collect.myContext({});
94
+ default:
95
+ throw new Error(`Unknown tool: ${name}`);
96
+ }
97
+ }
98
+
99
+ function ok(id, result) {
100
+ return id === undefined || id === null ? null : { jsonrpc: '2.0', id, result };
101
+ }
102
+
103
+ function rpcError(id, code, message) {
104
+ return id === undefined || id === null ? null : { jsonrpc: '2.0', id, error: { code, message } };
105
+ }
106
+
107
+ // Pure request handler: returns a JSON-RPC response object, or null for
108
+ // notifications (no `id`). Kept side-effect-free so it is unit-testable.
109
+ function dispatch(msg) {
110
+ const { id, method, params } = msg || {};
111
+ const isNotification = id === undefined || id === null;
112
+ try {
113
+ if (method === 'initialize') {
114
+ // Pin the version WE support, regardless of what the client requested —
115
+ // echoing an unknown/future version back defeats MCP version negotiation.
116
+ return ok(id, {
117
+ protocolVersion: PROTOCOL_VERSION,
118
+ capabilities: { tools: {} },
119
+ serverInfo: { name: 'gx', version: (packageJson && packageJson.version) || '0.0.0' },
120
+ });
121
+ }
122
+ if (method === 'tools/list') return ok(id, { tools: TOOLS });
123
+ if (method === 'tools/call') {
124
+ const name = params && params.name;
125
+ const args = (params && params.arguments) || {};
126
+ const result = callTool(name, args);
127
+ return ok(id, { content: [{ type: 'text', text: JSON.stringify(result) }] });
128
+ }
129
+ if (method === 'ping') return ok(id, {});
130
+ if (isNotification) return null; // e.g. notifications/initialized
131
+ return rpcError(id, -32601, `Method not found: ${method}`);
132
+ } catch (err) {
133
+ const message = String((err && err.message) || err);
134
+ // A failing tool call is reported as a tool result (isError), per MCP, so
135
+ // the agent sees the error instead of the whole call rejecting.
136
+ if (method === 'tools/call' && !isNotification) {
137
+ return ok(id, { content: [{ type: 'text', text: `Error: ${message}` }], isError: true });
138
+ }
139
+ if (isNotification) return null;
140
+ return rpcError(id, -32603, message);
141
+ }
142
+ }
143
+
144
+ function serve({ input = process.stdin, output = process.stdout } = {}) {
145
+ const rl = readline.createInterface({ input, terminal: false });
146
+ rl.on('line', (line) => {
147
+ const trimmed = line.trim();
148
+ if (!trimmed) return;
149
+ let msg;
150
+ try {
151
+ msg = JSON.parse(trimmed);
152
+ } catch {
153
+ // JSON-RPC 2.0: a parse error is reported with a null id.
154
+ output.write(`${JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } })}\n`);
155
+ return;
156
+ }
157
+ const res = dispatch(msg);
158
+ if (res) output.write(`${JSON.stringify(res)}\n`);
159
+ });
160
+ return rl;
161
+ }
162
+
163
+ module.exports = { serve, dispatch, callTool, TOOLS, PROTOCOL_VERSION };