@imdeadpool/guardex 7.1.1 → 8.2.0
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.
- package/README.md +123 -322
- package/package.json +23 -5
- package/skills/gitguardex/SKILL.md +83 -3
- package/src/agents/finish.js +15 -0
- package/src/ci-init/index.js +0 -1
- package/src/cli/args.js +142 -3
- package/src/cli/commands/branch.js +294 -14
- package/src/cli/commands/claude.js +15 -0
- package/src/cli/commands/doctor.js +26 -0
- package/src/cli/commands/onboard.js +293 -0
- package/src/cli/commands/prompt.js +15 -3
- package/src/cli/commands/review.js +18 -0
- package/src/cli/commands/setup.js +8 -6
- package/src/cli/commands/status.js +12 -0
- package/src/cli/main.js +2 -0
- package/src/cli/shared-locks.js +304 -0
- package/src/context.js +21 -3
- package/src/core/runtime.js +33 -1
- package/src/doctor/index.js +58 -6
- package/src/finish/heartbeat.js +169 -0
- package/src/finish/index.js +165 -18
- package/src/finish/progress.js +316 -0
- package/src/finish/review-gate.js +453 -32
- package/src/github-api.js +59 -0
- package/src/mcp/collect.js +155 -19
- package/src/mcp/server.js +35 -19
- package/src/output/index.js +210 -0
- package/src/pr-checks.js +121 -0
- package/src/pr-review.js +581 -51
- package/src/pr.js +143 -21
- package/src/provider-binary.js +101 -0
- package/src/review-diff.js +116 -0
- package/src/review-fix.js +229 -0
- package/src/sandbox/index.js +11 -5
- package/src/scaffold/index.js +4 -16
- package/src/shared-git-state.js +566 -0
- package/templates/AGENTS.multiagent-safety.md +63 -11
- package/templates/AGENTS.multiagent-safety.min.md +1 -0
- package/templates/codex/skills/gitguardex/SKILL.md +83 -3
- package/templates/githooks/post-checkout +4 -9
- package/templates/githooks/pre-commit +17 -1
- package/templates/github/workflows/README.md +30 -23
- package/templates/scripts/agent-autofinish-watch.sh +280 -0
- package/templates/scripts/agent-branch-finish.sh +354 -23
- package/templates/scripts/agent-branch-start.sh +49 -22
- package/templates/scripts/agent-claude-stop-finish.sh +194 -0
- package/templates/scripts/agent-file-locks.py +198 -29
- package/templates/scripts/agent-preflight.sh +14 -2
- package/templates/scripts/agent-stalled-report.sh +40 -0
- package/templates/scripts/codex-agent.sh +10 -63
- package/templates/github/workflows/cr.yml +0 -46
|
@@ -23,6 +23,7 @@ from __future__ import annotations
|
|
|
23
23
|
import argparse
|
|
24
24
|
import json
|
|
25
25
|
import os
|
|
26
|
+
import re
|
|
26
27
|
import subprocess
|
|
27
28
|
import sys
|
|
28
29
|
from contextlib import contextmanager
|
|
@@ -39,6 +40,7 @@ except ImportError: # non-POSIX (e.g. Windows): cross-worktree locking degrades
|
|
|
39
40
|
|
|
40
41
|
LOCK_FILE_RELATIVE = Path('.omx/state/agent-file-locks.json')
|
|
41
42
|
AGENT_ID_ENV = 'GUARDEX_AGENT_ID'
|
|
43
|
+
PANE_ID_ENV = 'TMUX_PANE'
|
|
42
44
|
CRITICAL_GUARDRAIL_PATHS = {
|
|
43
45
|
'AGENTS.md',
|
|
44
46
|
'.githooks/pre-commit',
|
|
@@ -48,6 +50,11 @@ CRITICAL_GUARDRAIL_PATHS = {
|
|
|
48
50
|
'scripts/guardex-env.sh',
|
|
49
51
|
}
|
|
50
52
|
ALLOW_GUARDRAIL_DELETE_ENV = 'AGENT_ALLOW_GUARDRAIL_DELETE'
|
|
53
|
+
LOCK_TTL_HOURS_ENV = 'GUARDEX_LOCK_TTL_HOURS'
|
|
54
|
+
LOCK_NOW_EPOCH_ENV = 'GUARDEX_LOCK_NOW_EPOCH'
|
|
55
|
+
# Generous default so an active long-running lane is never reaped; `reap` is an
|
|
56
|
+
# explicit, opt-in maintenance command, not an automatic background sweep.
|
|
57
|
+
DEFAULT_LOCK_TTL_HOURS = 168.0 # 7 days
|
|
51
58
|
|
|
52
59
|
|
|
53
60
|
@dataclass
|
|
@@ -56,6 +63,7 @@ class LockEntry:
|
|
|
56
63
|
claimed_at: str
|
|
57
64
|
allow_delete: bool = False
|
|
58
65
|
agent: str = ''
|
|
66
|
+
pane: str = ''
|
|
59
67
|
|
|
60
68
|
|
|
61
69
|
class LockError(Exception):
|
|
@@ -107,12 +115,30 @@ def resolve_agent(args: argparse.Namespace) -> str:
|
|
|
107
115
|
return (value or '').strip()
|
|
108
116
|
|
|
109
117
|
|
|
118
|
+
def resolve_pane() -> str:
|
|
119
|
+
"""Return the caller's tmux pane when it has the canonical `%<number>` form."""
|
|
120
|
+
value = os.environ.get(PANE_ID_ENV, '').strip()
|
|
121
|
+
return value if re.fullmatch(r'%\d+', value) else ''
|
|
122
|
+
|
|
123
|
+
|
|
110
124
|
def owner_label(entry: dict[str, Any]) -> str:
|
|
111
125
|
branch = str(entry.get('branch', ''))
|
|
112
126
|
agent = str(entry.get('agent', ''))
|
|
113
127
|
return f'{branch} as {agent}' if agent else branch
|
|
114
128
|
|
|
115
129
|
|
|
130
|
+
def owner_description(entry: dict[str, Any]) -> str:
|
|
131
|
+
details: list[str] = []
|
|
132
|
+
pane = str(entry.get('pane', '')).strip()
|
|
133
|
+
worktree = str(entry.get('_worktree', '')).strip()
|
|
134
|
+
if pane:
|
|
135
|
+
details.append(f'pane {pane}')
|
|
136
|
+
if worktree:
|
|
137
|
+
details.append(f'worktree {worktree}')
|
|
138
|
+
suffix = f"; {'; '.join(details)}" if details else ''
|
|
139
|
+
return f'{owner_label(entry)}{suffix}'
|
|
140
|
+
|
|
141
|
+
|
|
116
142
|
def owner_matches(entry: dict[str, Any], branch: str, agent: str) -> bool:
|
|
117
143
|
"""Does this branch+agent own the entry?
|
|
118
144
|
|
|
@@ -146,7 +172,7 @@ def load_state(repo_root: Path) -> dict[str, Any]:
|
|
|
146
172
|
if not isinstance(locks, dict):
|
|
147
173
|
return {'locks': {}}
|
|
148
174
|
|
|
149
|
-
# Backward-compat normalization for older lock
|
|
175
|
+
# Backward-compat normalization for older lock schemas (no `agent`/`pane` fields).
|
|
150
176
|
normalized_locks: dict[str, dict[str, Any]] = {}
|
|
151
177
|
for file_path, entry in locks.items():
|
|
152
178
|
if not isinstance(entry, dict):
|
|
@@ -155,11 +181,13 @@ def load_state(repo_root: Path) -> dict[str, Any]:
|
|
|
155
181
|
claimed_at = str(entry.get('claimed_at', ''))
|
|
156
182
|
allow_delete = bool(entry.get('allow_delete', False))
|
|
157
183
|
agent = str(entry.get('agent', ''))
|
|
184
|
+
pane = str(entry.get('pane', ''))
|
|
158
185
|
normalized_locks[str(file_path)] = {
|
|
159
186
|
'branch': branch,
|
|
160
187
|
'claimed_at': claimed_at,
|
|
161
188
|
'allow_delete': allow_delete,
|
|
162
189
|
'agent': agent,
|
|
190
|
+
'pane': pane,
|
|
163
191
|
}
|
|
164
192
|
|
|
165
193
|
return {'locks': normalized_locks}
|
|
@@ -174,7 +202,7 @@ def write_state(repo_root: Path, state: dict[str, Any]) -> None:
|
|
|
174
202
|
|
|
175
203
|
|
|
176
204
|
def now_iso() -> str:
|
|
177
|
-
return datetime.
|
|
205
|
+
return datetime.fromtimestamp(now_epoch(), tz=timezone.utc).isoformat()
|
|
178
206
|
|
|
179
207
|
|
|
180
208
|
def env_truthy(value: str | None) -> bool:
|
|
@@ -183,6 +211,71 @@ def env_truthy(value: str | None) -> bool:
|
|
|
183
211
|
return value.strip().lower() in {'1', 'true', 'yes', 'on'}
|
|
184
212
|
|
|
185
213
|
|
|
214
|
+
def now_epoch() -> float:
|
|
215
|
+
"""Current unix time, overridable via GUARDEX_LOCK_NOW_EPOCH for tests."""
|
|
216
|
+
override = os.environ.get(LOCK_NOW_EPOCH_ENV)
|
|
217
|
+
if override:
|
|
218
|
+
try:
|
|
219
|
+
return float(override)
|
|
220
|
+
except ValueError:
|
|
221
|
+
pass
|
|
222
|
+
return datetime.now(timezone.utc).timestamp()
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def parse_iso_epoch(value: str) -> float | None:
|
|
226
|
+
"""Parse a `claimed_at` ISO-8601 stamp to a unix epoch, or None if unset
|
|
227
|
+
or unparseable. Naive stamps are assumed UTC (claims are written in UTC)."""
|
|
228
|
+
if not value:
|
|
229
|
+
return None
|
|
230
|
+
try:
|
|
231
|
+
dt = datetime.fromisoformat(value)
|
|
232
|
+
except ValueError:
|
|
233
|
+
return None
|
|
234
|
+
if dt.tzinfo is None:
|
|
235
|
+
dt = dt.replace(tzinfo=timezone.utc)
|
|
236
|
+
return dt.timestamp()
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def has_live_process_in_worktree(worktree: Path) -> bool:
|
|
240
|
+
"""True when any running process has its cwd inside `worktree` (Linux /proc
|
|
241
|
+
only; best-effort no elsewhere). Guards reap from touching an active lane."""
|
|
242
|
+
proc = Path('/proc')
|
|
243
|
+
if not proc.is_dir():
|
|
244
|
+
return False
|
|
245
|
+
wt = str(worktree)
|
|
246
|
+
try:
|
|
247
|
+
entries = list(proc.iterdir())
|
|
248
|
+
except OSError:
|
|
249
|
+
return False
|
|
250
|
+
for entry in entries:
|
|
251
|
+
if not entry.name.isdigit():
|
|
252
|
+
continue
|
|
253
|
+
try:
|
|
254
|
+
target = os.readlink(entry / 'cwd')
|
|
255
|
+
except OSError:
|
|
256
|
+
continue
|
|
257
|
+
if target.endswith(' (deleted)'):
|
|
258
|
+
target = target[: -len(' (deleted)')]
|
|
259
|
+
if target == wt or target.startswith(wt + os.sep):
|
|
260
|
+
return True
|
|
261
|
+
return False
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def resolve_ttl_hours(args: argparse.Namespace) -> float:
|
|
265
|
+
"""Reap TTL in hours: --ttl-hours wins, then GUARDEX_LOCK_TTL_HOURS, then
|
|
266
|
+
the 7-day default."""
|
|
267
|
+
explicit = getattr(args, 'ttl_hours', None)
|
|
268
|
+
if explicit is not None:
|
|
269
|
+
return float(explicit)
|
|
270
|
+
env = os.environ.get(LOCK_TTL_HOURS_ENV)
|
|
271
|
+
if env:
|
|
272
|
+
try:
|
|
273
|
+
return float(env)
|
|
274
|
+
except ValueError:
|
|
275
|
+
pass
|
|
276
|
+
return DEFAULT_LOCK_TTL_HOURS
|
|
277
|
+
|
|
278
|
+
|
|
186
279
|
def staged_changes(repo_root: Path) -> list[tuple[str, str]]:
|
|
187
280
|
out = run_git(['diff', '--cached', '--name-status', '--diff-filter=ACMRDTUXB'], cwd=repo_root)
|
|
188
281
|
if not out:
|
|
@@ -215,13 +308,14 @@ def list_worktree_roots(repo_root: Path) -> list[Path]:
|
|
|
215
308
|
report their gitdir (<parent>/.git/worktrees/<wt>/modules/<sub>) as the
|
|
216
309
|
worktree path, not the actual working tree — repo_root (resolved via
|
|
217
310
|
--show-toplevel) is where claims are written, so it must be in the list
|
|
218
|
-
or claim/validate/status never see this checkout's own lock file.
|
|
219
|
-
|
|
311
|
+
or claim/validate/status never see this checkout's own lock file. Lock
|
|
312
|
+
enforcement fails closed when Git cannot enumerate every sibling."""
|
|
220
313
|
try:
|
|
221
314
|
out = run_git(['worktree', 'list', '--porcelain'], cwd=repo_root)
|
|
222
|
-
except LockError:
|
|
223
|
-
|
|
224
|
-
|
|
315
|
+
except LockError as exc:
|
|
316
|
+
raise LockError(
|
|
317
|
+
'cannot safely enumerate sibling worktrees; lock operation blocked'
|
|
318
|
+
) from exc
|
|
225
319
|
roots: list[Path] = []
|
|
226
320
|
for line in out.splitlines():
|
|
227
321
|
if line.startswith('worktree '):
|
|
@@ -240,11 +334,13 @@ def load_all_locks(repo_root: Path) -> dict[str, list[dict[str, Any]]]:
|
|
|
240
334
|
for root in list_worktree_roots(repo_root):
|
|
241
335
|
try:
|
|
242
336
|
state = load_state(root)
|
|
243
|
-
except LockError:
|
|
244
|
-
|
|
245
|
-
|
|
337
|
+
except LockError as exc:
|
|
338
|
+
raise LockError(
|
|
339
|
+
f'cannot safely inspect sibling lock registry in {root}; '
|
|
340
|
+
'lock operation blocked'
|
|
341
|
+
) from exc
|
|
246
342
|
for file_path, entry in state['locks'].items():
|
|
247
|
-
merged.setdefault(file_path, []).append(entry)
|
|
343
|
+
merged.setdefault(file_path, []).append({**entry, '_worktree': str(root)})
|
|
248
344
|
return merged
|
|
249
345
|
|
|
250
346
|
|
|
@@ -263,29 +359,27 @@ def cross_worktree_lock(repo_root: Path):
|
|
|
263
359
|
common git dir), so concurrent claim/release/validate runs — in the same or
|
|
264
360
|
different worktrees — are serialized. Without it, two claims race on the
|
|
265
361
|
read-modify-write of separate lock files and can both win the same path or
|
|
266
|
-
drop each other's writes.
|
|
267
|
-
|
|
362
|
+
drop each other's writes. Mutual exclusion is a safety boundary: unavailable
|
|
363
|
+
OS locking or an inaccessible common lock file blocks the command."""
|
|
268
364
|
if fcntl is None:
|
|
269
|
-
|
|
270
|
-
return
|
|
365
|
+
raise LockError('OS file locking is unavailable; lock operation blocked')
|
|
271
366
|
try:
|
|
272
367
|
lock_path = common_git_dir(repo_root) / 'agent-file-locks.lock'
|
|
273
368
|
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
|
274
369
|
handle = open(lock_path, 'w')
|
|
275
|
-
except (OSError, LockError):
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
locked = False
|
|
370
|
+
except (OSError, LockError) as exc:
|
|
371
|
+
raise LockError('cannot open the shared worktree lock; operation blocked') from exc
|
|
372
|
+
acquired = False
|
|
279
373
|
try:
|
|
280
374
|
try:
|
|
281
375
|
fcntl.flock(handle.fileno(), fcntl.LOCK_EX)
|
|
282
|
-
|
|
283
|
-
except OSError:
|
|
284
|
-
|
|
376
|
+
acquired = True
|
|
377
|
+
except OSError as exc:
|
|
378
|
+
raise LockError('cannot acquire the shared worktree lock; operation blocked') from exc
|
|
285
379
|
yield
|
|
286
380
|
finally:
|
|
287
381
|
try:
|
|
288
|
-
if
|
|
382
|
+
if acquired:
|
|
289
383
|
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
|
|
290
384
|
finally:
|
|
291
385
|
handle.close()
|
|
@@ -296,23 +390,36 @@ def cmd_claim(args: argparse.Namespace, repo_root: Path) -> int:
|
|
|
296
390
|
locks: dict[str, dict[str, Any]] = state['locks']
|
|
297
391
|
|
|
298
392
|
claim_agent = resolve_agent(args)
|
|
393
|
+
claim_pane = resolve_pane()
|
|
299
394
|
files = [normalize_repo_path(repo_root, p) for p in args.files]
|
|
300
|
-
conflicts: list[tuple[str, str]] = []
|
|
395
|
+
conflicts: list[tuple[str, dict[str, Any]]] = []
|
|
301
396
|
|
|
302
397
|
# Conflict detection spans EVERY worktree of the repo, not just this one: a
|
|
303
398
|
# file claimed by another owner in a sibling worktree must still block this
|
|
304
399
|
# claim (each worktree keeps a separate lock file). The write below still
|
|
305
400
|
# records the claim in THIS worktree's lock file.
|
|
306
401
|
all_locks = load_all_locks(repo_root)
|
|
402
|
+
ttl_seconds = resolve_ttl_hours(args) * 3600.0
|
|
403
|
+
now = now_epoch()
|
|
404
|
+
any_stale = False
|
|
307
405
|
for file_path in files:
|
|
308
406
|
foreign = [e for e in all_locks.get(file_path, []) if not owner_matches(e, args.branch, claim_agent)]
|
|
309
407
|
if foreign:
|
|
310
|
-
conflicts.append((file_path,
|
|
408
|
+
conflicts.append((file_path, foreign[0]))
|
|
409
|
+
claimed = parse_iso_epoch(str(foreign[0].get('claimed_at', '')))
|
|
410
|
+
if claimed is not None and (now - claimed) >= ttl_seconds:
|
|
411
|
+
any_stale = True
|
|
311
412
|
|
|
312
413
|
if conflicts:
|
|
313
414
|
print('[agent-file-locks] Cannot claim files already locked by another owner:', file=sys.stderr)
|
|
314
415
|
for file_path, owner in conflicts:
|
|
315
|
-
print(f' - {file_path} (locked by {owner})', file=sys.stderr)
|
|
416
|
+
print(f' - {file_path} (locked by {owner_description(owner)})', file=sys.stderr)
|
|
417
|
+
if any_stale:
|
|
418
|
+
print(
|
|
419
|
+
'[agent-file-locks] Some blocking locks are past the staleness TTL; if their '
|
|
420
|
+
'lane is abandoned, run `gx locks reap` to clear them.',
|
|
421
|
+
file=sys.stderr,
|
|
422
|
+
)
|
|
316
423
|
return 1
|
|
317
424
|
|
|
318
425
|
for file_path in files:
|
|
@@ -321,11 +428,13 @@ def cmd_claim(args: argparse.Namespace, repo_root: Path) -> int:
|
|
|
321
428
|
# A named claim adopts/upgrades the entry's agent; an anonymous claim
|
|
322
429
|
# keeps any existing agent rather than silently downgrading it.
|
|
323
430
|
resolved_owner_agent = claim_agent or str(existing.get('agent', ''))
|
|
431
|
+
resolved_owner_pane = claim_pane or str(existing.get('pane', ''))
|
|
324
432
|
locks[file_path] = LockEntry(
|
|
325
433
|
branch=args.branch,
|
|
326
434
|
claimed_at=now_iso(),
|
|
327
435
|
allow_delete=args.allow_delete or existing_allow_delete,
|
|
328
436
|
agent=resolved_owner_agent,
|
|
437
|
+
pane=resolved_owner_pane,
|
|
329
438
|
).__dict__
|
|
330
439
|
|
|
331
440
|
write_state(repo_root, state)
|
|
@@ -394,6 +503,52 @@ def cmd_release(args: argparse.Namespace, repo_root: Path) -> int:
|
|
|
394
503
|
return 0
|
|
395
504
|
|
|
396
505
|
|
|
506
|
+
def cmd_reap(args: argparse.Namespace, repo_root: Path) -> int:
|
|
507
|
+
# Clear locks held by ABANDONED worktrees: present on disk, idle past the
|
|
508
|
+
# TTL, and with no live process inside. Dead worktrees self-clean (their lock
|
|
509
|
+
# file lives inside them), so this targets the lingering-but-idle case where
|
|
510
|
+
# a crashed or forgotten lane keeps blocking a file forever. The caller's own
|
|
511
|
+
# worktree always has a live process, so reap never clears its active locks.
|
|
512
|
+
ttl_hours = resolve_ttl_hours(args)
|
|
513
|
+
ttl_seconds = ttl_hours * 3600.0
|
|
514
|
+
now = now_epoch()
|
|
515
|
+
roots = list_worktree_roots(repo_root)
|
|
516
|
+
reaped: list[tuple[str, str, str, int]] = [] # worktree, file, branch, age_hours
|
|
517
|
+
for root in roots:
|
|
518
|
+
try:
|
|
519
|
+
state = load_state(root)
|
|
520
|
+
except LockError as exc:
|
|
521
|
+
raise LockError(
|
|
522
|
+
f'cannot safely inspect sibling lock registry in {root}; '
|
|
523
|
+
'reap operation blocked'
|
|
524
|
+
) from exc
|
|
525
|
+
locks = state['locks']
|
|
526
|
+
if not locks:
|
|
527
|
+
continue
|
|
528
|
+
if has_live_process_in_worktree(root):
|
|
529
|
+
continue
|
|
530
|
+
survivors: dict[str, Any] = {}
|
|
531
|
+
changed = False
|
|
532
|
+
for file_path, entry in locks.items():
|
|
533
|
+
claimed = parse_iso_epoch(str(entry.get('claimed_at', '')))
|
|
534
|
+
if claimed is not None and (now - claimed) >= ttl_seconds:
|
|
535
|
+
reaped.append((str(root), file_path, str(entry.get('branch', '')), int((now - claimed) // 3600)))
|
|
536
|
+
changed = True
|
|
537
|
+
else:
|
|
538
|
+
survivors[file_path] = entry
|
|
539
|
+
if changed and not args.dry_run:
|
|
540
|
+
write_state(root, {**state, 'locks': survivors})
|
|
541
|
+
|
|
542
|
+
if not reaped:
|
|
543
|
+
print(f'[agent-file-locks] reap: no stale locks (ttl={int(ttl_hours)}h, scanned {len(roots)} worktree(s)).')
|
|
544
|
+
return 0
|
|
545
|
+
label = '[agent-file-locks] [dry-run] would reap' if args.dry_run else '[agent-file-locks] reaped'
|
|
546
|
+
print(f'{label} {len(reaped)} stale lock(s) (ttl={int(ttl_hours)}h):')
|
|
547
|
+
for root, file_path, branch, age_hours in reaped:
|
|
548
|
+
print(f' - {file_path} | {branch} | idle {age_hours}h | {root}')
|
|
549
|
+
return 0
|
|
550
|
+
|
|
551
|
+
|
|
397
552
|
def cmd_status(args: argparse.Namespace, repo_root: Path) -> int:
|
|
398
553
|
# Union across worktrees so status reflects what claim/validate now enforce —
|
|
399
554
|
# a sibling worktree's claims would otherwise be invisible here.
|
|
@@ -404,8 +559,11 @@ def cmd_status(args: argparse.Namespace, repo_root: Path) -> int:
|
|
|
404
559
|
for root in roots:
|
|
405
560
|
try:
|
|
406
561
|
locks = load_state(root)['locks']
|
|
407
|
-
except LockError:
|
|
408
|
-
|
|
562
|
+
except LockError as exc:
|
|
563
|
+
raise LockError(
|
|
564
|
+
f'cannot safely inspect sibling lock registry in {root}; '
|
|
565
|
+
'status is unavailable'
|
|
566
|
+
) from exc
|
|
409
567
|
for file_path, entry in locks.items():
|
|
410
568
|
branch = str(entry.get('branch', ''))
|
|
411
569
|
if args.branch and branch != args.branch:
|
|
@@ -555,6 +713,15 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
555
713
|
status.add_argument('--branch', help='Filter by branch')
|
|
556
714
|
add_agent_arg(status)
|
|
557
715
|
|
|
716
|
+
reap = sub.add_parser('reap', help='Clear stale locks from abandoned (idle past TTL, no live process) worktrees')
|
|
717
|
+
reap.add_argument(
|
|
718
|
+
'--ttl-hours',
|
|
719
|
+
type=float,
|
|
720
|
+
default=None,
|
|
721
|
+
help=f'Idle hours before a lock is stale (default {int(DEFAULT_LOCK_TTL_HOURS)}h or ${LOCK_TTL_HOURS_ENV})',
|
|
722
|
+
)
|
|
723
|
+
reap.add_argument('--dry-run', action='store_true', help='Report stale locks without removing them')
|
|
724
|
+
|
|
558
725
|
validate = sub.add_parser('validate', help='Validate staged files are locked by branch')
|
|
559
726
|
validate.add_argument('--branch', required=True, help='Owner branch name')
|
|
560
727
|
add_agent_arg(validate)
|
|
@@ -571,6 +738,8 @@ def dispatch_command(args: argparse.Namespace, repo_root: Path) -> int:
|
|
|
571
738
|
return cmd_allow_delete(args, repo_root)
|
|
572
739
|
if args.command == 'release':
|
|
573
740
|
return cmd_release(args, repo_root)
|
|
741
|
+
if args.command == 'reap':
|
|
742
|
+
return cmd_reap(args, repo_root)
|
|
574
743
|
if args.command == 'status':
|
|
575
744
|
return cmd_status(args, repo_root)
|
|
576
745
|
if args.command == 'validate':
|
|
@@ -589,7 +758,7 @@ def main() -> int:
|
|
|
589
758
|
# Serialize state-changing commands (and validate's snapshot read) across
|
|
590
759
|
# ALL worktrees with one shared lock, so concurrent runs can't clobber
|
|
591
760
|
# each other or both win the same file. status is a pure read -> unlocked.
|
|
592
|
-
if args.command in {'claim', 'allow-delete', 'release', 'validate'}:
|
|
761
|
+
if args.command in {'claim', 'allow-delete', 'release', 'reap', 'validate'}:
|
|
593
762
|
with cross_worktree_lock(repo_root):
|
|
594
763
|
return dispatch_command(args, repo_root)
|
|
595
764
|
return dispatch_command(args, repo_root)
|
|
@@ -31,13 +31,25 @@ fail=0
|
|
|
31
31
|
# failure (where it is actually useful). Stream full output live with
|
|
32
32
|
# GUARDEX_PREFLIGHT_VERBOSE=1.
|
|
33
33
|
GUARDEX_PREFLIGHT_FAIL_TAIL="${GUARDEX_PREFLIGHT_FAIL_TAIL:-40}"
|
|
34
|
+
run_verification_command() {
|
|
35
|
+
env \
|
|
36
|
+
-u ALLOW_BASH_ON_NON_AGENT_BRANCH \
|
|
37
|
+
-u ALLOW_CODE_EDIT_ON_PROTECTED_BRANCH \
|
|
38
|
+
-u ALLOW_CODE_EDIT_ON_PRIMARY_WORKTREE \
|
|
39
|
+
-u ALLOW_COMMIT_ON_PROTECTED_BRANCH \
|
|
40
|
+
-u ALLOW_PUSH_ON_PROTECTED_BRANCH \
|
|
41
|
+
-u GUARDEX_CLI_ENTRY \
|
|
42
|
+
-u GUARDEX_NODE_BIN \
|
|
43
|
+
"$@"
|
|
44
|
+
}
|
|
45
|
+
|
|
34
46
|
run_step() {
|
|
35
47
|
local label="$1"
|
|
36
48
|
shift
|
|
37
49
|
echo "[agent-preflight] -> $label"
|
|
38
50
|
attempted=$((attempted + 1))
|
|
39
51
|
if [[ "${GUARDEX_PREFLIGHT_VERBOSE:-0}" == "1" ]]; then
|
|
40
|
-
if "$@"; then
|
|
52
|
+
if run_verification_command "$@"; then
|
|
41
53
|
ran=$((ran + 1))
|
|
42
54
|
echo "[agent-preflight] ok"
|
|
43
55
|
else
|
|
@@ -48,7 +60,7 @@ run_step() {
|
|
|
48
60
|
fi
|
|
49
61
|
local out rc
|
|
50
62
|
# `if` keeps `set -e` from aborting on a failing step before we capture rc.
|
|
51
|
-
if out="$("$@" 2>&1)"; then
|
|
63
|
+
if out="$(run_verification_command "$@" 2>&1)"; then
|
|
52
64
|
rc=0
|
|
53
65
|
else
|
|
54
66
|
rc=$?
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# Quiet wrapper around scripts/agent-autofinish-watch.sh that surfaces stalled
|
|
3
|
+
# agent/* worktrees. Prints nothing when everything's clean; prints a one-line
|
|
4
|
+
# summary per stalled worktree + a finish hint when there's work to recover.
|
|
5
|
+
#
|
|
6
|
+
# Designed to be wired as a SessionStart hook so Claude Code (and the user)
|
|
7
|
+
# learn about half-finished codex/claude agent runs at the top of each session.
|
|
8
|
+
#
|
|
9
|
+
# Exit codes:
|
|
10
|
+
# 0 — no stalled worktrees (or watcher missing — soft fail)
|
|
11
|
+
# 0 — even when stalled worktrees ARE detected (this is informational, not a hard error)
|
|
12
|
+
|
|
13
|
+
set -euo pipefail
|
|
14
|
+
|
|
15
|
+
repo_root="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
|
|
16
|
+
watcher="${repo_root}/scripts/agent-autofinish-watch.sh"
|
|
17
|
+
|
|
18
|
+
if [[ ! -x "$watcher" ]]; then
|
|
19
|
+
exit 0
|
|
20
|
+
fi
|
|
21
|
+
|
|
22
|
+
raw_output="$(bash "$watcher" --once --dry-run 2>&1 || true)"
|
|
23
|
+
|
|
24
|
+
# Filter to per-worktree status lines only ("[agent-autofinish-watch] agent/<branch>: ...").
|
|
25
|
+
stalled_lines="$(printf '%s\n' "$raw_output" | grep -E '^\[agent-autofinish-watch\] agent/' || true)"
|
|
26
|
+
|
|
27
|
+
if [[ -z "$stalled_lines" ]]; then
|
|
28
|
+
exit 0
|
|
29
|
+
fi
|
|
30
|
+
|
|
31
|
+
stalled_count="$(printf '%s\n' "$stalled_lines" | wc -l | tr -d ' ')"
|
|
32
|
+
|
|
33
|
+
printf '⚠ Stalled agent worktrees detected (%s):\n' "$stalled_count"
|
|
34
|
+
printf '%s\n' "$stalled_lines" | sed 's/^\[agent-autofinish-watch\] / • /'
|
|
35
|
+
printf '\nResolve options:\n'
|
|
36
|
+
printf ' • Inspect: bash scripts/agent-autofinish-watch.sh --once --dry-run\n'
|
|
37
|
+
printf ' • Auto-finish: bash scripts/agent-autofinish-watch.sh --once --auto-merge\n'
|
|
38
|
+
printf ' • Run daemon: bash scripts/agent-autofinish-watch.sh --daemon --auto-merge\n'
|
|
39
|
+
|
|
40
|
+
exit 0
|
|
@@ -58,7 +58,7 @@ normalize_bool() {
|
|
|
58
58
|
|
|
59
59
|
normalize_tier() {
|
|
60
60
|
local raw="${1:-}"
|
|
61
|
-
local fallback="${2:-
|
|
61
|
+
local fallback="${2:-T1}"
|
|
62
62
|
local upper
|
|
63
63
|
upper="$(printf '%s' "$raw" | tr '[:lower:]' '[:upper:]')"
|
|
64
64
|
case "$upper" in
|
|
@@ -91,36 +91,6 @@ build_codex_launch_args() {
|
|
|
91
91
|
CODEX_LAUNCH_ARGS+=("$@")
|
|
92
92
|
}
|
|
93
93
|
|
|
94
|
-
string_contains_any() {
|
|
95
|
-
local haystack="$1"
|
|
96
|
-
shift
|
|
97
|
-
local needle
|
|
98
|
-
for needle in "$@"; do
|
|
99
|
-
if [[ "$haystack" == *"$needle"* ]]; then
|
|
100
|
-
return 0
|
|
101
|
-
fi
|
|
102
|
-
done
|
|
103
|
-
return 1
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
string_has_lightweight_prefix() {
|
|
107
|
-
local text="$1"
|
|
108
|
-
local prefix
|
|
109
|
-
for prefix in "quick:" "simple:" "tiny:" "minor:" "small:" "just:" "only:"; do
|
|
110
|
-
if [[ "$text" == "$prefix"* ]]; then
|
|
111
|
-
return 0
|
|
112
|
-
fi
|
|
113
|
-
done
|
|
114
|
-
return 1
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
task_requires_full_change_workspace() {
|
|
118
|
-
local text="$1"
|
|
119
|
-
string_contains_any "$text" \
|
|
120
|
-
"cleanup evidence" "merged cleanup" "merged state" "pr url" \
|
|
121
|
-
"cleanup pipeline" "finish pipeline" "sandbox cleanup" "tasks.md"
|
|
122
|
-
}
|
|
123
|
-
|
|
124
94
|
derive_task_mode_from_tier() {
|
|
125
95
|
case "$1" in
|
|
126
96
|
T0|T1) printf 'caveman' ;;
|
|
@@ -139,8 +109,8 @@ apply_openspec_tier() {
|
|
|
139
109
|
OPENSPEC_SKIP_PLAN=1
|
|
140
110
|
;;
|
|
141
111
|
T1)
|
|
112
|
+
OPENSPEC_SKIP_CHANGE=1
|
|
142
113
|
OPENSPEC_SKIP_PLAN=1
|
|
143
|
-
OPENSPEC_MINIMAL=1
|
|
144
114
|
;;
|
|
145
115
|
T2)
|
|
146
116
|
OPENSPEC_SKIP_PLAN=1
|
|
@@ -149,40 +119,15 @@ apply_openspec_tier() {
|
|
|
149
119
|
}
|
|
150
120
|
|
|
151
121
|
decide_task_routing() {
|
|
152
|
-
local task_lower
|
|
153
|
-
task_lower="$(printf '%s' "$TASK_NAME" | tr '[:upper:]' '[:lower:]')"
|
|
154
|
-
|
|
155
122
|
if [[ -n "$OPENSPEC_TIER_RAW" ]]; then
|
|
156
|
-
if ! OPENSPEC_TIER="$(normalize_tier "$OPENSPEC_TIER_RAW" "
|
|
123
|
+
if ! OPENSPEC_TIER="$(normalize_tier "$OPENSPEC_TIER_RAW" "T1")"; then
|
|
157
124
|
echo "[codex-agent] Unsupported OpenSpec tier: ${OPENSPEC_TIER_RAW}" >&2
|
|
158
125
|
return 1
|
|
159
126
|
fi
|
|
160
127
|
TASK_ROUTING_REASON="explicit tier override"
|
|
161
|
-
elif string_has_lightweight_prefix "$task_lower"; then
|
|
162
|
-
if task_requires_full_change_workspace "$task_lower"; then
|
|
163
|
-
OPENSPEC_TIER="T2"
|
|
164
|
-
TASK_ROUTING_REASON="cleanup-evidence artifact wording overrides lightweight prefix"
|
|
165
|
-
else
|
|
166
|
-
OPENSPEC_TIER="T1"
|
|
167
|
-
TASK_ROUTING_REASON="explicit lightweight prefix"
|
|
168
|
-
fi
|
|
169
|
-
elif string_contains_any "$task_lower" \
|
|
170
|
-
"ralph" "autopilot" "ultrawork" "ultraqa" "ralplan" "deep interview" "ouroboros" \
|
|
171
|
-
"migration" "refactor" "architecture" "re-architect" "cross-cutting" "multi-agent" \
|
|
172
|
-
"multiagent" "parallel" "orchestr" "release" "zero-copy" "install surface" "workflow"
|
|
173
|
-
then
|
|
174
|
-
OPENSPEC_TIER="T3"
|
|
175
|
-
TASK_ROUTING_REASON="plan-heavy or orchestration-heavy task wording"
|
|
176
|
-
elif string_contains_any "$task_lower" \
|
|
177
|
-
"typo" "spelling" "comment-only" "comment only" "format-only" "format only" \
|
|
178
|
-
"whitespace" "one-liner" "one liner" "version bump" "bump version" \
|
|
179
|
-
"single-file" "single file"
|
|
180
|
-
then
|
|
181
|
-
OPENSPEC_TIER="T1"
|
|
182
|
-
TASK_ROUTING_REASON="small bounded maintenance wording"
|
|
183
128
|
else
|
|
184
|
-
OPENSPEC_TIER="
|
|
185
|
-
TASK_ROUTING_REASON="default
|
|
129
|
+
OPENSPEC_TIER="T1"
|
|
130
|
+
TASK_ROUTING_REASON="default direct-execution route; OpenSpec requires --tier T2 or T3"
|
|
186
131
|
fi
|
|
187
132
|
|
|
188
133
|
if ! TASK_MODE="$(derive_task_mode_from_tier "$OPENSPEC_TIER")"; then
|
|
@@ -195,7 +140,7 @@ decide_task_routing() {
|
|
|
195
140
|
describe_task_routing() {
|
|
196
141
|
case "$OPENSPEC_TIER" in
|
|
197
142
|
T0) printf 'caveman / T0 (no OpenSpec scaffold)' ;;
|
|
198
|
-
T1) printf 'caveman / T1 (
|
|
143
|
+
T1) printf 'caveman / T1 (no OpenSpec scaffold)' ;;
|
|
199
144
|
T2) printf 'omx / T2 (change workspace only)' ;;
|
|
200
145
|
T3) printf 'omx / T3 (change plus plan workspace)' ;;
|
|
201
146
|
*) printf 'unknown / %s' "${OPENSPEC_TIER:-unset}" ;;
|
|
@@ -681,7 +626,7 @@ print_takeover_prompt() {
|
|
|
681
626
|
change_artifact="openspec/changes/${change_slug}/notes.md"
|
|
682
627
|
fi
|
|
683
628
|
if [[ ! -f "${wt}/${change_artifact}" ]]; then
|
|
684
|
-
change_artifact="
|
|
629
|
+
change_artifact=""
|
|
685
630
|
fi
|
|
686
631
|
|
|
687
632
|
finish_cmd="gx branch finish --branch \"${branch}\" --base ${base_branch} --via-pr --wait-for-merge --cleanup"
|
|
@@ -690,7 +635,9 @@ print_takeover_prompt() {
|
|
|
690
635
|
echo " change: ${change_slug}"
|
|
691
636
|
echo " branch: ${branch}"
|
|
692
637
|
echo " worktree: ${wt}"
|
|
693
|
-
|
|
638
|
+
if [[ -n "$change_artifact" ]]; then
|
|
639
|
+
echo " spec: ${change_artifact}"
|
|
640
|
+
fi
|
|
694
641
|
echo " routing: $(describe_task_routing) (${TASK_ROUTING_REASON})"
|
|
695
642
|
echo " rule: continue current state; do not create a new sandbox"
|
|
696
643
|
echo " finish: ${finish_cmd}"
|
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
name: Code Review
|
|
2
|
-
|
|
3
|
-
on:
|
|
4
|
-
pull_request:
|
|
5
|
-
types: [opened, reopened, synchronize, ready_for_review, labeled]
|
|
6
|
-
|
|
7
|
-
permissions:
|
|
8
|
-
contents: read
|
|
9
|
-
pull-requests: write
|
|
10
|
-
|
|
11
|
-
# Budget-friendly default for gitguardex-managed projects: cancel
|
|
12
|
-
# superseded runs on the same PR so rapid agent pushes don't fan-out
|
|
13
|
-
# the OpenAI bill.
|
|
14
|
-
concurrency:
|
|
15
|
-
group: cr-${{ github.workflow }}-${{ github.event.pull_request.number }}
|
|
16
|
-
cancel-in-progress: true
|
|
17
|
-
|
|
18
|
-
jobs:
|
|
19
|
-
review:
|
|
20
|
-
# Skip on draft PRs and on `agent/*` head branches by default.
|
|
21
|
-
# Agent PRs can opt-in by applying the `needs-review` label —
|
|
22
|
-
# useful for the occasional agent PR that genuinely needs AI
|
|
23
|
-
# eyes (security-sensitive change, public-API redesign, etc.).
|
|
24
|
-
# Human-authored PRs (any non-`agent/*` head branch) always run.
|
|
25
|
-
if: >-
|
|
26
|
-
github.event.pull_request.draft == false &&
|
|
27
|
-
(
|
|
28
|
-
!startsWith(github.event.pull_request.head.ref, 'agent/') ||
|
|
29
|
-
contains(github.event.pull_request.labels.*.name, 'needs-review') ||
|
|
30
|
-
(github.event.action == 'labeled' && github.event.label.name == 'needs-review')
|
|
31
|
-
)
|
|
32
|
-
runs-on: ubuntu-latest
|
|
33
|
-
env:
|
|
34
|
-
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
|
35
|
-
steps:
|
|
36
|
-
- name: Skip when OPENAI_API_KEY is missing
|
|
37
|
-
if: ${{ env.OPENAI_API_KEY == '' }}
|
|
38
|
-
run: echo "OPENAI_API_KEY is not configured; skipping Code Review workflow."
|
|
39
|
-
|
|
40
|
-
- uses: anc95/ChatGPT-CodeReview@1e3df152c1b85c12da580b206c91ad343460c584 # v1.0.23
|
|
41
|
-
if: ${{ env.OPENAI_API_KEY != '' }}
|
|
42
|
-
env:
|
|
43
|
-
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
44
|
-
OPENAI_API_KEY: ${{ env.OPENAI_API_KEY }}
|
|
45
|
-
OPENAI_API_ENDPOINT: https://api.openai.com/v1
|
|
46
|
-
MODEL: gpt-4o-mini
|