@imdeadpool/guardex 8.2.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.
@@ -11,6 +11,7 @@ MERGE_MODE="auto"
11
11
  GH_BIN="${GUARDEX_GH_BIN:-gh}"
12
12
  NODE_BIN="${GUARDEX_NODE_BIN:-node}"
13
13
  CLI_ENTRY="${GUARDEX_CLI_ENTRY:-}"
14
+ FINISH_SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
14
15
  CLEANUP_AFTER_MERGE_RAW="${GUARDEX_FINISH_CLEANUP:-true}"
15
16
  WAIT_FOR_MERGE_RAW="${GUARDEX_FINISH_WAIT_FOR_MERGE:-true}"
16
17
  WAIT_TIMEOUT_SECONDS_RAW="${GUARDEX_FINISH_WAIT_TIMEOUT_SECONDS:-1800}"
@@ -19,8 +20,12 @@ PARENT_GITLINK_AUTO_COMMIT_RAW="${GUARDEX_FINISH_PARENT_GITLINK_AUTO_COMMIT:-tru
19
20
  AUTO_RESOLVE_MODE_RAW="${GUARDEX_FINISH_AUTO_RESOLVE:-none}"
20
21
  AUTO_RESOLVE_SAFE_GLOBS_DEFAULT='.omc/**:.omx/state/**:.dev-ports.json:apps/logs/**:.codex/settings.local.json:.claude/settings.local.json:.codex/state/**:.claude/state/**'
21
22
  AUTO_RESOLVE_SAFE_GLOBS_RAW="${GUARDEX_FINISH_AUTO_RESOLVE_SAFE_GLOBS-$AUTO_RESOLVE_SAFE_GLOBS_DEFAULT}"
23
+ RECONCILE_OPENSPEC_TASKS_RAW="${GUARDEX_FINISH_RECONCILE_OPENSPEC_TASKS:-true}"
24
+ OPENSPEC_TASKS_RECONCILER="${GUARDEX_FINISH_OPENSPEC_TASKS_RECONCILER:-${FINISH_SCRIPT_DIR}/agent-reconcile-openspec-tasks.js}"
22
25
  PREFLIGHT_ENABLED_RAW="${GUARDEX_FINISH_PREFLIGHT:-true}"
23
26
  PREFLIGHT_SCRIPT_RAW="${GUARDEX_FINISH_PREFLIGHT_SCRIPT:-scripts/agent-preflight.sh}"
27
+ PREFLIGHT_REQUIRED_RAW="${GUARDEX_FINISH_REQUIRE_PREFLIGHT:-false}"
28
+ PREFLIGHT_CACHE_ENABLED_RAW="${GUARDEX_FINISH_PREFLIGHT_CACHE:-true}"
24
29
  AUTO_PROMOTE_DRAFT_RAW="${GUARDEX_FINISH_AUTO_PROMOTE:-true}"
25
30
  FINISH_CHECKLIST_RAW="${GUARDEX_FINISH_CHECKLIST:-false}"
26
31
  FINISH_GATE_DONE_RAW="${GUARDEX_FINISH_GATE_DONE:-false}"
@@ -142,16 +147,36 @@ finish_progress() {
142
147
  finish_event "$stage" "$state" "$number" "$label" "$detail"
143
148
  }
144
149
 
