@imdeadpool/guardex 8.4.0 → 8.4.2

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 (97) hide show
  1. package/CONTRIBUTING.md +13 -4
  2. package/README.md +223 -1
  3. package/THIRD-PARTY-NOTICES.md +29 -0
  4. package/bin/multiagent-safety.js +9 -12
  5. package/package.json +4 -2
  6. package/skills/gitguardex/SKILL.md +28 -0
  7. package/skills/pr-lens/SKILL.md +87 -0
  8. package/src/abide.js +534 -0
  9. package/src/agents/activity.js +23 -4
  10. package/src/agents/inspect.js +15 -6
  11. package/src/agents/launch.js +6 -1
  12. package/src/agents/process-lease.js +84 -0
  13. package/src/agents/sessions.js +96 -16
  14. package/src/agents/start.js +18 -9
  15. package/src/agents/status.js +35 -14
  16. package/src/agents/supervise.js +87 -0
  17. package/src/budget/index.js +6 -1
  18. package/src/cli/args.js +71 -77
  19. package/src/cli/commands/agents.js +38 -10
  20. package/src/cli/commands/branch.js +116 -103
  21. package/src/cli/commands/claude.js +604 -50
  22. package/src/cli/commands/codex.js +359 -0
  23. package/src/cli/commands/context.js +52 -0
  24. package/src/cli/commands/mcp.js +5 -1
  25. package/src/cli/commands/pr.js +138 -3
  26. package/src/cli/commands/review.js +3 -1
  27. package/src/cli/commands/setup.js +25 -0
  28. package/src/cli/commands/status.js +128 -60
  29. package/src/cli/commands/storage.js +24 -0
  30. package/src/cli/commands/usage.js +48 -0
  31. package/src/cli/commands/watch.js +157 -47
  32. package/src/cli/commands/worktree-copy-ignored.js +38 -0
  33. package/src/cli/commands/worktree-estimate.js +69 -0
  34. package/src/cli/commands/worktree-hooks.js +62 -0
  35. package/src/cli/commands/worktree-navigation.js +71 -0
  36. package/src/cli/commands/worktree-provision.js +92 -0
  37. package/src/cli/main.js +229 -110
  38. package/src/cli/shared/gate-flags.js +131 -0
  39. package/src/cli/shared/scaffolding.js +31 -3
  40. package/src/cli/shared-locks.js +3 -1
  41. package/src/cockpit/pane-actions.js +43 -7
  42. package/src/context.js +373 -17
  43. package/src/doctor/index.js +29 -35
  44. package/src/finish/events.js +254 -0
  45. package/src/finish/index.js +322 -62
  46. package/src/finish/post-branch-finish-cleanup.js +316 -22
  47. package/src/finish/preflight.js +44 -1
  48. package/src/finish/progress.js +36 -0
  49. package/src/finish/review-gate.js +317 -127
  50. package/src/finish/review-receipt.js +156 -0
  51. package/src/finish/with-claims-lock.py +29 -0
  52. package/src/git/index.js +179 -42
  53. package/src/hooks/index.js +68 -3
  54. package/src/mcp/collect.js +61 -5
  55. package/src/mcp/server.js +4 -0
  56. package/src/output/index.js +167 -1
  57. package/src/pr-lens-publish.js +93 -0
  58. package/src/pr-lens.js +184 -0
  59. package/src/pr-respond.js +860 -0
  60. package/src/pr-review.js +519 -159
  61. package/src/pr.js +73 -14
  62. package/src/provider-binary.js +21 -0
  63. package/src/review-diff-context.js +90 -0
  64. package/src/review-fix.js +23 -17
  65. package/src/scaffold/agent-worktree-prep.js +14 -12
  66. package/src/scaffold/dependency-store.js +234 -0
  67. package/src/scaffold/index.js +13 -1
  68. package/src/scaffold/provision-approvals.js +83 -0
  69. package/src/scaffold/provision-config.js +169 -40
  70. package/src/shared-git-state.js +11 -1
  71. package/src/speckit/index.js +12 -1
  72. package/src/storage/run-artifacts.js +185 -0
  73. package/src/toolchain/index.js +322 -2
  74. package/src/worktree-copy-ignored.js +200 -0
  75. package/src/worktree-hook-worker.js +29 -0
  76. package/src/worktree-hooks.js +333 -0
  77. package/src/worktree-navigation.js +248 -0
  78. package/src/worktree-picker.js +89 -0
  79. package/src/worktree-quota.js +100 -0
  80. package/src/worktree-start.js +100 -0
  81. package/templates/AGENTS.multiagent-safety.md +8 -0
  82. package/templates/AGENTS.multiagent-safety.min.md +3 -1
  83. package/templates/codex/skills/gitguardex/SKILL.md +28 -0
  84. package/templates/codex/skills/opensrc/SKILL.md +24 -0
  85. package/templates/githooks/post-merge +16 -2
  86. package/templates/scripts/agent-autofinish-watch.sh +17 -18
  87. package/templates/scripts/agent-branch-finish.sh +180 -19
  88. package/templates/scripts/agent-branch-merge.sh +7 -32
  89. package/templates/scripts/agent-branch-start.sh +202 -43
  90. package/templates/scripts/agent-claude-stop-finish.sh +4 -27
  91. package/templates/scripts/agent-file-locks.py +257 -29
  92. package/templates/scripts/agent-preflight.sh +3 -0
  93. package/templates/scripts/agent-worktree-prune.sh +975 -63
  94. package/templates/scripts/codex-agent.sh +55 -5
  95. package/templates/scripts/lib/guardex-base-branch.sh +207 -0
  96. package/templates/scripts/openspec/init-change-workspace.sh +10 -18
  97. package/templates/scripts/review-bot-watch.sh +171 -4
