@imdeadpool/guardex 7.0.43 → 7.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +35 -0
  2. package/package.json +4 -1
  3. package/scripts/prepublish-bump-version.js +191 -0
  4. package/skills/gx-act/SKILL.md +82 -0
  5. package/src/agents/activity.js +279 -0
  6. package/src/agents/inspect.js +17 -4
  7. package/src/agents/launch.js +10 -1
  8. package/src/agents/status.js +9 -6
  9. package/src/budget/index.js +2 -1
  10. package/src/cli/args.js +118 -5
  11. package/src/cli/commands/agents.js +381 -0
  12. package/src/cli/commands/bootstrap.js +92 -0
  13. package/src/cli/commands/branch.js +127 -0
  14. package/src/cli/commands/claude.js +674 -0
  15. package/src/cli/commands/doctor.js +268 -0
  16. package/src/cli/commands/finish.js +26 -0
  17. package/src/cli/commands/mcp.js +122 -0
  18. package/src/cli/commands/misc.js +304 -0
  19. package/src/cli/commands/pr.js +439 -0
  20. package/src/cli/commands/prompt.js +92 -0
  21. package/src/cli/commands/release.js +305 -0
  22. package/src/cli/commands/report.js +244 -0
  23. package/src/cli/commands/review.js +32 -0
  24. package/src/cli/commands/setup.js +242 -0
  25. package/src/cli/commands/status.js +338 -0
  26. package/src/cli/commands/watch.js +234 -0
  27. package/src/cli/main.js +68 -3726
  28. package/src/cli/shared/repo-env.js +161 -0
  29. package/src/cli/shared/sandbox.js +417 -0
  30. package/src/cli/shared/scaffolding.js +535 -0
  31. package/src/cli/shared/toolchain-shims.js +420 -0
  32. package/src/context.js +229 -11
  33. package/src/core/runtime.js +6 -1
  34. package/src/doctor/index.js +42 -13
  35. package/src/finish/index.js +147 -5
  36. package/src/finish/preflight.js +177 -0
  37. package/src/finish/review-gate.js +182 -0
  38. package/src/git/index.js +446 -4
  39. package/src/hooks/index.js +0 -64
  40. package/src/mcp/collect.js +394 -0
  41. package/src/mcp/server.js +163 -0
  42. package/src/output/index.js +67 -1
  43. package/src/pr-review.js +23 -0
  44. package/src/pr.js +381 -0
  45. package/src/sandbox/index.js +13 -2
  46. package/src/scaffold/agent-worktree-prep.js +220 -0
  47. package/src/scaffold/index.js +108 -10
  48. package/src/scaffold/provision-config.js +314 -0
  49. package/src/speckit/index.js +226 -0
  50. package/src/terminal/index.js +1 -76
  51. package/src/terminal/kitty.js +20 -0
  52. package/src/terminal/tmux.js +9 -1
  53. package/src/toolchain/index.js +20 -0
  54. package/templates/AGENTS.monorepo-apps.md +26 -0
  55. package/templates/AGENTS.multiagent-safety.md +68 -344
  56. package/templates/AGENTS.multiagent-safety.min.md +11 -0
  57. package/templates/codex/skills/gx-act/SKILL.md +82 -0
  58. package/templates/githooks/pre-commit +22 -19
  59. package/templates/scripts/agent-branch-finish.sh +17 -33
  60. package/templates/scripts/agent-branch-merge.sh +4 -1
  61. package/templates/scripts/agent-branch-start.sh +115 -6
  62. package/templates/scripts/agent-file-locks.py +245 -50
  63. package/templates/scripts/agent-preflight.sh +31 -5
  64. package/templates/scripts/agent-worktree-prune.sh +1 -1
  65. package/templates/scripts/codex-agent.sh +0 -91
  66. package/src/agents/detect.js +0 -160
  67. package/src/cockpit/keybindings.js +0 -224
  68. package/src/cockpit/layout.js +0 -224
package/README.md CHANGED
@@ -308,6 +308,41 @@ Being honest about where this still has issues:
308
308
  <details open>
309
309
  <summary><strong>v7.x</strong></summary>
310
310
 