145
- # Resolve the pre-flight script path against the source worktree. The
146
- # caller passes either the configured path (which may be relative) or
147
- # an empty string; we return the absolute path if it exists and is
148
- # executable, otherwise return empty.
150
+ # Resolve the pre-flight script path. Required relative scripts run from a
151
+ # temporary archive of the trusted base ref so script-relative helpers are also
152
+ # trusted; optional relative scripts retain worktree behavior.
149
153
  resolve_preflight_script() {
150
154
  local worktree="$1"
151
155
  local configured="$2"
152
156
  if [[ -z "$configured" ]]; then
153
157
  configured="scripts/agent-preflight.sh"
154
158
  fi
159
+ if [[ "${PREFLIGHT_REQUIRED:-0}" -eq 1 ]]; then
160
+ configured="${configured#./}"
161
+ if [[ -z "$configured" || "$configured" = /* || "$configured" == ".." || "$configured" == ../*
162
+ || "$configured" == */../* || "$configured" == */.. ]]; then
163
+ return 0
164
+ fi
165
+ local trusted_tree=""
166
+ trusted_tree="$(mktemp -d "${TMPDIR:-/tmp}/guardex-preflight.XXXXXX")" || return 0
167
+ if git -C "$worktree" archive "$start_ref" 2>/dev/null | tar -x -C "$trusted_tree" 2>/dev/null; then
168
+ local trusted_script="${trusted_tree}/${configured}"
169
+ local trusted_script_real=""
170
+ trusted_script_real="$(realpath -e -- "$trusted_script" 2>/dev/null || true)"
171
+ if [[ -n "$trusted_script_real" && "$trusted_script_real" == "$trusted_tree/"* && -x "$trusted_script_real" ]]; then
172
+ trusted_script="$trusted_script_real"
173
+ printf '%s' "$trusted_script"
174
+ return 0
175
+ fi
176
+ fi
177
+ rm -rf -- "$trusted_tree"
178
+ return 0
179
+ fi
155
180
  if [[ "$configured" = /* ]]; then
156
181
  if [[ -x "$configured" ]]; then
157
182
  printf '%s' "$configured"
@@ -164,6 +189,71 @@ resolve_preflight_script() {
164
189
  fi
165
190
  }
166
191
 
192
+ # Bind a reusable success receipt to every input that can change the result.
193
+ # The receipt is per source branch and is overwritten when HEAD, the base ref,
194
+ # or the configured preflight script changes. Mandatory billing-waiver
195
+ # preflights deliberately bypass this cache and always execute fail-closed.
196
+ preflight_cache_fingerprint() {
197
+ local worktree="$1"
198
+ local script_path="$2"
199
+ local source_sha=""
200
+ local base_sha=""
201
+ local script_sha=""
202
+
203
+ source_sha="$(git -C "$worktree" rev-parse 'HEAD^{commit}' 2>/dev/null || true)"
204
+ base_sha="$(git -C "$worktree" rev-parse "${start_ref}^{commit}" 2>/dev/null || true)"
205
+ script_sha="$(git -C "$worktree" hash-object --no-filters "$script_path" 2>/dev/null || true)"
206
+ if [[ -z "$source_sha" || -z "$base_sha" || -z "$script_sha" ]]; then
207
+ return 0
208
+ fi
209
+
210
+ printf 'guardex-preflight-cache-v1\n%s\n%s\n%s\n%s\n' \
211
+ "$source_sha" "$base_sha" "$PREFLIGHT_SCRIPT_RAW" "$script_sha" \
212
+ | git -C "$worktree" hash-object --stdin 2>/dev/null || true
213
+ }
214
+
215
+ preflight_cache_receipt_path() {
216
+ local worktree="$1"
217
+ local common_git_dir=""
218
+ local branch_name=""
219
+ local branch_key=""
220
+
221
+ common_git_dir="$(git -C "$worktree" rev-parse --git-common-dir 2>/dev/null || true)"
222
+ if [[ -z "$common_git_dir" ]]; then
223
+ return 0
224
+ fi
225
+ if [[ "$common_git_dir" != /* ]]; then
226
+ common_git_dir="${worktree}/${common_git_dir}"
227
+ fi
228
+ branch_name="${SOURCE_BRANCH:-$(git -C "$worktree" symbolic-ref --quiet --short HEAD 2>/dev/null || true)}"
229
+ if [[ -z "$branch_name" ]]; then
230
+ return 0
231
+ fi
232
+ branch_key="$(printf '%s' "$branch_name" | git -C "$worktree" hash-object --stdin 2>/dev/null || true)"
233
+ if [[ -z "$branch_key" ]]; then
234
+ return 0
235
+ fi
236
+
237
+ printf '%s/guardex/preflight-cache/%s.receipt' "$common_git_dir" "$branch_key"
238
+ }
239
+
240
+ write_preflight_cache_receipt() {
241
+ local receipt_path="$1"
242
+ local fingerprint="$2"
243
+ local receipt_dir=""
244
+ local temporary_receipt=""
245
+
246
+ [[ -n "$receipt_path" && -n "$fingerprint" ]] || return 0
247
+ receipt_dir="$(dirname "$receipt_path")"
248
+ mkdir -p "$receipt_dir" 2>/dev/null || return 0
249
+ temporary_receipt="${receipt_path}.$$"
250
+ if printf '%s\n' "$fingerprint" > "$temporary_receipt" 2>/dev/null; then
251
+ mv -f "$temporary_receipt" "$receipt_path" 2>/dev/null || rm -f "$temporary_receipt"
252
+ else
253
+ rm -f "$temporary_receipt"
254
+ fi
255
+ }
256
+
167
257
  # Run the pre-flight verification gate in the agent worktree before
168
258
  # any push happens. Returns 0 on success or when no gate is
169
259
  # configured; returns non-zero (and prints a hint) on failure, which
@@ -171,19 +261,79 @@ resolve_preflight_script() {
171
261
  run_preflight() {
172
262
  local worktree="$1"
173
263
  if [[ "$PREFLIGHT_ENABLED" -ne 1 ]]; then
264
+ if [[ "$PREFLIGHT_REQUIRED" -eq 1 ]]; then
265
+ finish_progress failed preflight "required because GitHub billing checks were waived"
266
+ echo "[agent-branch-finish] Billing-waived GitHub checks require local pre-flight; --no-preflight is not allowed." >&2
267
+ return 1
268
+ fi
174
269
  finish_progress skipped preflight "disabled by flag"
175
270
  return 0
176
271
  fi
177
272
  local script_path
178
273
  script_path="$(resolve_preflight_script "$worktree" "$PREFLIGHT_SCRIPT_RAW")"
179
274
  if [[ -z "$script_path" ]]; then
275
+ if [[ "$PREFLIGHT_REQUIRED" -eq 1 ]]; then
276
+ finish_progress failed preflight "required executable script missing"
277
+ echo "[agent-branch-finish] Billing-waived GitHub checks require a target-aware pre-flight script at ${PREFLIGHT_SCRIPT_RAW} in trusted base ${start_ref}; refusing push." >&2
278
+ return 1
279
+ fi
180
280
  finish_progress skipped preflight "no executable pre-flight script"
181
281
  echo "[agent-branch-finish] No executable pre-flight script at ${PREFLIGHT_SCRIPT_RAW} (in ${worktree}); skipping pre-flight." >&2
182
282
  return 0
183
283
  fi
184
284
  finish_progress running preflight "final verification before publish"
185
285
  echo "[agent-branch-finish] Running pre-flight: ${script_path}" >&2
186
- if ( cd "$worktree" && "$script_path" ); then
286
+ local preflight_cwd="$worktree"
287
+ local trusted_tree=""
288
+ if [[ "$PREFLIGHT_REQUIRED" -eq 1 && "$PREFLIGHT_SCRIPT_RAW" != /* ]]; then
289
+ local relative_configured="${PREFLIGHT_SCRIPT_RAW#./}"
290
+ local trusted_prefix="${TMPDIR:-/tmp}/guardex-preflight."
291
+ if [[ "$script_path" != "$trusted_prefix"*"/$relative_configured" ]]; then
292
+ finish_progress failed preflight "trusted execution tree missing"
293
+ echo "[agent-branch-finish] Mandatory pre-flight did not resolve inside its trusted base archive; refusing push." >&2
294
+ return 1
295
+ fi
296
+ local trusted_tree_length=$((${#script_path} - ${#relative_configured} - 1))
297
+ trusted_tree="${script_path:0:$trusted_tree_length}"
298
+ preflight_cwd="$trusted_tree"
299
+ local capabilities=""
300
+ capabilities="$(cd "$preflight_cwd" && "$script_path" --guardex-capabilities 2>/dev/null || true)"
301
+ if [[ "$capabilities" != "guardex-target-worktree-v1" ]]; then
302
+ rm -rf -- "$trusted_tree"
303
+ finish_progress failed preflight "trusted script does not support the target-worktree protocol"
304
+ echo "[agent-branch-finish] Mandatory pre-flight must implement guardex-target-worktree-v1; refusing push." >&2
305
+ return 1
306
+ fi
307
+ fi
308
+ local cache_fingerprint=""
309
+ local cache_receipt_path=""
310
+ local cached_fingerprint=""
311
+ if [[ "${PREFLIGHT_CACHE_ENABLED:-1}" -eq 1 && "$PREFLIGHT_REQUIRED" -ne 1 ]]; then
312
+ cache_fingerprint="$(preflight_cache_fingerprint "$worktree" "$script_path")"
313
+ cache_receipt_path="$(preflight_cache_receipt_path "$worktree")"
314
+ if [[ -n "$cache_fingerprint" && -n "$cache_receipt_path" && -f "$cache_receipt_path" ]]; then
315
+ cached_fingerprint="$(head -n 1 "$cache_receipt_path" 2>/dev/null || true)"
316
+ if [[ "$cached_fingerprint" == "$cache_fingerprint" ]]; then
317
+ if [[ -n "$trusted_tree" ]]; then
318
+ rm -rf -- "$trusted_tree"
319
+ fi
320
+ finish_progress complete preflight "cached pass"
321
+ echo "[agent-branch-finish] Pre-flight unchanged; reusing cached successful result." >&2
322
+ return 0
323
+ fi
324
+ fi
325
+ fi
326
+ local preflight_status=0
327
+ if [[ -n "$trusted_tree" ]]; then
328
+ ( cd "$preflight_cwd" && "$script_path" --guardex-target-worktree "$worktree" ) || preflight_status=$?
329
+ else
330
+ ( cd "$preflight_cwd" && GUARDEX_PREFLIGHT_TARGET_WORKTREE="$worktree" "$script_path" ) || preflight_status=$?
331
+ fi
332
+ if [[ -n "$trusted_tree" ]]; then
333
+ rm -rf -- "$trusted_tree"
334
+ fi
335
+ if [[ "$preflight_status" -eq 0 ]]; then
336
+ write_preflight_cache_receipt "$cache_receipt_path" "$cache_fingerprint"
187
337
  finish_progress complete preflight "passed"
188
338
  echo "[agent-branch-finish] Pre-flight passed." >&2
189
339
  return 0
@@ -281,6 +431,8 @@ WAIT_POLL_SECONDS="$(normalize_int "$WAIT_POLL_SECONDS_RAW" "10" "0")"
281
431
  PARENT_GITLINK_AUTO_COMMIT="$(normalize_bool "$PARENT_GITLINK_AUTO_COMMIT_RAW" "1")"
282
432
  FINISH_CHECKLIST="$(normalize_bool "$FINISH_CHECKLIST_RAW" "0")"
283
433
  FINISH_GATE_DONE="$(normalize_bool "$FINISH_GATE_DONE_RAW" "0")"
434
+ PREFLIGHT_REQUIRED="$(normalize_bool "$PREFLIGHT_REQUIRED_RAW" "0")"
435
+ RECONCILE_OPENSPEC_TASKS="$(normalize_bool "$RECONCILE_OPENSPEC_TASKS_RAW" "1")"
284
436
 
285
437
  while [[ $# -gt 0 ]]; do
286
438
  case "$1" in
@@ -408,6 +560,7 @@ done
408
560
  # silently ignored the flags, leaving --no-preflight inert. Flags that set the
409
561
  # normalized var directly in-loop (--cleanup, --wait-for-merge, ...) are unaffected.
410
562
  PREFLIGHT_ENABLED="$(normalize_bool "$PREFLIGHT_ENABLED_RAW" "1")"
563
+ PREFLIGHT_CACHE_ENABLED="$(normalize_bool "$PREFLIGHT_CACHE_ENABLED_RAW" "1")"
411
564
  AUTO_PROMOTE_DRAFT="$(normalize_bool "$AUTO_PROMOTE_DRAFT_RAW" "1")"
412
565
 
413
566
  if [[ "$CLEANUP_AFTER_MERGE" -eq 1 && "$DELETE_REMOTE_BRANCH_EXPLICIT" -eq 0 ]]; then
@@ -469,6 +622,89 @@ path_matches_auto_resolve_safe_glob() {
469
622
  return 1
470
623
  }
471
624
 
625
+ is_openspec_change_tasks_path() {
626
+ local conflict_path="$1"
627
+ [[ "$conflict_path" =~ ^openspec/changes/[^/]+/tasks\.md$ ]]
628
+ }
629
+
630
+ try_reconcile_openspec_tasks_conflict() {
631
+ local worktree="$1"
632
+ local conflict_path="$2"
633
+ [[ "$RECONCILE_OPENSPEC_TASKS" -eq 1 ]] || return 1
634
+ is_openspec_change_tasks_path "$conflict_path" || return 1
635
+ if [[ ! -f "$OPENSPEC_TASKS_RECONCILER" ]]; then
636
+ echo "[agent-branch-finish] OpenSpec tasks reconciler missing: ${OPENSPEC_TASKS_RECONCILER}" >&2
637
+ return 1
638
+ fi
639
+ "$NODE_BIN" "$OPENSPEC_TASKS_RECONCILER" "$worktree" "$conflict_path" >/dev/null
640
+ }
641
+
642
+ validate_reconciled_openspec_tasks() {
643
+ local worktree="$1"
644
+ local reconciled_paths="$2"
645
+ local conflict_path=""
646
+ local change_name=""
647
+ if ! command -v openspec >/dev/null 2>&1; then
648
+ echo "[agent-branch-finish] openspec CLI unavailable; deterministic tasks.md validation passed, spec validation skipped." >&2
649
+ return 0
650
+ fi
651
+ while IFS= read -r conflict_path; do
652
+ [[ -z "$conflict_path" ]] && continue
653
+ if ! is_openspec_change_tasks_path "$conflict_path"; then
654
+ echo "[agent-branch-finish] Refusing to validate unexpected reconciled path: ${conflict_path}" >&2
655
+ return 1
656
+ fi
657
+ change_name="${conflict_path#openspec/changes/}"
658
+ change_name="${change_name%/tasks.md}"
659
+ if ! (cd "$worktree" && openspec validate "$change_name" --type change --strict --no-interactive >/dev/null); then
660
+ echo "[agent-branch-finish] OpenSpec validation failed for change '${change_name}' after tasks.md reconciliation; leaving the Git operation for manual repair." >&2
661
+ return 1
662
+ fi
663
+ done < <(printf '%s' "$reconciled_paths" | sort -u)
664
+ }
665
+
666
+ try_finish_rebase_with_openspec_tasks() {
667
+ local worktree="$1"
668
+ local git_dir=""
669
+ local conflict_files=""
670
+ local conflict_path=""
671
+ local resolved_paths=""
672
+ local resolved_round=""
673
+
674
+ git_dir="$(git -C "$worktree" rev-parse --absolute-git-dir 2>/dev/null || true)"
675
+ while [[ -n "$git_dir" && ( -e "${git_dir}/rebase-merge" || -e "${git_dir}/rebase-apply" ) ]]; do
676
+ conflict_files="$(git -C "$worktree" diff --name-only --diff-filter=U || true)"
677
+ [[ -n "$conflict_files" ]] || return 1
678
+ resolved_round=""
679
+ while IFS= read -r conflict_path; do
680
+ [[ -z "$conflict_path" ]] && continue
681
+ if ! try_reconcile_openspec_tasks_conflict "$worktree" "$conflict_path"; then
682
+ return 1
683
+ fi
684
+ resolved_round+="${conflict_path}"$'\n'
685
+ resolved_paths+="${conflict_path}"$'\n'
686
+ done <<< "$conflict_files"
687
+
688
+ while IFS= read -r conflict_path; do
689
+ [[ -n "$conflict_path" ]] && run_guardex_cli locks claim --branch "$SOURCE_BRANCH" "$conflict_path" >/dev/null 2>&1 || true
690
+ done <<< "$resolved_round"
691
+ validate_reconciled_openspec_tasks "$worktree" "$resolved_round" || return 1
692
+
693
+ if ! GIT_EDITOR=true git -C "$worktree" rebase --continue >/dev/null 2>&1; then
694
+ git_dir="$(git -C "$worktree" rev-parse --absolute-git-dir 2>/dev/null || true)"
695
+ if [[ -e "${git_dir}/rebase-merge" || -e "${git_dir}/rebase-apply" ]]; then
696
+ continue
697
+ fi
698
+ return 1
699
+ fi
700
+ git_dir="$(git -C "$worktree" rev-parse --absolute-git-dir 2>/dev/null || true)"
701
+ done
702
+
703
+ [[ -n "$resolved_paths" ]] || return 1
704
+ echo "[agent-sync-guard] Automatically reconciled OpenSpec task progress during rebase:" >&2
705
+ printf '%s' "$resolved_paths" | sort -u | sed 's/^/ - /' >&2
706
+ }
707
+
472
708
  # Resolve a conflicting submodule pointer if and only if one side is a strict
473
709
  # ancestor of the other (fast-forward direction). Writes the resolved SHA via
474
710
  # git update-index and prints the chosen SHA on stdout. Returns 0 on success,
@@ -874,23 +1110,31 @@ if [[ "$should_require_sync" -eq 1 ]] && git -C "$repo_root" show-ref --verify -
874
1110
  echo "[agent-sync-guard] Branch '${SOURCE_BRANCH}' is behind origin/${BASE_BRANCH} by ${behind_count} commit(s)." >&2
875
1111
  echo "[agent-sync-guard] Auto-syncing '${SOURCE_BRANCH}' onto origin/${BASE_BRANCH} before finish..." >&2
876
1112
  if ! git -C "$source_worktree" rebase "origin/${BASE_BRANCH}"; then
877
- git_dir="$(git -C "$source_worktree" rev-parse --git-dir)"
878
- rebase_active=0
879
- if [[ -e "${git_dir}/rebase-merge" || -e "${git_dir}/rebase-apply" ]]; then
880
- rebase_active=1
1113
+ rebase_reconciled=0
1114
+ if try_finish_rebase_with_openspec_tasks "$source_worktree"; then
1115
+ rebase_reconciled=1
881
1116
  fi
1117
+ if [[ "$rebase_reconciled" -eq 1 ]]; then
1118
+ echo "[agent-sync-guard] Auto-sync completed after safe OpenSpec tasks.md reconciliation." >&2
1119
+ else
1120
+ git_dir="$(git -C "$source_worktree" rev-parse --absolute-git-dir)"
1121
+ rebase_active=0
1122
+ if [[ -e "${git_dir}/rebase-merge" || -e "${git_dir}/rebase-apply" ]]; then
1123
+ rebase_active=1
1124
+ fi
882
1125
 
883
- echo "[agent-sync-guard] Auto-sync failed while rebasing '${SOURCE_BRANCH}' onto origin/${BASE_BRANCH}." >&2
884
- if [[ "$rebase_active" -eq 1 ]]; then
885
- if [[ "$created_source_probe" -eq 1 ]]; then
886
- echo "[agent-sync-guard] Temporary source-probe worktree will be cleaned up on exit." >&2
887
- echo "[agent-sync-guard] Reattach '${SOURCE_BRANCH}' in a regular worktree, then rebase it onto origin/${BASE_BRANCH} manually." >&2
888
- else
889
- echo "[agent-sync-guard] Resolve conflicts, then run: git -C \"$source_worktree\" rebase --continue" >&2
890
- echo "[agent-sync-guard] Or abort: git -C \"$source_worktree\" rebase --abort" >&2
1126
+ echo "[agent-sync-guard] Auto-sync failed while rebasing '${SOURCE_BRANCH}' onto origin/${BASE_BRANCH}." >&2
1127
+ if [[ "$rebase_active" -eq 1 ]]; then
1128
+ if [[ "$created_source_probe" -eq 1 ]]; then
1129
+ echo "[agent-sync-guard] Temporary source-probe worktree will be cleaned up on exit." >&2
1130
+ echo "[agent-sync-guard] Reattach '${SOURCE_BRANCH}' in a regular worktree, then rebase it onto origin/${BASE_BRANCH} manually." >&2
1131
+ else
1132
+ echo "[agent-sync-guard] Resolve conflicts, then run: git -C \"$source_worktree\" rebase --continue" >&2
1133
+ echo "[agent-sync-guard] Or abort: git -C \"$source_worktree\" rebase --abort" >&2
1134
+ fi
891
1135
  fi
1136
+ exit 1
892
1137
  fi
893
- exit 1
894
1138
  fi
895
1139
 
896
1140
  behind_after="$(git -C "$repo_root" rev-list --left-right --count "${SOURCE_BRANCH}...origin/${BASE_BRANCH}" 2>/dev/null | awk '{print $2}')"
@@ -904,8 +1148,28 @@ if git -C "$repo_root" show-ref --verify --quiet "refs/remotes/origin/${BASE_BRA
904
1148
 
905
1149
  if ! git -C "$source_worktree" merge --no-commit --no-ff "origin/${BASE_BRANCH}" >/dev/null 2>&1; then
906
1150
  conflict_files="$(git -C "$source_worktree" diff --name-only --diff-filter=U || true)"
1151
+ openspec_tasks_reconciled=""
1152
+ while IFS= read -r conflict_path; do
1153
+ [[ -z "$conflict_path" ]] && continue
1154
+ if try_reconcile_openspec_tasks_conflict "$source_worktree" "$conflict_path"; then
1155
+ openspec_tasks_reconciled+="${conflict_path}"$'\n'
1156
+ fi
1157
+ done <<< "$conflict_files"
1158
+ conflict_files="$(git -C "$source_worktree" diff --name-only --diff-filter=U || true)"
907
1159
 
908
- if [[ "$AUTO_RESOLVE_MODE" != "none" && -n "$conflict_files" ]]; then
1160
+ if [[ -z "$conflict_files" && -n "$openspec_tasks_reconciled" ]]; then
1161
+ while IFS= read -r resolved_path; do
1162
+ [[ -n "$resolved_path" ]] && run_guardex_cli locks claim --branch "$SOURCE_BRANCH" "$resolved_path" >/dev/null 2>&1 || true
1163
+ done <<< "$openspec_tasks_reconciled"
1164
+ if ! validate_reconciled_openspec_tasks "$source_worktree" "$openspec_tasks_reconciled" \
1165
+ || ! git -C "$source_worktree" commit -m "Merge origin/${BASE_BRANCH} into ${SOURCE_BRANCH} (gx reconciled OpenSpec task progress)" >/dev/null 2>&1; then
1166
+ git -C "$source_worktree" merge --abort >/dev/null 2>&1 || true
1167
+ echo "[agent-branch-finish] Failed to validate or commit reconciled OpenSpec task progress." >&2
1168
+ exit 1
1169
+ fi
1170
+ echo "[agent-branch-finish] Automatically reconciled OpenSpec task progress:" >&2
1171
+ printf '%s' "$openspec_tasks_reconciled" | sort -u | sed 's/^/ - /' >&2
1172
+ elif [[ "$AUTO_RESOLVE_MODE" != "none" && -n "$conflict_files" ]]; then
909
1173
  auto_resolve_unresolved=""
910
1174
  auto_resolve_resolved_state=""
911
1175
  auto_resolve_resolved_submodules=""
@@ -950,11 +1214,24 @@ if git -C "$repo_root" show-ref --verify --quiet "refs/remotes/origin/${BASE_BRA
950
1214
  [[ -z "$resolved_entry" ]] && continue
951
1215
  auto_resolve_claim_paths+=("${resolved_entry%@*}")
952
1216
  done <<< "$auto_resolve_resolved_submodules"
1217
+ while IFS= read -r resolved_path; do
1218
+ [[ -n "$resolved_path" ]] && auto_resolve_claim_paths+=("$resolved_path")
1219
+ done <<< "$openspec_tasks_reconciled"
953
1220
  if [[ "${#auto_resolve_claim_paths[@]}" -gt 0 ]]; then
954
1221
  run_guardex_cli locks claim --branch "$SOURCE_BRANCH" "${auto_resolve_claim_paths[@]}" >/dev/null 2>&1 || true
955
1222
  fi
956
1223
 
957
- auto_resolve_commit_msg="Merge origin/${BASE_BRANCH} into ${SOURCE_BRANCH} (gx --auto-resolve=${AUTO_RESOLVE_MODE}; state files -> base, submodule pointers fast-forwarded)"
1224
+ auto_resolve_summary="state files -> base, submodule pointers fast-forwarded"
1225
+ if [[ -n "$openspec_tasks_reconciled" ]]; then
1226
+ auto_resolve_summary="OpenSpec task progress reconciled, ${auto_resolve_summary}"
1227
+ fi
1228
+ auto_resolve_commit_msg="Merge origin/${BASE_BRANCH} into ${SOURCE_BRANCH} (gx --auto-resolve=${AUTO_RESOLVE_MODE}; ${auto_resolve_summary})"
1229
+ if [[ -n "$openspec_tasks_reconciled" ]] \
1230
+ && ! validate_reconciled_openspec_tasks "$source_worktree" "$openspec_tasks_reconciled"; then
1231
+ git -C "$source_worktree" merge --abort >/dev/null 2>&1 || true
1232
+ echo "[agent-branch-finish] OpenSpec validation failed after task reconciliation." >&2
1233
+ exit 1
1234
+ fi
958
1235
  if ! git -C "$source_worktree" commit -m "$auto_resolve_commit_msg" >/dev/null 2>&1; then
959
1236
  git -C "$source_worktree" merge --abort >/dev/null 2>&1 || true
960
1237
  echo "[agent-branch-finish] --auto-resolve=${AUTO_RESOLVE_MODE}: failed to commit resolved merge (pre-commit hook may have rejected it; verify file locks)." >&2
@@ -965,7 +1242,9 @@ if git -C "$repo_root" show-ref --verify --quiet "refs/remotes/origin/${BASE_BRA
965
1242
  submod_count=0
966
1243
  [[ -n "$auto_resolve_resolved_state" ]] && state_count="$(printf '%s' "$auto_resolve_resolved_state" | grep -c '^[^[:space:]]')"
967
1244
  [[ -n "$auto_resolve_resolved_submodules" ]] && submod_count="$(printf '%s' "$auto_resolve_resolved_submodules" | grep -c '^[^[:space:]]')"
968
- echo "[agent-branch-finish] --auto-resolve=${AUTO_RESOLVE_MODE}: resolved ${state_count} state-file conflict(s), ${submod_count} submodule pointer conflict(s)." >&2
1245
+ tasks_count=0
1246
+ [[ -n "$openspec_tasks_reconciled" ]] && tasks_count="$(printf '%s' "$openspec_tasks_reconciled" | grep -c '^[^[:space:]]')"
1247
+ echo "[agent-branch-finish] --auto-resolve=${AUTO_RESOLVE_MODE}: resolved ${tasks_count} OpenSpec tasks conflict(s), ${state_count} state-file conflict(s), ${submod_count} submodule pointer conflict(s)." >&2
969
1248
  if [[ -n "$auto_resolve_resolved_state" ]]; then
970
1249
  echo "[agent-branch-finish] State files (resolved to base):" >&2
971
1250
  while IFS= read -r resolved_path; do
@@ -433,6 +433,26 @@ resolve_worktree_leaf() {
433
433
  print_reused_agent_worktree() {
434
434
  local branch_name="$1"
435
435
  local worktree_path="$2"
436
+ local stored_base=""
437
+
438
+ if [[ "$BASE_BRANCH_EXPLICIT" -eq 1 ]]; then
439
+ if ! git -C "$repo_root" show-ref --verify --quiet "refs/heads/${BASE_BRANCH}" \
440
+ && ! git -C "$repo_root" show-ref --verify --quiet "refs/remotes/origin/${BASE_BRANCH}"; then
441
+ echo "[agent-branch-start] Base branch not found locally or on origin: ${BASE_BRANCH}" >&2
442
+ return 1
443
+ fi
444
+ if ! git -C "$repo_root" config "branch.${branch_name}.guardexBase" "$BASE_BRANCH"; then
445
+ echo "[agent-branch-start] Failed to persist base '${BASE_BRANCH}' for reused branch '${branch_name}'." >&2
446
+ return 1
447
+ fi
448
+ elif [[ -z "$BASE_BRANCH" ]]; then
449
+ stored_base="$(git -C "$repo_root" config --get "branch.${branch_name}.guardexBase" || true)"
450
+ if [[ -n "$stored_base" ]]; then
451
+ BASE_BRANCH="$stored_base"
452
+ else
453
+ echo "[agent-branch-start] Warning: reused branch '${branch_name}' has no Guardex base metadata; pass --base <branch> to repair it." >&2
454
+ fi
455
+ fi
436
456
 
437
457
  echo "[agent-branch-start] Reusing existing branch: ${branch_name}"
438
458
  echo "[agent-branch-start] Worktree: ${worktree_path}"
@@ -780,7 +800,7 @@ fi
780
800
  current_branch="$(git -C "$repo_root" rev-parse --abbrev-ref HEAD 2>/dev/null || true)"
781
801
  if [[ "$REUSE_EXISTING_WORKTREE" -eq 1 && "$current_branch" == agent/* ]]; then
782
802
  print_reused_agent_worktree "$current_branch" "$repo_root"
783
- exit 0
803
+ exit $?
784
804
  fi
785
805
 
786
806
  task_slug="$(sanitize_slug "$TASK_NAME" "task")"
@@ -804,7 +824,7 @@ if [[ "$REUSE_EXISTING_WORKTREE" -eq 1 ]]; then
804
824
  IFS=$'\t' read -r reused_branch reused_worktree <<<"$matching_dirty_worktree"
805
825
  echo "[agent-branch-start] Matched dirty managed worktree for requested task."
806
826
  print_reused_agent_worktree "$reused_branch" "$reused_worktree"
807
- exit 0
827
+ exit $?
808
828
  fi
809
829
  fi
810
830
 
@@ -22,6 +22,7 @@ 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
27
28
  import subprocess
@@ -55,6 +56,8 @@ LOCK_NOW_EPOCH_ENV = 'GUARDEX_LOCK_NOW_EPOCH'
55
56
  # Generous default so an active long-running lane is never reaped; `reap` is an
56
57
  # explicit, opt-in maintenance command, not an automatic background sweep.
57
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
58
61
 
59
62
 
60
63
  @dataclass
@@ -115,6 +118,15 @@ def resolve_agent(args: argparse.Namespace) -> str:
115
118
  return (value or '').strip()
116
119
 
117
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
+
118
130
  def resolve_pane() -> str:
119
131
  """Return the caller's tmux pane when it has the canonical `%<number>` form."""
120
132
  value = os.environ.get(PANE_ID_ENV, '').strip()
@@ -385,13 +397,75 @@ def cross_worktree_lock(repo_root: Path):
385
397
  handle.close()
386
398
 
387
399
 
388
- def cmd_claim(args: argparse.Namespace, repo_root: Path) -> int:
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:
389
455
  state = load_state(repo_root)
390
456
  locks: dict[str, dict[str, Any]] = state['locks']
391
457
 
392
458
  claim_agent = resolve_agent(args)
459
+ claim_session = resolve_session_id()
393
460
  claim_pane = resolve_pane()
394
461
  files = [normalize_repo_path(repo_root, p) for p in args.files]
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
395
469
  conflicts: list[tuple[str, dict[str, Any]]] = []
396
470
 
397
471
  # Conflict detection spans EVERY worktree of the repo, not just this one: a
@@ -621,7 +695,10 @@ def cmd_validate(args: argparse.Namespace, repo_root: Path) -> int:
621
695
  for status, file_path in file_changes:
622
696
  owners = all_locks.get(file_path, [])
623
697
  if not owners:
624
- missing.append(file_path)
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)
625
702
  continue
626
703
 
627
704
  foreign_owners = [e for e in owners if not owner_matches(e, args.branch, agent)]
@@ -726,6 +803,11 @@ def build_parser() -> argparse.ArgumentParser:
726
803
  validate.add_argument('--branch', required=True, help='Owner branch name')
727
804
  add_agent_arg(validate)
728
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
+ )
729
811
  validate.add_argument('files', nargs='*', help='Files to validate when --staged is not used')
730
812
 
731
813
  return parser
@@ -733,7 +815,7 @@ def build_parser() -> argparse.ArgumentParser:
733
815
 
734
816
  def dispatch_command(args: argparse.Namespace, repo_root: Path) -> int:
735
817
  if args.command == 'claim':
736
- return cmd_claim(args, repo_root)
818
+ raise LockError('claim must run while holding the adaptive direct-session lock')
737
819
  if args.command == 'allow-delete':
738
820
  return cmd_allow_delete(args, repo_root)
739
821
  if args.command == 'release':
@@ -760,6 +842,9 @@ def main() -> int:
760
842
  # each other or both win the same file. status is a pure read -> unlocked.
761
843
  if args.command in {'claim', 'allow-delete', 'release', 'reap', 'validate'}:
762
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)
763
848
  return dispatch_command(args, repo_root)
764
849
  return dispatch_command(args, repo_root)
765
850
  except LockError as exc: