@calltelemetry/fmix 2.7.3 → 2.7.5

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.
Files changed (2) hide show
  1. package/bin/fmix +1227 -195
  2. package/package.json +3 -3
package/bin/fmix CHANGED
@@ -6,6 +6,7 @@
6
6
  # ./fmix test [--worktree <path>] [--session <id>] [--isolate] [--cache-base <N.N.N-stable>] [--unit] -- <mix test args>
7
7
  # ./fmix coverage --worktree <path> [--session <id>] --base <git-ref> -- <test paths>
8
8
  # ./fmix task [--worktree <path>] [--session <id>] [--database <name>] [--mix-env <env>] [--allow-run] -- <mix task> [args]
9
+ # ./fmix format [--worktree <path>] [--session <id>] [--mix-env <env>] [--check] -- <files...>
9
10
  # ./fmix setup [--worktree <path>] [--session <id>] [--rebuild-db|--cold-db|--from-zero]
10
11
  # ./fmix seed publish --worktree <path> [--session <id>] --cache-base <N.N.N-stable>
11
12
  # ./fmix cache explain --worktree <path> --cache-base <N.N.N-stable>
@@ -23,7 +24,7 @@ set -uo pipefail
23
24
  # ---------------------------------------------------------------------------
24
25
  # Constants & config
25
26
  # ---------------------------------------------------------------------------
26
- FMIX_VERSION="2.7.3"
27
+ FMIX_VERSION="2.7.5"
27
28
  FMIX_HOME="${FMIX_HOME:-${HOME}/.ct-fmix}"
28
29
  FMIX_OS="$(uname -s)"
29
30
  FMIX_ARCH="$(uname -m)"
@@ -100,15 +101,15 @@ FMIX_MIGRATE_FROM_ZERO_TIMEOUT="${FMIX_MIGRATE_FROM_ZERO_TIMEOUT:-1800}"
100
101
  FMIX_STRUCTURE_LOAD_TIMEOUT="${FMIX_STRUCTURE_LOAD_TIMEOUT:-120}"
101
102
  FMIX_STRUCTURE_LOAD_HEARTBEAT="${FMIX_STRUCTURE_LOAD_HEARTBEAT:-30}"
102
103
 
103
- # Kernel locks are held by inherited file descriptors for the full protected
104
- # operation. Indexed arrays keep this compatible with the Bash 3.2 shipped by
105
- # older macOS hosts; associative arrays and `flock(1)` are intentionally not
106
- # required.
107
- FMIX_LOCK_FD_MIN=210
108
- FMIX_LOCK_FD_MAX=239
104
+ # Kernel locks are held by dedicated Python keeper processes. The FMix shell
105
+ # never owns the lock descriptor, so compiler children and detached daemons
106
+ # cannot inherit lock ownership. Indexed arrays keep this compatible with the
107
+ # Bash 3.2 shipped by older macOS hosts; associative arrays and `flock(1)` are
108
+ # intentionally not required.
109
109
  FMIX_HELD_LOCK_NAMES=()
110
- FMIX_HELD_LOCK_FDS=()
110
+ FMIX_HELD_LOCK_KEEPER_PIDS=()
111
111
  FMIX_HELD_LOCK_TOKENS=()
112
+ FMIX_LAST_LOCK_KEEPER_PID=""
112
113
 
113
114
  # Set by fmix_activate_session before any mutable artifact, stamp, or scratch
114
115
  # database path is resolved.
