@imdeadpool/guardex 7.0.43 → 7.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -0
- package/package.json +4 -1
- package/scripts/prepublish-bump-version.js +191 -0
- package/skills/gx-act/SKILL.md +82 -0
- package/src/agents/activity.js +279 -0
- package/src/agents/inspect.js +17 -4
- package/src/agents/launch.js +10 -1
- package/src/agents/status.js +9 -6
- package/src/budget/index.js +2 -1
- package/src/cli/args.js +118 -5
- package/src/cli/commands/agents.js +381 -0
- package/src/cli/commands/bootstrap.js +92 -0
- package/src/cli/commands/branch.js +127 -0
- package/src/cli/commands/claude.js +674 -0
- package/src/cli/commands/doctor.js +268 -0
- package/src/cli/commands/finish.js +26 -0
- package/src/cli/commands/mcp.js +122 -0
- package/src/cli/commands/misc.js +304 -0
- package/src/cli/commands/pr.js +439 -0
- package/src/cli/commands/prompt.js +92 -0
- package/src/cli/commands/release.js +305 -0
- package/src/cli/commands/report.js +244 -0
- package/src/cli/commands/review.js +32 -0
- package/src/cli/commands/setup.js +242 -0
- package/src/cli/commands/status.js +338 -0
- package/src/cli/commands/watch.js +234 -0
- package/src/cli/main.js +68 -3726
- package/src/cli/shared/repo-env.js +161 -0
- package/src/cli/shared/sandbox.js +417 -0
- package/src/cli/shared/scaffolding.js +535 -0
- package/src/cli/shared/toolchain-shims.js +420 -0
- package/src/context.js +229 -11
- package/src/core/runtime.js +6 -1
- package/src/doctor/index.js +42 -13
- package/src/finish/index.js +147 -5
- package/src/finish/preflight.js +177 -0
- package/src/finish/review-gate.js +182 -0
- package/src/git/index.js +446 -4
- package/src/hooks/index.js +0 -64
- package/src/mcp/collect.js +394 -0
- package/src/mcp/server.js +163 -0
- package/src/output/index.js +67 -1
- package/src/pr-review.js +23 -0
- package/src/pr.js +381 -0
- package/src/sandbox/index.js +13 -2
- package/src/scaffold/agent-worktree-prep.js +220 -0
- package/src/scaffold/index.js +108 -10
- package/src/scaffold/provision-config.js +314 -0
- package/src/speckit/index.js +226 -0
- package/src/terminal/index.js +1 -76
- package/src/terminal/kitty.js +20 -0
- package/src/terminal/tmux.js +9 -1
- package/src/toolchain/index.js +20 -0
- package/templates/AGENTS.monorepo-apps.md +26 -0
- package/templates/AGENTS.multiagent-safety.md +68 -344
- package/templates/AGENTS.multiagent-safety.min.md +11 -0
- package/templates/codex/skills/gx-act/SKILL.md +82 -0
- package/templates/githooks/pre-commit +22 -19
- package/templates/scripts/agent-branch-finish.sh +17 -33
- package/templates/scripts/agent-branch-merge.sh +4 -1
- package/templates/scripts/agent-branch-start.sh +115 -6
- package/templates/scripts/agent-file-locks.py +245 -50
- package/templates/scripts/agent-preflight.sh +31 -5
- package/templates/scripts/agent-worktree-prune.sh +1 -1
- package/templates/scripts/codex-agent.sh +0 -91
- package/src/agents/detect.js +0 -160
- package/src/cockpit/keybindings.js +0 -224
- package/src/cockpit/layout.js +0 -224
|
@@ -1,11 +1,20 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
2
|
"""Per-file lock registry for concurrent agent branches.
|
|
3
3
|
|
|
4
|
+
Locks are scoped by *owner identity* = (branch, agent). The agent dimension is
|
|
5
|
+
optional: pass `--agent <id>` or set GUARDEX_AGENT_ID. It exists so that two
|
|
6
|
+
agents sharing ONE worktree (and therefore one branch) can still hold distinct
|
|
7
|
+
claims against each other — without it the owner is the branch alone, so
|
|
8
|
+
same-branch agents never conflict and silently overwrite each other. When no
|
|
9
|
+
agent identity is supplied anywhere, behavior is byte-identical to branch-only
|
|
10
|
+
locking (every identity collapses to (branch, "")).
|
|
11
|
+
|
|
4
12
|
Usage examples:
|
|
5
13
|
gx locks claim --branch agent/a path/to/file1 path/to/file2
|
|
14
|
+
gx locks claim --branch agent/a --agent alice path/to/file1
|
|
6
15
|
gx locks claim --branch agent/a --allow-delete path/to/obsolete-file
|
|
7
16
|
gx locks allow-delete --branch agent/a path/to/obsolete-file
|
|
8
|
-
gx locks validate --branch agent/a --staged
|
|
17
|
+
gx locks validate --branch agent/a --agent alice --staged
|
|
9
18
|
gx locks release --branch agent/a
|
|
10
19
|
"""
|
|
11
20
|
|
|
@@ -16,13 +25,20 @@ import json
|
|
|
16
25
|
import os
|
|
17
26
|
import subprocess
|
|
18
27
|
import sys
|
|
28
|
+
from contextlib import contextmanager
|
|
19
29
|
from dataclasses import dataclass
|
|
20
30
|
from datetime import datetime, timezone
|
|
21
31
|
from pathlib import Path
|
|
22
32
|
from typing import Any
|
|
23
33
|
|
|
34
|
+
try:
|
|
35
|
+
import fcntl
|
|
36
|
+
except ImportError: # non-POSIX (e.g. Windows): cross-worktree locking degrades to best-effort
|
|
37
|
+
fcntl = None
|
|
38
|
+
|
|
24
39
|
|
|
25
40
|
LOCK_FILE_RELATIVE = Path('.omx/state/agent-file-locks.json')
|
|
41
|
+
AGENT_ID_ENV = 'GUARDEX_AGENT_ID'
|
|
26
42
|
CRITICAL_GUARDRAIL_PATHS = {
|
|
27
43
|
'AGENTS.md',
|
|
28
44
|
'.githooks/pre-commit',
|
|
@@ -39,6 +55,7 @@ class LockEntry:
|
|
|
39
55
|
branch: str
|
|
40
56
|
claimed_at: str
|
|
41
57
|
allow_delete: bool = False
|
|
58
|
+
agent: str = ''
|
|
42
59
|
|
|
43
60
|
|
|
44
61
|
class LockError(Exception):
|
|
@@ -79,6 +96,41 @@ def lock_file_path(repo_root: Path) -> Path:
|
|
|
79
96
|
return repo_root / LOCK_FILE_RELATIVE
|
|
80
97
|
|
|
81
98
|
|
|
99
|
+
def resolve_agent(args: argparse.Namespace) -> str:
|
|
100
|
+
"""Owner agent id: explicit --agent wins, else GUARDEX_AGENT_ID, else ''.
|
|
101
|
+
|
|
102
|
+
Empty string means "no agent identity" — the legacy branch-only owner.
|
|
103
|
+
"""
|
|
104
|
+
value = getattr(args, 'agent', None)
|
|
105
|
+
if not value:
|
|
106
|
+
value = os.environ.get(AGENT_ID_ENV, '')
|
|
107
|
+
return (value or '').strip()
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def owner_label(entry: dict[str, Any]) -> str:
|
|
111
|
+
branch = str(entry.get('branch', ''))
|
|
112
|
+
agent = str(entry.get('agent', ''))
|
|
113
|
+
return f'{branch} as {agent}' if agent else branch
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def owner_matches(entry: dict[str, Any], branch: str, agent: str) -> bool:
|
|
117
|
+
"""Does this branch+agent own the entry?
|
|
118
|
+
|
|
119
|
+
Branch must always match. The agent dimension is a *refinement*: when either
|
|
120
|
+
side is unscoped (agent == '' — the legacy branch-only owner) ownership falls
|
|
121
|
+
back to branch level, so anonymous callers and branch-wide operations keep
|
|
122
|
+
working and a named agent can adopt a pre-existing anonymous lock on its own
|
|
123
|
+
branch. Two DIFFERENT named agents on the same branch do not match — that is
|
|
124
|
+
the mutual exclusion this feature adds.
|
|
125
|
+
"""
|
|
126
|
+
if str(entry.get('branch', '')) != branch:
|
|
127
|
+
return False
|
|
128
|
+
entry_agent = str(entry.get('agent', ''))
|
|
129
|
+
if not agent or not entry_agent:
|
|
130
|
+
return True
|
|
131
|
+
return entry_agent == agent
|
|
132
|
+
|
|
133
|
+
|
|
82
134
|
def load_state(repo_root: Path) -> dict[str, Any]:
|
|
83
135
|
path = lock_file_path(repo_root)
|
|
84
136
|
if not path.exists():
|
|
@@ -94,7 +146,7 @@ def load_state(repo_root: Path) -> dict[str, Any]:
|
|
|
94
146
|
if not isinstance(locks, dict):
|
|
95
147
|
return {'locks': {}}
|
|
96
148
|
|
|
97
|
-
# Backward-compat normalization for older lock schema.
|
|
149
|
+
# Backward-compat normalization for older lock schema (no `agent` field).
|
|
98
150
|
normalized_locks: dict[str, dict[str, Any]] = {}
|
|
99
151
|
for file_path, entry in locks.items():
|
|
100
152
|
if not isinstance(entry, dict):
|
|
@@ -102,10 +154,12 @@ def load_state(repo_root: Path) -> dict[str, Any]:
|
|
|
102
154
|
branch = str(entry.get('branch', ''))
|
|
103
155
|
claimed_at = str(entry.get('claimed_at', ''))
|
|
104
156
|
allow_delete = bool(entry.get('allow_delete', False))
|
|
157
|
+
agent = str(entry.get('agent', ''))
|
|
105
158
|
normalized_locks[str(file_path)] = {
|
|
106
159
|
'branch': branch,
|
|
107
160
|
'claimed_at': claimed_at,
|
|
108
161
|
'allow_delete': allow_delete,
|
|
162
|
+
'agent': agent,
|
|
109
163
|
}
|
|
110
164
|
|
|
111
165
|
return {'locks': normalized_locks}
|
|
@@ -155,43 +209,140 @@ def staged_changes(repo_root: Path) -> list[tuple[str, str]]:
|
|
|
155
209
|
return results
|
|
156
210
|
|
|
157
211
|
|
|
212
|
+
def list_worktree_roots(repo_root: Path) -> list[Path]:
|
|
213
|
+
"""Every worktree path for this repo (porcelain), ALWAYS including the
|
|
214
|
+
caller's own repo_root. Submodules checked out inside a LINKED worktree
|
|
215
|
+
report their gitdir (<parent>/.git/worktrees/<wt>/modules/<sub>) as the
|
|
216
|
+
worktree path, not the actual working tree — repo_root (resolved via
|
|
217
|
+
--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. Falls
|
|
219
|
+
back to [repo_root] when git cannot enumerate."""
|
|
220
|
+
try:
|
|
221
|
+
out = run_git(['worktree', 'list', '--porcelain'], cwd=repo_root)
|
|
222
|
+
except LockError:
|
|
223
|
+
print('[agent-file-locks] Warning: `git worktree list` failed; enforcing locks for THIS worktree only.', file=sys.stderr)
|
|
224
|
+
return [repo_root]
|
|
225
|
+
roots: list[Path] = []
|
|
226
|
+
for line in out.splitlines():
|
|
227
|
+
if line.startswith('worktree '):
|
|
228
|
+
roots.append(Path(line[len('worktree '):].strip()).resolve())
|
|
229
|
+
if repo_root not in roots:
|
|
230
|
+
roots.append(repo_root)
|
|
231
|
+
return roots
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def load_all_locks(repo_root: Path) -> dict[str, list[dict[str, Any]]]:
|
|
235
|
+
"""Union of EVERY worktree's lock map: file path -> list of owner entries
|
|
236
|
+
(one per worktree that claims it). Each worktree owns a separate lock file on
|
|
237
|
+
disk, so a file's full ownership is only visible by reading them all. With a
|
|
238
|
+
single worktree this is exactly that worktree's own locks (unchanged)."""
|
|
239
|
+
merged: dict[str, list[dict[str, Any]]] = {}
|
|
240
|
+
for root in list_worktree_roots(repo_root):
|
|
241
|
+
try:
|
|
242
|
+
state = load_state(root)
|
|
243
|
+
except LockError:
|
|
244
|
+
print(f'[agent-file-locks] Warning: could not read the lock file in {root}; its claims are not enforced this run.', file=sys.stderr)
|
|
245
|
+
continue
|
|
246
|
+
for file_path, entry in state['locks'].items():
|
|
247
|
+
merged.setdefault(file_path, []).append(entry)
|
|
248
|
+
return merged
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def common_git_dir(repo_root: Path) -> Path:
|
|
252
|
+
"""Absolute git common dir — shared by every worktree of the repo."""
|
|
253
|
+
common = run_git(['rev-parse', '--git-common-dir'], cwd=repo_root)
|
|
254
|
+
path = Path(common)
|
|
255
|
+
if not path.is_absolute():
|
|
256
|
+
path = repo_root / path
|
|
257
|
+
return path.resolve()
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
@contextmanager
|
|
261
|
+
def cross_worktree_lock(repo_root: Path):
|
|
262
|
+
"""Exclusive OS lock shared by ALL worktrees of the repo (it lives in the
|
|
263
|
+
common git dir), so concurrent claim/release/validate runs — in the same or
|
|
264
|
+
different worktrees — are serialized. Without it, two claims race on the
|
|
265
|
+
read-modify-write of separate lock files and can both win the same path or
|
|
266
|
+
drop each other's writes. Best-effort: a no-op where fcntl is unavailable or
|
|
267
|
+
the lock file can't be created, so locking never hard-fails a command."""
|
|
268
|
+
if fcntl is None:
|
|
269
|
+
yield
|
|
270
|
+
return
|
|
271
|
+
try:
|
|
272
|
+
lock_path = common_git_dir(repo_root) / 'agent-file-locks.lock'
|
|
273
|
+
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
|
274
|
+
handle = open(lock_path, 'w')
|
|
275
|
+
except (OSError, LockError):
|
|
276
|
+
yield
|
|
277
|
+
return
|
|
278
|
+
locked = False
|
|
279
|
+
try:
|
|
280
|
+
try:
|
|
281
|
+
fcntl.flock(handle.fileno(), fcntl.LOCK_EX)
|
|
282
|
+
locked = True
|
|
283
|
+
except OSError:
|
|
284
|
+
pass # e.g. NFS / fd limits: run unserialized rather than crash the command
|
|
285
|
+
yield
|
|
286
|
+
finally:
|
|
287
|
+
try:
|
|
288
|
+
if locked:
|
|
289
|
+
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
|
|
290
|
+
finally:
|
|
291
|
+
handle.close()
|
|
292
|
+
|
|
293
|
+
|
|
158
294
|
def cmd_claim(args: argparse.Namespace, repo_root: Path) -> int:
|
|
159
295
|
state = load_state(repo_root)
|
|
160
296
|
locks: dict[str, dict[str, Any]] = state['locks']
|
|
161
297
|
|
|
298
|
+
claim_agent = resolve_agent(args)
|
|
162
299
|
files = [normalize_repo_path(repo_root, p) for p in args.files]
|
|
163
300
|
conflicts: list[tuple[str, str]] = []
|
|
164
301
|
|
|
302
|
+
# Conflict detection spans EVERY worktree of the repo, not just this one: a
|
|
303
|
+
# file claimed by another owner in a sibling worktree must still block this
|
|
304
|
+
# claim (each worktree keeps a separate lock file). The write below still
|
|
305
|
+
# records the claim in THIS worktree's lock file.
|
|
306
|
+
all_locks = load_all_locks(repo_root)
|
|
165
307
|
for file_path in files:
|
|
166
|
-
|
|
167
|
-
if
|
|
168
|
-
conflicts.append((file_path,
|
|
308
|
+
foreign = [e for e in all_locks.get(file_path, []) if not owner_matches(e, args.branch, claim_agent)]
|
|
309
|
+
if foreign:
|
|
310
|
+
conflicts.append((file_path, owner_label(foreign[0])))
|
|
169
311
|
|
|
170
312
|
if conflicts:
|
|
171
|
-
print('[agent-file-locks] Cannot claim files already locked by
|
|
172
|
-
for file_path,
|
|
173
|
-
print(f' - {file_path} (locked by {
|
|
313
|
+
print('[agent-file-locks] Cannot claim files already locked by another owner:', file=sys.stderr)
|
|
314
|
+
for file_path, owner in conflicts:
|
|
315
|
+
print(f' - {file_path} (locked by {owner})', file=sys.stderr)
|
|
174
316
|
return 1
|
|
175
317
|
|
|
176
318
|
for file_path in files:
|
|
177
319
|
existing = locks.get(file_path, {})
|
|
178
320
|
existing_allow_delete = bool(existing.get('allow_delete', False))
|
|
321
|
+
# A named claim adopts/upgrades the entry's agent; an anonymous claim
|
|
322
|
+
# keeps any existing agent rather than silently downgrading it.
|
|
323
|
+
resolved_owner_agent = claim_agent or str(existing.get('agent', ''))
|
|
179
324
|
locks[file_path] = LockEntry(
|
|
180
325
|
branch=args.branch,
|
|
181
326
|
claimed_at=now_iso(),
|
|
182
327
|
allow_delete=args.allow_delete or existing_allow_delete,
|
|
328
|
+
agent=resolved_owner_agent,
|
|
183
329
|
).__dict__
|
|
184
330
|
|
|
185
331
|
write_state(repo_root, state)
|
|
186
332
|
delete_note = ' (delete-approved)' if args.allow_delete else ''
|
|
187
|
-
|
|
333
|
+
agent_note = f' as {claim_agent}' if claim_agent else ''
|
|
334
|
+
print(f"[agent-file-locks] Claimed {len(files)} file(s) for {args.branch}{agent_note}{delete_note}.")
|
|
188
335
|
return 0
|
|
189
336
|
|
|
190
337
|
|
|
191
338
|
def cmd_allow_delete(args: argparse.Namespace, repo_root: Path) -> int:
|
|
339
|
+
# Operates on THIS worktree's lock file only — run it from the worktree where
|
|
340
|
+
# the claim was made. (claim/validate union across worktrees; the write side
|
|
341
|
+
# stays local.)
|
|
192
342
|
state = load_state(repo_root)
|
|
193
343
|
locks: dict[str, dict[str, Any]] = state['locks']
|
|
194
344
|
files = [normalize_repo_path(repo_root, p) for p in args.files]
|
|
345
|
+
agent = resolve_agent(args)
|
|
195
346
|
|
|
196
347
|
missing: list[str] = []
|
|
197
348
|
foreign: list[tuple[str, str]] = []
|
|
@@ -200,9 +351,8 @@ def cmd_allow_delete(args: argparse.Namespace, repo_root: Path) -> int:
|
|
|
200
351
|
if not entry:
|
|
201
352
|
missing.append(file_path)
|
|
202
353
|
continue
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
foreign.append((file_path, owner))
|
|
354
|
+
if not owner_matches(entry, args.branch, agent):
|
|
355
|
+
foreign.append((file_path, owner_label(entry)))
|
|
206
356
|
continue
|
|
207
357
|
entry['allow_delete'] = True
|
|
208
358
|
|
|
@@ -212,7 +362,7 @@ def cmd_allow_delete(args: argparse.Namespace, repo_root: Path) -> int:
|
|
|
212
362
|
for file_path in missing:
|
|
213
363
|
print(f' - {file_path}', file=sys.stderr)
|
|
214
364
|
if foreign:
|
|
215
|
-
print('[agent-file-locks] Cannot enable delete: files are owned by another
|
|
365
|
+
print('[agent-file-locks] Cannot enable delete: files are owned by another owner:', file=sys.stderr)
|
|
216
366
|
for file_path, owner in foreign:
|
|
217
367
|
print(f' - {file_path} (owner: {owner})', file=sys.stderr)
|
|
218
368
|
return 1
|
|
@@ -223,15 +373,18 @@ def cmd_allow_delete(args: argparse.Namespace, repo_root: Path) -> int:
|
|
|
223
373
|
|
|
224
374
|
|
|
225
375
|
def cmd_release(args: argparse.Namespace, repo_root: Path) -> int:
|
|
376
|
+
# Local-only, like allow-delete: releases claims recorded in THIS worktree's
|
|
377
|
+
# lock file. Run it from the worktree that made the claim.
|
|
226
378
|
state = load_state(repo_root)
|
|
227
379
|
locks: dict[str, dict[str, Any]] = state['locks']
|
|
380
|
+
agent = resolve_agent(args)
|
|
228
381
|
|
|
229
382
|
to_release: set[str]
|
|
230
383
|
if args.files:
|
|
231
384
|
requested = {normalize_repo_path(repo_root, p) for p in args.files}
|
|
232
|
-
to_release = {p for p in requested if locks.get(p, {})
|
|
385
|
+
to_release = {p for p in requested if owner_matches(locks.get(p, {}), args.branch, agent)}
|
|
233
386
|
else:
|
|
234
|
-
to_release = {p for p, entry in locks.items() if entry
|
|
387
|
+
to_release = {p for p, entry in locks.items() if owner_matches(entry, args.branch, agent)}
|
|
235
388
|
|
|
236
389
|
for file_path in to_release:
|
|
237
390
|
locks.pop(file_path, None)
|
|
@@ -242,32 +395,47 @@ def cmd_release(args: argparse.Namespace, repo_root: Path) -> int:
|
|
|
242
395
|
|
|
243
396
|
|
|
244
397
|
def cmd_status(args: argparse.Namespace, repo_root: Path) -> int:
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
398
|
+
# Union across worktrees so status reflects what claim/validate now enforce —
|
|
399
|
+
# a sibling worktree's claims would otherwise be invisible here.
|
|
400
|
+
agent_filter = resolve_agent(args)
|
|
401
|
+
roots = list_worktree_roots(repo_root)
|
|
402
|
+
|
|
403
|
+
rows: list[tuple[str, str, str, str, bool, str]] = []
|
|
404
|
+
for root in roots:
|
|
405
|
+
try:
|
|
406
|
+
locks = load_state(root)['locks']
|
|
407
|
+
except LockError:
|
|
252
408
|
continue
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
409
|
+
for file_path, entry in locks.items():
|
|
410
|
+
branch = str(entry.get('branch', ''))
|
|
411
|
+
if args.branch and branch != args.branch:
|
|
412
|
+
continue
|
|
413
|
+
agent = str(entry.get('agent', ''))
|
|
414
|
+
if agent_filter and agent != agent_filter:
|
|
415
|
+
continue
|
|
416
|
+
claimed_at = str(entry.get('claimed_at', ''))
|
|
417
|
+
allow_delete = bool(entry.get('allow_delete', False))
|
|
418
|
+
rows.append((file_path, branch, agent, claimed_at, allow_delete, str(root)))
|
|
419
|
+
rows.sort()
|
|
256
420
|
|
|
257
421
|
if not rows:
|
|
258
422
|
print('[agent-file-locks] No active locks.')
|
|
259
423
|
return 0
|
|
260
424
|
|
|
425
|
+
multi = len(roots) > 1
|
|
261
426
|
print('[agent-file-locks] Active locks:')
|
|
262
|
-
for file_path, branch, claimed_at, allow_delete in rows:
|
|
427
|
+
for file_path, branch, agent, claimed_at, allow_delete, worktree in rows:
|
|
263
428
|
delete_flag = ' delete-ok' if allow_delete else ''
|
|
264
|
-
|
|
429
|
+
agent_flag = f' [{agent}]' if agent else ''
|
|
430
|
+
# Annotate the worktree only when there is more than one, so a single-
|
|
431
|
+
# worktree repo's output is unchanged.
|
|
432
|
+
wt_flag = f' @ {worktree}' if multi else ''
|
|
433
|
+
print(f' - {file_path} | {branch}{agent_flag} | {claimed_at}{delete_flag}{wt_flag}')
|
|
265
434
|
return 0
|
|
266
435
|
|
|
267
436
|
|
|
268
437
|
def cmd_validate(args: argparse.Namespace, repo_root: Path) -> int:
|
|
269
|
-
|
|
270
|
-
locks: dict[str, dict[str, Any]] = state['locks']
|
|
438
|
+
agent = resolve_agent(args)
|
|
271
439
|
|
|
272
440
|
if args.staged:
|
|
273
441
|
file_changes = staged_changes(repo_root)
|
|
@@ -289,35 +457,39 @@ def cmd_validate(args: argparse.Namespace, repo_root: Path) -> int:
|
|
|
289
457
|
|
|
290
458
|
allow_guardrail_delete = env_truthy(os.environ.get(ALLOW_GUARDRAIL_DELETE_ENV))
|
|
291
459
|
|
|
460
|
+
# Enforce claims across ALL worktrees: a file owned by another agent in a
|
|
461
|
+
# sibling worktree blocks this commit, not just one claimed in this worktree.
|
|
462
|
+
all_locks = load_all_locks(repo_root)
|
|
292
463
|
for status, file_path in file_changes:
|
|
293
|
-
|
|
294
|
-
if not
|
|
464
|
+
owners = all_locks.get(file_path, [])
|
|
465
|
+
if not owners:
|
|
295
466
|
missing.append(file_path)
|
|
296
467
|
continue
|
|
297
468
|
|
|
298
|
-
|
|
299
|
-
if
|
|
300
|
-
foreign.append((file_path,
|
|
469
|
+
foreign_owners = [e for e in owners if not owner_matches(e, args.branch, agent)]
|
|
470
|
+
if foreign_owners:
|
|
471
|
+
foreign.append((file_path, owner_label(foreign_owners[0])))
|
|
301
472
|
continue
|
|
302
473
|
|
|
303
474
|
if status == 'D':
|
|
304
475
|
if file_path in CRITICAL_GUARDRAIL_PATHS and not allow_guardrail_delete:
|
|
305
476
|
guardrail_delete_blocked.append(file_path)
|
|
306
477
|
|
|
307
|
-
|
|
478
|
+
mine = next((e for e in owners if owner_matches(e, args.branch, agent)), None)
|
|
479
|
+
allow_delete = bool(mine.get('allow_delete', False)) if mine else False
|
|
308
480
|
if not allow_delete:
|
|
309
481
|
delete_not_allowed.append(file_path)
|
|
310
482
|
|
|
311
483
|
if not missing and not foreign and not delete_not_allowed and not guardrail_delete_blocked:
|
|
312
484
|
return 0
|
|
313
485
|
|
|
314
|
-
print('[agent-file-locks] Commit blocked: staged files must be safely claimed by this
|
|
486
|
+
print('[agent-file-locks] Commit blocked: staged files must be safely claimed by this owner first.', file=sys.stderr)
|
|
315
487
|
if missing:
|
|
316
488
|
print(' Unclaimed files:', file=sys.stderr)
|
|
317
489
|
for file_path in missing:
|
|
318
490
|
print(f' - {file_path}', file=sys.stderr)
|
|
319
491
|
if foreign:
|
|
320
|
-
print(' Files claimed by another
|
|
492
|
+
print(' Files claimed by another owner:', file=sys.stderr)
|
|
321
493
|
for file_path, owner in foreign:
|
|
322
494
|
print(f' - {file_path} (owner: {owner})', file=sys.stderr)
|
|
323
495
|
if delete_not_allowed:
|
|
@@ -347,12 +519,21 @@ def cmd_validate(args: argparse.Namespace, repo_root: Path) -> int:
|
|
|
347
519
|
return 1
|
|
348
520
|
|
|
349
521
|
|
|
522
|
+
def add_agent_arg(parser: argparse.ArgumentParser) -> None:
|
|
523
|
+
parser.add_argument(
|
|
524
|
+
'--agent',
|
|
525
|
+
default=None,
|
|
526
|
+
help=f'Owner agent id (defaults to ${AGENT_ID_ENV}); scopes ownership within a shared branch',
|
|
527
|
+
)
|
|
528
|
+
|
|
529
|
+
|
|
350
530
|
def build_parser() -> argparse.ArgumentParser:
|
|
351
531
|
parser = argparse.ArgumentParser(description='Concurrent agent file-lock utility')
|
|
352
532
|
sub = parser.add_subparsers(dest='command', required=True)
|
|
353
533
|
|
|
354
534
|
claim = sub.add_parser('claim', help='Claim file locks for a branch')
|
|
355
535
|
claim.add_argument('--branch', required=True, help='Owner branch name (e.g., agent/foo/...)')
|
|
536
|
+
add_agent_arg(claim)
|
|
356
537
|
claim.add_argument(
|
|
357
538
|
'--allow-delete',
|
|
358
539
|
action='store_true',
|
|
@@ -362,42 +543,56 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
362
543
|
|
|
363
544
|
allow_delete = sub.add_parser('allow-delete', help='Enable delete approval on already claimed files')
|
|
364
545
|
allow_delete.add_argument('--branch', required=True, help='Owner branch name')
|
|
546
|
+
add_agent_arg(allow_delete)
|
|
365
547
|
allow_delete.add_argument('files', nargs='+', help='Files to mark as delete-approved')
|
|
366
548
|
|
|
367
549
|
release = sub.add_parser('release', help='Release file locks for a branch')
|
|
368
550
|
release.add_argument('--branch', required=True, help='Owner branch name')
|
|
551
|
+
add_agent_arg(release)
|
|
369
552
|
release.add_argument('files', nargs='*', help='Optional files; omit to release all branch locks')
|
|
370
553
|
|
|
371
554
|
status = sub.add_parser('status', help='Show lock status')
|
|
372
555
|
status.add_argument('--branch', help='Filter by branch')
|
|
556
|
+
add_agent_arg(status)
|
|
373
557
|
|
|
374
558
|
validate = sub.add_parser('validate', help='Validate staged files are locked by branch')
|
|
375
559
|
validate.add_argument('--branch', required=True, help='Owner branch name')
|
|
560
|
+
add_agent_arg(validate)
|
|
376
561
|
validate.add_argument('--staged', action='store_true', help='Validate staged files from git index')
|
|
377
562
|
validate.add_argument('files', nargs='*', help='Files to validate when --staged is not used')
|
|
378
563
|
|
|
379
564
|
return parser
|
|
380
565
|
|
|
381
566
|
|
|
567
|
+
def dispatch_command(args: argparse.Namespace, repo_root: Path) -> int:
|
|
568
|
+
if args.command == 'claim':
|
|
569
|
+
return cmd_claim(args, repo_root)
|
|
570
|
+
if args.command == 'allow-delete':
|
|
571
|
+
return cmd_allow_delete(args, repo_root)
|
|
572
|
+
if args.command == 'release':
|
|
573
|
+
return cmd_release(args, repo_root)
|
|
574
|
+
if args.command == 'status':
|
|
575
|
+
return cmd_status(args, repo_root)
|
|
576
|
+
if args.command == 'validate':
|
|
577
|
+
if not args.staged and not args.files:
|
|
578
|
+
raise LockError('validate requires --staged or one or more file paths')
|
|
579
|
+
return cmd_validate(args, repo_root)
|
|
580
|
+
raise LockError(f'Unknown command: {args.command}')
|
|
581
|
+
|
|
582
|
+
|
|
382
583
|
def main() -> int:
|
|
383
584
|
parser = build_parser()
|
|
384
585
|
args = parser.parse_args()
|
|
385
586
|
|
|
386
587
|
try:
|
|
387
588
|
repo_root = resolve_repo_root()
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
return cmd_status(args, repo_root)
|
|
396
|
-
if args.command == 'validate':
|
|
397
|
-
if not args.staged and not args.files:
|
|
398
|
-
raise LockError('validate requires --staged or one or more file paths')
|
|
399
|
-
return cmd_validate(args, repo_root)
|
|
400
|
-
raise LockError(f'Unknown command: {args.command}')
|
|
589
|
+
# Serialize state-changing commands (and validate's snapshot read) across
|
|
590
|
+
# ALL worktrees with one shared lock, so concurrent runs can't clobber
|
|
591
|
+
# each other or both win the same file. status is a pure read -> unlocked.
|
|
592
|
+
if args.command in {'claim', 'allow-delete', 'release', 'validate'}:
|
|
593
|
+
with cross_worktree_lock(repo_root):
|
|
594
|
+
return dispatch_command(args, repo_root)
|
|
595
|
+
return dispatch_command(args, repo_root)
|
|
401
596
|
except LockError as exc:
|
|
402
597
|
print(f'[agent-file-locks] {exc}', file=sys.stderr)
|
|
403
598
|
return 2
|
|
@@ -22,17 +22,43 @@ set -euo pipefail
|
|
|
22
22
|
repo_root="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
|
|
23
23
|
cd "$repo_root"
|
|
24
24
|
|
|
25
|
-
ran=0
|
|
25
|
+
ran=0 # steps that PASSED
|
|
26
|
+
attempted=0 # steps that RAN (pass or fail) — drives stack detection
|
|
26
27
|
fail=0
|
|
28
|
+
# Quiet by default: a green `npm test` run can be hundreds of lines of TAP that
|
|
29
|
+
# floods the agent's context on every `gx branch finish`. Capture each step's
|
|
30
|
+
# output, print a one-line summary on success, and surface only the tail on
|
|
31
|
+
# failure (where it is actually useful). Stream full output live with
|
|
32
|
+
# GUARDEX_PREFLIGHT_VERBOSE=1.
|
|
33
|
+
GUARDEX_PREFLIGHT_FAIL_TAIL="${GUARDEX_PREFLIGHT_FAIL_TAIL:-40}"
|
|
27
34
|
run_step() {
|
|
28
35
|
local label="$1"
|
|
29
36
|
shift
|
|
30
37
|
echo "[agent-preflight] -> $label"
|
|
31
|
-
|
|
38
|
+
attempted=$((attempted + 1))
|
|
39
|
+
if [[ "${GUARDEX_PREFLIGHT_VERBOSE:-0}" == "1" ]]; then
|
|
40
|
+
if "$@"; then
|
|
41
|
+
ran=$((ran + 1))
|
|
42
|
+
echo "[agent-preflight] ok"
|
|
43
|
+
else
|
|
44
|
+
echo "[agent-preflight] FAIL: $label" >&2
|
|
45
|
+
fail=1
|
|
46
|
+
fi
|
|
47
|
+
return 0
|
|
48
|
+
fi
|
|
49
|
+
local out rc
|
|
50
|
+
# `if` keeps `set -e` from aborting on a failing step before we capture rc.
|
|
51
|
+
if out="$("$@" 2>&1)"; then
|
|
52
|
+
rc=0
|
|
53
|
+
else
|
|
54
|
+
rc=$?
|
|
55
|
+
fi
|
|
56
|
+
if [[ "$rc" -eq 0 ]]; then
|
|
32
57
|
ran=$((ran + 1))
|
|
33
|
-
echo "[agent-preflight] ok"
|
|
58
|
+
echo "[agent-preflight] ok ($(printf '%s\n' "$out" | wc -l | tr -d ' ') lines suppressed; GUARDEX_PREFLIGHT_VERBOSE=1 to show)"
|
|
34
59
|
else
|
|
35
|
-
echo "[agent-preflight] FAIL: $label" >&2
|
|
60
|
+
echo "[agent-preflight] FAIL: $label (exit $rc) — last ${GUARDEX_PREFLIGHT_FAIL_TAIL} lines:" >&2
|
|
61
|
+
printf '%s\n' "$out" | tail -n "$GUARDEX_PREFLIGHT_FAIL_TAIL" >&2
|
|
36
62
|
fail=1
|
|
37
63
|
fi
|
|
38
64
|
}
|
|
@@ -74,7 +100,7 @@ if [[ -f pyproject.toml ]] && command -v ruff >/dev/null 2>&1; then
|
|
|
74
100
|
run_step "ruff check" ruff check .
|
|
75
101
|
fi
|
|
76
102
|
|
|
77
|
-
if [[ "$
|
|
103
|
+
if [[ "$attempted" -eq 0 ]]; then
|
|
78
104
|
echo "[agent-preflight] No recognized project stack detected; skipping checks." >&2
|
|
79
105
|
exit 0
|
|
80
106
|
fi
|
|
@@ -253,7 +253,7 @@ branch_has_worktree() {
|
|
|
253
253
|
# content matches these are considered clean for prune purposes. Mirrors the
|
|
254
254
|
# auto-transfer + auto-resolve allowlist from PRs #546/#547 (state-file globs
|
|
255
255
|
# never carry authoritative content out of an agent branch).
|
|
256
|
-
WORKTREE_STATE_EXCLUDE_GLOBS_DEFAULT='.omc/**:.omx/state/**:.dev-ports.json:apps/logs/**:.
|
|
256
|
+
WORKTREE_STATE_EXCLUDE_GLOBS_DEFAULT='.omc/**:.omx/state/**:.dev-ports.json:apps/logs/**:.codex/settings.local.json:.claude/settings.local.json:.codex/state/**:.claude/state/**'
|
|
257
257
|
WORKTREE_STATE_EXCLUDE_GLOBS_RAW="${GUARDEX_PRUNE_STATE_EXCLUDE_GLOBS-$WORKTREE_STATE_EXCLUDE_GLOBS_DEFAULT}"
|
|
258
258
|
|
|
259
259
|
build_state_exclude_pathspec_args() {
|