@imdeadpool/guardex 8.2.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.
Files changed (35) hide show
  1. package/README.md +68 -10
  2. package/bin/multiagent-safety.js +18 -1
  3. package/package.json +1 -1
  4. package/skills/gitguardex/SKILL.md +26 -2
  5. package/src/agents/message.js +764 -0
  6. package/src/agents/sessions.js +23 -1
  7. package/src/cli/args.js +64 -8
  8. package/src/cli/commands/agents.js +18 -0
  9. package/src/cli/commands/branch.js +94 -2
  10. package/src/cli/commands/finish.js +44 -2
  11. package/src/cli/commands/mcp.js +4 -3
  12. package/src/cli/shared/sandbox.js +5 -53
  13. package/src/cli/shared-locks.js +4 -0
  14. package/src/doctor/index.js +26 -26
  15. package/src/finish/index.js +10 -2
  16. package/src/finish/post-branch-finish-cleanup.js +324 -0
  17. package/src/finish/review-gate.js +47 -6
  18. package/src/git/index.js +9 -4
  19. package/src/mcp/collect.js +52 -3
  20. package/src/mcp/server.js +54 -2
  21. package/src/pr-checks.js +20 -5
  22. package/src/pr.js +122 -1
  23. package/src/scaffold/index.js +13 -0
  24. package/templates/AGENTS.multiagent-safety.md +37 -9
  25. package/templates/AGENTS.multiagent-safety.min.md +10 -4
  26. package/templates/codex/skills/gitguardex/SKILL.md +26 -2
  27. package/templates/githooks/pre-commit +40 -5
  28. package/templates/githooks/pre-push +72 -25
  29. package/templates/scripts/agent-branch-finish.sh +300 -21
  30. package/templates/scripts/agent-branch-start.sh +22 -2
  31. package/templates/scripts/agent-file-locks.py +170 -3
  32. package/templates/scripts/agent-preflight.sh +30 -0
  33. package/templates/scripts/agent-reconcile-openspec-tasks.js +105 -0
  34. package/templates/scripts/agent-worktree-prune.sh +406 -31
  35. package/templates/scripts/guardex-env.sh +291 -0
@@ -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, '.guardex', 'agents', 'sessions');
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
  }
@@ -960,7 +1007,8 @@ function parseCleanupArgs(rawArgs) {
960
1007
  dryRun: false,
961
1008
  forceDirty: false,
962
1009
  keepRemote: false,
963
- keepCleanWorktrees: false,
1010
+ keepCleanWorktrees: true,
1011
+ includeCleanLinkedWorktrees: false,
964
1012
  includePrMerged: false,
965
1013
  idleMinutes: 0,
966
1014
  watch: false,
@@ -1014,6 +1062,14 @@ function parseCleanupArgs(rawArgs) {
1014
1062
  options.keepCleanWorktrees = true;
1015
1063
  continue;
1016
1064
  }
1065
+ if (arg === '--prune-clean-worktrees') {
1066
+ options.keepCleanWorktrees = false;
1067
+ continue;
1068
+ }
1069
+ if (arg === '--include-clean-linked-worktrees') {
1070
+ options.includeCleanLinkedWorktrees = true;
1071
+ continue;
1072
+ }
1017
1073
  if (arg === '--include-pr-merged') {
1018
1074
  options.includePrMerged = true;
1019
1075
  continue;
@@ -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);
@@ -288,6 +305,7 @@ function agents(rawArgs) {
288
305
  String(options.cleanupIntervalSeconds),
289
306
  '--idle-minutes',
290
307
  String(options.idleMinutes),
308
+ '--prune-clean-worktrees',
291
309
  ],
292
310
  cwd: repoRoot,
293
311
  logPath: cleanupLogPath,
@@ -26,6 +26,48 @@ const { locks } = require('../shared-locks');
26
26
 
27
27
  const REVIEW_PROVIDERS = ['codex', 'claude'];
28
28
 
29
+ function printBranchFinishHelp() {
30
+ console.log(`USAGE: ${SHORT_TOOL_NAME} branch finish [options]
31
+
32
+ Finish an agent branch by committing pending work, publishing it, opening or
33
+ updating a PR, enforcing optional gates, merging, and cleaning up.
34
+
35
+ TARGET
36
+ --target <path> Target repository (default: current directory)
37
+ --branch <branch> Agent branch to finish (default: current branch)
38
+ --base <branch> Destination branch
39
+
40
+ PUBLISH AND MERGE
41
+ --via-pr Finish through a pull request
42
+ --direct-only Finish by direct merge only
43
+ --no-push Do not push the branch
44
+ --wait-for-merge Wait until the PR is merged
45
+ --cleanup Remove the finished worktree and branch
46
+ --keep-remote-branch Preserve the remote branch after merge
47
+
48
+ VERIFICATION
49
+ --gate-review Require AI review and green CI before merge
50
+ --gate-autofix Repair blocking review findings and review again
51
+ --gate-autofix-rounds <n> Limit repair rounds to 1-5 (default: 1)
52
+ --gate-baseline Ignore failures already present on the base branch
53
+ --review-provider <name> Review provider: codex|claude
54
+ --review-model <name> Model used by the review provider
55
+ --review-timeout-ms <n> Positive review timeout in milliseconds
56
+ --no-preflight Skip the repository preflight script
57
+ --preflight Run the repository preflight script
58
+
59
+ COMMIT
60
+ --no-auto-commit Refuse to auto-commit pending work
61
+ --commit-message <message> Message for the automatic finish commit
62
+
63
+ -h, --help Show this help without touching the repository`);
64
+ }
65
+
66
+ function isBranchFinishHelpRequest(args) {
67
+ return args.some((arg) => arg === '--help' || arg === '-h')
68
+ || (args.length === 1 && args[0] === 'help');
69
+ }
70
+
29
71
  // Review-gate and auto-commit options are gx-level flags.
30
72
  // agent-branch-finish.sh does not parse them (it exits 1 on the unknown
31
73
  // argument), and its --via-pr path merges the moment the PR opens, so the shell
@@ -197,15 +239,63 @@ function isLinkedAgentWorktree(worktreePath) {
197
239
  }
198
240
  }