@@ -0,0 +1,84 @@
1
+ const fs = require('node:fs');
2
+ const path = require('node:path');
3
+ const crypto = require('node:crypto');
4
+ const { execFileSync } = require('node:child_process');
5
+
6
+ function leaseDirectory(worktree) {
7
+ const common = execFileSync('git', ['-C', worktree, 'rev-parse', '--git-common-dir'], {
8
+ encoding: 'utf8',
9
+ stdio: ['ignore', 'pipe', 'pipe']
10
+ }).trim();
11
+ const key = crypto.createHash('sha256').update(fs.realpathSync(worktree)).digest('hex');
12
+ return path.join(fs.realpathSync(path.resolve(worktree, common)), 'gx-process-leases', key);
13
+ }
14
+
15
+ function processIdentity(pid) {
16
+ if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error('Invalid process identity');
17
+ if (process.platform !== 'linux') throw new Error('Process birth identity unavailable');
18
+ try {
19
+ const stat = fs.readFileSync('/proc/' + pid + '/stat', 'utf8');
20
+ const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
21
+ // An exited main thread can be Z while other threads still own work.
22
+ // Only a single-thread zombie proves that the process has stopped.
23
+ if (fields[0] === 'Z' && fields[17] === '1') return null;
24
+ const birth =
25
+ fs.readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim() + ':' + fields[19];
26
+ let cwd = null;
27
+ try {
28
+ cwd = fs.readlinkSync('/proc/' + pid + '/cwd');
29
+ } catch (error) {
30
+ if (!['ENOENT', 'ESRCH'].includes(error.code)) throw error;
31
+ }
32
+ return { pid, birth, cwd };
33
+ } catch (error) {
34
+ if (['ENOENT', 'ESRCH'].includes(error.code)) return null;
35
+ throw error;
36
+ }
37
+ }
38
+
39
+ function identityState(identity, probe = processIdentity) {
40
+ if (!identity || !Number.isSafeInteger(identity.pid) || !identity.birth) return 'unknown';
41
+ try {
42
+ const current = probe(identity.pid);
43
+ if (!current || current.birth !== identity.birth) return 'dead';
44
+ // A live owner may chdir while its task still owns this worktree.
45
+ return 'live';
46
+ } catch {
47
+ return 'unknown';
48
+ }
49
+ }
50
+
51
+ function probeLeases(worktree) {
52
+ try {
53
+ const directory = leaseDirectory(worktree);
54
+ let directoryStat;
55
+ try {
56
+ directoryStat = fs.lstatSync(directory);
57
+ } catch (error) {
58
+ if (error.code === 'ENOENT') return { active: false, supported: true };
59
+ throw error;
60
+ }
61
+ if (!fs.lstatSync(path.dirname(directory)).isDirectory() || !directoryStat.isDirectory())
62
+ return { active: true, supported: false };
63
+ for (const name of fs.readdirSync(directory)) {
64
+ if (!name.endsWith('.json')) continue;
65
+ const file = path.join(directory, name);
66
+ if (!fs.lstatSync(file).isFile()) return { active: true, supported: false };
67
+ const lease = JSON.parse(fs.readFileSync(file, 'utf8'));
68
+ if (lease.version !== 1 || lease.worktree !== fs.realpathSync(worktree))
69
+ return { active: true, supported: false };
70
+ const states = [identityState(lease.owner), identityState(lease.child)];
71
+ if (states.includes('live')) return { active: true, supported: true };
72
+ if (states.includes('unknown')) return { active: true, supported: false };
73
+ // Dead identities do not authorize deletion. All existing claim, Git,
74
+ // process, dirty-file and merge guards still have to pass.
75
+ }
76
+ return { active: false, supported: true };
77
+ } catch {
78
+ return { active: true, supported: false };
79
+ }
80
+ }
81
+
82
+ module.exports = { leaseDirectory, processIdentity, identityState, probeLeases };
83
+
84
+ if (require.main === module) process.exitCode = probeLeases(process.argv[2]).active ? 0 : 1;
@@ -1,7 +1,27 @@
1
1
  const crypto = require('node:crypto');
