@imdeadpool/guardex 8.3.0 → 8.4.0
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/README.md +40 -21
- package/package.json +1 -1
- package/src/agents/message.js +764 -0
- package/src/agents/sessions.js +23 -1
- package/src/cli/args.js +54 -7
- package/src/cli/commands/agents.js +17 -0
- package/src/cli/commands/branch.js +42 -1
- package/src/cli/commands/mcp.js +4 -3
- package/src/cli/shared/sandbox.js +5 -53
- package/src/mcp/collect.js +52 -3
- package/src/mcp/server.js +54 -2
- package/src/scaffold/index.js +3 -0
- package/templates/scripts/agent-file-locks.py +82 -0
- package/templates/scripts/agent-worktree-prune.sh +14 -4
package/src/agents/sessions.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
const crypto = require('node:crypto');
|
|
2
|
+
const cp = require('node:child_process');
|
|
2
3
|
const fs = require('node:fs');
|
|
3
4
|
const path = require('node:path');
|
|
4
5
|
|
|
@@ -22,8 +23,27 @@ const SESSION_FIELDS = [
|
|
|
22
23
|
'updatedAt',
|
|
23
24
|
];
|
|
24
25
|
|
|
26
|
+
function stateRepoRoot(repoRoot) {
|
|
27
|
+
const root = path.resolve(repoRoot);
|
|
28
|
+
const result = cp.spawnSync('git', ['rev-parse', '--git-common-dir'], {
|
|
29
|
+
cwd: root,
|
|
30
|
+
encoding: 'utf8',
|
|
31
|
+
timeout: 3000,
|
|
32
|
+
maxBuffer: 1024 * 1024,
|
|
33
|
+
});
|
|
34
|
+
if (!result || result.status !== 0) return root;
|
|
35
|
+
const common = String(result.stdout || '').trim();
|
|
36
|
+
if (!common) return root;
|
|
37
|
+
const absolute = path.isAbsolute(common) ? common : path.resolve(root, common);
|
|
38
|
+
return path.basename(absolute) === '.git' ? path.dirname(absolute) : root;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function agentStateDir(repoRoot) {
|
|
42
|
+
return path.join(stateRepoRoot(repoRoot), '.guardex', 'agents');
|
|
43
|
+
}
|
|
44
|
+
|
|
25
45
|
function sessionsDir(repoRoot) {
|
|
26
|
-
return path.join(repoRoot, '
|
|
46
|
+
return path.join(agentStateDir(repoRoot), 'sessions');
|
|
27
47
|
}
|
|
28
48
|
|
|
29
49
|
function assertSessionId(sessionId) {
|
|
@@ -141,6 +161,8 @@ function removeAgentSession(repoRoot, sessionId) {
|
|
|
141
161
|
}
|
|
142
162
|
|
|
143
163
|
module.exports = {
|
|
164
|
+
agentStateDir,
|
|
165
|
+
stateRepoRoot,
|
|
144
166
|
sessionFilePath,
|
|
145
167
|
sessionsDir,
|
|
146
168
|
createAgentSession,
|
package/src/cli/args.js
CHANGED
|
@@ -193,11 +193,11 @@ function parseSetupArgs(rawArgs, defaults) {
|
|
|
193
193
|
|
|
194
194
|
for (let index = 0; index < rawArgs.length; index += 1) {
|
|
195
195
|
const arg = rawArgs[index];
|
|
196
|
-
if (arg === '--parent-workspace-view') {
|
|
196
|
+
if (arg === '--parent-workspace-view' || arg === '--vscode-worktree-view') {
|
|
197
197
|
setupDefaults.parentWorkspaceView = true;
|
|
198
198
|
continue;
|
|
199
199
|
}
|
|
200
|
-
if (arg === '--no-parent-workspace-view') {
|
|
200
|
+
if (arg === '--no-parent-workspace-view' || arg === '--no-vscode-worktree-view') {
|
|
201
201
|
setupDefaults.parentWorkspaceView = false;
|
|
202
202
|
continue;
|
|
203
203
|
}
|
|
@@ -391,6 +391,9 @@ function parseAgentsArgs(rawArgs) {
|
|
|
391
391
|
waiting: false,
|
|
392
392
|
done: false,
|
|
393
393
|
print: false,
|
|
394
|
+
message: '',
|
|
395
|
+
sourceSessionId: '',
|
|
396
|
+
ackMessageId: '',
|
|
394
397
|
};
|
|
395
398
|
let terminalProvided = false;
|
|
396
399
|
|
|
@@ -448,6 +451,33 @@ function parseAgentsArgs(rawArgs) {
|
|
|
448
451
|
index += 1;
|
|
449
452
|
continue;
|
|
450
453
|
}
|
|
454
|
+
if (arg === '--from-session') {
|
|
455
|
+
const next = rest[index + 1];
|
|
456
|
+
if (!next || next.startsWith('-')) {
|
|
457
|
+
throw new Error('--from-session requires an agent session id');
|
|
458
|
+
}
|
|
459
|
+
options.sourceSessionId = next;
|
|
460
|
+
index += 1;
|
|
461
|
+
continue;
|
|
462
|
+
}
|
|
463
|
+
if (arg === '--message' || arg === '--text') {
|
|
464
|
+
const next = rest[index + 1];
|
|
465
|
+
if (!next || next.startsWith('-')) {
|
|
466
|
+
throw new Error('--message requires text');
|
|
467
|
+
}
|
|
468
|
+
options.message = next;
|
|
469
|
+
index += 1;
|
|
470
|
+
continue;
|
|
471
|
+
}
|
|
472
|
+
if (arg === '--ack') {
|
|
473
|
+
const next = rest[index + 1];
|
|
474
|
+
if (!next || next.startsWith('-')) {
|
|
475
|
+
throw new Error('--ack requires a queued message id');
|
|
476
|
+
}
|
|
477
|
+
options.ackMessageId = next;
|
|
478
|
+
index += 1;
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
451
481
|
if (arg === '--activity' || arg === '--status') {
|
|
452
482
|
const next = rest[index + 1];
|
|
453
483
|
if (!next || next.startsWith('-')) {
|
|
@@ -658,7 +688,7 @@ function parseAgentsArgs(rawArgs) {
|
|
|
658
688
|
throw new Error(`Unknown option: ${arg}`);
|
|
659
689
|
}
|
|
660
690
|
|
|
661
|
-
if (!['start', 'stop', 'status', 'files', 'diff', 'locks', 'finish', 'cleanup-sessions', 'set-status', 'jump'].includes(options.subcommand)) {
|
|
691
|
+
if (!['start', 'stop', 'status', 'files', 'diff', 'locks', 'finish', 'cleanup-sessions', 'set-status', 'jump', 'send', 'inbox'].includes(options.subcommand)) {
|
|
662
692
|
throw new Error(`Unknown agents subcommand: ${options.subcommand}`);
|
|
663
693
|
}
|
|
664
694
|
if (options.pid !== null && options.subcommand !== 'stop') {
|
|
@@ -704,8 +734,8 @@ function parseAgentsArgs(rawArgs) {
|
|
|
704
734
|
throw new Error('agents finish accepts only one of --session or --branch');
|
|
705
735
|
}
|
|
706
736
|
}
|
|
707
|
-
if (options.branch && !['files', 'diff', 'locks', 'finish', 'set-status', 'jump'].includes(options.subcommand)) {
|
|
708
|
-
throw new Error('--branch is only supported with `gx agents files|diff|locks|finish|set-status|jump`');
|
|
737
|
+
if (options.branch && !['files', 'diff', 'locks', 'finish', 'set-status', 'jump', 'send'].includes(options.subcommand)) {
|
|
738
|
+
throw new Error('--branch is only supported with `gx agents files|diff|locks|finish|set-status|jump|send`');
|
|
709
739
|
}
|
|
710
740
|
if ((options.activity || options.worktree) && !['set-status'].includes(options.subcommand)) {
|
|
711
741
|
throw new Error('--activity and --worktree are only supported with `gx agents set-status`');
|
|
@@ -718,10 +748,10 @@ function parseAgentsArgs(rawArgs) {
|
|
|
718
748
|
}
|
|
719
749
|
if (
|
|
720
750
|
options.json &&
|
|
721
|
-
!['status', 'files', 'diff', 'locks', 'cleanup-sessions', 'finish'].includes(options.subcommand) &&
|
|
751
|
+
!['status', 'files', 'diff', 'locks', 'cleanup-sessions', 'finish', 'send', 'inbox'].includes(options.subcommand) &&
|
|
722
752
|
!(options.subcommand === 'start' && options.dryRun)
|
|
723
753
|
) {
|
|
724
|
-
throw new Error('--json is only supported with `gx agents start --dry-run|status|files|diff|locks|finish|cleanup-sessions`');
|
|
754
|
+
throw new Error('--json is only supported with `gx agents start --dry-run|status|files|diff|locks|finish|cleanup-sessions|send|inbox`');
|
|
725
755
|
}
|
|
726
756
|
if (options.subcommand === 'start' && options.json && !options.dryRun) {
|
|
727
757
|
throw new Error('gx agents start --json requires --dry-run');
|
|
@@ -729,6 +759,23 @@ function parseAgentsArgs(rawArgs) {
|
|
|
729
759
|
if (options.staleAgeMinutes !== 24 * 60 && options.subcommand !== 'cleanup-sessions') {
|
|
730
760
|
throw new Error('--older-than-minutes is only supported with `gx agents cleanup-sessions`');
|
|
731
761
|
}
|
|
762
|
+
if ((options.message || options.sourceSessionId) && options.subcommand !== 'send') {
|
|
763
|
+
throw new Error('--message and --from-session are only supported with `gx agents send`');
|
|
764
|
+
}
|
|
765
|
+
if (options.ackMessageId && options.subcommand !== 'inbox') {
|
|
766
|
+
throw new Error('--ack is only supported with `gx agents inbox`');
|
|
767
|
+
}
|
|
768
|
+
if (options.subcommand === 'send') {
|
|
769
|
+
if (!options.message) {
|
|
770
|
+
throw new Error('gx agents send requires --message <text>');
|
|
771
|
+
}
|
|
772
|
+
if (!options.sessionId && !options.branch) {
|
|
773
|
+
throw new Error('gx agents send requires --session or --branch');
|
|
774
|
+
}
|
|
775
|
+
if (options.sessionId && options.branch) {
|
|
776
|
+
throw new Error('gx agents send accepts only one of --session or --branch');
|
|
777
|
+
}
|
|
778
|
+
}
|
|
732
779
|
|
|
733
780
|
return options;
|
|
734
781
|
}
|
|
@@ -12,6 +12,7 @@ const { run } = require('../../core/runtime');
|
|
|
12
12
|
const agentInspect = require('../../agents/inspect');
|
|
13
13
|
const agentStatus = require('../../agents/status');
|
|
14
14
|
const agentActivity = require('../../agents/activity');
|
|
15
|
+
const agentMessage = require('../../agents/message');
|
|
15
16
|
const agentCleanupSessions = require('../../agents/cleanup-sessions');
|
|
16
17
|
const agentsFinishModule = require('../../agents/finish');
|
|
17
18
|
const agentsStart = require('../../agents/start');
|
|
@@ -172,6 +173,22 @@ function agents(rawArgs) {
|
|
|
172
173
|
const repoRoot = resolveRepoRoot(options.target);
|
|
173
174
|
const statePath = agentsStatePathForRepo(repoRoot);
|
|
174
175
|
|
|
176
|
+
if (options.subcommand === 'send') {
|
|
177
|
+
const result = agentMessage.runSendCommand(repoRoot, options);
|
|
178
|
+
if (result.stdout) process.stdout.write(result.stdout);
|
|
179
|
+
if (result.stderr) process.stderr.write(result.stderr);
|
|
180
|
+
process.exitCode = result.status;
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
if (options.subcommand === 'inbox') {
|
|
185
|
+
const result = agentMessage.runInboxCommand(repoRoot, options);
|
|
186
|
+
if (result.stdout) process.stdout.write(result.stdout);
|
|
187
|
+
if (result.stderr) process.stderr.write(result.stderr);
|
|
188
|
+
process.exitCode = result.status;
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
|
|
175
192
|
if (options.subcommand === 'set-status') {
|
|
176
193
|
const result = agentActivity.runSetStatusCommand(repoRoot, options);
|
|
177
194
|
if (result.stdout) process.stdout.write(result.stdout);
|
|
@@ -239,12 +239,53 @@ function isLinkedAgentWorktree(worktreePath) {
|
|
|
239
239
|
}
|
|
240
240
|
}
|
|
241
241
|
|
|
242
|
+
function isReadOnlyBranchStart(args) {
|
|
243
|
+
return args.some((arg) => ['--help', '-h', 'help', '--print-name-only'].includes(arg));
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function recoverStaleManagedWorktrees(repoRoot) {
|
|
247
|
+
const idleMinutes = process.env.GUARDEX_BRANCH_START_CLEANUP_IDLE_MINUTES || '15';
|
|
248
|
+
const result = runPackageAsset(
|
|
249
|
+
'worktreePrune',
|
|
250
|
+
[
|
|
251
|
+
'--prune-stale-lanes',
|
|
252
|
+
'--preserve-open-prs',
|
|
253
|
+
'--delete-branches',
|
|
254
|
+
'--idle-minutes',
|
|
255
|
+
idleMinutes,
|
|
256
|
+
],
|
|
257
|
+
{
|
|
258
|
+
cwd: repoRoot,
|
|
259
|
+
timeout: 30_000,
|
|
260
|
+
env: { GUARDEX_PRUNE_ACTIVE_CWD: process.cwd() },
|
|
261
|
+
},
|
|
262
|
+
);
|
|
263
|
+
|
|
264
|
+
if (result.status !== 0) {
|
|
265
|
+
process.stderr.write(
|
|
266
|
+
`[${TOOL_NAME} branch start] Stale worktree recovery failed safely; continuing without cleanup.\n`,
|
|
267
|
+
);
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const output = `${result.stdout || ''}\n${result.stderr || ''}`;
|
|
272
|
+
const removedWorktrees = Number(output.match(/removed_worktrees=(\d+)/)?.[1] || 0);
|
|
273
|
+
if (removedWorktrees > 0) {
|
|
274
|
+
const suffix = removedWorktrees === 1 ? '' : 's';
|
|
275
|
+
process.stdout.write(
|
|
276
|
+
`[${TOOL_NAME} branch start] Recovered ${removedWorktrees} stale managed worktree${suffix} before branch start.\n`,
|
|
277
|
+
);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
242
281
|
function branch(rawArgs) {
|
|
243
282
|
const activeCwd = process.cwd();
|
|
244
283
|
const [subcommand, ...rest] = rawArgs;
|
|
245
284
|
if (subcommand === 'start') {
|
|
246
285
|
const { target, passthrough } = extractTargetedArgs(rest);
|
|
247
|
-
|
|
286
|
+
const repoRoot = resolveRepoRoot(target);
|
|
287
|
+
if (!isReadOnlyBranchStart(passthrough)) recoverStaleManagedWorktrees(repoRoot);
|
|
288
|
+
invokePackageAsset('branchStart', passthrough, { cwd: repoRoot });
|
|
248
289
|
return;
|
|
249
290
|
}
|
|
250
291
|
if (subcommand === 'finish') {
|
package/src/cli/commands/mcp.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
// `gx mcp` — cross-repo
|
|
3
|
+
// `gx mcp` — cross-repo observability plus authenticated local agent messaging.
|
|
4
4
|
// gx mcp serve run the stdio MCP server (for agent harnesses)
|
|
5
5
|
// gx mcp list-agents one-shot human/debug view of all agent lanes
|
|
6
6
|
// gx mcp who-owns <file> who holds the lock on a file
|
|
@@ -75,7 +75,7 @@ function whoOwns(rest) {
|
|
|
75
75
|
function register() {
|
|
76
76
|
process.stdout.write(
|
|
77
77
|
[
|
|
78
|
-
'Register the
|
|
78
|
+
'Register the gx agent-observability and messaging MCP with your harness:',
|
|
79
79
|
'',
|
|
80
80
|
'Claude Code (user scope — available in every repo):',
|
|
81
81
|
` claude mcp add gx -s user -- ${SHORT_TOOL_NAME} mcp serve`,
|
|
@@ -88,7 +88,8 @@ function register() {
|
|
|
88
88
|
' }',
|
|
89
89
|
'',
|
|
90
90
|
'Codex / other MCP clients: run `gx mcp serve` as a stdio MCP server.',
|
|
91
|
-
'
|
|
91
|
+
'Read-only tools: list_agents, repo_state, who_owns, my_context.',
|
|
92
|
+
'Authenticated messaging: send_agent_message, read_agent_messages, ack_agent_message.',
|
|
92
93
|
'',
|
|
93
94
|
].join('\n') + '\n',
|
|
94
95
|
);
|
|
@@ -7,7 +7,6 @@ const {
|
|
|
7
7
|
TOOL_NAME,
|
|
8
8
|
SHORT_TOOL_NAME,
|
|
9
9
|
LOCK_FILE_RELATIVE,
|
|
10
|
-
AGENT_WORKTREE_RELATIVE_DIRS,
|
|
11
10
|
defaultAgentWorktreeRelativeDir,
|
|
12
11
|
} = require('../../context');
|
|
13
12
|
const {
|
|
@@ -41,7 +40,11 @@ const {
|
|
|
41
40
|
run,
|
|
42
41
|
runPackageAsset,
|
|
43
42
|
} = require('../../core/runtime');
|
|
44
|
-
const {
|
|
43
|
+
const {
|
|
44
|
+
buildParentWorkspaceView,
|
|
45
|
+
ensureParentWorkspaceView,
|
|
46
|
+
printOperations,
|
|
47
|
+
} = require('../../scaffold');
|
|
45
48
|
const {
|
|
46
49
|
appendForceArgs,
|
|
47
50
|
runInstallInternal,
|
|
@@ -51,56 +54,6 @@ const {
|
|
|
51
54
|
printWorktreePruneSummary,
|
|
52
55
|
} = require('./scaffolding');
|
|
53
56
|
|
|
54
|
-
function normalizeWorkspacePath(relativePath) {
|
|
55
|
-
return String(relativePath || '.').replace(/\\/g, '/');
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
function buildParentWorkspaceView(repoRoot) {
|
|
59
|
-
const parentDir = path.dirname(repoRoot);
|
|
60
|
-
const workspaceFileName = `${path.basename(repoRoot)}-branches.code-workspace`;
|
|
61
|
-
const workspacePath = path.join(parentDir, workspaceFileName);
|
|
62
|
-
const repoRelativePath = normalizeWorkspacePath(path.relative(parentDir, repoRoot) || '.');
|
|
63
|
-
|
|
64
|
-
return {
|
|
65
|
-
workspacePath,
|
|
66
|
-
payload: {
|
|
67
|
-
folders: [
|
|
68
|
-
{ path: repoRelativePath },
|
|
69
|
-
...AGENT_WORKTREE_RELATIVE_DIRS.map((relativeDir) => ({
|
|
70
|
-
path: normalizeWorkspacePath(path.join(repoRelativePath === '.' ? '' : repoRelativePath, relativeDir)),
|
|
71
|
-
})),
|
|
72
|
-
],
|
|
73
|
-
settings: {
|
|
74
|
-
'scm.alwaysShowRepositories': true,
|
|
75
|
-
},
|
|
76
|
-
},
|
|
77
|
-
};
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
function ensureParentWorkspaceView(repoRoot, dryRun) {
|
|
81
|
-
const { workspacePath, payload } = buildParentWorkspaceView(repoRoot);
|
|
82
|
-
const operationFile = path.relative(repoRoot, workspacePath) || path.basename(workspacePath);
|
|
83
|
-
const nextContent = `${JSON.stringify(payload, null, 2)}\n`;
|
|
84
|
-
const note = 'parent VS Code workspace view';
|
|
85
|
-
|
|
86
|
-
if (!fs.existsSync(workspacePath)) {
|
|
87
|
-
if (!dryRun) {
|
|
88
|
-
fs.writeFileSync(workspacePath, nextContent, 'utf8');
|
|
89
|
-
}
|
|
90
|
-
return { status: dryRun ? 'would-create' : 'created', file: operationFile, note };
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
const currentContent = fs.readFileSync(workspacePath, 'utf8');
|
|
94
|
-
if (currentContent === nextContent) {
|
|
95
|
-
return { status: 'unchanged', file: operationFile, note };
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
if (!dryRun) {
|
|
99
|
-
fs.writeFileSync(workspacePath, nextContent, 'utf8');
|
|
100
|
-
}
|
|
101
|
-
return { status: dryRun ? 'would-update' : 'updated', file: operationFile, note };
|
|
102
|
-
}
|
|
103
|
-
|
|
104
57
|
function hasGuardexBootstrapFiles(repoRoot) {
|
|
105
58
|
const required = [
|
|
106
59
|
'AGENTS.md',
|
|
@@ -396,7 +349,6 @@ function runSetupInSandbox(options, blocked, repoLabel = '') {
|
|
|
396
349
|
}
|
|
397
350
|
|
|
398
351
|
module.exports = {
|
|
399
|
-
normalizeWorkspacePath,
|
|
400
352
|
buildParentWorkspaceView,
|
|
401
353
|
ensureParentWorkspaceView,
|
|
402
354
|
hasGuardexBootstrapFiles,
|
package/src/mcp/collect.js
CHANGED
|
@@ -104,6 +104,51 @@ function listWorktrees(repoRoot) {
|
|
|
104
104
|
return worktrees;
|
|
105
105
|
}
|
|
106
106
|
|
|
107
|
+
function knownBranchNames(repoRoot, worktrees) {
|
|
108
|
+
const names = new Set(worktrees.map((wt) => wt.branch).filter(Boolean));
|
|
109
|
+
const refs = git(repoRoot, ['for-each-ref', '--format=%(refname)', 'refs/heads', 'refs/remotes']);
|
|
110
|
+
if (refs == null) return names;
|
|
111
|
+
for (const ref of refs.split('\n').filter(Boolean)) {
|
|
112
|
+
if (ref.startsWith('refs/heads/')) {
|
|
113
|
+
names.add(ref.slice('refs/heads/'.length));
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (!ref.startsWith('refs/remotes/')) continue;
|
|
117
|
+
const remoteAndBranch = ref.slice('refs/remotes/'.length);
|
|
118
|
+
const slash = remoteAndBranch.indexOf('/');
|
|
119
|
+
if (slash !== -1) names.add(remoteAndBranch.slice(slash + 1));
|
|
120
|
+
}
|
|
121
|
+
return names;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// `pane` survives in the lock entry after an agent lane exits. If the lane's
|
|
125
|
+
// branch/ref is also gone, the pane's current checkout is the last local proof
|
|
126
|
+
// of ownership. Unknown states fail closed; only a confirmed different branch
|
|
127
|
+
// makes the entry orphaned.
|
|
128
|
+
function paneStillOwnsBranch(mainRoot, pane, branch) {
|
|
129
|
+
if (!/^%\d+$/.test(String(pane || ''))) return null;
|
|
130
|
+
const result = cp.spawnSync(
|
|
131
|
+
'tmux',
|
|
132
|
+
['display-message', '-p', '-t', pane, '#{pane_current_path}'],
|
|
133
|
+
{ encoding: 'utf8', timeout: 3000, maxBuffer: 1024 * 1024 },
|
|
134
|
+
);
|
|
135
|
+
if (result.error) return null;
|
|
136
|
+
if (!result || result.status !== 0) return null;
|
|
137
|
+
const paneCwd = (result.stdout || '').trim();
|
|
138
|
+
if (!paneCwd || !fs.existsSync(paneCwd)) return null;
|
|
139
|
+
const paneRepoRoot = mainRepoRoot(paneCwd);
|
|
140
|
+
if (!paneRepoRoot || path.resolve(paneRepoRoot) !== path.resolve(mainRoot)) return null;
|
|
141
|
+
const paneBranch = git(paneCwd, ['rev-parse', '--abbrev-ref', 'HEAD']);
|
|
142
|
+
if (!paneBranch || paneBranch === 'HEAD') return null;
|
|
143
|
+
return paneBranch === branch;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function isOrphanedLocalLock(mainRoot, entry, knownBranches) {
|
|
147
|
+
const branch = String((entry && entry.branch) || '');
|
|
148
|
+
if (!branch || knownBranches.has(branch)) return false;
|
|
149
|
+
return paneStillOwnsBranch(mainRoot, entry.pane, branch) === false;
|
|
150
|
+
}
|
|
151
|
+
|
|
107
152
|
function readLockMap(repoRoot) {
|
|
108
153
|
const lockPath = path.join(repoRoot, LOCK_FILE_RELATIVE);
|
|
109
154
|
let raw;
|
|
@@ -373,12 +418,16 @@ function whoOwnsMany(files, { cwd = process.cwd(), repoPath } = {}) {
|
|
|
373
418
|
target.owners.push(owner);
|
|
374
419
|
};
|
|
375
420
|
|
|
376
|
-
// Read each worktree lock map once for the whole requested batch.
|
|
377
|
-
|
|
421
|
+
// Read each worktree lock map once for the whole requested batch. A lock is
|
|
422
|
+
// ignored only when its branch/ref disappeared and its recorded pane is
|
|
423
|
+
// confirmed to be on another checkout; ambiguous ownership remains blocking.
|
|
424
|
+
const worktrees = listWorktrees(mainRoot);
|
|
425
|
+
const knownBranches = knownBranchNames(mainRoot, worktrees);
|
|
426
|
+
for (const wt of worktrees) {
|
|
378
427
|
const map = readLockMap(wt.path);
|
|
379
428
|
for (const target of targets) {
|
|
380
429
|
const entry = map[target.rel] || map[target.file];
|
|
381
|
-
if (!entry) continue;
|
|
430
|
+
if (!entry || isOrphanedLocalLock(mainRoot, entry, knownBranches)) continue;
|
|
382
431
|
addOwner(target, {
|
|
383
432
|
branch: entry.branch,
|
|
384
433
|
agent: entry.agent || parseAgentName(entry.branch),
|
package/src/mcp/server.js
CHANGED
|
@@ -5,13 +5,14 @@
|
|
|
5
5
|
// newline-delimited JSON-RPC 2.0; we implement the small surface an agent
|
|
6
6
|
// needs: initialize, tools/list, tools/call, ping.
|
|
7
7
|
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
8
|
+
// Radar tools are read-only. Messaging tools write only to GitGuardex's local
|
|
9
|
+
// authenticated agent inbox and guarded terminal-delivery state.
|
|
10
10
|
|
|
11
11
|
const readline = require('node:readline');
|
|
12
12
|
|
|
13
13
|
const collect = require('./collect');
|
|
14
14
|
const { packageJson } = require('../context');
|
|
15
|
+
const agentMessage = require('../agents/message');
|
|
15
16
|
|
|
16
17
|
const PROTOCOL_VERSION = '2024-11-05';
|
|
17
18
|
|
|
@@ -79,6 +80,43 @@ const TOOLS = [
|
|
|
79
80
|
},
|
|
80
81
|
},
|
|
81
82
|
},
|
|
83
|
+
{
|
|
84
|
+
name: 'send_agent_message',
|
|
85
|
+
description:
|
|
86
|
+
'Send to an authenticated GitGuardex agent session. Delivers live when safe, otherwise queues durably.',
|
|
87
|
+
inputSchema: {
|
|
88
|
+
type: 'object',
|
|
89
|
+
properties: {
|
|
90
|
+
session_id: { type: 'string', description: 'Target session id.' },
|
|
91
|
+
branch: { type: 'string', description: 'Target branch instead of session_id.' },
|
|
92
|
+
message: { type: 'string', description: 'Message body.' },
|
|
93
|
+
from_session: { type: 'string', description: 'Explicit source session id; caller ownership is verified.' },
|
|
94
|
+
},
|
|
95
|
+
required: ['message'],
|
|
96
|
+
},
|
|
97
|
+
},
|
|
98
|
+
{
|
|
99
|
+
name: 'read_agent_messages',
|
|
100
|
+
description: 'Read pending messages for the authenticated calling agent session.',
|
|
101
|
+
inputSchema: {
|
|
102
|
+
type: 'object',
|
|
103
|
+
properties: {
|
|
104
|
+
session_id: { type: 'string', description: 'Explicit caller session id; caller ownership is verified.' },
|
|
105
|
+
},
|
|
106
|
+
},
|
|
107
|
+
},
|
|
108
|
+
{
|
|
109
|
+
name: 'ack_agent_message',
|
|
110
|
+
description: 'Acknowledge and remove one queued message from the authenticated calling agent inbox.',
|
|
111
|
+
inputSchema: {
|
|
112
|
+
type: 'object',
|
|
113
|
+
properties: {
|
|
114
|
+
session_id: { type: 'string', description: 'Explicit caller session id; caller ownership is verified.' },
|
|
115
|
+
message_id: { type: 'string', description: 'Queued message id.' },
|
|
116
|
+
},
|
|
117
|
+
required: ['message_id'],
|
|
118
|
+
},
|
|
119
|
+
},
|
|
82
120
|
];
|
|
83
121
|
|
|
84
122
|
function callTool(name, args = {}) {
|
|
@@ -107,6 +145,20 @@ function callTool(name, args = {}) {
|
|
|
107
145
|
}
|
|
108
146
|
return collect.myContext({ includePr: includePrs });
|
|
109
147
|
}
|
|
148
|
+
case 'send_agent_message':
|
|
149
|
+
return agentMessage.sendOrQueueAgentMessage(process.cwd(), {
|
|
150
|
+
sessionId: args.session_id,
|
|
151
|
+
branch: args.branch,
|
|
152
|
+
sourceSessionId: args.from_session,
|
|
153
|
+
message: args.message,
|
|
154
|
+
});
|
|
155
|
+
case 'read_agent_messages':
|
|
156
|
+
return agentMessage.readAgentInbox(process.cwd(), { sessionId: args.session_id });
|
|
157
|
+
case 'ack_agent_message':
|
|
158
|
+
return agentMessage.acknowledgeAgentMessage(process.cwd(), {
|
|
159
|
+
sessionId: args.session_id,
|
|
160
|
+
messageId: args.message_id,
|
|
161
|
+
});
|
|
110
162
|
default:
|
|
111
163
|
throw new Error(`Unknown tool: ${name}`);
|
|
112
164
|
}
|
package/src/scaffold/index.js
CHANGED
|
@@ -781,6 +781,9 @@ function buildParentWorkspaceView(repoRoot) {
|
|
|
781
781
|
})),
|
|
782
782
|
],
|
|
783
783
|
settings: {
|
|
784
|
+
'git.autoRepositoryDetection': 'subFolders',
|
|
785
|
+
'git.detectWorktrees': true,
|
|
786
|
+
'git.repositoryScanIgnoredFolders': [],
|
|
784
787
|
'scm.alwaysShowRepositories': true,
|
|
785
788
|
},
|
|
786
789
|
},
|
|
@@ -25,6 +25,7 @@ import json
|
|
|
25
25
|
import math
|
|
26
26
|
import os
|
|
27
27
|
import re
|
|
28
|
+
import shutil
|
|
28
29
|
import subprocess
|
|
29
30
|
import sys
|
|
30
31
|
from contextlib import contextmanager
|
|
@@ -337,12 +338,88 @@ def list_worktree_roots(repo_root: Path) -> list[Path]:
|
|
|
337
338
|
return roots
|
|
338
339
|
|
|
339
340
|
|
|
341
|
+
def known_branch_names(repo_root: Path) -> set[str]:
|
|
342
|
+
"""Local and remote branch names plus branches attached to worktrees."""
|
|
343
|
+
names: set[str] = set()
|
|
344
|
+
worktrees = run_git(['worktree', 'list', '--porcelain'], cwd=repo_root)
|
|
345
|
+
for line in worktrees.splitlines():
|
|
346
|
+
if line.startswith('branch refs/heads/'):
|
|
347
|
+
names.add(line[len('branch refs/heads/'):].strip())
|
|
348
|
+
|
|
349
|
+
refs = run_git(
|
|
350
|
+
['for-each-ref', '--format=%(refname)', 'refs/heads', 'refs/remotes'],
|
|
351
|
+
cwd=repo_root,
|
|
352
|
+
)
|
|
353
|
+
for ref in refs.splitlines():
|
|
354
|
+
if ref.startswith('refs/heads/'):
|
|
355
|
+
names.add(ref[len('refs/heads/'):])
|
|
356
|
+
continue
|
|
357
|
+
if not ref.startswith('refs/remotes/'):
|
|
358
|
+
continue
|
|
359
|
+
remote_and_branch = ref[len('refs/remotes/'):]
|
|
360
|
+
_, separator, branch = remote_and_branch.partition('/')
|
|
361
|
+
if separator and branch:
|
|
362
|
+
names.add(branch)
|
|
363
|
+
return names
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def git_common_dir_identity(cwd: Path) -> Path:
|
|
367
|
+
top = Path(run_git(['rev-parse', '--show-toplevel'], cwd=cwd))
|
|
368
|
+
common = Path(run_git(['rev-parse', '--git-common-dir'], cwd=cwd))
|
|
369
|
+
return common.resolve() if common.is_absolute() else (top / common).resolve()
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def pane_still_owns_branch(repo_root: Path, pane: str, branch: str) -> bool | None:
|
|
373
|
+
"""True/False when tmux proves pane ownership; None means fail closed."""
|
|
374
|
+
if not re.fullmatch(r'%\d+', pane) or shutil.which('tmux') is None:
|
|
375
|
+
return None
|
|
376
|
+
try:
|
|
377
|
+
result = subprocess.run(
|
|
378
|
+
['tmux', 'display-message', '-p', '-t', pane, '#{pane_current_path}'],
|
|
379
|
+
check=False,
|
|
380
|
+
stdout=subprocess.PIPE,
|
|
381
|
+
stderr=subprocess.PIPE,
|
|
382
|
+
text=True,
|
|
383
|
+
timeout=3,
|
|
384
|
+
)
|
|
385
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
386
|
+
return None
|
|
387
|
+
if result.returncode != 0:
|
|
388
|
+
return None
|
|
389
|
+
pane_cwd = Path(result.stdout.strip())
|
|
390
|
+
if not result.stdout.strip() or not pane_cwd.exists():
|
|
391
|
+
return None
|
|
392
|
+
try:
|
|
393
|
+
if git_common_dir_identity(pane_cwd) != git_common_dir_identity(repo_root):
|
|
394
|
+
return None
|
|
395
|
+
pane_branch = run_git(['rev-parse', '--abbrev-ref', 'HEAD'], cwd=pane_cwd)
|
|
396
|
+
except LockError:
|
|
397
|
+
return None
|
|
398
|
+
if not pane_branch or pane_branch == 'HEAD':
|
|
399
|
+
return None
|
|
400
|
+
return pane_branch == branch
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def is_orphaned_local_lock(
|
|
404
|
+
repo_root: Path,
|
|
405
|
+
entry: dict[str, Any],
|
|
406
|
+
known_branches: set[str],
|
|
407
|
+
) -> bool:
|
|
408
|
+
"""Ignore only ownership disproved by both Git refs and live pane state."""
|
|
409
|
+
branch = str(entry.get('branch', ''))
|
|
410
|
+
if not branch or branch in known_branches:
|
|
411
|
+
return False
|
|
412
|
+
pane = str(entry.get('pane', ''))
|
|
413
|
+
return pane_still_owns_branch(repo_root, pane, branch) is False
|
|
414
|
+
|
|
415
|
+
|
|
340
416
|
def load_all_locks(repo_root: Path) -> dict[str, list[dict[str, Any]]]:
|
|
341
417
|
"""Union of EVERY worktree's lock map: file path -> list of owner entries
|
|
342
418
|
(one per worktree that claims it). Each worktree owns a separate lock file on
|
|
343
419
|
disk, so a file's full ownership is only visible by reading them all. With a
|
|
344
420
|
single worktree this is exactly that worktree's own locks (unchanged)."""
|
|
345
421
|
merged: dict[str, list[dict[str, Any]]] = {}
|
|
422
|
+
known_branches = known_branch_names(repo_root)
|
|
346
423
|
for root in list_worktree_roots(repo_root):
|
|
347
424
|
try:
|
|
348
425
|
state = load_state(root)
|
|
@@ -352,6 +429,8 @@ def load_all_locks(repo_root: Path) -> dict[str, list[dict[str, Any]]]:
|
|
|
352
429
|
'lock operation blocked'
|
|
353
430
|
) from exc
|
|
354
431
|
for file_path, entry in state['locks'].items():
|
|
432
|
+
if is_orphaned_local_lock(repo_root, entry, known_branches):
|
|
433
|
+
continue
|
|
355
434
|
merged.setdefault(file_path, []).append({**entry, '_worktree': str(root)})
|
|
356
435
|
return merged
|
|
357
436
|
|
|
@@ -628,6 +707,7 @@ def cmd_status(args: argparse.Namespace, repo_root: Path) -> int:
|
|
|
628
707
|
# a sibling worktree's claims would otherwise be invisible here.
|
|
629
708
|
agent_filter = resolve_agent(args)
|
|
630
709
|
roots = list_worktree_roots(repo_root)
|
|
710
|
+
known_branches = known_branch_names(repo_root)
|
|
631
711
|
|
|
632
712
|
rows: list[tuple[str, str, str, str, bool, str]] = []
|
|
633
713
|
for root in roots:
|
|
@@ -639,6 +719,8 @@ def cmd_status(args: argparse.Namespace, repo_root: Path) -> int:
|
|
|
639
719
|
'status is unavailable'
|
|
640
720
|
) from exc
|
|
641
721
|
for file_path, entry in locks.items():
|
|
722
|
+
if is_orphaned_local_lock(repo_root, entry, known_branches):
|
|
723
|
+
continue
|
|
642
724
|
branch = str(entry.get('branch', ''))
|
|
643
725
|
if args.branch and branch != args.branch:
|
|
644
726
|
continue
|