@imdeadpool/guardex 8.4.12 → 8.4.13

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@imdeadpool/guardex",
3
- "version": "8.4.12",
3
+ "version": "8.4.13",
4
4
  "description": "Guardian T-Rex for your multi-agent repo. Isolated worktrees, file locks, and PR-only merges stop parallel Codex & Claude agents from overwriting each other's work. Auto-wires Oh My Codex, Oh My Claude, OpenSpec, and Caveman.",
5
5
  "license": "MIT",
6
6
  "preferGlobal": true,
@@ -97,5 +97,5 @@
97
97
  "jsonc-parser": "3.3.1",
98
98
  "semver": "7.7.4"
99
99
  },
100
- "gitHead": "b86f38ac32992e3bbee2a9d1753590b241f9c813"
100
+ "gitHead": "a7f1bda2a3c02d75fb2b75fcafed7812c425d4b7"
101
101
  }
@@ -178,6 +178,21 @@ function isReadOnlyBranchStart(args) {
178
178
  return args.some((arg) => ['--help', '-h', 'help', '--print-name-only', '--preview'].includes(arg));
179
179
  }
180
180
 
181
+ // Identify options, not values that happen to look like one. Keep the shell
182
+ // asset as the authority for all branch-start arguments other than --json.
183
+ function branchStartOptionIndices(args, name) {
184
+ const takesValue = new Set([
185
+ '--task', '--task-id', '--agent', '--base', '--tier', '--provision-mode',
186
+ '--worktree-root', '--sparse-exclude', '--transfer-exclude'
187
+ ]);
188
+ const indices = [];
189
+ for (let index = 0; index < args.length; index++) {
190
+ if (args[index] === name) indices.push(index);
191
+ if (takesValue.has(args[index])) index++;
192
+ }
193
+ return indices;
194
+ }
195
+
181
196
  function recoverStaleManagedWorktrees(repoRoot) {
182
197
  const idleMinutes = process.env.GUARDEX_BRANCH_START_CLEANUP_IDLE_MINUTES || '15';
183
198
  const result = runPackageAsset(
@@ -216,10 +231,32 @@ function recoverStaleManagedWorktrees(repoRoot) {
216
231
  function branch(rawArgs) {
217
232
  const activeCwd = process.cwd();
218
233
  const [subcommand, ...rest] = rawArgs;
234
+ if (subcommand === 'tasks') {
235
+ if (rest[0] === '--help' || rest[0] === '-h') {
236
+ process.stdout.write(
237
+ 'Usage: gx branch tasks --json\n' +
238
+ 'List ready linked worktrees in this repository and their occupancy (versioned JSON).\n' +
239
+ 'Related: gx branch start --task-id <id> --json; gx branch run-task <id> <branch> <worktree> -- <command>\n'
240
+ );
241
+ return;
242
+ }
243
+ if (rest.length !== 1 || rest[0] !== '--json') throw new Error('Usage: gx branch tasks --json');
244
+ require('../../worktree-tasks').listTasks(resolveRepoRoot(activeCwd));
245
+ return;
246
+ }
247
+ if (subcommand === 'run-task') {
248
+ require('../../worktree-tasks').runTask(resolveRepoRoot(activeCwd), rest);
249
+ return;
250
+ }
219
251
  if (subcommand === 'start') {
220
252
  const { target, passthrough } = extractTargetedArgs(rest);
221
253
  const repoRoot = resolveRepoRoot(target);
222
254
  const readOnly = isReadOnlyBranchStart(passthrough);
255
+ const jsonIndices = branchStartOptionIndices(passthrough, '--json');
256
+ const json = jsonIndices.length > 0;
257
+ if (json && (readOnly || jsonIndices.length !== 1 ||
258
+ branchStartOptionIndices(passthrough, '--task-id').length !== 1))
259
+ throw new Error('--json requires a normal branch start with --task-id');
223
260
  const quota = readOnly ? {} : require('../../worktree-quota').readWorktreeQuota(repoRoot);
224
261
  if (!readOnly) {
225
262
  const modeIndex = passthrough.indexOf('--provision-mode');
@@ -235,6 +272,11 @@ function branch(rawArgs) {
235
272
  passthrough[passthrough.indexOf('--task-id') + 1]
236
273
  );
237
274
  }
275
+ if (json) {
276
+ require('../../worktree-start').invokeTaskStart(repoRoot,
277
+ passthrough.filter((_, index) => index !== jsonIndices[0]), true);
278
+ return;
279
+ }
238
280
  if (!isReadOnlyBranchStart(passthrough)) {
239
281
  require('../../finish/post-branch-finish-cleanup').retryPendingFinishedCleanup(repoRoot, {
240
282
  schedule: true
@@ -246,6 +288,9 @@ function branch(rawArgs) {
246
288
  return;
247
289
  }
248
290
  invokePackageAsset('branchStart', passthrough, { cwd: repoRoot });
291
+ if (passthrough[0] === '--help' || passthrough[0] === '-h') {
292
+ process.stdout.write(' --json With --task-id, emit a versioned task result on stdout\n');
293
+ }
249
294
  return;
250
295
  }
251
296
  if (subcommand === 'finish') {
@@ -65,19 +65,27 @@ function estimateCheckout(repoRoot, ref, exclusions) {
65
65
  };
66
66
  }
67
67
 
68
+ function commonGitDirectory(repoRoot) {
69
+ const common = run('git', ['-C', repoRoot, 'rev-parse', '--git-common-dir']);
70
+ if (common.status !== 0) throw new Error('Cannot resolve task lock directory');
71
+ return fs.realpathSync(path.resolve(repoRoot, common.stdout.trim()));
72
+ }
73
+
74
+ function taskLock(repoRoot, id, scope = 'task') {
75
+ const key = crypto.createHash('sha256').update(id).digest('hex');
76
+ return path.join(commonGitDirectory(repoRoot), `gitguardex-${scope}-${key}.lock`);
77
+ }
78
+
68
79
  function runTaskStart(repoRoot, args) {
69
80
  const taskFlags = args.filter((arg) => arg === '--task-id').length;
70
81
  if (taskFlags > 1)
71
82
  throw new Error('--task-id must appear once');
72
83
  const id = taskFlags ? validateTaskId(args[args.indexOf('--task-id') + 1]) : '';
73
- const common = run('git', ['-C', repoRoot, 'rev-parse', '--git-common-dir']);
74
- if (common.status !== 0) throw new Error('Cannot resolve task lock directory');
75
- const commonDir = fs.realpathSync(path.resolve(repoRoot, common.stdout.trim()));
76
84
  const locks = [];
77
85
  if (Object.keys(require('./worktree-quota').readWorktreeQuota(repoRoot)).length) {
78
- locks.push(path.join(commonDir, 'gitguardex-worktree-quota.lock'));
86
+ locks.push(path.join(commonGitDirectory(repoRoot), 'gitguardex-worktree-quota.lock'));
79
87
  }
80
- if (id) locks.push(path.join(commonDir, `gitguardex-task-${crypto.createHash('sha256').update(id).digest('hex')}.lock`));
88
+ if (id) locks.push(taskLock(repoRoot, id));
81
89
  let command = ['bash', packageAssetPath('branchStart'), ...args];
82
90
  for (const lock of locks.reverse()) {
83
91
  command = ['python3', path.join(__dirname, 'finish/with-claims-lock.py'), lock, ...command];
@@ -89,12 +97,17 @@ function runTaskStart(repoRoot, args) {
89
97
  );
90
98
  }
91
99
 
92
- function invokeTaskStart(repoRoot, args) {
100
+ function invokeTaskStart(repoRoot, args, json = false) {
93
101
  const result = runTaskStart(repoRoot, args);
94
- if (result.stdout) process.stdout.write(result.stdout);
102
+ if (result.stdout) (json ? process.stderr : process.stdout).write(result.stdout);
95
103
  if (result.stderr) process.stderr.write(result.stderr);
96
104
  if (result.status !== 0)
97
105
  throw new Error(`Task start failed or is busy (status ${result.status})`);
106
+ if (json) {
107
+ const { findTask } = require('./worktree-tasks');
108
+ const task = findTask(repoRoot, args[args.indexOf('--task-id') + 1]);
109
+ process.stdout.write(JSON.stringify({ version: 1, ...task }) + '\n');
110
+ }
98
111
  }
99
112
 
100
- module.exports = { estimateCheckout, runTaskStart, invokeTaskStart, validateTaskId };
113
+ module.exports = { commonGitDirectory, estimateCheckout, runTaskStart, invokeTaskStart, taskLock, validateTaskId };
@@ -0,0 +1,144 @@
1
+ const fs = require('node:fs');
2
+ const path = require('node:path');
3
+ const { randomUUID } = require('node:crypto');
4
+ const { run } = require('./core/runtime');
5
+ const { listWorktrees } = require('./worktree-navigation');
6
+ const { commonGitDirectory, taskLock, validateTaskId } = require('./worktree-start');
7
+
8
+ function taskWorktrees(repoRoot, onlyId) {
9
+ const config = run('git', ['config', '--local', '--null', '--list'], { cwd: repoRoot });
10
+ if (config.status !== 0) throw new Error('Cannot read task identities');
11
+ const settings = new Map();
12
+ const branchesById = new Map();
13
+ for (const record of config.stdout.split('\0')) {
14
+ const end = record.indexOf('\n');
15
+ if (end < 0) continue;
16
+ const key = record.slice(0, end);
17
+ const value = record.slice(end + 1);
18
+ settings.set(key, value);
19
+ }
20
+ for (const [key, value] of settings) {
21
+ const match = key.match(/^branch\.(.+)\.guardextaskid$/);
22
+ if (!match || (onlyId && value !== onlyId)) continue;
23
+ try {
24
+ validateTaskId(value);
25
+ } catch {
26
+ continue;
27
+ }
28
+ const branches = branchesById.get(value) || [];
29
+ branches.push(match[1]);
30
+ branchesById.set(value, branches);
31
+ }
32
+ if (!branchesById.size) return [];
33
+ const worktrees = new Map();
34
+ for (const entry of listWorktrees(repoRoot)) {
35
+ worktrees.set(entry.branch, worktrees.has(entry.branch) ? null : entry);
36
+ }
37
+ const tasks = [];
38
+ for (const [taskId, branches] of branchesById) {
39
+ if (branches.length !== 1) continue;
40
+ const [branch] = branches;
41
+ const agent = branch.match(/^agent\/([^/]+)\//)?.[1];
42
+ const entry = worktrees.get(branch);
43
+ if (
44
+ !agent ||
45
+ !entry ||
46
+ entry.locked ||
47
+ settings.get(`branch.${branch}.guardexstartready`) !== 'true'
48
+ )
49
+ continue;
50
+ const remote = settings.get(`branch.${branch}.remote`);
51
+ if (
52
+ remote &&
53
+ run('git', ['show-ref', '--verify', '--quiet', `refs/remotes/${remote}/${branch}`], {
54
+ cwd: repoRoot
55
+ }).status !== 0
56
+ )
57
+ continue;
58
+ let worktree;
59
+ try {
60
+ worktree = fs.realpathSync(entry.path);
61
+ if (!fs.lstatSync(path.join(worktree, '.git')).isFile()) continue;
62
+ } catch {
63
+ continue;
64
+ }
65
+ tasks.push({ taskId, agent, branch, worktree });
66
+ }
67
+ return tasks.sort((left, right) => left.taskId.localeCompare(right.taskId));
68
+ }
69
+
70
+ function worktreeBusy(worktree) {
71
+ const { active, supported } =
72
+ require('./finish/post-branch-finish-cleanup').probeWorktreeOwnership(worktree);
73
+ return active || !supported;
74
+ }
75
+
76
+ function listTasks(repoRoot) {
77
+ const tasks = taskWorktrees(repoRoot).map((task) => ({
78
+ ...task,
79
+ busy: worktreeBusy(task.worktree)
80
+ }));
81
+ process.stdout.write(JSON.stringify({ version: 1, tasks }) + '\n');
82
+ }
83
+
84
+ function findTask(repoRoot, id) {
85
+ const task = taskWorktrees(repoRoot, validateTaskId(id))[0];
86
+ if (!task) throw new Error('Task has no unique, ready linked worktree');
87
+ return task;
88
+ }
89
+
90
+ function runTask(repoRoot, [id, branch, worktree, separator, ...command]) {
91
+ if (!branch || !worktree || separator !== '--' || !command[0])
92
+ throw new Error('Usage: gx branch run-task <id> <branch> <worktree> -- <command> [args...]');
93
+ if (
94
+ ['GIT_DIR', 'GIT_COMMON_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE'].some(
95
+ (key) => key in process.env
96
+ )
97
+ )
98
+ throw new Error('Unset Git checkout overrides before running a task');
99
+ const result = run(
100
+ 'python3',
101
+ [
102
+ path.join(__dirname, 'finish/with-claims-lock.py'),
103
+ '--try-lock',
104
+ taskLock(repoRoot, validateTaskId(id), 'task-run'),
105
+ process.execPath,
106
+ __filename,
107
+ id,
108
+ branch,
109
+ worktree,
110
+ ...command
111
+ ],
112
+ { cwd: repoRoot, stdio: 'inherit' }
113
+ );
114
+ if (result.error) throw result.error;
115
+ if (result.status === 75)
116
+ console.error('GitGuardex: another launch holds the task lock (or the child exited 75).');
117
+ process.exitCode = result.status ?? (result.signal === 'SIGINT' ? 130 : 1);
118
+ }
119
+
120
+ if (require.main === module) {
121
+ try {
122
+ const [id, branch, worktree, ...command] = process.argv.slice(2);
123
+ // Recheck under the lock: a listing is not authority to write, and a task
124
+ // disappearing between selection and launch must not create another lane.
125
+ const task = findTask(process.cwd(), id);
126
+ if (task.branch !== branch || task.worktree !== worktree)
127
+ throw new Error('Selected task worktree changed; select it again');
128
+ const head = run('git', ['symbolic-ref', 'HEAD'], { cwd: worktree });
129
+ if (
130
+ head.status !== 0 ||
131
+ head.stdout.trim() !== `refs/heads/${branch}` ||
132
+ commonGitDirectory(worktree) !== commonGitDirectory(process.cwd())
133
+ )
134
+ throw new Error('Selected path is not the expected linked worktree');
135
+ if (worktreeBusy(worktree))
136
+ throw new Error('Task worktree is in use or its occupancy cannot be verified');
137
+ require('./agents/supervise').supervise(worktree, randomUUID(), '--', ...command);
138
+ } catch (error) {
139
+ console.error(`GitGuardex: ${error.message}`);
140
+ process.exitCode = 1;
141
+ }
142
+ }
143
+
144
+ module.exports = { findTask, listTasks, runTask };