@imdeadpool/guardex 8.1.0 → 8.3.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 +57 -8
- package/bin/multiagent-safety.js +18 -1
- package/package.json +1 -1
- package/skills/gitguardex/SKILL.md +26 -2
- package/src/cli/args.js +15 -1
- package/src/cli/commands/agents.js +1 -0
- package/src/cli/commands/branch.js +84 -6
- package/src/cli/commands/finish.js +44 -2
- package/src/cli/shared-locks.js +4 -0
- package/src/doctor/index.js +26 -27
- package/src/finish/index.js +73 -20
- package/src/finish/post-branch-finish-cleanup.js +324 -0
- package/src/finish/progress.js +57 -3
- package/src/finish/review-gate.js +47 -6
- package/src/git/index.js +9 -4
- package/src/mcp/collect.js +84 -23
- package/src/mcp/server.js +35 -19
- package/src/pr-checks.js +20 -5
- package/src/pr.js +122 -1
- package/src/scaffold/index.js +10 -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 +119 -8
- 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 +396 -31
- package/templates/scripts/guardex-env.sh +291 -0
|
@@ -22,7 +22,9 @@ from __future__ import annotations
|
|
|
22
22
|
|
|
23
23
|
import argparse
|
|
24
24
|
import json
|
|
25
|
+
import math
|
|
25
26
|
import os
|
|
27
|
+
import re
|
|
26
28
|
import subprocess
|
|
27
29
|
import sys
|
|
28
30
|
from contextlib import contextmanager
|
|
@@ -39,6 +41,7 @@ except ImportError: # non-POSIX (e.g. Windows): cross-worktree locking degrades
|
|
|
39
41
|
|
|
40
42
|
LOCK_FILE_RELATIVE = Path('.omx/state/agent-file-locks.json')
|
|
41
43
|
AGENT_ID_ENV = 'GUARDEX_AGENT_ID'
|
|
44
|
+
PANE_ID_ENV = 'TMUX_PANE'
|
|
42
45
|
CRITICAL_GUARDRAIL_PATHS = {
|
|
43
46
|
'AGENTS.md',
|
|
44
47
|
'.githooks/pre-commit',
|
|
@@ -53,6 +56,8 @@ LOCK_NOW_EPOCH_ENV = 'GUARDEX_LOCK_NOW_EPOCH'
|
|
|
53
56
|
# Generous default so an active long-running lane is never reaped; `reap` is an
|
|
54
57
|
# explicit, opt-in maintenance command, not an automatic background sweep.
|
|
55
58
|
DEFAULT_LOCK_TTL_HOURS = 168.0 # 7 days
|
|
59
|
+
ADAPTIVE_SESSION_LEASE_SECONDS_ENV = 'GUARDEX_ADAPTIVE_SESSION_LEASE_SEC'
|
|
60
|
+
DEFAULT_ADAPTIVE_SESSION_LEASE_SECONDS = 900.0
|
|
56
61
|
|
|
57
62
|
|
|
58
63
|
@dataclass
|
|
@@ -61,6 +66,7 @@ class LockEntry:
|
|
|
61
66
|
claimed_at: str
|
|
62
67
|
allow_delete: bool = False
|
|
63
68
|
agent: str = ''
|
|
69
|
+
pane: str = ''
|
|
64
70
|
|
|
65
71
|
|
|
66
72
|
class LockError(Exception):
|
|
@@ -112,12 +118,39 @@ def resolve_agent(args: argparse.Namespace) -> str:
|
|
|
112
118
|
return (value or '').strip()
|
|
113
119
|
|
|
114
120
|
|
|
121
|
+
def resolve_session_id() -> str:
|
|
122
|
+
return (
|
|
123
|
+
os.environ.get('CODEX_THREAD_ID')
|
|
124
|
+
or os.environ.get('OMX_SESSION_ID')
|
|
125
|
+
or os.environ.get('CLAUDE_CODE_SESSION_ID')
|
|
126
|
+
or ''
|
|
127
|
+
).strip()
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def resolve_pane() -> str:
|
|
131
|
+
"""Return the caller's tmux pane when it has the canonical `%<number>` form."""
|
|
132
|
+
value = os.environ.get(PANE_ID_ENV, '').strip()
|
|
133
|
+
return value if re.fullmatch(r'%\d+', value) else ''
|
|
134
|
+
|
|
135
|
+
|
|
115
136
|
def owner_label(entry: dict[str, Any]) -> str:
|
|
116
137
|
branch = str(entry.get('branch', ''))
|
|
117
138
|
agent = str(entry.get('agent', ''))
|
|
118
139
|
return f'{branch} as {agent}' if agent else branch
|
|
119
140
|
|
|
120
141
|
|
|
142
|
+
def owner_description(entry: dict[str, Any]) -> str:
|
|
143
|
+
details: list[str] = []
|
|
144
|
+
pane = str(entry.get('pane', '')).strip()
|
|
145
|
+
worktree = str(entry.get('_worktree', '')).strip()
|
|
146
|
+
if pane:
|
|
147
|
+
details.append(f'pane {pane}')
|
|
148
|
+
if worktree:
|
|
149
|
+
details.append(f'worktree {worktree}')
|
|
150
|
+
suffix = f"; {'; '.join(details)}" if details else ''
|
|
151
|
+
return f'{owner_label(entry)}{suffix}'
|
|
152
|
+
|
|
153
|
+
|
|
121
154
|
def owner_matches(entry: dict[str, Any], branch: str, agent: str) -> bool:
|
|
122
155
|
"""Does this branch+agent own the entry?
|
|
123
156
|
|
|
@@ -151,7 +184,7 @@ def load_state(repo_root: Path) -> dict[str, Any]:
|
|
|
151
184
|
if not isinstance(locks, dict):
|
|
152
185
|
return {'locks': {}}
|
|
153
186
|
|
|
154
|
-
# Backward-compat normalization for older lock
|
|
187
|
+
# Backward-compat normalization for older lock schemas (no `agent`/`pane` fields).
|
|
155
188
|
normalized_locks: dict[str, dict[str, Any]] = {}
|
|
156
189
|
for file_path, entry in locks.items():
|
|
157
190
|
if not isinstance(entry, dict):
|
|
@@ -160,11 +193,13 @@ def load_state(repo_root: Path) -> dict[str, Any]:
|
|
|
160
193
|
claimed_at = str(entry.get('claimed_at', ''))
|
|
161
194
|
allow_delete = bool(entry.get('allow_delete', False))
|
|
162
195
|
agent = str(entry.get('agent', ''))
|
|
196
|
+
pane = str(entry.get('pane', ''))
|
|
163
197
|
normalized_locks[str(file_path)] = {
|
|
164
198
|
'branch': branch,
|
|
165
199
|
'claimed_at': claimed_at,
|
|
166
200
|
'allow_delete': allow_delete,
|
|
167
201
|
'agent': agent,
|
|
202
|
+
'pane': pane,
|
|
168
203
|
}
|
|
169
204
|
|
|
170
205
|
return {'locks': normalized_locks}
|
|
@@ -317,7 +352,7 @@ def load_all_locks(repo_root: Path) -> dict[str, list[dict[str, Any]]]:
|
|
|
317
352
|
'lock operation blocked'
|
|
318
353
|
) from exc
|
|
319
354
|
for file_path, entry in state['locks'].items():
|
|
320
|
-
merged.setdefault(file_path, []).append(entry)
|
|
355
|
+
merged.setdefault(file_path, []).append({**entry, '_worktree': str(root)})
|
|
321
356
|
return merged
|
|
322
357
|
|
|
323
358
|
|
|
@@ -362,13 +397,76 @@ def cross_worktree_lock(repo_root: Path):
|
|
|
362
397
|
handle.close()
|
|
363
398
|
|
|
364
399
|
|
|
365
|
-
|
|
400
|
+
@contextmanager
|
|
401
|
+
def adaptive_direct_owner_lock(repo_root: Path):
|
|
402
|
+
"""Yield the live primary-checkout owner while holding its OS lock."""
|
|
403
|
+
if fcntl is None:
|
|
404
|
+
raise LockError('OS file locking is unavailable; lock operation blocked')
|
|
405
|
+
state_dir = common_git_dir(repo_root) / 'gitguardex'
|
|
406
|
+
lease_path = state_dir / 'adaptive-direct-session.json'
|
|
407
|
+
lease_lock_path = state_dir / 'adaptive-direct-session.lock'
|
|
408
|
+
try:
|
|
409
|
+
state_dir.mkdir(parents=True, exist_ok=True)
|
|
410
|
+
handle = open(lease_lock_path, 'a+')
|
|
411
|
+
except OSError as exc:
|
|
412
|
+
raise LockError('cannot open the adaptive direct-session lock; claim blocked') from exc
|
|
413
|
+
acquired = False
|
|
414
|
+
contended = False
|
|
415
|
+
try:
|
|
416
|
+
try:
|
|
417
|
+
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
418
|
+
acquired = True
|
|
419
|
+
except BlockingIOError:
|
|
420
|
+
contended = True
|
|
421
|
+
except OSError as exc:
|
|
422
|
+
raise LockError('cannot acquire the adaptive direct-session lock; claim blocked') from exc
|
|
423
|
+
try:
|
|
424
|
+
lease = json.loads(lease_path.read_text())
|
|
425
|
+
except FileNotFoundError:
|
|
426
|
+
yield ''
|
|
427
|
+
return
|
|
428
|
+
except (OSError, json.JSONDecodeError, ValueError) as exc:
|
|
429
|
+
raise LockError('adaptive direct-session lease is unreadable; claim blocked') from exc
|
|
430
|
+
if not isinstance(lease, dict):
|
|
431
|
+
raise LockError('adaptive direct-session lease is malformed; claim blocked')
|
|
432
|
+
owner = lease.get('session_id')
|
|
433
|
+
last_seen = lease.get('last_seen_epoch')
|
|
434
|
+
if not isinstance(owner, str) or not owner.strip():
|
|
435
|
+
raise LockError('adaptive direct-session owner is malformed; claim blocked')
|
|
436
|
+
if isinstance(last_seen, bool) or not isinstance(last_seen, (int, float)):
|
|
437
|
+
raise LockError('adaptive direct-session timestamp is malformed; claim blocked')
|
|
438
|
+
raw_ttl = os.environ.get(ADAPTIVE_SESSION_LEASE_SECONDS_ENV, '').strip()
|
|
439
|
+
try:
|
|
440
|
+
ttl_seconds = float(raw_ttl) if raw_ttl else DEFAULT_ADAPTIVE_SESSION_LEASE_SECONDS
|
|
441
|
+
except ValueError as exc:
|
|
442
|
+
raise LockError('adaptive direct-session TTL is invalid; claim blocked') from exc
|
|
443
|
+
if ttl_seconds <= 0 or not math.isfinite(ttl_seconds):
|
|
444
|
+
raise LockError('adaptive direct-session TTL is invalid; claim blocked')
|
|
445
|
+
yield owner if contended or now_epoch() - float(last_seen) < ttl_seconds else ''
|
|
446
|
+
finally:
|
|
447
|
+
try:
|
|
448
|
+
if acquired:
|
|
449
|
+
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
|
|
450
|
+
finally:
|
|
451
|
+
handle.close()
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def cmd_claim(args: argparse.Namespace, repo_root: Path, adaptive_owner: str) -> int:
|
|
366
455
|
state = load_state(repo_root)
|
|
367
456
|
locks: dict[str, dict[str, Any]] = state['locks']
|
|
368
457
|
|
|
369
458
|
claim_agent = resolve_agent(args)
|
|
459
|
+
claim_session = resolve_session_id()
|
|
460
|
+
claim_pane = resolve_pane()
|
|
370
461
|
files = [normalize_repo_path(repo_root, p) for p in args.files]
|
|
371
|
-
|
|
462
|
+
if adaptive_owner and adaptive_owner != claim_session:
|
|
463
|
+
print(
|
|
464
|
+
'[agent-file-locks] Cannot claim files while adaptive direct work owns '
|
|
465
|
+
f'the primary checkout as {adaptive_owner}.',
|
|
466
|
+
file=sys.stderr,
|
|
467
|
+
)
|
|
468
|
+
return 1
|
|
469
|
+
conflicts: list[tuple[str, dict[str, Any]]] = []
|
|
372
470
|
|
|
373
471
|
# Conflict detection spans EVERY worktree of the repo, not just this one: a
|
|
374
472
|
# file claimed by another owner in a sibling worktree must still block this
|
|
@@ -381,7 +479,7 @@ def cmd_claim(args: argparse.Namespace, repo_root: Path) -> int:
|
|
|
381
479
|
for file_path in files:
|
|
382
480
|
foreign = [e for e in all_locks.get(file_path, []) if not owner_matches(e, args.branch, claim_agent)]
|
|
383
481
|
if foreign:
|
|
384
|
-
conflicts.append((file_path,
|
|
482
|
+
conflicts.append((file_path, foreign[0]))
|
|
385
483
|
claimed = parse_iso_epoch(str(foreign[0].get('claimed_at', '')))
|
|
386
484
|
if claimed is not None and (now - claimed) >= ttl_seconds:
|
|
387
485
|
any_stale = True
|
|
@@ -389,7 +487,7 @@ def cmd_claim(args: argparse.Namespace, repo_root: Path) -> int:
|
|
|
389
487
|
if conflicts:
|
|
390
488
|
print('[agent-file-locks] Cannot claim files already locked by another owner:', file=sys.stderr)
|
|
391
489
|
for file_path, owner in conflicts:
|
|
392
|
-
print(f' - {file_path} (locked by {owner})', file=sys.stderr)
|
|
490
|
+
print(f' - {file_path} (locked by {owner_description(owner)})', file=sys.stderr)
|
|
393
491
|
if any_stale:
|
|
394
492
|
print(
|
|
395
493
|
'[agent-file-locks] Some blocking locks are past the staleness TTL; if their '
|
|
@@ -404,11 +502,13 @@ def cmd_claim(args: argparse.Namespace, repo_root: Path) -> int:
|
|
|
404
502
|
# A named claim adopts/upgrades the entry's agent; an anonymous claim
|
|
405
503
|
# keeps any existing agent rather than silently downgrading it.
|
|
406
504
|
resolved_owner_agent = claim_agent or str(existing.get('agent', ''))
|
|
505
|
+
resolved_owner_pane = claim_pane or str(existing.get('pane', ''))
|
|
407
506
|
locks[file_path] = LockEntry(
|
|
408
507
|
branch=args.branch,
|
|
409
508
|
claimed_at=now_iso(),
|
|
410
509
|
allow_delete=args.allow_delete or existing_allow_delete,
|
|
411
510
|
agent=resolved_owner_agent,
|
|
511
|
+
pane=resolved_owner_pane,
|
|
412
512
|
).__dict__
|
|
413
513
|
|
|
414
514
|
write_state(repo_root, state)
|
|
@@ -595,7 +695,10 @@ def cmd_validate(args: argparse.Namespace, repo_root: Path) -> int:
|
|
|
595
695
|
for status, file_path in file_changes:
|
|
596
696
|
owners = all_locks.get(file_path, [])
|
|
597
697
|
if not owners:
|
|
598
|
-
|
|
698
|
+
if not args.allow_unclaimed:
|
|
699
|
+
missing.append(file_path)
|
|
700
|
+
elif status == 'D' and file_path in CRITICAL_GUARDRAIL_PATHS and not allow_guardrail_delete:
|
|
701
|
+
guardrail_delete_blocked.append(file_path)
|
|
599
702
|
continue
|
|
600
703
|
|
|
601
704
|
foreign_owners = [e for e in owners if not owner_matches(e, args.branch, agent)]
|
|
@@ -700,6 +803,11 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
700
803
|
validate.add_argument('--branch', required=True, help='Owner branch name')
|
|
701
804
|
add_agent_arg(validate)
|
|
702
805
|
validate.add_argument('--staged', action='store_true', help='Validate staged files from git index')
|
|
806
|
+
validate.add_argument(
|
|
807
|
+
'--allow-unclaimed',
|
|
808
|
+
action='store_true',
|
|
809
|
+
help='Allow unclaimed files while still rejecting foreign claims',
|
|
810
|
+
)
|
|
703
811
|
validate.add_argument('files', nargs='*', help='Files to validate when --staged is not used')
|
|
704
812
|
|
|
705
813
|
return parser
|
|
@@ -707,7 +815,7 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
707
815
|
|
|
708
816
|
def dispatch_command(args: argparse.Namespace, repo_root: Path) -> int:
|
|
709
817
|
if args.command == 'claim':
|
|
710
|
-
|
|
818
|
+
raise LockError('claim must run while holding the adaptive direct-session lock')
|
|
711
819
|
if args.command == 'allow-delete':
|
|
712
820
|
return cmd_allow_delete(args, repo_root)
|
|
713
821
|
if args.command == 'release':
|
|
@@ -734,6 +842,9 @@ def main() -> int:
|
|
|
734
842
|
# each other or both win the same file. status is a pure read -> unlocked.
|
|
735
843
|
if args.command in {'claim', 'allow-delete', 'release', 'reap', 'validate'}:
|
|
736
844
|
with cross_worktree_lock(repo_root):
|
|
845
|
+
if args.command == 'claim':
|
|
846
|
+
with adaptive_direct_owner_lock(repo_root) as adaptive_owner:
|
|
847
|
+
return cmd_claim(args, repo_root, adaptive_owner)
|
|
737
848
|
return dispatch_command(args, repo_root)
|
|
738
849
|
return dispatch_command(args, repo_root)
|
|
739
850
|
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
|
+
};
|