@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,248 @@
1
+ // Behavior inspired by Worktrunk (MIT OR Apache-2.0); native GX implementation.
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+ const crypto = require('node:crypto');
5
+ const { run } = require('./core/runtime');
6
+ const { runTaskStart } = require('./worktree-start');
7
+
8
+ function checkedRun(command, args, repoRoot, deps = {}) {
9
+ const result = (deps.run || run)(command, args, { cwd: repoRoot, timeout: 30000 });
10
+ if (result.status !== 0) {
11
+ throw new Error(`${command} failed: ${String(result.stderr || result.error || '').trim()}`);
12
+ }
13
+ return String(result.stdout || '');
14
+ }
15
+
16
+ function listWorktrees(repoRoot, deps = {}) {
17
+ const output = checkedRun('git', ['worktree', 'list', '--porcelain', '-z'], repoRoot, deps);
18
+ return output
19
+ .split('\0\0')
20
+ .filter(Boolean)
21
+ .map((record) => {
22
+ const entry = { path: '', branch: '', head: '', detached: false, bare: false };
23
+ for (const field of record.split('\0')) {
24
+ if (field.startsWith('worktree ')) entry.path = field.slice(9);
25
+ else if (field.startsWith('branch refs/heads/')) entry.branch = field.slice(18);
26
+ else if (field.startsWith('HEAD ')) entry.head = field.slice(5);
27
+ else if (field === 'detached') entry.detached = true;
28
+ else if (field === 'bare') entry.bare = true;
29
+ else if (field.startsWith('prunable')) entry.prunable = true;
30
+ else if (field.startsWith('locked')) entry.locked = true;
31
+ }
32
+ return entry;
33
+ })
34
+ .filter((entry) => entry.path && !entry.bare && !entry.prunable);
35
+ }
36
+
37
+ function validSelector(selector) {
38
+ if (typeof selector !== 'string' || !selector || /[\x00-\x1f\x7f]/.test(selector)) {
39
+ throw new Error('A non-empty selector without control characters is required');
40
+ }
41
+ if (selector.startsWith('-') && selector !== '-') throw new Error('Invalid selector');
42
+ }
43
+
44
+ function realPath(value) {
45
+ try {
46
+ return fs.realpathSync(value);
47
+ } catch {
48
+ return null;
49
+ }
50
+ }
51
+
52
+ function pathEntry(entries, value, cwd, deps) {
53
+ const candidate = realPath(path.resolve(cwd, value));
54
+ if (!candidate) return null;
55
+ const result = (deps.run || run)('git', ['-C', candidate, 'rev-parse', '--show-toplevel']);
56
+ if (result.status !== 0) return null;
57
+ const root = realPath(String(result.stdout).trim());
58
+ return entries.find((entry) => root && realPath(entry.path) === root);
59
+ }
60
+
61
+ function pullRequest(repoRoot, selector, deps) {
62
+ const match = selector.match(/^(?:pr:|#)([1-9]\d*)$/i) || selector.match(/^([1-9]\d*)$/);
63
+ let number = match?.[1];
64
+ if (selector.startsWith('https://')) {
65
+ const url = selector.match(/^https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/pull\/([1-9]\d*)\/?$/);
66
+ if (!url) throw new Error('Invalid GitHub pull request URL');
67
+ const repo = JSON.parse(
68
+ checkedRun('gh', ['repo', 'view', '--json', 'nameWithOwner'], repoRoot, deps)
69
+ );
70
+ if (repo.nameWithOwner?.toLowerCase() !== url[1].toLowerCase()) {
71
+ throw new Error('Pull request URL belongs to another repository');
72
+ }
73
+ number = url[2];
74
+ }
75
+ if (!number) return null;
76
+ const pr = JSON.parse(
77
+ checkedRun(
78
+ 'gh',
79
+ ['pr', 'view', number, '--json', 'number,headRefName,headRefOid,baseRefName,url'],
80
+ repoRoot,
81
+ deps
82
+ )
83
+ );
84
+ if (String(pr.number) !== number || !/^[0-9a-f]{40,64}$/.test(pr.headRefOid || '')) {
85
+ throw new Error('Invalid pull request metadata');
86
+ }
87
+ validSelector(pr.headRefName);
88
+ checkedRun('git', ['check-ref-format', '--branch', pr.headRefName], repoRoot, deps);
89
+ return pr;
90
+ }
91
+
92
+ function taskId(key) {
93
+ return `navigation:${crypto.createHash('sha256').update(key).digest('hex').slice(0, 24)}`;
94
+ }
95
+
96
+ function taskWorktree(repoRoot, entries, key, deps) {
97
+ const result = (deps.run || run)(
98
+ 'git',
99
+ ['config', '--get-regexp', '^branch\\..*\\.guardexTaskId$'],
100
+ { cwd: repoRoot }
101
+ );
102
+ if (result.status === 1) return null;
103
+ if (result.status !== 0) throw new Error('Cannot read navigation task identity');
104
+ const matches = String(result.stdout)
105
+ .split('\n')
106
+ .map((line) => line.match(/^branch\.(.+)\.guardextaskid\s+(.+)$/i))
107
+ .filter((match) => match && match[2] === taskId(key))
108
+ .flatMap((match) => entries.filter((entry) => entry.branch === match[1]));
109
+ if (matches.length > 1) throw new Error('Ambiguous navigation task identity');
110
+ return matches[0] || null;
111
+ }
112
+
113
+ function createLane(repoRoot, base, key, deps) {
114
+ const id = taskId(key);
115
+ const args = ['--task', `navigate-${key}`, '--task-id', id, '--base', base, '--no-transfer'];
116
+ const result = (deps.runTaskStart || runTaskStart)(repoRoot, args);
117
+ if (result.status !== 0)
118
+ throw new Error(
119
+ `Guarded worktree creation failed: ${result.stderr || result.stdout || result.error || ''}`
120
+ );
121
+ const branch = String(result.stdout || '').match(
122
+ /^\[agent-branch-start\] (?:Created branch|Reusing existing branch):\s+(.+)$/m
123
+ )?.[1];
124
+ const entry = listWorktrees(repoRoot, deps).find((item) => item.branch === branch);
125
+ if (!entry) throw new Error('Guarded creation did not return a registered worktree');
126
+ return { ...entry, created: true };
127
+ }
128
+
129
+ function resolveWorktree(repoRoot, selector, options = {}, deps = {}) {
130
+ validSelector(selector);
131
+ const entries = listWorktrees(repoRoot, deps);
132
+ const cwd = options.cwd || repoRoot;
133
+ if (selector === '-') {
134
+ const previous = options.previous || process.env.GX_PREVIOUS_WORKTREE || process.env.OLDPWD;
135
+ if (!previous) throw new Error('No previous worktree; use gx shell-init integration');
136
+ const entry = pathEntry(entries, previous, cwd, deps);
137
+ if (!entry) throw new Error('Previous directory is not a worktree in this repository');
138
+ return entry;
139
+ }
140
+ const branch = entries.find((entry) => entry.branch === selector);
141
+ if (branch) return branch;
142
+ const byPath = pathEntry(entries, selector, cwd, deps);
143
+ if (byPath) return byPath;
144
+ const pr = pullRequest(repoRoot, selector, deps);
145
+ if (pr) {
146
+ const existing =
147
+ entries.find((entry) => entry.head === pr.headRefOid && entry.branch === pr.headRefName) ||
148
+ entries.find((entry) => entry.head === pr.headRefOid && entry.detached) ||
149
+ taskWorktree(repoRoot, entries, `pr-${pr.number}-${pr.headRefOid}`, deps);
150
+ if (existing) return { ...existing, pr };
151
+ if (!options.create) throw new Error(`No worktree for PR #${pr.number}; use --create`);
152
+ validSelector(pr.baseRefName);
153
+ checkedRun('git', ['check-ref-format', '--branch', pr.baseRefName], repoRoot, deps);
154
+ const baseExists = ['refs/heads/', 'refs/remotes/origin/'].some(
155
+ (prefix) =>
156
+ (deps.run || run)(
157
+ 'git',
158
+ ['show-ref', '--verify', '--quiet', `${prefix}${pr.baseRefName}`],
159
+ { cwd: repoRoot }
160
+ ).status === 0
161
+ );
162
+ if (!baseExists) throw new Error('Pull request base is not available locally; fetch it first');
163
+ const origin = checkedRun('git', ['remote', 'get-url', 'origin'], repoRoot, deps).trim();
164
+ const originRepo = origin.match(
165
+ /^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([\w.-]+\/[\w.-]+?)(?:\.git)?$/
166
+ )?.[1];
167
+ const prRepo = pr.url?.match(
168
+ /^https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/pull\/[1-9]\d*$/
169
+ )?.[1];
170
+ if (!originRepo || !prRepo || originRepo.toLowerCase() !== prRepo.toLowerCase()) {
171
+ throw new Error('PR repository does not match the origin fetch remote');
172
+ }
173
+ // Fetch only the repository's numbered PR ref, never GitHub-provided shell/ref text.
174
+ checkedRun(
175
+ 'git',
176
+ ['fetch', '--no-tags', 'origin', `refs/pull/${pr.number}/head`],
177
+ repoRoot,
178
+ deps
179
+ );
180
+ const oid = checkedRun(
181
+ 'git',
182
+ ['rev-parse', '--verify', 'FETCH_HEAD^{commit}'],
183
+ repoRoot,
184
+ deps
185
+ ).trim();
186
+ if (oid !== pr.headRefOid) throw new Error('Pull request changed during fetch; retry');
187
+ const base = `gx-pr/${pr.number}/${oid}`;
188
+ const existingBase = (deps.run || run)('git', ['rev-parse', '--verify', `refs/heads/${base}`], {
189
+ cwd: repoRoot
190
+ });
191
+ if (existingBase.status === 0) {
192
+ if (existingBase.stdout.trim() !== oid) throw new Error('Pull request base ref collision');
193
+ } else {
194
+ checkedRun('git', ['branch', base, oid], repoRoot, deps);
195
+ }
196
+ const entry = createLane(repoRoot, base, `pr-${pr.number}-${oid}`, deps);
197
+ checkedRun(
198
+ 'git',
199
+ ['config', `branch.${entry.branch}.guardexBase`, pr.baseRefName],
200
+ repoRoot,
201
+ deps
202
+ );
203
+ return { ...entry, pr };
204
+ }
205
+ const existingTask = taskWorktree(repoRoot, entries, selector, deps);
206
+ if (existingTask) return existingTask;
207
+ if (!options.create)
208
+ throw new Error(`No worktree matches ${selector}; use --create for a branch`);
209
+ checkedRun('git', ['check-ref-format', '--branch', selector], repoRoot, deps);
210
+ return createLane(repoRoot, selector, selector, deps);
211
+ }
212
+
213
+ function shellIntegration(shell = 'bash') {
214
+ if (!['bash', 'zsh', 'fish'].includes(shell))
215
+ throw new Error('Supported shells: bash, zsh, fish');
216
+ if (shell === 'fish')
217
+ return `function gx
218
+ if test "$argv[1]" = switch; and not contains -- --print $argv; and not contains -- --json $argv; and not contains -- --help $argv; and not contains -- -h $argv
219
+ set -l destination (command gx $argv --print)
220
+ or return $status
221
+ test -n "$destination"; or return 0
222
+ set -l previous "$PWD"
223
+ cd -- "$destination"; or return $status
224
+ set -gx GX_PREVIOUS_WORKTREE "$previous"
225
+ else
226
+ command gx $argv
227
+ end
228
+ end
229
+ `;
230
+ return `gx() {
231
+ if [ "\${1-}" = switch ]; then
232
+ case " $* " in
233
+ *" --print "*|*" --json "*|*" --help "*|*" -h "*) command gx "$@"; return $? ;;
234
+ esac
235
+ local destination previous
236
+ destination=$(command gx "$@" --print) || return $?
237
+ [ -n "$destination" ] || return 0
238
+ previous=$PWD
239
+ builtin cd -- "$destination" || return $?
240
+ export GX_PREVIOUS_WORKTREE="$previous"
241
+ else
242
+ command gx "$@"
243
+ fi
244
+ }
245
+ `;
246
+ }
247
+
248
+ module.exports = { checkedRun, listWorktrees, resolveWorktree, shellIntegration };
@@ -0,0 +1,89 @@
1
+ const readline = require('node:readline/promises');
2
+ const { listWorktrees, checkedRun } = require('./worktree-navigation');
3
+
4
+ function terminalText(value) {
5
+ return String(value).replace(/[\x00-\x1f\x7f-\x9f]/g, '');
6
+ }
7
+
8
+ function worktreePreview(entry, deps = {}) {
9
+ let diff;
10
+ let pr;
11
+ try {
12
+ diff =
13
+ checkedRun(
14
+ 'git',
15
+ ['--no-pager', 'diff', '--no-ext-diff', '--stat', 'HEAD', '--'],
16
+ entry.path,
17
+ deps
18
+ ).trim() || 'No tracked changes';
19
+ } catch {
20
+ diff = 'Diff unavailable';
21
+ }
22
+ try {
23
+ pr = JSON.parse(
24
+ checkedRun('gh', ['pr', 'view', '--json', 'number,title,state,url'], entry.path, deps)
25
+ );
26
+ } catch {
27
+ pr = null;
28
+ }
29
+ return { diff, pr };
30
+ }
31
+
32
+ async function pickWorktree(repoRoot, options = {}, deps = {}) {
33
+ const input = options.input || process.stdin;
34
+ const output = options.output || process.stderr;
35
+ if (!input.isTTY || !output.isTTY)
36
+ throw new Error(
37
+ 'Interactive picker requires a TTY; provide a branch/path/PR selector with --print or --json'
38
+ );
39
+ const entries = (deps.listWorktrees || listWorktrees)(repoRoot);
40
+ if (!entries.length) throw new Error('No worktrees available');
41
+ let visible = entries;
42
+ const display = () =>
43
+ visible.forEach((entry, index) =>
44
+ output.write(
45
+ `${index + 1}. ${terminalText(entry.branch || '(detached)')} ${terminalText(entry.path)}\n`
46
+ )
47
+ );
48
+ display();
49
+ const rl = deps.question ? null : readline.createInterface({ input, output });
50
+ const question = deps.question || ((prompt) => rl.question(prompt));
51
+ try {
52
+ while (true) {
53
+ const answer = (
54
+ await question('Worktree number (/text filters, p N previews, q cancels): ')
55
+ ).trim();
56
+ if (!answer || /^(?:q|quit|cancel)$/i.test(answer)) return null;
57
+ if (answer.startsWith('/')) {
58
+ const query = answer.slice(1).toLowerCase();
59
+ visible = entries.filter((entry) =>
60
+ `${entry.branch} ${entry.path}`.toLowerCase().includes(query)
61
+ );
62
+ display();
63
+ if (!visible.length) output.write('No matches. Use / to clear the filter.\n');
64
+ continue;
65
+ }
66
+ const match = answer.match(/^(p\s+)?([1-9]\d*)$/i);
67
+ const entry = match && visible[Number(match[2]) - 1];
68
+ if (!entry) {
69
+ output.write('Choose a listed number.\n');
70
+ continue;
71
+ }
72
+ const preview = (deps.worktreePreview || worktreePreview)(entry, deps);
73
+ output.write(`${terminalText(preview.diff)}\n`);
74
+ output.write(
75
+ preview.pr
76
+ ? `PR #${preview.pr.number}: ${terminalText(preview.pr.title)} (${terminalText(preview.pr.state)})\n${terminalText(preview.pr.url)}\n`
77
+ : 'No PR preview available\n'
78
+ );
79
+ if (match[1]) continue;
80
+ const confirm = (await question('Switch here? [y/N]: ')).trim();
81
+ if (/^(?:y|yes)$/i.test(confirm)) return entry;
82
+ if (/^(?:q|quit|cancel)$/i.test(confirm)) return null;
83
+ }
84
+ } finally {
85
+ rl?.close();
86
+ }
87
+ }
88
+
89
+ module.exports = { pickWorktree, worktreePreview, terminalText };
@@ -0,0 +1,100 @@
1
+ const fs = require('node:fs');
2
+ const path = require('node:path');
3
+ const { run } = require('./core/runtime');
4
+
5
+ const KEYS = {
6
+ maxCount: 'multiagent.worktreeMaxCount',
7
+ maxBytes: 'multiagent.worktreeMaxBytes',
8
+ minFreeBytes: 'multiagent.worktreeMinFreeBytes'
9
+ };
10
+
11
+ function readWorktreeQuota(repoRoot) {
12
+ const limits = {};
13
+ for (const [name, key] of Object.entries(KEYS)) {
14
+ const result = run('git', ['-C', repoRoot, 'config', '--get', key]);
15
+ if (result.status === 1) continue;
16
+ const raw = String(result.stdout || '').trim();
17
+ if (result.status !== 0 || !/^\d+$/.test(raw) || !Number.isSafeInteger(Number(raw))) {
18
+ throw new Error('Invalid non-negative integer quota: ' + key);
19
+ }
20
+ limits[name] = Number(raw);
21
+ }
22
+ return limits;
23
+ }
24
+
25
+ // Conservative allocated bytes: do not follow symlinks; count hardlinks once.
26
+ // Reflink-shared blocks may be counted more than once by the filesystem.
27
+ function allocatedBytes(root, seen = new Set()) {
28
+ const stat = fs.lstatSync(root);
29
+ const id = stat.dev + ':' + stat.ino;
30
+ if (seen.has(id)) return 0;
31
+ seen.add(id);
32
+ let bytes = stat.blocks == null ? stat.size : stat.blocks * 512;
33
+ if (stat.isDirectory()) {
34
+ for (const name of fs.readdirSync(root)) bytes += allocatedBytes(path.join(root, name), seen);
35
+ }
36
+ if (!Number.isSafeInteger(bytes)) throw new Error('Cannot safely represent worktree usage');
37
+ return bytes;
38
+ }
39
+
40
+ function inspectWorktreeQuota(repoRoot, checkoutBytes, destination = repoRoot) {
41
+ const limits = readWorktreeQuota(repoRoot);
42
+ if (!Object.keys(limits).length) return null;
43
+ const list = run('git', ['-C', repoRoot, 'worktree', 'list', '--porcelain', '-z']);
44
+ if (list.status !== 0) throw new Error('Cannot inspect registered worktrees for quota');
45
+ const worktrees = list.stdout
46
+ .split('\0')
47
+ .filter((field) => field.startsWith('worktree '))
48
+ .map((field) => field.slice(9));
49
+ const secondary = worktrees.slice(1);
50
+ const seen = new Set();
51
+ let currentBytes = null;
52
+ if (limits.maxBytes != null) {
53
+ currentBytes = 0;
54
+ for (const worktree of secondary) {
55
+ // Missing registrations consume a count slot, but no disk space. A
56
+ // failure during traversal is unknown usage, not permission to proceed.
57
+ try {
58
+ fs.lstatSync(worktree);
59
+ } catch (error) {
60
+ if (error.code === 'ENOENT') continue;
61
+ throw error;
62
+ }
63
+ currentBytes += allocatedBytes(worktree, seen);
64
+ }
65
+ }
66
+ let freeBytes = null;
67
+ if (limits.minFreeBytes != null) {
68
+ let existing = path.resolve(destination);
69
+ while (!fs.existsSync(existing)) {
70
+ const parent = path.dirname(existing);
71
+ if (parent === existing) throw new Error('Cannot inspect destination filesystem');
72
+ existing = parent;
73
+ }
74
+ if (typeof fs.statfsSync !== 'function')
75
+ throw new Error('Filesystem quota requires Node statfs support');
76
+ const stat = fs.statfsSync(existing, { bigint: true });
77
+ freeBytes = stat.bavail * stat.bsize;
78
+ }
79
+ const violations = [];
80
+ if (limits.maxCount != null && secondary.length + 1 > limits.maxCount)
81
+ violations.push('QUOTA_WORKTREE_COUNT');
82
+ if (limits.maxBytes != null && currentBytes + checkoutBytes > limits.maxBytes)
83
+ violations.push('QUOTA_WORKTREE_BYTES');
84
+ if (
85
+ limits.minFreeBytes != null &&
86
+ freeBytes - BigInt(checkoutBytes) < BigInt(limits.minFreeBytes)
87
+ )
88
+ violations.push('QUOTA_MIN_FREE_BYTES');
89
+ return {
90
+ limits,
91
+ worktreeCount: secondary.length,
92
+ currentBytes,
93
+ freeBytes: freeBytes == null ? null : freeBytes.toString(),
94
+ projectedCheckoutBytes: checkoutBytes,
95
+ violations,
96
+ note: 'Secondary registered worktrees only. Admission estimate, not an OS quota: later writes, dependency provisioning and checkout filters may consume more. Reflink shared blocks may be overcounted.'
97
+ };
98
+ }
99
+
100
+ module.exports = { readWorktreeQuota, inspectWorktreeQuota, allocatedBytes };
@@ -0,0 +1,100 @@
1
+ const fs = require('node:fs');
2
+ const path = require('node:path');
3
+ const crypto = require('node:crypto');
4
+ const { run, packageAssetPath, packageAssetEnv } = require('./core/runtime');
5
+
6
+ function validateTaskId(id) {
7
+ if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(id || '')) {
8
+ throw new Error(
9
+ '--task-id requires 1-128 letters, digits, dots, underscores, colons or hyphens'
10
+ );
11
+ }
12
+ return id;
13
+ }
14
+
15
+ function estimateCheckout(repoRoot, ref, exclusions) {
16
+ for (const dir of exclusions) {
17
+ if (
18
+ !dir ||
19
+ /^[/-]/.test(dir) ||
20
+ /[*?\[\]\\\x00-\x1f\x7f]/.test(dir) ||
21
+ dir.endsWith(' ') ||
22
+ dir.split('/').some((part) => ['', '.', '..', '.git'].includes(part))
23
+ ) {
24
+ throw new Error('Invalid --sparse-exclude directory');
25
+ }
26
+ }
27
+ const resolved = run('git', [
28
+ '-C',
29
+ repoRoot,
30
+ 'rev-parse',
31
+ '--verify',
32
+ '--end-of-options',
33
+ `${ref}^{tree}`
34
+ ]);
35
+ if (resolved.status !== 0) throw new Error('Cannot resolve checkout estimate ref');
36
+ const result = run('git', ['-C', repoRoot, 'ls-tree', '-r', '-l', '-z', resolved.stdout.trim()]);
37
+ if (result.status !== 0) throw new Error('Cannot estimate tracked checkout data');
38
+ let trackedBytes = 0;
39
+ let excludedBytes = 0;
40
+ const directories = new Map();
41
+ for (const record of result.stdout.split('\0')) {
42
+ const tab = record.indexOf('\t');
43
+ if (tab < 0) continue;
44
+ const [mode, type, , rawSize] = record.slice(0, tab).trim().split(/\s+/);
45
+ if (type !== 'blob' || mode === '120000') continue;
46
+ const bytes = Number(rawSize);
47
+ if (!Number.isSafeInteger(bytes) || bytes < 0) throw new Error('Invalid Git object size');
48
+ const file = record.slice(tab + 1);
49
+ trackedBytes += bytes;
50
+ if (exclusions.some((dir) => file.startsWith(`${dir}/`))) excludedBytes += bytes;
51
+ if (file.includes('/')) {
52
+ const dir = file.split('/')[0];
53
+ directories.set(dir, (directories.get(dir) || 0) + bytes);
54
+ }
55
+ }
56
+ return {
57
+ trackedBytes,
58
+ excludedBytes,
59
+ checkoutBytes: trackedBytes - excludedBytes,
60
+ directories: [...directories]
61
+ .map(([dir, bytes]) => ({ path: dir, bytes }))
62
+ .sort((a, b) => b.bytes - a.bytes)
63
+ .slice(0, 8),
64
+ note: 'Tracked blob estimate only; filesystem overhead, checkout filters, LFS, dependencies and generated caches are not included.'
65
+ };
66
+ }
67
+
68
+ function runTaskStart(repoRoot, args) {
69
+ const taskFlags = args.filter((arg) => arg === '--task-id').length;
70
+ if (taskFlags > 1)
71
+ throw new Error('--task-id must appear once');
72
+ 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
+ const locks = [];
77
+ if (Object.keys(require('./worktree-quota').readWorktreeQuota(repoRoot)).length) {
78
+ locks.push(path.join(commonDir, 'gitguardex-worktree-quota.lock'));
79
+ }
80
+ if (id) locks.push(path.join(commonDir, `gitguardex-task-${crypto.createHash('sha256').update(id).digest('hex')}.lock`));
81
+ let command = ['bash', packageAssetPath('branchStart'), ...args];
82
+ for (const lock of locks.reverse()) {
83
+ command = ['python3', path.join(__dirname, 'finish/with-claims-lock.py'), lock, ...command];
84
+ }
85
+ return run(
86
+ command[0],
87
+ command.slice(1),
88
+ { cwd: repoRoot, env: packageAssetEnv() }
89
+ );
90
+ }
91
+
92
+ function invokeTaskStart(repoRoot, args) {
93
+ const result = runTaskStart(repoRoot, args);
94
+ if (result.stdout) process.stdout.write(result.stdout);
95
+ if (result.stderr) process.stderr.write(result.stderr);
96
+ if (result.status !== 0)
97
+ throw new Error(`Task start failed or is busy (status ${result.status})`);
98
+ }
99
+
100
+ module.exports = { estimateCheckout, runTaskStart, invokeTaskStart, validateTaskId };
@@ -14,6 +14,8 @@ routing with `GUARDEX_WORKTREE_MODE=adaptive` in `.env` or
14
14
  - In strict `always` mode, work from an `agent/*` branch + worktree. **Never** edit the protected base directly.
15
15
  - In adaptive mode, bounded single-agent work may remain on the current checkout after the radar and ownership checks below pass.
16
16
  - Claim files before editing in isolated lanes. Confirm a path is in your claim before deleting it.
17
+ - Use CodeGraph first for repository symbol, relationship, architecture, and impact lookup. If the project is not initialized, run `codegraph init -i` once and retry.
18
+ - Use `opensrc path <package-or-owner/repo[@ref|#ref]>` before generic clone/download when inspecting dependency or external repository source.
17
19
  - Commit, push, and open/update a PR for completed work unless the user says keep-local.
18
20
  - Keep outputs and notes compact. Less word, same proof.
19
21
 
@@ -163,6 +165,12 @@ Two things the gate deliberately will NOT do, so do not expect them:
163
165
  - **It never lets the fixer grade its own work.** Every repair is judged by a
164
166
  separate review invocation.
165
167
 
168
+ **Review and merge without asking.** The AI review and the gated merge are part of
169
+ finishing, not a separate decision: never stop to ask the user "should I run the
170
+ review?" or "should I merge?". Run the review automatically on every finished
171
+ lane; if it is clean (no HIGH/CRITICAL) and the change adds no new failing check,
172
+ merge. Stop and report only when the gate blocks, or the user said keep-local.
173
+
166
174
  Posting a review is NOT merging. `gx pr-review` / `gx review` post findings and
167
175
  exit; only `gx branch finish` (or `gx ship`) merges. A PR sitting open with a
168
176
  clean review means the finish flow was never run.
@@ -11,8 +11,10 @@ single-agent path may opt in with `GUARDEX_WORKTREE_MODE=adaptive` in `.env` (or
11
11
  - Pivot to an isolated lane when the task is substantial/long-lived, another writer is active in the repo, a target path is dirty or owned elsewhere, or scope expands. Use `gx branch start --new --no-transfer "<task>" "<agent-name>"`, then `cd` into the printed worktree.
12
12
  - In strict `always` mode, work from an `agent/*` branch + worktree and never edit the protected base (`main`/`dev`) directly.
13
13
  - In an isolated lane, claim files before editing: `gx locks claim --branch "<agent-branch>" <file...>`.
14
+ - Use CodeGraph first for repository symbol, relationship, architecture, and impact lookup. If the project is not initialized, run `codegraph init -i` once and retry.
15
+ - Use `opensrc path <package-or-owner/repo[@ref|#ref]>` before generic clone/download when inspecting dependency or external repository source.
14
16
  - Finish isolated work via PR + cleanup: `gx branch finish --branch "<agent-branch>" --via-pr --wait-for-merge --cleanup` (or `gx finish --all`). Direct adaptive work uses the repository's ordinary commit/push flow.
15
- - For isolated lanes, default to the self-repairing gated ship — add `--gate-review --gate-autofix` so blocking findings are fixed and re-verified before the merge instead of leaving the PR open. Add `--gate-baseline` only where the base branch CI is already red. CI waits until the review is clean by default; `--no-gate-serial-ci` opts into overlap. Codex code-assist defaults to bounded `medium` effort (override with `GUARDEX_REVIEW_CODEX_EFFORT`). Posting a review is not merging: `gx pr-review` posts and exits; only `gx branch finish` merges.
17
+ - For isolated lanes, default to the self-repairing gated ship — add `--gate-review --gate-autofix` so blocking findings are fixed and re-verified before the merge instead of leaving the PR open. Add `--gate-baseline` only where the base branch CI is already red. CI waits until the review is clean by default; `--no-gate-serial-ci` opts into overlap. Codex code-assist defaults to bounded `medium` effort (override with `GUARDEX_REVIEW_CODEX_EFFORT`). Posting a review is not merging: `gx pr-review` posts and exits; only `gx branch finish` merges. Never ask the user whether to run the review or to merge: review automatically and merge when the gate is clean; stop only when it blocks or the user said keep-local.
16
18
 
17
19
  Want the full multi-agent contract (Colony coordination, OpenSpec, token discipline, recovery)? Run `gx setup --contract`.
18
20
  <!-- multiagent-safety:END -->
@@ -112,6 +112,34 @@ Treat `🏁 Cleanup` as finished-but-best-effort, not as unconditional success:
112
112
 
113
113
  Structured phase events are persisted privately under `.omx/state/finish-runs/*.jsonl` (`0700` directory, `0600` files). Prefer that JSONL stream over parsing narrative logs when exact state is needed; the visual output prints the active event-file path.
114
114
 
115
+ For agent transcripts, opt into `gx branch finish --agent-quiet` (or `gx finish --agent-quiet`)
116
+ alongside the same required finish flags and gates. It prints one run ID/event-file pointer,
117
+ retains warnings and blockers, and ends with a bounded summary; it does not skip verification.
118
+ Read only new observations with `gx finish events --run <run-id> --wait-ms 30000`, then
119
+ pass the returned `--cursor <cursor>` on the next read. Use the same repository target as
120
+ the finish invocation. Let this bounded CLI wait do the polling instead of repeatedly
121
+ asking the model to reread the whole log. Events are observations, never merge authority.
122
+
123
+ Opt-in bounded observations (defaults remain unchanged):
124
+ - MCP `my_context`: pass `max_bytes` to bound UTF-8 JSON tool text. Ownership,
125
+ conflicts and safety fields are mandatory; `budget-too-small` requires a larger
126
+ budget or smaller file batch. Check `complete`/`omitted`; fetch full peers only
127
+ when needed. This budgets bytes, not model tokens.
128
+ - `gx watch --pr-cache-ms 5000` shares PR probes with a short in-process TTL keyed
129
+ by repository, remote, branch and HEAD. Observation age is shown; dirty state
130
+ stays fresh. The cache is never used by merge gates.
131
+ - `gx finish events --run <id> --view state`: merge `stages` patches by stage,
132
+ retain every `alerts` record, and resume with the opaque cursor. Paginated
133
+ snapshots are incomplete until `snapshotComplete: true`. Raw view remains the
134
+ default; reset explicitly on invalid/replaced/truncated cursors.
135
+ - `gx agents set-status --activity working --dedupe-surface`: skip identical
136
+ successful pane-label writes, but still renew session activity on every call.
137
+ Changed targets and failed writes retry. This never infers agent completion.
138
+
139
+ For setup guidance, use `gx prompt --list-parts` then `gx prompt --part <name>` for the
140
+ needed slice; use `--exec --part <name>` only for command-capable slices. Do not repeatedly
141
+ load the full setup prompt or remove the mandatory safety contract to save tokens.
142
+
115
143
  When inspecting or verifying, prefer `rtk` compact wrappers if available (`rtk git status`, `rtk grep`, `rtk test <cmd>`, and noisy gx reads like `rtk gx status` / `rtk gx doctor`). Do not wrap commands whose stdout is parsed by scripts (`--json`, `--porcelain`, exact stdout contracts) or shell-ready output (`gx prompt --exec`).
116
144
 
117
145
  To shrink gx's own large narrative output (e.g. `gx prompt`, `gx prompt --snippet`) before it lands in your context, set `GUARDEX_COMPRESS_CMD="<stdin->stdout filter>"`; gx routes that output through the filter (terse/non-TTY mode, fail-open, JSON skipped). Unset = byte-for-byte unchanged. Confirm it is wired with `gx status` or `gx doctor` — both print a `Token compression` line and flag a configured-but-missing binary (doctor's warning is advisory and never changes its safe/unsafe exit code).
@@ -0,0 +1,24 @@
1
+ ---
2
+ name: opensrc
3
+ description: "Fetch exact dependency or external repository source before inspecting internals. Use for package implementation, upstream behavior, or external GitHub source lookup."
4
+ allowed-tools: Bash(opensrc:*)
5
+ ---
6
+
7
+ # OpenSrc source lookup
8
+
9
+ Prefer OpenSrc over a generic clone when inspecting dependency or upstream
10
+ implementation code. It resolves package versions from the current lockfile and
11
+ caches sources outside the project.
12
+
13
+ ```bash
14
+ opensrc path <npm-package>
15
+ opensrc path pypi:<package>
16
+ opensrc path crates:<crate>
17
+ opensrc path <owner>/<repo>[@ref|#ref]
18
+ ```
19
+
20
+ Use the printed absolute directory with narrow `rg`, `find`, or file reads. Pass
21
+ `--cwd <project>` when dependency resolution must use another project's lockfile.
22
+
23
+ Do not use OpenSrc for ordinary public API questions that current official docs
24
+ or local types answer directly.
@@ -1,9 +1,23 @@
1
1
  #!/usr/bin/env bash
2
2
  set -euo pipefail
3
3
 
4
- if [[ "${GUARDEX_DISABLE_POST_MERGE_CLEANUP:-0}" == "1" ]]; then
5
- exit 0
4
+ # The env var alone is not reachable from a GUI client: VS Code's Source Control
5
+ # "Sync Changes" runs `git pull` with its own environment, so a user who only
6
+ # wants their pulls back cannot set it. Same reason pre-push reads
7
+ # multiagent.allowVscodeProtectedBranchWrites from git config — GUI clients get
8
+ # a config key, not an env var.
9
+ #
10
+ # git config --global multiagent.disablePostMergeCleanup true
11
+ #
12
+ # The sweep is housekeeping; `gx cleanup` and the next doctor run still do it.
13
+ disable_cleanup_raw="${GUARDEX_DISABLE_POST_MERGE_CLEANUP:-$(git config --get multiagent.disablePostMergeCleanup 2>/dev/null || true)}"
14
+ if [[ -z "$disable_cleanup_raw" ]]; then
15
+ disable_cleanup_raw="false"
6
16
  fi
17
+ disable_cleanup="$(printf '%s' "$disable_cleanup_raw" | tr '[:upper:]' '[:lower:]')"
18
+ case "$disable_cleanup" in
19
+ 1|true|yes|on) exit 0 ;;
20
+ esac
7
21
 
8
22
  repo_root="$(git rev-parse --show-toplevel 2>/dev/null || true)"
9
23
  if [[ -z "$repo_root" ]]; then