@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,156 @@
1
+ 'use strict';
2
+
3
+ const { createHash } = require('node:crypto');
4
+ const { fs, path, GH_BIN } = require('../context');
5
+ const { run } = require('../core/runtime');
6
+ const { repoApiPath } = require('../github-api');
7
+
8
+ const MAX_AGE_MS = 24 * 60 * 60 * 1000;
9
+ const hash = (value) => createHash('sha256').update(value).digest('hex');
10
+
11
+ // Only reuse the primary Codex verdict, never a Claude fallback. User Codex
12
+ // config and installed Abide rubrics can change outside the reviewed revision.
13
+ // Don't cache those cases (or a PR Lens run with its own local artifacts).
14
+ function reviewReceipt(repoRoot, revision, options, execute = run, env = process.env) {
15
+ const isOn = (value) => /^(1|true|yes|on)$/i.test(String(value || '').trim());
16
+ const abide =
17
+ options.gateAbide !== false &&
18
+ !/^(0|false|off|no)$/i.test(String(env.GUARDEX_REVIEW_ABIDE || '').trim());
19
+ if (
20
+ !revision.head ||
21
+ !revision.base ||
22
+ !revision.prUrl ||
23
+ (options.reviewProvider && options.reviewProvider !== 'codex') ||
24
+ isOn(env.GUARDEX_REVIEW_INHERIT_CODEX_CONFIG) ||
25
+ isOn(env.GUARDEX_REVIEW_PR_LENS) ||
26
+ (abide && fs.existsSync(path.join(repoRoot, '.abide/rubric.json')))
27
+ )
28
+ return null;
29
+
30
+ const result = execute('git', ['rev-parse', '--git-common-dir'], { cwd: repoRoot });
31
+ const gitDir = String(result.stdout || '').trim();
32
+ if (result.status !== 0 || !gitDir) return null;
33
+ const file = path.resolve(repoRoot, gitDir, 'guardex', 'review-receipts', hash(revision.prUrl));
34
+ // Invalidate on policy implementation changes even in unreleased source CLI
35
+ // checkouts where package.json's version has not changed.
36
+ let implementation;
37
+ try {
38
+ implementation = [
39
+ __filename,
40
+ require.resolve('./review-gate'),
41
+ require.resolve('../pr-review'),
42
+ require.resolve('../provider-binary'),
43
+ require.resolve('../review-diff'),
44
+ require.resolve('../review-diff-context')
45
+ ].map((source) => hash(fs.readFileSync(source)));
46
+ } catch {
47
+ return null;
48
+ }
49
+ const reviewEnv = Object.entries(env)
50
+ .filter(([name]) => name.startsWith('GUARDEX_REVIEW_'))
51
+ .sort(([a], [b]) => a.localeCompare(b));
52
+ const fingerprint = hash(
53
+ JSON.stringify([
54
+ revision,
55
+ options.reviewProvider || 'auto',
56
+ options.reviewModel || '',
57
+ abide,
58
+ env.GH_HOST || '',
59
+ implementation,
60
+ reviewEnv
61
+ ])
62
+ );
63
+
64
+ return {
65
+ read() {
66
+ try {
67
+ const receipt = JSON.parse(fs.readFileSync(file, 'utf8'));
68
+ const age = Date.now() - receipt.at;
69
+ if (
70
+ receipt.fingerprint !== fingerprint ||
71
+ !Number.isFinite(age) ||
72
+ age < 0 ||
73
+ age > MAX_AGE_MS ||
74
+ !Number.isSafeInteger(receipt.id) ||
75
+ receipt.id <= 0 ||
76
+ !Number.isSafeInteger(receipt.count) ||
77
+ receipt.count < 0
78
+ )
79
+ return null;
80
+ const endpoint = repoApiPath(
81
+ repoRoot,
82
+ `pulls/${revision.prNumber}/reviews?per_page=100`,
83
+ execute
84
+ );
85
+ if (endpoint.includes(':owner')) return null;
86
+ // A later PR review can supersede a receipt without changing HEAD.
87
+ // Ask for the last review on each chronological GitHub page.
88
+ const check = execute(
89
+ GH_BIN,
90
+ ['api', '--paginate', endpoint, '-q', '.[-1] | {id,state,commit_id,body}'],
91
+ { cwd: repoRoot, timeout: 15_000 }
92
+ );
93
+ if (check.status !== 0) return null;
94
+ const posted = JSON.parse(
95
+ String(check.stdout || '')
96
+ .trim()
97
+ .split('\n')
98
+ .at(-1)
99
+ );
100
+ if (
101
+ posted.id !== receipt.id ||
102
+ posted.state !== 'COMMENTED' ||
103
+ posted.commit_id !== revision.head ||
104
+ typeof posted.body !== 'string' ||
105
+ hash(posted.body) !== receipt.body
106
+ )
107
+ return null;
108
+ return { id: receipt.id, count: receipt.count };
109
+ } catch {
110
+ return null;
111
+ }
112
+ },
113
+ write(review) {
114
+ if (
115
+ review.provider !== 'codex' ||
116
+ review.degraded ||
117
+ review.truncated ||
118
+ !Number.isSafeInteger(review.reviewId) ||
119
+ review.reviewId <= 0 ||
120
+ !/^[0-9a-f]{64}$/.test(review.reviewBodyHash || '') ||
121
+ review.reviewedHeadSha !== revision.head
122
+ )
123
+ return;
124
+ let temp;
125
+ try {
126
+ const directory = path.dirname(file);
127
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
128
+ temp = fs.mkdtempSync(path.join(directory, '.pending-'));
129
+ const receipt = path.join(temp, 'receipt');
130
+ fs.writeFileSync(
131
+ receipt,
132
+ JSON.stringify({
133
+ fingerprint,
134
+ at: Date.now(),
135
+ id: review.reviewId,
136
+ body: review.reviewBodyHash,
137
+ count: review.findings.length
138
+ }),
139
+ { mode: 0o600 }
140
+ );
141
+ fs.renameSync(receipt, file);
142
+ } catch {
143
+ // An unavailable receipt never prevents the normal gate from running.
144
+ } finally {
145
+ if (temp)
146
+ try {
147
+ fs.rmSync(temp, { recursive: true, force: true });
148
+ } catch {
149
+ /* best effort */
150
+ }
151
+ }
152
+ }
153
+ };
154
+ }
155
+
156
+ module.exports = { reviewReceipt };
@@ -0,0 +1,29 @@
1
+ """Run one command under a GitGuardex advisory lock, without stealing stale locks."""
2
+ import fcntl
3
+ import os
4
+ import stat
5
+ import subprocess
6
+ import sys
7
+ import time
8
+
9
+ args = sys.argv[1:]
10
+ nonblocking = args[0] == "--try-lock"
11
+ if nonblocking:
12
+ args = args[1:]
13
+ lock_path, *command = args
14
+ fd = os.open(lock_path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
15
+ try:
16
+ if not stat.S_ISREG(os.fstat(fd).st_mode) or os.fstat(fd).st_nlink != 1:
17
+ raise RuntimeError("unsafe advisory lock file")
18
+ deadline = time.monotonic() + (0 if nonblocking else 20)
19
+ while True:
20
+ try:
21
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
22
+ break
23
+ except BlockingIOError:
24
+ if time.monotonic() >= deadline:
25
+ raise SystemExit(75)
26
+ time.sleep(0.1)
27
+ raise SystemExit(subprocess.run(command, pass_fds=(fd,)).returncode)
28
+ finally:
29
+ os.close(fd)
package/src/git/index.js CHANGED
@@ -381,25 +381,25 @@ function listLocalAgentBranches(repoRoot) {
381
381
  * @returns {Map<string, string>} Branch -> absolute worktree path; empty on failure.
382
382
  */
383
383
  function mapWorktreePathsByBranch(repoRoot) {
384
- const result = gitRun(repoRoot, ['worktree', 'list', '--porcelain'], { allowFailure: true });
384
+ const result = gitRun(repoRoot, ['worktree', 'list', '--porcelain', '-z'], { allowFailure: true });
385
385
  const map = new Map();
386
386
  if (result.status !== 0) {
387
387
  return map;
388
388
  }
389
389
 
390
- const lines = String(result.stdout || '').split('\n');
391
- let currentWorktree = '';
392
- for (const line of lines) {
393
- if (line.startsWith('worktree ')) {
394
- currentWorktree = line.slice('worktree '.length).trim();
395
- continue;
396
- }
397
- if (line.startsWith('branch refs/heads/')) {
398
- const branchName = line.slice('branch refs/heads/'.length).trim();
399
- if (currentWorktree && branchName) {
400
- map.set(branchName, currentWorktree);
390
+ for (const record of String(result.stdout || '').split('\0\0').filter(Boolean)) {
391
+ let worktreePath = '';
392
+ let branchName = '';
393
+ for (const field of record.split('\0')) {
394
+ if (field.startsWith('worktree ')) {
395
+ worktreePath = field.slice('worktree '.length);
396
+ } else if (field.startsWith('branch refs/heads/')) {
397
+ branchName = field.slice('branch refs/heads/'.length);
401
398
  }
402
399
  }
400
+ if (worktreePath && branchName) {
401
+ map.set(branchName, worktreePath);
402
+ }
403
403
  }
404
404
  return map;
405
405
  }
@@ -930,42 +930,29 @@ function lockRegistryStatus(repoRoot) {
930
930
  * @throws {Error} When `git worktree list` cannot run.
931
931
  */
932
932
  function listAgentWorktrees(repoRoot) {
933
- const result = gitRun(repoRoot, ['worktree', 'list', '--porcelain'], { allowFailure: true });
933
+ const result = gitRun(repoRoot, ['worktree', 'list', '--porcelain', '-z'], { allowFailure: true });
934
934
  if (result.status !== 0) {
935
935
  throw new Error('Unable to list git worktrees for finish command');
936
936
  }
937
937
 
938
938
  const entries = [];
939
- let currentPath = '';
940
- let currentBranchRef = '';
941
- const lines = String(result.stdout || '').split('\n');
942
- for (const line of lines) {
943
- if (!line.trim()) {
944
- if (currentPath && currentBranchRef.startsWith('refs/heads/agent/')) {
945
- entries.push({
946
- worktreePath: currentPath,
947
- branch: currentBranchRef.replace(/^refs\/heads\//, ''),
948
- });
939
+ for (const record of String(result.stdout || '').split('\0\0').filter(Boolean)) {
940
+ let currentPath = '';
941
+ let currentBranchRef = '';
942
+ for (const field of record.split('\0')) {
943
+ if (field.startsWith('worktree ')) {
944
+ currentPath = field.slice('worktree '.length);
945
+ } else if (field.startsWith('branch ')) {
946
+ currentBranchRef = field.slice('branch '.length);
949
947
  }
950
- currentPath = '';
951
- currentBranchRef = '';
952
- continue;
953
- }
954
- if (line.startsWith('worktree ')) {
955
- currentPath = line.slice('worktree '.length).trim();
956
- continue;
957
948
  }
958
- if (line.startsWith('branch ')) {
959
- currentBranchRef = line.slice('branch '.length).trim();
960
- continue;
949
+ if (currentPath && currentBranchRef.startsWith('refs/heads/agent/')) {
950
+ entries.push({
951
+ worktreePath: currentPath,
952
+ branch: currentBranchRef.replace(/^refs\/heads\//, ''),
953
+ });
961
954
  }
962
955
  }
963
- if (currentPath && currentBranchRef.startsWith('refs/heads/agent/')) {
964
- entries.push({
965
- worktreePath: currentPath,
966
- branch: currentBranchRef.replace(/^refs\/heads\//, ''),
967
- });
968
- }
969
956
 
970
957
  return entries;
971
958
  }
@@ -1021,7 +1008,7 @@ function worktreeHasLocalChanges(worktreePath) {
1021
1008
  '--quiet',
1022
1009
  '--',
1023
1010
  '.',
1024
- ':(exclude).omx/state/agent-file-locks.json',
1011
+ `:(exclude)${LOCK_FILE_RELATIVE}`,
1025
1012
  ]);
1026
1013
  if (hasUnstaged) {
1027
1014
  return true;
@@ -1033,7 +1020,7 @@ function worktreeHasLocalChanges(worktreePath) {
1033
1020
  '--quiet',
1034
1021
  '--',
1035
1022
  '.',
1036
- ':(exclude).omx/state/agent-file-locks.json',
1023
+ `:(exclude)${LOCK_FILE_RELATIVE}`,
1037
1024
  ]);
1038
1025
  if (hasStaged) {
1039
1026
  return true;
@@ -1086,11 +1073,142 @@ function branchExists(repoRoot, branch) {
1086
1073
  return result.status === 0;
1087
1074
  }
1088
1075
 
1076
+ /**
1077
+ * Infer the PR base branch from git history when no explicit base is recorded.
1078
+ *
1079
+ * Tries two strategies in order:
1080
+ * 1. Reflog hint — scans the source branch's reflog for the oldest
1081
+ * "branch: Created from <name>" entry; when <name> is an existing local
1082
+ * branch (not HEAD, not a SHA, not sourceBranch itself) it is returned
1083
+ * immediately.
1084
+ * 2. Ancestry — builds a candidate set from configuredBase,
1085
+ * protectedBranches, defaultBase, and every local non-agent branch;
1086
+ * computes `git rev-list --count <merge-base>..<source>` for each;
1087
+ * the candidate with the smallest count wins. Ties are broken by
1088
+ * configuredBase preference, then protectedBranches order, then
1089
+ * lexical; a one-line WARNING is printed on stderr when a tie occurs.
1090
+ *
1091
+ * Returns null when no candidate shares history with sourceBranch (the
1092
+ * branch may not exist yet, or is an unrelated orphan).
1093
+ *
1094
+ * @param {string} repoRoot Repo to inspect.
1095
+ * @param {string} sourceBranch Agent branch whose base to infer.
1096
+ * @param {{configuredBase?: string, protectedBranches?: string[], defaultBase?: string}} opts
1097
+ * @returns {string|null} Inferred base branch name, or null.
1098
+ */
1099
+ function inferBaseBranchFromHistory(repoRoot, sourceBranch, {
1100
+ configuredBase = '',
1101
+ protectedBranches = [],
1102
+ defaultBase = '',
1103
+ } = {}) {
1104
+ // 1. Reflog hint: oldest "Created from <name>" entry.
1105
+ const reflogResult = gitRun(repoRoot, ['reflog', 'show', '--no-abbrev', sourceBranch], { allowFailure: true });
1106
+ if (reflogResult.status === 0) {
1107
+ let reflogBase = '';
1108
+ for (const line of String(reflogResult.stdout || '').split('\n')) {
1109
+ const m = line.match(/: branch: Created from (.+)$/);
1110
+ if (m) {
1111
+ reflogBase = m[1].trim();
1112
+ }
1113
+ }
1114
+ if (
1115
+ reflogBase &&
1116
+ reflogBase !== 'HEAD' &&
1117
+ reflogBase !== sourceBranch &&
1118
+ !/^[0-9a-f]{40}$/i.test(reflogBase) &&
1119
+ branchExists(repoRoot, reflogBase)
1120
+ ) {
1121
+ return reflogBase;
1122
+ }
1123
+ }
1124
+
1125
+ // 2. Ancestry search: build ordered, deduped candidate set.
1126
+ const seen = new Set();
1127
+ /** @type {Array<{name: string, ref: string}>} */
1128
+ const candidates = [];
1129
+
1130
+ /** @param {string} name */
1131
+ function addCandidate(name) {
1132
+ if (!name || seen.has(name)) return;
1133
+ seen.add(name);
1134
+ const hasRemote = gitRefExists(repoRoot, `refs/remotes/origin/${name}`);
1135
+ if (branchExists(repoRoot, name) || hasRemote) {
1136
+ candidates.push({ name, ref: hasRemote ? `origin/${name}` : name });
1137
+ }
1138
+ }
1139
+
1140
+ if (configuredBase) addCandidate(configuredBase);
1141
+ for (const pb of protectedBranches) addCandidate(pb);
1142
+ if (defaultBase) addCandidate(defaultBase);
1143
+
1144
+ // All local non-agent branches.
1145
+ const allBranches = gitRun(repoRoot, ['for-each-ref', '--format=%(refname:short)', 'refs/heads'], { allowFailure: true });
1146
+ if (allBranches.status === 0) {
1147
+ for (const b of String(allBranches.stdout || '').split('\n').map((s) => s.trim()).filter(Boolean)) {
1148
+ if (b !== sourceBranch && !b.startsWith('agent/')) {
1149
+ addCandidate(b);
1150
+ }
1151
+ }
1152
+ }
1153
+
1154
+ if (candidates.length === 0) return null;
1155
+
1156
+ let bestCount = Infinity;
1157
+ /** @type {string[]} */
1158
+ let bestCandidates = [];
1159
+
1160
+ for (const { name: candidate, ref } of candidates) {
1161
+ const mbResult = gitRun(repoRoot, ['merge-base', sourceBranch, ref], { allowFailure: true });
1162
+ if (mbResult.status !== 0) continue;
1163
+ const mb = String(mbResult.stdout || '').trim();
1164
+ if (!mb) continue;
1165
+ const countResult = gitRun(repoRoot, ['rev-list', '--count', `${mb}..${sourceBranch}`], { allowFailure: true });
1166
+ if (countResult.status !== 0) continue;
1167
+ const count = parseInt(String(countResult.stdout || '').trim(), 10);
1168
+ if (Number.isNaN(count)) continue;
1169
+
1170
+ if (count < bestCount) {
1171
+ bestCount = count;
1172
+ bestCandidates = [candidate];
1173
+ } else if (count === bestCount) {
1174
+ bestCandidates.push(candidate);
1175
+ }
1176
+ }
1177
+
1178
+ if (bestCandidates.length === 0) return null;
1179
+
1180
+ if (bestCandidates.length > 1) {
1181
+ // Tie-break: configuredBase > protectedBranches order > lexical.
1182
+ let winner = '';
1183
+ if (configuredBase && bestCandidates.includes(configuredBase)) {
1184
+ winner = configuredBase;
1185
+ } else {
1186
+ for (const pb of protectedBranches) {
1187
+ if (bestCandidates.includes(pb)) {
1188
+ winner = pb;
1189
+ break;
1190
+ }
1191
+ }
1192
+ }
1193
+ if (!winner) {
1194
+ winner = [...bestCandidates].sort()[0];
1195
+ }
1196
+ process.stderr.write(
1197
+ `[gx] WARNING: tie between base candidates [${bestCandidates.join(', ')}]; picked '${winner}'\n`,
1198
+ );
1199
+ return winner;
1200
+ }
1201
+
1202
+ return bestCandidates[0];
1203
+ }
1204
+
1089
1205
  /**
1090
1206
  * Resolve the base branch for the finish flow: CLI override wins and repairs
1091
1207
  * the branch metadata before any gate can restart the finish; otherwise the
1092
1208
  * per-branch `branch.<source>.guardexBase` recorded at branch-start; otherwise
1093
- * the repo-wide configured base; otherwise the repo's detected default branch.
1209
+ * inferred from git history (persisted as branch.<source>.guardexBase so every
1210
+ * later step agrees); otherwise the repo-wide configured base; otherwise the
1211
+ * repo's detected default branch.
1094
1212
  *
1095
1213
  * @param {string} repoRoot Repo to inspect.
1096
1214
  * @param {string} sourceBranch Source agent branch (used for per-branch base).
@@ -1112,6 +1230,24 @@ function resolveFinishBaseBranch(repoRoot, sourceBranch, explicitBase) {
1112
1230
  if (perBranch) {
1113
1231
  return perBranch;
1114
1232
  }
1233
+
1234
+ // No recorded base: infer from git history before trusting the repo-wide config.
1235
+ const configuredBase = readGitConfig(repoRoot, GIT_BASE_BRANCH_KEY);
1236
+ const protectedBranches = readConfiguredProtectedBranches(repoRoot) || [...DEFAULT_PROTECTED_BRANCHES];
1237
+ const defaultBase = detectDefaultBaseBranch(repoRoot);
1238
+ const inferred = inferBaseBranchFromHistory(repoRoot, sourceBranch, {
1239
+ configuredBase,
1240
+ protectedBranches,
1241
+ defaultBase,
1242
+ });
1243
+ if (inferred) {
1244
+ gitRun(repoRoot, ['config', `branch.${sourceBranch}.guardexBase`, inferred]);
1245
+ process.stderr.write(
1246
+ `[gx] base for '${sourceBranch}' not recorded; inferred '${inferred}' from git history` +
1247
+ ` (set branch.${sourceBranch}.guardexBase to override)\n`,
1248
+ );
1249
+ return inferred;
1250
+ }
1115
1251
  }
1116
1252
 
1117
1253
  const configured = readGitConfig(repoRoot, GIT_BASE_BRANCH_KEY);
@@ -1231,6 +1367,7 @@ module.exports = {
1231
1367
  worktreeHasLocalChanges,
1232
1368
  gitOutputLines,
1233
1369
  branchExists,
1370
+ inferBaseBranchFromHistory,
1234
1371
  resolveFinishBaseBranch,
1235
1372
  branchMergedIntoBase,
1236
1373
  syncOperation,
@@ -1,5 +1,50 @@
1
1
  const path = require('node:path');
2
2
 
3
+ const HELP_FLAGS = new Set(['--help', '-h', 'help']);
4
+
5
+ /**
6
+ * `gx hook` used to answer every wrong invocation with one line —
7
+ * `Usage: gx hook <run|install> ...` — and `gx hook run --help` was worse: it
8
+ * read `--help` as a hook name and died with "Unknown hook name: --help". The
9
+ * hooks are the part of this tool that runs unattended on somebody else's
10
+ * machine, so "what does it actually do, and how do I turn it off" has to be
11
+ * answerable from the CLI.
12
+ */
13
+ function hookUsage(SHORT_TOOL_NAME, HOOK_NAMES) {
14
+ return [
15
+ `Usage: ${SHORT_TOOL_NAME} hook <run|install> [options]`,
16
+ '',
17
+ 'Subcommands',
18
+ ` run <name> [--target <repo>] [args...] Execute one managed hook now.`,
19
+ ` install [--target <repo>] Point the repo's core.hooksPath at the managed hooks.`,
20
+ '',
21
+ `Hook names: ${HOOK_NAMES.join(', ')}`,
22
+ '',
23
+ 'What each hook does',
24
+ ' pre-commit Branch-protection check: refuses a commit on a protected base.',
25
+ ' pre-push Branch-protection check, then the repo\'s own verification',
26
+ ' (its scripts/agent-preflight.sh, if present).',
27
+ ' post-merge Housekeeping sweep on the base branch: prunes worktrees and',
28
+ ' branches whose PRs have landed. Asks the forge, so it is the',
29
+ ' slow one — see the env switches below.',
30
+ ' post-checkout Cheap bookkeeping after a checkout.',
31
+ '',
32
+ 'Environment',
33
+ ' GUARDEX_DISABLE_POST_MERGE_CLEANUP=1 Skip the post-merge sweep entirely.',
34
+ ' GUARDEX_SKIP_AUTO_FINISH_READY_BRANCHES=1',
35
+ ' Skip the merged-PR branch sweep.',
36
+ ' GUARDEX_SKIP_AUTO_WORKTREE_PRUNE=1 Skip the stale-worktree prune.',
37
+ ' GUARDEX_OPEN_PR_LOOKUP_LIMIT=<n> How many open PRs one batched lookup',
38
+ ' may cover (default 200). Above it the',
39
+ ' prune falls back to a per-branch probe.',
40
+ ' GUARDEX_BASE_BRANCH=<name> Override the detected base branch.',
41
+ '',
42
+ 'Per-repo opt-outs (git config)',
43
+ ' git config --local hooks.actPrePush false Skip the pre-push verification.',
44
+ ' git push --no-verify Skip it for one push.',
45
+ ].join('\n');
46
+ }
47
+
3
48
  function hook(rawArgs, deps) {
4
49
  const {
5
50
  extractTargetedArgs,
@@ -14,10 +59,23 @@ function hook(rawArgs, deps) {
14
59
  } = deps;
15
60
 
16
61
  const [subcommand, ...rest] = rawArgs;
62
+ if (subcommand === undefined || HELP_FLAGS.has(subcommand)) {
63
+ console.log(hookUsage(SHORT_TOOL_NAME, HOOK_NAMES));
64
+ process.exitCode = 0;
65
+ return;
66
+ }
17
67
  if (subcommand === 'run') {
18
68
  const [hookName, ...hookArgs] = rest;
69
+ if (hookName === undefined || HELP_FLAGS.has(hookName)) {
70
+ console.log(hookUsage(SHORT_TOOL_NAME, HOOK_NAMES));
71
+ process.exitCode = 0;
72
+ return;
73
+ }
19
74
  if (!HOOK_NAMES.includes(hookName)) {
20
- throw new Error(`Unknown hook name: ${hookName || '(missing)'}`);
75
+ throw new Error(
76
+ `Unknown hook name: ${hookName}. Known hooks: ${HOOK_NAMES.join(', ')}. ` +
77
+ `Run \`${SHORT_TOOL_NAME} hook --help\` for what each one does.`,
78
+ );
21
79
  }
22
80
  const { target, passthrough } = extractTargetedArgs(hookArgs);
23
81
  const hookAssetPath = path.join(TEMPLATE_ROOT, 'githooks', hookName);
@@ -28,10 +86,15 @@ function hook(rawArgs, deps) {
28
86
  });
29
87
  if (result.stdout) process.stdout.write(result.stdout);
30
88
  if (result.stderr) process.stderr.write(result.stderr);
31
- process.exitCode = result.status;
89
+ process.exitCode = result.status ?? (result.signal ? 1 : 0);
32
90
  return;
33
91
  }
34
92
  if (subcommand === 'install') {
93
+ if (rest.some((arg) => HELP_FLAGS.has(arg))) {
94
+ console.log(hookUsage(SHORT_TOOL_NAME, HOOK_NAMES));
95
+ process.exitCode = 0;
96
+ return;
97
+ }
35
98
  const { target, passthrough } = extractTargetedArgs(rest);
36
99
  if (passthrough.length > 0) {
37
100
  throw new Error(`Unknown hook install option: ${passthrough[0]}`);
@@ -43,7 +106,9 @@ function hook(rawArgs, deps) {
43
106
  process.exitCode = 0;
44
107
  return;
45
108
  }
46
- throw new Error(`Usage: ${SHORT_TOOL_NAME} hook <run|install> ...`);
109
+ throw new Error(
110
+ `Unknown hook subcommand: ${subcommand}\n\n${hookUsage(SHORT_TOOL_NAME, HOOK_NAMES)}`,
111
+ );
47
112
  }
48
113
 
49
114
  function internal(rawArgs, deps) {
@@ -17,6 +17,7 @@ const path = require('node:path');
17
17
  const { findProjects } = require('../cockpit/projects-finder');
18
18
  const { findOpenPrForBranch, listOpenPrsForRepo } = require('../pr');
19
19
  const sharedGitState = require('../shared-git-state');
20
+ const abide = require('../abide');
20
21
 
21
22
  const PROTECTED_BRANCHES = new Set(['main', 'master', 'dev']);
22
23
  const LOCK_FILE_RELATIVE = path.join('.omx', 'state', 'agent-file-locks.json');
@@ -522,7 +523,20 @@ function myContext({ cwd = process.cwd(), includePr = true } = {}) {
522
523
  sharedGitState: shared.enabled ? { enabled: true, remote: shared.remote } : { enabled: false },
523
524
  pr: includePr && branch ? safePr(mainRoot, branch) : null,
524
525
  lastCommit: lc,
525
- ageDays: lc ? daysSince(lc.date, Date.now()) : null
526
+ ageDays: lc ? daysSince(lc.date, Date.now()) : null,
527
+ // The repo's own AGENTS.md rules: are they enforced here, and what fired lately.
528
+ abide: compactAbide(abide.abideSummary(here))
529
+ };
530
+ }
531
+
532
+ function compactAbide(summary) {
533
+ return {
534
+ hooks: summary.hooks,
535
+ rubric: summary.rubric.status,
536
+ rules: summary.rubric.rules,
537
+ key: Boolean(summary.key),
538
+ violations7d: summary.last7d.violations,
539
+ recent: summary.violations.map((v) => `${v.ruleId} (${v.band}) ${v.files.join(', ')}`)
526
540
  };
527
541
  }
528
542
 
@@ -547,18 +561,60 @@ function compactOwnership(result) {
547
561
  }
548
562
 
549
563
  /** One compact, repo-scoped snapshot for an agent about to edit files. */
550
- function editContext({ cwd = process.cwd(), files = [], includePrs = false } = {}) {
564
+ function editContext({ cwd = process.cwd(), files = [], includePrs = false, maxBytes } = {}) {
565
+ if (maxBytes !== undefined && (!Array.isArray(files) || files.length > 200 || files.some((file) => typeof file !== 'string' || !file.trim()))) {
566
+ throw new Error('Bounded context requires at most 200 file paths; split the file batch');
567
+ }
551
568
  const context = myContext({ cwd, includePr: includePrs });
552
- if (context.error) return context;
569
+ if (context.error) return maxBytes === undefined ? context : boundContext(context, maxBytes);
553
570
  const otherAgents = collectRepoAgents(context.repoPath, { includePrs })
554
571
  .filter((agent) => agent.branch !== context.branch)
555
572
  .map(radarRecord);
556
573
  const ownership = whoOwnsMany(files, { repoPath: context.repoPath })
557
- .map(compactOwnership);
558
- return { ...context, otherAgents, ownership };
574
+ .map((result) => ({ ...compactOwnership(result), ...(maxBytes !== undefined && result.error ? { error: result.error } : {}) }));
575
+ const result = { ...context, otherAgents, ownership };
576
+ return maxBytes === undefined ? result : boundContext(result, maxBytes);
577
+ }
578
+
579
+ // Budget the JSON tool text, not the JSON-RPC envelope. Safety data is never
580
+ // truncated: only optional peer summaries may be omitted.
581
+ function boundContext(context, maxBytes) {
582
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 1048576) {
583
+ throw new Error('max_bytes must be an integer between 1 and 1048576');
584
+ }
585
+ const { otherAgents = [], ...required } = context;
586
+ const relevant = new Set((context.ownership || []).flatMap((item) =>
587
+ [item.owner, ...(item.owners || [])].filter(Boolean).map((owner) => owner.branch)));
588
+ const peers = [...otherAgents].sort((a, b) => Number(relevant.has(b.branch)) - Number(relevant.has(a.branch)));
589
+ const result = { ...required, otherAgents: [], complete: peers.length === 0,
590
+ omitted: { otherAgents: peers.length }, details: 'Use repo_state for peers; omit max_bytes for full context.' };
591
+ // Compute the base serialization size once; then track deltas per peer so
592
+ // we avoid an O(N^2) re-serialization of the growing otherAgents array.
593
+ let runningBytes = Buffer.byteLength(JSON.stringify(result), 'utf8');
594
+ if (runningBytes > maxBytes) throw new Error('budget-too-small: mandatory context exceeds max_bytes; raise budget or split the file batch');
595
+ for (const peer of peers) {
596
+ const peerBytes = Buffer.byteLength(JSON.stringify(peer), 'utf8');
597
+ // `,` separator added between array elements by JSON.stringify (no space).
598
+ const sepBytes = result.otherAgents.length === 0 ? 0 : 1;
599
+ // Digit-length change when omitted count decrements (e.g. 10→9 = -1 byte).
600
+ const curOmit = result.omitted.otherAgents;
601
+ const omitDelta = String(curOmit - 1).length - String(curOmit).length;
602
+ // "complete" flips false(5)→true(4) = -1 byte only when this is the last peer.
603
+ const completeDelta = curOmit === 1 ? -1 : 0;
604
+ if (runningBytes + peerBytes + sepBytes + omitDelta + completeDelta > maxBytes) {
605
+ continue;
606
+ }
607
+ result.otherAgents.push(peer);
608
+ result.omitted.otherAgents--;
609
+ result.complete = result.omitted.otherAgents === 0;
610
+ runningBytes += peerBytes + sepBytes + omitDelta + completeDelta;
611
+ }
612
+ result.complete = result.omitted.otherAgents === 0;
613
+ return result;
559
614
  }
560
615
 
561
616
  module.exports = {
617
+ boundContext,
562
618
  collectAllAgents,
563
619
  collectRepoAgents,
564
620
  repoState,