2
- const cp = require('node:child_process');
3
2
  const fs = require('node:fs');
4
3
  const path = require('node:path');
4
+ const { cachedSpawn } = require('../context');
5
+
6
+ // Per-session write-lock constants. The lock file is a sibling of the session
7
+ // JSON (`<id>.json.lock`) created with O_EXCL to make acquisition atomic on
8
+ // POSIX file systems. A short exponential backoff makes concurrent callers
9
+ // (the hook subprocess and the main CLI) serialise without busy-spinning.
10
+ //
11
+ // Stale-lock note: we intentionally do NOT attempt to detect or steal stale
12
+ // locks here. Any user-space stale-detection that involves unlink + re-create
13
+ // (whether via O_EXCL or via rename) has an inherent TOCTOU window: two
14
+ // concurrent callers can both observe the same "stale" mtime, then race to
15
+ // replace the lock, and both may confirm ownership before the other's replace
16
+ // lands — letting both enter the critical section simultaneously. Closing
17
+ // this window requires kernel-level CAS semantics (flock/fcntl) which are not
18
+ // natively available in Node.js. Accordingly, if a process crashes while
19
+ // holding the lock, future callers will exhaust their retries and throw an
20
+ // error whose message includes the lock path for manual recovery.
21
+ const SESSION_LOCK_MAX_ATTEMPTS = 8; // total wait ~2.5 s at full contention
22
+ // Shared wait buffer — avoids busy-spinning between retries (same pattern as
23
+ // shared-git-state.js).
24
+ const _sessionLockWaitArray = new Int32Array(new SharedArrayBuffer(4));
5
25
 
