@imdeadpool/guardex 7.1.1 → 8.1.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 +115 -324
- package/package.json +23 -5
- package/skills/gitguardex/SKILL.md +83 -3
- package/src/agents/finish.js +15 -0
- package/src/ci-init/index.js +0 -1
- package/src/cli/args.js +137 -3
- package/src/cli/commands/branch.js +267 -14
- package/src/cli/commands/claude.js +15 -0
- package/src/cli/commands/doctor.js +26 -0
- package/src/cli/commands/onboard.js +293 -0
- package/src/cli/commands/prompt.js +15 -3
- package/src/cli/commands/review.js +18 -0
- package/src/cli/commands/setup.js +8 -6
- package/src/cli/commands/status.js +12 -0
- package/src/cli/main.js +2 -0
- package/src/cli/shared-locks.js +304 -0
- package/src/context.js +21 -3
- package/src/core/runtime.js +33 -1
- package/src/doctor/index.js +58 -5
- package/src/finish/heartbeat.js +169 -0
- package/src/finish/index.js +106 -4
- package/src/finish/progress.js +262 -0
- package/src/finish/review-gate.js +453 -32
- package/src/github-api.js +59 -0
- package/src/mcp/collect.js +87 -12
- package/src/output/index.js +210 -0
- package/src/pr-checks.js +121 -0
- package/src/pr-review.js +581 -51
- package/src/pr.js +143 -21
- package/src/provider-binary.js +101 -0
- package/src/review-diff.js +116 -0
- package/src/review-fix.js +229 -0
- package/src/sandbox/index.js +11 -5
- package/src/scaffold/index.js +4 -16
- package/src/shared-git-state.js +566 -0
- package/templates/AGENTS.multiagent-safety.md +63 -11
- package/templates/AGENTS.multiagent-safety.min.md +1 -0
- package/templates/codex/skills/gitguardex/SKILL.md +83 -3
- package/templates/githooks/post-checkout +4 -9
- package/templates/githooks/pre-commit +17 -1
- package/templates/github/workflows/README.md +30 -23
- package/templates/scripts/agent-autofinish-watch.sh +280 -0
- package/templates/scripts/agent-branch-finish.sh +354 -23
- package/templates/scripts/agent-branch-start.sh +49 -22
- package/templates/scripts/agent-claude-stop-finish.sh +194 -0
- package/templates/scripts/agent-file-locks.py +167 -24
- package/templates/scripts/agent-preflight.sh +14 -2
- package/templates/scripts/agent-stalled-report.sh +40 -0
- package/templates/scripts/codex-agent.sh +10 -63
- package/templates/github/workflows/cr.yml +0 -46
|
@@ -14,9 +14,9 @@ OPENSPEC_PLAN_SLUG_OVERRIDE="${GUARDEX_OPENSPEC_PLAN_SLUG:-}"
|
|
|
14
14
|
OPENSPEC_CHANGE_SLUG_OVERRIDE="${GUARDEX_OPENSPEC_CHANGE_SLUG:-}"
|
|
15
15
|
OPENSPEC_CAPABILITY_SLUG_OVERRIDE="${GUARDEX_OPENSPEC_CAPABILITY_SLUG:-}"
|
|
16
16
|
OPENSPEC_MASTERPLAN_LABEL_RAW="${GUARDEX_OPENSPEC_MASTERPLAN_LABEL-masterplan}"
|
|
17
|
-
# Default tier is T1 (
|
|
18
|
-
#
|
|
19
|
-
#
|
|
17
|
+
# Default tier is T1 (direct execution, no OpenSpec scaffold). T2/T3 remain
|
|
18
|
+
# explicit structured-workflow choices.
|
|
19
|
+
# Select --tier T2 for an explicit structured change or T3 for plan-driven work.
|
|
20
20
|
OPENSPEC_TIER_RAW="${GUARDEX_OPENSPEC_TIER:-T1}"
|
|
21
21
|
REUSE_EXISTING_RAW="${GUARDEX_BRANCH_START_REUSE_EXISTING:-true}"
|
|
22
22
|
AUTO_TRANSFER_ENABLED_RAW="${GUARDEX_AUTO_TRANSFER:-true}"
|
|
@@ -341,8 +341,8 @@ case "$OPENSPEC_TIER" in
|
|
|
341
341
|
OPENSPEC_SKIP_PLAN=1
|
|
342
342
|
;;
|
|
343
343
|
T1)
|
|
344
|
+
OPENSPEC_SKIP_CHANGE=1
|
|
344
345
|
OPENSPEC_SKIP_PLAN=1
|
|
345
|
-
OPENSPEC_MINIMAL=1
|
|
346
346
|
;;
|
|
347
347
|
T2)
|
|
348
348
|
OPENSPEC_SKIP_PLAN=1
|
|
@@ -910,21 +910,50 @@ case "$auto_transfer_enabled_lc" in
|
|
|
910
910
|
*) AUTO_TRANSFER_ENABLED=1 ;;
|
|
911
911
|
esac
|
|
912
912
|
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
if [[ -z "${AUTO_TRANSFER_EXCLUDE_RAW:-}" ]]; then
|
|
918
|
-
return 0
|
|
919
|
-
fi
|
|
920
|
-
printf '%s\0' '--' ':/'
|
|
913
|
+
path_matches_auto_transfer_exclude() {
|
|
914
|
+
local rel_path="$1"
|
|
915
|
+
[[ -n "${AUTO_TRANSFER_EXCLUDE_RAW:-}" ]] || return 1
|
|
916
|
+
|
|
921
917
|
local -a patterns=()
|
|
922
918
|
IFS=':' read -ra patterns <<< "$AUTO_TRANSFER_EXCLUDE_RAW"
|
|
923
919
|
local pattern
|
|
924
920
|
for pattern in "${patterns[@]}"; do
|
|
925
921
|
[[ -z "$pattern" ]] && continue
|
|
926
|
-
|
|
922
|
+
if [[ "$rel_path" == $pattern ]]; then
|
|
923
|
+
return 0
|
|
924
|
+
fi
|
|
927
925
|
done
|
|
926
|
+
return 1
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
collect_auto_transfer_paths() {
|
|
930
|
+
local root="$1"
|
|
931
|
+
local rel_path
|
|
932
|
+
declare -A seen_paths=()
|
|
933
|
+
|
|
934
|
+
while IFS= read -r -d '' rel_path; do
|
|
935
|
+
[[ -n "$rel_path" ]] || continue
|
|
936
|
+
[[ -z "${seen_paths[$rel_path]+seen}" ]] || continue
|
|
937
|
+
seen_paths["$rel_path"]=1
|
|
938
|
+
path_matches_auto_transfer_exclude "$rel_path" && continue
|
|
939
|
+
printf '%s\0' "$rel_path"
|
|
940
|
+
done < <(
|
|
941
|
+
git -C "$root" diff --name-only -z
|
|
942
|
+
git -C "$root" diff --cached --name-only -z
|
|
943
|
+
git -C "$root" ls-files --others --exclude-standard -z
|
|
944
|
+
)
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
build_auto_transfer_stash_argv() {
|
|
948
|
+
# Emit NUL-separated argv: --include-untracked --message <msg> -- <changed paths...>
|
|
949
|
+
# Use an explicit changed-file list instead of a root pathspec with excludes.
|
|
950
|
+
# `git stash push -- :/ :(exclude,glob).omc/** ...` can create a stash but
|
|
951
|
+
# still exit 1 when the repo has ignored .omc/.omx directories, which made the
|
|
952
|
+
# auto-transfer path silently skip a usable stash.
|
|
953
|
+
local root="$1"
|
|
954
|
+
local msg="$2"
|
|
955
|
+
printf '%s\0' --include-untracked --message "$msg" --
|
|
956
|
+
collect_auto_transfer_paths "$root"
|
|
928
957
|
}
|
|
929
958
|
|
|
930
959
|
current_branch="$(git -C "$repo_root" rev-parse --abbrev-ref HEAD 2>/dev/null || true)"
|
|
@@ -939,8 +968,10 @@ if [[ -n "$current_branch" && "$current_branch" != "HEAD" ]] && is_protected_bra
|
|
|
939
968
|
stash_argv=()
|
|
940
969
|
while IFS= read -r -d '' arg; do
|
|
941
970
|
stash_argv+=("$arg")
|
|
942
|
-
done < <(build_auto_transfer_stash_argv "$auto_transfer_message")
|
|
943
|
-
if
|
|
971
|
+
done < <(build_auto_transfer_stash_argv "$repo_root" "$auto_transfer_message")
|
|
972
|
+
if [[ "${#stash_argv[@]}" -le 4 ]]; then
|
|
973
|
+
echo "[agent-branch-start] Local changes on '${current_branch}' all match the auto-transfer exclude list; leaving them in place on '${current_branch}'." >&2
|
|
974
|
+
elif git -C "$repo_root" stash push "${stash_argv[@]}" >/dev/null 2>&1; then
|
|
944
975
|
auto_transfer_stash_ref="$(resolve_stash_ref_by_message "$repo_root" "$auto_transfer_message")"
|
|
945
976
|
if [[ -n "$auto_transfer_stash_ref" ]]; then
|
|
946
977
|
auto_transfer_source_branch="$current_branch"
|
|
@@ -948,11 +979,10 @@ if [[ -n "$current_branch" && "$current_branch" != "HEAD" ]] && is_protected_bra
|
|
|
948
979
|
if ! maybe_fail_after_auto_transfer_stash; then
|
|
949
980
|
exit 1
|
|
950
981
|
fi
|
|
951
|
-
else
|
|
952
|
-
if has_local_changes "$repo_root"; then
|
|
953
|
-
echo "[agent-branch-start] Local changes on '${current_branch}' all match the auto-transfer exclude list; leaving them in place on '${current_branch}'." >&2
|
|
954
|
-
fi
|
|
955
982
|
fi
|
|
983
|
+
else
|
|
984
|
+
echo "[agent-branch-start] Failed to capture local changes on protected branch '${current_branch}' for auto-transfer." >&2
|
|
985
|
+
exit 1
|
|
956
986
|
fi
|
|
957
987
|
fi
|
|
958
988
|
fi
|
|
@@ -1005,9 +1035,6 @@ fi
|
|
|
1005
1035
|
echo "[agent-branch-start] Created branch: ${branch_name}"
|
|
1006
1036
|
echo "[agent-branch-start] Worktree: ${worktree_path}"
|
|
1007
1037
|
echo "[agent-branch-start] OpenSpec tier: ${OPENSPEC_TIER}"
|
|
1008
|
-
if [[ "$OPENSPEC_TIER" == "T1" ]]; then
|
|
1009
|
-
echo "[agent-branch-start] T1 minimal scaffold (notes.md). Escalate: --tier T2 for a behavior change, T3 for plan-driven work."
|
|
1010
|
-
fi
|
|
1011
1038
|
if [[ "$OPENSPEC_AUTO_INIT" -ne 1 ]]; then
|
|
1012
1039
|
echo "[agent-branch-start] OpenSpec change: skipped (GUARDEX_OPENSPEC_AUTO_INIT disabled)"
|
|
1013
1040
|
elif [[ "$OPENSPEC_SKIP_CHANGE" -eq 1 ]]; then
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# Claude Stop hook: when a Claude session ends inside an agent/* worktree,
|
|
3
|
+
# hand the lane to the canonical Guardex finish flow so commits, PR merge wait,
|
|
4
|
+
# and sandbox cleanup stay coupled.
|
|
5
|
+
#
|
|
6
|
+
# Modes:
|
|
7
|
+
# GUARDEX_CLAUDE_STOP_FINISH=commit auto-commit dirty work via gx finish (default)
|
|
8
|
+
# GUARDEX_CLAUDE_STOP_FINISH=clean finish only clean committed lanes
|
|
9
|
+
# GUARDEX_CLAUDE_STOP_FINISH=off disable the hook
|
|
10
|
+
#
|
|
11
|
+
# The hook is fail-open: finish failures keep the sandbox and print a recovery
|
|
12
|
+
# command, but never block Claude's Stop event.
|
|
13
|
+
|
|
14
|
+
set -euo pipefail
|
|
15
|
+
|
|
16
|
+
NODE_BIN="${GUARDEX_NODE_BIN:-node}"
|
|
17
|
+
CLI_ENTRY="${GUARDEX_CLI_ENTRY:-}"
|
|
18
|
+
|
|
19
|
+
run_guardex_cli() {
|
|
20
|
+
if [[ -n "$CLI_ENTRY" ]]; then
|
|
21
|
+
"$NODE_BIN" "$CLI_ENTRY" "$@"
|
|
22
|
+
return $?
|
|
23
|
+
fi
|
|
24
|
+
if command -v gx >/dev/null 2>&1; then
|
|
25
|
+
gx "$@"
|
|
26
|
+
return $?
|
|
27
|
+
fi
|
|
28
|
+
if command -v gitguardex >/dev/null 2>&1; then
|
|
29
|
+
gitguardex "$@"
|
|
30
|
+
return $?
|
|
31
|
+
fi
|
|
32
|
+
echo "[agent-claude-stop-finish] Guardex CLI entrypoint unavailable; rerun via gx." >&2
|
|
33
|
+
return 127
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
normalize_mode() {
|
|
37
|
+
local raw="${1:-commit}" lowered
|
|
38
|
+
lowered="$(printf '%s' "$raw" | tr '[:upper:]' '[:lower:]')"
|
|
39
|
+
case "$lowered" in
|
|
40
|
+
''|1|true|yes|on|commit|dirty|auto) printf 'commit' ;;
|
|
41
|
+
clean|committed) printf 'clean' ;;
|
|
42
|
+
0|false|no|off|none|disabled) printf 'off' ;;
|
|
43
|
+
*)
|
|
44
|
+
echo "[agent-claude-stop-finish] Unknown GUARDEX_CLAUDE_STOP_FINISH='${raw}', using commit." >&2
|
|
45
|
+
printf 'commit'
|
|
46
|
+
;;
|
|
47
|
+
esac
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
json_field() {
|
|
51
|
+
local key="$1"
|
|
52
|
+
python3 -c '
|
|
53
|
+
import json
|
|
54
|
+
import sys
|
|
55
|
+
|
|
56
|
+
key = sys.argv[1]
|
|
57
|
+
try:
|
|
58
|
+
data = json.loads(sys.stdin.read() or "{}")
|
|
59
|
+
except Exception:
|
|
60
|
+
data = {}
|
|
61
|
+
value = data.get(key, "")
|
|
62
|
+
if isinstance(value, bool):
|
|
63
|
+
print("true" if value else "false")
|
|
64
|
+
elif value is not None:
|
|
65
|
+
print(value)
|
|
66
|
+
' "$key" 2>/dev/null || true
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
resolve_base_branch() {
|
|
70
|
+
local repo="$1" branch="$2" configured head_ref cand
|
|
71
|
+
configured="$(git -C "$repo" config --get "branch.${branch}.guardexBase" 2>/dev/null || true)"
|
|
72
|
+
if [[ -n "$configured" ]]; then
|
|
73
|
+
printf '%s' "$configured"
|
|
74
|
+
return 0
|
|
75
|
+
fi
|
|
76
|
+
configured="$(git -C "$repo" config --get multiagent.baseBranch 2>/dev/null || true)"
|
|
77
|
+
if [[ -n "$configured" ]]; then
|
|
78
|
+
printf '%s' "$configured"
|
|
79
|
+
return 0
|
|
80
|
+
fi
|
|
81
|
+
head_ref="$(git -C "$repo" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)"
|
|
82
|
+
if [[ -n "$head_ref" ]]; then
|
|
83
|
+
printf '%s' "${head_ref#origin/}"
|
|
84
|
+
return 0
|
|
85
|
+
fi
|
|
86
|
+
for cand in main dev master; do
|
|
87
|
+
if git -C "$repo" show-ref --verify --quiet "refs/heads/${cand}"; then
|
|
88
|
+
printf '%s' "$cand"
|
|
89
|
+
return 0
|
|
90
|
+
fi
|
|
91
|
+
done
|
|
92
|
+
printf 'main'
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
base_ref_for_count() {
|
|
96
|
+
local repo="$1" base="$2"
|
|
97
|
+
if git -C "$repo" show-ref --verify --quiet "refs/heads/${base}"; then
|
|
98
|
+
printf '%s' "$base"
|
|
99
|
+
return 0
|
|
100
|
+
fi
|
|
101
|
+
if git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/${base}"; then
|
|
102
|
+
printf 'origin/%s' "$base"
|
|
103
|
+
return 0
|
|
104
|
+
fi
|
|
105
|
+
return 1
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
dirty_count() {
|
|
109
|
+
local wt="$1"
|
|
110
|
+
git -C "$wt" status --porcelain -- . ":(exclude).omx/state/agent-file-locks.json" 2>/dev/null | grep -c . || true
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
payload="$(cat || true)"
|
|
114
|
+
event="$(printf '%s' "$payload" | json_field hook_event_name)"
|
|
115
|
+
stop_hook_active="$(printf '%s' "$payload" | json_field stop_hook_active)"
|
|
116
|
+
session_cwd="$(printf '%s' "$payload" | json_field cwd)"
|
|
117
|
+
|
|
118
|
+
if [[ -n "$event" && "$event" != "Stop" ]]; then
|
|
119
|
+
exit 0
|
|
120
|
+
fi
|
|
121
|
+
if [[ "$stop_hook_active" == "true" ]]; then
|
|
122
|
+
exit 0
|
|
123
|
+
fi
|
|
124
|
+
|
|
125
|
+
mode="$(normalize_mode "${GUARDEX_CLAUDE_STOP_FINISH:-commit}")"
|
|
126
|
+
if [[ "$mode" == "off" ]]; then
|
|
127
|
+
exit 0
|
|
128
|
+
fi
|
|
129
|
+
|
|
130
|
+
if [[ -z "$session_cwd" || ! -d "$session_cwd" ]]; then
|
|
131
|
+
session_cwd="$PWD"
|
|
132
|
+
fi
|
|
133
|
+
|
|
134
|
+
if ! worktree_path="$(git -C "$session_cwd" rev-parse --show-toplevel 2>/dev/null)"; then
|
|
135
|
+
exit 0
|
|
136
|
+
fi
|
|
137
|
+
if ! branch="$(git -C "$worktree_path" rev-parse --abbrev-ref HEAD 2>/dev/null)"; then
|
|
138
|
+
exit 0
|
|
139
|
+
fi
|
|
140
|
+
if [[ "$branch" != agent/* ]]; then
|
|
141
|
+
exit 0
|
|
142
|
+
fi
|
|
143
|
+
|
|
144
|
+
base_branch="$(resolve_base_branch "$worktree_path" "$branch")"
|
|
145
|
+
base_ref=""
|
|
146
|
+
ahead="0"
|
|
147
|
+
if base_ref="$(base_ref_for_count "$worktree_path" "$base_branch")"; then
|
|
148
|
+
ahead="$(git -C "$worktree_path" rev-list --count "${base_ref}..${branch}" 2>/dev/null || printf '0')"
|
|
149
|
+
fi
|
|
150
|
+
dirty="$(dirty_count "$worktree_path")"
|
|
151
|
+
|
|
152
|
+
if [[ "$dirty" -eq 0 && "$ahead" -eq 0 ]]; then
|
|
153
|
+
exit 0
|
|
154
|
+
fi
|
|
155
|
+
|
|
156
|
+
# --gate-review is not optional here. This hook fires unattended at the end of
|
|
157
|
+
# every agent turn, so a bare --via-pr lands the work with NOTHING having read
|
|
158
|
+
# it: the merge runs as soon as the *required* checks pass, and a repo without
|
|
159
|
+
# branch protection has none. Measured on opencue/gitguardex #700 —
|
|
160
|
+
# ready_for_review at 22:05:56Z, merged at 22:06:00Z, four seconds later, zero
|
|
161
|
+
# reviews on the PR, while a separately launched gated run was still reviewing
|
|
162
|
+
# that very branch.
|
|
163
|
+
#
|
|
164
|
+
# The gate is fail-closed: a CRITICAL/HIGH finding, red CI, or a PR GitHub will
|
|
165
|
+
# not merge each abort before the merge runs. Auto-landing unreviewed agent work
|
|
166
|
+
# is the outcome this tool exists to prevent.
|
|
167
|
+
finish_cmd=(
|
|
168
|
+
branch finish --branch "$branch" --base "$base_branch" --via-pr
|
|
169
|
+
--gate-review --review-provider claude
|
|
170
|
+
--wait-for-merge --cleanup
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
if [[ "$dirty" -gt 0 && "$mode" == "clean" ]]; then
|
|
174
|
+
echo "[agent-claude-stop-finish] ${branch}: ${dirty} uncommitted change(s); clean-only mode left the sandbox open." >&2
|
|
175
|
+
echo "[agent-claude-stop-finish] Finish manually when ready: gx ${finish_cmd[*]}" >&2
|
|
176
|
+
exit 0
|
|
177
|
+
fi
|
|
178
|
+
|
|
179
|
+
echo "[agent-claude-stop-finish] ${branch}: handing off to gx ${finish_cmd[*]}" >&2
|
|
180
|
+
finish_output=""
|
|
181
|
+
if finish_output="$(run_guardex_cli "${finish_cmd[@]}" 2>&1)"; then
|
|
182
|
+
printf '%s\n' "$finish_output"
|
|
183
|
+
if grep -q '^MERGE_HELD=1$' <<<"$finish_output"; then
|
|
184
|
+
echo "[agent-claude-stop-finish] ${branch}: merge held (guardex:merge-hold); sandbox kept at ${worktree_path}. Lift with: gx branch finish --branch ${branch} --auto-promote" >&2
|
|
185
|
+
else
|
|
186
|
+
echo "[agent-claude-stop-finish] ${branch}: finish completed." >&2
|
|
187
|
+
fi
|
|
188
|
+
exit 0
|
|
189
|
+
fi
|
|
190
|
+
|
|
191
|
+
printf '%s\n' "$finish_output" >&2
|
|
192
|
+
echo "[agent-claude-stop-finish] ${branch}: finish did not complete; sandbox kept at ${worktree_path}." >&2
|
|
193
|
+
echo "[agent-claude-stop-finish] Retry when ready: gx ${finish_cmd[*]}" >&2
|
|
194
|
+
exit 0
|
|
@@ -48,6 +48,11 @@ CRITICAL_GUARDRAIL_PATHS = {
|
|
|
48
48
|
'scripts/guardex-env.sh',
|
|
49
49
|
}
|
|
50
50
|
ALLOW_GUARDRAIL_DELETE_ENV = 'AGENT_ALLOW_GUARDRAIL_DELETE'
|
|
51
|
+
LOCK_TTL_HOURS_ENV = 'GUARDEX_LOCK_TTL_HOURS'
|
|
52
|
+
LOCK_NOW_EPOCH_ENV = 'GUARDEX_LOCK_NOW_EPOCH'
|
|
53
|
+
# Generous default so an active long-running lane is never reaped; `reap` is an
|
|
54
|
+
# explicit, opt-in maintenance command, not an automatic background sweep.
|
|
55
|
+
DEFAULT_LOCK_TTL_HOURS = 168.0 # 7 days
|
|
51
56
|
|
|
52
57
|
|
|
53
58
|
@dataclass
|
|
@@ -174,7 +179,7 @@ def write_state(repo_root: Path, state: dict[str, Any]) -> None:
|
|
|
174
179
|
|
|
175
180
|
|
|
176
181
|
def now_iso() -> str:
|
|
177
|
-
return datetime.
|
|
182
|
+
return datetime.fromtimestamp(now_epoch(), tz=timezone.utc).isoformat()
|
|
178
183
|
|
|
179
184
|
|
|
180
185
|
def env_truthy(value: str | None) -> bool:
|
|
@@ -183,6 +188,71 @@ def env_truthy(value: str | None) -> bool:
|
|
|
183
188
|
return value.strip().lower() in {'1', 'true', 'yes', 'on'}
|
|
184
189
|
|
|
185
190
|
|
|
191
|
+
def now_epoch() -> float:
|
|
192
|
+
"""Current unix time, overridable via GUARDEX_LOCK_NOW_EPOCH for tests."""
|
|
193
|
+
override = os.environ.get(LOCK_NOW_EPOCH_ENV)
|
|
194
|
+
if override:
|
|
195
|
+
try:
|
|
196
|
+
return float(override)
|
|
197
|
+
except ValueError:
|
|
198
|
+
pass
|
|
199
|
+
return datetime.now(timezone.utc).timestamp()
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def parse_iso_epoch(value: str) -> float | None:
|
|
203
|
+
"""Parse a `claimed_at` ISO-8601 stamp to a unix epoch, or None if unset
|
|
204
|
+
or unparseable. Naive stamps are assumed UTC (claims are written in UTC)."""
|
|
205
|
+
if not value:
|
|
206
|
+
return None
|
|
207
|
+
try:
|
|
208
|
+
dt = datetime.fromisoformat(value)
|
|
209
|
+
except ValueError:
|
|
210
|
+
return None
|
|
211
|
+
if dt.tzinfo is None:
|
|
212
|
+
dt = dt.replace(tzinfo=timezone.utc)
|
|
213
|
+
return dt.timestamp()
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def has_live_process_in_worktree(worktree: Path) -> bool:
|
|
217
|
+
"""True when any running process has its cwd inside `worktree` (Linux /proc
|
|
218
|
+
only; best-effort no elsewhere). Guards reap from touching an active lane."""
|
|
219
|
+
proc = Path('/proc')
|
|
220
|
+
if not proc.is_dir():
|
|
221
|
+
return False
|
|
222
|
+
wt = str(worktree)
|
|
223
|
+
try:
|
|
224
|
+
entries = list(proc.iterdir())
|
|
225
|
+
except OSError:
|
|
226
|
+
return False
|
|
227
|
+
for entry in entries:
|
|
228
|
+
if not entry.name.isdigit():
|
|
229
|
+
continue
|
|
230
|
+
try:
|
|
231
|
+
target = os.readlink(entry / 'cwd')
|
|
232
|
+
except OSError:
|
|
233
|
+
continue
|
|
234
|
+
if target.endswith(' (deleted)'):
|
|
235
|
+
target = target[: -len(' (deleted)')]
|
|
236
|
+
if target == wt or target.startswith(wt + os.sep):
|
|
237
|
+
return True
|
|
238
|
+
return False
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def resolve_ttl_hours(args: argparse.Namespace) -> float:
|
|
242
|
+
"""Reap TTL in hours: --ttl-hours wins, then GUARDEX_LOCK_TTL_HOURS, then
|
|
243
|
+
the 7-day default."""
|
|
244
|
+
explicit = getattr(args, 'ttl_hours', None)
|
|
245
|
+
if explicit is not None:
|
|
246
|
+
return float(explicit)
|
|
247
|
+
env = os.environ.get(LOCK_TTL_HOURS_ENV)
|
|
248
|
+
if env:
|
|
249
|
+
try:
|
|
250
|
+
return float(env)
|
|
251
|
+
except ValueError:
|
|
252
|
+
pass
|
|
253
|
+
return DEFAULT_LOCK_TTL_HOURS
|
|
254
|
+
|
|
255
|
+
|
|
186
256
|
def staged_changes(repo_root: Path) -> list[tuple[str, str]]:
|
|
187
257
|
out = run_git(['diff', '--cached', '--name-status', '--diff-filter=ACMRDTUXB'], cwd=repo_root)
|
|
188
258
|
if not out:
|
|
@@ -215,13 +285,14 @@ def list_worktree_roots(repo_root: Path) -> list[Path]:
|
|
|
215
285
|
report their gitdir (<parent>/.git/worktrees/<wt>/modules/<sub>) as the
|
|
216
286
|
worktree path, not the actual working tree — repo_root (resolved via
|
|
217
287
|
--show-toplevel) is where claims are written, so it must be in the list
|
|
218
|
-
or claim/validate/status never see this checkout's own lock file.
|
|
219
|
-
|
|
288
|
+
or claim/validate/status never see this checkout's own lock file. Lock
|
|
289
|
+
enforcement fails closed when Git cannot enumerate every sibling."""
|
|
220
290
|
try:
|
|
221
291
|
out = run_git(['worktree', 'list', '--porcelain'], cwd=repo_root)
|
|
222
|
-
except LockError:
|
|
223
|
-
|
|
224
|
-
|
|
292
|
+
except LockError as exc:
|
|
293
|
+
raise LockError(
|
|
294
|
+
'cannot safely enumerate sibling worktrees; lock operation blocked'
|
|
295
|
+
) from exc
|
|
225
296
|
roots: list[Path] = []
|
|
226
297
|
for line in out.splitlines():
|
|
227
298
|
if line.startswith('worktree '):
|
|
@@ -240,9 +311,11 @@ def load_all_locks(repo_root: Path) -> dict[str, list[dict[str, Any]]]:
|
|
|
240
311
|
for root in list_worktree_roots(repo_root):
|
|
241
312
|
try:
|
|
242
313
|
state = load_state(root)
|
|
243
|
-
except LockError:
|
|
244
|
-
|
|
245
|
-
|
|
314
|
+
except LockError as exc:
|
|
315
|
+
raise LockError(
|
|
316
|
+
f'cannot safely inspect sibling lock registry in {root}; '
|
|
317
|
+
'lock operation blocked'
|
|
318
|
+
) from exc
|
|
246
319
|
for file_path, entry in state['locks'].items():
|
|
247
320
|
merged.setdefault(file_path, []).append(entry)
|
|
248
321
|
return merged
|
|
@@ -263,29 +336,27 @@ def cross_worktree_lock(repo_root: Path):
|
|
|
263
336
|
common git dir), so concurrent claim/release/validate runs — in the same or
|
|
264
337
|
different worktrees — are serialized. Without it, two claims race on the
|
|
265
338
|
read-modify-write of separate lock files and can both win the same path or
|
|
266
|
-
drop each other's writes.
|
|
267
|
-
|
|
339
|
+
drop each other's writes. Mutual exclusion is a safety boundary: unavailable
|
|
340
|
+
OS locking or an inaccessible common lock file blocks the command."""
|
|
268
341
|
if fcntl is None:
|
|
269
|
-
|
|
270
|
-
return
|
|
342
|
+
raise LockError('OS file locking is unavailable; lock operation blocked')
|
|
271
343
|
try:
|
|
272
344
|
lock_path = common_git_dir(repo_root) / 'agent-file-locks.lock'
|
|
273
345
|
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
|
274
346
|
handle = open(lock_path, 'w')
|
|
275
|
-
except (OSError, LockError):
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
locked = False
|
|
347
|
+
except (OSError, LockError) as exc:
|
|
348
|
+
raise LockError('cannot open the shared worktree lock; operation blocked') from exc
|
|
349
|
+
acquired = False
|
|
279
350
|
try:
|
|
280
351
|
try:
|
|
281
352
|
fcntl.flock(handle.fileno(), fcntl.LOCK_EX)
|
|
282
|
-
|
|
283
|
-
except OSError:
|
|
284
|
-
|
|
353
|
+
acquired = True
|
|
354
|
+
except OSError as exc:
|
|
355
|
+
raise LockError('cannot acquire the shared worktree lock; operation blocked') from exc
|
|
285
356
|
yield
|
|
286
357
|
finally:
|
|
287
358
|
try:
|
|
288
|
-
if
|
|
359
|
+
if acquired:
|
|
289
360
|
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
|
|
290
361
|
finally:
|
|
291
362
|
handle.close()
|
|
@@ -304,15 +375,27 @@ def cmd_claim(args: argparse.Namespace, repo_root: Path) -> int:
|
|
|
304
375
|
# claim (each worktree keeps a separate lock file). The write below still
|
|
305
376
|
# records the claim in THIS worktree's lock file.
|
|
306
377
|
all_locks = load_all_locks(repo_root)
|
|
378
|
+
ttl_seconds = resolve_ttl_hours(args) * 3600.0
|
|
379
|
+
now = now_epoch()
|
|
380
|
+
any_stale = False
|
|
307
381
|
for file_path in files:
|
|
308
382
|
foreign = [e for e in all_locks.get(file_path, []) if not owner_matches(e, args.branch, claim_agent)]
|
|
309
383
|
if foreign:
|
|
310
384
|
conflicts.append((file_path, owner_label(foreign[0])))
|
|
385
|
+
claimed = parse_iso_epoch(str(foreign[0].get('claimed_at', '')))
|
|
386
|
+
if claimed is not None and (now - claimed) >= ttl_seconds:
|
|
387
|
+
any_stale = True
|
|
311
388
|
|
|
312
389
|
if conflicts:
|
|
313
390
|
print('[agent-file-locks] Cannot claim files already locked by another owner:', file=sys.stderr)
|
|
314
391
|
for file_path, owner in conflicts:
|
|
315
392
|
print(f' - {file_path} (locked by {owner})', file=sys.stderr)
|
|
393
|
+
if any_stale:
|
|
394
|
+
print(
|
|
395
|
+
'[agent-file-locks] Some blocking locks are past the staleness TTL; if their '
|
|
396
|
+
'lane is abandoned, run `gx locks reap` to clear them.',
|
|
397
|
+
file=sys.stderr,
|
|
398
|
+
)
|
|
316
399
|
return 1
|
|
317
400
|
|
|
318
401
|
for file_path in files:
|
|
@@ -394,6 +477,52 @@ def cmd_release(args: argparse.Namespace, repo_root: Path) -> int:
|
|
|
394
477
|
return 0
|
|
395
478
|
|
|
396
479
|
|
|
480
|
+
def cmd_reap(args: argparse.Namespace, repo_root: Path) -> int:
|
|
481
|
+
# Clear locks held by ABANDONED worktrees: present on disk, idle past the
|
|
482
|
+
# TTL, and with no live process inside. Dead worktrees self-clean (their lock
|
|
483
|
+
# file lives inside them), so this targets the lingering-but-idle case where
|
|
484
|
+
# a crashed or forgotten lane keeps blocking a file forever. The caller's own
|
|
485
|
+
# worktree always has a live process, so reap never clears its active locks.
|
|
486
|
+
ttl_hours = resolve_ttl_hours(args)
|
|
487
|
+
ttl_seconds = ttl_hours * 3600.0
|
|
488
|
+
now = now_epoch()
|
|
489
|
+
roots = list_worktree_roots(repo_root)
|
|
490
|
+
reaped: list[tuple[str, str, str, int]] = [] # worktree, file, branch, age_hours
|
|
491
|
+
for root in roots:
|
|
492
|
+
try:
|
|
493
|
+
state = load_state(root)
|
|
494
|
+
except LockError as exc:
|
|
495
|
+
raise LockError(
|
|
496
|
+
f'cannot safely inspect sibling lock registry in {root}; '
|
|
497
|
+
'reap operation blocked'
|
|
498
|
+
) from exc
|
|
499
|
+
locks = state['locks']
|
|
500
|
+
if not locks:
|
|
501
|
+
continue
|
|
502
|
+
if has_live_process_in_worktree(root):
|
|
503
|
+
continue
|
|
504
|
+
survivors: dict[str, Any] = {}
|
|
505
|
+
changed = False
|
|
506
|
+
for file_path, entry in locks.items():
|
|
507
|
+
claimed = parse_iso_epoch(str(entry.get('claimed_at', '')))
|
|
508
|
+
if claimed is not None and (now - claimed) >= ttl_seconds:
|
|
509
|
+
reaped.append((str(root), file_path, str(entry.get('branch', '')), int((now - claimed) // 3600)))
|
|
510
|
+
changed = True
|
|
511
|
+
else:
|
|
512
|
+
survivors[file_path] = entry
|
|
513
|
+
if changed and not args.dry_run:
|
|
514
|
+
write_state(root, {**state, 'locks': survivors})
|
|
515
|
+
|
|
516
|
+
if not reaped:
|
|
517
|
+
print(f'[agent-file-locks] reap: no stale locks (ttl={int(ttl_hours)}h, scanned {len(roots)} worktree(s)).')
|
|
518
|
+
return 0
|
|
519
|
+
label = '[agent-file-locks] [dry-run] would reap' if args.dry_run else '[agent-file-locks] reaped'
|
|
520
|
+
print(f'{label} {len(reaped)} stale lock(s) (ttl={int(ttl_hours)}h):')
|
|
521
|
+
for root, file_path, branch, age_hours in reaped:
|
|
522
|
+
print(f' - {file_path} | {branch} | idle {age_hours}h | {root}')
|
|
523
|
+
return 0
|
|
524
|
+
|
|
525
|
+
|
|
397
526
|
def cmd_status(args: argparse.Namespace, repo_root: Path) -> int:
|
|
398
527
|
# Union across worktrees so status reflects what claim/validate now enforce —
|
|
399
528
|
# a sibling worktree's claims would otherwise be invisible here.
|
|
@@ -404,8 +533,11 @@ def cmd_status(args: argparse.Namespace, repo_root: Path) -> int:
|
|
|
404
533
|
for root in roots:
|
|
405
534
|
try:
|
|
406
535
|
locks = load_state(root)['locks']
|
|
407
|
-
except LockError:
|
|
408
|
-
|
|
536
|
+
except LockError as exc:
|
|
537
|
+
raise LockError(
|
|
538
|
+
f'cannot safely inspect sibling lock registry in {root}; '
|
|
539
|
+
'status is unavailable'
|
|
540
|
+
) from exc
|
|
409
541
|
for file_path, entry in locks.items():
|
|
410
542
|
branch = str(entry.get('branch', ''))
|
|
411
543
|
if args.branch and branch != args.branch:
|
|
@@ -555,6 +687,15 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
555
687
|
status.add_argument('--branch', help='Filter by branch')
|
|
556
688
|
add_agent_arg(status)
|
|
557
689
|
|
|
690
|
+
reap = sub.add_parser('reap', help='Clear stale locks from abandoned (idle past TTL, no live process) worktrees')
|
|
691
|
+
reap.add_argument(
|
|
692
|
+
'--ttl-hours',
|
|
693
|
+
type=float,
|
|
694
|
+
default=None,
|
|
695
|
+
help=f'Idle hours before a lock is stale (default {int(DEFAULT_LOCK_TTL_HOURS)}h or ${LOCK_TTL_HOURS_ENV})',
|
|
696
|
+
)
|
|
697
|
+
reap.add_argument('--dry-run', action='store_true', help='Report stale locks without removing them')
|
|
698
|
+
|
|
558
699
|
validate = sub.add_parser('validate', help='Validate staged files are locked by branch')
|
|
559
700
|
validate.add_argument('--branch', required=True, help='Owner branch name')
|
|
560
701
|
add_agent_arg(validate)
|
|
@@ -571,6 +712,8 @@ def dispatch_command(args: argparse.Namespace, repo_root: Path) -> int:
|
|
|
571
712
|
return cmd_allow_delete(args, repo_root)
|
|
572
713
|
if args.command == 'release':
|
|
573
714
|
return cmd_release(args, repo_root)
|
|
715
|
+
if args.command == 'reap':
|
|
716
|
+
return cmd_reap(args, repo_root)
|
|
574
717
|
if args.command == 'status':
|
|
575
718
|
return cmd_status(args, repo_root)
|
|
576
719
|
if args.command == 'validate':
|
|
@@ -589,7 +732,7 @@ def main() -> int:
|
|
|
589
732
|
# Serialize state-changing commands (and validate's snapshot read) across
|
|
590
733
|
# ALL worktrees with one shared lock, so concurrent runs can't clobber
|
|
591
734
|
# each other or both win the same file. status is a pure read -> unlocked.
|
|
592
|
-
if args.command in {'claim', 'allow-delete', 'release', 'validate'}:
|
|
735
|
+
if args.command in {'claim', 'allow-delete', 'release', 'reap', 'validate'}:
|
|
593
736
|
with cross_worktree_lock(repo_root):
|
|
594
737
|
return dispatch_command(args, repo_root)
|
|
595
738
|
return dispatch_command(args, repo_root)
|
|
@@ -31,13 +31,25 @@ fail=0
|
|
|
31
31
|
# failure (where it is actually useful). Stream full output live with
|
|
32
32
|
# GUARDEX_PREFLIGHT_VERBOSE=1.
|
|
33
33
|
GUARDEX_PREFLIGHT_FAIL_TAIL="${GUARDEX_PREFLIGHT_FAIL_TAIL:-40}"
|
|
34
|
+
run_verification_command() {
|
|
35
|
+
env \
|
|
36
|
+
-u ALLOW_BASH_ON_NON_AGENT_BRANCH \
|
|
37
|
+
-u ALLOW_CODE_EDIT_ON_PROTECTED_BRANCH \
|
|
38
|
+
-u ALLOW_CODE_EDIT_ON_PRIMARY_WORKTREE \
|
|
39
|
+
-u ALLOW_COMMIT_ON_PROTECTED_BRANCH \
|
|
40
|
+
-u ALLOW_PUSH_ON_PROTECTED_BRANCH \
|
|
41
|
+
-u GUARDEX_CLI_ENTRY \
|
|
42
|
+
-u GUARDEX_NODE_BIN \
|
|
43
|
+
"$@"
|
|
44
|
+
}
|
|
45
|
+
|
|
34
46
|
run_step() {
|
|
35
47
|
local label="$1"
|
|
36
48
|
shift
|
|
37
49
|
echo "[agent-preflight] -> $label"
|
|
38
50
|
attempted=$((attempted + 1))
|
|
39
51
|
if [[ "${GUARDEX_PREFLIGHT_VERBOSE:-0}" == "1" ]]; then
|
|
40
|
-
if "$@"; then
|
|
52
|
+
if run_verification_command "$@"; then
|
|
41
53
|
ran=$((ran + 1))
|
|
42
54
|
echo "[agent-preflight] ok"
|
|
43
55
|
else
|
|
@@ -48,7 +60,7 @@ run_step() {
|
|
|
48
60
|
fi
|
|
49
61
|
local out rc
|
|
50
62
|
# `if` keeps `set -e` from aborting on a failing step before we capture rc.
|
|
51
|
-
if out="$("$@" 2>&1)"; then
|
|
63
|
+
if out="$(run_verification_command "$@" 2>&1)"; then
|
|
52
64
|
rc=0
|
|
53
65
|
else
|
|
54
66
|
rc=$?
|