311
+ ### v7.1.1
312
+ - Bumped `@imdeadpool/guardex` from `7.1.0` to `7.1.1` so the current
313
+ `main` payload can publish under a fresh npm version after `7.1.0` reached
314
+ the registry.
315
+ - Direct maintainer `npm publish` now checks npm during `prepublishOnly` and
316
+ bumps package release metadata to the next unpublished patch version when the
317
+ committed version is already published. GitHub Actions release publishes keep
318
+ the committed metadata so packed and signed assets stay aligned.
319
+
320
+ ### v7.0.43
321
+ - Budget-friendly CI defaults for gitguardex-managed projects: live
322
+ workflows drop `push: main`, gate per-PR jobs on `pull_request.draft
323
+ == false`, add `concurrency: cancel-in-progress`, and split per-runtime
324
+ matrix coverage into a weekly `ci-full.yml`. CodeQL and Scorecard run
325
+ on the weekly schedule + `workflow_dispatch` only. Templates under
326
+ `templates/github/workflows/` carry the same posture so downstream
327
+ projects inherit it via `gx setup`.
328
+ - New `gx ci-init` subcommand scaffolds `ci.yml`, `ci-full.yml`, `cr.yml`,
329
+ and a `README.md` budget-posture guide into a target repo's
330
+ `.github/workflows/` directory. Supports `--target`, `--dry-run`,
331
+ `--force`, `--no-stage`, and `--json`.
332
+ - New `gx budget` subcommand wraps the new GitHub
333
+ `/settings/billing/usage` endpoint (the legacy
334
+ `/settings/billing/actions` endpoint was retired in early 2026) and
335
+ reports monthly Actions minute spend with warn/critical USD thresholds
336
+ per `--org` or `--user`.
337
+ - Per-PR label opt-in for `agent/*` lanes: `needs-review` runs AI code
338
+ review on an otherwise-skipped agent PR; `needs-ci-full` triggers the
339
+ full cross-runtime matrix without waiting for the weekly schedule.
340
+ - `gx branch finish` runs `scripts/agent-preflight.sh` in the worktree
341
+ before pushing. Default script auto-detects pnpm/npm, Rust, and Python
342
+ stacks and refuses the push on verification failure. After pre-flight
343
+ passes, draft PRs are promoted to ready-for-review so the
344
+ budget-friendly CI defaults fire once on a known-passing commit.
345
+
311
346
  ### v7.0.42
312
347
  - Bumped `@imdeadpool/guardex` from `7.0.41` to `7.0.42` so the current
313
348
  `main` payload can publish under a fresh npm version after `7.0.41` reached
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@imdeadpool/guardex",
3
- "version": "7.0.43",
3
+ "version": "7.1.1",
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,
@@ -12,12 +12,14 @@
12
12
  },
