@imdeadpool/guardex 8.4.4 → 8.4.6
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/package.json +2 -2
- package/src/cli/commands/pr.js +11 -0
- package/src/cli/shared-locks.js +7 -0
- package/src/pr.js +11 -10
- package/templates/scripts/agent-file-locks.py +251 -31
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@imdeadpool/guardex",
|
|
3
|
-
"version": "8.4.
|
|
3
|
+
"version": "8.4.6",
|
|
4
4
|
"description": "Guardian T-Rex for your multi-agent repo. Isolated worktrees, file locks, and PR-only merges stop parallel Codex & Claude agents from overwriting each other's work. Auto-wires Oh My Codex, Oh My Claude, OpenSpec, and Caveman.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"preferGlobal": true,
|
|
@@ -97,5 +97,5 @@
|
|
|
97
97
|
"jsonc-parser": "3.3.1",
|
|
98
98
|
"semver": "7.7.4"
|
|
99
99
|
},
|
|
100
|
-
"gitHead": "
|
|
100
|
+
"gitHead": "a8a451a154513fecd94b366f5e57dd84c55a7a58"
|
|
101
101
|
}
|
package/src/cli/commands/pr.js
CHANGED
|
@@ -123,6 +123,8 @@ function renderChecksLine(checks) {
|
|
|
123
123
|
if (checks.pending) parts.push(`${checks.pending} pending`);
|
|
124
124
|
if (checks.failed) parts.push(`${checks.failed} failed`);
|
|
125
125
|
if (checks.cancelled) parts.push(`${checks.cancelled} cancelled`);
|
|
126
|
+
if (checks.waived) parts.push(`${checks.waived} did not start (GitHub billing)`);
|
|
127
|
+
if (checks.skipped) parts.push(`${checks.skipped} skipped`);
|
|
126
128
|
if (checks.other) parts.push(`${checks.other} other`);
|
|
127
129
|
return parts.length ? parts.join(', ') : `${checks.total} checks`;
|
|
128
130
|
}
|
|
@@ -295,6 +297,15 @@ async function cmdWatch(opts) {
|
|
|
295
297
|
logError(`CI checks failed. Investigate the PR before retrying.${buildChecksFailedDetail(result.pr)}`);
|
|
296
298
|
return;
|
|
297
299
|
}
|
|
300
|
+
if (result.status === 'billing-blocked') {
|
|
301
|
+
process.exitCode = 2;
|
|
302
|
+
logError(
|
|
303
|
+
`GitHub Actions did not start due to billing or a spending limit${buildTimeoutDetail(result.pr)}. ` +
|
|
304
|
+
'Restore Actions and rerun CI, or use the review-gated finish with a trusted base preflight. ' +
|
|
305
|
+
'GitHub merge requirements still apply.',
|
|
306
|
+
);
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
298
309
|
if (result.status === 'timeout') {
|
|
299
310
|
process.exitCode = 3;
|
|
300
311
|
logWarn(`Timed out waiting for PR to merge.${buildTimeoutDetail(result.pr)}`);
|
package/src/cli/shared-locks.js
CHANGED
|
@@ -261,6 +261,10 @@ function locks(rawArgs) {
|
|
|
261
261
|
const { target, passthrough } = extractTargetedArgs(rawArgs);
|
|
262
262
|
const repoRoot = resolveRepoRoot(target);
|
|
263
263
|
const [command, ...rest] = passthrough;
|
|
264
|
+
if (['handoff-request', 'handoff-approve'].includes(command)
|
|
265
|
+
&& repoRoot !== resolveRepoRoot(process.cwd())) {
|
|
266
|
+
throw new Error('Run handoff requests and approvals from your own checked-out worktree.');
|
|
267
|
+
}
|
|
264
268
|
if (command === 'shared-enable') {
|
|
265
269
|
const state = sharedGitState.enable(repoRoot, parseSharedRemote(rest));
|
|
266
270
|
process.stdout.write(`[${TOOL_NAME}] Shared Git state enabled via ${state.remote}.\n`);
|
|
@@ -292,6 +296,9 @@ function locks(rawArgs) {
|
|
|
292
296
|
}
|
|
293
297
|
|
|
294
298
|
const state = sharedGitState.settings(repoRoot);
|
|
299
|
+
if (state.enabled && ['handoff-request', 'handoff-approve', 'handoffs'].includes(command)) {
|
|
300
|
+
throw new Error('Lock handoffs are only supported for local worktrees, not shared Git locks.');
|
|
301
|
+
}
|
|
295
302
|
if (
|
|
296
303
|
!state.enabled ||
|
|
297
304
|
!['claim', 'allow-delete', 'release', 'validate', 'status'].includes(command)
|
package/src/pr.js
CHANGED
|
@@ -609,9 +609,8 @@ async function watchPullRequest(options) {
|
|
|
609
609
|
|
|
610
610
|
// eslint-disable-next-line no-constant-condition
|
|
611
611
|
while (true) {
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
if (!open) {
|
|
612
|
+
const snapshot = getPullRequestStatus(repoRoot, branch);
|
|
613
|
+
if (!snapshot) {
|
|
615
614
|
const latest = findLatestPrForBranch(repoRoot, branch);
|
|
616
615
|
if (latest && latest.state === 'MERGED') {
|
|
617
616
|
onEvent({ phase: 'merged', pr: latest });
|
|
@@ -625,19 +624,21 @@ async function watchPullRequest(options) {
|
|
|
625
624
|
return { status: 'no-pr', pr: null };
|
|
626
625
|
}
|
|
627
626
|
|
|
628
|
-
const snapshot = getPullRequestStatus(repoRoot, branch);
|
|
629
627
|
onEvent({ phase: 'polling', pr: snapshot });
|
|
630
628
|
|
|
631
|
-
|
|
629
|
+
const { checks } = snapshot;
|
|
630
|
+
if (checks.failed > 0 || checks.cancelled > 0) {
|
|
632
631
|
return { status: 'checks-failed', pr: snapshot };
|
|
633
632
|
}
|
|
633
|
+
if (checks.waived > 0 && checks.pending === 0) {
|
|
634
|
+
return { status: 'billing-blocked', pr: snapshot };
|
|
635
|
+
}
|
|
634
636
|
if (
|
|
635
|
-
snapshot
|
|
636
|
-
&& !snapshot.isDraft
|
|
637
|
+
!snapshot.isDraft
|
|
637
638
|
&& snapshot.mergeable === 'MERGEABLE'
|
|
638
|
-
&& snapshot.
|
|
639
|
-
&&
|
|
640
|
-
&&
|
|
639
|
+
&& (snapshot.mergeStateStatus === 'CLEAN' || snapshot.mergeStateStatus === 'HAS_HOOKS')
|
|
640
|
+
&& checks.total > 0
|
|
641
|
+
&& checks.success + (checks.skipped || 0) === checks.total
|
|
641
642
|
) {
|
|
642
643
|
// CI is green and PR is non-draft + mergeable; the merge itself will be
|
|
643
644
|
// driven by auto-merge or a separate `gh pr merge` invocation.
|
|
@@ -34,6 +34,7 @@ from dataclasses import dataclass
|
|
|
34
34
|
from datetime import datetime, timezone
|
|
35
35
|
from pathlib import Path
|
|
36
36
|
from typing import Any
|
|
37
|
+
from uuid import uuid4
|
|
37
38
|
|
|
38
39
|
try:
|
|
39
40
|
import fcntl
|
|
@@ -79,6 +80,13 @@ class LockError(Exception):
|
|
|
79
80
|
pass
|
|
80
81
|
|
|
81
82
|
|
|
83
|
+
@dataclass
|
|
84
|
+
class ClaimConflict(Exception):
|
|
85
|
+
conflicts: list[tuple[str, dict[str, Any]]]
|
|
86
|
+
agent: str
|
|
87
|
+
stale: bool
|
|
88
|
+
|
|
89
|
+
|
|
82
90
|
def run_git(args: list[str], cwd: Path) -> str:
|
|
83
91
|
result = subprocess.run(
|
|
84
92
|
['git', *args],
|
|
@@ -206,13 +214,34 @@ def load_state(repo_root: Path) -> dict[str, Any]:
|
|
|
206
214
|
'allow_delete': allow_delete,
|
|
207
215
|
'agent': agent,
|
|
208
216
|
'pane': pane,
|
|
217
|
+
**{key: entry[key] for key in ('handoff_id', 'handoff_commit', 'handoff_check') if key in entry},
|
|
209
218
|
}
|
|
210
219
|
|
|
211
220
|
return {'locks': normalized_locks}
|
|
212
221
|
|
|
213
222
|
|
|
214
223
|
def write_state(repo_root: Path, state: dict[str, Any]) -> None:
|
|
215
|
-
|
|
224
|
+
# Preserve an interrupted transfer's receipt before the recipient can
|
|
225
|
+
# release, reap, or replace its only durable completion marker.
|
|
226
|
+
for file_path, existing in load_state(repo_root)['locks'].items():
|
|
227
|
+
request_id = existing.get('handoff_id')
|
|
228
|
+
replacement = state['locks'].get(file_path, {})
|
|
229
|
+
if (not isinstance(request_id, str) or not re.fullmatch(r'[a-f0-9]{32}', request_id)
|
|
230
|
+
or replacement.get('handoff_id') == request_id):
|
|
231
|
+
continue
|
|
232
|
+
receipt = handoff_dir(repo_root) / f'{request_id}.json'
|
|
233
|
+
request = read_handoff(receipt)
|
|
234
|
+
if request.get('commit'):
|
|
235
|
+
continue
|
|
236
|
+
owner = request['owner']
|
|
237
|
+
source = Path(owner['_worktree'])
|
|
238
|
+
source_entry = load_state(source)['locks'].get(file_path)
|
|
239
|
+
if not source_entry or (source == repo_root and source_entry.get('handoff_id') == request_id):
|
|
240
|
+
record_handoff(receipt, request, existing)
|
|
241
|
+
write_json(lock_file_path(repo_root), state)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def write_json(path: Path, state: dict[str, Any]) -> None:
|
|
216
245
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
217
246
|
tmp = path.with_suffix(path.suffix + '.tmp')
|
|
218
247
|
tmp.write_text(json.dumps(state, indent=2, sort_keys=True) + '\n')
|
|
@@ -303,6 +332,30 @@ def get_worktree_branch(worktree: Path) -> str | None:
|
|
|
303
332
|
return None
|
|
304
333
|
|
|
305
334
|
|
|
335
|
+
def open_pr_links(repo_root: Path, branches: set[str]) -> dict[str, str]:
|
|
336
|
+
"""Best-effort hints only; a forge outage never grants ownership."""
|
|
337
|
+
gh = os.environ.get(LOCK_GH_BIN_ENV) or shutil.which('gh')
|
|
338
|
+
if not gh:
|
|
339
|
+
return {}
|
|
340
|
+
try:
|
|
341
|
+
run_git(['remote', 'get-url', 'origin'], cwd=repo_root)
|
|
342
|
+
result = subprocess.run(
|
|
343
|
+
[gh, 'pr', 'list', '--state', 'open', '--limit', '100', '--json', 'headRefName,url,isCrossRepository'],
|
|
344
|
+
capture_output=True, text=True, cwd=repo_root, timeout=2, check=False,
|
|
345
|
+
)
|
|
346
|
+
if result.returncode != 0:
|
|
347
|
+
return {}
|
|
348
|
+
rows = json.loads(result.stdout)
|
|
349
|
+
return {
|
|
350
|
+
row['headRefName']: row['url'] for row in rows
|
|
351
|
+
if isinstance(row, dict) and isinstance(row.get('headRefName'), str) and row['headRefName'] in branches
|
|
352
|
+
and row.get('isCrossRepository') is False
|
|
353
|
+
and isinstance(row.get('url'), str) and re.fullmatch(r'https://[^\s]+', row['url'])
|
|
354
|
+
} if isinstance(rows, list) else {}
|
|
355
|
+
except (LockError, OSError, subprocess.TimeoutExpired, ValueError):
|
|
356
|
+
return {}
|
|
357
|
+
|
|
358
|
+
|
|
306
359
|
def is_branch_merged_via_gh(branch: str, gh_bin: str) -> bool | None:
|
|
307
360
|
"""Ask the forge whether `branch` has at least one merged PR.
|
|
308
361
|
|
|
@@ -683,32 +736,7 @@ def cmd_claim(args: argparse.Namespace, repo_root: Path, adaptive_owner: str) ->
|
|
|
683
736
|
any_stale = True
|
|
684
737
|
|
|
685
738
|
if conflicts:
|
|
686
|
-
|
|
687
|
-
for file_path, owner in conflicts:
|
|
688
|
-
print(f' - {file_path} (locked by {owner_description(owner)})', file=sys.stderr)
|
|
689
|
-
# Taking a lock over is an owner decision, so spell out the command
|
|
690
|
-
# rather than leave the next agent to discover where the claim lives.
|
|
691
|
-
owners: dict[str, list[str]] = {}
|
|
692
|
-
for file_path, owner in conflicts:
|
|
693
|
-
owner_agent = str(owner.get('agent', '')).strip()
|
|
694
|
-
owner_args = f"--branch {shlex.quote(str(owner.get('branch', '')))}"
|
|
695
|
-
if owner_agent:
|
|
696
|
-
owner_args += f' --agent {shlex.quote(owner_agent)}'
|
|
697
|
-
owners.setdefault(owner_args, []).append(file_path)
|
|
698
|
-
print(
|
|
699
|
-
'[agent-file-locks] If the owner agreed to hand them over, release them '
|
|
700
|
-
'(works from any worktree), then claim again:',
|
|
701
|
-
file=sys.stderr,
|
|
702
|
-
)
|
|
703
|
-
for owner_args, owned in owners.items():
|
|
704
|
-
print(f' gx locks release {owner_args} {" ".join(shlex.quote(p) for p in owned)}', file=sys.stderr)
|
|
705
|
-
if any_stale:
|
|
706
|
-
print(
|
|
707
|
-
'[agent-file-locks] Some blocking locks are past the staleness TTL; if their '
|
|
708
|
-
'lane is abandoned, run `gx locks reap` to clear them.',
|
|
709
|
-
file=sys.stderr,
|
|
710
|
-
)
|
|
711
|
-
return 1
|
|
739
|
+
raise ClaimConflict(conflicts, claim_agent, any_stale)
|
|
712
740
|
|
|
713
741
|
for file_path in files:
|
|
714
742
|
existing = locks.get(file_path, {})
|
|
@@ -732,6 +760,181 @@ def cmd_claim(args: argparse.Namespace, repo_root: Path, adaptive_owner: str) ->
|
|
|
732
760
|
return 0
|
|
733
761
|
|
|
734
762
|
|
|
763
|
+
def report_claim_conflict(repo_root: Path, conflict: ClaimConflict) -> int:
|
|
764
|
+
# The conflict snapshot is advisory; do not hold any worktree locks while calling GitHub.
|
|
765
|
+
prs = open_pr_links(repo_root, {owner['branch'] for _, owner in conflict.conflicts})
|
|
766
|
+
print('[agent-file-locks] Cannot claim files already locked by another owner:', file=sys.stderr)
|
|
767
|
+
identity = f'{AGENT_ID_ENV}={shlex.quote(conflict.agent)} ' if conflict.agent else ''
|
|
768
|
+
for file_path, owner in conflict.conflicts:
|
|
769
|
+
pr = f"; PR {prs[owner['branch']]}" if owner['branch'] in prs else ''
|
|
770
|
+
print(f' - {file_path} (locked by {owner_description(owner)}{pr})', file=sys.stderr)
|
|
771
|
+
print(f' Request owner approval: {identity}gx locks handoff-request -- {shlex.quote(file_path)}', file=sys.stderr)
|
|
772
|
+
print('[agent-file-locks] Or wait for the owner PR and retry the claim after the lock is released.', file=sys.stderr)
|
|
773
|
+
if conflict.stale:
|
|
774
|
+
print(
|
|
775
|
+
'[agent-file-locks] Some blocking locks are past the staleness TTL; if their '
|
|
776
|
+
'lane is abandoned, run `gx locks reap` to clear them.',
|
|
777
|
+
file=sys.stderr,
|
|
778
|
+
)
|
|
779
|
+
return 1
|
|
780
|
+
|
|
781
|
+
|
|
782
|
+
def handoff_dir(repo_root: Path) -> Path:
|
|
783
|
+
return common_git_dir(repo_root) / 'agent-file-lock-handoffs'
|
|
784
|
+
|
|
785
|
+
|
|
786
|
+
def read_handoff(path: Path) -> dict[str, Any]:
|
|
787
|
+
try:
|
|
788
|
+
request = json.loads(path.read_text())
|
|
789
|
+
if (not isinstance(request, dict) or request.get('id') != path.stem
|
|
790
|
+
or not isinstance(request.get('owner'), dict) or not isinstance(request.get('recipient'), dict)):
|
|
791
|
+
raise ValueError('invalid request')
|
|
792
|
+
return request
|
|
793
|
+
except (OSError, ValueError) as exc:
|
|
794
|
+
raise LockError(f'Cannot read handoff {path.stem}') from exc
|
|
795
|
+
|
|
796
|
+
|
|
797
|
+
def handoff_lane(repo_root: Path) -> dict[str, str]:
|
|
798
|
+
branch = get_worktree_branch(repo_root)
|
|
799
|
+
if not branch:
|
|
800
|
+
raise LockError('Handoffs require a checked-out branch')
|
|
801
|
+
return {'branch': branch, 'agent': os.environ.get(AGENT_ID_ENV, '').strip(), '_worktree': str(repo_root)}
|
|
802
|
+
|
|
803
|
+
|
|
804
|
+
def matches_handoff_lane(entry: dict[str, Any], lane: dict[str, Any]) -> bool:
|
|
805
|
+
# Unlike legacy branch-wide maintenance commands, handoffs require an exact lane.
|
|
806
|
+
return all(entry.get(key, '') == lane.get(key, '') for key in ('branch', 'agent', '_worktree'))
|
|
807
|
+
|
|
808
|
+
|
|
809
|
+
def cmd_handoff_request(args: argparse.Namespace, repo_root: Path) -> int:
|
|
810
|
+
file_path = normalize_repo_path(repo_root, args.file)
|
|
811
|
+
recipient = handoff_lane(repo_root)
|
|
812
|
+
owners = load_all_locks(repo_root).get(file_path, [])
|
|
813
|
+
if len(owners) != 1 or owner_matches(owners[0], recipient['branch'], recipient['agent']):
|
|
814
|
+
raise LockError('Handoff requires one lock held by another lane')
|
|
815
|
+
owner = owners[0]
|
|
816
|
+
if get_worktree_branch(Path(owner['_worktree'])) != owner['branch']:
|
|
817
|
+
raise LockError('The lock owner is not currently checked out in its worktree')
|
|
818
|
+
directory = handoff_dir(repo_root)
|
|
819
|
+
for path in directory.glob('*.json'):
|
|
820
|
+
request = read_handoff(path)
|
|
821
|
+
if (not request.get('commit') and request.get('file') == file_path
|
|
822
|
+
and request['owner'] == owner and request['recipient'] == recipient):
|
|
823
|
+
print(f"Handoff {request['id']} is already pending. The current lock is unchanged.")
|
|
824
|
+
return 0
|
|
825
|
+
request_id = uuid4().hex
|
|
826
|
+
write_json(directory / f'{request_id}.json', {
|
|
827
|
+
'id': request_id, 'file': file_path, 'owner': owner, 'recipient': recipient,
|
|
828
|
+
'pane': resolve_pane(),
|
|
829
|
+
})
|
|
830
|
+
print(f'Handoff {request_id} pending for {file_path}. The current lock is unchanged.')
|
|
831
|
+
identity = f'{AGENT_ID_ENV}={shlex.quote(owner["agent"])} ' if owner['agent'] else ''
|
|
832
|
+
print(f'Owner ({owner_description(owner)}): {identity}gx locks handoff-approve {request_id}')
|
|
833
|
+
return 0
|
|
834
|
+
|
|
835
|
+
|
|
836
|
+
def cmd_handoffs(repo_root: Path) -> int:
|
|
837
|
+
locks = load_all_locks(repo_root)
|
|
838
|
+
for path in sorted(handoff_dir(repo_root).glob('*.json')):
|
|
839
|
+
entry = read_handoff(path)
|
|
840
|
+
commit = entry.get('commit')
|
|
841
|
+
check = entry.get('check')
|
|
842
|
+
owners = locks.get(entry['file'], [])
|
|
843
|
+
stale = entry['owner'] not in owners
|
|
844
|
+
source_still_locked = any(
|
|
845
|
+
lock['_worktree'] == entry['owner']['_worktree'] and lock.get('handoff_id') != entry['id']
|
|
846
|
+
for lock in owners
|
|
847
|
+
)
|
|
848
|
+
if not commit and not source_still_locked:
|
|
849
|
+
# A process may have moved the lock without writing the receipt yet.
|
|
850
|
+
transferred = next((lock for lock in owners if lock.get('handoff_id') == entry['id']), {})
|
|
851
|
+
commit = transferred.get('handoff_commit')
|
|
852
|
+
check = transferred.get('handoff_check')
|
|
853
|
+
status = f'approved at {commit}' if commit else ('stale (owner lock changed)' if stale else 'pending')
|
|
854
|
+
print(f"{entry['id']} {status}: {entry['file']} — {owner_label(entry['owner'])} → {owner_label(entry['recipient'])}")
|
|
855
|
+
if check:
|
|
856
|
+
print(f" Verify: {check}")
|
|
857
|
+
return 0
|
|
858
|
+
|
|
859
|
+
|
|
860
|
+
def record_handoff(path: Path, request: dict[str, Any], entry: dict[str, Any]) -> None:
|
|
861
|
+
write_json(path, {**request, 'commit': entry['handoff_commit'], 'check': entry.get('handoff_check')})
|
|
862
|
+
|
|
863
|
+
|
|
864
|
+
def cmd_handoff_approve(args: argparse.Namespace, repo_root: Path) -> int:
|
|
865
|
+
if not re.fullmatch(r'[a-f0-9]{32}', args.id):
|
|
866
|
+
raise LockError('Invalid handoff id')
|
|
867
|
+
path = handoff_dir(repo_root) / f'{args.id}.json'
|
|
868
|
+
request = read_handoff(path)
|
|
869
|
+
owner = request['owner']
|
|
870
|
+
if not matches_handoff_lane(owner, handoff_lane(repo_root)):
|
|
871
|
+
raise LockError('Only the current owner branch and agent can approve from its worktree')
|
|
872
|
+
if request.get('commit'):
|
|
873
|
+
print(f"Handoff {args.id} was already approved at {request['commit']}.")
|
|
874
|
+
return 0
|
|
875
|
+
|
|
876
|
+
file_path = normalize_repo_path(repo_root, request['file'])
|
|
877
|
+
recipient = request['recipient']
|
|
878
|
+
target = Path(recipient['_worktree'])
|
|
879
|
+
if target not in list_worktree_roots(repo_root) or get_worktree_branch(target) != recipient['branch']:
|
|
880
|
+
raise LockError('Recipient must still have its branch checked out in the requesting worktree')
|
|
881
|
+
source_state = load_state(repo_root)
|
|
882
|
+
source_entry = source_state['locks'].get(file_path)
|
|
883
|
+
target_state = source_state if target == repo_root else load_state(target)
|
|
884
|
+
target_entry = target_state['locks'].get(file_path)
|
|
885
|
+
if any(
|
|
886
|
+
entry != owner and not (matches_handoff_lane(entry, recipient) and entry.get('handoff_id') == args.id)
|
|
887
|
+
for entry in load_all_locks(repo_root).get(file_path, [])
|
|
888
|
+
):
|
|
889
|
+
raise LockError('An unrelated lock exists for this file; cannot safely transfer ownership')
|
|
890
|
+
# A retry can complete the receipt if the locks were moved before the process exited.
|
|
891
|
+
if target_entry and target_entry.get('handoff_id') == args.id and (
|
|
892
|
+
not source_entry or target == repo_root):
|
|
893
|
+
record_handoff(path, request, target_entry)
|
|
894
|
+
print(f"Handoff {args.id} already transferred at {target_entry['handoff_commit']}.")
|
|
895
|
+
return 0
|
|
896
|
+
if not source_entry or {**source_entry, '_worktree': str(repo_root)} != owner:
|
|
897
|
+
raise LockError('The owner lock changed; request a new handoff')
|
|
898
|
+
if target != repo_root and target_entry and target_entry.get('handoff_id') != args.id:
|
|
899
|
+
raise LockError('The recipient already has a different lock')
|
|
900
|
+
for cwd in {repo_root, target}:
|
|
901
|
+
tracked = run_git(['--literal-pathspecs', 'ls-files', '-v', '--', file_path], cwd=cwd)
|
|
902
|
+
if any(line[0] == 'S' or line[0].islower() for line in tracked.splitlines() if line):
|
|
903
|
+
raise LockError(f'Cannot hand off {file_path}: skip-worktree or assume-unchanged set in {cwd}')
|
|
904
|
+
if run_git(['--literal-pathspecs', 'status', '--porcelain', '--untracked-files=all',
|
|
905
|
+
'--ignored=matching', '--ignore-submodules=none', '--', file_path], cwd=cwd):
|
|
906
|
+
raise LockError(f'Cannot hand off {file_path}: uncommitted changes in {cwd}')
|
|
907
|
+
resumed = target_entry and target_entry.get('handoff_id') == args.id
|
|
908
|
+
commit = target_entry['handoff_commit'] if resumed else run_git(['rev-parse', 'HEAD'], cwd=repo_root)
|
|
909
|
+
if resumed:
|
|
910
|
+
try:
|
|
911
|
+
run_git(['--literal-pathspecs', 'diff', '--quiet', '--ignore-submodules=none', commit, 'HEAD',
|
|
912
|
+
'--', file_path], cwd=repo_root)
|
|
913
|
+
except LockError as exc:
|
|
914
|
+
raise LockError(f'Cannot resume: {file_path} changed after recorded handoff commit {commit}') from exc
|
|
915
|
+
try:
|
|
916
|
+
run_git(['merge-base', '--is-ancestor', commit, 'HEAD'], cwd=target)
|
|
917
|
+
except LockError as exc:
|
|
918
|
+
raise LockError(f"Recipient {recipient['branch']} does not contain {commit}; update it and retry") from exc
|
|
919
|
+
|
|
920
|
+
# Write destination first. If interrupted across worktrees, both claims
|
|
921
|
+
# block one another; rerun the same approval to finish. No unlocked gap.
|
|
922
|
+
check = args.check
|
|
923
|
+
if check is None and resumed:
|
|
924
|
+
check = target_entry.get('handoff_check')
|
|
925
|
+
target_state['locks'][file_path] = {
|
|
926
|
+
**LockEntry(recipient['branch'], now_iso(), agent=recipient['agent'], pane=request.get('pane', '')).__dict__,
|
|
927
|
+
'handoff_id': args.id, 'handoff_commit': commit, 'handoff_check': check,
|
|
928
|
+
}
|
|
929
|
+
write_state(target, target_state)
|
|
930
|
+
if target != repo_root:
|
|
931
|
+
del source_state['locks'][file_path]
|
|
932
|
+
write_state(repo_root, source_state)
|
|
933
|
+
record_handoff(path, request, target_state['locks'][file_path])
|
|
934
|
+
print(f"Handoff {args.id} approved for {owner_label(recipient)} at {commit}.")
|
|
935
|
+
return 0
|
|
936
|
+
|
|
937
|
+
|
|
735
938
|
def cmd_allow_delete(args: argparse.Namespace, repo_root: Path) -> int:
|
|
736
939
|
# Operates on THIS worktree's lock file only — run it from the worktree where
|
|
737
940
|
# the claim was made. (claim/validate union across worktrees; the write side
|
|
@@ -1084,6 +1287,13 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
1084
1287
|
add_agent_arg(release)
|
|
1085
1288
|
release.add_argument('files', nargs='*', help='Optional files; omit to release all branch locks')
|
|
1086
1289
|
|
|
1290
|
+
request = sub.add_parser('handoff-request', help='Ask the current file owner to transfer a local worktree lock')
|
|
1291
|
+
request.add_argument('file', help='File to request (repo-relative or absolute)')
|
|
1292
|
+
sub.add_parser('handoffs', help='List pending and approved local handoffs')
|
|
1293
|
+
approve = sub.add_parser('handoff-approve', help='Approve a request from the current owner worktree')
|
|
1294
|
+
approve.add_argument('id', help='Handoff request id')
|
|
1295
|
+
approve.add_argument('--check', help='Verification command to pass to the recipient (not executed)')
|
|
1296
|
+
|
|
1087
1297
|
status = sub.add_parser('status', help='Show lock status')
|
|
1088
1298
|
status.add_argument('--branch', help='Filter by branch')
|
|
1089
1299
|
add_agent_arg(status)
|
|
@@ -1130,6 +1340,10 @@ def dispatch_command(args: argparse.Namespace, repo_root: Path) -> int:
|
|
|
1130
1340
|
return cmd_allow_delete(args, repo_root)
|
|
1131
1341
|
if args.command == 'release':
|
|
1132
1342
|
return cmd_release(args, repo_root)
|
|
1343
|
+
if args.command == 'handoff-request':
|
|
1344
|
+
return cmd_handoff_request(args, repo_root)
|
|
1345
|
+
if args.command == 'handoffs':
|
|
1346
|
+
return cmd_handoffs(repo_root)
|
|
1133
1347
|
if args.command == 'reap':
|
|
1134
1348
|
return cmd_reap(args, repo_root)
|
|
1135
1349
|
if args.command == 'status':
|
|
@@ -1147,16 +1361,22 @@ def main() -> int:
|
|
|
1147
1361
|
|
|
1148
1362
|
try:
|
|
1149
1363
|
repo_root = resolve_repo_root()
|
|
1150
|
-
# Serialize
|
|
1151
|
-
#
|
|
1152
|
-
|
|
1153
|
-
if args.command in {'claim', 'allow-delete', 'release', 'reap', 'validate'}:
|
|
1364
|
+
# Serialize mutations and consistent snapshot reads across all worktrees.
|
|
1365
|
+
# The informational status command remains an unlocked read.
|
|
1366
|
+
if args.command in {'claim', 'allow-delete', 'release', 'reap', 'validate', 'handoff-request', 'handoff-approve', 'handoffs'}:
|
|
1154
1367
|
with cross_worktree_lock(repo_root):
|
|
1155
1368
|
if args.command == 'claim':
|
|
1156
1369
|
with adaptive_direct_owner_lock(repo_root) as adaptive_owner:
|
|
1157
1370
|
return cmd_claim(args, repo_root, adaptive_owner)
|
|
1371
|
+
if args.command == 'handoff-approve':
|
|
1372
|
+
with adaptive_direct_owner_lock(repo_root) as adaptive_owner:
|
|
1373
|
+
if adaptive_owner:
|
|
1374
|
+
raise LockError('Handoff blocked while an adaptive direct session owns the primary checkout')
|
|
1375
|
+
return cmd_handoff_approve(args, repo_root)
|
|
1158
1376
|
return dispatch_command(args, repo_root)
|
|
1159
1377
|
return dispatch_command(args, repo_root)
|
|
1378
|
+
except ClaimConflict as exc:
|
|
1379
|
+
return report_claim_conflict(repo_root, exc)
|
|
1160
1380
|
except LockError as exc:
|
|
1161
1381
|
print(f'[agent-file-locks] {exc}', file=sys.stderr)
|
|
1162
1382
|
return 2
|