@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
package/src/abide.js ADDED
@@ -0,0 +1,534 @@
1
+ // Shared abide runtime for gx (github.com/coldteadotai/abide).
2
+ //
3
+ // Abide compiles a repo's AGENTS.md / CLAUDE.md into `.abide/rubric.json` and
4
+ // judges edits against those rules with TypeSafe's Jev model. gx wires it in
5
+ // three places: the Claude Code / Codex hooks (`gx claude install`), the repo
6
+ // status surfaces (`gx status`, MCP `my_context`), and the PR review gate
7
+ // (`gx pr-review`, `gx branch finish --gate-review`). Everything they share
8
+ // about abide — where it is, whether it has a key, whether the rubric is
9
+ // fresh, how to run a check — lives here.
10
+
11
+ const cp = require('child_process');
12
+ const crypto = require('crypto');
13
+ const fs = require('fs');
14
+ const os = require('os');
15
+ const path = require('path');
16
+
17
+ const ABIDE_PACKAGE = '@coldtea/abide';
18
+ // Pinned: the npx fallback must not execute whatever the registry calls
19
+ // latest, and a new version lands in a new npx cache dir.
20
+ const ABIDE_VERSION = '0.0.5';
21
+ // abide's own installer writes `node "<abs>/dist/abide-hook.js" <event>`; the
22
+ // gx shim is `.claude/hooks/abide_hook.js`. Both markers identify abide entries.
23
+ const ABIDE_UPSTREAM_HOOK_MARKER = 'abide-hook.js';
24
+ const ABIDE_SHIM_REL = '.claude/hooks/abide_hook.js';
25
+ const ABIDE_SHIM_MARKER = 'abide_hook.js';
26
+ const ABIDE_HOOK_EVENTS = ['SessionStart', 'UserPromptSubmit', 'PostToolUse', 'Stop'];
27
+ // Where abide itself looks for a key, in order: process env, .env.local and
28
+ // .env at the repo root, then ~/.abide/.env.
29
+ const ABIDE_KEY_NAMES = ['TYPESAFE_AI_API_KEY', 'AI_GATEWAY_API_KEY'];
30
+ const ABIDE_DIR_REL = '.abide';
31
+ const ABIDE_RUBRIC_REL = '.abide/rubric.json';
32
+ const ABIDE_EVENTS_REL = '.abide/events.jsonl';
33
+ const ABIDE_INIT_TIMEOUT_MS = 120_000;
34
+ const ABIDE_CHECK_TIMEOUT_MS = 180_000;
35
+
36
+ // The hook entries gx writes. `${CLAUDE_PROJECT_DIR:-...}` is the same
37
+ // resolution every other managed hook uses, so the entry is identical on
38
+ // every machine and safe to commit. Timeouts mirror abide's own.
39
+ const SHIM_COMMAND_PREFIX =
40
+ 'node "${CLAUDE_PROJECT_DIR:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}/' +
41
+ ABIDE_SHIM_REL +
42
+ '"';
43
+ const ABIDE_HOOK_SPECS = [
44
+ { event: 'SessionStart', arg: 'session-start', timeout: 10 },
45
+ { event: 'UserPromptSubmit', arg: 'turn-start', timeout: 10 },
46
+ {
47
+ event: 'PostToolUse',
48
+ arg: 'post-tool-use',
49
+ timeout: 20,
50
+ matcher: 'Edit|Write|MultiEdit|apply_patch'
51
+ },
52
+ { event: 'Stop', arg: 'stop', timeout: 30 }
53
+ ];
54
+
55
+ function abideSettingsTemplate() {
56
+ const hooks = {};
57
+ for (const spec of ABIDE_HOOK_SPECS) {
58
+ hooks[spec.event] = [
59
+ {
60
+ ...(spec.matcher ? { matcher: spec.matcher } : {}),
61
+ hooks: [
62
+ { type: 'command', command: `${SHIM_COMMAND_PREFIX} ${spec.arg}`, timeout: spec.timeout }
63
+ ]
64
+ }
65
+ ];
66
+ }
67
+ return { hooks };
68
+ }
69
+
70
+ function isAbideHookCommand(cmd) {
71
+ const text = String(cmd || '');
72
+ return text.includes(ABIDE_UPSTREAM_HOOK_MARKER) || text.includes(ABIDE_SHIM_MARKER);
73
+ }
74
+
75
+ function isShimCommand(cmd) {
76
+ return String(cmd || '').includes(ABIDE_SHIM_MARKER);
77
+ }
78
+
79
+ // Every abide hook entry in a settings object, keyed by event. All matches are
80
+ // kept, so a dead entry beside a live one is still seen.
81
+ function abideHookEntries(settings) {
82
+ const out = {};
83
+ const hooks = (settings && settings.hooks) || {};
84
+ for (const eventName of ABIDE_HOOK_EVENTS) {
85
+ for (const group of hooks[eventName] || []) {
86
+ for (const hook of group.hooks || []) {
87
+ const cmd = hook.command || '';
88
+ if (!isAbideHookCommand(cmd)) continue;
89
+ const match = cmd.match(/"([^"]*abide-hook\.js)"/);
90
+ (out[eventName] ||= []).push({
91
+ command: cmd,
92
+ shim: isShimCommand(cmd),
93
+ script: match ? match[1] : null
94
+ });
95
+ }
96
+ }
97
+ }
98
+ return out;
99
+ }
100
+
101
+ function readJsonIfExists(filePath) {
102
+ if (!fs.existsSync(filePath)) return null;
103
+ const raw = fs.readFileSync(filePath, 'utf8');
104
+ if (!raw.trim()) return null;
105
+ return JSON.parse(raw);
106
+ }
107
+
108
+ function readEnvFileKeys(filePath) {
109
+ let raw;
110
+ try {
111
+ raw = fs.readFileSync(filePath, 'utf8');
112
+ } catch (_error) {
113
+ return new Set();
114
+ }
115
+ const found = new Set();
116
+ for (const line of raw.split(/\r?\n/)) {
117
+ const match = line.match(/^\s*(?:export\s+)?([A-Z0-9_]+)\s*=\s*(.*)$/);
118
+ if (!match) continue;
119
+ // KEY="" and KEY='' are as empty as KEY=.
120
+ const value = match[2]
121
+ .trim()
122
+ .replace(/^(["'])(.*)\1$/, '$2')
123
+ .trim();
124
+ if (!value) continue;
125
+ if (ABIDE_KEY_NAMES.includes(match[1])) found.add(match[1]);
126
+ }
127
+ return found;
128
+ }
129
+
130
+ // Mirrors abide's own credential lookup so callers can say up front whether
131
+ // a check will have a key to call Jev with.
132
+ function abideKeySource(repoRoot, env = process.env) {
133
+ if (ABIDE_KEY_NAMES.some((name) => (env[name] || '').trim() !== '')) return 'environment';
134
+ const places = [
135
+ ['.env.local', path.join(repoRoot, '.env.local')],
136
+ ['.env', path.join(repoRoot, '.env')],
137
+ ['~/.abide/.env', path.join(os.homedir(), '.abide', '.env')]
138
+ ];
139
+ for (const [label, filePath] of places) {
140
+ if (readEnvFileKeys(filePath).size > 0) return label;
141
+ }
142
+ return null;
143
+ }
144
+
145
+ function commandOnPath(bin) {
146
+ const probe = process.platform === 'win32' ? 'where' : 'which';
147
+ return cp.spawnSync(probe, [bin], { stdio: 'ignore' }).status === 0;
148
+ }
149
+
150
+ // `abide` on PATH wins (a global install keeps the package at a stable path).
151
+ // Otherwise npx fetches the pinned package, which is how abide's own README
152
+ // installs it. GUARDEX_ABIDE_BIN points at a specific executable instead.
153
+ function resolveAbideCommand(env = process.env) {
154
+ const override = (env.GUARDEX_ABIDE_BIN || '').trim();
155
+ if (override) return { command: override, args: [], via: 'GUARDEX_ABIDE_BIN' };
156
+ if (commandOnPath('abide')) return { command: 'abide', args: [], via: 'PATH' };
157
+ if (commandOnPath('npx')) {
158
+ return { command: 'npx', args: ['--yes', `${ABIDE_PACKAGE}@${ABIDE_VERSION}`], via: 'npx' };
159
+ }
160
+ return null;
161
+ }
162
+
163
+ // Runs `abide <args>` in the repo. Never throws; the caller reads status.
164
+ function runAbide(
165
+ repoRoot,
166
+ args,
167
+ { timeoutMs = ABIDE_INIT_TIMEOUT_MS, stdio = 'pipe', env = process.env } = {}
168
+ ) {
169
+ const abide = resolveAbideCommand(env);
170
+ if (!abide) return { status: 'unavailable', label: null };
171
+ const label = [abide.command, ...abide.args, ...args].join(' ');
172
+ const result = cp.spawnSync(abide.command, [...abide.args, ...args], {
173
+ cwd: repoRoot,
174
+ encoding: 'utf8',
175
+ timeout: timeoutMs,
176
+ stdio,
177
+ env: { ...env, CI: '1', FORCE_COLOR: '0' },
178
+ // npx / abide are .cmd shims on Windows and only resolve through a shell.
179
+ shell: process.platform === 'win32'
180
+ });
181
+ return {
182
+ status: result.error ? 'failed' : result.status === 0 ? 'ok' : 'failed',
183
+ exitCode: result.status,
184
+ label,
185
+ via: abide.via,
186
+ stdout: result.stdout || '',
187
+ stderr: result.stderr || '',
188
+ error: result.error ? result.error.message : null
189
+ };
190
+ }
191
+
192
+ // abide renders an Ink box; keep the words, drop the frame.
193
+ function summarizeAbideOutput(result, lines = 3) {
194
+ if (result.error) return result.error;
195
+ const text = `${result.stdout || ''}\n${result.stderr || ''}`
196
+ .replace(/[─-╿]/g, ' ')
197
+ .split('\n')
198
+ .map((l) => l.replace(/\s+/g, ' ').trim())
199
+ .filter(Boolean)
200
+ .slice(0, lines)
201
+ .join(' ');
202
+ return text || `exit ${result.exitCode}`;
203
+ }
204
+
205
+ // Where the in-repo shim would find abide on this machine (null when nowhere).
206
+ function resolveShimPackageDir(repoRoot, env = process.env) {
207
+ const shim = path.join(repoRoot, ABIDE_SHIM_REL);
208
+ if (!fs.existsSync(shim)) return null;
209
+ const result = cp.spawnSync(process.execPath, [shim, '--resolve'], {
210
+ encoding: 'utf8',
211
+ env,
212
+ cwd: repoRoot
213
+ });
214
+ if (result.status !== 0) return null;
215
+ return (result.stdout || '').trim() || null;
216
+ }
217
+
218
+ function sha256File(filePath) {
219
+ try {
220
+ return crypto.createHash('sha256').update(fs.readFileSync(filePath)).digest('hex');
221
+ } catch (_error) {
222
+ return null;
223
+ }
224
+ }
225
+
226
+ function resolveSourcePath(repoRoot, sourcePath) {
227
+ if (sourcePath.startsWith('~/')) return path.join(os.homedir(), sourcePath.slice(2));
228
+ return path.resolve(repoRoot, sourcePath);
229
+ }
230
+
231
+ // The rubric abide compiled for this repo, and whether the instruction files
232
+ // it was compiled from still hash the same (abide's own staleness rule).
233
+ function rubricStatus(repoRoot) {
234
+ const rubricPath = path.join(repoRoot, ABIDE_RUBRIC_REL);
235
+ let rubric;
236
+ try {
237
+ rubric = readJsonIfExists(rubricPath);
238
+ } catch (_error) {
239
+ return {
240
+ status: 'invalid',
241
+ path: rubricPath,
242
+ rules: 0,
243
+ modelRules: 0,
244
+ changed: [],
245
+ removed: []
246
+ };
247
+ }
248
+ if (!rubric)
249
+ return {
250
+ status: 'missing',
251
+ path: rubricPath,
252
+ rules: 0,
253
+ modelRules: 0,
254
+ changed: [],
255
+ removed: []
256
+ };
257
+ const rules = Array.isArray(rubric.rules) ? rubric.rules : [];
258
+ const changed = [];
259
+ const removed = [];
260
+ for (const source of Array.isArray(rubric.sources) ? rubric.sources : []) {
261
+ if (!source || typeof source.path !== 'string') continue;
262
+ const now = sha256File(resolveSourcePath(repoRoot, source.path));
263
+ if (now === null) removed.push(source.path);
264
+ else if (typeof source.sha === 'string' && source.sha !== now) changed.push(source.path);
265
+ }
266
+ return {
267
+ status: changed.length > 0 || removed.length > 0 ? 'stale' : 'fresh',
268
+ path: rubricPath,
269
+ rules: rules.length,
270
+ modelRules: rules.filter(
271
+ (r) => r && r.check && r.check.type === 'model' && r.status !== 'disabled'
272
+ ).length,
273
+ changed,
274
+ removed,
275
+ rulesById: new Map(rules.filter((r) => r && typeof r.id === 'string').map((r) => [r.id, r]))
276
+ };
277
+ }
278
+
279
+ // Recent check events from .abide/events.jsonl: what fired, when, on which files.
280
+ function readRecentEvents(
281
+ repoRoot,
282
+ { sinceMs = 7 * 24 * 60 * 60 * 1000, now = Date.now(), limit = 20 } = {}
283
+ ) {
284
+ const eventsPath = path.join(repoRoot, ABIDE_EVENTS_REL);
285
+ let raw;
286
+ try {
287
+ raw = fs.readFileSync(eventsPath, 'utf8');
288
+ } catch (_error) {
289
+ return { checks: 0, violations: [], blocked: 0 };
290
+ }
291
+ let checks = 0;
292
+ let blocked = 0;
293
+ const violations = [];
294
+ for (const line of raw.split('\n')) {
295
+ if (!line.trim()) continue;
296
+ let event;
297
+ try {
298
+ event = JSON.parse(line);
299
+ } catch (_error) {
300
+ continue;
301
+ }
302
+ if (!event || event.kind !== 'check') continue;
303
+ const at = Date.parse(event.at);
304
+ if (Number.isFinite(at) && now - at > sinceMs) continue;
305
+ checks += 1;
306
+ if (event.blocked) blocked += 1;
307
+ for (const verdict of Array.isArray(event.verdicts) ? event.verdicts : []) {
308
+ if (!verdict || verdict.band === 'clear') continue;
309
+ violations.push({
310
+ at: event.at,
311
+ phase: event.phase,
312
+ ruleId: verdict.ruleId,
313
+ band: verdict.band,
314
+ probability: verdict.probability,
315
+ files: Array.isArray(event.files) ? event.files : []
316
+ });
317
+ }
318
+ }
319
+ violations.sort((a, b) => String(b.at).localeCompare(String(a.at)));
320
+ return { checks, blocked, violations: violations.slice(0, limit) };
321
+ }
322
+
323
+ // Runs `abide check --diff <patch> --json` and returns the parsed sections.
324
+ // `skipped` with a reason when there is nothing abide can do here.
325
+ function runAbideCheck(
326
+ repoRoot,
327
+ diff,
328
+ { env = process.env, timeoutMs = ABIDE_CHECK_TIMEOUT_MS, runner = runAbide } = {}
329
+ ) {
330
+ const rubric = rubricStatus(repoRoot);
331
+ if (rubric.status === 'missing')
332
+ return { skipped: 'no rubric (.abide/rubric.json); compile it first' };
333
+ if (rubric.status === 'invalid') return { skipped: 'rubric is not valid JSON' };
334
+ if (!abideKeySource(repoRoot, env)) return { skipped: `no ${ABIDE_KEY_NAMES.join(' / ')} found` };
335
+ if (!String(diff || '').trim()) return { skipped: 'empty diff' };
336
+
337
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gx-abide-'));
338
+ const diffPath = path.join(dir, 'pr.diff');
339
+ try {
340
+ fs.writeFileSync(diffPath, diff);
341
+ const result = runner(repoRoot, ['check', '--diff', diffPath, '--json', '--phase', 'all'], {
342
+ timeoutMs,
343
+ env
344
+ });
345
+ if (result.status === 'unavailable')
346
+ return { skipped: 'abide is not installed and npx is unavailable' };
347
+ // abide exits 1 when a verdict lands in the act band; that is still a parsed result.
348
+ const jsonLine = (result.stdout || '')
349
+ .split('\n')
350
+ .map((l) => l.trim())
351
+ .filter((l) => l.startsWith('{'))
352
+ .pop();
353
+ if (!jsonLine) {
354
+ return { failed: `${result.label} produced no JSON: ${summarizeAbideOutput(result)}` };
355
+ }
356
+ let parsed;
357
+ try {
358
+ parsed = JSON.parse(jsonLine);
359
+ } catch (error) {
360
+ return { failed: `${result.label} output was not JSON: ${error.message}` };
361
+ }
362
+ return {
363
+ sections: Array.isArray(parsed.sections) ? parsed.sections : [],
364
+ spendUsd: parsed.spendUsd || 0,
365
+ rubric
366
+ };
367
+ } finally {
368
+ fs.rmSync(dir, { recursive: true, force: true });
369
+ }
370
+ }
371
+
372
+ // First added line per file in a unified diff, for anchoring findings.
373
+ function firstAddedLines(diff) {
374
+ const out = new Map();
375
+ let file = null;
376
+ let line = 0;
377
+ for (const raw of String(diff || '').split('\n')) {
378
+ if (raw.startsWith('+++ ')) {
379
+ file = raw.slice(4).trim().replace(/^b\//, '');
380
+ continue;
381
+ }
382
+ const hunk = raw.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
383
+ if (hunk) {
384
+ line = parseInt(hunk[1], 10);
385
+ continue;
386
+ }
387
+ if (!file || raw.startsWith('---')) continue;
388
+ if (raw.startsWith('+')) {
389
+ if (!out.has(file)) out.set(file, line);
390
+ line += 1;
391
+ } else if (!raw.startsWith('-') && !raw.startsWith('\\')) {
392
+ line += 1;
393
+ }
394
+ }
395
+ return out;
396
+ }
397
+
398
+ // Turns abide verdicts into gx review findings. `act` blocks the gate (high);
399
+ // `flag` is advisory (medium); `clear` is dropped.
400
+ function abideFindings(check, diff) {
401
+ if (!check || !Array.isArray(check.sections)) return [];
402
+ const anchors = firstAddedLines(diff);
403
+ const rules = (check.rubric && check.rubric.rulesById) || new Map();
404
+ const findings = [];
405
+ for (const section of check.sections) {
406
+ const files = Array.isArray(section.files) ? section.files : [];
407
+ const file = files.find((f) => anchors.has(f)) || files[0];
408
+ if (!file) continue;
409
+ for (const verdict of Array.isArray(section.verdicts) ? section.verdicts : []) {
410
+ if (!verdict || verdict.band === 'clear') continue;
411
+ const rule = rules.get(verdict.ruleId) || {};
412
+ const source =
413
+ rule.source && rule.source.path
414
+ ? `${rule.source.path}${rule.source.line ? ` line ${rule.source.line}` : ''}`
415
+ : 'the repository instructions';
416
+ const scope =
417
+ section.phase === 'turn' && files.length > 1
418
+ ? ` across the whole change (${files.length} files)`
419
+ : '';
420
+ findings.push({
421
+ path: file,
422
+ line: anchors.get(file) || 1,
423
+ severity: verdict.band === 'act' ? 'high' : 'medium',
424
+ category: 'abide',
425
+ message: `Rule "${verdict.ruleId}" from ${source}${scope}: "${rule.text || verdict.ruleId}" (p=${Number(verdict.probability || 0).toFixed(2)})`,
426
+ abide: {
427
+ ruleId: verdict.ruleId,
428
+ band: verdict.band,
429
+ probability: verdict.probability,
430
+ phase: section.phase
431
+ }
432
+ });
433
+ }
434
+ }
435
+ return findings;
436
+ }
437
+
438
+ // How the hooks are wired in a settings file: through the shim, through
439
+ // abide's own absolute-path entries, or not at all.
440
+ function hooksState(settingsPath) {
441
+ let settings;
442
+ try {
443
+ settings = readJsonIfExists(settingsPath);
444
+ } catch (_error) {
445
+ return 'invalid';
446
+ }
447
+ const entries = abideHookEntries(settings);
448
+ const events = Object.keys(entries);
449
+ if (events.length === 0) return 'none';
450
+ const shim = events.filter((e) => entries[e].some((entry) => entry.shim));
451
+ if (shim.length === ABIDE_HOOK_EVENTS.length) return 'shim';
452
+ if (shim.length > 0) return 'partial';
453
+ return 'legacy';
454
+ }
455
+
456
+ // One compact object for every status surface (gx status, MCP my_context).
457
+ function abideSummary(repoRoot, { env = process.env, now = Date.now() } = {}) {
458
+ const hooks = hooksState(path.join(repoRoot, '.claude', 'settings.json'));
459
+ const codexHooks = hooksState(path.join(repoRoot, '.codex', 'hooks.json'));
460
+ const rubric = rubricStatus(repoRoot);
461
+ const recent = readRecentEvents(repoRoot, { now });
462
+ return {
463
+ hooks,
464
+ codexHooks,
465
+ package: hooks === 'none' ? null : resolveShimPackageDir(repoRoot, env),
466
+ key: abideKeySource(repoRoot, env),
467
+ rubric: {
468
+ status: rubric.status,
469
+ rules: rubric.rules,
470
+ modelRules: rubric.modelRules,
471
+ changed: rubric.changed,
472
+ removed: rubric.removed
473
+ },
474
+ last7d: {
475
+ checks: recent.checks,
476
+ blocked: recent.blocked,
477
+ violations: recent.violations.length
478
+ },
479
+ violations: recent.violations
480
+ .slice(0, 5)
481
+ .map((v) => ({ ruleId: v.ruleId, band: v.band, at: v.at, files: v.files.slice(0, 3) }))
482
+ };
483
+ }
484
+
485
+ // One line for humans: `abide: hooks=shim · rubric=fresh (12 rules) · key=~/.abide/.env · 7d: 14 checks, 2 violations`.
486
+ function renderAbideSummary(summary, shortToolName = 'gx') {
487
+ if (summary.hooks === 'none' && summary.codexHooks === 'none') {
488
+ return `abide: not wired (${shortToolName} claude install)`;
489
+ }
490
+ const parts = [];
491
+ parts.push(
492
+ `hooks=${summary.hooks}${summary.codexHooks !== 'none' ? `+codex:${summary.codexHooks}` : ''}`
493
+ );
494
+ if (summary.hooks !== 'none' && !summary.package) parts.push('package=missing');
495
+ const rules = summary.rubric.rules ? ` (${summary.rubric.rules} rules)` : '';
496
+ parts.push(`rubric=${summary.rubric.status}${rules}`);
497
+ parts.push(`key=${summary.key || 'none'}`);
498
+ if (summary.last7d.checks > 0) {
499
+ parts.push(`7d: ${summary.last7d.checks} checks, ${summary.last7d.violations} violation(s)`);
500
+ }
501
+ return `abide: ${parts.join(' · ')}`;
502
+ }
503
+
504
+ module.exports = {
505
+ ABIDE_PACKAGE,
506
+ ABIDE_VERSION,
507
+ ABIDE_UPSTREAM_HOOK_MARKER,
508
+ ABIDE_SHIM_REL,
509
+ ABIDE_SHIM_MARKER,
510
+ ABIDE_HOOK_EVENTS,
511
+ ABIDE_HOOK_SPECS,
512
+ ABIDE_KEY_NAMES,
513
+ ABIDE_DIR_REL,
514
+ ABIDE_RUBRIC_REL,
515
+ ABIDE_EVENTS_REL,
516
+ ABIDE_INIT_TIMEOUT_MS,
517
+ abideSettingsTemplate,
518
+ isAbideHookCommand,
519
+ isShimCommand,
520
+ abideHookEntries,
521
+ abideKeySource,
522
+ resolveAbideCommand,
523
+ runAbide,
524
+ summarizeAbideOutput,
525
+ resolveShimPackageDir,
526
+ rubricStatus,
527
+ readRecentEvents,
528
+ runAbideCheck,
529
+ firstAddedLines,
530
+ abideFindings,
531
+ hooksState,
532
+ abideSummary,
533
+ renderAbideSummary
534
+ };
@@ -140,7 +140,10 @@ function applySurface(context, deps = {}) {
140
140
  const apply = deps.applyWindowStatus;
141
141
  if (typeof apply !== 'function') return { applied: false, reason: 'no-surface' };
142
142
  try {
143
- apply({ target, label, backend: sessionBackendName(context.session), activity: context.activity });
143
+ const result = apply({ target, label, backend: sessionBackendName(context.session), activity: context.activity });
144
+ if (result === false || result?.applied === false || (result?.status != null && result.status !== 0)) {
145
+ return { applied: false, reason: 'surface-error' };
146
+ }
144
147
  return { applied: true };
145
148
  } catch (error) {
146
149
  return { applied: false, reason: 'surface-error', error: error && error.message };
@@ -163,10 +166,25 @@ function setAgentActivity(repoRoot, options = {}, deps = {}) {
163
166
  }
164
167
 
165
168
  const update = deps.updateAgentSession || updateAgentSession;
166
- const updated = update(repoRoot, session.id, { activity }) || session;
169
+ const fingerprint = (record) => JSON.stringify([record.id, record.createdAt,
170
+ options.backend || sessionBackendName(record), record.tmux,
171
+ sessionPaneTarget(record), activity, windowLabel(record, activity, options.icons)]);
172
+ const unchanged = options.dedupeSurface && session.metadata?.activitySurface === fingerprint(session);
173
+ // Always renew activity/updatedAt, including duplicate notifications. Clear a
174
+ // receipt before a different attempted write so failures cannot become hits.
175
+ const patch = { activity };
176
+ if (!unchanged && session.metadata?.activitySurface) {
177
+ patch.metadata = { ...session.metadata, activitySurface: null };
178
+ }
179
+ const updated = update(repoRoot, session.id, patch) || session;
167
180
  const label = windowLabel(updated, activity, options.icons);
168
181
  const target = sessionPaneTarget(updated);
169
- const surface = applySurface({ session: updated, label, target, activity }, deps);
182
+ const surface = unchanged && fingerprint(updated) === fingerprint(session)
183
+ ? { applied: false, reason: 'unchanged' }
184
+ : applySurface({ session: updated, label, target, activity }, deps);
185
+ if (options.dedupeSurface && surface.applied) {
186
+ update(repoRoot, session.id, { metadata: { ...updated.metadata, activitySurface: fingerprint(updated) } });
187
+ }
170
188
 
171
189
  return { ok: true, activity, sessionId: session.id, label, target, surface };
172
190
  }
@@ -212,8 +230,9 @@ function runSetStatusCommand(repoRoot, options = {}, deps = {}) {
212
230
  const backendName = options.backend || sessionBackend || 'auto';
213
231
  if (!backend) backend = (deps.selectTerminalBackend || selectTerminalBackend)(backendName);
214
232
  if (backend && typeof backend.setWindowStatus === 'function') {
215
- backend.setWindowStatus(target, label);
233
+ return backend.setWindowStatus(target, label);
216
234
  }
235
+ return false;
217
236
  },
218
237
  });
219
238
 
@@ -1,6 +1,6 @@
1
1
  const { fs, path, DEFAULT_BASE_BRANCH, LOCK_FILE_RELATIVE } = require('../context');
2
2
  const { run } = require('../core/runtime');
3
- const { resolveRepoRoot } = require('../git');
3
+ const { resolveRepoRoot, inferBaseBranchFromHistory } = require('../git');
4
4
 
5
5
  const INSPECT_EXCLUDE_PATHS = new Set([LOCK_FILE_RELATIVE]);
6
6
 
@@ -68,11 +68,19 @@ function worktreePathForBranch(repoRoot, branch, worktrees = null) {
68
68
  }
69
69
 
70
70
  function resolveBaseBranch(repoRoot, branch) {
71
- return (
72
- readGitConfig(repoRoot, `branch.${branch}.guardexBase`) ||
73
- readGitConfig(repoRoot, 'multiagent.baseBranch') ||
74
- DEFAULT_BASE_BRANCH
75
- );
71
+ const perBranch = readGitConfig(repoRoot, `branch.${branch}.guardexBase`);
72
+ if (perBranch) return perBranch;
73
+
74
+ const configuredBase = readGitConfig(repoRoot, 'multiagent.baseBranch');
75
+ // Infer from history; do NOT persist (inspect is read-only display).
76
+ const inferred = inferBaseBranchFromHistory(repoRoot, branch, {
77
+ configuredBase,
78
+ protectedBranches: [],
79
+ defaultBase: DEFAULT_BASE_BRANCH,
80
+ });
81
+ if (inferred) return inferred;
82
+
83
+ return configuredBase || DEFAULT_BASE_BRANCH;
76
84
  }
77
85
 
78
86
  function compareRefForBase(repoRoot, baseBranch) {
@@ -199,4 +207,5 @@ module.exports = {
199
207
  renderLocks,
200
208
  resolveBaseBranch,
201
209
  runInspectCommand,
210
+ worktreePathForBranch,
202
211
  };
@@ -214,7 +214,12 @@ function buildAgentLaunchCommand(options) {
214
214
  throw new Error(`Unsupported agent: ${agentId}`);
215
215
  }
216
216
 
217
- const launchCommand = buildPromptCommand(baseParts, agent, prompt);
217
+ if (options.supervisorSessionId && !worktreePath) throw new Error('Supervised launch requires a worktree');
218
+ const launchParts = options.supervisorSessionId
219
+ ? [process.execPath, require('node:path').join(__dirname, 'supervise.js'),
220
+ worktreePath, options.supervisorSessionId, '--', ...baseParts]
221
+ : baseParts;
222
+ const launchCommand = buildPromptCommand(launchParts, agent, prompt);
218
223
  const envParts = [...buildResourceEnv(), ...buildSessionEnv(agent, sessionId)];
219
224
  const envPrefix = envParts.join(' ');
220
225
  const launchWithEnv = envPrefix ? `${envPrefix} ${launchCommand}` : launchCommand;