@@ -4366,34 +4367,52 @@ fmix_prepare_dependency_artifacts() {
4366
4367
  # ---------------------------------------------------------------------------
4367
4368
 
4368
4369
  fmix_hash_source_paths() {
4369
- local root="$1"
4370
+ local root="$1" tmp_tracked="" tmp_diff="" tmp_staged=""
4371
+ local unstaged_hash="" staged_hash="" rc
4370
4372
  shift
4371
4373
  local path
4372
4374
 
4373
- if git -C "$root" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
4374
- local tmp_tracked tmp_diff tmp_staged
4375
- tmp_tracked="$(mktemp)"
4376
- tmp_diff="$(mktemp)"
4377
- tmp_staged="$(mktemp)"
4375
+ if [[ -d "$root/.git" || -f "$root/.git" ]]; then
4376
+ git -C "$root" rev-parse --is-inside-work-tree >/dev/null 2>&1 \
4377
+ || return 1
4378
+ tmp_tracked="$(mktemp)" || return 1
4379
+ tmp_diff="$(mktemp)" || { rm -f "$tmp_tracked"; return 1; }
4380
+ tmp_staged="$(mktemp)" \
4381
+ || { rm -f "$tmp_tracked" "$tmp_diff"; return 1; }
4378
4382
 
4379
- git -C "$root" ls-files -s -- "$@" \
4383
+ if ! git -C "$root" ls-files -s -- "$@" \
4380
4384
  | awk '$1 != "160000" { print $0 }' \
4381
- | LC_ALL=C sort >"$tmp_tracked"
4382
-
4383
- git -C "$root" diff --binary -- "$@" >"$tmp_diff" 2>/dev/null
4384
- git -C "$root" diff --cached --binary -- "$@" >"$tmp_staged" 2>/dev/null
4385
-
4385
+ | LC_ALL=C sort >"$tmp_tracked"; then
4386
+ rm -f "$tmp_tracked" "$tmp_diff" "$tmp_staged"
4387
+ return 1
4388
+ fi
4389
+ if ! git -C "$root" diff --binary -- "$@" >"$tmp_diff" 2>/dev/null; then
4390
+ rm -f "$tmp_tracked" "$tmp_diff" "$tmp_staged"
4391
+ return 1
4392
+ fi
4393
+ if ! git -C "$root" diff --cached --binary -- "$@" \
4394
+ >"$tmp_staged" 2>/dev/null; then
4395
+ rm -f "$tmp_tracked" "$tmp_diff" "$tmp_staged"
4396
+ return 1
4397
+ fi
4398
+ if [[ -s "$tmp_diff" ]]; then
4399
+ unstaged_hash="$(fmix_hash_files "$tmp_diff" | awk '{print $1}')" \
4400
+ || { rm -f "$tmp_tracked" "$tmp_diff" "$tmp_staged"; return 1; }
4401
+ fi
4402
+ if [[ -s "$tmp_staged" ]]; then
4403
+ staged_hash="$(fmix_hash_files "$tmp_staged" | awk '{print $1}')" \
4404
+ || { rm -f "$tmp_tracked" "$tmp_diff" "$tmp_staged"; return 1; }
4405
+ fi
4386
4406
  {
4387
4407
  cat "$tmp_tracked"
4388
- if [[ -s "$tmp_diff" ]]; then
4389
- printf 'unstaged-diff:%s\n' "$(fmix_hash_files "$tmp_diff" | awk '{print $1}')"
4390
- fi
4391
- if [[ -s "$tmp_staged" ]]; then
4392
- printf 'staged-diff:%s\n' "$(fmix_hash_files "$tmp_staged" | awk '{print $1}')"
4393
- fi
4408
+ [[ -z "$unstaged_hash" ]] \
4409
+ || printf 'unstaged-diff:%s\n' "$unstaged_hash"
4410
+ [[ -z "$staged_hash" ]] \
4411
+ || printf 'staged-diff:%s\n' "$staged_hash"
4394
4412
  }
4395
-
4413
+ rc=$?
4396
4414
  rm -f "$tmp_tracked" "$tmp_diff" "$tmp_staged"
4415
+ return "$rc"
4397
4416
  else
4398
4417
  for path in "$@"; do
4399
4418
  if [[ -f "$root/$path" || -L "$root/$path" ]]; then
@@ -4642,28 +4661,6 @@ fmix_lock_find_index() {
4642
4661
  return 1
4643
4662
  }
4644
4663
 
4645
- fmix_lock_allocate_fd() {
4646
- local fd
4647
- for (( fd = FMIX_LOCK_FD_MIN; fd <= FMIX_LOCK_FD_MAX; fd++ )); do
4648
- if ! eval "true >&${fd}" 2>/dev/null; then
4649
- printf '%s\n' "$fd"
4650
- return 0
4651
- fi
4652
- done
4653
- fmix_error "No FMix lock file descriptor is available (${FMIX_LOCK_FD_MIN}-${FMIX_LOCK_FD_MAX})."
4654
- return 1
4655
- }
4656
-
4657
- fmix_lock_close_fd() {
4658
- local fd="$1"
4659
- eval "exec ${fd}>&-"
4660
- }
4661
-
4662
- fmix_lock_open_fd() {
4663
- local fd="$1" path="$2"
4664
- eval "exec ${fd}>>\"\$path\""
4665
- }
4666
-
4667
4664
  fmix_lock_quarantine_metadata() {
4668
4665
  local lock_name="$1" lock_dir="$2" reason="$3" destination
4669
4666
  [[ "$lock_name" =~ ^[A-Za-z0-9._-]+$ ]] || return 1
@@ -4677,26 +4674,77 @@ fmix_lock_quarantine_metadata() {
4677
4674
  return 1
4678
4675
  }
4679
4676
 
4680
- fmix_lock_kernel_try() {
4681
- local fd="$1" timeout="$2" diagnostic_name="${3:-${lock_name:-lock}}" lock_name="${4:-${diagnostic_name:-lock}}" py_bin
4677
+ fmix_lock_keeper_start() {
4678
+ local path="$1" mode="$2" timeout="$3"
4679
+ local diagnostic_name="${4:-lock}"
4680
+ local lock_name="${5:-${diagnostic_name:-lock}}"
4681
+ local py_bin owner_pid owner_file state keeper_pid status
4682
+ FMIX_LAST_LOCK_KEEPER_PID=""
4682
4683
  py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
4683
- "$py_bin" - "$fd" "$timeout" "$diagnostic_name" "$lock_name" "$FMIX_HOME" <<'PY'
4684
+ # Bash 3.2 does not expose BASHPID, and $$ intentionally remains the
4685
+ # top-level shell PID inside a subshell. Ask a short-lived child for its
4686
+ # real parent so the keeper monitors the process that actually owns it.
4687
+ owner_pid="${BASHPID:-}"
4688
+ if [[ ! "$owner_pid" =~ ^[0-9]+$ ]]; then
4689
+ owner_file="$(mktemp)" || return 1
4690
+ if ! "$py_bin" -c 'import os; print(os.getppid())' >"$owner_file" \
4691
+ || ! IFS= read -r owner_pid <"$owner_file"; then
4692
+ rm -f "$owner_file"
4693
+ return 1
4694
+ fi
4695
+ rm -f "$owner_file"
4696
+ [[ "$owner_pid" =~ ^[0-9]+$ ]] || return 1
4697
+ fi
4698
+ mkdir -p "$FMIX_HOME/lock-keeper-state" || return 1
4699
+ state="$FMIX_HOME/lock-keeper-state/${lock_name}.${owner_pid}.${RANDOM}.state"
4700
+ (
4701
+ exec "$py_bin" - "$path" "$mode" "$timeout" "$diagnostic_name" \
4702
+ "$lock_name" "$FMIX_HOME" "$owner_pid" "$state" <<'PY'
4684
4703
  import fcntl
4685
4704
  import json
4686
4705
  import os
4706
+ import signal
4687
4707
  import sys
4688
4708
  import time
4689
4709
  from pathlib import Path
4690
4710
 
4691
- fd = int(sys.argv[1])
4692
- timeout = int(sys.argv[2])
4693
- diag_name = sys.argv[3] if len(sys.argv) > 3 and sys.argv[3] else "lock"
4694
- lock_name = sys.argv[4] if len(sys.argv) > 4 and sys.argv[4] else diag_name
4695
- fmix_home = sys.argv[5] if len(sys.argv) > 5 and sys.argv[5] else os.environ.get("FMIX_HOME", "")
4711
+ path = sys.argv[1]
4712
+ mode = sys.argv[2]
4713
+ timeout = int(sys.argv[3])
4714
+ diag_name = sys.argv[4] if sys.argv[4] else "lock"
4715
+ lock_name = sys.argv[5] if sys.argv[5] else diag_name
4716
+ fmix_home = sys.argv[6]
4717
+ owner_pid = int(sys.argv[7])
4718
+ state_path = Path(sys.argv[8])
4696
4719
 
4697
4720
  start_time = time.monotonic()
4698
4721
  deadline = start_time + timeout
4699
4722
  last_heartbeat = start_time
4723
+ stop_requested = False
4724
+
4725
+
4726
+ def request_stop(_signum, _frame):
4727
+ global stop_requested
4728
+ stop_requested = True
4729
+
4730
+
4731
+ def publish_state(value):
4732
+ temporary = state_path.with_name(
4733
+ state_path.name + f".tmp-{os.getpid()}"
4734
+ )
4735
+ temporary.write_text(value + "\n", encoding="utf-8")
4736
+ os.replace(temporary, state_path)
4737
+
4738
+
4739
+ def owner_alive():
4740
+ if os.getppid() != owner_pid:
4741
+ return False
4742
+ try:
4743
+ os.kill(owner_pid, 0)
4744
+ except OSError:
4745
+ return False
4746
+ return True
4747
+
4700
4748
 
4701
4749
  def get_holder_info(lock_name, fmix_home):
4702
4750
  if not lock_name or not fmix_home:
@@ -4718,28 +4766,80 @@ def get_holder_info(lock_name, fmix_home):
4718
4766
  pass
4719
4767
  return "unknown", diag_name
4720
4768
 
4721
- while True:
4722
- try:
4723
- fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
4724
- raise SystemExit(0)
4725
- except BlockingIOError:
4726
- now = time.monotonic()
4727
- if now >= deadline:
4728
- raise SystemExit(1)
4729
- if now - last_heartbeat >= 15.0:
4730
- elapsed = int(now - start_time)
4731
- holder_pid, purpose = get_holder_info(lock_name, fmix_home)
4732
- sys.stderr.write(f"[fmix] Waiting for lock '{lock_name}' ({elapsed}s elapsed, timeout {timeout}s, holder PID: {holder_pid}, purpose: \"{purpose}\") ...\n")
4733
- sys.stderr.flush()
4734
- last_heartbeat = now
4769
+ signal.signal(signal.SIGTERM, request_stop)
4770
+ signal.signal(signal.SIGINT, request_stop)
4771
+ fd = os.open(path, os.O_RDWR | os.O_CREAT, 0o600)
4772
+ os.set_inheritable(fd, False)
4773
+ operation = fcntl.LOCK_SH if mode == "shared" else fcntl.LOCK_EX
4774
+ try:
4775
+ while not stop_requested and owner_alive():
4776
+ try:
4777
+ fcntl.flock(fd, operation | fcntl.LOCK_NB)
4778
+ break
4779
+ except BlockingIOError:
4780
+ now = time.monotonic()
4781
+ if now >= deadline:
4782
+ publish_state("timeout")
4783
+ raise SystemExit(1)
4784
+ if now - last_heartbeat >= 15.0:
4785
+ elapsed = int(now - start_time)
4786
+ holder_pid, purpose = get_holder_info(lock_name, fmix_home)
4787
+ sys.stderr.write(
4788
+ f"[fmix] Waiting for lock '{lock_name}' ({elapsed}s elapsed, "
4789
+ f"timeout {timeout}s, holder PID: {holder_pid}, "
4790
+ f"purpose: \"{purpose}\") ...\n"
4791
+ )
4792
+ sys.stderr.flush()
4793
+ last_heartbeat = now
4794
+ time.sleep(0.05)
4795
+ else:
4796
+ publish_state("stopped")
4797
+ raise SystemExit(1)
4798
+
4799
+ publish_state("ready")
4800
+ while not stop_requested and owner_alive():
4735
4801
  time.sleep(0.05)
4802
+ finally:
4803
+ os.close(fd)
4736
4804
  PY
4805
+ ) >/dev/null &
4806
+ keeper_pid=$!
4807
+ while true; do
4808
+ if [[ -s "$state" ]]; then
4809
+ IFS= read -r status <"$state"
4810
+ rm -f "$state" 2>/dev/null || true
4811
+ case "$status" in
4812
+ ready)
4813
+ if kill -0 "$keeper_pid" 2>/dev/null; then
4814
+ FMIX_LAST_LOCK_KEEPER_PID="$keeper_pid"
4815
+ return 0
4816
+ fi
4817
+ ;;
4818
+ esac
4819
+ wait "$keeper_pid" 2>/dev/null || true
4820
+ return 1
4821
+ fi
4822
+ if ! kill -0 "$keeper_pid" 2>/dev/null; then
4823
+ wait "$keeper_pid" 2>/dev/null || true
4824
+ rm -f "$state" 2>/dev/null || true
4825
+ return 1
4826
+ fi
4827
+ sleep 0.05
4828
+ done
4829
+ }
4830
+
4831
+ fmix_lock_keeper_stop() {
4832
+ local keeper_pid="${1:-}"
4833
+ [[ "$keeper_pid" =~ ^[0-9]+$ ]] || return 1
4834
+ kill -TERM "$keeper_pid" 2>/dev/null || true
4835
+ wait "$keeper_pid" 2>/dev/null || true
4836
+ return 0
4737
4837
  }
4738
4838
 
4739
4839
  fmix_lock_acquire() {
4740
4840
  local lock_name="${1:-}" timeout="${2:-$FMIX_LOCK_TIMEOUT}"
4741
4841
  local diagnostic_name="${3:-${1:-}}" lock_dir kernel_file deadline
4742
- local fd token owner_start holder_pid holder_start recorded_start
4842
+ local keeper_pid token owner_start holder_pid holder_start recorded_start
4743
4843
  local lock_mtime lock_age grace printed_wait=0 index py_bin
4744
4844
 
4745
4845
  [[ "$lock_name" =~ ^[A-Za-z0-9._-]+$ ]] || {
@@ -4747,7 +4847,7 @@ fmix_lock_acquire() {
4747
4847
  return 1
4748
4848
  }
4749
4849
  if index="$(fmix_lock_find_index "$lock_name")"; then
4750
- fmix_error "Nested acquisition of FMix lock '$diagnostic_name' is not supported (fd=${FMIX_HELD_LOCK_FDS[$index]})."
4850
+ fmix_error "Nested acquisition of FMix lock '$diagnostic_name' is not supported (keeper pid=${FMIX_HELD_LOCK_KEEPER_PIDS[$index]})."
4751
4851
  return 1
4752
4852
  fi
4753
4853
  py_bin="$(fmix_python_bin)"
@@ -4764,16 +4864,15 @@ fmix_lock_acquire() {
4764
4864
  mkdir -p "$FMIX_HOME/locks" "$FMIX_HOME/lock-kernel" "$FMIX_HOME/lock-metadata" || return 1
4765
4865
 
4766
4866
  while true; do
4767
- fd="$(fmix_lock_allocate_fd)" || return 1
4768
- fmix_lock_open_fd "$fd" "$kernel_file" || return 1
4769
4867
  local remaining=$(( deadline - $(fmix_epoch) ))
4770
4868
  (( remaining >= 0 )) || remaining=0
4771
- if ! fmix_lock_kernel_try "$fd" "$remaining" "$diagnostic_name" "$lock_name"; then
4772
- fmix_lock_close_fd "$fd"
4869
+ if ! fmix_lock_keeper_start "$kernel_file" exclusive "$remaining" \
4870
+ "$diagnostic_name" "$lock_name"; then
4773
4871
  fmix_error "Timed out waiting for kernel lock '$diagnostic_name' after ${timeout}s."
4774
4872
  fmix_error "Inspect with: fmix status"
4775
4873
  return 1
4776
4874
  fi
4875
+ keeper_pid="$FMIX_LAST_LOCK_KEEPER_PID"
4777
4876
 
4778
4877
  # Keep a directory-shaped record for older FMix binaries. mkdir remains
4779
4878
  # the mixed-version arbitration point, while the persistent inode above
@@ -4790,11 +4889,11 @@ fmix_lock_acquire() {
4790
4889
  if (( lock_age >= grace )); then
4791
4890
  fmix_lock_quarantine_metadata "$lock_name" "$lock_dir" \
4792
4891
  "owner publication never completed" || {
4793
- fmix_lock_close_fd "$fd"
4892
+ fmix_lock_keeper_stop "$keeper_pid"
4794
4893
  return 1
4795
4894
  }
4796
4895
  else
4797
- fmix_lock_close_fd "$fd"
4896
+ fmix_lock_keeper_stop "$keeper_pid"
4798
4897
  sleep 0.05
4799
4898
  continue
4800
4899
  fi
@@ -4802,7 +4901,7 @@ fmix_lock_acquire() {
4802
4901
  || { [[ -n "$recorded_start" ]] && [[ "$recorded_start" != "$holder_start" ]]; }; then
4803
4902
  fmix_lock_quarantine_metadata "$lock_name" "$lock_dir" \
4804
4903
  "dead or reused pid $holder_pid" || {
4805
- fmix_lock_close_fd "$fd"
4904
+ fmix_lock_keeper_stop "$keeper_pid"
4806
4905
  return 1
4807
4906
  }
4808
4907
  else
@@ -4810,7 +4909,7 @@ fmix_lock_acquire() {
4810
4909
  fmix_info "Waiting for mixed-version lock '$diagnostic_name' (pid=$holder_pid) …"
4811
4910
  printed_wait=1
4812
4911
  fi
4813
- fmix_lock_close_fd "$fd"
4912
+ fmix_lock_keeper_stop "$keeper_pid"
4814
4913
  if (( $(fmix_epoch) >= deadline )); then
4815
4914
  fmix_error "Timed out waiting for mixed-version lock '$diagnostic_name' after ${timeout}s."
4816
4915
  return 1
@@ -4819,13 +4918,13 @@ fmix_lock_acquire() {
4819
4918
  continue
4820
4919
  fi
4821
4920
  elif [[ -e "$lock_dir" || -L "$lock_dir" ]]; then
4822
- fmix_lock_close_fd "$fd"
4921
+ fmix_lock_keeper_stop "$keeper_pid"
4823
4922
  fmix_error "Lock metadata path is not a directory: $lock_dir"
4824
4923
  return 1
4825
4924
  fi
4826
4925
 
4827
4926
  if ! mkdir "$lock_dir" 2>/dev/null; then
4828
- fmix_lock_close_fd "$fd"
4927
+ fmix_lock_keeper_stop "$keeper_pid"
4829
4928
  if (( $(fmix_epoch) >= deadline )); then
4830
4929
  fmix_error "Timed out publishing lock metadata for '$diagnostic_name'."
4831
4930
  return 1
@@ -4850,7 +4949,7 @@ EOF
4850
4949
  then
4851
4950
  fmix_lock_quarantine_metadata "$lock_name" "$lock_dir" \
4852
4951
  "owner publication failed" >/dev/null 2>&1 || true
4853
- fmix_lock_close_fd "$fd"
4952
+ fmix_lock_keeper_stop "$keeper_pid"
4854
4953
  fmix_error "Could not publish ownership for lock '$diagnostic_name'."
4855
4954
  return 1
4856
4955
  fi
@@ -4868,14 +4967,14 @@ EOF
4868
4967
  true
4869
4968
 
4870
4969
  FMIX_HELD_LOCK_NAMES+=("$lock_name")
4871
- FMIX_HELD_LOCK_FDS+=("$fd")
4970
+ FMIX_HELD_LOCK_KEEPER_PIDS+=("$keeper_pid")
4872
4971
  FMIX_HELD_LOCK_TOKENS+=("$token")
4873
4972
  return 0
4874
4973
  done
4875
4974
  }
4876
4975
 
4877
4976
  fmix_lock_release() {
4878
- local lock_name="${1:-}" index fd token lock_dir recorded_token destination
4977
+ local lock_name="${1:-}" index keeper_pid token lock_dir recorded_token destination
4879
4978
  [[ -n "$lock_name" ]] || {
4880
4979
  fmix_error "fmix_lock_release called with empty lock name — refusing."
4881
4980
  return 1
@@ -4888,15 +4987,15 @@ fmix_lock_release() {
4888
4987
  fmix_error "Refusing to release unowned FMix lock '$lock_name'."
4889
4988
  return 1
4890
4989
  }
4891
- fd="${FMIX_HELD_LOCK_FDS[$index]}"
4990
+ keeper_pid="${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}"
4892
4991
  token="${FMIX_HELD_LOCK_TOKENS[$index]}"
4893
4992
  lock_dir="$FMIX_HOME/locks/$lock_name"
4894
4993
  recorded_token="$(sed -n 's/^token=//p' "$lock_dir/owner" 2>/dev/null | head -1)"
4895
4994
  if [[ "$recorded_token" != "$token" ]] \
4896
4995
  || [[ "$(cat "$lock_dir/pid" 2>/dev/null || true)" != "$$" ]]; then
4897
- fmix_lock_close_fd "$fd"
4996
+ fmix_lock_keeper_stop "$keeper_pid"
4898
4997
  FMIX_HELD_LOCK_NAMES[$index]=""
4899
- FMIX_HELD_LOCK_FDS[$index]=""
4998
+ FMIX_HELD_LOCK_KEEPER_PIDS[$index]=""
4900
4999
  FMIX_HELD_LOCK_TOKENS[$index]=""
4901
5000
  fmix_error "Refusing to remove lock metadata for '$lock_name': ownership changed."
4902
5001
  return 1
@@ -4907,17 +5006,17 @@ fmix_lock_release() {
4907
5006
  destination="$FMIX_HOME/lock-metadata/released/${lock_name}.$(fmix_epoch).$$.${RANDOM}"
4908
5007
  if ! mkdir -p "$(dirname "$destination")" \
4909
5008
  || ! mv "$lock_dir" "$destination"; then
4910
- fmix_lock_close_fd "$fd"
5009
+ fmix_lock_keeper_stop "$keeper_pid"
4911
5010
  FMIX_HELD_LOCK_NAMES[$index]=""
4912
- FMIX_HELD_LOCK_FDS[$index]=""
5011
+ FMIX_HELD_LOCK_KEEPER_PIDS[$index]=""
4913
5012
  FMIX_HELD_LOCK_TOKENS[$index]=""
4914
5013
  fmix_error "Could not retire lock metadata for '$lock_name'."
4915
5014
  fmix_error "The kernel lock was released; stale metadata will be quarantined by the next owner."
4916
5015
  return 1
4917
5016
  fi
4918
- fmix_lock_close_fd "$fd"
5017
+ fmix_lock_keeper_stop "$keeper_pid"
4919
5018
  FMIX_HELD_LOCK_NAMES[$index]=""
4920
- FMIX_HELD_LOCK_FDS[$index]=""
5019
+ FMIX_HELD_LOCK_KEEPER_PIDS[$index]=""
4921
5020
  FMIX_HELD_LOCK_TOKENS[$index]=""
4922
5021
  return 0
4923
5022
  }
@@ -5937,34 +6036,20 @@ fmix_clone_donor_to_session() {
5937
6036
 
5938
6037
  py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
5939
6038
 
5940
- # Lock-Then-Revalidate (LOCK_SH): acquire shared lock on donor session
5941
- local donor_fd
5942
- donor_fd="$(fmix_lock_allocate_fd)" || return 1
5943
- if [[ -f "$donor/meta.json" ]]; then
5944
- eval "exec ${donor_fd}<\"$donor/meta.json\""
5945
- else
5946
- fmix_lock_close_fd "$donor_fd"
5947
- return 1
5948
- fi
5949
-
5950
- if ! "$py_bin" - "$donor_fd" <<'PY' 2>/dev/null
5951
- import fcntl, sys
5952
- fd = int(sys.argv[1])
5953
- try:
5954
- fcntl.flock(fd, fcntl.LOCK_SH | fcntl.LOCK_NB)
5955
- raise SystemExit(0)
5956
- except Exception:
5957
- raise SystemExit(1)
5958
- PY
5959
- then
5960
- fmix_lock_close_fd "$donor_fd"
6039
+ # Lock-Then-Revalidate (LOCK_SH): a dedicated keeper owns the descriptor,
6040
+ # so copy helpers cannot inherit and extend donor-lock lifetime.
6041
+ local donor_keeper_pid
6042
+ [[ -f "$donor/meta.json" ]] || return 1
6043
+ if ! fmix_lock_keeper_start "$donor/meta.json" shared 0 \
6044
+ "donor session clone" "donor-$(fmix_hash_text "$donor" | cut -c1-16)"; then
5961
6045
  fmix_warn "Could not acquire shared lock on donor session $donor."
5962
6046
  return 1
5963
6047
  fi
6048
+ donor_keeper_pid="$FMIX_LAST_LOCK_KEEPER_PID"
5964
6049
 
5965
6050
  # Revalidate donor artifacts under active LOCK_SH
5966
6051
  if [[ ! -d "$donor/deps" || ! -d "$donor/_build" || ! -f "$donor/compile-stamp.json" ]]; then
5967
- fmix_lock_close_fd "$donor_fd"
6052
+ fmix_lock_keeper_stop "$donor_keeper_pid"
5968
6053
  fmix_warn "Donor session $donor missing required artifacts during revalidation."
5969
6054
  return 1
5970
6055
  fi
@@ -5972,25 +6057,25 @@ PY
5972
6057
  retired="$FMIX_ACTIVE_SESSION_ROOT/retired/$(date +%Y%m%dT%H%M%S)-$$-${RANDOM}"
5973
6058
  if [[ -e "$deps_root" || -L "$deps_root" \
5974
6059
  || -e "$build_root" || -L "$build_root" ]]; then
5975
- mkdir -p "$retired" || { fmix_lock_close_fd "$donor_fd"; return 1; }
6060
+ mkdir -p "$retired" || { fmix_lock_keeper_stop "$donor_keeper_pid"; return 1; }
5976
6061
  retired_used=1
5977
6062
  [[ -e "$deps_root" || -L "$deps_root" ]] && mv "$deps_root" "$retired/deps"
5978
6063
  [[ -e "$build_root" || -L "$build_root" ]] && mv "$build_root" "$retired/_build"
5979
6064
  fi
5980
6065
 
5981
6066
  if ! fmix_cow_clone "$donor/deps" "$deps_root"; then
5982
- fmix_lock_close_fd "$donor_fd"
6067
+ fmix_lock_keeper_stop "$donor_keeper_pid"
5983
6068
  return 1
5984
6069
  fi
5985
6070
  if ! fmix_cow_clone "$donor/_build" "$build_root"; then
5986
6071
  mkdir -p "$retired" || true
5987
6072
  mv "$deps_root" "$retired/failed-deps" 2>/dev/null || true
5988
- fmix_lock_close_fd "$donor_fd"
6073
+ fmix_lock_keeper_stop "$donor_keeper_pid"
5989
6074
  return 1
5990
6075
  fi
5991
6076
  chmod -R u+w "$deps_root" "$build_root" || {
5992
6077
  fmix_error "Could not make donor clone writable."
5993
- fmix_lock_close_fd "$donor_fd"
6078
+ fmix_lock_keeper_stop "$donor_keeper_pid"
5994
6079
  return 1
5995
6080
  }
5996
6081
 
@@ -6022,8 +6107,8 @@ for name in ("compile-stamp.json", "dependency-stamp.json"):
6022
6107
  PY
6023
6108
  true
6024
6109
 
6025
- # Release LOCK_SH on donor
6026
- fmix_lock_close_fd "$donor_fd"
6110
+ # Release LOCK_SH on donor.
6111
+ fmix_lock_keeper_stop "$donor_keeper_pid"
6027
6112
 
6028
6113
  # Post-clone manifest synchronization: touch compile manifests to prevent full DAG recompiles
6029
6114
  find "$build_root" -type f -name 'compile.*' -exec touch {} + 2>/dev/null || true
@@ -7785,29 +7870,150 @@ fmix_compile_build_root() {
7785
7870
  fi
7786
7871
  }
7787
7872
 
7873
+ fmix_reject_compile_input_symlink_components() {
7874
+ # Compiler-input pathspecs are always relative to the canonical worktree.
7875
+ # Reject a symlink at any component below that root before asking Git to
7876
+ # enumerate the path: Git returns no entry for a pathspec beneath a tracked
7877
+ # directory symlink, which would otherwise make an escaped input invisible.
7878
+ # Path dependencies deliberately use fmix_hash_path_dependency instead; it
7879
+ # canonicalizes the explicitly configured dependency root first, then
7880
+ # rejects nested links beneath that allowed top-level alias.
7881
+ local root="$1" relative="$2" current remaining component
7882
+ [[ -n "$root" && -n "$relative" ]] || return 1
7883
+ case "$relative" in
7884
+ /*)
7885
+ fmix_error "Compiler input path must be relative to the worktree: $relative"
7886
+ return 1
7887
+ ;;
7888
+ esac
7889
+
7890
+ current="${root%/}"
7891
+ remaining="$relative"
7892
+ while [[ -n "$remaining" ]]; do
7893
+ if [[ "$remaining" == */* ]]; then
7894
+ component="${remaining%%/*}"
7895
+ remaining="${remaining#*/}"
7896
+ else
7897
+ component="$remaining"
7898
+ remaining=""
7899
+ fi
7900
+ case "$component" in
7901
+ ""|.) continue ;;
7902
+ ..)
7903
+ fmix_error "Compiler input path escapes the worktree: $relative"
7904
+ return 1
7905
+ ;;
7906
+ esac
7907
+ current="$current/$component"
7908
+ if [[ -L "$current" ]]; then
7909
+ fmix_error "Symlinked compiler input is unsupported: $current"
7910
+ return 1
7911
+ fi
7912
+ done
7913
+ return 0
7914
+ }
7915
+
7916
+ fmix_reject_repo_elixir_input_symlinks() {
7917
+ # priv/repo compiler inputs are discovered with find before they are passed
7918
+ # to fmix_hash_compile_paths. Validate the discovery root explicitly so a
7919
+ # root or nested directory alias cannot disappear from that candidate list.
7920
+ # This is a worktree-owned input root, not the deliberate top-level alias
7921
+ # exception for explicitly configured path dependencies.
7922
+ local root="$1" repo_root="${1%/}/priv/repo" probe symlink_path
7923
+ fmix_reject_compile_input_symlink_components "$root" "priv/repo" \
7924
+ || return 1
7925
+ [[ -d "$repo_root" ]] || return 0
7926
+ probe="$(mktemp)" || return 1
7927
+ if ! find "$repo_root" -type l -print -quit >"$probe" 2>/dev/null; then
7928
+ rm -f "$probe"
7929
+ return 1
7930
+ fi
7931
+ if [[ -s "$probe" ]]; then
7932
+ IFS= read -r symlink_path <"$probe" || symlink_path="$repo_root"
7933
+ rm -f "$probe"
7934
+ fmix_error "Symlinked compiler input is unsupported: $symlink_path"
7935
+ return 1
7936
+ fi
7937
+ rm -f "$probe"
7938
+ return 0
7939
+ }
7940
+
7788
7941
  fmix_hash_compile_paths() {
7789
- local root="$1"
7942
+ local root="$1" tracked_file="" untracked_file="" entry metadata mode path file
7790
7943
  shift
7791
- if git -C "$root" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
7792
- fmix_hash_source_paths "$root" "$@"
7793
- local untracked
7794
- untracked="$(git -C "$root" ls-files --others --exclude-standard -- "$@" 2>/dev/null)"
7795
- if [[ -n "$untracked" ]]; then
7796
- while IFS= read -r path; do
7797
- [[ -f "$root/$path" ]] || continue
7798
- printf 'untracked:%s:' "$path"
7799
- fmix_hash_files "$root/$path"
7800
- done <<<"$untracked"
7944
+ for path in "$@"; do
7945
+ fmix_reject_compile_input_symlink_components "$root" "$path" || return 1
7946
+ done
7947
+ if [[ -d "$root/.git" || -f "$root/.git" ]]; then
7948
+ git -C "$root" rev-parse --is-inside-work-tree >/dev/null 2>&1 \
7949
+ || return 1
7950
+ tracked_file="$(mktemp)" || return 1
7951
+ if ! git -C "$root" ls-files -s -z -- "$@" \
7952
+ >"$tracked_file" 2>/dev/null; then
7953
+ rm -f "$tracked_file"
7954
+ return 1
7955
+ fi
7956
+ while IFS= read -r -d '' entry; do
7957
+ metadata="${entry%%$'\t'*}"
7958
+ mode="${metadata%% *}"
7959
+ path="${entry#*$'\t'}"
7960
+ [[ "$mode" != "160000" ]] || continue
7961
+ printf 'tracked:%s:%s:' "$metadata" "$path"
7962
+ if [[ -L "$root/$path" ]]; then
7963
+ fmix_error "Symlinked compiler input is unsupported: $root/$path"
7964
+ rm -f "$tracked_file"
7965
+ return 1
7966
+ elif [[ -f "$root/$path" ]]; then
7967
+ fmix_hash_stdin <"$root/$path" \
7968
+ || { rm -f "$tracked_file"; return 1; }
7969
+ else
7970
+ printf 'missing\n'
7971
+ fi
7972
+ done <"$tracked_file"
7973
+ rm -f "$tracked_file"
7974
+ untracked_file="$(mktemp)" || return 1
7975
+ if ! (
7976
+ git -C "$root" ls-files --others --exclude-standard -z -- "$@" \
7977
+ || exit 1
7978
+ # Git ignores do not change what Mix can compile or execute. Keep
7979
+ # ignored source files in the exact run identity, but only beneath
7980
+ # the caller's bounded source/test pathspecs. Never widen an empty
7981
+ # pathspec into a scan of ignored cache artifacts.
7982
+ if (( $# > 0 )); then
7983
+ git -C "$root" ls-files --others --ignored \
7984
+ --exclude-standard -z -- "$@" || exit 1
7985
+ fi
7986
+ ) >"$untracked_file" 2>/dev/null; then
7987
+ rm -f "$untracked_file"
7988
+ return 1
7801
7989
  fi
7990
+ while IFS= read -r -d '' path; do
7991
+ case "$path" in
7992
+ _build|_build/*|deps|deps/*) continue ;;
7993
+ esac
7994
+ if [[ -L "$root/$path" ]]; then
7995
+ fmix_error "Symlinked compiler input is unsupported: $root/$path"
7996
+ rm -f "$untracked_file"
7997
+ return 1
7998
+ fi
7999
+ [[ -f "$root/$path" ]] || continue
8000
+ printf 'untracked:%s:' "$path"
8001
+ fmix_hash_files "$root/$path" \
8002
+ || { rm -f "$untracked_file"; return 1; }
8003
+ done <"$untracked_file"
8004
+ rm -f "$untracked_file"
7802
8005
  return 0
7803
8006
  fi
7804
8007
 
7805
- local path file
7806
8008
  for path in "$@"; do
7807
- if [[ -f "$root/$path" ]]; then
8009
+ if [[ -L "$root/$path" ]]; then
8010
+ fmix_error "Symlinked compiler input is unsupported: $root/$path"
8011
+ return 1
8012
+ elif [[ -f "$root/$path" ]]; then
7808
8013
  printf 'file:%s:' "$path"
7809
8014
  fmix_hash_files "$root/$path"
7810
8015
  elif [[ -d "$root/$path" ]]; then
8016
+ fmix_reject_nested_source_symlinks "$root/$path" || return 1
7811
8017
  while IFS= read -r file; do
7812
8018
  printf 'file:%s:' "${file#"$root/"}"
7813
8019
  fmix_hash_files "$file"
@@ -7818,6 +8024,62 @@ fmix_hash_compile_paths() {
7818
8024
  done
7819
8025
  }
7820
8026
 
8027
+ fmix_ignored_compile_inputs_hash() {
8028
+ # Git's ordinary dirty hash intentionally omits ignored files, but ignored
8029
+ # files under Mix compiler roots are still executable inputs. Hash only
8030
+ # that bounded set; never walk dependency, build, node, or artifact caches.
8031
+ local worktree="$1" real ignored_file manifest hash rc path
8032
+ local -a compile_paths=(
8033
+ .tool-versions mix.exs mix.lock
8034
+ config/config.exs config/config_sync.exs config/test.exs
8035
+ lib test/support test/cdrcisco/policies/reputation_signals/shared
8036
+ vendor dev_tools priv/repo
8037
+ )
8038
+ real="$(fmix_realpath "$worktree" 2>/dev/null)" || return 1
8039
+ if [[ ! -d "$real/.git" && ! -f "$real/.git" ]]; then
8040
+ printf 'non-git\n'
8041
+ return 0
8042
+ fi
8043
+ command -v git >/dev/null 2>&1 || return 1
8044
+ git -C "$real" rev-parse --is-inside-work-tree >/dev/null 2>&1 \
8045
+ || return 1
8046
+ ignored_file="$(mktemp)" || return 1
8047
+ manifest="$(mktemp)" || { rm -f "$ignored_file"; return 1; }
8048
+ if ! git -C "$real" ls-files --others --ignored --exclude-standard -z \
8049
+ -- "${compile_paths[@]}" >"$ignored_file" 2>/dev/null; then
8050
+ rm -f "$ignored_file" "$manifest"
8051
+ return 1
8052
+ fi
8053
+ rc=0
8054
+ {
8055
+ printf 'fmix-ignored-compile-inputs-v1\n'
8056
+ while IFS= read -r -d '' path; do
8057
+ case "/$path/" in
8058
+ */.git/*|*/_build/*|*/deps/*|*/node_modules/*|*/artifacts/*)
8059
+ continue
8060
+ ;;
8061
+ esac
8062
+ [[ -f "$real/$path" ]] || continue
8063
+ printf 'ignored:%s:' "$path"
8064
+ if ! fmix_hash_files "$real/$path"; then
8065
+ rc=1
8066
+ break
8067
+ fi
8068
+ done <"$ignored_file"
8069
+ } >"$manifest"
8070
+ rm -f "$ignored_file"
8071
+ if (( rc != 0 )); then
8072
+ rm -f "$manifest"
8073
+ return "$rc"
8074
+ fi
8075
+ hash="$(fmix_hash_stdin <"$manifest")"
8076
+ rc=$?
8077
+ rm -f "$manifest"
8078
+ (( rc == 0 )) || return "$rc"
8079
+ [[ "$hash" =~ ^[0-9a-f]{64}$ ]] || return 1
8080
+ printf '%s\n' "$hash"
8081
+ }
8082
+
7821
8083
  fmix_compute_compile_fingerprint() {
7822
8084
  # Content-only and deliberately conservative. Ordinary test files are not
7823
8085
  # compiler inputs, but all test elixirc paths, config, dependency inputs,
@@ -7836,9 +8098,11 @@ fmix_compute_compile_fingerprint() {
7836
8098
  vendor dev_tools
7837
8099
  )
7838
8100
  local -a repo_elixir_paths=()
8101
+ fmix_reject_repo_elixir_input_symlinks "$real" || return 1
7839
8102
  while IFS= read -r file; do
7840
8103
  repo_elixir_paths+=("${file#"$real/"}")
7841
- done < <(find "$real/priv/repo" -type f -name '*.ex' -print 2>/dev/null | LC_ALL=C sort)
8104
+ done < <(find "$real/priv/repo" \( -type f -o -type l \) \
8105
+ -name '*.ex' -print 2>/dev/null | LC_ALL=C sort)
7842
8106
  manifest="$(mktemp)" || return 1
7843
8107
  (
7844
8108
  printf 'fmix-compile-fingerprint-v4\n'
@@ -7862,6 +8126,184 @@ fmix_compute_compile_fingerprint() {
7862
8126
  printf '%s\n' "$fingerprint"
7863
8127
  }
7864
8128
 
8129
+ fmix_source_stability_compile_identity() {
8130
+ local worktree="${1:-}" real head manifest identity rc file
8131
+ local -a compile_paths=(
8132
+ .tool-versions mix.exs mix.lock
8133
+ config/config.exs config/config_sync.exs config/test.exs
8134
+ lib test/support test/cdrcisco/policies/reputation_signals/shared
8135
+ vendor dev_tools
8136
+ )
8137
+ local -a repo_elixir_paths=()
8138
+ (( $# >= 1 )) || return 1
8139
+ real="$(fmix_realpath "$worktree")" || return 1
8140
+ if [[ -d "$real/.git" || -f "$real/.git" ]]; then
8141
+ git -C "$real" rev-parse --is-inside-work-tree >/dev/null 2>&1 \
8142
+ || return 1
8143
+ head="$(git -C "$real" rev-parse HEAD 2>/dev/null)" || return 1
8144
+ [[ "$head" =~ ^[0-9a-f]{40}$ ]] || return 1
8145
+ else
8146
+ head="non-git"
8147
+ fi
8148
+ fmix_reject_repo_elixir_input_symlinks "$real" || return 1
8149
+ while IFS= read -r file; do
8150
+ repo_elixir_paths+=("${file#"$real/"}")
8151
+ done < <(find "$real/priv/repo" \( -type f -o -type l \) \
8152
+ -name '*.ex' -print 2>/dev/null | LC_ALL=C sort)
8153
+ manifest="$(mktemp)" || return 1
8154
+ {
8155
+ printf 'fmix-source-stability-compile-v1\n'
8156
+ printf 'worktree=%s\n' "$real"
8157
+ printf 'head=%s\n' "$head"
8158
+ printf 'compile-inputs\n'
8159
+ fmix_hash_compile_paths \
8160
+ "$real" \
8161
+ "${compile_paths[@]}" \
8162
+ "${repo_elixir_paths[@]+"${repo_elixir_paths[@]}"}" || return 1
8163
+ fmix_declared_path_dependency_guard "$real" || return 1
8164
+ fmix_path_dependency_source_guard "$real" || return 1
8165
+ } >"$manifest"
8166
+ rc=$?
8167
+ if (( rc != 0 )); then
8168
+ rm -f "$manifest"
8169
+ return "$rc"
8170
+ fi
8171
+ identity="$(fmix_hash_stdin <"$manifest")"
8172
+ rc=$?
8173
+ rm -f "$manifest"
8174
+ (( rc == 0 )) || return "$rc"
8175
+ [[ "$identity" =~ ^[0-9a-f]{64}$ ]] || return 1
8176
+ printf '%s\n' "$identity"
8177
+ }
8178
+
8179
+ # Exact identity for an immutable test/coverage run. Bind the compiler inputs
8180
+ # above to the selected tests and every shared helper file, including helper
8181
+ # dependencies such as test_helper_nats.exs.
8182
+ fmix_source_stability_identity() {
8183
+ local worktree="${1:-}" real manifest identity compile_identity rc arg candidate relative
8184
+ local selected_path_count=0 file
8185
+ local -a helper_paths=()
8186
+ (( $# >= 1 )) || return 1
8187
+ shift
8188
+ real="$(fmix_realpath "$worktree")" || return 1
8189
+ compile_identity="$(fmix_source_stability_compile_identity "$real")" || return 1
8190
+ while IFS= read -r file; do
8191
+ helper_paths+=("${file#"$real/"}")
8192
+ done < <(find "$real/test" \( -type f -o -type l \) \
8193
+ \( -name '*helper*.ex' -o -name '*helper*.exs' \) \
8194
+ -print 2>/dev/null | LC_ALL=C sort)
8195
+
8196
+ manifest="$(mktemp)" || return 1
8197
+ {
8198
+ printf 'fmix-source-stability-v2\n'
8199
+ printf 'compile-identity=%s\n' "$compile_identity"
8200
+ printf 'shared-test-helpers\n'
8201
+ fmix_hash_compile_paths \
8202
+ "$real" \
8203
+ "${helper_paths[@]+"${helper_paths[@]}"}" || return 1
8204
+ printf 'selected-count=%s\n' "$#"
8205
+ for arg in "$@"; do
8206
+ printf 'selected-arg:'
8207
+ printf '%s' "$arg" | fmix_hash_stdin || return 1
8208
+ candidate="$arg"
8209
+ if [[ "$candidate" =~ ^(.+):[0-9]+$ ]]; then
8210
+ candidate="${BASH_REMATCH[1]}"
8211
+ fi
8212
+ [[ "$candidate" != -* ]] || continue
8213
+ if [[ "$candidate" == /* ]]; then
8214
+ case "$candidate" in
8215
+ "$real"/*) relative="${candidate#"$real/"}" ;;
8216
+ *) continue ;;
8217
+ esac
8218
+ else
8219
+ relative="${candidate#./}"
8220
+ case "$relative" in ../*|*/../*|..|*/..) continue ;; esac
8221
+ fi
8222
+ [[ -e "$real/$relative" || -L "$real/$relative" ]] || continue
8223
+ printf 'selected-path=%s\n' "$relative"
8224
+ fmix_hash_compile_paths "$real" "$relative" || return 1
8225
+ selected_path_count=$((selected_path_count + 1))
8226
+ done
8227
+ if (( selected_path_count == 0 )); then
8228
+ printf 'selected-default=test\n'
8229
+ fmix_hash_compile_paths "$real" test || return 1
8230
+ fi
8231
+ } >"$manifest"
8232
+ rc=$?
8233
+ if (( rc != 0 )); then
8234
+ rm -f "$manifest"
8235
+ return "$rc"
8236
+ fi
8237
+ identity="$(fmix_hash_stdin <"$manifest")"
8238
+ rc=$?
8239
+ rm -f "$manifest"
8240
+ (( rc == 0 )) || return "$rc"
8241
+ [[ "$identity" =~ ^[0-9a-f]{64}$ ]] || return 1
8242
+ printf '%s\n' "$identity"
8243
+ }
8244
+
8245
+ fmix_invalidate_compile_stamp() {
8246
+ local worktree="${1:-}" stamp
8247
+ [[ -n "$worktree" ]] || return 1
8248
+ stamp="$(fmix_compile_stamp_file "$worktree" 2>/dev/null)" || return 1
8249
+ [[ -n "$stamp" ]] || return 1
8250
+ if [[ -e "$stamp" || -L "$stamp" ]]; then
8251
+ rm -f "$stamp" || {
8252
+ fmix_error "Could not invalidate rejected compile stamp: $stamp"
8253
+ return 1
8254
+ }
8255
+ fi
8256
+ return 0
8257
+ }
8258
+
8259
+ fmix_invalidate_dependency_stamp() {
8260
+ local worktree="${1:-}" stamp
8261
+ [[ -n "$worktree" ]] || return 1
8262
+ stamp="$(fmix_dependency_stamp_file "$worktree" 2>/dev/null)" || return 1
8263
+ [[ -n "$stamp" ]] || return 1
8264
+ if [[ -e "$stamp" || -L "$stamp" ]]; then
8265
+ rm -f "$stamp" || {
8266
+ fmix_error "Could not invalidate rejected dependency stamp: $stamp"
8267
+ return 1
8268
+ }
8269
+ fi
8270
+ return 0
8271
+ }
8272
+
8273
+ fmix_invalidate_rejected_stamps() {
8274
+ local worktree="${1:-}" rc=0
8275
+ fmix_invalidate_compile_stamp "$worktree" || rc=1
8276
+ fmix_invalidate_dependency_stamp "$worktree" || rc=1
8277
+ return "$rc"
8278
+ }
8279
+
8280
+ fmix_require_stable_source() {
8281
+ local worktree="${1:-}" phase="${2:-execution}" invalidate_stamps="${3:-0}" current
8282
+ [[ "${FMIX_SOURCE_STABILITY_REQUIRED:-0}" == "1" ]] || return 0
8283
+ [[ "${FMIX_SOURCE_STABILITY_IDENTITY:-}" =~ ^[0-9a-f]{64}$ ]] || {
8284
+ fmix_error "Source stability identity is missing; refusing $phase."
8285
+ [[ "$invalidate_stamps" != "1" ]] \
8286
+ || fmix_invalidate_rejected_stamps "$worktree"
8287
+ return 1
8288
+ }
8289
+ current="$(fmix_source_stability_identity \
8290
+ "$worktree" \
8291
+ "${FMIX_SOURCE_STABILITY_SELECTED_ARGS[@]+"${FMIX_SOURCE_STABILITY_SELECTED_ARGS[@]}"}")" \
8292
+ || {
8293
+ fmix_error "Source stability could not be revalidated; refusing $phase."
8294
+ [[ "$invalidate_stamps" != "1" ]] \
8295
+ || fmix_invalidate_rejected_stamps "$worktree"
8296
+ return 1
8297
+ }
8298
+ if [[ "$current" != "$FMIX_SOURCE_STABILITY_IDENTITY" ]]; then
8299
+ fmix_error "Source/test inputs changed during $phase; refusing to use mixed-revision results."
8300
+ [[ "$invalidate_stamps" != "1" ]] \
8301
+ || fmix_invalidate_rejected_stamps "$worktree"
8302
+ return 1
8303
+ fi
8304
+ return 0
8305
+ }
8306
+
7865
8307
  fmix_compute_dependency_fingerprint() {
7866
8308
  # Inputs that can change dependency resolution or native dependency builds.
7867
8309
  # Production/test source and ordinary config changes deliberately stay out:
@@ -7909,9 +8351,11 @@ fmix_compute_legacy_compile_fingerprint_v2() {
7909
8351
  vendor dev_tools
7910
8352
  )
7911
8353
  local -a repo_elixir_paths=()
8354
+ fmix_reject_repo_elixir_input_symlinks "$real" || return 1
7912
8355
  while IFS= read -r file; do
7913
8356
  repo_elixir_paths+=("${file#"$real/"}")
7914
- done < <(find "$real/priv/repo" -type f -name '*.ex' -print 2>/dev/null | LC_ALL=C sort)
8357
+ done < <(find "$real/priv/repo" \( -type f -o -type l \) \
8358
+ -name '*.ex' -print 2>/dev/null | LC_ALL=C sort)
7915
8359
  {
7916
8360
  printf 'fmix-compile-fingerprint-v2\n'
7917
8361
  printf 'worktree=%s\n' "$real"
@@ -8080,6 +8524,35 @@ fmix_dependency_source_root() {
8080
8524
  fi
8081
8525
  }
8082
8526
 
8527
+ fmix_reject_nested_source_symlinks() {
8528
+ # Local dependency roots may themselves be symlinks (Mix commonly creates
8529
+ # those for path deps), so canonicalize the explicit root first. Beneath
8530
+ # that root, never follow or accept another symlink: its target could escape
8531
+ # the bounded compiler-input tree, form a cycle, or change without changing
8532
+ # the link identity recorded by Git.
8533
+ local root="$1" real probe symlink_path
8534
+ real="$(fmix_realpath "$root")" || return 1
8535
+ [[ -d "$real" ]] || return 1
8536
+ probe="$(mktemp)" || return 1
8537
+ if ! find "$real" \
8538
+ \( \( -type d -o -type l \) \
8539
+ \( -name .git -o -name _build -o -name deps -o \
8540
+ -name target -o -name c_build -o -name node_modules -o \
8541
+ -name .elixir_ls \) -prune \) -o \
8542
+ -type l -print -quit >"$probe" 2>/dev/null; then
8543
+ rm -f "$probe"
8544
+ return 1
8545
+ fi
8546
+ if [[ -s "$probe" ]]; then
8547
+ IFS= read -r symlink_path <"$probe" || symlink_path="$real"
8548
+ rm -f "$probe"
8549
+ fmix_error "Symlinked compiler input is unsupported: $symlink_path"
8550
+ return 1
8551
+ fi
8552
+ rm -f "$probe"
8553
+ return 0
8554
+ }
8555
+
8083
8556
  fmix_dependency_source_guard() {
8084
8557
  local worktree="$1" deps_root
8085
8558
  deps_root="$(fmix_dependency_source_root "$worktree")"
@@ -8095,6 +8568,7 @@ fmix_dependency_source_guard() {
8095
8568
  dependency_count=$(( dependency_count + 1 ))
8096
8569
  printf '%s\n' "$(basename "$dependency")"
8097
8570
  if [[ -f "$dependency/.hex" ]]; then
8571
+ fmix_reject_nested_source_symlinks "$dependency" || return 1
8098
8572
  hex_markers+=("$dependency/.hex")
8099
8573
  elif [[ -e "$dependency/.git" ]]; then
8100
8574
  fmix_hash_git_dependency "$dependency" || return 1
@@ -8150,6 +8624,7 @@ fmix_hash_path_dependency() {
8150
8624
  local dependency="$1" path_real file
8151
8625
  local -a files=()
8152
8626
  path_real="$(fmix_realpath "$dependency")" || return 1
8627
+ fmix_reject_nested_source_symlinks "$path_real" || return 1
8153
8628
 
8154
8629
  while IFS= read -r file; do
8155
8630
  files+=("$file")
@@ -8247,8 +8722,9 @@ fmix_declared_path_dependency_resolution_guard() {
8247
8722
  }
8248
8723
 
8249
8724
  fmix_hash_git_dependency() {
8250
- local dependency="$1" commit diff_hash file
8725
+ local dependency="$1" commit diff_hash file untracked_file
8251
8726
  local -a untracked=()
8727
+ fmix_reject_nested_source_symlinks "$dependency" || return 1
8252
8728
  commit="$(git -C "$dependency" rev-parse HEAD 2>/dev/null)" || return 1
8253
8729
  [[ -n "$commit" ]] || return 1
8254
8730
  printf '.git-commit:%s\n' "$commit"
@@ -8257,9 +8733,16 @@ fmix_hash_git_dependency() {
8257
8733
  | fmix_hash_stdin)" || return 1
8258
8734
  printf '.git-worktree-diff:%s\n' "$diff_hash"
8259
8735
 
8736
+ untracked_file="$(mktemp)" || return 1
8737
+ if ! git -C "$dependency" ls-files --others --exclude-standard -z \
8738
+ >"$untracked_file" 2>/dev/null; then
8739
+ rm -f "$untracked_file"
8740
+ return 1
8741
+ fi
8260
8742
  while IFS= read -r -d '' file; do
8261
8743
  untracked+=("$dependency/$file")
8262
- done < <(git -C "$dependency" ls-files --others --exclude-standard -z 2>/dev/null)
8744
+ done <"$untracked_file"
8745
+ rm -f "$untracked_file"
8263
8746
  if (( ${#untracked[@]} > 0 )); then
8264
8747
  printf '.git-untracked-count:%s\n' "${#untracked[@]}"
8265
8748
  fmix_hash_file_batches "${untracked[@]}" || return 1
@@ -8424,13 +8907,14 @@ PY
8424
8907
 
8425
8908
  fmix_get_git_tree_hash() {
8426
8909
  local worktree="$1" real tree_hash
8427
- real="$(fmix_realpath "$worktree" 2>/dev/null || echo "$worktree")"
8428
- if command -v git >/dev/null 2>&1 && { [[ -d "$real/.git" ]] || [[ -f "$real/.git" ]]; }; then
8429
- tree_hash="$(git -C "$real" rev-parse HEAD^{tree} 2>/dev/null || true)"
8430
- if [[ "$tree_hash" =~ ^[0-9a-f]{40}$ ]]; then
8431
- printf '%s\n' "$tree_hash"
8432
- return 0
8433
- fi
8910
+ real="$(fmix_realpath "$worktree" 2>/dev/null)" || return 1
8911
+ if [[ -d "$real/.git" || -f "$real/.git" ]]; then
8912
+ command -v git >/dev/null 2>&1 || return 1
8913
+ tree_hash="$(git -C "$real" rev-parse HEAD^{tree} 2>/dev/null)" \
8914
+ || return 1
8915
+ [[ "$tree_hash" =~ ^[0-9a-f]{40}$ ]] || return 1
8916
+ printf '%s\n' "$tree_hash"
8917
+ return 0
8434
8918
  fi
8435
8919
  printf 'unknown\n'
8436
8920
  }
@@ -8453,37 +8937,84 @@ fmix_compute_compile_env_hash() {
8453
8937
  }
8454
8938
 
8455
8939
  fmix_compute_dirty_hash() {
8456
- local worktree="$1" real status
8457
- real="$(fmix_realpath "$worktree" 2>/dev/null || echo "$worktree")"
8458
- if ! command -v git >/dev/null 2>&1 || { [[ ! -d "$real/.git" ]] && [[ ! -f "$real/.git" ]]; }; then
8940
+ local worktree="$1" real status manifest hash rc file
8941
+ local untracked_file diff_file staged_file
8942
+ local -a untracked=()
8943
+ real="$(fmix_realpath "$worktree" 2>/dev/null)" || return 1
8944
+ if [[ ! -d "$real/.git" && ! -f "$real/.git" ]]; then
8459
8945
  printf 'clean\n'
8460
8946
  return 0
8461
8947
  fi
8462
- status="$(git -C "$real" status --porcelain=v1 2>/dev/null || true)"
8948
+ command -v git >/dev/null 2>&1 || return 1
8949
+ git -C "$real" rev-parse --is-inside-work-tree >/dev/null 2>&1 \
8950
+ || return 1
8951
+ status="$(git -C "$real" status --porcelain=v1 2>/dev/null)" || return 1
8463
8952
  if [[ -z "$status" ]]; then
8464
8953
  printf 'clean\n'
8465
8954
  return 0
8466
8955
  fi
8956
+ manifest="$(mktemp)" || return 1
8957
+ untracked_file="$(mktemp)" || { rm -f "$manifest"; return 1; }
8958
+ diff_file="$(mktemp)" \
8959
+ || { rm -f "$manifest" "$untracked_file"; return 1; }
8960
+ staged_file="$(mktemp)" \
8961
+ || { rm -f "$manifest" "$untracked_file" "$diff_file"; return 1; }
8962
+ if ! git -C "$real" ls-files --others --exclude-standard -z \
8963
+ >"$untracked_file" 2>/dev/null; then
8964
+ rm -f "$manifest" "$untracked_file" "$diff_file" "$staged_file"
8965
+ return 1
8966
+ fi
8967
+ if ! git -C "$real" diff --no-ext-diff --binary -- . \
8968
+ >"$diff_file" 2>/dev/null; then
8969
+ rm -f "$manifest" "$untracked_file" "$diff_file" "$staged_file"
8970
+ return 1
8971
+ fi
8972
+ if ! git -C "$real" diff --cached --no-ext-diff --binary -- . \
8973
+ >"$staged_file" 2>/dev/null; then
8974
+ rm -f "$manifest" "$untracked_file" "$diff_file" "$staged_file"
8975
+ return 1
8976
+ fi
8977
+ while IFS= read -r -d '' file; do
8978
+ untracked+=("$file")
8979
+ done <"$untracked_file"
8467
8980
  (
8468
8981
  printf '%s\n' "$status"
8469
- git -C "$real" ls-files --others --modified --exclude-standard 2>/dev/null | head -50 | while IFS= read -r f; do
8470
- fmix_stat_mtime "$real/$f" 2>/dev/null || echo 0
8982
+ cat "$diff_file" || exit 1
8983
+ cat "$staged_file" || exit 1
8984
+ for file in "${untracked[@]+"${untracked[@]}"}"; do
8985
+ printf 'untracked:%s:' "$file"
8986
+ fmix_hash_files "$real/$file" || exit 1
8471
8987
  done
8472
- ) | fmix_hash_stdin
8988
+ ) >"$manifest"
8989
+ rc=$?
8990
+ rm -f "$untracked_file" "$diff_file" "$staged_file"
8991
+ if (( rc != 0 )); then
8992
+ rm -f "$manifest"
8993
+ return "$rc"
8994
+ fi
8995
+ hash="$(fmix_hash_stdin <"$manifest")"
8996
+ rc=$?
8997
+ rm -f "$manifest"
8998
+ (( rc == 0 )) || return "$rc"
8999
+ [[ "$hash" =~ ^[0-9a-f]{64}$ ]] || return 1
9000
+ printf '%s\n' "$hash"
8473
9001
  }
8474
9002
 
8475
9003
  fmix_write_compile_stamp() {
8476
9004
  local worktree="$1" fingerprint="$2" real build_root guard dependency_guard stamp tmp quick_guard
8477
- local template_key tree_hash env_hash dirty_hash
9005
+ local template_key tree_hash env_hash dirty_hash ignored_compile_hash source_stability_identity
8478
9006
  real="$(fmix_realpath "$worktree")"
8479
9007
  build_root="$(fmix_compile_build_root "$real")"
8480
9008
  guard="$(fmix_compile_manifest_guard "$real")" || return 1
8481
9009
  dependency_guard="$(fmix_dependency_source_guard "$real")" || return 1
8482
- quick_guard="$(fmix_compile_quick_guard "$real")" || quick_guard=""
9010
+ quick_guard="$(fmix_compile_quick_guard "$real")" || return 1
8483
9011
  template_key="$(fmix_compute_template_key "$real" 2>/dev/null || echo "")"
8484
- tree_hash="$(fmix_get_git_tree_hash "$real")"
9012
+ tree_hash="$(fmix_get_git_tree_hash "$real")" || return 1
8485
9013
  env_hash="$(fmix_compute_compile_env_hash "$real" 2>/dev/null || echo "")"
8486
- dirty_hash="$(fmix_compute_dirty_hash "$real" 2>/dev/null || echo "clean")"
9014
+ dirty_hash="$(fmix_compute_dirty_hash "$real" 2>/dev/null)" || return 1
9015
+ ignored_compile_hash="$(fmix_ignored_compile_inputs_hash "$real" 2>/dev/null)" \
9016
+ || return 1
9017
+ source_stability_identity="${FMIX_SOURCE_STABILITY_COMPILE_IDENTITY:-}"
8487
9018
  stamp="$(fmix_compile_stamp_file "$real")"
8488
9019
  mkdir -p "$(dirname "$stamp")"
8489
9020
  tmp="$(mktemp "${stamp}.tmp.XXXXXX")" || return 1
@@ -8496,10 +9027,12 @@ fmix_write_compile_stamp() {
8496
9027
  "git_tree_hash": $(fmix_json_escape "$tree_hash"),
8497
9028
  "compile_env_hash": $(fmix_json_escape "$env_hash"),
8498
9029
  "dirty_hash": $(fmix_json_escape "$dirty_hash"),
9030
+ "ignored_compile_hash": $(fmix_json_escape "$ignored_compile_hash"),
8499
9031
  "fingerprint": $(fmix_json_escape "$fingerprint"),
8500
9032
  "manifest_guard": $(fmix_json_escape "$guard"),
8501
9033
  "dependency_source_guard": $(fmix_json_escape "$dependency_guard"),
8502
9034
  "quick_guard": $(fmix_json_escape "$quick_guard"),
9035
+ "source_stability_identity": $(fmix_json_escape "$source_stability_identity"),
8503
9036
  "compiled_at": $(fmix_json_escape "$(fmix_now)")
8504
9037
  }
8505
9038
  EOF
@@ -8510,11 +9043,16 @@ EOF
8510
9043
  mv "$tmp" "$stamp" || { rm -f "$tmp"; return 1; }
8511
9044
  }
8512
9045
 
8513
- # Warm-path short-circuit: accept an existing stamp when the cheap invalidator
8514
- # matches and beams still exist. Skips full content fingerprint + deps walk.
9046
+ # Warm-path staged admission: cheap invalidators reject obvious drift before
9047
+ # bounded live-content and dependency-source guards authorize artifact reuse.
8515
9048
  fmix_try_compile_stamp_quick_hit() {
8516
- local worktree="$1" real build_root stamp dependency_stamp dependency_fingerprint dependency_guard
9049
+ local worktree="$1" real build_root stamp dependency_stamp dependency_fingerprint
8517
9050
  local recorded_path recorded_build recorded_quick current_quick
9051
+ local recorded_tree_hash current_tree_hash recorded_dirty_hash current_dirty_hash
9052
+ local recorded_ignored_compile_hash current_ignored_compile_hash
9053
+ local recorded_fingerprint current_fingerprint
9054
+ local recorded_dependency_guard current_dependency_guard dependency_stamp_guard
9055
+ local recorded_source_stability_identity
8518
9056
  local app_ebin
8519
9057
  real="$(fmix_realpath "$worktree")" || return 1
8520
9058
  build_root="$(fmix_compile_build_root "$real")" || return 1
@@ -8523,21 +9061,53 @@ fmix_try_compile_stamp_quick_hit() {
8523
9061
  recorded_path="$(fmix_read_state "$stamp" path)"
8524
9062
  recorded_build="$(fmix_read_state "$stamp" build_root)"
8525
9063
  recorded_quick="$(fmix_read_state "$stamp" quick_guard)"
9064
+ recorded_tree_hash="$(fmix_read_state "$stamp" git_tree_hash)"
9065
+ recorded_dirty_hash="$(fmix_read_state "$stamp" dirty_hash)"
9066
+ recorded_ignored_compile_hash="$(fmix_read_state "$stamp" ignored_compile_hash)"
9067
+ recorded_fingerprint="$(fmix_read_state "$stamp" fingerprint)"
9068
+ recorded_dependency_guard="$(fmix_read_state "$stamp" dependency_source_guard)"
9069
+ recorded_source_stability_identity="$(fmix_read_state "$stamp" source_stability_identity)"
9070
+ [[ "$recorded_path" == "$real" ]] || return 1
9071
+ [[ "$recorded_build" == "$build_root" ]] || return 1
8526
9072
  [[ -n "$recorded_quick" ]] || return 1
9073
+ [[ -n "$recorded_tree_hash" && "$recorded_tree_hash" != "unknown" ]] || return 1
9074
+ [[ -n "$recorded_dirty_hash" ]] || return 1
9075
+ [[ "$recorded_fingerprint" =~ ^[0-9a-f]{64}$ ]] || return 1
9076
+ [[ "$recorded_dependency_guard" =~ ^[0-9a-f]{64}$ ]] || return 1
9077
+ [[ "$recorded_ignored_compile_hash" =~ ^[0-9a-f]{64}$ \
9078
+ || "$recorded_ignored_compile_hash" == "non-git" ]] || return 1
9079
+ if [[ "${FMIX_SOURCE_STABILITY_REQUIRED:-0}" == "1" ]]; then
9080
+ [[ "${FMIX_SOURCE_STABILITY_COMPILE_IDENTITY:-}" =~ ^[0-9a-f]{64}$ ]] || return 1
9081
+ [[ "$recorded_source_stability_identity" \
9082
+ == "$FMIX_SOURCE_STABILITY_COMPILE_IDENTITY" ]] || return 1
9083
+ fi
8527
9084
  app_ebin="$build_root/test/lib/cdrcisco/ebin"
8528
9085
  [[ -d "$app_ebin" ]] || return 1
8529
9086
  [[ -n "$(find "$app_ebin" -maxdepth 1 -type f -name '*.beam' -print -quit 2>/dev/null)" ]] || return 1
8530
9087
  current_quick="$(fmix_compile_quick_guard "$real")" || return 1
8531
9088
  [[ "$recorded_quick" == "$current_quick" ]] || return 1
9089
+ current_tree_hash="$(fmix_get_git_tree_hash "$real")" || return 1
9090
+ [[ "$current_tree_hash" != "unknown" \
9091
+ && "$recorded_tree_hash" == "$current_tree_hash" ]] || return 1
9092
+ current_dirty_hash="$(fmix_compute_dirty_hash "$real")" || return 1
9093
+ [[ "$recorded_dirty_hash" == "$current_dirty_hash" ]] || return 1
9094
+ current_ignored_compile_hash="$(fmix_ignored_compile_inputs_hash "$real")" \
9095
+ || return 1
9096
+ [[ "$recorded_ignored_compile_hash" == "$current_ignored_compile_hash" ]] \
9097
+ || return 1
9098
+ # Git's status/index stat cache and the mtime quick guard are only early
9099
+ # rejectors. Admission is content-exact for the bounded compiler inputs.
9100
+ current_fingerprint="$(fmix_compute_compile_fingerprint "$real")" || return 1
9101
+ [[ "$recorded_fingerprint" == "$current_fingerprint" ]] || return 1
9102
+ current_dependency_guard="$(fmix_dependency_source_guard "$real")" || return 1
9103
+ [[ "$recorded_dependency_guard" == "$current_dependency_guard" ]] || return 1
8532
9104
  # A quick hit must not accept a stale or partial dependency checkpoint.
8533
- # Validate the cheap structural fields here; the full dependency/source
8534
- # guard remains the responsibility of fmix_ensure_compile on a miss.
8535
9105
  dependency_stamp="$(fmix_dependency_stamp_file "$real")"
8536
9106
  [[ -f "$dependency_stamp" ]] || return 1
8537
9107
  dependency_fingerprint="$(fmix_read_state "$dependency_stamp" dependency_fingerprint)"
8538
- dependency_guard="$(fmix_read_state "$dependency_stamp" source_guard)"
9108
+ dependency_stamp_guard="$(fmix_read_state "$dependency_stamp" source_guard)"
8539
9109
  [[ "$dependency_fingerprint" =~ ^[0-9a-f]{64}$ ]] || return 1
8540
- [[ -n "$dependency_guard" ]] || return 1
9110
+ [[ "$dependency_stamp_guard" == "$current_dependency_guard" ]] || return 1
8541
9111
  return 0
8542
9112
  }
8543
9113
 
@@ -8565,6 +9135,8 @@ fmix_compile_stamp_matches() {
8565
9135
  local recorded_schema recorded_path recorded_build recorded_fingerprint recorded_guard current_guard
8566
9136
  local recorded_dependency_guard current_dependency_guard
8567
9137
  local recorded_template_key recorded_tree_hash recorded_env_hash recorded_dirty_hash
9138
+ local recorded_ignored_compile_hash current_ignored_compile_hash
9139
+ local recorded_source_stability_identity
8568
9140
  real="$(fmix_realpath "$worktree")"
8569
9141
  build_root="$(fmix_compile_build_root "$real")"
8570
9142
  stamp="$(fmix_compile_stamp_file "$real")"
@@ -8576,6 +9148,12 @@ fmix_compile_stamp_matches() {
8576
9148
  recorded_fingerprint="$(fmix_read_state "$stamp" fingerprint)"
8577
9149
  recorded_guard="$(fmix_read_state "$stamp" manifest_guard)"
8578
9150
  recorded_dependency_guard="$(fmix_read_state "$stamp" dependency_source_guard)"
9151
+ recorded_source_stability_identity="$(fmix_read_state "$stamp" source_stability_identity)"
9152
+ if [[ "${FMIX_SOURCE_STABILITY_REQUIRED:-0}" == "1" ]]; then
9153
+ [[ "${FMIX_SOURCE_STABILITY_COMPILE_IDENTITY:-}" =~ ^[0-9a-f]{64}$ ]] || return 1
9154
+ [[ "$recorded_source_stability_identity" \
9155
+ == "$FMIX_SOURCE_STABILITY_COMPILE_IDENTITY" ]] || return 1
9156
+ fi
8579
9157
 
8580
9158
  # Schema v2 content-identity matching (Patch 3)
8581
9159
  if [[ "$recorded_schema" == "2" ]]; then
@@ -8583,12 +9161,18 @@ fmix_compile_stamp_matches() {
8583
9161
  recorded_tree_hash="$(fmix_read_state "$stamp" git_tree_hash)"
8584
9162
  recorded_env_hash="$(fmix_read_state "$stamp" compile_env_hash)"
8585
9163
  recorded_dirty_hash="$(fmix_read_state "$stamp" dirty_hash)"
9164
+ recorded_ignored_compile_hash="$(fmix_read_state "$stamp" ignored_compile_hash)"
8586
9165
 
8587
9166
  local current_template_key current_tree_hash current_env_hash current_dirty_hash
8588
9167
  current_template_key="$(fmix_compute_template_key "$real" 2>/dev/null || echo "")"
8589
- current_tree_hash="$(fmix_get_git_tree_hash "$real")"
9168
+ current_tree_hash="$(fmix_get_git_tree_hash "$real")" || return 1
8590
9169
  current_env_hash="$(fmix_compute_compile_env_hash "$real" 2>/dev/null || echo "")"
8591
- current_dirty_hash="$(fmix_compute_dirty_hash "$real" 2>/dev/null || echo "clean")"
9170
+ current_dirty_hash="$(fmix_compute_dirty_hash "$real" 2>/dev/null)" \
9171
+ || return 1
9172
+ current_ignored_compile_hash="$(fmix_ignored_compile_inputs_hash "$real" 2>/dev/null)" \
9173
+ || return 1
9174
+ current_dependency_guard="$(fmix_dependency_source_guard "$real")" \
9175
+ || return 1
8592
9176
 
8593
9177
  if [[ "$recorded_tree_hash" != "unknown" && "$current_tree_hash" != "unknown" ]]; then
8594
9178
  # template_key is compared for equality rather than required to be
@@ -8601,7 +9185,11 @@ fmix_compile_stamp_matches() {
8601
9185
  if [[ "$recorded_template_key" == "$current_template_key" \
8602
9186
  && -n "$recorded_tree_hash" && "$recorded_tree_hash" == "$current_tree_hash" \
8603
9187
  && -n "$recorded_env_hash" && "$recorded_env_hash" == "$current_env_hash" \
8604
- && "$recorded_dirty_hash" == "$current_dirty_hash" ]]; then
9188
+ && "$recorded_dirty_hash" == "$current_dirty_hash" \
9189
+ && "$recorded_ignored_compile_hash" == "$current_ignored_compile_hash" \
9190
+ && "$recorded_fingerprint" == "$fingerprint" \
9191
+ && -n "$recorded_dependency_guard" \
9192
+ && "$recorded_dependency_guard" == "$current_dependency_guard" ]]; then
8605
9193
  local app_ebin="$build_root/test/lib/cdrcisco/ebin"
8606
9194
  if [[ -d "$app_ebin" ]] && [[ -n "$(find "$app_ebin" -maxdepth 1 -type f -name '*.beam' -print -quit 2>/dev/null)" ]]; then
8607
9195
  return 0
@@ -8767,7 +9355,7 @@ fmix_adopt_compatible_worktree_artifacts() {
8767
9355
  }
8768
9356
 
8769
9357
  FMIX_CURRENT_SEMAPHORE_SLOT=""
8770
- FMIX_CURRENT_SEMAPHORE_FD=""
9358
+ FMIX_CURRENT_SEMAPHORE_KEEPER_PID=""
8771
9359
 
8772
9360
  fmix_compile_semaphore_permits() {
8773
9361
  if [[ -n "${FMIX_COMPILE_PERMITS:-}" ]]; then
@@ -8791,8 +9379,7 @@ fmix_compile_semaphore_acquire() {
8791
9379
  permits="$(fmix_compile_semaphore_permits)"
8792
9380
  deadline_secs="${FMIX_CALLER_DEADLINE_SECS:-}"
8793
9381
 
8794
- local py_bin slot fd acquired_slot=-1 acquired_fd=""
8795
- py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
9382
+ local slot acquired_slot=-1 acquired_keeper_pid=""
8796
9383
  mkdir -p "$FMIX_HOME/lock-kernel" "$FMIX_HOME/lock-metadata" || return 1
8797
9384
 
8798
9385
  local t0=$(fmix_epoch)
@@ -8802,28 +9389,17 @@ fmix_compile_semaphore_acquire() {
8802
9389
  while true; do
8803
9390
  for (( slot = 0; slot < permits; slot++ )); do
8804
9391
  local kfile="$FMIX_HOME/lock-kernel/compile-permit-${slot}"
8805
- fd="$(fmix_lock_allocate_fd)" || return 1
8806
- fmix_lock_open_fd "$fd" "$kfile" || { fmix_lock_close_fd "$fd"; continue; }
8807
- if "$py_bin" - "$fd" 0 <<'PY' 2>/dev/null
8808
- import fcntl, sys
8809
- fd = int(sys.argv[1])
8810
- try:
8811
- fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
8812
- raise SystemExit(0)
8813
- except Exception:
8814
- raise SystemExit(1)
8815
- PY
8816
- then
9392
+ if fmix_lock_keeper_start "$kfile" exclusive 0 \
9393
+ "compile permit ${slot}" "compile-permit-${slot}" 2>/dev/null; then
8817
9394
  acquired_slot="$slot"
8818
- acquired_fd="$fd"
9395
+ acquired_keeper_pid="$FMIX_LAST_LOCK_KEEPER_PID"
8819
9396
  break
8820
9397
  fi
8821
- fmix_lock_close_fd "$fd"
8822
9398
  done
8823
9399
 
8824
9400
  if (( acquired_slot >= 0 )); then
8825
9401
  FMIX_CURRENT_SEMAPHORE_SLOT="$acquired_slot"
8826
- FMIX_CURRENT_SEMAPHORE_FD="$acquired_fd"
9402
+ FMIX_CURRENT_SEMAPHORE_KEEPER_PID="$acquired_keeper_pid"
8827
9403
  cat >"$FMIX_HOME/lock-metadata/compile-permit-${acquired_slot}.json" 2>/dev/null <<EOF
8828
9404
  {
8829
9405
  "slot": $acquired_slot,
@@ -8861,11 +9437,12 @@ EOF
8861
9437
  }
8862
9438
 
8863
9439
  fmix_compile_semaphore_release() {
8864
- if [[ -n "$FMIX_CURRENT_SEMAPHORE_SLOT" && -n "$FMIX_CURRENT_SEMAPHORE_FD" ]]; then
9440
+ if [[ -n "$FMIX_CURRENT_SEMAPHORE_SLOT" \
9441
+ && -n "$FMIX_CURRENT_SEMAPHORE_KEEPER_PID" ]]; then
8865
9442
  rm -f "$FMIX_HOME/lock-metadata/compile-permit-${FMIX_CURRENT_SEMAPHORE_SLOT}.json" 2>/dev/null || true
8866
- fmix_lock_close_fd "$FMIX_CURRENT_SEMAPHORE_FD" 2>/dev/null || true
9443
+ fmix_lock_keeper_stop "$FMIX_CURRENT_SEMAPHORE_KEEPER_PID" 2>/dev/null || true
8867
9444
  FMIX_CURRENT_SEMAPHORE_SLOT=""
8868
- FMIX_CURRENT_SEMAPHORE_FD=""
9445
+ FMIX_CURRENT_SEMAPHORE_KEEPER_PID=""
8869
9446
  fi
8870
9447
  }
8871
9448
 
@@ -9245,8 +9822,24 @@ fmix_ensure_compile() {
9245
9822
  FMIX_LAST_COMPILE_SECONDS="0"
9246
9823
  FMIX_LAST_COMPILE_LOG=""
9247
9824
 
9248
- # Warm-path short-circuit: cheap mtime/manifest guard before full
9249
- # content fingerprint (which walked deps + lib and cost ~8–10s).
9825
+ if [[ "${FMIX_SOURCE_STABILITY_REQUIRED:-0}" == "1" ]]; then
9826
+ if ! fmix_require_stable_source "$worktree" "compile preparation" 1; then
9827
+ FMIX_LAST_COMPILE_OUTCOME="error"
9828
+ return 1
9829
+ fi
9830
+ if [[ ! "${FMIX_SOURCE_STABILITY_COMPILE_IDENTITY:-}" =~ ^[0-9a-f]{64}$ ]]; then
9831
+ FMIX_SOURCE_STABILITY_COMPILE_IDENTITY="$(
9832
+ fmix_source_stability_compile_identity "$worktree"
9833
+ )" || {
9834
+ fmix_invalidate_rejected_stamps "$worktree"
9835
+ FMIX_LAST_COMPILE_OUTCOME="error"
9836
+ return 1
9837
+ }
9838
+ fi
9839
+ fi
9840
+
9841
+ # Warm-path staged admission: cheap stat/manifest checks reject obvious
9842
+ # drift before bounded live-content and dependency-source verification.
9250
9843
  if fmix_try_compile_stamp_quick_hit "$worktree"; then
9251
9844
  fmix_info "Compile stamp quick-hit — skipping deps.get and mix compile."
9252
9845
  FMIX_LAST_COMPILE_OUTCOME="stamp_hit_quick"
@@ -9340,6 +9933,10 @@ fmix_ensure_compile() {
9340
9933
  compile_timeout="$FMIX_SETUP_COMPILE_TIMEOUT"
9341
9934
  fmix_info "Explicit setup compile budget: ${compile_timeout}s."
9342
9935
  fi
9936
+ if ! fmix_require_stable_source "$worktree" "compile start" 1; then
9937
+ FMIX_LAST_COMPILE_OUTCOME="error"
9938
+ return 1
9939
+ fi
9343
9940
  fmix_run_compile_streamed "$worktree" "$db_name" "" "$log_file" "$compile_timeout"
9344
9941
  rc=$?
9345
9942
  t1=$(fmix_epoch)
@@ -9360,6 +9957,10 @@ fmix_ensure_compile() {
9360
9957
  fmix_error "Fix the source error or explicitly repair the worktree build before retrying."
9361
9958
  return "$rc"
9362
9959
  fi
9960
+ if ! fmix_require_stable_source "$worktree" "compile" 1; then
9961
+ FMIX_LAST_COMPILE_OUTCOME="error"
9962
+ return 1
9963
+ fi
9363
9964
  local compiled_files=0
9364
9965
  compiled_files="$(sed -nE 's/.*Compiling ([0-9]+) files?.*/\1/p' "$log_file" 2>/dev/null \
9365
9966
  | awk '{ total += $1 } END { print total + 0 }')" || compiled_files=0
@@ -9385,18 +9986,29 @@ fmix_ensure_compile() {
9385
9986
  || dependency_fingerprint=""
9386
9987
  if [[ -z "$dependency_fingerprint" ]] \
9387
9988
  || ! fmix_write_dependency_stamp "$worktree" "$dependency_fingerprint"; then
9989
+ fmix_invalidate_rejected_stamps "$worktree"
9388
9990
  fmix_error "Compile succeeded, but final dependency provenance could not be recorded."
9389
9991
  FMIX_LAST_COMPILE_OUTCOME="error"
9390
9992
  return 1
9391
9993
  fi
9994
+ if ! fmix_require_stable_source "$worktree" "final dependency provenance" 1; then
9995
+ FMIX_LAST_COMPILE_OUTCOME="error"
9996
+ return 1
9997
+ fi
9392
9998
 
9393
9999
  fingerprint="$(fmix_compute_compile_fingerprint "$worktree")" || fingerprint=""
9394
10000
  if [[ -z "$fingerprint" ]] \
10001
+ || ! fmix_require_stable_source "$worktree" "compile stamp construction" 1 \
9395
10002
  || ! fmix_write_compile_stamp "$worktree" "$fingerprint"; then
10003
+ fmix_invalidate_rejected_stamps "$worktree"
9396
10004
  fmix_error "Compile succeeded, but final content/config provenance could not be recorded."
9397
10005
  FMIX_LAST_COMPILE_OUTCOME="error"
9398
10006
  return 1
9399
10007
  fi
10008
+ if ! fmix_require_stable_source "$worktree" "compile stamp publication" 1; then
10009
+ FMIX_LAST_COMPILE_OUTCOME="error"
10010
+ return 1
10011
+ fi
9400
10012
  return 0
9401
10013
  }
9402
10014
 
@@ -9578,6 +10190,18 @@ cmd_cache() {
9578
10190
  # ---------------------------------------------------------------------------
9579
10191
 
9580
10192
  cmd_setup() {
10193
+ # Command substitutions inside one setup inherit the parent's `bash fmix
10194
+ # setup ...` argv and can look recursive in a process snapshot, but they do
10195
+ # not call cmd_setup again. A descendant wrapper that actually launches
10196
+ # setup does re-enter this function, so carry a function-scoped sentinel
10197
+ # through the environment and reject that child before any setup work.
10198
+ if [[ "${FMIX_SETUP_ACTIVE:-0}" == "1" ]]; then
10199
+ fmix_error "Recursive fmix setup invocation refused; a setup descendant attempted to re-enter setup."
10200
+ return 2
10201
+ fi
10202
+ local FMIX_SETUP_ACTIVE=1
10203
+ export FMIX_SETUP_ACTIVE
10204
+
9581
10205
  local worktree_arg="auto"
9582
10206
  local session_arg=""
9583
10207
  local rebuild_existing=0
@@ -10023,6 +10647,39 @@ cmd_test() {
10023
10647
  fmix_run_telemetry_phase "lock"
10024
10648
  fmix_emit_phase_change "lock" "completed"
10025
10649
 
10650
+ # Test and coverage runs are immutable snapshots. Capture exact compiler
10651
+ # inputs, HEAD, and selected test content only after the canonical
10652
+ # worktree lock is held. `fmix task` deliberately does not enable this
10653
+ # guard because generators are expected to mutate repository inputs.
10654
+ local FMIX_SOURCE_STABILITY_REQUIRED=1
10655
+ local FMIX_SOURCE_STABILITY_IDENTITY=""
10656
+ local FMIX_SOURCE_STABILITY_COMPILE_IDENTITY=""
10657
+ local -a FMIX_SOURCE_STABILITY_SELECTED_ARGS=("${mix_args[@]+"${mix_args[@]}"}")
10658
+ FMIX_SOURCE_STABILITY_IDENTITY="$(fmix_source_stability_identity \
10659
+ "$real_worktree" \
10660
+ "${FMIX_SOURCE_STABILITY_SELECTED_ARGS[@]+"${FMIX_SOURCE_STABILITY_SELECTED_ARGS[@]}"}")" \
10661
+ || {
10662
+ fmix_error "Could not capture a source-stability identity after acquiring the worktree lock."
10663
+ fmix_invalidate_rejected_stamps "$real_worktree"
10664
+ fmix_lock_release "$lock_name"
10665
+ fmix_run_telemetry_finish 1
10666
+ return 1
10667
+ }
10668
+ FMIX_SOURCE_STABILITY_COMPILE_IDENTITY="$(
10669
+ fmix_source_stability_compile_identity "$real_worktree"
10670
+ )" || {
10671
+ fmix_error "Could not capture compile-source identity after acquiring the worktree lock."
10672
+ fmix_invalidate_rejected_stamps "$real_worktree"
10673
+ fmix_lock_release "$lock_name"
10674
+ fmix_run_telemetry_finish 1
10675
+ return 1
10676
+ }
10677
+ if ! fmix_require_stable_source "$real_worktree" "source identity capture" 1; then
10678
+ fmix_lock_release "$lock_name"
10679
+ fmix_run_telemetry_finish 1
10680
+ return 1
10681
+ fi
10682
+
10026
10683
  # An explicitly selected stable base may seed dependency artifacts. A
10027
10684
  # selector or restore miss is intentionally cold: the unchanged V2
10028
10685
  # artifact path below remains authoritative.
@@ -10070,6 +10727,12 @@ cmd_test() {
10070
10727
  fmix_run_telemetry_finish "$compile_rc"
10071
10728
  return "$compile_rc"
10072
10729
  fi
10730
+ if ! fmix_require_stable_source "$real_worktree" "compilation" 1; then
10731
+ fmix_lock_release "$lock_name"
10732
+ fmix_emit_phase_change "compile" "failed"
10733
+ fmix_run_telemetry_finish 1
10734
+ return 1
10735
+ fi
10073
10736
  fmix_run_telemetry_phase "compile"
10074
10737
  fmix_emit_phase_change "compile" "completed"
10075
10738
 
@@ -10103,8 +10766,6 @@ cmd_test() {
10103
10766
  fmix_run_telemetry_finish 1
10104
10767
  return 1
10105
10768
  }
10106
- fmix_update_template_last_used "$template_key"
10107
-
10108
10769
  # Keep the worktree lock through ExUnit: callers for the same realpath share
10109
10770
  # one scratch DB. Different worktrees remain fully independent.
10110
10771
  fmix_prepend_toolchain_paths
@@ -10174,6 +10835,13 @@ cmd_test() {
10174
10835
  [[ -n "${MIX_BUILD_PATH:-}" ]] && build_env+=("MIX_BUILD_PATH=$MIX_BUILD_PATH")
10175
10836
  [[ -n "${MIX_DEPS_PATH:-}" ]] && build_env+=("MIX_DEPS_PATH=$MIX_DEPS_PATH")
10176
10837
 
10838
+ if ! fmix_require_stable_source "$real_worktree" "Mix startup"; then
10839
+ fmix_lock_release "$lock_name"
10840
+ fmix_emit_phase_change "mix_test" "failed"
10841
+ fmix_run_telemetry_finish 1
10842
+ return 1
10843
+ fi
10844
+
10177
10845
  fmix_emit_phase_change "mix_test" "started"
10178
10846
  local test_rc=0
10179
10847
  (
@@ -10274,6 +10942,12 @@ end
10274
10942
  )
10275
10943
  test_rc=$?
10276
10944
 
10945
+ local source_stable_after_mix=1
10946
+ if ! fmix_require_stable_source "$real_worktree" "Mix execution"; then
10947
+ source_stable_after_mix=0
10948
+ test_rc=1
10949
+ fi
10950
+
10277
10951
  t1=$(fmix_epoch)
10278
10952
  local test_duration_ms=$(( (t1 - t0) * 1000 ))
10279
10953
  (( test_duration_ms < 0 )) && test_duration_ms=0
@@ -10284,9 +10958,13 @@ end
10284
10958
  fmix_emit_phase_change "mix_test" "failed" "$test_duration_ms"
10285
10959
  fi
10286
10960
 
10287
- # Update last_used after test run
10288
- fmix_update_last_used "$state_file"
10289
- fmix_update_template_last_used "$template_key"
10961
+ # A drifted run must not refresh successful-use provenance. Ordinary test
10962
+ # failures retain the historical last-used behavior when source stayed
10963
+ # fixed for the entire run.
10964
+ if (( source_stable_after_mix == 1 )); then
10965
+ fmix_update_last_used "$state_file"
10966
+ fmix_update_template_last_used "$template_key"
10967
+ fi
10290
10968
  fmix_lock_release "$lock_name"
10291
10969
 
10292
10970
  if [[ "$run_mode" == "coverage" ]]; then
@@ -10463,6 +11141,138 @@ cmd_task() {
10463
11141
  return "$task_rc"
10464
11142
  }
10465
11143
 
11144
+ cmd_format() {
11145
+ # Format Elixir sources with the exact pinned toolchain (.tool-versions)
11146
+ # and the same session deps/_build state fmix test compiles against.
11147
+ #
11148
+ # Formatting with an ambient manager shim (mise/asdf/global) whose Elixir
11149
+ # differs from the repo pin is a known hazard: a newer formatter silently
11150
+ # rewrites unrelated hunks and formatter plugins can fail to resolve
11151
+ # (".formatter.exs import_deps" needs the pinned deps compiled). This is
11152
+ # the supported alternative to bare `mix format`.
11153
+ #
11154
+ # Formatting is DB-free: no database is provisioned or contacted, and no
11155
+ # MIX_ENV database variables are injected.
11156
+ local worktree_arg="auto"
11157
+ local session_arg=""
11158
+ local mix_env_arg="test"
11159
+ local check_only=0
11160
+ local found_sep=0
11161
+ local -a fmt_args=()
11162
+ while (( $# > 0 )); do
11163
+ case "$1" in
11164
+ --worktree)
11165
+ [[ $# -ge 2 ]] || { fmix_error "--worktree requires a path argument."; return 2; }
11166
+ worktree_arg="$2"
11167
+ shift 2
11168
+ ;;
11169
+ --worktree=*) worktree_arg="${1#--worktree=}"; shift ;;
11170
+ --session)
11171
+ [[ $# -ge 2 ]] || { fmix_error "--session requires an identifier."; return 2; }
11172
+ session_arg="$2"
11173
+ shift 2
11174
+ ;;
11175
+ --session=*) session_arg="${1#--session=}"; shift ;;
11176
+ --mix-env)
11177
+ [[ $# -ge 2 ]] || { fmix_error "--mix-env requires an environment name."; return 2; }
11178
+ mix_env_arg="$2"
11179
+ shift 2
11180
+ ;;
11181
+ --mix-env=*) mix_env_arg="${1#--mix-env=}"; shift ;;
11182
+ --check) check_only=1; shift ;;
11183
+ --) found_sep=1; shift; break ;;
11184
+ *)
11185
+ fmix_error "Unknown option: $1. Usage: fmix format [--worktree <path>] [--session <id>] [--mix-env <env>] [--check] -- <files...>"
11186
+ return 2
11187
+ ;;
11188
+ esac
11189
+ done
11190
+ (( found_sep == 1 )) || {
11191
+ fmix_error "'fmix format' requires -- before the file arguments."
11192
+ return 2
11193
+ }
11194
+ fmt_args=("$@")
11195
+ (( ${#fmt_args[@]} > 0 )) || {
11196
+ fmix_error "'fmix format' requires at least one file or glob argument after --."
11197
+ return 2
11198
+ }
11199
+ case "${fmt_args[0]}" in
11200
+ test.*)
11201
+ fmix_error "'fmix format' formats files; pass file paths, not a Mix task."
11202
+ return 2
11203
+ ;;
11204
+ esac
11205
+
11206
+ fmix_validate_mix_env "$mix_env_arg" || return 2
11207
+
11208
+ local worktree real_worktree template_key lock_name
11209
+ worktree="$(fmix_find_worktree "$worktree_arg")" || return 1
11210
+ real_worktree="$(fmix_realpath "$worktree")" || return 1
11211
+ fmix_activate_toolchain "$real_worktree" || return 1
11212
+ fmix_activate_session "$real_worktree" "$session_arg" || return 1
11213
+ template_key="$(fmix_compute_template_key "$real_worktree")" || return 1
11214
+ lock_name="$(fmix_execution_lock_name "$real_worktree")"
11215
+
11216
+ fmix_info "=== fmix format ==="
11217
+ fmix_info "Worktree: $real_worktree"
11218
+ fmix_info "Session root: $FMIX_ACTIVE_SESSION_ROOT"
11219
+ fmix_info "Template key: $template_key"
11220
+ fmix_info "Mix environment: $mix_env_arg"
11221
+ if (( check_only == 1 )); then
11222
+ fmix_info "Mode: --check-formatted (read-only; no files are rewritten)"
11223
+ fi
11224
+ fmix_info "Running with pinned toolchain + session deps: mix format ${fmt_args[*]}"
11225
+
11226
+ fmix_lock_acquire "$lock_name" "$FMIX_WORKTREE_LOCK_TIMEOUT" || return 1
11227
+ # Formatter plugins (e.g. .formatter.exs import_deps) require the pinned
11228
+ # deps to be present and compiled; reuse the same ensure path as task.
11229
+ if ! fmix_ensure_artifacts "$real_worktree" "$template_key" 1 ||
11230
+ ! fmix_ensure_compile "$real_worktree" "$(fmix_db_name_for_worktree "$real_worktree")" setup; then
11231
+ fmix_lock_release "$lock_name"
11232
+ return 1
11233
+ fi
11234
+
11235
+ local -a build_env=()
11236
+ [[ -n "${MIX_BUILD_PATH:-}" ]] && build_env+=("MIX_BUILD_PATH=$MIX_BUILD_PATH")
11237
+ [[ -n "${MIX_DEPS_PATH:-}" ]] && build_env+=("MIX_DEPS_PATH=$MIX_DEPS_PATH")
11238
+
11239
+ local -a mix_cmd=(format)
11240
+ if (( check_only == 1 )); then
11241
+ mix_cmd+=(--check-formatted)
11242
+ fi
11243
+ mix_cmd+=("${fmt_args[@]}")
11244
+
11245
+ local fmt_rc=0
11246
+ (
11247
+ cd "$real_worktree" || exit 1
11248
+ exec env \
11249
+ -u DB_HOST_IPV4 \
11250
+ "${build_env[@]+"${build_env[@]}"}" \
11251
+ MIX_ENV="$mix_env_arg" \
11252
+ mix "${mix_cmd[@]}"
11253
+ ) || fmt_rc=$?
11254
+
11255
+ if (( fmt_rc == 0 && check_only == 0 )); then
11256
+ # Formatting rewrites sources, so refresh compile stamps and template
11257
+ # provenance while still holding the worktree lock.
11258
+ if ! fmix_ensure_compile "$real_worktree" "$(fmix_db_name_for_worktree "$real_worktree")" setup; then
11259
+ fmt_rc=1
11260
+ else
11261
+ template_key="$(fmix_compute_template_key "$real_worktree")" || fmt_rc=1
11262
+ fi
11263
+ if (( fmt_rc == 0 )); then
11264
+ fmix_update_template_last_used "$template_key"
11265
+ fi
11266
+ fi
11267
+ fmix_lock_release "$lock_name"
11268
+ if (( check_only == 1 && fmt_rc == 1 )); then
11269
+ fmix_error "Format check failed: files are not formatted per the pinned toolchain."
11270
+ return 1
11271
+ fi
11272
+ fmix_info "Format completed (rc=$fmt_rc)."
11273
+ return "$fmt_rc"
11274
+ }
11275
+
10466
11276
  # ---------------------------------------------------------------------------
10467
11277
  # cmd: fmix doctor
10468
11278
  # ---------------------------------------------------------------------------
@@ -16155,6 +16965,211 @@ cmd_install() {
16155
16965
  # Main dispatch
16156
16966
  # ---------------------------------------------------------------------------
16157
16967
 
16968
+ # Per-verb help: `fmix help <verb>` (or fmix_error hints) prints the focused
16969
+ # usage for one verb plus its examples, without the full --help wall.
16970
+ fmix_verb_help() {
16971
+ local verb="$1"
16972
+ case "$verb" in
16973
+ test)
16974
+ cat <<'VERB'
16975
+ fmix test — run ExUnit targets inside a provisioned session DB.
16976
+
16977
+ Usage:
16978
+ fmix test [--worktree <path>] [--session <id>] [--isolate]
16979
+ [--cache-base <N.N.N-stable>] [--event-fd <fd>] [--unit]
16980
+ -- <mix test args>
16981
+
16982
+ Notes:
16983
+ - One worktree → one warm overlay (SUPER-HOT): pass --session only with a
16984
+ stable name plus --isolate for true parallel Mix on one checkout.
16985
+ - Slow DB startup = local snapshot recovery (see fmix status / fmix timing).
16986
+ - Slow compiles ("Compiling 47xx files") = session fragmentation; inspect
16987
+ with fmix timing --worktree <path>.
16988
+
16989
+ Examples:
16990
+ fmix test -- test/cdrcisco/sip/replaces_test.exs
16991
+ fmix test --worktree ./cisco-cdr -- test/cdrcisco/sip/replaces_test.exs
16992
+ fmix test --worktree ./cisco-cdr --cache-base 0.8.7-stable -- test/cdrcisco/sip/replaces_test.exs
16993
+ VERB
16994
+ ;;
16995
+ coverage)
16996
+ cat <<'VERB'
16997
+ fmix coverage — targeted diff-coverage gate (ADR 0054).
16998
+
16999
+ Usage:
17000
+ fmix coverage --worktree <path> [--session <id>] --base <git-ref>
17001
+ [--source <lib/**/*.ex>]... [--threshold 80]
17002
+ -- <test paths>
17003
+
17004
+ Notes:
17005
+ --base is REQUIRED: it defines the changed-module set. --source scopes
17006
+ cover-compilation to explicit modules (default: every changed lib module).
17007
+ Cannot gate staged-but-uncommitted changes — the bootstrap diffs the
17008
+ committed base...HEAD range. For staged gates use:
17009
+ fmix task -- cdrcisco.diff_coverage --staged --staged-diff <patch>
17010
+
17011
+ Examples:
17012
+ fmix coverage --worktree ./cisco-cdr --base origin/0.8.7-stable -- test/cdrcisco/sip/replaces_test.exs
17013
+ fmix coverage --worktree . --base HEAD --threshold 80 -- test/cdrcisco/call_health/poller_test.exs
17014
+ VERB
17015
+ ;;
17016
+ task)
17017
+ cat <<'VERB'
17018
+ fmix task — run one mix task in a provisioned session DB.
17019
+
17020
+ Usage:
17021
+ fmix task --worktree <path> [--session <id>] [--database <name>]
17022
+ [--mix-env <env>] [--allow-run] -- <mix task> [args]
17023
+
17024
+ Notes:
17025
+ ExUnit tasks are rejected — use fmix test so database and test-lane
17026
+ isolation stay enforced. --allow-run is required for tasks that shell out
17027
+ to git or external processes (e.g. cdrcisco.diff_coverage --staged).
17028
+
17029
+ Examples:
17030
+ fmix task --worktree ./cisco-cdr -- openapi.gen --format all
17031
+ fmix task --worktree ./cisco-cdr --database ct_dev --mix-env dev -- ecto.migrate
17032
+ fmix task --worktree . --mix-env test --allow-run -- cdrcisco.diff_coverage --staged \
17033
+ --staged-diff test-logs/coverage/diff/staged.patch --threshold 80
17034
+ VERB
17035
+ ;;
17036
+ format)
17037
+ cat <<'VERB'
17038
+ fmix format - format Elixir sources with the exact pinned toolchain.
17039
+
17040
+ Usage:
17041
+ fmix format [--worktree <path>] [--session <id>] [--mix-env <env>]
17042
+ [--check] -- <files...>
17043
+
17044
+ Notes:
17045
+ Uses the repo's .tool-versions pin and the same session deps/_build as
17046
+ fmix test, so formatter plugins (.formatter.exs import_deps) resolve the
17047
+ way CI compiles them. Never uses an ambient mise/asdf/global Elixir, which
17048
+ can silently rewrite unrelated hunks when its version differs from the
17049
+ pin. --check is read-only (--check-formatted) for CI and pre-push gates.
17050
+ Formatting is DB-free: no database is provisioned or contacted.
17051
+
17052
+ Examples:
17053
+ fmix format --worktree ./cisco-cdr -- lib/cdrcisco/pipeline_data.ex
17054
+ fmix format -- lib/**/*.ex
17055
+ fmix format --check -- lib/cdrcisco/pipeline_data.ex
17056
+ VERB
17057
+ ;;
17058
+ setup)
17059
+ cat <<'VERB'
17060
+ fmix setup — provision the session DB and build artifacts.
17061
+
17062
+ Usage:
17063
+ fmix setup [--worktree <path>] [--session <id>]
17064
+ [--rebuild-db|--cold-db|--from-zero]
17065
+
17066
+ Notes:
17067
+ --rebuild-db reuse snapshots only; never replays structure.sql
17068
+ --cold-db explicit one-time schema cache build
17069
+ --from-zero full migration chain from an empty DB (structure.sql stale)
17070
+
17071
+ Example:
17072
+ fmix setup --worktree ./cisco-cdr
17073
+ VERB
17074
+ ;;
17075
+ seed)
17076
+ cat <<'VERB'
17077
+ fmix seed publish — explicit clean-stable-only maintenance.
17078
+
17079
+ Usage:
17080
+ fmix seed publish --worktree <path> --cache-base <N.N.N-stable>
17081
+
17082
+ Example:
17083
+ fmix seed publish --worktree ./cisco-cdr --cache-base 0.8.7-stable
17084
+ VERB
17085
+ ;;
17086
+ cache)
17087
+ cat <<'VERB'
17088
+ fmix cache — explain or verify the template cache.
17089
+
17090
+ Usage:
17091
+ fmix cache explain --worktree <path> --cache-base <N.N.N-stable> # read-only
17092
+ fmix cache verify [--key <16-hex-template-key>]
17093
+
17094
+ Example:
17095
+ fmix cache explain --worktree ./cisco-cdr --cache-base 0.8.7-stable
17096
+ VERB
17097
+ ;;
17098
+ ensure)
17099
+ cat <<'VERB'
17100
+ fmix ensure — idempotent toolchain + artifact readiness check (no network
17101
+ when stamps are current).
17102
+
17103
+ Example:
17104
+ fmix ensure
17105
+ VERB
17106
+ ;;
17107
+ doctor)
17108
+ cat <<'VERB'
17109
+ fmix doctor — read-only host diagnostic (toolchain, DB, NATS, FMix state).
17110
+
17111
+ Example:
17112
+ fmix doctor
17113
+ VERB
17114
+ ;;
17115
+ status)
17116
+ cat <<'VERB'
17117
+ fmix status — read-only session/artifact/lock diagnostics. Exits 1 when
17118
+ session metadata discovery is incomplete, still printing remaining sections.
17119
+
17120
+ Example:
17121
+ fmix status
17122
+ VERB
17123
+ ;;
17124
+ timing)
17125
+ cat <<'VERB'
17126
+ fmix timing — phase timings + session fragmentation report.
17127
+
17128
+ Usage:
17129
+ fmix timing [--limit N] [--worktree <path>]
17130
+
17131
+ Example:
17132
+ fmix timing --worktree ./cisco-cdr
17133
+ VERB
17134
+ ;;
17135
+ gc)
17136
+ cat <<'VERB'
17137
+ fmix gc — reclaim stale sessions and consolidated templates.
17138
+
17139
+ Usage:
17140
+ fmix gc [--reap|--consolidate] [--worktree <path>] [--yes]
17141
+
17142
+ Notes:
17143
+ Review the fmix status report before --reap --yes.
17144
+
17145
+ Examples:
17146
+ fmix gc
17147
+ fmix gc --consolidate --worktree ./cisco-cdr --yes
17148
+ VERB
17149
+ ;;
17150
+ install)
17151
+ cat <<'VERB'
17152
+ fmix install — immutable runtime snapshot + atomic PATH link (~/.local/bin).
17153
+
17154
+ Example:
17155
+ fmix install
17156
+ VERB
17157
+ ;;
17158
+ self-test)
17159
+ cat <<'VERB'
17160
+ fmix self-test — run the runner's internal correctness suite.
17161
+
17162
+ Example:
17163
+ fmix self-test
17164
+ VERB
17165
+ ;;
17166
+ *)
17167
+ fmix_error "No focused help for '$verb'. Valid commands: test, coverage, task, format, setup, seed publish, cache explain, cache verify, ensure, doctor, status, timing, gc, install, self-test, version, help"
17168
+ return 1
17169
+ ;;
17170
+ esac
17171
+ }
17172
+
16158
17173
  fmix_usage() {
16159
17174
  cat <<'USAGE'
16160
17175
  fmix — fast native Elixir test runner for cisco-cdr
@@ -16163,6 +17178,7 @@ Usage:
16163
17178
  ./fmix test [--worktree <path>] [--session <id>] [--cache-base <N.N.N-stable>] [--event-fd <fd>] [--unit] -- <mix test args>
16164
17179
  ./fmix coverage [--worktree <path>] [--session <id>] --base <git-ref> [--source <lib/**/*.ex>] [--threshold 80] -- <test paths>
16165
17180
  ./fmix task [--worktree <path>] [--session <id>] [--database <name>] [--mix-env <env>] [--allow-run] -- <mix task> [args]
17181
+ ./fmix format [--worktree <path>] [--session <id>] [--mix-env <env>] [--check] -- <files...>
16166
17182
  ./fmix setup [--worktree <path>] [--session <id>] [--rebuild-db|--cold-db|--from-zero]
16167
17183
  ./fmix seed publish --worktree <path> [--session <id>] --cache-base <N.N.N-stable>
16168
17184
  ./fmix cache explain --worktree <path> --cache-base <N.N.N-stable>
@@ -18421,6 +19437,11 @@ main() {
18421
19437
  shift
18422
19438
  case "$cmd" in
18423
19439
  help|--help|-h)
19440
+ # focused help: fmix help <verb> | fmix <verb> --help
19441
+ if [[ $# -ge 1 && "$1" != "--json" ]]; then
19442
+ fmix_verb_help "$1"
19443
+ return 0
19444
+ fi
18424
19445
  fmix_usage
18425
19446
  return 0
18426
19447
  ;;
@@ -18454,10 +19475,20 @@ main() {
18454
19475
  chmod 0700 "$FMIX_HOME" 2>/dev/null || true
18455
19476
  fi
18456
19477
 
19478
+ case "$cmd" in
19479
+ test|coverage|task|format|setup|seed|cache|ensure|doctor|status|timing|gc|install|self-test)
19480
+ if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
19481
+ fmix_verb_help "$cmd"
19482
+ return 0
19483
+ fi
19484
+ ;;
19485
+ esac
19486
+
18457
19487
  case "$cmd" in
18458
19488
  test) cmd_test "$@" ;;
18459
19489
  coverage) cmd_coverage "$@" ;;
18460
19490
  task) cmd_task "$@" ;;
19491
+ format) cmd_format "$@" ;;
18461
19492
  setup) cmd_setup "$@" ;;
18462
19493
  seed) cmd_seed "$@" ;;
18463
19494
  cache) cmd_cache "$@" ;;
@@ -18470,7 +19501,8 @@ main() {
18470
19501
  self-test) cmd_self_test "$@" ;;
18471
19502
  *)
18472
19503
  fmix_error "Unknown command: $cmd"
18473
- fmix_error "Valid commands: test, coverage, task, setup, seed publish, cache explain, cache verify, doctor, status, timing, gc, install, self-test, version, help"
19504
+ fmix_error "Valid commands: test, coverage, task, format, setup, seed publish, cache explain, cache verify, ensure, doctor, status, timing, gc, install, self-test, version, help"
19505
+ fmix_error "Run 'fmix --help' for the full manual or 'fmix help <command>' for focused usage."
18474
19506
  return 1
18475
19507
  ;;
18476
19508
  esac