6
26
  const SESSION_FIELDS = [
7
27
  'id',
@@ -25,7 +45,7 @@ const SESSION_FIELDS = [
25
45
 
26
46
  function stateRepoRoot(repoRoot) {
27
47
  const root = path.resolve(repoRoot);
28
- const result = cp.spawnSync('git', ['rev-parse', '--git-common-dir'], {
48
+ const result = cachedSpawn('git', ['rev-parse', '--git-common-dir'], {
29
49
  cwd: root,
30
50
  encoding: 'utf8',
31
51
  timeout: 3000,
@@ -115,26 +135,86 @@ function readAgentSession(repoRoot, sessionId) {
115
135
  return pickSessionFields(readJsonFile(filePath));
116
136
  }
117
137
 
138
+ // Acquire a per-session write lock using an O_EXCL lock file.
139
+ // On EEXIST back off exponentially; throw after SESSION_LOCK_MAX_ATTEMPTS.
140
+ // See the constant comment above for why stale-lock stealing is omitted.
141
+ function acquireSessionWriteLock(lockPath) {
142
+ const pidStr = String(process.pid);
143
+ for (let attempt = 0; attempt < SESSION_LOCK_MAX_ATTEMPTS; attempt++) {
144
+ try {
145
+ const fd = fs.openSync(lockPath, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);
146
+ try {
147
+ fs.writeSync(fd, pidStr);
148
+ } catch (writeErr) {
149
+ // Remove the lock file so future callers are not stuck waiting for a
150
+ // lock that will never be released (the holder never entered the
151
+ // critical section and cannot call releaseSessionWriteLock).
152
+ try { fs.unlinkSync(lockPath); } catch (_) {}
153
+ throw writeErr;
154
+ } finally {
155
+ fs.closeSync(fd);
156
+ }
157
+ return; // lock acquired
158
+ } catch (err) {
159
+ if (err.code !== 'EEXIST') throw err;
160
+ // Exponential backoff: 10, 20, 40, 80, 160, 320, 640, 1280 ms.
161
+ Atomics.wait(_sessionLockWaitArray, 0, 0, 10 * (1 << attempt));
162
+ }
163
+ }
164
+ throw new Error(
165
+ `Could not acquire session write lock for ${path.basename(lockPath, '.lock')} ` +
166
+ `after ${SESSION_LOCK_MAX_ATTEMPTS} attempts. ` +
167
+ `If a prior session-update process crashed, delete ${lockPath} to recover.`,
168
+ );
169
+ }
170
+
171
+ function releaseSessionWriteLock(lockPath) {
172
+ try { fs.unlinkSync(lockPath); } catch (_) {}
173
+ }
174
+
118
175
  function updateAgentSession(repoRoot, sessionId, patch) {
119
176
  if (!patch || typeof patch !== 'object' || Array.isArray(patch)) {
120
177
  throw new Error('Agent session patch must be an object.');
121
178
  }
122
179
 
123
- const existing = readAgentSession(repoRoot, sessionId);
124
- if (!existing) {
125
- return null;
180
+ const filePath = sessionFilePath(repoRoot, sessionId);
181
+ const lockPath = `${filePath}.lock`;
182
+ // ENOENT means the sessions directory (and thus the session file) does not
183
+ // exist yet — treat it the same as a missing session rather than throwing.
184
+ try {
185
+ acquireSessionWriteLock(lockPath);
186
+ } catch (err) {
187
+ if (err.code === 'ENOENT') return null;
188
+ throw err;
189
+ }
190
+ try {
191
+ const existing = readAgentSession(repoRoot, sessionId);
192
+ if (!existing) {
193
+ return null;
194
+ }
195
+
196
+ const now = new Date().toISOString();
197
+ const session = pickSessionFields({
198
+ ...existing,
199
+ ...patch,
200
+ // Merge metadata rather than replacing it so callers can add individual
201
+ // keys without wiping keys set by other concurrent operations.
202
+ // null explicitly clears all metadata; undefined leaves it unchanged.
203
+ metadata:
204
+ patch.metadata === null
205
+ ? null
206
+ : patch.metadata !== undefined
207
+ ? { ...(existing.metadata || {}), ...patch.metadata }
208
+ : existing.metadata,
209
+ id: existing.id,
210
+ createdAt: existing.createdAt,
211
+ updatedAt: now,
212
+ });
213
+ writeJsonAtomic(filePath, session);
214
+ return session;
215
+ } finally {
216
+ releaseSessionWriteLock(lockPath);
126
217
  }
127
-
128
- const now = new Date().toISOString();
129
- const session = pickSessionFields({
130
- ...existing,
131
- ...patch,
132
- id: existing.id,
133
- createdAt: existing.createdAt,
134
- updatedAt: now,
135
- });
136
- writeJsonAtomic(sessionFilePath(repoRoot, sessionId), session);
137
- return session;
138
218
  }
139
219
 
140
220
  function listAgentSessions(repoRoot) {
@@ -6,6 +6,7 @@ const {
6
6
  const { runPackageAsset } = require('../core/runtime');
7
7
  const { currentBranchName } = require('../git');
8
8
  const { buildAgentLaunchCommand } = require('./launch');
9
+ const { runTaskStart } = require('../worktree-start');
9
10
  const { resolveAgent } = require('./registry');
10
11
  const {
11
12
  applyAgentSelectionKey,
@@ -369,8 +370,15 @@ function buildSessionPayload(options, metadata, status, extra = {}) {
369
370
  return null;
370
371
  }
371
372
 
373
+ const id = extra.id || agentSessionIdForBranch(metadata.branch);
374
+ const launch = buildAgentLaunchCommand({
375
+ agentId: options.agent || 'codex',
376
+ prompt: options.task,
377
+ worktreePath: path.resolve(metadata.worktreePath),
378
+ supervisorSessionId: id,
379
+ });
372
380
  return {
373
- id: extra.id || agentSessionIdForBranch(metadata.branch),
381
+ id,
374
382
  task: options.task,
375
383
  agent: options.agent || 'codex',
376
384
  branch: metadata.branch,
@@ -378,11 +386,7 @@ function buildSessionPayload(options, metadata, status, extra = {}) {
378
386
  base: options.base || null,
379
387
  claims: Array.isArray(options.claims) ? [...options.claims] : [],
380
388
  metadata: options.metadata && typeof options.metadata === 'object' ? { ...options.metadata } : {},
381
- launchCommand: buildAgentLaunchCommand({
382
- agentId: options.agent || 'codex',
383
- prompt: options.task,
384
- worktreePath: path.resolve(metadata.worktreePath),
385
- }),
389
+ launchCommand: launch,
386
390
  tmux: options.tmux && typeof options.tmux === 'object' ? { ...options.tmux } : null,
387
391
  status,
388
392
  ...extra,
@@ -452,7 +456,9 @@ function buildRecoveryLines(metadata, claims, session) {
452
456
 
453
457
  function startSingleAgentLane(repoRoot, options, deps = {}) {
454
458
  const packageAssetRunner = deps.packageAssetRunner || runPackageAsset;
455
- const startResult = packageAssetRunner('branchStart', buildBranchStartArgs(options), { cwd: repoRoot });
459
+ const startResult = deps.packageAssetRunner
460
+ ? packageAssetRunner('branchStart', buildBranchStartArgs(options), { cwd: repoRoot })
461
+ : runTaskStart(repoRoot, buildBranchStartArgs(options));
456
462
  let stdout = String(startResult.stdout || '');
457
463
  let stderr = String(startResult.stderr || '');
458
464
  if (isSpawnFailure(startResult)) {
@@ -473,7 +479,7 @@ function startSingleAgentLane(repoRoot, options, deps = {}) {
473
479
  const metadata = extractAgentBranchStartMetadata(stdout);
474
480
  const session = writeAgentSession(repoRoot, options, metadata, 'active');
475
481
  stdout = appendSessionId(stdout, session);
476
- if (options.claims.length === 0) {
482
+ if (!options.claims || options.claims.length === 0) {
477
483
  return { status: 0, stdout, stderr, session };
478
484
  }
479
485
 
@@ -522,8 +528,10 @@ function startAgentLane(repoRoot, options, deps = {}) {
522
528
  kittyBin: deps.kittyBin,
523
529
  });
524
530
 
531
+ const terminalOk = terminalResult.status === 'launched' || terminalResult.status === 'skipped';
525
532
  return {
526
533
  ...result,
534
+ status: terminalOk ? result.status : 2,
527
535
  stdout: `${String(result.stdout || '')}${String(terminalResult.stdout || '')}`,
528
536
  stderr: `${String(result.stderr || '')}${String(terminalResult.stderr || '')}`,
529
537
  terminal: terminalResult,
@@ -563,8 +571,9 @@ function startAgentLane(repoRoot, options, deps = {}) {
563
571
  stdout += String(terminalResult.stdout || '');
564
572
  stderr += String(terminalResult.stderr || '');
565
573
 
574
+ const terminalOk = terminalResult.status === 'launched' || terminalResult.status === 'skipped';
566
575
  return {
567
- status: 0,
576
+ status: terminalOk ? 0 : 2,
568
577
  stdout,
569
578
  stderr,
570
579
  terminal: terminalResult,
@@ -53,7 +53,7 @@ function normalizePr(session) {
53
53
  };
54
54
  }
55
55
 
56
- function normalizeSessionForStatus(session, lockDetails, repoRoot, worktrees) {
56
+ function normalizeSessionForStatus(session, lockDetails, repoRoot, worktrees, readChanges = readChangedFiles) {
57
57
  const branch = session.branch || '';
58
58
  const worktreePath = session.worktreePath || '';
59
59
  const claimedFiles = uniqueSorted([
@@ -73,7 +73,7 @@ function normalizeSessionForStatus(session, lockDetails, repoRoot, worktrees) {
73
73
  worktreeExists: worktreePath ? fs.existsSync(worktreePath) : false,
74
74
  lockCount: lockDetails.counts.get(branch) || 0,
75
75
  claimedFiles,
76
- changedFiles: readChangedFiles(repoRoot, branch, worktrees),
76
+ changedFiles: readChanges(repoRoot, branch, worktrees),
77
77
  metadata: session.metadata && typeof session.metadata === 'object' ? session.metadata : {},
78
78
  launchCommand: session.launchCommand || '',
79
79
  tmux: session.tmux && typeof session.tmux === 'object' ? session.tmux : null,
@@ -110,6 +110,17 @@ function metadataSummary(metadata) {
110
110
  .join(' ');
111
111
  }
112
112
 
113
+ function renderSession(session) {
114
+ const meta = metadataSummary(session.metadata);
115
+ const pr = session.prUrl || session.prState ? ` pr=${formatValue(session.prState)} ${formatValue(session.prUrl)}` : '';
116
+ return `- ${formatValue(session.id)} ${formatValue(session.agent)} ${formatValue(session.status)} ` +
117
+ `branch=${formatValue(session.branch)} base=${formatValue(session.base)} ` +
118
+ `worktreeExists=${session.worktreeExists ? 'yes' : 'no'} locks=${session.lockCount} ` +
119
+ `changed=${Array.isArray(session.changedFiles) ? session.changedFiles.length : 0}${pr} ` +
120
+ `task=${formatValue(session.task)} worktree=${formatValue(session.worktreePath)}` +
121
+ `${meta ? ` meta=${meta}` : ''}`;
122
+ }
123
+
113
124
  function renderAgentsStatus(payload, options = {}) {
114
125
  if (options.json) return `${JSON.stringify(payload, null, 2)}\n`;
115
126
 
@@ -118,18 +129,7 @@ function renderAgentsStatus(payload, options = {}) {
118
129
  }
119
130
 
120
131
  const lines = [`[${TOOL_NAME}] Agent sessions: ${payload.sessions.length} (${payload.repoRoot})`];
121
- for (const session of payload.sessions) {
122
- const meta = metadataSummary(session.metadata);
123
- const pr = session.prUrl || session.prState ? ` pr=${formatValue(session.prState)} ${formatValue(session.prUrl)}` : '';
124
- lines.push(
125
- `- ${formatValue(session.id)} ${formatValue(session.agent)} ${formatValue(session.status)} ` +
126
- `branch=${formatValue(session.branch)} base=${formatValue(session.base)} ` +
127
- `worktreeExists=${session.worktreeExists ? 'yes' : 'no'} locks=${session.lockCount} ` +
128
- `changed=${Array.isArray(session.changedFiles) ? session.changedFiles.length : 0}${pr} ` +
129
- `task=${formatValue(session.task)} worktree=${formatValue(session.worktreePath)}` +
130
- `${meta ? ` meta=${meta}` : ''}`,
131
- );
132
- }
132
+ for (const session of payload.sessions) lines.push(renderSession(session));
133
133
  return `${lines.join('\n')}\n`;
134
134
  }
135
135
 
@@ -137,10 +137,31 @@ function runStatusCommand(repoRoot, options = {}) {
137
137
  return renderAgentsStatus(buildAgentsStatusPayload(repoRoot), options);
138
138
  }
139
139
 
140
+ function writeStatusCommand(repoRoot, options = {}, output = process.stdout, deps = {}) {
141
+ if (options.json || !output.isTTY) {
142
+ output.write(runStatusCommand(repoRoot, options));
143
+ return;
144
+ }
145
+ const sessions = listAgentSessions(repoRoot);
146
+ if (sessions.length === 0) {
147
+ output.write(renderAgentsStatus({ repoRoot, sessions: [] }));
148
+ return;
149
+ }
150
+ // Append-only progress works on narrow terminals and needs no cursor rewrites.
151
+ output.write(`[${TOOL_NAME}] Agent sessions: ${sessions.length} (${repoRoot})\n`);
152
+ const lockDetails = readLockDetails(repoRoot);
153
+ const worktrees = (deps.listWorktrees || listWorktrees)(repoRoot);
154
+ for (const session of sessions) {
155
+ const row = normalizeSessionForStatus(session, lockDetails, repoRoot, worktrees, deps.readChangedFiles);
156
+ output.write(`${renderSession(row)}\n`);
157
+ }
158
+ }
159
+
140
160
  module.exports = {
141
161
  buildAgentsStatusPayload,
142
162
  buildAgentsStatus,
143
163
  readLockDetails,
144
164
  renderAgentsStatus,
145
165
  runStatusCommand,
166
+ writeStatusCommand,
146
167
  };
@@ -0,0 +1,87 @@
1
+ const fs = require('node:fs');
2
+ const path = require('node:path');
3
+ const crypto = require('node:crypto');
4
+ const { spawn } = require('node:child_process');
5
+ const { leaseDirectory, processIdentity } = require('./process-lease');
6
+
7
+ function supervise(worktreePath, sessionId, separator, ...command) {
8
+ if (!worktreePath || !sessionId || separator !== '--' || !command[0])
9
+ throw new Error('Missing agent supervision arguments');
10
+ const worktree = fs.realpathSync(worktreePath);
11
+ process.chdir(worktree);
12
+ const directory = leaseDirectory(worktree);
13
+ for (const part of [path.dirname(directory), directory]) {
14
+ try {
15
+ fs.mkdirSync(part, { mode: 0o700 });
16
+ } catch (error) {
17
+ if (error.code !== 'EEXIST') throw error;
18
+ }
19
+ if (!fs.lstatSync(part).isDirectory()) throw new Error('Lease store must not use symlinks');
20
+ }
21
+ const id = crypto.randomUUID();
22
+ const file = path.join(directory, id + '.json');
23
+ const temp = path.join(directory, id + '.tmp');
24
+ const probe = (pid) => {
25
+ try {
26
+ return processIdentity(pid);
27
+ } catch {
28
+ return { pid, birth: null, cwd: worktree };
29
+ }
30
+ };
31
+ // Lease the supervisor before spawning: no unregistered startup interval.
32
+ const lease = { version: 1, sessionId, worktree, owner: probe(process.pid), child: null };
33
+ const heartbeat = () => {
34
+ lease.heartbeatAt = Date.now();
35
+ fs.writeFileSync(temp, JSON.stringify(lease), { flag: 'wx', mode: 0o600 });
36
+ fs.renameSync(temp, file);
37
+ };
38
+ heartbeat();
39
+ // Spawn the registered executable directly, not an intermediate shell.
40
+ // Keep the terminal session/group so /dev/tty and job control still work.
41
+ const child = spawn(command[0], command.slice(1), { cwd: worktree, stdio: 'inherit' });
42
+ lease.child = child.pid ? probe(child.pid) : null;
43
+ heartbeat();
44
+ const interval = Number(process.env.GUARDEX_HEARTBEAT_MS || 5000);
45
+ const timer = setInterval(
46
+ () => {
47
+ try {
48
+ heartbeat();
49
+ } catch {
50
+ /* Existing identity remains a fail-closed lease. */
51
+ }
52
+ },
53
+ Number.isSafeInteger(interval) && interval >= 100 ? interval : 5000
54
+ );
55
+ // SIGINT from the terminal already reaches the foreground group. Forward
56
+ // explicit SIGTERM only to our direct child, never to the user's shell group.
57
+ const forward = (signal) => {
58
+ if (!child.pid) return;
59
+ try {
60
+ child.kill(signal);
61
+ } catch (error) {
62
+ if (error.code !== 'ESRCH') throw error;
63
+ }
64
+ };
65
+ process.on('SIGINT', () => {});
66
+ process.on('SIGTERM', () => forward('SIGTERM'));
67
+ const done = (code, signal) => {
68
+ clearInterval(timer);
69
+ fs.rmSync(file, { force: true });
70
+ fs.rmSync(temp, { force: true });
71
+ process.exitCode = signal
72
+ ? 128 + (require('node:os').constants.signals[signal] || 1)
73
+ : code || 0;
74
+ };
75
+ child.once('error', () => done(127));
76
+ child.once('exit', done);
77
+ }
78
+
79
+ module.exports = { supervise };
80
+ if (require.main === module) {
81
+ try {
82
+ supervise(...process.argv.slice(2));
83
+ } catch (error) {
84
+ console.error(error.message);
85
+ process.exitCode = 1;
86
+ }
87
+ }
@@ -28,8 +28,12 @@ function ghApi(endpoint) {
28
28
  throw err;
29
29
  }
30
30
  if (/403/.test(message)) {
31
+ const rawExcerpt = message.slice(0, 120).replace(/\n/g, ' ');
31
32
  const err = new Error(
32
- `GitHub API 403: ${endpoint}. The current token lacks the billing scope (org owners need admin:org; user accounts need user scope).`,
33
+ `GitHub API 403: ${endpoint}. Likely causes: missing billing scope (org owners ` +
34
+ `need admin:org; user accounts need user scope), SAML SSO enforcement on the org, ` +
35
+ `an expired or revoked token, or an IP allowlist restriction. ` +
36
+ `Response: ${rawExcerpt}`,
33
37
  );
34
38
  err.code = 'GH_API_FORBIDDEN';
35
39
  throw err;
@@ -339,6 +343,7 @@ module.exports = {
339
343
  formatBudgetReportText,
340
344
  renderBudgetHelp,
341
345
  currentMonthKey,
346
+ fetchUsage,
342
347
  DEFAULT_WARN_NET_USD,
343
348
  DEFAULT_CRITICAL_NET_USD,
344
349
  };