13
13
  "scripts": {
14
14
  "test": "node --test test/*.test.js",
15
+ "prepublishOnly": "node scripts/prepublish-bump-version.js",
15
16
  "agent:codex": "bash ./scripts/codex-agent.sh",
16
17
  "agent:branch:start": "bash ./scripts/agent-branch-start.sh",
17
18
  "agent:branch:finish": "bash ./scripts/agent-branch-finish.sh",
18
19
  "agent:branch:merge": "bash ./scripts/agent-branch-merge.sh",
19
20
  "agent:cleanup": "gx cleanup",
20
21
  "agent:hooks:install": "bash ./scripts/install-agent-git-hooks.sh",
22
+ "guardex:install-global": "bash ./scripts/install-global-hooks.sh",
21
23
  "agent:locks:claim": "python3 ./scripts/agent-file-locks.py claim",
22
24
  "agent:locks:allow-delete": "python3 ./scripts/agent-file-locks.py allow-delete",
23
25
  "agent:locks:release": "python3 ./scripts/agent-file-locks.py release",
@@ -39,6 +41,7 @@
39
41
  "files": [
40
42
  "bin",
41
43
  "src",
44
+ "scripts/prepublish-bump-version.js",
42
45
  "skills",
43
46
  "templates",
44
47
  "README.md",
@@ -0,0 +1,191 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const cp = require('node:child_process');
5
+ const fs = require('node:fs');
6
+ const path = require('node:path');
7
+
8
+ function readJson(filePath) {
9
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
10
+ }
11
+
12
+ function writeJson(filePath, value) {
13
+ fs.writeFileSync(filePath, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
14
+ }
15
+
16
+ function escapeRegexLiteral(value) {
17
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
18
+ }
19
+
20
+ function nextPatchVersion(version) {
21
+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(String(version || '').trim());
22
+ if (!match) {
23
+ throw new Error(`Cannot auto-bump non-plain semver version: ${version}`);
24
+ }
25
+ return `${match[1]}.${match[2]}.${Number(match[3]) + 1}`;
26
+ }
27
+
28
+ function defaultNpmView(name, version) {
29
+ const result = cp.spawnSync('npm', ['view', `${name}@${version}`, 'version', '--json'], {
30
+ encoding: 'utf8',
31
+ stdio: ['ignore', 'pipe', 'pipe'],
32
+ });
33
+
34
+ if (result.status === 0) {
35
+ return { state: 'published' };
36
+ }
37
+
38
+ const details = `${result.stdout || ''}\n${result.stderr || ''}`.trim();
39
+ if (/E404|404\s+Not Found|No match found|is not in this registry/i.test(details)) {
40
+ return { state: 'unpublished' };
41
+ }
42
+
43
+ if (result.error) {
44
+ return { state: 'error', message: result.error.message };
45
+ }
46
+
47
+ return { state: 'error', message: details || `npm view exited with status ${result.status}` };
48
+ }
49
+
50
+ function shouldSkip(env) {
51
+ if (env.GUARDEX_SKIP_PUBLISH_BUMP === '1') {
52
+ return 'GUARDEX_SKIP_PUBLISH_BUMP=1';
53
+ }
54
+ if (env.npm_config_dry_run === 'true') {
55
+ return 'npm publish --dry-run';
56
+ }
57
+ if (env.GITHUB_ACTIONS === 'true' && env.GUARDEX_ALLOW_PUBLISH_BUMP !== '1') {
58
+ return 'GitHub Actions release workflows keep package.json as the release source of truth';
59
+ }
60
+ return null;
61
+ }
62
+
63
+ function findPublishableVersion({ name, version, npmView, maxAttempts = 100 }) {
64
+ let candidate = version;
65
+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
66
+ const check = npmView(name, candidate);
67
+ if (check.state === 'unpublished') {
68
+ return { version: candidate, changed: candidate !== version };
69
+ }
70
+ if (check.state !== 'published') {
71
+ throw new Error(
72
+ `Unable to verify ${name}@${candidate} on npm: ${check.message || `state=${check.state}`}`,
73
+ );
74
+ }
75
+ candidate = nextPatchVersion(candidate);
76
+ }
77
+
78
+ throw new Error(`Unable to find an unpublished patch version after ${maxAttempts} attempts`);
79
+ }
80
+
81
+ function updatePackageLock(repoRoot, name, version) {
82
+ const lockPath = path.join(repoRoot, 'package-lock.json');
83
+ if (!fs.existsSync(lockPath)) {
84
+ return false;
85
+ }
86
+
87
+ const lockfile = readJson(lockPath);
88
+ lockfile.name = name;
89
+ lockfile.version = version;
90
+ if (lockfile.packages && lockfile.packages['']) {
91
+ lockfile.packages[''].name = name;
92
+ lockfile.packages[''].version = version;
93
+ }
94
+ writeJson(lockPath, lockfile);
95
+ return true;
96
+ }
97
+
98
+ function buildReleaseNote(name, previousVersion, version) {
99
+ return (
100
+ `### v${version}\n` +
101
+ `- Bumped \`${name}\` from \`${previousVersion}\` to \`${version}\` so direct\n` +
102
+ ` \`npm publish\` can continue after \`${previousVersion}\` reached the registry.\n\n`
103
+ );
104
+ }
105
+
106
+ function updateReadmeReleaseNote(repoRoot, name, previousVersion, version) {
107
+ const readmePath = path.join(repoRoot, 'README.md');
108
+ if (!fs.existsSync(readmePath)) {
109
+ return false;
110
+ }
111
+
112
+ const readme = fs.readFileSync(readmePath, 'utf8');
113
+ const headingPattern = new RegExp(`^###\\s+v${escapeRegexLiteral(version)}\\b`, 'm');
114
+ if (headingPattern.test(readme)) {
115
+ return false;
116
+ }
117
+
118
+ const releaseNote = buildReleaseNote(name, previousVersion, version);
119
+ const major = String(version).split('.')[0];
120
+ const majorSummaryPattern = new RegExp(
121
+ `(<summary><strong>v${escapeRegexLiteral(major)}\\.x</strong></summary>\\n\\n)`,
122
+ );
123
+ if (majorSummaryPattern.test(readme)) {
124
+ fs.writeFileSync(readmePath, readme.replace(majorSummaryPattern, `$1${releaseNote}`), 'utf8');
125
+ return true;
126
+ }
127
+
128
+ if (/## Release notes\n\n/.test(readme)) {
129
+ fs.writeFileSync(readmePath, readme.replace(/## Release notes\n\n/, `## Release notes\n\n${releaseNote}`), 'utf8');
130
+ return true;
131
+ }
132
+
133
+ throw new Error('README.md is missing a Release notes section for the generated publish bump');
134
+ }
135
+
136
+ function runPrepublishBump(options = {}) {
137
+ const repoRoot = options.repoRoot || path.resolve(__dirname, '..');
138
+ const env = options.env || process.env;
139
+ const log = options.log || console.log;
140
+ const npmView = options.npmView || defaultNpmView;
141
+ const skipReason = shouldSkip(env);
142
+
143
+ if (skipReason) {
144
+ log(`[guardex] prepublish version bump skipped: ${skipReason}.`);
145
+ return { changed: false, reason: 'skipped' };
146
+ }
147
+
148
+ const packagePath = path.join(repoRoot, 'package.json');
149
+ const packageJson = readJson(packagePath);
150
+ if (!packageJson.name || !packageJson.version) {
151
+ throw new Error('package.json must include name and version before publish');
152
+ }
153
+
154
+ const next = findPublishableVersion({
155
+ name: packageJson.name,
156
+ version: packageJson.version,
157
+ npmView,
158
+ });
159
+
160
+ if (!next.changed) {
161
+ log(`[guardex] ${packageJson.name}@${packageJson.version} is not published yet; keeping package version.`);
162
+ return { changed: false, version: packageJson.version };
163
+ }
164
+
165
+ const previousVersion = packageJson.version;
166
+ packageJson.version = next.version;
167
+ writeJson(packagePath, packageJson);
168
+ updatePackageLock(repoRoot, packageJson.name, next.version);
169
+ updateReadmeReleaseNote(repoRoot, packageJson.name, previousVersion, next.version);
170
+ log(`[guardex] bumped ${packageJson.name} from ${previousVersion} to ${next.version} before npm publish.`);
171
+ return { changed: true, version: next.version, previousVersion };
172
+ }
173
+
174
+ if (require.main === module) {
175
+ try {
176
+ runPrepublishBump();
177
+ } catch (error) {
178
+ console.error(`[guardex] prepublish version bump failed: ${error.message}`);
179
+ process.exitCode = 1;
180
+ }
181
+ }
182
+
183
+ module.exports = {
184
+ defaultNpmView,
185
+ buildReleaseNote,
186
+ findPublishableVersion,
187
+ nextPatchVersion,
188
+ runPrepublishBump,
189
+ shouldSkip,
190
+ updateReadmeReleaseNote,
191
+ };
@@ -0,0 +1,82 @@
1
+ ---
2
+ name: gx-act
3
+ description: "Run GitHub Actions workflows locally with nektos/act before pushing, so CI failures are caught on the laptop and the PR can be squash-merged on the first remote run."
4
+ ---
5
+
6
+ # gx-act — local GitHub Actions
7
+
8
+ Use whenever a change touches code that would trigger CI on GitHub. Run the workflows locally with `act` first; only push the branch when the local run is green, then squash-merge the PR on GitHub.
9
+
10
+ ## When to invoke
11
+
12
+ - Before `gx pr open` / `gx pr sync` / `gx branch finish --via-pr`.
13
+ - Before re-pushing after a CI failure.
14
+ - When iterating on `.github/workflows/*.yml` itself.
15
+
16
+ ## Install `act`
17
+
18
+ `act` requires Docker (or Podman). Check the binary:
19
+
20
+ ```sh
21
+ command -v act || echo "act not installed"
22
+ ```
23
+
24
+ Install one way:
25
+
26
+ ```sh
27
+ # Linux/macOS via the upstream installer
28
+ curl -fsSL https://raw.githubusercontent.com/nektos/act/master/install.sh | bash -s -- -b "$HOME/.local/bin"
29
+
30
+ # macOS via Homebrew
31
+ brew install act
32
+
33
+ # Arch
34
+ sudo pacman -S act
35
+
36
+ # Or use the GitHub CLI extension
37
+ gh extension install https://github.com/nektos/gh-act
38
+ ```
39
+
40
+ Upstream: https://github.com/nektos/act
41
+
42
+ ## Quick commands
43
+
44
+ ```sh
45
+ # List jobs the local runner would execute for the push event
46
+ act -l
47
+
48
+ # Run the default push workflows (what GitHub runs on a normal push)
49
+ act push
50
+
51
+ # Run a specific event
52
+ act pull_request
53
+ act workflow_dispatch -W .github/workflows/release.yml
54
+
55
+ # Run a single job
56
+ act -j test
57
+
58
+ # Pin a runner image (medium is the act default; large matches real GH closer)
59
+ act -P ubuntu-latest=catthehacker/ubuntu:act-latest
60
+
61
+ # Pass secrets / env without committing them
62
+ act -s GITHUB_TOKEN="$GITHUB_TOKEN" --env-file .env.act
63
+
64
+ # Reuse containers between runs (faster iteration)
65
+ act --reuse
66
+ ```
67
+
68
+ ## Workflow (local CI → squash-merge on GitHub)
69
+
70
+ 1. Implement the change in the agent worktree.
71
+ 2. `act -l` to confirm which jobs will fire for the event you care about.
72
+ 3. `act push` (or the specific event/job) until it is green locally.
73
+ 4. `gx branch finish --branch "<agent-branch>" --base main --via-pr --wait-for-merge --cleanup`.
74
+ - Or `gx pr open` then `gx pr sync --auto-merge --merge-strategy squash` for explicit PR control.
75
+ 5. On GitHub: squash-merge once the remote run mirrors the local one.
76
+
77
+ ## Notes
78
+
79
+ - `act` does not reproduce GitHub-hosted services exactly (no real secrets, different runner image, no concurrency groups). Treat a green `act` run as a strong signal, not a proof — the remote run is still authoritative.
80
+ - Keep `act` config in `.actrc` at the repo root so every agent uses the same runner image.
81
+ - If a workflow uses `GITHUB_TOKEN` for API calls, pass a PAT via `-s GITHUB_TOKEN=...`; do not commit it.
82
+ - Add `.actrc`, `.cache/act`, and any `act`-specific event payloads to `.gitignore` if they appear.
@@ -0,0 +1,279 @@
1
+ 'use strict';
2
+
3
+ // Live agent-lane activity: the W1 producer (`gx agents set-status`) and the
4
+ // jump selector (`gx agents jump`). The core functions are dependency-injected
5
+ // (session store + surface writer) so they unit-test without a live tmux/kitty.
6
+ const path = require('node:path');
7
+
8
+ const { TOOL_NAME } = require('../context');
9
+ const {
10
+ readAgentSession,
11
+ listAgentSessions,
12
+ updateAgentSession,
13
+ } = require('./sessions');
14
+ const { selectTerminalBackend } = require('../terminal');
15
+
16
+ // Canonical states a lane can be in, surfaced as cockpit pane icons.
17
+ const ACTIVITY_STATES = ['working', 'waiting', 'done', 'idle'];
18
+
19
+ const DEFAULT_ICONS = {
20
+ working: '🤖',
21
+ waiting: '💬',
22
+ done: '✅',
23
+ idle: '·',
24
+ };
25
+
26
+ // Aliases an agent hook or human might send; everything maps to one canonical
27
+ // state so callers do not need to memorize exact tokens.
28
+ const ACTIVITY_ALIASES = {
29
+ work: 'working',
30
+ working: 'working',
31
+ busy: 'working',
32
+ running: 'working',
33
+ active: 'working',
34
+ thinking: 'working',
35
+ wait: 'waiting',
36
+ waiting: 'waiting',
37
+ input: 'waiting',
38
+ blocked: 'waiting',
39
+ prompt: 'waiting',
40
+ attention: 'waiting',
41
+ done: 'done',
42
+ complete: 'done',
43
+ completed: 'done',
44
+ finished: 'done',
45
+ stop: 'done',
46
+ idle: 'idle',
47
+ none: 'idle',
48
+ clear: 'idle',
49
+ };
50
+
51
+ // Lower-priority jump targets sort after; waiting outranks done.
52
+ const JUMP_PRIORITY = { waiting: 0, done: 1 };
53
+
54
+ function normalizeActivity(raw) {
55
+ const key = String(raw === undefined || raw === null ? '' : raw).trim().toLowerCase();
56
+ if (!key) return '';
57
+ if (ACTIVITY_ALIASES[key]) return ACTIVITY_ALIASES[key];
58
+ return ACTIVITY_STATES.includes(key) ? key : '';
59
+ }
60
+
61
+ function activityIcon(activity, icons = DEFAULT_ICONS) {
62
+ const normalized = normalizeActivity(activity);
63
+ return (icons && icons[normalized]) || '';
64
+ }
65
+
66
+ function laneName(session) {
67
+ const value = session && typeof session === 'object' ? session : {};
68
+ const branch = typeof value.branch === 'string' ? value.branch : '';
69
+ const tail = branch.includes('/') ? branch.slice(branch.lastIndexOf('/') + 1) : branch;
70
+ const title = typeof value.title === 'string' ? value.title.trim() : '';
71
+ return title || tail || (typeof value.id === 'string' ? value.id : '') || 'agent';
72
+ }
73
+
74
+ // "🤖 fix-auth" — icon plus the short lane name. Falls back gracefully when an
75
+ // icon or name is missing.
76
+ function windowLabel(session, activity, icons = DEFAULT_ICONS) {
77
+ const icon = activityIcon(activity, icons);
78
+ const name = laneName(session);
79
+ if (!icon) return name;
80
+ return name ? `${icon} ${name}` : icon;
81
+ }
82
+
83
+ function sessionPaneTarget(session) {
84
+ const value = session && typeof session === 'object' ? session : {};
85
+ const tmux = value.tmux && typeof value.tmux === 'object' ? value.tmux : {};
86
+ return (
87
+ tmux.target ||
88
+ tmux.paneId ||
89
+ value.tmuxTarget ||
90
+ tmux.session ||
91
+ value.tmuxSession ||
92
+ ''
93
+ );
94
+ }
95
+
96
+ function sessionBackendName(session) {
97
+ const value = session && typeof session === 'object' ? session : {};
98
+ const tmux = value.tmux && typeof value.tmux === 'object' ? value.tmux : {};
99
+ if (tmux.backend) return String(tmux.backend);
100
+ if (value.terminal) return String(value.terminal);
101
+ return 'tmux';
102
+ }
103
+
104
+ function resolveSession(repoRoot, options = {}, deps = {}) {
105
+ const read = deps.readAgentSession || readAgentSession;
106
+ const list = deps.listAgentSessions || listAgentSessions;
107
+
108
+ // A malformed --session id or a corrupt session file must surface as a clean
109
+ // "no lane matched", not a thrown stack trace.
110
+ try {
111
+ if (options.sessionId) {
112
+ return read(repoRoot, options.sessionId);
113
+ }
114
+
115
+ const sessions = list(repoRoot);
116
+ if (options.branch) {
117
+ return sessions.find((session) => session.branch === options.branch) || null;
118
+ }
119
+
120
+ const worktree = options.worktree || options.cwd;
121
+ if (worktree) {
122
+ const target = path.resolve(worktree);
123
+ return (
124
+ sessions.find(
125
+ (session) => session.worktreePath && path.resolve(session.worktreePath) === target,
126
+ ) || null
127
+ );
128
+ }
129
+ } catch (_error) {
130
+ return null;
131
+ }
132
+ return null;
133
+ }
134
+
135
+ // Best-effort: apply the status label to the lane's pane. Never throws — a dead
136
+ // or absent multiplexer must not fail set-status.
137
+ function applySurface(context, deps = {}) {
138
+ const { target, label } = context;
139
+ if (!target) return { applied: false, reason: 'no-target' };
140
+ const apply = deps.applyWindowStatus;
141
+ if (typeof apply !== 'function') return { applied: false, reason: 'no-surface' };
142
+ try {
143
+ apply({ target, label, backend: sessionBackendName(context.session), activity: context.activity });
144
+ return { applied: true };
145
+ } catch (error) {
146
+ return { applied: false, reason: 'surface-error', error: error && error.message };
147
+ }
148
+ }
149
+
150
+ // Producer core: persist the activity onto the session and (best-effort) write
151
+ // its label to the cockpit pane. `deps` injects the session store + surface.
152
+ function setAgentActivity(repoRoot, options = {}, deps = {}) {
153
+ const activity = normalizeActivity(options.activity);
154
+ if (!activity) {
155
+ throw new Error(
156
+ `Unknown agent activity: ${options.activity}. Use one of: ${ACTIVITY_STATES.join(', ')}.`,
157
+ );
158
+ }
159
+
160
+ const session = resolveSession(repoRoot, options, deps);
161
+ if (!session) {
162
+ return { ok: false, reason: 'session-not-found', activity };
163
+ }
164
+
165
+ const update = deps.updateAgentSession || updateAgentSession;
166
+ const updated = update(repoRoot, session.id, { activity }) || session;
167
+ const label = windowLabel(updated, activity, options.icons);
168
+ const target = sessionPaneTarget(updated);
169
+ const surface = applySurface({ session: updated, label, target, activity }, deps);
170
+
171
+ return { ok: true, activity, sessionId: session.id, label, target, surface };
172
+ }
173
+
174
+ function jumpFilter(options = {}) {
175
+ if (options.waiting && !options.done) return new Set(['waiting']);
176
+ if (options.done && !options.waiting) return new Set(['done']);
177
+ return new Set(['waiting', 'done']);
178
+ }
179
+
180
+ // Pick the lane most in need of attention: waiting before done, newest first,
181
+ // restricted to lanes that actually have a cockpit pane to focus.
182
+ function selectJumpTarget(sessions, options = {}) {
183
+ const wanted = jumpFilter(options);
184
+ const candidates = (Array.isArray(sessions) ? sessions : [])
185
+ .filter((session) => wanted.has(normalizeActivity(session.activity)))
186
+ .filter((session) => sessionPaneTarget(session));
187
+
188
+ candidates.sort((left, right) => {
189
+ const leftPriority = JUMP_PRIORITY[normalizeActivity(left.activity)] ?? 9;
190
+ const rightPriority = JUMP_PRIORITY[normalizeActivity(right.activity)] ?? 9;
191
+ if (leftPriority !== rightPriority) return leftPriority - rightPriority;
192
+ return String(right.updatedAt || '').localeCompare(String(left.updatedAt || ''));
193
+ });
194
+
195
+ return candidates[0] || null;
196
+ }
197
+
198
+ // CLI wrapper for `gx agents set-status`: wires the live terminal backend in as
199
+ // the surface writer, then delegates to the pure core.
200
+ function runSetStatusCommand(repoRoot, options = {}, deps = {}) {
201
+ // When invoked from inside a lane (e.g. an agent hook) with no explicit
202
+ // selector, fall back to the current working directory's worktree.
203
+ const resolved = options.sessionId || options.branch || options.worktree
204
+ ? options
205
+ : { ...options, worktree: process.cwd() };
206
+ let backend = null;
207
+ const result = setAgentActivity(repoRoot, resolved, {
208
+ ...deps,
209
+ applyWindowStatus({ target, label, backend: sessionBackend }) {
210
+ // Honor an explicit --backend, else the lane's recorded backend (matching
211
+ // runJumpCommand), else auto-detect.
212
+ const backendName = options.backend || sessionBackend || 'auto';
213
+ if (!backend) backend = (deps.selectTerminalBackend || selectTerminalBackend)(backendName);
214
+ if (backend && typeof backend.setWindowStatus === 'function') {
215
+ backend.setWindowStatus(target, label);
216
+ }
217
+ },
218
+ });
219
+
220
+ if (!result.ok) {
221
+ return {
222
+ status: 1,
223
+ stderr: `[${TOOL_NAME}] No agent lane matched for set-status (use --session, --branch, or --worktree).\n`,
224
+ };
225
+ }
226
+
227
+ const applied = result.surface && result.surface.applied;
228
+ const note = applied ? '' : ` (surface ${result.surface ? result.surface.reason : 'skipped'})`;
229
+ return {
230
+ status: 0,
231
+ stdout: `[${TOOL_NAME}] ${result.sessionId} -> ${result.activity} ${result.label}${note}\n`,
232
+ };
233
+ }
234
+
235
+ // CLI wrapper for `gx agents jump`.
236
+ function runJumpCommand(repoRoot, options = {}, deps = {}) {
237
+ const list = deps.listAgentSessions || listAgentSessions;
238
+ const target = selectJumpTarget(list(repoRoot), options);
239
+ if (!target) {
240
+ return { status: 1, stderr: `[${TOOL_NAME}] No waiting/done agent lane to jump to.\n` };
241
+ }
242
+
243
+ const paneTarget = sessionPaneTarget(target);
244
+ if (options.print) {
245
+ return { status: 0, stdout: `${paneTarget}\n` };
246
+ }
247
+
248
+ try {
249
+ const backendName = options.backend || sessionBackendName(target);
250
+ const backend = (deps.selectTerminalBackend || selectTerminalBackend)(backendName);
251
+ backend.focusPane(paneTarget);
252
+ } catch (error) {
253
+ return {
254
+ status: 1,
255
+ stderr: `[${TOOL_NAME}] Could not focus ${paneTarget}: ${error && error.message}\n`,
256
+ };
257
+ }
258
+
259
+ return {
260
+ status: 0,
261
+ stdout: `[${TOOL_NAME}] Jumped to ${target.id} (${normalizeActivity(target.activity)}) ${paneTarget}\n`,
262
+ };
263
+ }
264
+
265
+ module.exports = {
266
+ ACTIVITY_STATES,
267
+ DEFAULT_ICONS,
268
+ normalizeActivity,
269
+ activityIcon,
270
+ laneName,
271
+ windowLabel,
272
+ sessionPaneTarget,
273
+ sessionBackendName,
274
+ resolveSession,
275
+ setAgentActivity,
276
+ selectJumpTarget,
277
+ runSetStatusCommand,
278
+ runJumpCommand,
279
+ };
@@ -45,10 +45,22 @@ function parseWorktreeList(outputText) {
45
45
  return worktrees;
46
46
  }
47
47
 
48
- function worktreePathForBranch(repoRoot, branch) {
48
+ function listWorktrees(repoRoot) {
49
49
  const result = git(repoRoot, ['worktree', 'list', '--porcelain'], { allowFailure: true });
50
- if (result.status !== 0) return { worktreePath: repoRoot, worktreeFound: false };
51
- const match = parseWorktreeList(result.stdout).find((entry) => entry.branch === branch);
50
+ return result.status === 0 ? parseWorktreeList(result.stdout) : null;
51
+ }
52
+
53
+ // `worktrees` (pre-parsed via listWorktrees) lets callers iterating many branches
54
+ // in one pass hoist the invariant `git worktree list` out of their loop. When
55
+ // omitted, the list is fetched on demand — unchanged behavior.
56
+ function worktreePathForBranch(repoRoot, branch, worktrees = null) {
57
+ let entries = worktrees;
58
+ if (entries == null) {
59
+ const result = git(repoRoot, ['worktree', 'list', '--porcelain'], { allowFailure: true });
60
+ if (result.status !== 0) return { worktreePath: repoRoot, worktreeFound: false };
61
+ entries = parseWorktreeList(result.stdout);
62
+ }
63
+ const match = entries.find((entry) => entry.branch === branch);
52
64
  return {
53
65
  worktreePath: match?.path || repoRoot,
54
66
  worktreeFound: Boolean(match?.path),
@@ -119,7 +131,7 @@ function inspectAgentBranch(options) {
119
131
 
120
132
  const baseBranch = resolveBaseBranch(repoRoot, branch);
121
133
  const compareRef = compareRefForBase(repoRoot, baseBranch);
122
- const { worktreePath, worktreeFound } = worktreePathForBranch(repoRoot, branch);
134
+ const { worktreePath, worktreeFound } = worktreePathForBranch(repoRoot, branch, options.worktrees);
123
135
  return { repoRoot, branch, baseBranch, compareRef, worktreePath, worktreeFound };
124
136
  }
125
137
 
@@ -179,6 +191,7 @@ module.exports = {
179
191
  branchLocks,
180
192
  changedFiles,
181
193
  inspectAgentBranch,
194
+ listWorktrees,
182
195
  parseWorktreeList,
183
196
  readLockRegistry,
184
197
  renderDiff,
@@ -185,6 +185,14 @@ function buildPromptCommand(parts, agent, prompt) {
185
185
  return commandToShell([...parts, prompt]);
186
186
  }
187
187
 
188
+ function buildResourceEnv() {
189
+ const cpus = require('node:os').cpus().length || 8;
190
+ // Cap each agent's cargo parallelism to avoid overwhelming the system
191
+ // when multiple agents build concurrently.
192
+ const jobs = Math.max(2, Math.floor(cpus / 4));
193
+ return [`CARGO_BUILD_JOBS=${jobs}`];
194
+ }
195
+
188
196
  function buildAgentLaunchCommand(options) {
189
197
  if (!options || typeof options !== 'object') {
190
198
  throw new TypeError('options are required');
@@ -207,7 +215,8 @@ function buildAgentLaunchCommand(options) {
207
215
  }
208
216
 
209
217
  const launchCommand = buildPromptCommand(baseParts, agent, prompt);
210
- const envPrefix = buildSessionEnv(agent, sessionId).join(' ');
218
+ const envParts = [...buildResourceEnv(), ...buildSessionEnv(agent, sessionId)];
219
+ const envPrefix = envParts.join(' ');
211
220
  const launchWithEnv = envPrefix ? `${envPrefix} ${launchCommand}` : launchCommand;
212
221
  if (!worktreePath) return launchWithEnv;
213
222
  return `cd ${shellQuote(worktreePath)} && ${launchWithEnv}`;