@imdeadpool/guardex 8.2.0 → 8.4.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 +68 -10
- package/bin/multiagent-safety.js +18 -1
- package/package.json +1 -1
- package/skills/gitguardex/SKILL.md +26 -2
- package/src/agents/message.js +764 -0
- package/src/agents/sessions.js +23 -1
- package/src/cli/args.js +64 -8
- package/src/cli/commands/agents.js +18 -0
- package/src/cli/commands/branch.js +94 -2
- package/src/cli/commands/finish.js +44 -2
- package/src/cli/commands/mcp.js +4 -3
- package/src/cli/shared/sandbox.js +5 -53
- package/src/cli/shared-locks.js +4 -0
- package/src/doctor/index.js +26 -26
- package/src/finish/index.js +10 -2
- package/src/finish/post-branch-finish-cleanup.js +324 -0
- package/src/finish/review-gate.js +47 -6
- package/src/git/index.js +9 -4
- package/src/mcp/collect.js +52 -3
- package/src/mcp/server.js +54 -2
- package/src/pr-checks.js +20 -5
- package/src/pr.js +122 -1
- package/src/scaffold/index.js +13 -0
- package/templates/AGENTS.multiagent-safety.md +37 -9
- package/templates/AGENTS.multiagent-safety.min.md +10 -4
- package/templates/codex/skills/gitguardex/SKILL.md +26 -2
- package/templates/githooks/pre-commit +40 -5
- package/templates/githooks/pre-push +72 -25
- package/templates/scripts/agent-branch-finish.sh +300 -21
- package/templates/scripts/agent-branch-start.sh +22 -2
- package/templates/scripts/agent-file-locks.py +170 -3
- package/templates/scripts/agent-preflight.sh +30 -0
- package/templates/scripts/agent-reconcile-openspec-tasks.js +105 -0
- package/templates/scripts/agent-worktree-prune.sh +406 -31
- package/templates/scripts/guardex-env.sh +291 -0
|
@@ -22,8 +22,10 @@ from __future__ import annotations
|
|
|
22
22
|
|
|
23
23
|
import argparse
|
|
24
24
|
import json
|
|
25
|
+
import math
|
|
25
26
|
import os
|
|
26
27
|
import re
|
|
28
|
+
import shutil
|
|
27
29
|
import subprocess
|
|
28
30
|
import sys
|
|
29
31
|
from contextlib import contextmanager
|
|
@@ -55,6 +57,8 @@ LOCK_NOW_EPOCH_ENV = 'GUARDEX_LOCK_NOW_EPOCH'
|
|
|
55
57
|
# Generous default so an active long-running lane is never reaped; `reap` is an
|
|
56
58
|
# explicit, opt-in maintenance command, not an automatic background sweep.
|
|
57
59
|
DEFAULT_LOCK_TTL_HOURS = 168.0 # 7 days
|
|
60
|
+
ADAPTIVE_SESSION_LEASE_SECONDS_ENV = 'GUARDEX_ADAPTIVE_SESSION_LEASE_SEC'
|
|
61
|
+
DEFAULT_ADAPTIVE_SESSION_LEASE_SECONDS = 900.0
|
|
58
62
|
|
|
59
63
|
|
|
60
64
|
@dataclass
|
|
@@ -115,6 +119,15 @@ def resolve_agent(args: argparse.Namespace) -> str:
|
|
|
115
119
|
return (value or '').strip()
|
|
116
120
|
|
|
117
121
|
|
|
122
|
+
def resolve_session_id() -> str:
|
|
123
|
+
return (
|
|
124
|
+
os.environ.get('CODEX_THREAD_ID')
|
|
125
|
+
or os.environ.get('OMX_SESSION_ID')
|
|
126
|
+
or os.environ.get('CLAUDE_CODE_SESSION_ID')
|
|
127
|
+
or ''
|
|
128
|
+
).strip()
|
|
129
|
+
|
|
130
|
+
|
|
118
131
|
def resolve_pane() -> str:
|
|
119
132
|
"""Return the caller's tmux pane when it has the canonical `%<number>` form."""
|
|
120
133
|
value = os.environ.get(PANE_ID_ENV, '').strip()
|
|
@@ -325,12 +338,88 @@ def list_worktree_roots(repo_root: Path) -> list[Path]:
|
|
|
325
338
|
return roots
|
|
326
339
|
|
|
327
340
|
|
|
341
|
+
def known_branch_names(repo_root: Path) -> set[str]:
|
|
342
|
+
"""Local and remote branch names plus branches attached to worktrees."""
|
|
343
|
+
names: set[str] = set()
|
|
344
|
+
worktrees = run_git(['worktree', 'list', '--porcelain'], cwd=repo_root)
|
|
345
|
+
for line in worktrees.splitlines():
|
|
346
|
+
if line.startswith('branch refs/heads/'):
|
|
347
|
+
names.add(line[len('branch refs/heads/'):].strip())
|
|
348
|
+
|
|
349
|
+
refs = run_git(
|
|
350
|
+
['for-each-ref', '--format=%(refname)', 'refs/heads', 'refs/remotes'],
|
|
351
|
+
cwd=repo_root,
|
|
352
|
+
)
|
|
353
|
+
for ref in refs.splitlines():
|
|
354
|
+
if ref.startswith('refs/heads/'):
|
|
355
|
+
names.add(ref[len('refs/heads/'):])
|
|
356
|
+
continue
|
|
357
|
+
if not ref.startswith('refs/remotes/'):
|
|
358
|
+
continue
|
|
359
|
+
remote_and_branch = ref[len('refs/remotes/'):]
|
|
360
|
+
_, separator, branch = remote_and_branch.partition('/')
|
|
361
|
+
if separator and branch:
|
|
362
|
+
names.add(branch)
|
|
363
|
+
return names
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def git_common_dir_identity(cwd: Path) -> Path:
|
|
367
|
+
top = Path(run_git(['rev-parse', '--show-toplevel'], cwd=cwd))
|
|
368
|
+
common = Path(run_git(['rev-parse', '--git-common-dir'], cwd=cwd))
|
|
369
|
+
return common.resolve() if common.is_absolute() else (top / common).resolve()
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def pane_still_owns_branch(repo_root: Path, pane: str, branch: str) -> bool | None:
|
|
373
|
+
"""True/False when tmux proves pane ownership; None means fail closed."""
|
|
374
|
+
if not re.fullmatch(r'%\d+', pane) or shutil.which('tmux') is None:
|
|
375
|
+
return None
|
|
376
|
+
try:
|
|
377
|
+
result = subprocess.run(
|
|
378
|
+
['tmux', 'display-message', '-p', '-t', pane, '#{pane_current_path}'],
|
|
379
|
+
check=False,
|
|
380
|
+
stdout=subprocess.PIPE,
|
|
381
|
+
stderr=subprocess.PIPE,
|
|
382
|
+
text=True,
|
|
383
|
+
timeout=3,
|
|
384
|
+
)
|
|
385
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
386
|
+
return None
|
|
387
|
+
if result.returncode != 0:
|
|
388
|
+
return None
|
|
389
|
+
pane_cwd = Path(result.stdout.strip())
|
|
390
|
+
if not result.stdout.strip() or not pane_cwd.exists():
|
|
391
|
+
return None
|
|
392
|
+
try:
|
|
393
|
+
if git_common_dir_identity(pane_cwd) != git_common_dir_identity(repo_root):
|
|
394
|
+
return None
|
|
395
|
+
pane_branch = run_git(['rev-parse', '--abbrev-ref', 'HEAD'], cwd=pane_cwd)
|
|
396
|
+
except LockError:
|
|
397
|
+
return None
|
|
398
|
+
if not pane_branch or pane_branch == 'HEAD':
|
|
399
|
+
return None
|
|
400
|
+
return pane_branch == branch
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def is_orphaned_local_lock(
|
|
404
|
+
repo_root: Path,
|
|
405
|
+
entry: dict[str, Any],
|
|
406
|
+
known_branches: set[str],
|
|
407
|
+
) -> bool:
|
|
408
|
+
"""Ignore only ownership disproved by both Git refs and live pane state."""
|
|
409
|
+
branch = str(entry.get('branch', ''))
|
|
410
|
+
if not branch or branch in known_branches:
|
|
411
|
+
return False
|
|
412
|
+
pane = str(entry.get('pane', ''))
|
|
413
|
+
return pane_still_owns_branch(repo_root, pane, branch) is False
|
|
414
|
+
|
|
415
|
+
|
|
328
416
|
def load_all_locks(repo_root: Path) -> dict[str, list[dict[str, Any]]]:
|
|
329
417
|
"""Union of EVERY worktree's lock map: file path -> list of owner entries
|
|
330
418
|
(one per worktree that claims it). Each worktree owns a separate lock file on
|
|
331
419
|
disk, so a file's full ownership is only visible by reading them all. With a
|
|
332
420
|
single worktree this is exactly that worktree's own locks (unchanged)."""
|
|
333
421
|
merged: dict[str, list[dict[str, Any]]] = {}
|
|
422
|
+
known_branches = known_branch_names(repo_root)
|
|
334
423
|
for root in list_worktree_roots(repo_root):
|
|
335
424
|
try:
|
|
336
425
|
state = load_state(root)
|
|
@@ -340,6 +429,8 @@ def load_all_locks(repo_root: Path) -> dict[str, list[dict[str, Any]]]:
|
|
|
340
429
|
'lock operation blocked'
|
|
341
430
|
) from exc
|
|
342
431
|
for file_path, entry in state['locks'].items():
|
|
432
|
+
if is_orphaned_local_lock(repo_root, entry, known_branches):
|
|
433
|
+
continue
|
|
343
434
|
merged.setdefault(file_path, []).append({**entry, '_worktree': str(root)})
|
|
344
435
|
return merged
|
|
345
436
|
|
|
@@ -385,13 +476,75 @@ def cross_worktree_lock(repo_root: Path):
|
|
|
385
476
|
handle.close()
|
|
386
477
|
|
|
387
478
|
|
|
388
|
-
|
|
479
|
+
@contextmanager
|
|
480
|
+
def adaptive_direct_owner_lock(repo_root: Path):
|
|
481
|
+
"""Yield the live primary-checkout owner while holding its OS lock."""
|
|
482
|
+
if fcntl is None:
|
|
483
|
+
raise LockError('OS file locking is unavailable; lock operation blocked')
|
|
484
|
+
state_dir = common_git_dir(repo_root) / 'gitguardex'
|
|
485
|
+
lease_path = state_dir / 'adaptive-direct-session.json'
|
|
486
|
+
lease_lock_path = state_dir / 'adaptive-direct-session.lock'
|
|
487
|
+
try:
|
|
488
|
+
state_dir.mkdir(parents=True, exist_ok=True)
|
|
489
|
+
handle = open(lease_lock_path, 'a+')
|
|
490
|
+
except OSError as exc:
|
|
491
|
+
raise LockError('cannot open the adaptive direct-session lock; claim blocked') from exc
|
|
492
|
+
acquired = False
|
|
493
|
+
contended = False
|
|
494
|
+
try:
|
|
495
|
+
try:
|
|
496
|
+
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
497
|
+
acquired = True
|
|
498
|
+
except BlockingIOError:
|
|
499
|
+
contended = True
|
|
500
|
+
except OSError as exc:
|
|
501
|
+
raise LockError('cannot acquire the adaptive direct-session lock; claim blocked') from exc
|
|
502
|
+
try:
|
|
503
|
+
lease = json.loads(lease_path.read_text())
|
|
504
|
+
except FileNotFoundError:
|
|
505
|
+
yield ''
|
|
506
|
+
return
|
|
507
|
+
except (OSError, json.JSONDecodeError, ValueError) as exc:
|
|
508
|
+
raise LockError('adaptive direct-session lease is unreadable; claim blocked') from exc
|
|
509
|
+
if not isinstance(lease, dict):
|
|
510
|
+
raise LockError('adaptive direct-session lease is malformed; claim blocked')
|
|
511
|
+
owner = lease.get('session_id')
|
|
512
|
+
last_seen = lease.get('last_seen_epoch')
|
|
513
|
+
if not isinstance(owner, str) or not owner.strip():
|
|
514
|
+
raise LockError('adaptive direct-session owner is malformed; claim blocked')
|
|
515
|
+
if isinstance(last_seen, bool) or not isinstance(last_seen, (int, float)):
|
|
516
|
+
raise LockError('adaptive direct-session timestamp is malformed; claim blocked')
|
|
517
|
+
raw_ttl = os.environ.get(ADAPTIVE_SESSION_LEASE_SECONDS_ENV, '').strip()
|
|
518
|
+
try:
|
|
519
|
+
ttl_seconds = float(raw_ttl) if raw_ttl else DEFAULT_ADAPTIVE_SESSION_LEASE_SECONDS
|
|
520
|
+
except ValueError as exc:
|
|
521
|
+
raise LockError('adaptive direct-session TTL is invalid; claim blocked') from exc
|
|
522
|
+
if ttl_seconds <= 0 or not math.isfinite(ttl_seconds):
|
|
523
|
+
raise LockError('adaptive direct-session TTL is invalid; claim blocked')
|
|
524
|
+
yield owner if contended or now_epoch() - float(last_seen) < ttl_seconds else ''
|
|
525
|
+
finally:
|
|
526
|
+
try:
|
|
527
|
+
if acquired:
|
|
528
|
+
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
|
|
529
|
+
finally:
|
|
530
|
+
handle.close()
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
def cmd_claim(args: argparse.Namespace, repo_root: Path, adaptive_owner: str) -> int:
|
|
389
534
|
state = load_state(repo_root)
|
|
390
535
|
locks: dict[str, dict[str, Any]] = state['locks']
|
|
391
536
|
|
|
392
537
|
claim_agent = resolve_agent(args)
|
|
538
|
+
claim_session = resolve_session_id()
|
|
393
539
|
claim_pane = resolve_pane()
|
|
394
540
|
files = [normalize_repo_path(repo_root, p) for p in args.files]
|
|
541
|
+
if adaptive_owner and adaptive_owner != claim_session:
|
|
542
|
+
print(
|
|
543
|
+
'[agent-file-locks] Cannot claim files while adaptive direct work owns '
|
|
544
|
+
f'the primary checkout as {adaptive_owner}.',
|
|
545
|
+
file=sys.stderr,
|
|
546
|
+
)
|
|
547
|
+
return 1
|
|
395
548
|
conflicts: list[tuple[str, dict[str, Any]]] = []
|
|
396
549
|
|
|
397
550
|
# Conflict detection spans EVERY worktree of the repo, not just this one: a
|
|
@@ -554,6 +707,7 @@ def cmd_status(args: argparse.Namespace, repo_root: Path) -> int:
|
|
|
554
707
|
# a sibling worktree's claims would otherwise be invisible here.
|
|
555
708
|
agent_filter = resolve_agent(args)
|
|
556
709
|
roots = list_worktree_roots(repo_root)
|
|
710
|
+
known_branches = known_branch_names(repo_root)
|
|
557
711
|
|
|
558
712
|
rows: list[tuple[str, str, str, str, bool, str]] = []
|
|
559
713
|
for root in roots:
|
|
@@ -565,6 +719,8 @@ def cmd_status(args: argparse.Namespace, repo_root: Path) -> int:
|
|
|
565
719
|
'status is unavailable'
|
|
566
720
|
) from exc
|
|
567
721
|
for file_path, entry in locks.items():
|
|
722
|
+
if is_orphaned_local_lock(repo_root, entry, known_branches):
|
|
723
|
+
continue
|
|
568
724
|
branch = str(entry.get('branch', ''))
|
|
569
725
|
if args.branch and branch != args.branch:
|
|
570
726
|
continue
|
|
@@ -621,7 +777,10 @@ def cmd_validate(args: argparse.Namespace, repo_root: Path) -> int:
|
|
|
621
777
|
for status, file_path in file_changes:
|
|
622
778
|
owners = all_locks.get(file_path, [])
|
|
623
779
|
if not owners:
|
|
624
|
-
|
|
780
|
+
if not args.allow_unclaimed:
|
|
781
|
+
missing.append(file_path)
|
|
782
|
+
elif status == 'D' and file_path in CRITICAL_GUARDRAIL_PATHS and not allow_guardrail_delete:
|
|
783
|
+
guardrail_delete_blocked.append(file_path)
|
|
625
784
|
continue
|
|
626
785
|
|
|
627
786
|
foreign_owners = [e for e in owners if not owner_matches(e, args.branch, agent)]
|
|
@@ -726,6 +885,11 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
726
885
|
validate.add_argument('--branch', required=True, help='Owner branch name')
|
|
727
886
|
add_agent_arg(validate)
|
|
728
887
|
validate.add_argument('--staged', action='store_true', help='Validate staged files from git index')
|
|
888
|
+
validate.add_argument(
|
|
889
|
+
'--allow-unclaimed',
|
|
890
|
+
action='store_true',
|
|
891
|
+
help='Allow unclaimed files while still rejecting foreign claims',
|
|
892
|
+
)
|
|
729
893
|
validate.add_argument('files', nargs='*', help='Files to validate when --staged is not used')
|
|
730
894
|
|
|
731
895
|
return parser
|
|
@@ -733,7 +897,7 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
733
897
|
|
|
734
898
|
def dispatch_command(args: argparse.Namespace, repo_root: Path) -> int:
|
|
735
899
|
if args.command == 'claim':
|
|
736
|
-
|
|
900
|
+
raise LockError('claim must run while holding the adaptive direct-session lock')
|
|
737
901
|
if args.command == 'allow-delete':
|
|
738
902
|
return cmd_allow_delete(args, repo_root)
|
|
739
903
|
if args.command == 'release':
|
|
@@ -760,6 +924,9 @@ def main() -> int:
|
|
|
760
924
|
# each other or both win the same file. status is a pure read -> unlocked.
|
|
761
925
|
if args.command in {'claim', 'allow-delete', 'release', 'reap', 'validate'}:
|
|
762
926
|
with cross_worktree_lock(repo_root):
|
|
927
|
+
if args.command == 'claim':
|
|
928
|
+
with adaptive_direct_owner_lock(repo_root) as adaptive_owner:
|
|
929
|
+
return cmd_claim(args, repo_root, adaptive_owner)
|
|
763
930
|
return dispatch_command(args, repo_root)
|
|
764
931
|
return dispatch_command(args, repo_root)
|
|
765
932
|
except LockError as exc:
|
|
@@ -20,6 +20,28 @@
|
|
|
20
20
|
set -euo pipefail
|
|
21
21
|
|
|
22
22
|
repo_root="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
|
|
23
|
+
if [[ "${1:-}" == "--guardex-capabilities" ]]; then
|
|
24
|
+
printf '%s\n' 'guardex-target-worktree-v1'
|
|
25
|
+
exit 0
|
|
26
|
+
fi
|
|
27
|
+
if [[ "${1:-}" == "--guardex-target-worktree" ]]; then
|
|
28
|
+
if [[ "$#" -ne 2 || -z "$2" ]]; then
|
|
29
|
+
echo "[agent-preflight] --guardex-target-worktree requires exactly one path." >&2
|
|
30
|
+
exit 1
|
|
31
|
+
fi
|
|
32
|
+
GUARDEX_PREFLIGHT_TARGET_WORKTREE="$2"
|
|
33
|
+
fi
|
|
34
|
+
if [[ -n "${GUARDEX_PREFLIGHT_TARGET_WORKTREE:-}" ]]; then
|
|
35
|
+
repo_root="$(cd "$GUARDEX_PREFLIGHT_TARGET_WORKTREE" 2>/dev/null && pwd -P)" || {
|
|
36
|
+
echo "[agent-preflight] Invalid GUARDEX_PREFLIGHT_TARGET_WORKTREE." >&2
|
|
37
|
+
exit 1
|
|
38
|
+
}
|
|
39
|
+
target_git_root="$(git -C "$repo_root" rev-parse --show-toplevel 2>/dev/null || true)"
|
|
40
|
+
if [[ -z "$target_git_root" || "$(cd "$target_git_root" && pwd -P)" != "$repo_root" ]]; then
|
|
41
|
+
echo "[agent-preflight] Target is not a Git worktree root: $repo_root" >&2
|
|
42
|
+
exit 1
|
|
43
|
+
fi
|
|
44
|
+
fi
|
|
23
45
|
cd "$repo_root"
|
|
24
46
|
|
|
25
47
|
ran=0 # steps that PASSED
|
|
@@ -40,6 +62,14 @@ run_verification_command() {
|
|
|
40
62
|
-u ALLOW_PUSH_ON_PROTECTED_BRANCH \
|
|
41
63
|
-u GUARDEX_CLI_ENTRY \
|
|
42
64
|
-u GUARDEX_NODE_BIN \
|
|
65
|
+
-u GUARDEX_FINISH_ACTIVE_CWD \
|
|
66
|
+
-u GUARDEX_FINISH_CHECKLIST \
|
|
67
|
+
-u GUARDEX_FINISH_GATE_DONE \
|
|
68
|
+
-u GUARDEX_FINISH_REQUIRE_PREFLIGHT \
|
|
69
|
+
-u GUARDEX_FINISH_EVENT_FILE \
|
|
70
|
+
-u GUARDEX_FINISH_RUN_ID \
|
|
71
|
+
-u GUARDEX_FINISH_EVENT_BRANCH \
|
|
72
|
+
-u GUARDEX_FINISH_EVENT_BASE \
|
|
43
73
|
"$@"
|
|
44
74
|
}
|
|
45
75
|
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const cp = require('node:child_process');
|
|
5
|
+
const fs = require('node:fs');
|
|
6
|
+
const path = require('node:path');
|
|
7
|
+
|
|
8
|
+
const TASK_LINE = /^(\s*-\s+\[)([ xX])(\]\s+.*)$/;
|
|
9
|
+
const TASKS_PATH = /^openspec\/changes\/[^/]+\/tasks\.md$/;
|
|
10
|
+
|
|
11
|
+
function isOpenSpecTasksPath(filePath) {
|
|
12
|
+
return TASKS_PATH.test(String(filePath || ''));
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function mergeTaskDocuments(base, ours, theirs) {
|
|
16
|
+
const baseLines = String(base).split('\n');
|
|
17
|
+
const oursLines = String(ours).split('\n');
|
|
18
|
+
const theirsLines = String(theirs).split('\n');
|
|
19
|
+
if (baseLines.length !== oursLines.length || oursLines.length !== theirsLines.length) {
|
|
20
|
+
throw new Error('task documents have different line counts');
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
let taskCount = 0;
|
|
24
|
+
const merged = oursLines.map((oursLine, index) => {
|
|
25
|
+
const baseLine = baseLines[index];
|
|
26
|
+
const theirsLine = theirsLines[index];
|
|
27
|
+
const baseTask = baseLine.match(TASK_LINE);
|
|
28
|
+
const oursTask = oursLine.match(TASK_LINE);
|
|
29
|
+
const theirsTask = theirsLine.match(TASK_LINE);
|
|
30
|
+
|
|
31
|
+
if (!baseTask && !oursTask && !theirsTask) {
|
|
32
|
+
if (baseLine !== oursLine || oursLine !== theirsLine) {
|
|
33
|
+
throw new Error(`non-checklist content differs at line ${index + 1}`);
|
|
34
|
+
}
|
|
35
|
+
return oursLine;
|
|
36
|
+
}
|
|
37
|
+
if (!baseTask || !oursTask || !theirsTask) {
|
|
38
|
+
throw new Error(`checklist structure differs at line ${index + 1}`);
|
|
39
|
+
}
|
|
40
|
+
const baseText = `${baseTask[1]} ${baseTask[3]}`;
|
|
41
|
+
if (
|
|
42
|
+
baseText !== `${oursTask[1]} ${oursTask[3]}` ||
|
|
43
|
+
baseText !== `${theirsTask[1]} ${theirsTask[3]}`
|
|
44
|
+
) {
|
|
45
|
+
throw new Error(`checklist text differs at line ${index + 1}`);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
taskCount += 1;
|
|
49
|
+
const baseChecked = /x/i.test(baseTask[2]);
|
|
50
|
+
const oursChecked = /x/i.test(oursTask[2]);
|
|
51
|
+
const theirsChecked = /x/i.test(theirsTask[2]);
|
|
52
|
+
const checked = oursChecked === baseChecked ? theirsChecked : oursChecked;
|
|
53
|
+
return `${oursTask[1]}${checked ? 'x' : ' '}${oursTask[3]}`;
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
if (taskCount === 0) {
|
|
57
|
+
throw new Error('task document contains no checklist items');
|
|
58
|
+
}
|
|
59
|
+
return merged.join('\n');
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function readIndexStage(worktree, stage, filePath) {
|
|
63
|
+
return cp.execFileSync('git', ['-C', worktree, 'show', `:${stage}:${filePath}`], {
|
|
64
|
+
encoding: 'utf8',
|
|
65
|
+
maxBuffer: 4 * 1024 * 1024
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function reconcileFromIndex(worktree, filePath) {
|
|
70
|
+
if (!isOpenSpecTasksPath(filePath)) {
|
|
71
|
+
throw new Error(`unsupported conflict path: ${filePath}`);
|
|
72
|
+
}
|
|
73
|
+
const base = readIndexStage(worktree, 1, filePath);
|
|
74
|
+
const ours = readIndexStage(worktree, 2, filePath);
|
|
75
|
+
const theirs = readIndexStage(worktree, 3, filePath);
|
|
76
|
+
const merged = mergeTaskDocuments(base, ours, theirs);
|
|
77
|
+
const destination = path.join(worktree, filePath);
|
|
78
|
+
fs.writeFileSync(destination, merged);
|
|
79
|
+
cp.execFileSync('git', ['-C', worktree, 'add', '--', filePath], { stdio: 'pipe' });
|
|
80
|
+
return merged;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function main(argv) {
|
|
84
|
+
const [worktree, filePath] = argv;
|
|
85
|
+
if (!worktree || !filePath) {
|
|
86
|
+
throw new Error('usage: agent-reconcile-openspec-tasks.js <worktree> <path>');
|
|
87
|
+
}
|
|
88
|
+
reconcileFromIndex(path.resolve(worktree), filePath);
|
|
89
|
+
process.stdout.write(`${filePath}\n`);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (require.main === module) {
|
|
93
|
+
try {
|
|
94
|
+
main(process.argv.slice(2));
|
|
95
|
+
} catch (error) {
|
|
96
|
+
process.stderr.write(`[agent-reconcile-openspec-tasks] ${error.message}\n`);
|
|
97
|
+
process.exitCode = 2;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
module.exports = {
|
|
102
|
+
isOpenSpecTasksPath,
|
|
103
|
+
mergeTaskDocuments,
|
|
104
|
+
reconcileFromIndex
|
|
105
|
+
};
|