199
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
+
200
281
  function branch(rawArgs) {
201
282
  const activeCwd = process.cwd();
202
283
  const [subcommand, ...rest] = rawArgs;
203
284
  if (subcommand === 'start') {
204
285
  const { target, passthrough } = extractTargetedArgs(rest);
205
- invokePackageAsset('branchStart', passthrough, { cwd: resolveRepoRoot(target) });
286
+ const repoRoot = resolveRepoRoot(target);
287
+ if (!isReadOnlyBranchStart(passthrough)) recoverStaleManagedWorktrees(repoRoot);
288
+ invokePackageAsset('branchStart', passthrough, { cwd: repoRoot });
206
289
  return;
207
290
  }
208
291
  if (subcommand === 'finish') {
292
+ // Help is a read-only control path. Handle it before target resolution,
293
+ // worktree discovery, progress initialization, or the automatic commit.
294
+ if (isBranchFinishHelpRequest(rest)) {
295
+ printBranchFinishHelp();
296
+ process.exitCode = 0;
297
+ return;
298
+ }
209
299
  const { target, passthrough } = extractTargetedArgs(rest);
210
300
  const repoRoot = resolveRepoRoot(target);
211
301
  const {
@@ -256,8 +346,9 @@ function branch(rawArgs) {
256
346
  // Fail-closed: runReviewGate throws on a dirty review, red CI, or a PR
257
347
  // GitHub will not merge. Throwing here means the script never runs, so
258
348
  // the merge never happens.
349
+ let gateResult;
259
350
  if (gateReview) {
260
- runReviewGate({
351
+ gateResult = runReviewGate({
261
352
  repoRoot,
262
353
  branch: finishBranch,
263
354
  // Must match how the shell resolves --base when it is omitted, which
@@ -288,6 +379,7 @@ function branch(rawArgs) {
288
379
  GUARDEX_FINISH_ACTIVE_CWD: activeCwd,
289
380
  GUARDEX_FINISH_CHECKLIST: '1',
290
381
  GUARDEX_FINISH_GATE_DONE: gateReview ? '1' : '0',
382
+ GUARDEX_FINISH_REQUIRE_PREFLIGHT: gateResult?.billingChecksWaived?.length > 0 ? '1' : '0',
291
383
  ...progress.eventEnv,
292
384
  },
293
385
  };
@@ -1,6 +1,48 @@
1
1
  // `gx cleanup`, `gx merge`, `gx finish`, `gx sync` — thin wrappers around
2
2
  // the finishCommands module. Pure code-motion from src/cli/main.js.
3
3
  const finishCommands = require('../../finish');
4
+ const { resolveRepoRoot, listAgentWorktrees, branchExists } = require('../../git');
5
+
6
+ /**
7
+ * Translate `gx sync --branch <agent/*>` into the existing worktree-oriented
8
+ * `--target` form. Sync changes the checked-out branch, so a named branch must
9
+ * already have a linked worktree instead of being checked out behind the
10
+ * caller's back.
11
+ *
12
+ * @param {ReadonlyArray<string>} rawArgs CLI argv slice for the sync command.
13
+ * @returns {string[]} Arguments accepted by the core sync parser.
14
+ */
15
+ function resolveSyncBranchTarget(rawArgs) {
16
+ const args = [...rawArgs];
17
+ const branchIndex = args.indexOf('--branch');
18
+ if (branchIndex === -1) return args;
19
+
20
+ const branch = args[branchIndex + 1];
21
+ if (!branch) throw new Error('--branch requires an agent/* branch value');
22
+ if (!branch.startsWith('agent/')) {
23
+ throw new Error(`--branch must reference an agent/* branch (received: ${branch})`);
24
+ }
25
+ if (args.includes('--all-agent-branches')) {
26
+ throw new Error('--branch cannot be combined with --all-agent-branches');
27
+ }
28
+
29
+ const targetIndex = args.indexOf('--target');
30
+ const target = targetIndex === -1 ? process.cwd() : args[targetIndex + 1];
31
+ if (!target) throw new Error('--target requires a path value');
32
+
33
+ const repoRoot = resolveRepoRoot(target);
34
+ const worktree = listAgentWorktrees(repoRoot).find((entry) => entry.branch === branch);
35
+ if (!worktree) {
36
+ if (!branchExists(repoRoot, branch)) throw new Error(`Local branch not found: ${branch}`);
37
+ throw new Error(`Agent branch '${branch}' is not checked out in a linked worktree`);
38
+ }
39
+
40
+ args.splice(branchIndex, 2);
41
+ const normalizedTargetIndex = args.indexOf('--target');
42
+ if (normalizedTargetIndex === -1) args.push('--target', worktree.worktreePath);
43
+ else args[normalizedTargetIndex + 1] = worktree.worktreePath;
44
+ return args;
45
+ }
4
46
 
5
47
  function cleanup(rawArgs) {
6
48
  return finishCommands.cleanup(rawArgs);
@@ -15,12 +57,12 @@ function finish(rawArgs, defaults = {}) {
15
57
  }
16
58
 
17
59
  function sync(rawArgs) {
18
- return finishCommands.sync(rawArgs);
60
+ return finishCommands.sync(resolveSyncBranchTarget(rawArgs));
19
61
  }
20
62
 
21
63
  module.exports = {
22
64
  cleanup,
23
65
  merge,
24
66
  finish,
25
- sync,
67
+ sync
26
68
  };
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- // `gx mcp` — cross-repo, read-only multi-agent observability over MCP.
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 read-only gx agent-observability MCP with your harness:',
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
- 'Tools exposed (all read-only): list_agents, repo_state, who_owns, my_context.',
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 { printOperations } = require('../../scaffold');
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,
@@ -35,6 +35,7 @@ function parseLockOperation(args) {
35
35
  branch: '',
36
36
  agent: process.env.GUARDEX_AGENT_ID || '',
37
37
  allowDelete: false,
38
+ allowUnclaimed: false,
38
39
  staged: false,
39
40
  files: []
40
41
  };
@@ -56,6 +57,8 @@ function parseLockOperation(args) {
56
57
  parsed.agent = arg.slice('--agent='.length);
57
58
  } else if (arg === '--allow-delete') {
58
59
  parsed.allowDelete = true;
60
+ } else if (arg === '--allow-unclaimed') {
61
+ parsed.allowUnclaimed = true;
59
62
  } else if (arg === '--staged') {
60
63
  parsed.staged = true;
61
64
  } else if (arg.startsWith('-')) {
@@ -212,6 +215,7 @@ function sharedValidate(repoRoot, args, parsed) {
212
215
  const files = parsed.staged ? stagedFiles(repoRoot) : parsed.files;
213
216
  try {
214
217
  for (const file of files) {
218
+ if (parsed.allowUnclaimed && !sharedGitState.getLock(repoRoot, file)) continue;
215
219
  sharedGitState.validateLock(repoRoot, { file, branch: parsed.branch, agent: parsed.agent });
216
220
  }
217
221
  } catch (error) {
@@ -50,7 +50,6 @@ const {
50
50
  } = require('../sandbox');
51
51
  const { ensureOmxScaffold, configureHooks } = require('../scaffold');
52
52
  const { detectRecoverableAutoFinishConflict, printAutoFinishSummary, isTerseMode } = require('../output');
53
- const { autoCommitWorktreeForFinish } = require('../finish');
54
53
  const { runReviewGate } = require('../finish/review-gate');
55
54
 
56
55
  /**
@@ -980,49 +979,45 @@ function autoFinishReadyAgentBranches(repoRoot, options = {}) {
980
979
  continue;
981
980
  }
982
981
 
983
- if (branch === baseBranch) {
982
+ const branchBase = readGitConfig(repoRoot, `branch.${branch}.guardexBase`) || baseBranch;
983
+ if (!branchBase || branchBase === 'HEAD' || branchBase.startsWith('agent/')) {
984
984
  summary.skipped += 1;
985
- summary.details.push(`[skip] ${branch}: source branch equals base branch.`);
985
+ summary.details.push(`[skip] ${branch}: recorded base is missing or invalid.`);
986
986
  continue;
987
987
  }
988
988
 
989
- let counts;
990
- try {
991
- counts = aheadBehind(repoRoot, branch, baseBranch);
992
- } catch (error) {
993
- summary.failed += 1;
994
- summary.details.push(`[fail] ${branch}: unable to compute ahead/behind (${error.message}).`);
989
+ if (branch === branchBase) {
990
+ summary.skipped += 1;
991
+ summary.details.push(`[skip] ${branch}: source branch equals base branch.`);
995
992
  continue;
996
993
  }
997
994
 
998
995
  const branchWorktree = branchWorktrees.get(branch) || '';
999
996
  if (branchWorktree && hasSignificantWorkingTreeChanges(branchWorktree)) {
1000
- try {
1001
- const commitResult = autoCommitWorktreeForFinish(repoRoot, branchWorktree, branch, {});
1002
- if (commitResult.committed) {
1003
- counts = aheadBehind(repoRoot, branch, baseBranch);
1004
- }
1005
- } catch (error) {
1006
- summary.failed += 1;
1007
- summary.details.push(`[fail] ${branch}: auto-commit failed (${error.message}).`);
1008
- continue;
1009
- }
997
+ summary.skipped += 1;
998
+ summary.details.push(
999
+ `[skip] ${branch}: dirty worktree; refusing unattended auto-commit or sync (${branchWorktree}).`,
1000
+ );
1001
+ continue;
1010
1002
  }
1011
1003
 
1012
- if (counts.ahead <= 0) {
1013
- summary.skipped += 1;
1014
- summary.details.push(`[skip] ${branch}: already merged into ${baseBranch}.`);
1004
+ let counts;
1005
+ try {
1006
+ counts = aheadBehind(repoRoot, branch, branchBase);
1007
+ } catch (error) {
1008
+ summary.failed += 1;
1009
+ summary.details.push(`[fail] ${branch}: unable to compute ahead/behind (${error.message}).`);
1015
1010
  continue;
1016
1011
  }
1017
1012
 
1018
- if (branchWorktree && hasSignificantWorkingTreeChanges(branchWorktree)) {
1013
+ if (counts.ahead <= 0) {
1019
1014
  summary.skipped += 1;
1020
- summary.details.push(`[skip] ${branch}: dirty worktree after auto-commit (${branchWorktree}).`);
1015
+ summary.details.push(`[skip] ${branch}: already merged into ${branchBase}.`);
1021
1016
  continue;
1022
1017
  }
1023
1018
 
1024
1019
  const gateOutcome = runAutoShipGateForBranch(
1025
- { autoShip, fallbackMode, repoRoot, branch, baseBranch },
1020
+ { autoShip, fallbackMode, repoRoot, branch, baseBranch: branchBase },
1026
1021
  { runReviewGate: options.runReviewGate },
1027
1022
  );
1028
1023
  if (gateOutcome.skip) {
@@ -1036,7 +1031,7 @@ function autoFinishReadyAgentBranches(repoRoot, options = {}) {
1036
1031
  '--branch',
1037
1032
  branch,
1038
1033
  '--base',
1039
- baseBranch,
1034
+ branchBase,
1040
1035
  ];
1041
1036
  if (fallbackMode === 'local') {
1042
1037
  finishArgs.push('--direct-only', '--no-push');
@@ -1103,6 +1098,11 @@ function pruneStaleAgentWorktrees(repoRoot, options = {}) {
1103
1098
 
1104
1099
  const args = [
1105
1100
  '--idle-minutes', String(idleMinutes),
1101
+ // Doctor may retire clean inactive lanes after the grace period, but the
1102
+ // prune asset must classify them from PR metadata first. Open PRs, dirty
1103
+ // worktrees, and live processes remain fail-closed recovery points.
1104
+ '--prune-stale-lanes',
1105
+ '--preserve-open-prs',
1106
1106
  '--delete-branches',
1107
1107
  '--delete-remote-branches',
1108
1108
  '--include-pr-merged',